org.texi: Remove useless section
[org-mode.git] / lisp / org.el
blob39c37f52ac638a64ccba6dfe0374181abe060c92
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 ;; Return value has to be a string, but match group 4 is
8096 ;; optional.
8097 (or (match-string 4) ""))
8098 (no-tags
8099 (looking-at (concat org-outline-regexp
8100 "\\(.*?\\)"
8101 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
8102 (match-string 1))
8103 (no-todo
8104 (looking-at org-todo-line-regexp)
8105 (match-string 3))
8106 (t (looking-at org-heading-regexp)
8107 (match-string 2))))))
8109 (defvar orgstruct-mode) ; defined below
8111 (defun org-heading-components ()
8112 "Return the components of the current heading.
8113 This is a list with the following elements:
8114 - the level as an integer
8115 - the reduced level, different if `org-odd-levels-only' is set.
8116 - the TODO keyword, or nil
8117 - the priority character, like ?A, or nil if no priority is given
8118 - the headline text itself, or the tags string if no headline text
8119 - the tags string, or nil."
8120 (save-excursion
8121 (org-back-to-heading t)
8122 (when (let (case-fold-search)
8123 (looking-at
8124 (if orgstruct-mode
8125 org-heading-regexp
8126 org-complex-heading-regexp)))
8127 (if orgstruct-mode
8128 (list (length (match-string 1))
8129 (org-reduced-level (length (match-string 1)))
8132 (match-string 2)
8133 nil)
8134 (list (length (match-string 1))
8135 (org-reduced-level (length (match-string 1)))
8136 (match-string-no-properties 2)
8137 (and (match-end 3) (aref (match-string 3) 2))
8138 (match-string-no-properties 4)
8139 (match-string-no-properties 5))))))
8141 (defun org-get-entry ()
8142 "Get the entry text, after heading, entire subtree."
8143 (save-excursion
8144 (org-back-to-heading t)
8145 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8147 (defun org-edit-headline (&optional heading)
8148 "Edit the current headline.
8149 Set it to HEADING when provided."
8150 (interactive)
8151 (org-with-wide-buffer
8152 (org-back-to-heading t)
8153 (when (looking-at org-complex-heading-regexp)
8154 (let* ((old (match-string-no-properties 4))
8155 (new (save-match-data
8156 (org-trim (or heading (read-string "Edit: " old))))))
8157 (unless (equal old new)
8158 (if old (replace-match new t t nil 4)
8159 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8160 (insert " " new))
8161 (org-set-tags nil t)
8162 (when (looking-at "[ \t]*$") (replace-match "")))))))
8164 (defun org-insert-heading-after-current ()
8165 "Insert a new heading with same level as current, after current subtree."
8166 (interactive)
8167 (org-back-to-heading)
8168 (org-insert-heading)
8169 (org-move-subtree-down)
8170 (end-of-line 1))
8172 (defun org-insert-heading-respect-content (&optional invisible-ok)
8173 "Insert heading with `org-insert-heading-respect-content' set to t."
8174 (interactive)
8175 (org-insert-heading '(4) invisible-ok))
8177 (defun org-insert-todo-heading-respect-content (&optional force-state)
8178 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8179 (interactive)
8180 (org-insert-todo-heading force-state '(4)))
8182 (defun org-insert-todo-heading (arg &optional force-heading)
8183 "Insert a new heading with the same level and TODO state as current heading.
8184 If the heading has no TODO state, or if the state is DONE, use the first
8185 state (TODO by default). Also with one prefix arg, force first state. With
8186 two prefix args, force inserting at the end of the parent subtree."
8187 (interactive "P")
8188 (when (or force-heading (not (org-insert-item 'checkbox)))
8189 (org-insert-heading (or (and (equal arg '(16)) '(16))
8190 force-heading))
8191 (save-excursion
8192 (org-back-to-heading)
8193 (outline-previous-heading)
8194 (looking-at org-todo-line-regexp))
8195 (let*
8196 ((new-mark-x
8197 (if (or (equal arg '(4))
8198 (not (match-beginning 2))
8199 (member (match-string 2) org-done-keywords))
8200 (car org-todo-keywords-1)
8201 (match-string 2)))
8202 (new-mark
8204 (run-hook-with-args-until-success
8205 'org-todo-get-default-hook new-mark-x nil)
8206 new-mark-x)))
8207 (beginning-of-line 1)
8208 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8209 (if org-treat-insert-todo-heading-as-state-change
8210 (org-todo new-mark)
8211 (insert new-mark " "))))
8212 (when org-provide-todo-statistics
8213 (org-update-parent-todo-statistics))))
8215 (defun org-insert-subheading (arg)
8216 "Insert a new subheading and demote it.
8217 Works for outline headings and for plain lists alike."
8218 (interactive "P")
8219 (org-insert-heading arg)
8220 (cond
8221 ((org-at-heading-p) (org-do-demote))
8222 ((org-at-item-p) (org-indent-item))))
8224 (defun org-insert-todo-subheading (arg)
8225 "Insert a new subheading with TODO keyword or checkbox and demote it.
8226 Works for outline headings and for plain lists alike."
8227 (interactive "P")
8228 (org-insert-todo-heading arg)
8229 (cond
8230 ((org-at-heading-p) (org-do-demote))
8231 ((org-at-item-p) (org-indent-item))))
8233 ;;; Promotion and Demotion
8235 (defvar org-after-demote-entry-hook nil
8236 "Hook run after an entry has been demoted.
8237 The cursor will be at the beginning of the entry.
8238 When a subtree is being demoted, the hook will be called for each node.")
8240 (defvar org-after-promote-entry-hook nil
8241 "Hook run after an entry has been promoted.
8242 The cursor will be at the beginning of the entry.
8243 When a subtree is being promoted, the hook will be called for each node.")
8245 (defun org-promote-subtree ()
8246 "Promote the entire subtree.
8247 See also `org-promote'."
8248 (interactive)
8249 (save-excursion
8250 (org-with-limited-levels (org-map-tree 'org-promote)))
8251 (org-fix-position-after-promote))
8253 (defun org-demote-subtree ()
8254 "Demote the entire subtree.
8255 See `org-demote' and `org-promote'."
8256 (interactive)
8257 (save-excursion
8258 (org-with-limited-levels (org-map-tree 'org-demote)))
8259 (org-fix-position-after-promote))
8261 (defun org-do-promote ()
8262 "Promote the current heading higher up the tree.
8263 If the region is active in `transient-mark-mode', promote all
8264 headings in the region."
8265 (interactive)
8266 (save-excursion
8267 (if (org-region-active-p)
8268 (org-map-region 'org-promote (region-beginning) (region-end))
8269 (org-promote)))
8270 (org-fix-position-after-promote))
8272 (defun org-do-demote ()
8273 "Demote the current heading lower down the tree.
8274 If the region is active in `transient-mark-mode', demote all
8275 headings in the region."
8276 (interactive)
8277 (save-excursion
8278 (if (org-region-active-p)
8279 (org-map-region 'org-demote (region-beginning) (region-end))
8280 (org-demote)))
8281 (org-fix-position-after-promote))
8283 (defun org-fix-position-after-promote ()
8284 "Fix cursor position and indentation after demoting/promoting."
8285 (let ((pos (point)))
8286 (when (save-excursion
8287 (beginning-of-line 1)
8288 (looking-at org-todo-line-regexp)
8289 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8290 (cond ((eobp) (insert " "))
8291 ((eolp) (insert " "))
8292 ((equal (char-after) ?\ ) (forward-char 1))))))
8294 (defun org-current-level ()
8295 "Return the level of the current entry, or nil if before the first headline.
8296 The level is the number of stars at the beginning of the
8297 headline. Use `org-reduced-level' to remove the effect of
8298 `org-odd-levels'. Unlike to `org-outline-level', this function
8299 ignores inlinetasks."
8300 (let ((level (org-with-limited-levels (org-outline-level))))
8301 (and (> level 0) level)))
8303 (defun org-get-previous-line-level ()
8304 "Return the outline depth of the last headline before the current line.
8305 Returns 0 for the first headline in the buffer, and nil if before the
8306 first headline."
8307 (and (org-current-level)
8308 (or (and (/= (line-beginning-position) (point-min))
8309 (save-excursion (beginning-of-line 0) (org-current-level)))
8310 0)))
8312 (defun org-reduced-level (l)
8313 "Compute the effective level of a heading.
8314 This takes into account the setting of `org-odd-levels-only'."
8315 (cond
8316 ((zerop l) 0)
8317 (org-odd-levels-only (1+ (floor (/ l 2))))
8318 (t l)))
8320 (defun org-level-increment ()
8321 "Return the number of stars that will be added or removed at a
8322 time to headlines when structure editing, based on the value of
8323 `org-odd-levels-only'."
8324 (if org-odd-levels-only 2 1))
8326 (defun org-get-valid-level (level &optional change)
8327 "Rectify a level change under the influence of `org-odd-levels-only'
8328 LEVEL is a current level, CHANGE is by how much the level should be
8329 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8330 even level numbers will become the next higher odd number."
8331 (if org-odd-levels-only
8332 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8333 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8334 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8335 (max 1 (+ level (or change 0)))))
8337 (defun org-promote ()
8338 "Promote the current heading higher up the tree."
8339 (org-with-wide-buffer
8340 (org-back-to-heading t)
8341 (let* ((after-change-functions (remq 'flyspell-after-change-function
8342 after-change-functions))
8343 (level (save-match-data (funcall outline-level)))
8344 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8345 (diff (abs (- level (length up-head) -1))))
8346 (cond
8347 ((and (= level 1) org-allow-promoting-top-level-subtree)
8348 (replace-match "# " nil t))
8349 ((= level 1)
8350 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8351 (t (replace-match up-head nil t)))
8352 (unless (= level 1)
8353 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8354 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8355 (run-hooks 'org-after-promote-entry-hook))))
8357 (defun org-demote ()
8358 "Demote the current heading lower down the tree."
8359 (org-with-wide-buffer
8360 (org-back-to-heading t)
8361 (let* ((after-change-functions (remq 'flyspell-after-change-function
8362 after-change-functions))
8363 (level (save-match-data (funcall outline-level)))
8364 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8365 (diff (abs (- level (length down-head) -1))))
8366 (replace-match down-head nil t)
8367 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8368 (when org-adapt-indentation (org-fixup-indentation diff))
8369 (run-hooks 'org-after-demote-entry-hook))))
8371 (defun org-cycle-level ()
8372 "Cycle the level of an empty headline through possible states.
8373 This goes first to child, then to parent, level, then up the hierarchy.
8374 After top level, it switches back to sibling level."
8375 (interactive)
8376 (let ((org-adapt-indentation nil))
8377 (when (org-point-at-end-of-empty-headline)
8378 (setq this-command 'org-cycle-level) ; Only needed for caching
8379 (let ((cur-level (org-current-level))
8380 (prev-level (org-get-previous-line-level)))
8381 (cond
8382 ;; If first headline in file, promote to top-level.
8383 ((= prev-level 0)
8384 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8385 do (org-do-promote)))
8386 ;; If same level as prev, demote one.
8387 ((= prev-level cur-level)
8388 (org-do-demote))
8389 ;; If parent is top-level, promote to top level if not already.
8390 ((= prev-level 1)
8391 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8392 do (org-do-promote)))
8393 ;; If top-level, return to prev-level.
8394 ((= cur-level 1)
8395 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8396 do (org-do-demote)))
8397 ;; If less than prev-level, promote one.
8398 ((< cur-level prev-level)
8399 (org-do-promote))
8400 ;; If deeper than prev-level, promote until higher than
8401 ;; prev-level.
8402 ((> cur-level prev-level)
8403 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8404 do (org-do-promote))))
8405 t))))
8407 (defun org-map-tree (fun)
8408 "Call FUN for every heading underneath the current one."
8409 (org-back-to-heading t)
8410 (let ((level (funcall outline-level)))
8411 (save-excursion
8412 (funcall fun)
8413 (while (and (progn
8414 (outline-next-heading)
8415 (> (funcall outline-level) level))
8416 (not (eobp)))
8417 (funcall fun)))))
8419 (defun org-map-region (fun beg end)
8420 "Call FUN for every heading between BEG and END."
8421 (let ((org-ignore-region t))
8422 (save-excursion
8423 (setq end (copy-marker end))
8424 (goto-char beg)
8425 (when (and (re-search-forward org-outline-regexp-bol nil t)
8426 (< (point) end))
8427 (funcall fun))
8428 (while (and (progn
8429 (outline-next-heading)
8430 (< (point) end))
8431 (not (eobp)))
8432 (funcall fun)))))
8434 (defun org-fixup-indentation (diff)
8435 "Change the indentation in the current entry by DIFF.
8437 DIFF is an integer. Indentation is done according to the
8438 following rules:
8440 - Planning information and property drawers are always indented
8441 according to the new level of the headline;
8443 - Footnote definitions and their contents are ignored;
8445 - Inlinetasks' boundaries are not shifted;
8447 - Empty lines are ignored;
8449 - Other lines' indentation are shifted by DIFF columns, unless
8450 it would introduce a structural change in the document, in
8451 which case no shifting is done at all.
8453 Assume point is at a heading or an inlinetask beginning."
8454 (org-with-wide-buffer
8455 (narrow-to-region (line-beginning-position)
8456 (save-excursion
8457 (if (org-with-limited-levels (org-at-heading-p))
8458 (org-with-limited-levels (outline-next-heading))
8459 (org-inlinetask-goto-end))
8460 (point)))
8461 (forward-line)
8462 ;; Indent properly planning info and property drawer.
8463 (when (looking-at-p org-planning-line-re)
8464 (org-indent-line)
8465 (forward-line))
8466 (when (looking-at org-property-drawer-re)
8467 (goto-char (match-end 0))
8468 (forward-line)
8469 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8470 (catch 'no-shift
8471 (when (zerop diff) (throw 'no-shift nil))
8472 ;; If DIFF is negative, first check if a shift is possible at all
8473 ;; (e.g., it doesn't break structure). This can only happen if
8474 ;; some contents are not properly indented.
8475 (let ((case-fold-search t))
8476 (when (< diff 0)
8477 (let ((diff (- diff))
8478 (forbidden-re (concat org-outline-regexp
8479 "\\|"
8480 (substring org-footnote-definition-re 1))))
8481 (save-excursion
8482 (while (not (eobp))
8483 (cond
8484 ((looking-at-p "[ \t]*$") (forward-line))
8485 ((and (looking-at-p org-footnote-definition-re)
8486 (let ((e (org-element-at-point)))
8487 (and (eq (org-element-type e) 'footnote-definition)
8488 (goto-char (org-element-property :end e))))))
8489 ((looking-at-p org-outline-regexp) (forward-line))
8490 ;; Give up if shifting would move before column 0 or
8491 ;; if it would introduce a headline or a footnote
8492 ;; definition.
8494 (skip-chars-forward " \t")
8495 (let ((ind (current-column)))
8496 (when (or (< ind diff)
8497 (and (= ind diff) (looking-at-p forbidden-re)))
8498 (throw 'no-shift nil)))
8499 ;; Ignore contents of example blocks and source
8500 ;; blocks if their indentation is meant to be
8501 ;; preserved. Jump to block's closing line.
8502 (beginning-of-line)
8503 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8504 (let ((e (org-element-at-point)))
8505 (and (memq (org-element-type e)
8506 '(example-block src-block))
8507 (or org-src-preserve-indentation
8508 (org-element-property :preserve-indent e))
8509 (goto-char (org-element-property :end e))
8510 (progn (skip-chars-backward " \r\t\n")
8511 (beginning-of-line)
8512 t))))
8513 (forward-line))))))))
8514 ;; Shift lines but footnote definitions, inlinetasks boundaries
8515 ;; by DIFF. Also skip contents of source or example blocks
8516 ;; when indentation is meant to be preserved.
8517 (while (not (eobp))
8518 (cond
8519 ((and (looking-at-p org-footnote-definition-re)
8520 (let ((e (org-element-at-point)))
8521 (and (eq (org-element-type e) 'footnote-definition)
8522 (goto-char (org-element-property :end e))))))
8523 ((looking-at-p org-outline-regexp) (forward-line))
8524 ((looking-at-p "[ \t]*$") (forward-line))
8526 (indent-line-to (+ (org-get-indentation) diff))
8527 (beginning-of-line)
8528 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8529 (let ((e (org-element-at-point)))
8530 (and (memq (org-element-type e)
8531 '(example-block src-block))
8532 (or org-src-preserve-indentation
8533 (org-element-property :preserve-indent e))
8534 (goto-char (org-element-property :end e))
8535 (progn (skip-chars-backward " \r\t\n")
8536 (beginning-of-line)
8537 t))))
8538 (forward-line)))))))))
8540 (defun org-convert-to-odd-levels ()
8541 "Convert an org-mode file with all levels allowed to one with odd levels.
8542 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8543 level 5 etc."
8544 (interactive)
8545 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8546 (let ((outline-level 'org-outline-level)
8547 (org-odd-levels-only nil) n)
8548 (save-excursion
8549 (goto-char (point-min))
8550 (while (re-search-forward "^\\*\\*+ " nil t)
8551 (setq n (- (length (match-string 0)) 2))
8552 (while (>= (setq n (1- n)) 0)
8553 (org-demote))
8554 (end-of-line 1))))))
8556 (defun org-convert-to-oddeven-levels ()
8557 "Convert an org-mode file with only odd levels to one with odd/even levels.
8558 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8559 file contains a section with an even level, conversion would
8560 destroy the structure of the file. An error is signaled in this
8561 case."
8562 (interactive)
8563 (goto-char (point-min))
8564 ;; First check if there are no even levels
8565 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8566 (org-show-set-visibility 'canonical)
8567 (error "Not all levels are odd in this file. Conversion not possible"))
8568 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8569 (let ((outline-regexp org-outline-regexp)
8570 (outline-level 'org-outline-level)
8571 (org-odd-levels-only nil) n)
8572 (save-excursion
8573 (goto-char (point-min))
8574 (while (re-search-forward "^\\*\\*+ " nil t)
8575 (setq n (/ (1- (length (match-string 0))) 2))
8576 (while (>= (setq n (1- n)) 0)
8577 (org-promote))
8578 (end-of-line 1))))))
8580 (defun org-tr-level (n)
8581 "Make N odd if required."
8582 (if org-odd-levels-only (1+ (/ n 2)) n))
8584 ;;; Vertical tree motion, cutting and pasting of subtrees
8586 (defun org-move-subtree-up (&optional arg)
8587 "Move the current subtree up past ARG headlines of the same level."
8588 (interactive "p")
8589 (org-move-subtree-down (- (prefix-numeric-value arg))))
8591 (defun org-move-subtree-down (&optional arg)
8592 "Move the current subtree down past ARG headlines of the same level."
8593 (interactive "p")
8594 (setq arg (prefix-numeric-value arg))
8595 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8596 'org-get-last-sibling))
8597 (ins-point (make-marker))
8598 (cnt (abs arg))
8599 (col (current-column))
8600 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8601 ;; Select the tree
8602 (org-back-to-heading)
8603 (setq beg0 (point))
8604 (save-excursion
8605 (setq ne-beg (org-back-over-empty-lines))
8606 (setq beg (point)))
8607 (save-match-data
8608 (save-excursion (outline-end-of-heading)
8609 (setq folded (outline-invisible-p)))
8610 (progn (org-end-of-subtree nil t)
8611 (unless (eobp) (backward-char))))
8612 (outline-next-heading)
8613 (setq ne-end (org-back-over-empty-lines))
8614 (setq end (point))
8615 (goto-char beg0)
8616 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8617 ;; include less whitespace
8618 (save-excursion
8619 (goto-char beg)
8620 (forward-line (- ne-beg ne-end))
8621 (setq beg (point))))
8622 ;; Find insertion point, with error handling
8623 (while (> cnt 0)
8624 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8625 (progn (goto-char beg0)
8626 (user-error "Cannot move past superior level or buffer limit")))
8627 (setq cnt (1- cnt)))
8628 (when (> arg 0)
8629 ;; Moving forward - still need to move over subtree
8630 (org-end-of-subtree t t)
8631 (save-excursion
8632 (org-back-over-empty-lines)
8633 (or (bolp) (newline))))
8634 (setq ne-ins (org-back-over-empty-lines))
8635 (move-marker ins-point (point))
8636 (setq txt (buffer-substring beg end))
8637 (org-save-markers-in-region beg end)
8638 (delete-region beg end)
8639 (org-remove-empty-overlays-at beg)
8640 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8641 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8642 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8643 (let ((bbb (point)))
8644 (insert-before-markers txt)
8645 (org-reinstall-markers-in-region bbb)
8646 (move-marker ins-point bbb))
8647 (or (bolp) (insert "\n"))
8648 (setq ins-end (point))
8649 (goto-char ins-point)
8650 (org-skip-whitespace)
8651 (when (and (< arg 0)
8652 (org-first-sibling-p)
8653 (> ne-ins ne-beg))
8654 ;; Move whitespace back to beginning
8655 (save-excursion
8656 (goto-char ins-end)
8657 (let ((kill-whole-line t))
8658 (kill-line (- ne-ins ne-beg)) (point)))
8659 (insert (make-string (- ne-ins ne-beg) ?\n)))
8660 (move-marker ins-point nil)
8661 (if folded
8662 (outline-hide-subtree)
8663 (org-show-entry)
8664 (org-show-children)
8665 (org-cycle-hide-drawers 'children))
8666 (org-clean-visibility-after-subtree-move)
8667 ;; move back to the initial column we were at
8668 (move-to-column col)))
8670 (defvar org-subtree-clip ""
8671 "Clipboard for cut and paste of subtrees.
8672 This is actually only a copy of the kill, because we use the normal kill
8673 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8675 (defvar org-subtree-clip-folded nil
8676 "Was the last copied subtree folded?
8677 This is used to fold the tree back after pasting.")
8679 (defun org-cut-subtree (&optional n)
8680 "Cut the current subtree into the clipboard.
8681 With prefix arg N, cut this many sequential subtrees.
8682 This is a short-hand for marking the subtree and then cutting it."
8683 (interactive "p")
8684 (org-copy-subtree n 'cut))
8686 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8687 "Copy the current subtree it in the clipboard.
8688 With prefix arg N, copy this many sequential subtrees.
8689 This is a short-hand for marking the subtree and then copying it.
8690 If CUT is non-nil, actually cut the subtree.
8691 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8692 of some markers in the region, even if CUT is non-nil. This is
8693 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8694 (interactive "p")
8695 (let (beg end folded (beg0 (point)))
8696 (if (called-interactively-p 'any)
8697 (org-back-to-heading nil) ; take what looks like a subtree
8698 (org-back-to-heading t)) ; take what is really there
8699 (setq beg (point))
8700 (skip-chars-forward " \t\r\n")
8701 (save-match-data
8702 (if nosubtrees
8703 (outline-next-heading)
8704 (save-excursion (outline-end-of-heading)
8705 (setq folded (outline-invisible-p)))
8706 (ignore-errors (org-forward-heading-same-level (1- n) t))
8707 (org-end-of-subtree t t)))
8708 ;; Include the end of an inlinetask
8709 (when (and (featurep 'org-inlinetask)
8710 (looking-at-p (concat (org-inlinetask-outline-regexp)
8711 "END[ \t]*$")))
8712 (end-of-line))
8713 (setq end (point))
8714 (goto-char beg0)
8715 (when (> end beg)
8716 (setq org-subtree-clip-folded folded)
8717 (when (or cut force-store-markers)
8718 (org-save-markers-in-region beg end))
8719 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8720 (setq org-subtree-clip (current-kill 0))
8721 (message "%s: Subtree(s) with %d characters"
8722 (if cut "Cut" "Copied")
8723 (length org-subtree-clip)))))
8725 (defun org-paste-subtree (&optional level tree for-yank remove)
8726 "Paste the clipboard as a subtree, with modification of headline level.
8727 The entire subtree is promoted or demoted in order to match a new headline
8728 level.
8730 If the cursor is at the beginning of a headline, the same level as
8731 that headline is used to paste the tree.
8733 If not, the new level is derived from the *visible* headings
8734 before and after the insertion point, and taken to be the inferior headline
8735 level of the two. So if the previous visible heading is level 3 and the
8736 next is level 4 (or vice versa), level 4 will be used for insertion.
8737 This makes sure that the subtree remains an independent subtree and does
8738 not swallow low level entries.
8740 You can also force a different level, either by using a numeric prefix
8741 argument, or by inserting the heading marker by hand. For example, if the
8742 cursor is after \"*****\", then the tree will be shifted to level 5.
8744 If optional TREE is given, use this text instead of the kill ring.
8746 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8747 move back over whitespace before inserting, and move point to the end of
8748 the inserted text when done.
8750 When REMOVE is non-nil, remove the subtree from the clipboard."
8751 (interactive "P")
8752 (setq tree (or tree (and kill-ring (current-kill 0))))
8753 (unless (org-kill-is-subtree-p tree)
8754 (user-error "%s"
8755 (substitute-command-keys
8756 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8757 (org-with-limited-levels
8758 (let* ((visp (not (outline-invisible-p)))
8759 (txt tree)
8760 (^re_ "\\(\\*+\\)[ \t]*")
8761 (old-level (if (string-match org-outline-regexp-bol txt)
8762 (- (match-end 0) (match-beginning 0) 1)
8763 -1))
8764 (force-level (cond (level (prefix-numeric-value level))
8765 ((and (looking-at "[ \t]*$")
8766 (string-match
8767 "^\\*+$" (buffer-substring
8768 (point-at-bol) (point))))
8769 (- (match-end 0) (match-beginning 0)))
8770 ((and (bolp)
8771 (looking-at org-outline-regexp))
8772 (- (match-end 0) (point) 1))))
8773 (previous-level (save-excursion
8774 (condition-case nil
8775 (progn
8776 (outline-previous-visible-heading 1)
8777 (if (looking-at ^re_)
8778 (- (match-end 0) (match-beginning 0) 1)
8780 (error 1))))
8781 (next-level (save-excursion
8782 (condition-case nil
8783 (progn
8784 (or (looking-at org-outline-regexp)
8785 (outline-next-visible-heading 1))
8786 (if (looking-at ^re_)
8787 (- (match-end 0) (match-beginning 0) 1)
8789 (error 1))))
8790 (new-level (or force-level (max previous-level next-level)))
8791 (shift (if (or (= old-level -1)
8792 (= new-level -1)
8793 (= old-level new-level))
8795 (- new-level old-level)))
8796 (delta (if (> shift 0) -1 1))
8797 (func (if (> shift 0) 'org-demote 'org-promote))
8798 (org-odd-levels-only nil)
8799 beg end newend)
8800 ;; Remove the forced level indicator
8801 (when force-level
8802 (delete-region (point-at-bol) (point)))
8803 ;; Paste
8804 (beginning-of-line (if (bolp) 1 2))
8805 (setq beg (point))
8806 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8807 (insert-before-markers txt)
8808 (unless (string-match "\n\\'" txt) (insert "\n"))
8809 (setq newend (point))
8810 (org-reinstall-markers-in-region beg)
8811 (setq end (point))
8812 (goto-char beg)
8813 (skip-chars-forward " \t\n\r")
8814 (setq beg (point))
8815 (when (and (outline-invisible-p) visp)
8816 (save-excursion (outline-show-heading)))
8817 ;; Shift if necessary
8818 (unless (= shift 0)
8819 (save-restriction
8820 (narrow-to-region beg end)
8821 (while (not (= shift 0))
8822 (org-map-region func (point-min) (point-max))
8823 (setq shift (+ delta shift)))
8824 (goto-char (point-min))
8825 (setq newend (point-max))))
8826 (when (or (called-interactively-p 'interactive) for-yank)
8827 (message "Clipboard pasted as level %d subtree" new-level))
8828 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8829 kill-ring
8830 (eq org-subtree-clip (current-kill 0))
8831 org-subtree-clip-folded)
8832 ;; The tree was folded before it was killed/copied
8833 (outline-hide-subtree))
8834 (and for-yank (goto-char newend))
8835 (and remove (setq kill-ring (cdr kill-ring))))))
8837 (defun org-kill-is-subtree-p (&optional txt)
8838 "Check if the current kill is an outline subtree, or a set of trees.
8839 Returns nil if kill does not start with a headline, or if the first
8840 headline level is not the largest headline level in the tree.
8841 So this will actually accept several entries of equal levels as well,
8842 which is OK for `org-paste-subtree'.
8843 If optional TXT is given, check this string instead of the current kill."
8844 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8845 (re (org-get-limited-outline-regexp))
8846 (^re (concat "^" re))
8847 (start-level (and kill
8848 (string-match
8849 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8850 kill)
8851 (- (match-end 2) (match-beginning 2) 1)))
8852 (start (1+ (or (match-beginning 2) -1))))
8853 (if (not start-level)
8854 (progn
8855 nil) ;; does not even start with a heading
8856 (catch 'exit
8857 (while (setq start (string-match ^re kill (1+ start)))
8858 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8859 (throw 'exit nil)))
8860 t))))
8862 (defvar org-markers-to-move nil
8863 "Markers that should be moved with a cut-and-paste operation.
8864 Those markers are stored together with their positions relative to
8865 the start of the region.")
8867 (defun org-save-markers-in-region (beg end)
8868 "Check markers in region.
8869 If these markers are between BEG and END, record their position relative
8870 to BEG, so that after moving the block of text, we can put the markers back
8871 into place.
8872 This function gets called just before an entry or tree gets cut from the
8873 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8874 called immediately, to move the markers with the entries."
8875 (setq org-markers-to-move nil)
8876 (when (featurep 'org-clock)
8877 (org-clock-save-markers-for-cut-and-paste beg end))
8878 (when (featurep 'org-agenda)
8879 (org-agenda-save-markers-for-cut-and-paste beg end)))
8881 (defun org-check-and-save-marker (marker beg end)
8882 "Check if MARKER is between BEG and END.
8883 If yes, remember the marker and the distance to BEG."
8884 (when (and (marker-buffer marker)
8885 (equal (marker-buffer marker) (current-buffer))
8886 (>= marker beg) (< marker end))
8887 (push (cons marker (- marker beg)) org-markers-to-move)))
8889 (defun org-reinstall-markers-in-region (beg)
8890 "Move all remembered markers to their position relative to BEG."
8891 (dolist (x org-markers-to-move)
8892 (move-marker (car x) (+ beg (cdr x))))
8893 (setq org-markers-to-move nil))
8895 (defun org-narrow-to-subtree ()
8896 "Narrow buffer to the current subtree."
8897 (interactive)
8898 (save-excursion
8899 (save-match-data
8900 (org-with-limited-levels
8901 (narrow-to-region
8902 (progn (org-back-to-heading t) (point))
8903 (progn (org-end-of-subtree t t)
8904 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8905 (point)))))))
8907 (defun org-narrow-to-block ()
8908 "Narrow buffer to the current block."
8909 (interactive)
8910 (let* ((case-fold-search t)
8911 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8912 "^[ \t]*#\\+end_.*")))
8913 (if blockp
8914 (narrow-to-region (car blockp) (cdr blockp))
8915 (user-error "Not in a block"))))
8917 (defun org-clone-subtree-with-time-shift (n &optional shift)
8918 "Clone the task (subtree) at point N times.
8919 The clones will be inserted as siblings.
8921 In interactive use, the user will be prompted for the number of
8922 clones to be produced. If the entry has a timestamp, the user
8923 will also be prompted for a time shift, which may be a repeater
8924 as used in time stamps, for example `+3d'. To disable this,
8925 you can call the function with a universal prefix argument.
8927 When a valid repeater is given and the entry contains any time
8928 stamps, the clones will become a sequence in time, with time
8929 stamps in the subtree shifted for each clone produced. If SHIFT
8930 is nil or the empty string, time stamps will be left alone. The
8931 ID property of the original subtree is removed.
8933 If the original subtree did contain time stamps with a repeater,
8934 the following will happen:
8935 - the repeater will be removed in each clone
8936 - an additional clone will be produced, with the current, unshifted
8937 date(s) in the entry.
8938 - the original entry will be placed *after* all the clones, with
8939 repeater intact.
8940 - the start days in the repeater in the original entry will be shifted
8941 to past the last clone.
8942 In this way you can spell out a number of instances of a repeating task,
8943 and still retain the repeater to cover future instances of the task.
8945 As described above, N+1 clones are produced when the original
8946 subtree has a repeater. Setting N to 0, then, can be used to
8947 remove the repeater from a subtree and create a shifted clone
8948 with the original repeater."
8949 (interactive "nNumber of clones to produce: ")
8950 (let ((shift
8951 (or shift
8952 (if (and (not (equal current-prefix-arg '(4)))
8953 (save-excursion
8954 (re-search-forward org-ts-regexp-both
8955 (save-excursion
8956 (org-end-of-subtree t)
8957 (point)) t)))
8958 (read-from-minibuffer
8959 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8960 ""))) ;; No time shift
8961 (n-no-remove -1)
8962 (drawer-re org-drawer-regexp)
8963 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8964 beg end template task idprop
8965 shift-n shift-what doshift nmin nmax)
8966 (unless (wholenump n)
8967 (user-error "Invalid number of replications %s" n))
8968 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8969 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8970 shift)))
8971 (user-error "Invalid shift specification %s" shift))
8972 (when doshift
8973 (setq shift-n (string-to-number (match-string 1 shift))
8974 shift-what (cdr (assoc (match-string 2 shift)
8975 '(("d" . day) ("w" . week)
8976 ("m" . month) ("y" . year))))))
8977 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8978 (setq nmin 1 nmax n)
8979 (org-back-to-heading t)
8980 (setq beg (point))
8981 (setq idprop (org-entry-get nil "ID"))
8982 (org-end-of-subtree t t)
8983 (or (bolp) (insert "\n"))
8984 (setq end (point))
8985 (setq template (buffer-substring beg end))
8986 (when (and doshift
8987 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8988 (delete-region beg end)
8989 (setq end beg)
8990 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8991 (goto-char end)
8992 (cl-loop for n from nmin to nmax do
8993 ;; prepare clone
8994 (with-temp-buffer
8995 (insert template)
8996 (org-mode)
8997 (goto-char (point-min))
8998 (org-show-subtree)
8999 (and idprop (if org-clone-delete-id
9000 (org-entry-delete nil "ID")
9001 (org-id-get-create t)))
9002 (unless (= n 0)
9003 (while (re-search-forward org-clock-re nil t)
9004 (kill-whole-line))
9005 (goto-char (point-min))
9006 (while (re-search-forward drawer-re nil t)
9007 (org-remove-empty-drawer-at (point))))
9008 (goto-char (point-min))
9009 (when doshift
9010 (while (re-search-forward org-ts-regexp-both nil t)
9011 (org-timestamp-change (* n shift-n) shift-what))
9012 (unless (= n n-no-remove)
9013 (goto-char (point-min))
9014 (while (re-search-forward org-ts-regexp nil t)
9015 (save-excursion
9016 (goto-char (match-beginning 0))
9017 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
9018 (delete-region (match-beginning 1) (match-end 1)))))))
9019 (setq task (buffer-string)))
9020 (insert task))
9021 (goto-char beg)))
9023 ;;; Outline Sorting
9025 (defun org-sort (with-case)
9026 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
9027 Optional argument WITH-CASE means sort case-sensitively."
9028 (interactive "P")
9029 (cond
9030 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
9031 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
9033 (org-call-with-arg 'org-sort-entries with-case))))
9035 (defun org-sort-remove-invisible (s)
9036 "Remove invisible links from string S."
9037 (remove-text-properties 0 (length s) org-rm-props s)
9038 (while (string-match org-bracket-link-regexp s)
9039 (setq s (replace-match (if (match-end 2)
9040 (match-string 3 s)
9041 (match-string 1 s))
9042 t t s)))
9043 (let ((st (format " %s " s)))
9044 (while (string-match org-emph-re st)
9045 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
9046 (setq s (substring st 1 -1)))
9049 (defvar org-priority-regexp) ; defined later in the file
9051 (defvar org-after-sorting-entries-or-items-hook nil
9052 "Hook that is run after a bunch of entries or items have been sorted.
9053 When children are sorted, the cursor is in the parent line when this
9054 hook gets called. When a region or a plain list is sorted, the cursor
9055 will be in the first entry of the sorted region/list.")
9057 (defun org-sort-entries
9058 (&optional with-case sorting-type getkey-func compare-func property)
9059 "Sort entries on a certain level of an outline tree.
9060 If there is an active region, the entries in the region are sorted.
9061 Else, if the cursor is before the first entry, sort the top-level items.
9062 Else, the children of the entry at point are sorted.
9064 Sorting can be alphabetically, numerically, by date/time as given by
9065 a time stamp, by a property, by priority order, or by a custom function.
9067 The command prompts for the sorting type unless it has been given to the
9068 function through the SORTING-TYPE argument, which needs to be a character,
9069 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
9070 the precise meaning of each character:
9072 a Alphabetically, ignoring the TODO keyword and the priority, if any.
9073 c By creation time, which is assumed to be the first inactive time stamp
9074 at the beginning of a line.
9075 d By deadline date/time.
9076 k By clocking time.
9077 n Numerically, by converting the beginning of the entry/item to a number.
9078 o By order of TODO keywords.
9079 p By priority according to the cookie.
9080 r By the value of a property.
9081 s By scheduled date/time.
9082 t By date/time, either the first active time stamp in the entry, or, if
9083 none exist, by the first inactive one.
9085 Capital letters will reverse the sort order.
9087 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
9088 called with point at the beginning of the record. It must return either
9089 a string or a number that should serve as the sorting key for that record.
9091 Comparing entries ignores case by default. However, with an optional argument
9092 WITH-CASE, the sorting considers case as well.
9094 Sorting is done against the visible part of the headlines, it ignores hidden
9095 links.
9097 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
9098 (interactive "P")
9099 (let ((case-func (if with-case 'identity 'downcase))
9100 (cmstr
9101 ;; The clock marker is lost when using `sort-subr', let's
9102 ;; store the clocking string.
9103 (when (equal (marker-buffer org-clock-marker) (current-buffer))
9104 (save-excursion
9105 (goto-char org-clock-marker)
9106 (buffer-substring-no-properties (line-beginning-position)
9107 (point)))))
9108 start beg end stars re re2
9109 txt what tmp)
9110 ;; Find beginning and end of region to sort
9111 (cond
9112 ((org-region-active-p)
9113 ;; we will sort the region
9114 (setq end (region-end)
9115 what "region")
9116 (goto-char (region-beginning))
9117 (unless (org-at-heading-p) (outline-next-heading))
9118 (setq start (point)))
9119 ((or (org-at-heading-p)
9120 (ignore-errors (progn (org-back-to-heading) t)))
9121 ;; we will sort the children of the current headline
9122 (org-back-to-heading)
9123 (setq start (point)
9124 end (progn (org-end-of-subtree t t)
9125 (or (bolp) (insert "\n"))
9126 (when (>= (org-back-over-empty-lines) 1)
9127 (forward-line 1))
9128 (point))
9129 what "children")
9130 (goto-char start)
9131 (outline-show-subtree)
9132 (outline-next-heading))
9134 ;; we will sort the top-level entries in this file
9135 (goto-char (point-min))
9136 (or (org-at-heading-p) (outline-next-heading))
9137 (setq start (point))
9138 (goto-char (point-max))
9139 (beginning-of-line 1)
9140 (when (looking-at ".*?\\S-")
9141 ;; File ends in a non-white line
9142 (end-of-line 1)
9143 (insert "\n"))
9144 (setq end (point-max))
9145 (setq what "top-level")
9146 (goto-char start)
9147 (outline-show-all)))
9149 (setq beg (point))
9150 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9152 (looking-at "\\(\\*+\\)")
9153 (setq stars (match-string 1)
9154 re (concat "^" (regexp-quote stars) " +")
9155 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9156 txt (buffer-substring beg end))
9157 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9158 (when (and (not (equal stars "*")) (string-match re2 txt))
9159 (user-error "Region to sort contains a level above the first entry"))
9161 (unless sorting-type
9162 (message
9163 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9164 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9165 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9166 what)
9167 (setq sorting-type (read-char-exclusive))
9169 (unless getkey-func
9170 (and (= (downcase sorting-type) ?f)
9171 (setq getkey-func
9172 (completing-read "Sort using function: "
9173 obarray 'fboundp t nil nil))
9174 (setq getkey-func (intern getkey-func))))
9176 (and (= (downcase sorting-type) ?r)
9177 (not property)
9178 (setq property
9179 (completing-read "Property: "
9180 (mapcar #'list (org-buffer-property-keys t))
9181 nil t))))
9183 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9184 (message "Sorting entries...")
9186 (save-restriction
9187 (narrow-to-region start end)
9188 (let ((dcst (downcase sorting-type))
9189 (case-fold-search nil)
9190 (now (current-time)))
9191 (sort-subr
9192 (/= dcst sorting-type)
9193 ;; This function moves to the beginning character of the "record" to
9194 ;; be sorted.
9195 (lambda nil
9196 (if (re-search-forward re nil t)
9197 (goto-char (match-beginning 0))
9198 (goto-char (point-max))))
9199 ;; This function moves to the last character of the "record" being
9200 ;; sorted.
9201 (lambda nil
9202 (save-match-data
9203 (condition-case nil
9204 (outline-forward-same-level 1)
9205 (error
9206 (goto-char (point-max))))))
9207 ;; This function returns the value that gets sorted against.
9208 (lambda nil
9209 (cond
9210 ((= dcst ?n)
9211 (if (looking-at org-complex-heading-regexp)
9212 (string-to-number (org-sort-remove-invisible (match-string 4)))
9213 nil))
9214 ((= dcst ?a)
9215 (if (looking-at org-complex-heading-regexp)
9216 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9217 nil))
9218 ((= dcst ?k)
9219 (or (get-text-property (point) :org-clock-minutes) 0))
9220 ((= dcst ?t)
9221 (let ((end (save-excursion (outline-next-heading) (point))))
9222 (if (or (re-search-forward org-ts-regexp end t)
9223 (re-search-forward org-ts-regexp-both end t))
9224 (org-time-string-to-seconds (match-string 0))
9225 (float-time now))))
9226 ((= dcst ?c)
9227 (let ((end (save-excursion (outline-next-heading) (point))))
9228 (if (re-search-forward
9229 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9230 end t)
9231 (org-time-string-to-seconds (match-string 0))
9232 (float-time now))))
9233 ((= dcst ?s)
9234 (let ((end (save-excursion (outline-next-heading) (point))))
9235 (if (re-search-forward org-scheduled-time-regexp end t)
9236 (org-time-string-to-seconds (match-string 1))
9237 (float-time now))))
9238 ((= dcst ?d)
9239 (let ((end (save-excursion (outline-next-heading) (point))))
9240 (if (re-search-forward org-deadline-time-regexp end t)
9241 (org-time-string-to-seconds (match-string 1))
9242 (float-time now))))
9243 ((= dcst ?p)
9244 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9245 (string-to-char (match-string 2))
9246 org-default-priority))
9247 ((= dcst ?r)
9248 (or (org-entry-get nil property) ""))
9249 ((= dcst ?o)
9250 (when (looking-at org-complex-heading-regexp)
9251 (let* ((m (match-string 2))
9252 (s (if (member m org-done-keywords) '- '+)))
9253 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9254 ((= dcst ?f)
9255 (if getkey-func
9256 (progn
9257 (setq tmp (funcall getkey-func))
9258 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9259 tmp)
9260 (error "Invalid key function `%s'" getkey-func)))
9261 (t (error "Invalid sorting type `%c'" sorting-type))))
9263 (cond
9264 ((= dcst ?a) 'string<)
9265 ((= dcst ?f) compare-func)
9266 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9267 (run-hooks 'org-after-sorting-entries-or-items-hook)
9268 ;; Reset the clock marker if needed
9269 (when cmstr
9270 (save-excursion
9271 (goto-char start)
9272 (search-forward cmstr nil t)
9273 (move-marker org-clock-marker (point))))
9274 (message "Sorting entries...done")))
9276 ;;; The orgstruct minor mode
9278 ;; Define a minor mode which can be used in other modes in order to
9279 ;; integrate the org-mode structure editing commands.
9281 ;; This is really a hack, because the org-mode structure commands use
9282 ;; keys which normally belong to the major mode. Here is how it
9283 ;; works: The minor mode defines all the keys necessary to operate the
9284 ;; structure commands, but wraps the commands into a function which
9285 ;; tests if the cursor is currently at a headline or a plain list
9286 ;; item. If that is the case, the structure command is used,
9287 ;; temporarily setting many Org-mode variables like regular
9288 ;; expressions for filling etc. However, when any of those keys is
9289 ;; used at a different location, function uses `key-binding' to look
9290 ;; up if the key has an associated command in another currently active
9291 ;; keymap (minor modes, major mode, global), and executes that
9292 ;; command. There might be problems if any of the keys is otherwise
9293 ;; used as a prefix key.
9295 (defcustom orgstruct-heading-prefix-regexp ""
9296 "Regexp that matches the custom prefix of Org headlines in
9297 orgstruct(++)-mode."
9298 :group 'org
9299 :version "24.4"
9300 :package-version '(Org . "8.3")
9301 :type 'regexp)
9302 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9304 (defcustom orgstruct-setup-hook nil
9305 "Hook run after orgstruct-mode-map is filled."
9306 :group 'org
9307 :version "24.4"
9308 :package-version '(Org . "8.0")
9309 :type 'hook)
9311 (defvar orgstruct-initialized nil)
9313 (defvar org-local-vars nil
9314 "List of local variables, for use by `orgstruct-mode'.")
9316 ;;;###autoload
9317 (define-minor-mode orgstruct-mode
9318 "Toggle the minor mode `orgstruct-mode'.
9319 This mode is for using Org-mode structure commands in other
9320 modes. The following keys behave as if Org-mode were active, if
9321 the cursor is on a headline, or on a plain list item (both as
9322 defined by Org-mode)."
9323 nil " OrgStruct" (make-sparse-keymap)
9324 (funcall (if orgstruct-mode
9325 'add-to-invisibility-spec
9326 'remove-from-invisibility-spec)
9327 '(outline . t))
9328 (when orgstruct-mode
9329 (org-load-modules-maybe)
9330 (unless orgstruct-initialized
9331 (orgstruct-setup)
9332 (setq orgstruct-initialized t))))
9334 ;;;###autoload
9335 (defun turn-on-orgstruct ()
9336 "Unconditionally turn on `orgstruct-mode'."
9337 (orgstruct-mode 1))
9339 (defvar-local orgstruct-is-++ nil
9340 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9341 (defvar-local org-fb-vars nil)
9342 (defun orgstruct++-mode (&optional arg)
9343 "Toggle `orgstruct-mode', the enhanced version of it.
9344 In addition to setting orgstruct-mode, this also exports all
9345 indentation and autofilling variables from org-mode into the
9346 buffer. It will also recognize item context in multiline items."
9347 (interactive "P")
9348 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9349 (if (< arg 1)
9350 (progn (orgstruct-mode -1)
9351 (dolist (v org-fb-vars)
9352 (set (make-local-variable (car v))
9353 (if (eq (car-safe (cadr v)) 'quote)
9354 (cl-cadadr v)
9355 (nth 1 v)))))
9356 (orgstruct-mode 1)
9357 (setq org-fb-vars nil)
9358 (unless org-local-vars
9359 (setq org-local-vars (org-get-local-variables)))
9360 (let (var val)
9361 (dolist (x org-local-vars)
9362 (when (string-match
9363 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9364 \\|fill-prefix\\|indent-\\)"
9365 (symbol-name (car x)))
9366 (setq var (car x) val (nth 1 x))
9367 (push (list var `(quote ,(eval var))) org-fb-vars)
9368 (set (make-local-variable var)
9369 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9370 (setq-local orgstruct-is-++ t))))
9372 ;;;###autoload
9373 (defun turn-on-orgstruct++ ()
9374 "Unconditionally turn on `orgstruct++-mode'."
9375 (orgstruct++-mode 1))
9377 (defun orgstruct-error ()
9378 "Error when there is no default binding for a structure key."
9379 (interactive)
9380 (funcall (if (fboundp 'user-error)
9381 'user-error
9382 'error)
9383 "This key has no function outside structure elements"))
9385 (defun orgstruct-setup ()
9386 "Setup orgstruct keymap."
9387 (dolist (cell '((org-demote . t)
9388 (org-metaleft . t)
9389 (org-metaright . t)
9390 (org-promote . t)
9391 (org-shiftmetaleft . t)
9392 (org-shiftmetaright . t)
9393 org-backward-element
9394 org-backward-heading-same-level
9395 org-ctrl-c-ret
9396 org-ctrl-c-minus
9397 org-ctrl-c-star
9398 org-cycle
9399 org-force-cycle-archived
9400 org-forward-heading-same-level
9401 org-insert-heading
9402 org-insert-heading-respect-content
9403 org-kill-note-or-show-branches
9404 org-mark-subtree
9405 org-meta-return
9406 org-metadown
9407 org-metaup
9408 org-narrow-to-subtree
9409 org-promote-subtree
9410 org-reveal
9411 org-shiftdown
9412 org-shiftleft
9413 org-shiftmetadown
9414 org-shiftmetaup
9415 org-shiftright
9416 org-shifttab
9417 org-shifttab
9418 org-shiftup
9419 org-show-children
9420 org-show-subtree
9421 org-sort
9422 org-up-element
9423 outline-demote
9424 outline-next-visible-heading
9425 outline-previous-visible-heading
9426 outline-promote
9427 outline-up-heading))
9428 (let ((f (or (car-safe cell) cell))
9429 (disable-when-heading-prefix (cdr-safe cell)))
9430 (when (fboundp f)
9431 (let ((new-bindings))
9432 (dolist (binding (nconc (where-is-internal f org-mode-map)
9433 (where-is-internal f outline-mode-map)))
9434 (push binding new-bindings)
9435 ;; TODO use local-function-key-map
9436 (dolist (rep '(("<tab>" . "TAB")
9437 ("<return>" . "RET")
9438 ("<escape>" . "ESC")
9439 ("<delete>" . "DEL")))
9440 (setq binding (read-kbd-macro
9441 (let ((case-fold-search))
9442 (replace-regexp-in-string
9443 (regexp-quote (cdr rep))
9444 (car rep)
9445 (key-description binding)))))
9446 (cl-pushnew binding new-bindings :test 'equal)))
9447 (dolist (binding new-bindings)
9448 (let ((key (lookup-key orgstruct-mode-map binding)))
9449 (when (or (not key) (numberp key))
9450 (ignore-errors
9451 (org-defkey orgstruct-mode-map
9452 binding
9453 (orgstruct-make-binding
9454 f binding disable-when-heading-prefix))))))))))
9455 (run-hooks 'orgstruct-setup-hook))
9457 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9458 "Create a function for binding in the structure minor mode.
9459 FUN is the command to call inside a table. KEY is the key that
9460 should be checked in for a command to execute outside of tables.
9461 Non-nil `disable-when-heading-prefix' means to disable the command
9462 if `orgstruct-heading-prefix-regexp' is not empty."
9463 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9464 (let ((nname name)
9465 (i 0))
9466 (while (fboundp (intern nname))
9467 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9468 (setq name (intern nname)))
9469 (eval
9470 (let ((bindings '((org-heading-regexp
9471 (concat "^"
9472 orgstruct-heading-prefix-regexp
9473 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9474 (org-outline-regexp
9475 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9476 (org-outline-regexp-bol
9477 (concat "^" org-outline-regexp))
9478 (outline-regexp org-outline-regexp)
9479 (outline-heading-end-regexp "\n")
9480 (outline-level 'org-outline-level)
9481 (outline-heading-alist))))
9482 `(defun ,name (arg)
9483 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9484 "Outside of structure, run the binding of `"
9485 (key-description key) "'."
9486 (when disable-when-heading-prefix
9487 (concat
9488 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9489 "back to the default binding due to limitations of Org's implementation of\n"
9490 "`" (symbol-name fun) "'.")))
9491 (interactive "p")
9492 (let* ((disable
9493 ,(and disable-when-heading-prefix
9494 '(not (string= orgstruct-heading-prefix-regexp ""))))
9495 (fallback
9496 (or disable
9497 (not
9498 (let* ,bindings
9499 (org-context-p 'headline 'item
9500 ,(when (memq fun
9501 '(org-insert-heading
9502 org-insert-heading-respect-content
9503 org-meta-return))
9504 '(when orgstruct-is-++
9505 'item-body))))))))
9506 (if fallback
9507 (let* ((orgstruct-mode)
9508 (binding
9509 (let ((key ,key))
9510 (catch 'exit
9511 (dolist
9512 (rep
9513 '(nil
9514 ("<\\([^>]*\\)tab>" . "\\1TAB")
9515 ("<\\([^>]*\\)return>" . "\\1RET")
9516 ("<\\([^>]*\\)escape>" . "\\1ESC")
9517 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9518 nil)
9519 (when rep
9520 (setq key (read-kbd-macro
9521 (let ((case-fold-search))
9522 (replace-regexp-in-string
9523 (car rep)
9524 (cdr rep)
9525 (key-description key))))))
9526 (when (key-binding key)
9527 (throw 'exit (key-binding key))))))))
9528 (if (keymapp binding)
9529 (org-set-transient-map binding)
9530 (let ((func (or binding
9531 (unless disable
9532 'orgstruct-error))))
9533 (when func
9534 (call-interactively func)))))
9535 (org-run-like-in-org-mode
9536 (lambda ()
9537 (interactive)
9538 (let* ,bindings
9539 (call-interactively ',fun)))))))))
9540 name))
9542 (defun org-contextualize-keys (alist contexts)
9543 "Return valid elements in ALIST depending on CONTEXTS.
9545 `org-agenda-custom-commands' or `org-capture-templates' are the
9546 values used for ALIST, and `org-agenda-custom-commands-contexts'
9547 or `org-capture-templates-contexts' are the associated contexts
9548 definitions."
9549 (let ((contexts
9550 ;; normalize contexts
9551 (mapcar
9552 (lambda(c) (cond ((listp (cadr c))
9553 (list (car c) (car c) (nth 1 c)))
9554 ((string= "" (cadr c))
9555 (list (car c) (car c) (nth 2 c)))
9556 (t c)))
9557 contexts))
9558 (a alist) r s)
9559 ;; loop over all commands or templates
9560 (dolist (c a)
9561 (let (vrules repl)
9562 (cond
9563 ((not (assoc (car c) contexts))
9564 (push c r))
9565 ((and (assoc (car c) contexts)
9566 (setq vrules (org-contextualize-validate-key
9567 (car c) contexts)))
9568 (mapc (lambda (vr)
9569 (unless (equal (car vr) (cadr vr))
9570 (setq repl vr)))
9571 vrules)
9572 (if (not repl) (push c r)
9573 (push (cadr repl) s)
9574 (push
9575 (cons (car c)
9576 (cdr (or (assoc (cadr repl) alist)
9577 (error "Undefined key `%s' as contextual replacement for `%s'"
9578 (cadr repl) (car c)))))
9579 r))))))
9580 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9581 (delq
9583 (delete-dups
9584 (mapcar (lambda (x)
9585 (let ((tpl (car x)))
9586 (unless (delq
9588 (mapcar (lambda (y)
9589 (equal y tpl))
9591 x)))
9592 (reverse r))))))
9594 (defun org-contextualize-validate-key (key contexts)
9595 "Check CONTEXTS for agenda or capture KEY."
9596 (let (res)
9597 (dolist (r contexts)
9598 (dolist (rr (car (last r)))
9599 (when
9600 (and (equal key (car r))
9601 (if (functionp rr) (funcall rr)
9602 (or (and (eq (car rr) 'in-file)
9603 (buffer-file-name)
9604 (string-match (cdr rr) (buffer-file-name)))
9605 (and (eq (car rr) 'in-mode)
9606 (string-match (cdr rr) (symbol-name major-mode)))
9607 (and (eq (car rr) 'in-buffer)
9608 (string-match (cdr rr) (buffer-name)))
9609 (when (and (eq (car rr) 'not-in-file)
9610 (buffer-file-name))
9611 (not (string-match (cdr rr) (buffer-file-name))))
9612 (when (eq (car rr) 'not-in-mode)
9613 (not (string-match (cdr rr) (symbol-name major-mode))))
9614 (when (eq (car rr) 'not-in-buffer)
9615 (not (string-match (cdr rr) (buffer-name)))))))
9616 (push r res))))
9617 (delete-dups (delq nil res))))
9619 (defun org-context-p (&rest contexts)
9620 "Check if local context is any of CONTEXTS.
9621 Possible values in the list of contexts are `table', `headline', and `item'."
9622 (let ((pos (point)))
9623 (goto-char (point-at-bol))
9624 (prog1 (or (and (memq 'table contexts)
9625 (looking-at "[ \t]*|"))
9626 (and (memq 'headline contexts)
9627 (looking-at org-outline-regexp))
9628 (and (memq 'item contexts)
9629 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9630 (and (memq 'item-body contexts)
9631 (org-in-item-p)))
9632 (goto-char pos))))
9634 (defconst org-unique-local-variables
9635 '(org-element--cache
9636 org-element--cache-objects
9637 org-element--cache-sync-keys
9638 org-element--cache-sync-requests
9639 org-element--cache-sync-timer)
9640 "List of local variables that cannot be transferred to another buffer.")
9642 (defun org-get-local-variables ()
9643 "Return a list of all local variables in an Org mode buffer."
9644 (delq nil
9645 (mapcar
9646 (lambda (x)
9647 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9648 (name (car binding)))
9649 (and (not (get name 'org-state))
9650 (not (memq name org-unique-local-variables))
9651 (string-match-p
9652 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9653 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9654 (symbol-name name))
9655 binding)))
9656 (with-temp-buffer
9657 (org-mode)
9658 (buffer-local-variables)))))
9660 (defun org-clone-local-variables (from-buffer &optional regexp)
9661 "Clone local variables from FROM-BUFFER.
9662 Optional argument REGEXP selects variables to clone."
9663 (dolist (pair (buffer-local-variables from-buffer))
9664 (let ((name (car pair)))
9665 (when (and (symbolp name)
9666 (not (memq name org-unique-local-variables))
9667 (or (null regexp) (string-match regexp (symbol-name name))))
9668 (set (make-local-variable name) (cdr pair))))))
9670 ;;;###autoload
9671 (defun org-run-like-in-org-mode (cmd)
9672 "Run a command, pretending that the current buffer is in Org-mode.
9673 This will temporarily bind local variables that are typically bound in
9674 Org-mode to the values they have in Org-mode, and then interactively
9675 call CMD."
9676 (org-load-modules-maybe)
9677 (unless org-local-vars
9678 (setq org-local-vars (org-get-local-variables)))
9679 (let (binds)
9680 (dolist (var org-local-vars)
9681 (when (or (not (boundp (car var)))
9682 (eq (symbol-value (car var))
9683 (default-value (car var))))
9684 (push (list (car var) `(quote ,(cadr var))) binds)))
9685 (eval `(let ,binds
9686 (call-interactively (quote ,cmd))))))
9688 (defun org-get-category (&optional pos force-refresh)
9689 "Get the category applying to position POS."
9690 (save-match-data
9691 (when force-refresh (org-refresh-category-properties))
9692 (let ((pos (or pos (point))))
9693 (or (get-text-property pos 'org-category)
9694 (progn (org-refresh-category-properties)
9695 (get-text-property pos 'org-category))))))
9697 ;;; Refresh properties
9699 (defun org-refresh-properties (dprop tprop)
9700 "Refresh buffer text properties.
9701 DPROP is the drawer property and TPROP is either the
9702 corresponding text property to set, or an alist with each element
9703 being a text property (as a symbol) and a function to apply to
9704 the value of the drawer property."
9705 (let ((case-fold-search t)
9706 (inhibit-read-only t))
9707 (org-with-silent-modifications
9708 (save-excursion
9709 (save-restriction
9710 (widen)
9711 (goto-char (point-min))
9712 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9713 (org-refresh-property tprop (match-string-no-properties 1))))))))
9715 (defun org-refresh-property (tprop p)
9716 "Refresh the buffer text property TPROP from the drawer property P.
9717 The refresh happens only for the current tree (not subtree)."
9718 (unless (org-before-first-heading-p)
9719 (save-excursion
9720 (org-back-to-heading t)
9721 (if (symbolp tprop)
9722 ;; TPROP is a text property symbol
9723 (put-text-property
9724 (point) (or (outline-next-heading) (point-max)) tprop p)
9725 ;; TPROP is an alist with (properties . function) elements
9726 (dolist (al tprop)
9727 (save-excursion
9728 (put-text-property
9729 (line-beginning-position) (or (outline-next-heading) (point-max))
9730 (car al)
9731 (funcall (cdr al) p))))))))
9733 (defun org-refresh-category-properties ()
9734 "Refresh category text properties in the buffer."
9735 (let ((case-fold-search t)
9736 (inhibit-read-only t)
9737 (default-category
9738 (cond ((null org-category)
9739 (if buffer-file-name
9740 (file-name-sans-extension
9741 (file-name-nondirectory buffer-file-name))
9742 "???"))
9743 ((symbolp org-category) (symbol-name org-category))
9744 (t org-category))))
9745 (org-with-silent-modifications
9746 (org-with-wide-buffer
9747 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9748 ;; This is the default category for the buffer. If none is
9749 ;; found, fall-back to `org-category' or buffer file name.
9750 (put-text-property
9751 (point-min) (point-max)
9752 'org-category
9753 (catch 'buffer-category
9754 (goto-char (point-max))
9755 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9756 (let ((element (org-element-at-point)))
9757 (when (eq (org-element-type element) 'keyword)
9758 (throw 'buffer-category
9759 (org-element-property :value element)))))
9760 default-category))
9761 ;; Set sub-tree specific categories.
9762 (goto-char (point-min))
9763 (let ((regexp (org-re-property "CATEGORY")))
9764 (while (re-search-forward regexp nil t)
9765 (let ((value (match-string-no-properties 3)))
9766 (when (org-at-property-p)
9767 (put-text-property
9768 (save-excursion (org-back-to-heading t) (point))
9769 (save-excursion (org-end-of-subtree t t) (point))
9770 'org-category
9771 value)))))))))
9773 (defun org-refresh-stats-properties ()
9774 "Refresh stats text properties in the buffer."
9775 (let (stats)
9776 (org-with-silent-modifications
9777 (save-excursion
9778 (save-restriction
9779 (widen)
9780 (goto-char (point-min))
9781 (while (re-search-forward
9782 (concat org-outline-regexp-bol ".*"
9783 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9784 nil t)
9785 (setq stats (cond ((equal (match-string 3) "0") 0)
9786 ((match-string 2)
9787 (/ (* (string-to-number (match-string 2)) 100)
9788 (string-to-number (match-string 3))))
9789 (t (string-to-number (match-string 1)))))
9790 (org-back-to-heading t)
9791 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9792 'org-stats stats)))))))
9794 (defun org-refresh-effort-properties ()
9795 "Refresh effort properties"
9796 (org-refresh-properties
9797 org-effort-property
9798 '((effort . identity)
9799 (effort-minutes . org-duration-string-to-minutes))))
9801 ;;;; Link Stuff
9803 ;;; Link abbreviations
9805 (defun org-link-expand-abbrev (link)
9806 "Apply replacements as defined in `org-link-abbrev-alist'."
9807 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9808 (let* ((key (match-string 1 link))
9809 (as (or (assoc key org-link-abbrev-alist-local)
9810 (assoc key org-link-abbrev-alist)))
9811 (tag (and (match-end 2) (match-string 3 link)))
9812 rpl)
9813 (if (not as)
9814 link
9815 (setq rpl (cdr as))
9816 (cond
9817 ((symbolp rpl) (funcall rpl tag))
9818 ((string-match "%(\\([^)]+\\))" rpl)
9819 (replace-match
9820 (save-match-data
9821 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9822 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9823 ((string-match "%h" rpl)
9824 (replace-match (url-hexify-string (or tag "")) t t rpl))
9825 (t (concat rpl tag)))))
9826 link))
9828 ;;; Storing and inserting links
9830 (defvar org-insert-link-history nil
9831 "Minibuffer history for links inserted with `org-insert-link'.")
9833 (defvar org-stored-links nil
9834 "Contains the links stored with `org-store-link'.")
9836 (defvar org-store-link-plist nil
9837 "Plist with info about the most recently link created with `org-store-link'.")
9839 (defun org-store-link-functions ()
9840 "Return a list of functions that are called to create and store a link.
9841 The functions defined in the :store property of
9842 `org-link-parameters'.
9844 Each function will be called in turn until one returns a non-nil
9845 value. Each function should check if it is responsible for
9846 creating this link (for example by looking at the major mode).
9847 If not, it must exit and return nil. If yes, it should return
9848 a non-nil value after calling `org-store-link-props' with a list
9849 of properties and values. Special properties are:
9851 :type The link prefix, like \"http\". This must be given.
9852 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9853 This is obligatory as well.
9854 :description Optional default description for the second pair
9855 of brackets in an Org mode link. The user can still change
9856 this when inserting this link into an Org mode buffer.
9858 In addition to these, any additional properties can be specified
9859 and then used in capture templates."
9860 (cl-loop for link in org-link-parameters
9861 with store-func
9862 do (setq store-func (org-link-get-parameter (car link) :store))
9863 if store-func
9864 collect store-func))
9866 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9867 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9869 ;;;###autoload
9870 (defun org-store-link (arg)
9871 "\\<org-mode-map>Store an org-link to the current location.
9872 This link is added to `org-stored-links' and can later be inserted
9873 into an Org buffer with \\[org-insert-link].
9875 For some link types, a prefix ARG is interpreted.
9876 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9877 For file links, ARG negates `org-context-in-file-links'.
9879 A double prefix ARG force skipping storing functions that are not
9880 part of Org's core.
9882 A triple prefix ARG force storing a link for each line in the
9883 active region."
9884 (interactive "P")
9885 (org-load-modules-maybe)
9886 (if (and (equal arg '(64)) (org-region-active-p))
9887 (save-excursion
9888 (let ((end (region-end)))
9889 (goto-char (region-beginning))
9890 (set-mark (point))
9891 (while (< (point-at-eol) end)
9892 (move-end-of-line 1) (activate-mark)
9893 (let (current-prefix-arg)
9894 (call-interactively 'org-store-link))
9895 (move-beginning-of-line 2)
9896 (set-mark (point)))))
9897 (setq org-store-link-plist nil)
9898 (let (link cpltxt desc description search
9899 txt custom-id agenda-link sfuns sfunsn)
9900 (cond
9902 ;; Store a link using an external link type
9903 ((and (not (equal arg '(16)))
9904 (setq sfuns
9905 (delq
9906 nil (mapcar (lambda (f)
9907 (let (fs) (if (funcall f) (push f fs))))
9908 (org-store-link-functions)))
9909 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9910 (or (and (cdr sfuns)
9911 (funcall (intern
9912 (completing-read
9913 "Which function for creating the link? "
9914 sfunsn nil t (car sfunsn)))))
9915 (funcall (caar sfuns)))
9916 (setq link (plist-get org-store-link-plist :link)
9917 desc (or (plist-get org-store-link-plist
9918 :description)
9919 link))))
9921 ;; Store a link from a source code buffer.
9922 ((org-src-edit-buffer-p)
9923 (let ((coderef-format (org-src-coderef-format)))
9924 (cond ((save-excursion
9925 (beginning-of-line)
9926 (looking-at (org-src-coderef-regexp coderef-format)))
9927 (setq link (format "(%s)" (match-string-no-properties 3))))
9928 ((called-interactively-p 'any)
9929 (let ((label (read-string "Code line label: ")))
9930 (end-of-line)
9931 (setq link (format coderef-format label))
9932 (let ((gc (- 79 (length link))))
9933 (if (< (current-column) gc)
9934 (org-move-to-column gc t)
9935 (insert " ")))
9936 (insert link)
9937 (setq link (concat "(" label ")"))
9938 (setq desc nil)))
9939 (t (setq link nil)))))
9941 ;; We are in the agenda, link to referenced location
9942 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9943 (let ((m (or (get-text-property (point) 'org-hd-marker)
9944 (get-text-property (point) 'org-marker))))
9945 (when m
9946 (org-with-point-at m
9947 (setq agenda-link
9948 (if (called-interactively-p 'any)
9949 (call-interactively 'org-store-link)
9950 (org-store-link nil)))))))
9952 ((eq major-mode 'calendar-mode)
9953 (let ((cd (calendar-cursor-to-date)))
9954 (setq link
9955 (format-time-string
9956 (car org-time-stamp-formats)
9957 (apply 'encode-time
9958 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9959 nil nil nil))))
9960 (org-store-link-props :type "calendar" :date cd)))
9962 ((eq major-mode 'help-mode)
9963 (setq link (concat "help:" (save-excursion
9964 (goto-char (point-min))
9965 (looking-at "^[^ ]+")
9966 (match-string 0))))
9967 (org-store-link-props :type "help"))
9969 ((eq major-mode 'w3-mode)
9970 (setq cpltxt (if (and (buffer-name)
9971 (not (string-match "Untitled" (buffer-name))))
9972 (buffer-name)
9973 (url-view-url t))
9974 link (url-view-url t))
9975 (org-store-link-props :type "w3" :url (url-view-url t)))
9977 ((eq major-mode 'image-mode)
9978 (setq cpltxt (concat "file:"
9979 (abbreviate-file-name buffer-file-name))
9980 link cpltxt)
9981 (org-store-link-props :type "image" :file buffer-file-name))
9983 ;; In dired, store a link to the file of the current line
9984 ((derived-mode-p 'dired-mode)
9985 (let ((file (dired-get-filename nil t)))
9986 (setq file (if file
9987 (abbreviate-file-name
9988 (expand-file-name (dired-get-filename nil t)))
9989 ;; otherwise, no file so use current directory.
9990 default-directory))
9991 (setq cpltxt (concat "file:" file)
9992 link cpltxt)))
9994 ((setq search (run-hook-with-args-until-success
9995 'org-create-file-search-functions))
9996 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9997 "::" search))
9998 (setq cpltxt (or description link)))
10000 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10001 (org-with-limited-levels
10002 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10003 (cond
10004 ;; Store a link using the target at point
10005 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10006 (setq cpltxt
10007 (concat "file:"
10008 (abbreviate-file-name
10009 (buffer-file-name (buffer-base-buffer)))
10010 "::" (match-string 1))
10011 link cpltxt))
10012 ((and (featurep 'org-id)
10013 (or (eq org-id-link-to-org-use-id t)
10014 (and (called-interactively-p 'any)
10015 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10016 (and (eq org-id-link-to-org-use-id
10017 'create-if-interactive-and-no-custom-id)
10018 (not custom-id))))
10019 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10020 ;; Store a link using the ID at point
10021 (setq link (condition-case nil
10022 (prog1 (org-id-store-link)
10023 (setq desc (or (plist-get org-store-link-plist
10024 :description)
10025 "")))
10026 (error
10027 ;; Probably before first headline, link only to file
10028 (concat "file:"
10029 (abbreviate-file-name
10030 (buffer-file-name (buffer-base-buffer))))))))
10032 ;; Just link to current headline
10033 (setq cpltxt (concat "file:"
10034 (abbreviate-file-name
10035 (buffer-file-name (buffer-base-buffer)))))
10036 ;; Add a context search string
10037 (when (org-xor org-context-in-file-links arg)
10038 (let* ((element (org-element-at-point))
10039 (name (org-element-property :name element)))
10040 (setq txt (cond
10041 ((org-at-heading-p) nil)
10042 (name)
10043 ((org-region-active-p)
10044 (buffer-substring (region-beginning) (region-end)))))
10045 (when (or (null txt) (string-match "\\S-" txt))
10046 (setq cpltxt
10047 (concat cpltxt "::"
10048 (condition-case nil
10049 (org-make-org-heading-search-string txt)
10050 (error "")))
10051 desc (or name
10052 (nth 4 (ignore-errors (org-heading-components)))
10053 "NONE")))))
10054 (when (string-match "::\\'" cpltxt)
10055 (setq cpltxt (substring cpltxt 0 -2)))
10056 (setq link cpltxt)))))
10058 ((buffer-file-name (buffer-base-buffer))
10059 ;; Just link to this file here.
10060 (setq cpltxt (concat "file:"
10061 (abbreviate-file-name
10062 (buffer-file-name (buffer-base-buffer)))))
10063 ;; Add a context string.
10064 (when (org-xor org-context-in-file-links arg)
10065 (setq txt (if (org-region-active-p)
10066 (buffer-substring (region-beginning) (region-end))
10067 (buffer-substring (point-at-bol) (point-at-eol))))
10068 ;; Only use search option if there is some text.
10069 (when (string-match "\\S-" txt)
10070 (setq cpltxt
10071 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10072 desc "NONE")))
10073 (setq link cpltxt))
10075 ((called-interactively-p 'interactive)
10076 (user-error "No method for storing a link from this buffer"))
10078 (t (setq link nil)))
10080 ;; We're done setting link and desc, clean up
10081 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10082 (setq link (or link cpltxt)
10083 desc (or desc cpltxt))
10084 (cond ((not desc))
10085 ((equal desc "NONE") (setq desc nil))
10086 (t (setq desc
10087 (replace-regexp-in-string
10088 org-bracket-link-analytic-regexp
10089 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10090 desc))))
10091 ;; Return the link
10092 (if (not (and (or (called-interactively-p 'any)
10093 executing-kbd-macro)
10094 link))
10095 (or agenda-link (and link (org-make-link-string link desc)))
10096 (push (list link desc) org-stored-links)
10097 (message "Stored: %s" (or desc link))
10098 (when custom-id
10099 (setq link (concat "file:" (abbreviate-file-name
10100 (buffer-file-name)) "::#" custom-id))
10101 (push (list link desc) org-stored-links))
10102 (car org-stored-links)))))
10104 (defun org-store-link-props (&rest plist)
10105 "Store link properties, extract names, addresses and dates."
10106 (let ((x (plist-get plist :from)))
10107 (when x
10108 (let ((adr (mail-extract-address-components x)))
10109 (setq plist (plist-put plist :fromname (car adr)))
10110 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10111 (let ((x (plist-get plist :to)))
10112 (when x
10113 (let ((adr (mail-extract-address-components x)))
10114 (setq plist (plist-put plist :toname (car adr)))
10115 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10116 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10117 (when x
10118 (setq plist (plist-put plist :date-timestamp
10119 (format-time-string
10120 (org-time-stamp-format t) x)))
10121 (setq plist (plist-put plist :date-timestamp-inactive
10122 (format-time-string
10123 (org-time-stamp-format t t) x)))))
10124 (let ((from (plist-get plist :from))
10125 (to (plist-get plist :to)))
10126 (when (and from to org-from-is-user-regexp)
10127 (setq plist
10128 (plist-put plist :fromto
10129 (if (string-match org-from-is-user-regexp from)
10130 (concat "to %t")
10131 (concat "from %f"))))))
10132 (setq org-store-link-plist plist))
10134 (defun org-add-link-props (&rest plist)
10135 "Add these properties to the link property list."
10136 (let (key value)
10137 (while plist
10138 (setq key (pop plist) value (pop plist))
10139 (setq org-store-link-plist
10140 (plist-put org-store-link-plist key value)))))
10142 (defun org-email-link-description (&optional fmt)
10143 "Return the description part of an email link.
10144 This takes information from `org-store-link-plist' and formats it
10145 according to FMT (default from `org-email-link-description-format')."
10146 (setq fmt (or fmt org-email-link-description-format))
10147 (let* ((p org-store-link-plist)
10148 (to (plist-get p :toaddress))
10149 (from (plist-get p :fromaddress))
10150 (table
10151 (list
10152 (cons "%c" (plist-get p :fromto))
10153 (cons "%F" (plist-get p :from))
10154 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10155 (cons "%T" (plist-get p :to))
10156 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10157 (cons "%s" (plist-get p :subject))
10158 (cons "%d" (plist-get p :date))
10159 (cons "%m" (plist-get p :message-id)))))
10160 (when (string-match "%c" fmt)
10161 ;; Check if the user wrote this message
10162 (if (and org-from-is-user-regexp from to
10163 (save-match-data (string-match org-from-is-user-regexp from)))
10164 (setq fmt (replace-match "to %t" t t fmt))
10165 (setq fmt (replace-match "from %f" t t fmt))))
10166 (org-replace-escapes fmt table)))
10168 (defun org-make-org-heading-search-string (&optional string)
10169 "Make search string for the current headline or STRING."
10170 (let ((s (or string
10171 (and (derived-mode-p 'org-mode)
10172 (save-excursion
10173 (org-back-to-heading t)
10174 (org-element-property :raw-value (org-element-at-point))))))
10175 (lines org-context-in-file-links))
10176 (or string (setq s (concat "*" s))) ; Add * for headlines
10177 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10178 (when (and string (integerp lines) (> lines 0))
10179 (let ((slines (org-split-string s "\n")))
10180 (when (< lines (length slines))
10181 (setq s (mapconcat
10182 'identity
10183 (reverse (nthcdr (- (length slines) lines)
10184 (reverse slines))) "\n")))))
10185 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10187 (defun org-make-link-string (link &optional description)
10188 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10189 (unless (org-string-nw-p link) (error "Empty link"))
10190 (let ((uri (cond ((string-match org-link-types-re link)
10191 (concat (match-string 1 link)
10192 (org-link-escape (substring link (match-end 1)))))
10193 ;; For readability, url-encode internal links only
10194 ;; when absolutely needed (i.e, when they contain
10195 ;; square brackets). File links however, are
10196 ;; encoded since, e.g., spaces are significant.
10197 ((or (file-name-absolute-p link)
10198 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10199 (org-link-escape link))
10200 (t link)))
10201 (description
10202 (and (org-string-nw-p description)
10203 ;; Remove brackets from description, as they are fatal.
10204 (replace-regexp-in-string
10205 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10206 (org-trim description)))))
10207 (format "[[%s]%s]"
10209 (if description (format "[%s]" description) ""))))
10211 (defconst org-link-escape-chars
10212 ;;%20 %5B %5D %25
10213 '(?\s ?\[ ?\] ?%)
10214 "List of characters that should be escaped in a link when stored to Org.
10215 This is the list that is used for internal purposes.")
10217 (defun org-link-escape (text &optional table merge)
10218 "Return percent escaped representation of TEXT.
10219 TEXT is a string with the text to escape.
10220 Optional argument TABLE is a list with characters that should be
10221 escaped. When nil, `org-link-escape-chars' is used.
10222 If optional argument MERGE is set, merge TABLE into
10223 `org-link-escape-chars'."
10224 (let ((characters-to-encode
10225 (cond ((null table) org-link-escape-chars)
10226 (merge (append org-link-escape-chars table))
10227 (t table))))
10228 (mapconcat
10229 (lambda (c)
10230 (if (or (memq c characters-to-encode)
10231 (and org-url-hexify-p (or (< c 32) (> c 126))))
10232 (mapconcat (lambda (e) (format "%%%.2X" e))
10233 (or (encode-coding-char c 'utf-8)
10234 (error "Unable to percent escape character: %c" c))
10236 (char-to-string c)))
10237 text "")))
10239 (defun org-link-unescape (str)
10240 "Unhex hexified Unicode parts in string STR.
10241 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10242 reciprocal of `org-link-escape', which see."
10243 (if (org-string-nw-p str)
10244 (replace-regexp-in-string
10245 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10246 str))
10248 (defun org-link-unescape-compound (hex)
10249 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10250 Note: this function also decodes single byte encodings like
10251 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10252 (save-match-data
10253 (let* ((bytes (cdr (split-string hex "%")))
10254 (ret "")
10255 (eat 0)
10256 (sum 0))
10257 (while bytes
10258 (let* ((val (string-to-number (pop bytes) 16))
10259 (shift-xor
10260 (if (= 0 eat)
10261 (cond
10262 ((>= val 252) (cons 6 252))
10263 ((>= val 248) (cons 5 248))
10264 ((>= val 240) (cons 4 240))
10265 ((>= val 224) (cons 3 224))
10266 ((>= val 192) (cons 2 192))
10267 (t (cons 0 0)))
10268 (cons 6 128))))
10269 (when (>= val 192) (setq eat (car shift-xor)))
10270 (setq val (logxor val (cdr shift-xor)))
10271 (setq sum (+ (lsh sum (car shift-xor)) val))
10272 (when (> eat 0) (setq eat (- eat 1)))
10273 (cond
10274 ((= 0 eat) ;multi byte
10275 (setq ret (concat ret (char-to-string sum)))
10276 (setq sum 0))
10277 ((not bytes) ; single byte(s)
10278 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10279 ret)))
10281 (defun org-link-unescape-single-byte-sequence (hex)
10282 "Unhexify hex-encoded single byte character sequences."
10283 (mapconcat (lambda (byte)
10284 (char-to-string (string-to-number byte 16)))
10285 (cdr (split-string hex "%")) ""))
10287 (defun org-xor (a b)
10288 "Exclusive or."
10289 (if a (not b) b))
10291 (defun org-fixup-message-id-for-http (s)
10292 "Replace special characters in a message id, so it can be used in an http query."
10293 (when (string-match "%" s)
10294 (setq s (mapconcat (lambda (c)
10295 (if (eq c ?%)
10296 "%25"
10297 (char-to-string c)))
10298 s "")))
10299 (while (string-match "<" s)
10300 (setq s (replace-match "%3C" t t s)))
10301 (while (string-match ">" s)
10302 (setq s (replace-match "%3E" t t s)))
10303 (while (string-match "@" s)
10304 (setq s (replace-match "%40" t t s)))
10307 (defun org-link-prettify (link)
10308 "Return a human-readable representation of LINK.
10309 The car of LINK must be a raw link.
10310 The cdr of LINK must be either a link description or nil."
10311 (let ((desc (or (cadr link) "<no description>")))
10312 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10313 "<" (car link) ">")))
10315 ;;;###autoload
10316 (defun org-insert-link-global ()
10317 "Insert a link like Org-mode does.
10318 This command can be called in any mode to insert a link in Org-mode syntax."
10319 (interactive)
10320 (org-load-modules-maybe)
10321 (org-run-like-in-org-mode 'org-insert-link))
10323 (defun org-insert-all-links (arg &optional pre post)
10324 "Insert all links in `org-stored-links'.
10325 When a universal prefix, do not delete the links from `org-stored-links'.
10326 When `ARG' is a number, insert the last N link(s).
10327 `PRE' and `POST' are optional arguments to define a string to
10328 prepend or to append."
10329 (interactive "P")
10330 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10331 (links (copy-sequence org-stored-links))
10332 (pr (or pre "- "))
10333 (po (or post "\n"))
10334 (cnt 1) l)
10335 (if (null org-stored-links)
10336 (message "No link to insert")
10337 (while (and (or (listp arg) (>= arg cnt))
10338 (setq l (if (listp arg)
10339 (pop links)
10340 (pop org-stored-links))))
10341 (setq cnt (1+ cnt))
10342 (insert pr)
10343 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10344 (insert po)))))
10346 (defun org-insert-last-stored-link (arg)
10347 "Insert the last link stored in `org-stored-links'."
10348 (interactive "p")
10349 (org-insert-all-links arg "" "\n"))
10351 (defun org-link-fontify-links-to-this-file ()
10352 "Fontify links to the current file in `org-stored-links'."
10353 (let ((f (buffer-file-name)) a b)
10354 (setq a (mapcar (lambda(l)
10355 (let ((ll (car l)))
10356 (when (and (string-match "^file:\\(.+\\)::" ll)
10357 (equal f (expand-file-name (match-string 1 ll))))
10358 ll)))
10359 org-stored-links))
10360 (when (featurep 'org-id)
10361 (setq b (mapcar (lambda(l)
10362 (let ((ll (car l)))
10363 (when (and (string-match "^id:\\(.+\\)$" ll)
10364 (equal f (expand-file-name
10365 (or (org-id-find-id-file
10366 (match-string 1 ll)) ""))))
10367 ll)))
10368 org-stored-links)))
10369 (mapcar (lambda(l)
10370 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10371 (delq nil (append a b)))))
10373 (defvar org--links-history nil)
10374 (defun org-insert-link (&optional complete-file link-location default-description)
10375 "Insert a link. At the prompt, enter the link.
10377 Completion can be used to insert any of the link protocol prefixes like
10378 http or ftp in use.
10380 The history can be used to select a link previously stored with
10381 `org-store-link'. When the empty string is entered (i.e. if you just
10382 press RET at the prompt), the link defaults to the most recently
10383 stored link. As SPC triggers completion in the minibuffer, you need to
10384 use M-SPC or C-q SPC to force the insertion of a space character.
10386 You will also be prompted for a description, and if one is given, it will
10387 be displayed in the buffer instead of the link.
10389 If there is already a link at point, this command will allow you to edit link
10390 and description parts.
10392 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10393 be selected using completion. The path to the file will be relative to the
10394 current directory if the file is in the current directory or a subdirectory.
10395 Otherwise, the link will be the absolute path as completed in the minibuffer
10396 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10397 option `org-link-file-path-type'.
10399 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10400 the current directory or below.
10402 With three \\[universal-argument] prefixes, negate the meaning of
10403 `org-keep-stored-link-after-insertion'.
10405 If `org-make-link-description-function' is non-nil, this function will be
10406 called with the link target, and the result will be the default
10407 link description.
10409 If the LINK-LOCATION parameter is non-nil, this value will be
10410 used as the link location instead of reading one interactively.
10412 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10413 be used as the default description."
10414 (interactive "P")
10415 (let* ((wcf (current-window-configuration))
10416 (origbuf (current-buffer))
10417 (region (when (org-region-active-p)
10418 (buffer-substring (region-beginning) (region-end))))
10419 (remove (and region (list (region-beginning) (region-end))))
10420 (desc region)
10421 (link link-location)
10422 (abbrevs org-link-abbrev-alist-local)
10423 entry all-prefixes auto-desc)
10424 (cond
10425 (link-location) ; specified by arg, just use it.
10426 ((org-in-regexp org-bracket-link-regexp 1)
10427 ;; We do have a link at point, and we are going to edit it.
10428 (setq remove (list (match-beginning 0) (match-end 0)))
10429 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10430 (setq link (read-string "Link: "
10431 (org-link-unescape
10432 (match-string-no-properties 1)))))
10433 ((or (org-in-regexp org-angle-link-re)
10434 (org-in-regexp org-plain-link-re))
10435 ;; Convert to bracket link
10436 (setq remove (list (match-beginning 0) (match-end 0))
10437 link (read-string "Link: "
10438 (org-remove-angle-brackets (match-string 0)))))
10439 ((member complete-file '((4) (16)))
10440 ;; Completing read for file names.
10441 (setq link (org-file-complete-link complete-file)))
10443 ;; Read link, with completion for stored links.
10444 (org-link-fontify-links-to-this-file)
10445 (org-switch-to-buffer-other-window "*Org Links*")
10446 (with-current-buffer "*Org Links*"
10447 (erase-buffer)
10448 (insert "Insert a link.
10449 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10450 (when org-stored-links
10451 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10452 (insert (mapconcat 'org-link-prettify
10453 (reverse org-stored-links) "\n")))
10454 (goto-char (point-min)))
10455 (let ((cw (selected-window)))
10456 (select-window (get-buffer-window "*Org Links*" 'visible))
10457 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10458 (unless (pos-visible-in-window-p (point-max))
10459 (org-fit-window-to-buffer))
10460 (and (window-live-p cw) (select-window cw)))
10461 (setq all-prefixes (append (mapcar 'car abbrevs)
10462 (mapcar 'car org-link-abbrev-alist)
10463 (org-link-types)))
10464 (unwind-protect
10465 ;; Fake a link history, containing the stored links.
10466 (let ((org--links-history
10467 (append (mapcar #'car org-stored-links)
10468 org-insert-link-history)))
10469 (setq link
10470 (org-completing-read
10471 "Link: "
10472 (append
10473 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10474 (mapcar #'car org-stored-links))
10475 nil nil nil
10476 'org--links-history
10477 (caar org-stored-links)))
10478 (unless (org-string-nw-p link) (user-error "No link selected"))
10479 (dolist (l org-stored-links)
10480 (when (equal link (cadr l))
10481 (setq link (car l))
10482 (setq auto-desc t)))
10483 (when (or (member link all-prefixes)
10484 (and (equal ":" (substring link -1))
10485 (member (substring link 0 -1) all-prefixes)
10486 (setq link (substring link 0 -1))))
10487 (setq link (with-current-buffer origbuf
10488 (org-link-try-special-completion link)))))
10489 (set-window-configuration wcf)
10490 (kill-buffer "*Org Links*"))
10491 (setq entry (assoc link org-stored-links))
10492 (or entry (push link org-insert-link-history))
10493 (setq desc (or desc (nth 1 entry)))))
10495 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10496 (not org-keep-stored-link-after-insertion))
10497 (setq org-stored-links (delq (assoc link org-stored-links)
10498 org-stored-links)))
10500 (when (and (string-match org-plain-link-re link)
10501 (not (string-match org-ts-regexp link)))
10502 ;; URL-like link, normalize the use of angular brackets.
10503 (setq link (org-remove-angle-brackets link)))
10505 ;; Check if we are linking to the current file with a search
10506 ;; option If yes, simplify the link by using only the search
10507 ;; option.
10508 (when (and buffer-file-name
10509 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10510 (let* ((path (match-string 1 link))
10511 (case-fold-search nil)
10512 (search (match-string 2 link)))
10513 (save-match-data
10514 (when (equal (file-truename buffer-file-name) (file-truename path))
10515 ;; We are linking to this same file, with a search option
10516 (setq link search)))))
10518 ;; Check if we can/should use a relative path. If yes, simplify the link
10519 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10520 (let* ((type (match-string 1 link))
10521 (path (match-string 2 link))
10522 (origpath path)
10523 (case-fold-search nil))
10524 (cond
10525 ((or (eq org-link-file-path-type 'absolute)
10526 (equal complete-file '(16)))
10527 (setq path (abbreviate-file-name (expand-file-name path))))
10528 ((eq org-link-file-path-type 'noabbrev)
10529 (setq path (expand-file-name path)))
10530 ((eq org-link-file-path-type 'relative)
10531 (setq path (file-relative-name path)))
10533 (save-match-data
10534 (if (string-match (concat "^" (regexp-quote
10535 (expand-file-name
10536 (file-name-as-directory
10537 default-directory))))
10538 (expand-file-name path))
10539 ;; We are linking a file with relative path name.
10540 (setq path (substring (expand-file-name path)
10541 (match-end 0)))
10542 (setq path (abbreviate-file-name (expand-file-name path)))))))
10543 (setq link (concat type path))
10544 (when (equal desc origpath)
10545 (setq desc path))))
10547 (if org-make-link-description-function
10548 (setq desc
10549 (or (condition-case nil
10550 (funcall org-make-link-description-function link desc)
10551 (error (progn (message "Can't get link description from `%s'"
10552 (symbol-name org-make-link-description-function))
10553 (sit-for 2) nil)))
10554 (read-string "Description: " default-description)))
10555 (if default-description (setq desc default-description)
10556 (setq desc (or (and auto-desc desc)
10557 (read-string "Description: " desc)))))
10559 (unless (string-match "\\S-" desc) (setq desc nil))
10560 (when remove (apply 'delete-region remove))
10561 (insert (org-make-link-string link desc))
10562 ;; Redisplay so as the new link has proper invisible characters.
10563 (sit-for 0)))
10565 (defun org-link-try-special-completion (type)
10566 "If there is completion support for link type TYPE, offer it."
10567 (let ((fun (org-link-get-parameter type :complete)))
10568 (if (functionp fun)
10569 (funcall fun)
10570 (read-string "Link (no completion support): " (concat type ":")))))
10572 (defun org-file-complete-link (&optional arg)
10573 "Create a file link using completion."
10574 (let ((file (read-file-name "File: "))
10575 (pwd (file-name-as-directory (expand-file-name ".")))
10576 (pwd1 (file-name-as-directory (abbreviate-file-name
10577 (expand-file-name ".")))))
10578 (cond ((equal arg '(16))
10579 (concat "file:"
10580 (abbreviate-file-name (expand-file-name file))))
10581 ((string-match
10582 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10583 (concat "file:" (match-string 1 file)))
10584 ((string-match
10585 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10586 (expand-file-name file))
10587 (concat "file:"
10588 (match-string 1 (expand-file-name file))))
10589 (t (concat "file:" file)))))
10591 (defun org-completing-read (&rest args)
10592 "Completing-read with SPACE being a normal character."
10593 (let ((enable-recursive-minibuffers t)
10594 (minibuffer-local-completion-map
10595 (copy-keymap minibuffer-local-completion-map)))
10596 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10597 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10598 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10599 'org-time-stamp-inactive)
10600 (apply #'completing-read args)))
10602 ;;; Opening/following a link
10604 (defvar org-link-search-failed nil)
10606 (defvar org-open-link-functions nil
10607 "Hook for functions finding a plain text link.
10608 These functions must take a single argument, the link content.
10609 They will be called for links that look like [[link text][description]]
10610 when LINK TEXT does not have a protocol like \"http:\" and does not look
10611 like a filename (e.g. \"./blue.png\").
10613 These functions will be called *before* Org attempts to resolve the
10614 link by doing text searches in the current buffer - so if you want a
10615 link \"[[target]]\" to still find \"<<target>>\", your function should
10616 handle this as a special case.
10618 When the function does handle the link, it must return a non-nil value.
10619 If it decides that it is not responsible for this link, it must return
10620 nil to indicate that that Org-mode can continue with other options
10621 like exact and fuzzy text search.")
10623 (defun org-next-link (&optional search-backward)
10624 "Move forward to the next link.
10625 If the link is in hidden text, expose it."
10626 (interactive "P")
10627 (when (and org-link-search-failed (eq this-command last-command))
10628 (goto-char (point-min))
10629 (message "Link search wrapped back to beginning of buffer"))
10630 (setq org-link-search-failed nil)
10631 (let* ((pos (point))
10632 (ct (org-context))
10633 (a (assoc :link ct))
10634 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10635 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10636 ((looking-at org-any-link-re)
10637 ;; Don't stay stuck at link without an org-link face
10638 (forward-char (if search-backward -1 1))))
10639 (if (funcall srch-fun org-any-link-re nil t)
10640 (progn
10641 (goto-char (match-beginning 0))
10642 (when (outline-invisible-p) (org-show-context)))
10643 (goto-char pos)
10644 (setq org-link-search-failed t)
10645 (message "No further link found"))))
10647 (defun org-previous-link ()
10648 "Move backward to the previous link.
10649 If the link is in hidden text, expose it."
10650 (interactive)
10651 (funcall 'org-next-link t))
10653 (defun org-translate-link (s)
10654 "Translate a link string if a translation function has been defined."
10655 (with-temp-buffer
10656 (insert (org-trim s))
10657 (org-trim (org-element-interpret-data (org-element-context)))))
10659 (defun org-translate-link-from-planner (type path)
10660 "Translate a link from Emacs Planner syntax so that Org can follow it.
10661 This is still an experimental function, your mileage may vary."
10662 (cond
10663 ((member type '("http" "https" "news" "ftp"))
10664 ;; standard Internet links are the same.
10665 nil)
10666 ((and (equal type "irc") (string-match "^//" path))
10667 ;; Planner has two / at the beginning of an irc link, we have 1.
10668 ;; We should have zero, actually....
10669 (setq path (substring path 1)))
10670 ((and (equal type "lisp") (string-match "^/" path))
10671 ;; Planner has a slash, we do not.
10672 (setq type "elisp" path (substring path 1)))
10673 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10674 ;; A typical message link. Planner has the id after the final slash,
10675 ;; we separate it with a hash mark
10676 (setq path (concat (match-string 1 path) "#"
10677 (org-remove-angle-brackets (match-string 2 path))))))
10678 (cons type path))
10680 (defun org-find-file-at-mouse (ev)
10681 "Open file link or URL at mouse."
10682 (interactive "e")
10683 (mouse-set-point ev)
10684 (org-open-at-point 'in-emacs))
10686 (defun org-open-at-mouse (ev)
10687 "Open file link or URL at mouse.
10688 See the docstring of `org-open-file' for details."
10689 (interactive "e")
10690 (mouse-set-point ev)
10691 (when (eq major-mode 'org-agenda-mode)
10692 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10693 (org-open-at-point))
10695 (defvar org-window-config-before-follow-link nil
10696 "The window configuration before following a link.
10697 This is saved in case the need arises to restore it.")
10699 ;;;###autoload
10700 (defun org-open-at-point-global ()
10701 "Follow a link or time-stamp like Org mode does.
10702 This command can be called in any mode to follow an external link
10703 or a time-stamp that has Org mode syntax. Its behavior is
10704 undefined when called on internal links (e.g., fuzzy links).
10705 Raise an error when there is nothing to follow. "
10706 (interactive)
10707 (cond ((org-in-regexp org-any-link-re)
10708 (org-open-link-from-string (match-string-no-properties 0)))
10709 ((or (org-in-regexp org-ts-regexp-both nil t)
10710 (org-in-regexp org-tsr-regexp-both nil t))
10711 (org-follow-timestamp-link))
10712 (t (user-error "No link found"))))
10714 ;;;###autoload
10715 (defun org-open-link-from-string (s &optional arg reference-buffer)
10716 "Open a link in the string S, as if it was in Org-mode."
10717 (interactive "sLink: \nP")
10718 (let ((reference-buffer (or reference-buffer (current-buffer))))
10719 (with-temp-buffer
10720 (let ((org-inhibit-startup (not reference-buffer)))
10721 (org-mode)
10722 (insert s)
10723 (goto-char (point-min))
10724 (when reference-buffer
10725 (setq org-link-abbrev-alist-local
10726 (with-current-buffer reference-buffer
10727 org-link-abbrev-alist-local)))
10728 (org-open-at-point arg reference-buffer)))))
10730 (defvar org-open-at-point-functions nil
10731 "Hook that is run when following a link at point.
10733 Functions in this hook must return t if they identify and follow
10734 a link at point. If they don't find anything interesting at point,
10735 they must return nil.")
10737 (defvar org-link-search-inhibit-query nil)
10738 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10739 (defun org--open-doi-link (path)
10740 "Open a \"doi\" type link.
10741 PATH is a the path to search for, as a string."
10742 (browse-url (url-encode-url (concat org-doi-server-url path))))
10744 (defun org--open-elisp-link (path)
10745 "Open a \"elisp\" type link.
10746 PATH is the sexp to evaluate, as a string."
10747 (let ((cmd path))
10748 (if (or (and (org-string-nw-p
10749 org-confirm-elisp-link-not-regexp)
10750 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10751 (not org-confirm-elisp-link-function)
10752 (funcall org-confirm-elisp-link-function
10753 (format "Execute \"%s\" as elisp? "
10754 (org-add-props cmd nil 'face 'org-warning))))
10755 (message "%s => %s" cmd
10756 (if (eq (string-to-char cmd) ?\()
10757 (eval (read cmd))
10758 (call-interactively (read cmd))))
10759 (user-error "Abort"))))
10761 (defun org--open-help-link (path)
10762 "Open a \"help\" type link.
10763 PATH is a symbol name, as a string."
10764 (pcase (intern path)
10765 ((and (pred fboundp) variable) (describe-function variable))
10766 ((and (pred boundp) function) (describe-variable function))
10767 (name (user-error "Unknown function or variable: %s" name))))
10769 (defun org--open-shell-link (path)
10770 "Open a \"shell\" type link.
10771 PATH is the command to execute, as a string."
10772 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10773 (cmd path))
10774 (if (or (and (org-string-nw-p
10775 org-confirm-shell-link-not-regexp)
10776 (string-match
10777 org-confirm-shell-link-not-regexp cmd))
10778 (not org-confirm-shell-link-function)
10779 (funcall org-confirm-shell-link-function
10780 (format "Execute \"%s\" in shell? "
10781 (org-add-props cmd nil
10782 'face 'org-warning))))
10783 (progn
10784 (message "Executing %s" cmd)
10785 (shell-command cmd buf)
10786 (when (featurep 'midnight)
10787 (setq clean-buffer-list-kill-buffer-names
10788 (cons (buffer-name buf)
10789 clean-buffer-list-kill-buffer-names))))
10790 (user-error "Abort"))))
10792 (defun org-open-at-point (&optional arg reference-buffer)
10793 "Open link, timestamp, footnote or tags at point.
10795 When point is on a link, follow it. Normally, files will be
10796 opened by an appropriate application. If the optional prefix
10797 argument ARG is non-nil, Emacs will visit the file. With
10798 a double prefix argument, try to open outside of Emacs, in the
10799 application the system uses for this file type.
10801 When point is on a timestamp, open the agenda at the day
10802 specified.
10804 When point is a footnote definition, move to the first reference
10805 found. If it is on a reference, move to the associated
10806 definition.
10808 When point is on a headline, display a list of every link in the
10809 entry, so it is possible to pick one, or all, of them. If point
10810 is on a tag, call `org-tags-view' instead.
10812 When optional argument REFERENCE-BUFFER is non-nil, it should
10813 specify a buffer from where the link search should happen. This
10814 is used internally by `org-open-link-from-string'.
10816 On top of syntactically correct links, this function will open
10817 the link at point in comments or comment blocks and the first
10818 link in a property drawer line."
10819 (interactive "P")
10820 ;; On a code block, open block's results.
10821 (unless (call-interactively 'org-babel-open-src-block-result)
10822 (org-load-modules-maybe)
10823 (setq org-window-config-before-follow-link (current-window-configuration))
10824 (org-remove-occur-highlights nil nil t)
10825 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10826 (let* ((context
10827 ;; Only consider supported types, even if they are not
10828 ;; the closest one.
10829 (org-element-lineage
10830 (org-element-context)
10831 '(clock comment comment-block footnote-definition
10832 footnote-reference headline inlinetask keyword link
10833 node-property timestamp)
10835 (type (org-element-type context))
10836 (value (org-element-property :value context)))
10837 (cond
10838 ((not context) (user-error "No link found"))
10839 ;; Exception: open timestamps and links in properties
10840 ;; drawers, keywords and comments.
10841 ((memq type '(comment comment-block keyword node-property))
10842 (call-interactively #'org-open-at-point-global))
10843 ;; On a headline or an inlinetask, but not on a timestamp,
10844 ;; a link, a footnote reference or on tags.
10845 ((and (memq type '(headline inlinetask))
10846 ;; Not on tags.
10847 (progn (save-excursion (beginning-of-line)
10848 (looking-at org-complex-heading-regexp))
10849 (or (not (match-beginning 5))
10850 (< (point) (match-beginning 5)))))
10851 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10852 (links (car data))
10853 (links-end (cdr data)))
10854 (if links
10855 (dolist (link (if (stringp links) (list links) links))
10856 (search-forward link nil links-end)
10857 (goto-char (match-beginning 0))
10858 (org-open-at-point))
10859 (require 'org-attach)
10860 (org-attach-reveal 'if-exists))))
10861 ;; On a clock line, make sure point is on the timestamp
10862 ;; before opening it.
10863 ((and (eq type 'clock)
10864 value
10865 (>= (point) (org-element-property :begin value))
10866 (<= (point) (org-element-property :end value)))
10867 (org-follow-timestamp-link))
10868 ;; Do nothing on white spaces after an object.
10869 ((>= (point)
10870 (save-excursion
10871 (goto-char (org-element-property :end context))
10872 (skip-chars-backward " \t")
10873 (point)))
10874 (user-error "No link found"))
10875 ((eq type 'timestamp) (org-follow-timestamp-link))
10876 ;; On tags within a headline or an inlinetask.
10877 ((and (memq type '(headline inlinetask))
10878 (progn (save-excursion (beginning-of-line)
10879 (looking-at org-complex-heading-regexp))
10880 (and (match-beginning 5)
10881 (>= (point) (match-beginning 5)))))
10882 (org-tags-view arg (substring (match-string 5) 0 -1)))
10883 ((eq type 'link)
10884 ;; When link is located within the description of another
10885 ;; link (e.g., an inline image), always open the parent
10886 ;; link.
10887 (let* ((link (let ((up (org-element-property :parent context)))
10888 (if (eq (org-element-type up) 'link) up context)))
10889 (type (org-element-property :type link))
10890 (path (org-link-unescape (org-element-property :path link))))
10891 ;; Switch back to REFERENCE-BUFFER needed when called in
10892 ;; a temporary buffer through `org-open-link-from-string'.
10893 (with-current-buffer (or reference-buffer (current-buffer))
10894 (cond
10895 ((equal type "file")
10896 (if (string-match "[*?{]" (file-name-nondirectory path))
10897 (dired path)
10898 ;; Look into `org-link-parameters' in order to find
10899 ;; a DEDICATED-FUNCTION to open file. The function
10900 ;; will be applied on raw link instead of parsed
10901 ;; link due to the limitation in `org-add-link-type'
10902 ;; ("open" function called with a single argument).
10903 ;; If no such function is found, fallback to
10904 ;; `org-open-file'.
10905 (let* ((option (org-element-property :search-option link))
10906 (app (org-element-property :application link))
10907 (dedicated-function
10908 (org-link-get-parameter
10909 (if app (concat type "+" app) type)
10910 :follow)))
10911 (if dedicated-function
10912 (funcall dedicated-function
10913 (concat path
10914 (and option (concat "::" option))))
10915 (apply #'org-open-file
10916 path
10917 (cond (arg)
10918 ((equal app "emacs") 'emacs)
10919 ((equal app "sys") 'system))
10920 (cond ((not option) nil)
10921 ((string-match-p "\\`[0-9]+\\'" option)
10922 (list (string-to-number option)))
10923 (t (list nil
10924 (org-link-unescape option)))))))))
10925 ((functionp (org-link-get-parameter type :follow))
10926 (funcall (org-link-get-parameter type :follow) path))
10927 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10928 (unless (run-hook-with-args-until-success
10929 'org-open-link-functions path)
10930 (if (not arg) (org-mark-ring-push)
10931 (switch-to-buffer-other-window
10932 (org-get-buffer-for-internal-link (current-buffer))))
10933 (let ((destination
10934 (org-with-wide-buffer
10935 (if (equal type "radio")
10936 (org-search-radio-target
10937 (org-element-property :path link))
10938 (org-link-search
10939 (if (member type '("custom-id" "coderef"))
10940 (org-element-property :raw-link link)
10941 path)
10942 ;; Prevent fuzzy links from matching
10943 ;; themselves.
10944 (and (equal type "fuzzy")
10945 (+ 2 (org-element-property :begin link)))))
10946 (point))))
10947 (unless (and (<= (point-min) destination)
10948 (>= (point-max) destination))
10949 (widen))
10950 (goto-char destination))))
10951 (t (browse-url-at-point))))))
10952 ;; On a footnote reference or at a footnote definition's label.
10953 ((or (eq type 'footnote-reference)
10954 (and (eq type 'footnote-definition)
10955 (save-excursion
10956 ;; Do not validate action when point is on the
10957 ;; spaces right after the footnote label, in
10958 ;; order to be on par with behaviour on links.
10959 (skip-chars-forward " \t")
10960 (let ((begin
10961 (org-element-property :contents-begin context)))
10962 (if begin (< (point) begin)
10963 (= (org-element-property :post-affiliated context)
10964 (line-beginning-position)))))))
10965 (org-footnote-action))
10966 (t (user-error "No link found")))))
10967 (run-hook-with-args 'org-follow-link-hook)))
10969 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10970 "Offer links in the current entry and return the selected link.
10971 If there is only one link, return it.
10972 If NTH is an integer, return the NTH link found.
10973 If ZERO is a string, check also this string for a link, and if
10974 there is one, return it."
10975 (with-current-buffer buffer
10976 (save-excursion
10977 (save-restriction
10978 (widen)
10979 (goto-char marker)
10980 (let ((cnt ?0)
10981 have-zero end links link c)
10982 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10983 (push (match-string 0 zero) links)
10984 (setq cnt (1- cnt) have-zero t))
10985 (save-excursion
10986 (org-back-to-heading t)
10987 (setq end (save-excursion (outline-next-heading) (point)))
10988 (while (re-search-forward org-any-link-re end t)
10989 (push (match-string 0) links))
10990 (setq links (org-uniquify (reverse links))))
10991 (cond
10992 ((null links)
10993 (message "No links"))
10994 ((equal (length links) 1)
10995 (setq link (car links)))
10996 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10997 (setq link (nth (if have-zero nth (1- nth)) links)))
10998 (t ; we have to select a link
10999 (save-excursion
11000 (save-window-excursion
11001 (delete-other-windows)
11002 (with-output-to-temp-buffer "*Select Link*"
11003 (dolist (l links)
11004 (cond
11005 ((not (string-match org-bracket-link-regexp l))
11006 (princ (format "[%c] %s\n" (cl-incf cnt)
11007 (org-remove-angle-brackets l))))
11008 ((match-end 3)
11009 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11010 (match-string 3 l) (match-string 1 l))))
11011 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11012 (match-string 1 l)))))))
11013 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11014 (message "Select link to open, RET to open all:")
11015 (setq c (read-char-exclusive))
11016 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11017 (when (equal c ?q) (user-error "Abort"))
11018 (if (equal c ?\C-m)
11019 (setq link links)
11020 (setq nth (- c ?0))
11021 (when have-zero (setq nth (1+ nth)))
11022 (unless (and (integerp nth) (>= (length links) nth))
11023 (user-error "Invalid link selection"))
11024 (setq link (nth (1- nth) links)))))
11025 (cons link end))))))
11027 ;; TODO: These functions are deprecated since `org-open-at-point'
11028 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11029 (defun org-open-file-with-system (path)
11030 "Open file at PATH using the system way of opening it."
11031 (org-open-file path 'system))
11032 (defun org-open-file-with-emacs (path)
11033 "Open file at PATH in Emacs."
11034 (org-open-file path 'emacs))
11037 ;;; File search
11039 (defvar org-create-file-search-functions nil
11040 "List of functions to construct the right search string for a file link.
11041 These functions are called in turn with point at the location to
11042 which the link should point.
11044 A function in the hook should first test if it would like to
11045 handle this file type, for example by checking the `major-mode'
11046 or the file extension. If it decides not to handle this file, it
11047 should just return nil to give other functions a chance. If it
11048 does handle the file, it must return the search string to be used
11049 when following the link. The search string will be part of the
11050 file link, given after a double colon, and `org-open-at-point'
11051 will automatically search for it. If special measures must be
11052 taken to make the search successful, another function should be
11053 added to the companion hook `org-execute-file-search-functions',
11054 which see.
11056 A function in this hook may also use `setq' to set the variable
11057 `description' to provide a suggestion for the descriptive text to
11058 be used for this link when it gets inserted into an Org-mode
11059 buffer with \\[org-insert-link].")
11061 (defvar org-execute-file-search-functions nil
11062 "List of functions to execute a file search triggered by a link.
11064 Functions added to this hook must accept a single argument, the
11065 search string that was part of the file link, the part after the
11066 double colon. The function must first check if it would like to
11067 handle this search, for example by checking the `major-mode' or
11068 the file extension. If it decides not to handle this search, it
11069 should just return nil to give other functions a chance. If it
11070 does handle the search, it must return a non-nil value to keep
11071 other functions from trying.
11073 Each function can access the current prefix argument through the
11074 variable `current-prefix-arg'. Note that a single prefix is used
11075 to force opening a link in Emacs, so it may be good to only use a
11076 numeric or double prefix to guide the search function.
11078 In case this is needed, a function in this hook can also restore
11079 the window configuration before `org-open-at-point' was called using:
11081 \(set-window-configuration org-window-config-before-follow-link)")
11083 (defun org-search-radio-target (target)
11084 "Search a radio target matching TARGET in current buffer.
11085 White spaces are not significant."
11086 (let ((re (format "<<<%s>>>"
11087 (mapconcat #'regexp-quote
11088 (org-split-string target "[ \t\n]+")
11089 "[ \t]+\\(?:\n[ \t]*\\)?")))
11090 (origin (point)))
11091 (goto-char (point-min))
11092 (catch :radio-match
11093 (while (re-search-forward re nil t)
11094 (backward-char)
11095 (let ((object (org-element-context)))
11096 (when (eq (org-element-type object) 'radio-target)
11097 (goto-char (org-element-property :begin object))
11098 (org-show-context 'link-search)
11099 (throw :radio-match nil))))
11100 (goto-char origin)
11101 (user-error "No match for radio target: %s" target))))
11103 (defun org-link-search (s &optional avoid-pos stealth)
11104 "Search for a search string S.
11106 If S starts with \"#\", it triggers a custom ID search.
11108 If S is enclosed within parenthesis, it initiates a coderef
11109 search.
11111 If S is surrounded by forward slashes, it is interpreted as
11112 a regular expression. In Org mode files, this will create an
11113 `org-occur' sparse tree. In ordinary files, `occur' will be used
11114 to list matches. If the current buffer is in `dired-mode', grep
11115 will be used to search in all files.
11117 When AVOID-POS is given, ignore matches near that position.
11119 When optional argument STEALTH is non-nil, do not modify
11120 visibility around point, thus ignoring `org-show-context-detail'
11121 variable.
11123 Search is case-insensitive and ignores white spaces. Return type
11124 of matched result, with is either `dedicated' or `fuzzy'."
11125 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11126 (let* ((case-fold-search t)
11127 (origin (point))
11128 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11129 (words (org-split-string s "[ \t\n]+"))
11130 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11131 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11132 type)
11133 (cond
11134 ;; Check if there are any special search functions.
11135 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11136 ((eq (string-to-char s) ?#)
11137 ;; Look for a custom ID S if S starts with "#".
11138 (let* ((id (substring normalized 1))
11139 (match (org-find-property "CUSTOM_ID" id)))
11140 (if match (progn (goto-char match) (setf type 'dedicated))
11141 (error "No match for custom ID: %s" id))))
11142 ((string-match "\\`(\\(.*\\))\\'" normalized)
11143 ;; Look for coderef targets if S is enclosed within parenthesis.
11144 (let ((coderef (match-string-no-properties 1 normalized))
11145 (re (substring s-single-re 1 -1)))
11146 (goto-char (point-min))
11147 (catch :coderef-match
11148 (while (re-search-forward re nil t)
11149 (let ((element (org-element-at-point)))
11150 (when (and (memq (org-element-type element)
11151 '(example-block src-block))
11152 ;; Build proper regexp according to current
11153 ;; block's label format.
11154 (let ((label-fmt
11155 (regexp-quote
11156 (or (org-element-property :label-fmt element)
11157 org-coderef-label-format))))
11158 (save-excursion
11159 (beginning-of-line)
11160 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11161 (format label-fmt coderef))))))
11162 (setq type 'dedicated)
11163 (goto-char (match-beginning 1))
11164 (throw :coderef-match nil))))
11165 (goto-char origin)
11166 (error "No match for coderef: %s" coderef))))
11167 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11168 ;; Look for a regular expression.
11169 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11170 (match-string 1 s)))
11171 ;; Fuzzy links.
11173 (let ((starred (eq (string-to-char normalized) ?*)))
11174 (cond
11175 ;; Look for targets, only if not in a headline search.
11176 ((and (not starred)
11177 (let ((target (format "<<%s>>" s-multi-re)))
11178 (catch :target-match
11179 (goto-char (point-min))
11180 (while (re-search-forward target nil t)
11181 (backward-char)
11182 (let ((context (org-element-context)))
11183 (when (eq (org-element-type context) 'target)
11184 (setq type 'dedicated)
11185 (goto-char (org-element-property :begin context))
11186 (throw :target-match t))))
11187 nil))))
11188 ;; Look for elements named after S, only if not in a headline
11189 ;; search.
11190 ((and (not starred)
11191 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11192 (catch :name-match
11193 (goto-char (point-min))
11194 (while (re-search-forward name nil t)
11195 (let ((element (org-element-at-point)))
11196 (when (equal (org-split-string
11197 (org-element-property :name element)
11198 "[ \t]+")
11199 words)
11200 (setq type 'dedicated)
11201 (beginning-of-line)
11202 (throw :name-match t))))
11203 nil))))
11204 ;; Regular text search. Prefer headlines in Org mode
11205 ;; buffers.
11206 ((and (derived-mode-p 'org-mode)
11207 (let* ((wspace "[ \t]")
11208 (wspaceopt (concat wspace "*"))
11209 (cookie (concat "\\(?:"
11210 wspaceopt
11211 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11212 wspaceopt
11213 "\\)"))
11214 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11215 (re (concat
11216 org-outline-regexp-bol
11217 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11218 "\\(?:\\[#.\\][ \t]+\\)?"
11219 "\\(?:" org-comment-string "[ \t]+\\)?"
11220 sep "?"
11221 (let ((title (mapconcat #'regexp-quote
11222 words
11223 sep)))
11224 (if starred (substring title 1) title))
11225 sep "?"
11226 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11227 "[ \t]*$")))
11228 (goto-char (point-min))
11229 (re-search-forward re nil t)))
11230 (goto-char (match-beginning 0))
11231 (setq type 'dedicated))
11232 ;; Offer to create non-existent headline depending on
11233 ;; `org-link-search-must-match-exact-headline'.
11234 ((and (derived-mode-p 'org-mode)
11235 (not org-link-search-inhibit-query)
11236 (eq org-link-search-must-match-exact-headline 'query-to-create)
11237 (yes-or-no-p "No match - create this as a new heading? "))
11238 (goto-char (point-max))
11239 (unless (bolp) (newline))
11240 (org-insert-heading nil t t)
11241 (insert s "\n")
11242 (beginning-of-line 0))
11243 ;; Only headlines are looked after. No need to process
11244 ;; further: throw an error.
11245 ((and (derived-mode-p 'org-mode)
11246 (or starred org-link-search-must-match-exact-headline))
11247 (goto-char origin)
11248 (error "No match for fuzzy expression: %s" normalized))
11249 ;; Regular text search.
11250 ((catch :fuzzy-match
11251 (goto-char (point-min))
11252 (while (re-search-forward s-multi-re nil t)
11253 ;; Skip match if it contains AVOID-POS or it is included
11254 ;; in a link with a description but outside the
11255 ;; description.
11256 (unless (or (and avoid-pos
11257 (<= (match-beginning 0) avoid-pos)
11258 (> (match-end 0) avoid-pos))
11259 (and (save-match-data
11260 (org-in-regexp org-bracket-link-regexp))
11261 (match-beginning 3)
11262 (or (> (match-beginning 3) (point))
11263 (<= (match-end 3) (point)))
11264 (org-element-lineage
11265 (save-match-data (org-element-context))
11266 '(link) t)))
11267 (goto-char (match-beginning 0))
11268 (setq type 'fuzzy)
11269 (throw :fuzzy-match t)))
11270 nil))
11271 ;; All failed. Throw an error.
11272 (t (goto-char origin)
11273 (error "No match for fuzzy expression: %s" normalized))))))
11274 ;; Disclose surroundings of match, if appropriate.
11275 (when (and (derived-mode-p 'org-mode) (not stealth))
11276 (org-show-context 'link-search))
11277 type))
11279 (defun org-get-buffer-for-internal-link (buffer)
11280 "Return a buffer to be used for displaying the link target of internal links."
11281 (cond
11282 ((not org-display-internal-link-with-indirect-buffer)
11283 buffer)
11284 ((string-match "(Clone)$" (buffer-name buffer))
11285 (message "Buffer is already a clone, not making another one")
11286 ;; we also do not modify visibility in this case
11287 buffer)
11288 (t ; make a new indirect buffer for displaying the link
11289 (let* ((bn (buffer-name buffer))
11290 (ibn (concat bn "(Clone)"))
11291 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11292 (with-current-buffer ib (org-overview))
11293 ib))))
11295 (defun org-do-occur (regexp &optional cleanup)
11296 "Call the Emacs command `occur'.
11297 If CLEANUP is non-nil, remove the printout of the regular expression
11298 in the *Occur* buffer. This is useful if the regex is long and not useful
11299 to read."
11300 (occur regexp)
11301 (when cleanup
11302 (let ((cwin (selected-window)) win beg end)
11303 (when (setq win (get-buffer-window "*Occur*"))
11304 (select-window win))
11305 (goto-char (point-min))
11306 (when (re-search-forward "match[a-z]+" nil t)
11307 (setq beg (match-end 0))
11308 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11309 (setq end (1- (match-beginning 0)))))
11310 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11311 (goto-char (point-min))
11312 (select-window cwin))))
11314 ;;; The mark ring for links jumps
11316 (defvar org-mark-ring nil
11317 "Mark ring for positions before jumps in Org-mode.")
11318 (defvar org-mark-ring-last-goto nil
11319 "Last position in the mark ring used to go back.")
11320 ;; Fill and close the ring
11321 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11322 (dotimes (_ org-mark-ring-length)
11323 (push (make-marker) org-mark-ring))
11324 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11325 org-mark-ring)
11327 (defun org-mark-ring-push (&optional pos buffer)
11328 "Put the current position or POS into the mark ring and rotate it."
11329 (interactive)
11330 (setq pos (or pos (point)))
11331 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11332 (move-marker (car org-mark-ring)
11333 (or pos (point))
11334 (or buffer (current-buffer)))
11335 (message "%s"
11336 (substitute-command-keys
11337 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11339 (defun org-mark-ring-goto (&optional n)
11340 "Jump to the previous position in the mark ring.
11341 With prefix arg N, jump back that many stored positions. When
11342 called several times in succession, walk through the entire ring.
11343 Org-mode commands jumping to a different position in the current file,
11344 or to another Org-mode file, automatically push the old position
11345 onto the ring."
11346 (interactive "p")
11347 (let (p m)
11348 (if (eq last-command this-command)
11349 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11350 (setq p org-mark-ring))
11351 (setq org-mark-ring-last-goto p)
11352 (setq m (car p))
11353 (pop-to-buffer-same-window (marker-buffer m))
11354 (goto-char m)
11355 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11357 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11358 ;;; Emacs 24.4+
11359 (defun org-remove-angle-brackets (s)
11360 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11361 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11363 (defun org-add-angle-brackets (s)
11364 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11365 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11367 (defun org-remove-double-quotes (s)
11368 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11369 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11372 ;;; Following specific links
11374 (defvar org-agenda-buffer-tmp-name)
11375 (defvar org-agenda-start-on-weekday)
11376 (defun org-follow-timestamp-link ()
11377 "Open an agenda view for the time-stamp date/range at point."
11378 (cond
11379 ((org-at-date-range-p t)
11380 (let ((org-agenda-start-on-weekday)
11381 (t1 (match-string 1))
11382 (t2 (match-string 2)) tt1 tt2)
11383 (setq tt1 (time-to-days (org-time-string-to-time t1))
11384 tt2 (time-to-days (org-time-string-to-time t2)))
11385 (let ((org-agenda-buffer-tmp-name
11386 (format "*Org Agenda(a:%s)"
11387 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11388 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11389 ((org-at-timestamp-p t)
11390 (let ((org-agenda-buffer-tmp-name
11391 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11392 (org-agenda-list nil (time-to-days (org-time-string-to-time
11393 (substring (match-string 1) 0 10)))
11394 1)))
11395 (t (error "This should not happen"))))
11398 ;;; Following file links
11399 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11400 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11401 (declare-function mailcap-mime-info
11402 "mailcap" (string &optional request no-decode))
11403 (defvar org-wait nil)
11404 (defun org-open-file (path &optional in-emacs line search)
11405 "Open the file at PATH.
11406 First, this expands any special file name abbreviations. Then the
11407 configuration variable `org-file-apps' is checked if it contains an
11408 entry for this file type, and if yes, the corresponding command is launched.
11410 If no application is found, Emacs simply visits the file.
11412 With optional prefix argument IN-EMACS, Emacs will visit the file.
11413 With a double \\[universal-argument] \\[universal-argument] \
11414 prefix arg, Org tries to avoid opening in Emacs
11415 and to use an external application to visit the file.
11417 Optional LINE specifies a line to go to, optional SEARCH a string
11418 to search for. If LINE or SEARCH is given, the file will be
11419 opened in Emacs, unless an entry from org-file-apps that makes
11420 use of groups in a regexp matches.
11422 If you want to change the way frames are used when following a
11423 link, please customize `org-link-frame-setup'.
11425 If the file does not exist, an error is thrown."
11426 (let* ((file (if (equal path "")
11427 buffer-file-name
11428 (substitute-in-file-name (expand-file-name path))))
11429 (file-apps (append org-file-apps (org-default-apps)))
11430 (apps (cl-remove-if
11431 'org-file-apps-entry-match-against-dlink-p file-apps))
11432 (apps-dlink (cl-remove-if-not
11433 'org-file-apps-entry-match-against-dlink-p file-apps))
11434 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11435 (dirp (unless remp (file-directory-p file)))
11436 (file (if (and dirp org-open-directory-means-index-dot-org)
11437 (concat (file-name-as-directory file) "index.org")
11438 file))
11439 (a-m-a-p (assq 'auto-mode apps))
11440 (dfile (downcase file))
11441 ;; Reconstruct the original link from the PATH, LINE and
11442 ;; SEARCH args.
11443 (link (cond (line (concat file "::" (number-to-string line)))
11444 (search (concat file "::" search))
11445 (t file)))
11446 (dlink (downcase link))
11447 (old-buffer (current-buffer))
11448 (old-pos (point))
11449 (old-mode major-mode)
11450 (ext
11451 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11452 (match-string 1 dfile)))
11453 cmd link-match-data)
11454 (cond
11455 ((member in-emacs '((16) system))
11456 (setq cmd (cdr (assq 'system apps))))
11457 (in-emacs (setq cmd 'emacs))
11459 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11460 (and dirp (cdr (assq 'directory apps)))
11461 ;; First, try matching against apps-dlink if we
11462 ;; get a match here, store the match data for
11463 ;; later.
11464 (let ((match (assoc-default dlink apps-dlink
11465 'string-match)))
11466 (if match
11467 (progn (setq link-match-data (match-data))
11468 match)
11469 (progn (setq in-emacs (or in-emacs line search))
11470 nil))) ; if we have no match in apps-dlink,
11471 ; always open the file in emacs if line or search
11472 ; is given (for backwards compatibility)
11473 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11474 'string-match)
11475 (cdr (assoc ext apps))
11476 (cdr (assq t apps))))))
11477 (when (eq cmd 'system)
11478 (setq cmd (cdr (assoc 'system apps))))
11479 (when (eq cmd 'default)
11480 (setq cmd (cdr (assoc t apps))))
11481 (when (eq cmd 'mailcap)
11482 (require 'mailcap)
11483 (mailcap-parse-mailcaps)
11484 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11485 (command (mailcap-mime-info mime-type)))
11486 (if (stringp command)
11487 (setq cmd command)
11488 (setq cmd 'emacs))))
11489 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11490 (not (file-exists-p file))
11491 (not org-open-non-existing-files))
11492 (user-error "No such file: %s" file))
11493 (cond
11494 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11495 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11496 (while (string-match "['\"]%s['\"]" cmd)
11497 (setq cmd (replace-match "%s" t t cmd)))
11498 (while (string-match "%s" cmd)
11499 (setq cmd (replace-match
11500 (save-match-data
11501 (shell-quote-argument
11502 (convert-standard-filename file)))
11503 t t cmd)))
11505 ;; Replace "%1", "%2" etc. in command with group matches from regex
11506 (save-match-data
11507 (let ((match-index 1)
11508 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11509 (set-match-data link-match-data)
11510 (while (<= match-index number-of-groups)
11511 (let ((regex (concat "%" (number-to-string match-index)))
11512 (replace-with (match-string match-index dlink)))
11513 (while (string-match regex cmd)
11514 (setq cmd (replace-match replace-with t t cmd))))
11515 (setq match-index (+ match-index 1)))))
11517 (save-window-excursion
11518 (message "Running %s...done" cmd)
11519 (start-process-shell-command cmd nil cmd)
11520 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11521 ((or (stringp cmd)
11522 (eq cmd 'emacs))
11523 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11524 (widen)
11525 (cond (line (org-goto-line line)
11526 (when (derived-mode-p 'org-mode) (org-reveal)))
11527 (search (org-link-search search))))
11528 ((functionp cmd)
11529 (save-match-data
11530 (set-match-data link-match-data)
11531 (condition-case nil
11532 (funcall cmd file link)
11533 ;; FIXME: Remove this check when most default installations
11534 ;; of Emacs have at least Org 9.0.
11535 ((debug wrong-number-of-arguments wrong-type-argument
11536 invalid-function)
11537 (user-error "Please see Org News for version 9.0 about \
11538 `org-file-apps'--Lisp error: %S" cmd)))))
11539 ((consp cmd)
11540 ;; FIXME: Remove this check when most default installations of
11541 ;; Emacs have at least Org 9.0.
11542 ;; Heads-up instead of silently fall back to
11543 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11544 ;; with sexp instead of a function for `cmd'.
11545 (user-error "Please see Org News for version 9.0 about \
11546 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11547 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11548 (and (derived-mode-p 'org-mode)
11549 (eq old-mode 'org-mode)
11550 (or (not (eq old-buffer (current-buffer)))
11551 (not (eq old-pos (point))))
11552 (org-mark-ring-push old-pos old-buffer))))
11554 (defun org-file-apps-entry-match-against-dlink-p (entry)
11555 "This function returns non-nil if `entry' uses a regular
11556 expression which should be matched against the whole link by
11557 org-open-file.
11559 It assumes that is the case when the entry uses a regular
11560 expression which has at least one grouping construct and the
11561 action is either a lisp form or a command string containing
11562 `%1', i.e. using at least one subexpression match as a
11563 parameter."
11564 (let ((selector (car entry))
11565 (action (cdr entry)))
11566 (if (stringp selector)
11567 (and (> (regexp-opt-depth selector) 0)
11568 (or (and (stringp action)
11569 (string-match "%[0-9]" action))
11570 (consp action)))
11571 nil)))
11573 (defun org-default-apps ()
11574 "Return the default applications for this operating system."
11575 (cond
11576 ((eq system-type 'darwin)
11577 org-file-apps-defaults-macosx)
11578 ((eq system-type 'windows-nt)
11579 org-file-apps-defaults-windowsnt)
11580 (t org-file-apps-defaults-gnu)))
11582 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11583 "Convert extensions to regular expressions in the cars of LIST.
11584 Also, weed out any non-string entries, because the return value is used
11585 only for regexp matching.
11586 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11587 point to the symbol `emacs', indicating that the file should
11588 be opened in Emacs."
11589 (append
11590 (delq nil
11591 (mapcar (lambda (x)
11592 (unless (not (stringp (car x)))
11593 (if (string-match "\\W" (car x))
11595 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11596 list))
11597 (when add-auto-mode
11598 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11600 (defvar ange-ftp-name-format)
11601 (defun org-file-remote-p (file)
11602 "Test whether FILE specifies a location on a remote system.
11603 Return non-nil if the location is indeed remote.
11605 For example, the filename \"/user@host:/foo\" specifies a location
11606 on the system \"/user@host:\"."
11607 (cond ((fboundp 'file-remote-p)
11608 (file-remote-p file))
11609 ((fboundp 'tramp-handle-file-remote-p)
11610 (tramp-handle-file-remote-p file))
11611 ((and (boundp 'ange-ftp-name-format)
11612 (string-match (car ange-ftp-name-format) file))
11613 t)))
11616 ;;;; Refiling
11618 (defun org-get-org-file ()
11619 "Read a filename, with default directory `org-directory'."
11620 (let ((default (or org-default-notes-file remember-data-file)))
11621 (read-file-name (format "File name [%s]: " default)
11622 (file-name-as-directory org-directory)
11623 default)))
11625 (defun org-notes-order-reversed-p ()
11626 "Check if the current file should receive notes in reversed order."
11627 (cond
11628 ((not org-reverse-note-order) nil)
11629 ((eq t org-reverse-note-order) t)
11630 ((not (listp org-reverse-note-order)) nil)
11631 (t (catch 'exit
11632 (dolist (entry org-reverse-note-order)
11633 (when (string-match (car entry) buffer-file-name)
11634 (throw 'exit (cdr entry))))))))
11636 (defvar org-refile-target-table nil
11637 "The list of refile targets, created by `org-refile'.")
11639 (defvar org-agenda-new-buffers nil
11640 "Buffers created to visit agenda files.")
11642 (defvar org-refile-cache nil
11643 "Cache for refile targets.")
11645 (defvar org-refile-markers nil
11646 "All the markers used for caching refile locations.")
11648 (defun org-refile-marker (pos)
11649 "Get a new refile marker, but only if caching is in use."
11650 (if (not org-refile-use-cache)
11652 (let ((m (make-marker)))
11653 (move-marker m pos)
11654 (push m org-refile-markers)
11655 m)))
11657 (defun org-refile-cache-clear ()
11658 "Clear the refile cache and disable all the markers."
11659 (dolist (m org-refile-markers) (move-marker m nil))
11660 (setq org-refile-markers nil)
11661 (setq org-refile-cache nil)
11662 (message "Refile cache has been cleared"))
11664 (defun org-refile-cache-check-set (set)
11665 "Check if all the markers in the cache still have live buffers."
11666 (let (marker)
11667 (catch 'exit
11668 (while (and set (setq marker (nth 3 (pop set))))
11669 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11670 (when (and marker (null (marker-buffer marker)))
11671 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11672 (sit-for 3)
11673 (throw 'exit nil)))
11674 t)))
11676 (defun org-refile-cache-put (set &rest identifiers)
11677 "Push the refile targets SET into the cache, under IDENTIFIERS."
11678 (let* ((key (sha1 (prin1-to-string identifiers)))
11679 (entry (assoc key org-refile-cache)))
11680 (if entry
11681 (setcdr entry set)
11682 (push (cons key set) org-refile-cache))))
11684 (defun org-refile-cache-get (&rest identifiers)
11685 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11686 (cond
11687 ((not org-refile-cache) nil)
11688 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11690 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11691 org-refile-cache))))
11692 (and set (org-refile-cache-check-set set) set)))))
11694 (defvar org-outline-path-cache nil
11695 "Alist between buffer positions and outline paths.
11696 It value is an alist (POSITION . PATH) where POSITION is the
11697 buffer position at the beginning of an entry and PATH is a list
11698 of strings describing the outline path for that entry, in reverse
11699 order.")
11701 (defun org-refile-get-targets (&optional default-buffer)
11702 "Produce a table with refile targets."
11703 (let ((case-fold-search nil)
11704 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11705 (entries (or org-refile-targets '((nil . (:level . 1)))))
11706 targets tgs files desc descre)
11707 (message "Getting targets...")
11708 (with-current-buffer (or default-buffer (current-buffer))
11709 (dolist (entry entries)
11710 (setq files (car entry) desc (cdr entry))
11711 (cond
11712 ((null files) (setq files (list (current-buffer))))
11713 ((eq files 'org-agenda-files)
11714 (setq files (org-agenda-files 'unrestricted)))
11715 ((and (symbolp files) (fboundp files))
11716 (setq files (funcall files)))
11717 ((and (symbolp files) (boundp files))
11718 (setq files (symbol-value files))))
11719 (when (stringp files) (setq files (list files)))
11720 (cond
11721 ((eq (car desc) :tag)
11722 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11723 ((eq (car desc) :todo)
11724 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11725 ((eq (car desc) :regexp)
11726 (setq descre (cdr desc)))
11727 ((eq (car desc) :level)
11728 (setq descre (concat "^\\*\\{" (number-to-string
11729 (if org-odd-levels-only
11730 (1- (* 2 (cdr desc)))
11731 (cdr desc)))
11732 "\\}[ \t]")))
11733 ((eq (car desc) :maxlevel)
11734 (setq descre (concat "^\\*\\{1," (number-to-string
11735 (if org-odd-levels-only
11736 (1- (* 2 (cdr desc)))
11737 (cdr desc)))
11738 "\\}[ \t]")))
11739 (t (error "Bad refiling target description %s" desc)))
11740 (dolist (f files)
11741 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11743 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11744 (progn
11745 (when (bufferp f)
11746 (setq f (buffer-file-name (buffer-base-buffer f))))
11747 (setq f (and f (expand-file-name f)))
11748 (when (eq org-refile-use-outline-path 'file)
11749 (push (list (file-name-nondirectory f) f nil nil) tgs))
11750 (org-with-wide-buffer
11751 (goto-char (point-min))
11752 (setq org-outline-path-cache nil)
11753 (while (re-search-forward descre nil t)
11754 (beginning-of-line)
11755 (looking-at org-complex-heading-regexp)
11756 (let ((begin (point))
11757 (heading (match-string-no-properties 4)))
11758 (unless (or (and
11759 org-refile-target-verify-function
11760 (not
11761 (funcall org-refile-target-verify-function)))
11762 (not heading))
11763 (let ((re (format org-complex-heading-regexp-format
11764 (regexp-quote heading)))
11765 (target
11766 (if (not org-refile-use-outline-path) heading
11767 (mapconcat
11768 #'org-protect-slash
11769 (append
11770 (pcase org-refile-use-outline-path
11771 (`file (list (file-name-nondirectory
11772 (buffer-file-name
11773 (buffer-base-buffer)))))
11774 (`full-file-path
11775 (list (buffer-file-name
11776 (buffer-base-buffer))))
11777 (_ nil))
11778 (org-get-outline-path t t))
11779 "/"))))
11780 (push (list target f re (org-refile-marker (point)))
11781 tgs)))
11782 (when (= (point) begin)
11783 ;; Verification function has not moved point.
11784 (end-of-line)))))))
11785 (when org-refile-use-cache
11786 (org-refile-cache-put tgs (buffer-file-name) descre))
11787 (setq targets (append tgs targets))))))
11788 (message "Getting targets...done")
11789 (nreverse targets)))
11791 (defun org-protect-slash (s)
11792 (while (string-match "/" s)
11793 (setq s (replace-match "\\" t t s)))
11796 (defun org--get-outline-path-1 (&optional use-cache)
11797 "Return outline path to current headline.
11799 Outline path is a list of strings, in reverse order. When
11800 optional argument USE-CACHE is non-nil, make use of a cache. See
11801 `org-get-outline-path' for details.
11803 Assume buffer is widened and point is on a headline."
11804 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11805 (let ((p (point))
11806 (heading (progn
11807 (looking-at org-complex-heading-regexp)
11808 (if (not (match-end 4)) ""
11809 ;; Remove statistics cookies.
11810 (org-trim
11811 (org-link-display-format
11812 (replace-regexp-in-string
11813 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11814 (match-string-no-properties 4))))))))
11815 (if (org-up-heading-safe)
11816 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11817 (when use-cache
11818 (push (cons p path) org-outline-path-cache))
11819 path)
11820 ;; This is a new root node. Since we assume we are moving
11821 ;; forward, we can drop previous cache so as to limit number
11822 ;; of associations there.
11823 (let ((path (list heading)))
11824 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11825 path)))))
11827 (defun org-get-outline-path (&optional with-self use-cache)
11828 "Return the outline path to the current entry.
11830 An outline path is a list of ancestors for current headline, as
11831 a list of strings. Statistics cookies are removed and links are
11832 replaced with their description, if any, or their path otherwise.
11834 When optional argument WITH-SELF is non-nil, the path also
11835 includes the current headline.
11837 When optional argument USE-CACHE is non-nil, cache outline paths
11838 between calls to this function so as to avoid backtracking. This
11839 argument is useful when planning to find more than one outline
11840 path in the same document. In that case, there are two
11841 conditions to satisfy:
11842 - `org-outline-path-cache' is set to nil before starting the
11843 process;
11844 - outline paths are computed by increasing buffer positions."
11845 (org-with-wide-buffer
11846 (and (or (and with-self (org-back-to-heading t))
11847 (org-up-heading-safe))
11848 (reverse (org--get-outline-path-1 use-cache)))))
11850 (defun org-format-outline-path (path &optional width prefix separator)
11851 "Format the outline path PATH for display.
11852 WIDTH is the maximum number of characters that is available.
11853 PREFIX is a prefix to be included in the returned string,
11854 such as the file name.
11855 SEPARATOR is inserted between the different parts of the path,
11856 the default is \"/\"."
11857 (setq width (or width 79))
11858 (setq path (delq nil path))
11859 (unless (> width 0)
11860 (user-error "Argument `width' must be positive"))
11861 (setq separator (or separator "/"))
11862 (let* ((org-odd-levels-only nil)
11863 (fpath (concat
11864 prefix (and prefix path separator)
11865 (mapconcat
11866 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11867 (cl-loop for head in path
11868 for n from 0
11869 collect (org-add-props
11870 head nil 'face
11871 (nth (% n org-n-level-faces) org-level-faces)))
11872 separator))))
11873 (when (> (length fpath) width)
11874 (if (< width 7)
11875 ;; It's unlikely that `width' will be this small, but don't
11876 ;; waste characters by adding ".." if it is.
11877 (setq fpath (substring fpath 0 width))
11878 (setf (substring fpath (- width 2)) "..")))
11879 fpath))
11881 (defun org-display-outline-path (&optional file current separator just-return-string)
11882 "Display the current outline path in the echo area.
11884 If FILE is non-nil, prepend the output with the file name.
11885 If CURRENT is non-nil, append the current heading to the output.
11886 SEPARATOR is passed through to `org-format-outline-path'. It separates
11887 the different parts of the path and defaults to \"/\".
11888 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11889 (interactive "P")
11890 (let* (case-fold-search
11891 (bfn (buffer-file-name (buffer-base-buffer)))
11892 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11893 res)
11894 (when current (setq path (append path
11895 (save-excursion
11896 (org-back-to-heading t)
11897 (when (looking-at org-complex-heading-regexp)
11898 (list (match-string 4)))))))
11899 (setq res
11900 (org-format-outline-path
11901 path
11902 (1- (frame-width))
11903 (and file bfn (concat (file-name-nondirectory bfn) separator))
11904 separator))
11905 (if just-return-string
11906 (org-no-properties res)
11907 (org-unlogged-message "%s" res))))
11909 (defvar org-refile-history nil
11910 "History for refiling operations.")
11912 (defvar org-after-refile-insert-hook nil
11913 "Hook run after `org-refile' has inserted its stuff at the new location.
11914 Note that this is still *before* the stuff will be removed from
11915 the *old* location.")
11917 (defvar org-capture-last-stored-marker)
11918 (defvar org-refile-keep nil
11919 "Non-nil means `org-refile' will copy instead of refile.")
11921 (defun org-copy ()
11922 "Like `org-refile', but copy."
11923 (interactive)
11924 (let ((org-refile-keep t))
11925 (funcall 'org-refile nil nil nil "Copy")))
11927 (defun org-refile (&optional arg default-buffer rfloc msg)
11928 "Move the entry or entries at point to another heading.
11929 The list of target headings is compiled using the information in
11930 `org-refile-targets', which see.
11932 At the target location, the entry is filed as a subitem of the
11933 target heading. Depending on `org-reverse-note-order', the new
11934 subitem will either be the first or the last subitem.
11936 If there is an active region, all entries in that region will be
11937 refiled. However, the region must fulfill the requirement that
11938 the first heading sets the top-level of the moved text.
11940 With prefix arg ARG, the command will only visit the target
11941 location and not actually move anything.
11943 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11944 refiling operation has put the subtree.
11946 With a numeric prefix argument of `2', refile to the running clock.
11948 With a numeric prefix argument of `3', emulate `org-refile-keep'
11949 being set to t and copy to the target location, don't move it.
11950 Beware that keeping refiled entries may result in duplicated ID
11951 properties.
11953 RFLOC can be a refile location obtained in a different way.
11955 MSG is a string to replace \"Refile\" in the default prompt with
11956 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11958 See also `org-refile-use-outline-path'.
11960 If you are using target caching (see `org-refile-use-cache'), you
11961 have to clear the target cache in order to find new targets.
11962 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11963 prefix argument (`C-u C-u C-u C-c C-w')."
11964 (interactive "P")
11965 (if (member arg '(0 (64)))
11966 (org-refile-cache-clear)
11967 (let* ((actionmsg (cond (msg msg)
11968 ((equal arg 3) "Refile (and keep)")
11969 (t "Refile")))
11970 (regionp (org-region-active-p))
11971 (region-start (and regionp (region-beginning)))
11972 (region-end (and regionp (region-end)))
11973 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11974 pos it nbuf file level reversed)
11975 (setq last-command nil)
11976 (when regionp
11977 (goto-char region-start)
11978 (or (bolp) (goto-char (point-at-bol)))
11979 (setq region-start (point))
11980 (unless (or (org-kill-is-subtree-p
11981 (buffer-substring region-start region-end))
11982 (prog1 org-refile-active-region-within-subtree
11983 (let ((s (point-at-eol)))
11984 (org-toggle-heading)
11985 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11986 (user-error "The region is not a (sequence of) subtree(s)")))
11987 (if (equal arg '(16))
11988 (org-refile-goto-last-stored)
11989 (when (or
11990 (and (equal arg 2)
11991 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11992 (prog1
11993 (setq it (list (or org-clock-heading "running clock")
11994 (buffer-file-name
11995 (marker-buffer org-clock-hd-marker))
11997 (marker-position org-clock-hd-marker)))
11998 (setq arg nil)))
11999 (setq it
12000 (or rfloc
12001 (let (heading-text)
12002 (save-excursion
12003 (unless (and arg (listp arg))
12004 (org-back-to-heading t)
12005 (setq heading-text
12006 (replace-regexp-in-string
12007 org-bracket-link-regexp
12008 "\\3"
12009 (or (nth 4 (org-heading-components))
12010 ""))))
12011 (org-refile-get-location
12012 (cond ((and arg (listp arg)) "Goto")
12013 (regionp (concat actionmsg " region to"))
12014 (t (concat actionmsg " subtree \""
12015 heading-text "\" to")))
12016 default-buffer
12017 (and (not (equal '(4) arg))
12018 org-refile-allow-creating-parent-nodes)))))))
12019 (setq file (nth 1 it)
12020 pos (nth 3 it))
12021 (when (and (not arg)
12023 (equal (buffer-file-name) file)
12024 (if regionp
12025 (and (>= pos region-start)
12026 (<= pos region-end))
12027 (and (>= pos (point))
12028 (< pos (save-excursion
12029 (org-end-of-subtree t t))))))
12030 (error "Cannot refile to position inside the tree or region"))
12031 (setq nbuf (or (find-buffer-visiting file)
12032 (find-file-noselect file)))
12033 (if (and arg (not (equal arg 3)))
12034 (progn
12035 (pop-to-buffer-same-window nbuf)
12036 (goto-char pos)
12037 (org-show-context 'org-goto))
12038 (if regionp
12039 (progn
12040 (org-kill-new (buffer-substring region-start region-end))
12041 (org-save-markers-in-region region-start region-end))
12042 (org-copy-subtree 1 nil t))
12043 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12044 (find-file-noselect file)))
12045 (setq reversed (org-notes-order-reversed-p))
12046 (save-excursion
12047 (save-restriction
12048 (widen)
12049 (if pos
12050 (progn
12051 (goto-char pos)
12052 (looking-at org-outline-regexp)
12053 (setq level (org-get-valid-level (funcall outline-level) 1))
12054 (goto-char
12055 (if reversed
12056 (or (outline-next-heading) (point-max))
12057 (or (save-excursion (org-get-next-sibling))
12058 (org-end-of-subtree t t)
12059 (point-max)))))
12060 (setq level 1)
12061 (if (not reversed)
12062 (goto-char (point-max))
12063 (goto-char (point-min))
12064 (or (outline-next-heading) (goto-char (point-max)))))
12065 (unless (bolp) (newline))
12066 (org-paste-subtree level nil nil t)
12067 (when org-log-refile
12068 (org-add-log-setup 'refile nil nil org-log-refile)
12069 (unless (eq org-log-refile 'note)
12070 (save-excursion (org-add-log-note))))
12071 (and org-auto-align-tags
12072 (let ((org-loop-over-headlines-in-active-region nil))
12073 (org-set-tags nil t)))
12074 (let ((bookmark-name (plist-get org-bookmark-names-plist
12075 :last-refile)))
12076 (when bookmark-name
12077 (with-demoted-errors
12078 (bookmark-set bookmark-name))))
12079 ;; If we are refiling for capture, make sure that the
12080 ;; last-capture pointers point here
12081 (when (bound-and-true-p org-capture-is-refiling)
12082 (let ((bookmark-name (plist-get org-bookmark-names-plist
12083 :last-capture-marker)))
12084 (when bookmark-name
12085 (with-demoted-errors
12086 (bookmark-set bookmark-name))))
12087 (move-marker org-capture-last-stored-marker (point)))
12088 (when (fboundp 'deactivate-mark) (deactivate-mark))
12089 (run-hooks 'org-after-refile-insert-hook))))
12090 (unless org-refile-keep
12091 (if regionp
12092 (delete-region (point) (+ (point) (- region-end region-start)))
12093 (delete-region
12094 (and (org-back-to-heading t) (point))
12095 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12096 (when (featurep 'org-inlinetask)
12097 (org-inlinetask-remove-END-maybe))
12098 (setq org-markers-to-move nil)
12099 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12101 (defun org-refile-goto-last-stored ()
12102 "Go to the location where the last refile was stored."
12103 (interactive)
12104 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12105 (message "This is the location of the last refile"))
12107 (defun org-refile--get-location (refloc tbl)
12108 "When user refile to REFLOC, find the associated target in TBL.
12109 Also check `org-refile-target-table'."
12110 (car (delq
12112 (mapcar
12113 (lambda (r) (or (assoc r tbl)
12114 (assoc r org-refile-target-table)))
12115 (list (replace-regexp-in-string "/$" "" refloc)
12116 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12118 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12119 "Prompt the user for a refile location, using PROMPT.
12120 PROMPT should not be suffixed with a colon and a space, because
12121 this function appends the default value from
12122 `org-refile-history' automatically, if that is not empty."
12123 (let ((org-refile-targets org-refile-targets)
12124 (org-refile-use-outline-path org-refile-use-outline-path))
12125 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12126 (unless org-refile-target-table
12127 (user-error "No refile targets"))
12128 (let* ((cbuf (current-buffer))
12129 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12130 (cfunc (if (and org-refile-use-outline-path
12131 org-outline-path-complete-in-steps)
12132 #'org-olpath-completing-read
12133 #'completing-read))
12134 (extra (if org-refile-use-outline-path "/" ""))
12135 (cbnex (concat (buffer-name) extra))
12136 (filename (and cfn (expand-file-name cfn)))
12137 (tbl (mapcar
12138 (lambda (x)
12139 (if (and (not (member org-refile-use-outline-path
12140 '(file full-file-path)))
12141 (not (equal filename (nth 1 x))))
12142 (cons (concat (car x) extra " ("
12143 (file-name-nondirectory (nth 1 x)) ")")
12144 (cdr x))
12145 (cons (concat (car x) extra) (cdr x))))
12146 org-refile-target-table))
12147 (completion-ignore-case t)
12148 cdef
12149 (prompt (concat prompt
12150 (or (and (car org-refile-history)
12151 (concat " (default " (car org-refile-history) ")"))
12152 (and (assoc cbnex tbl) (setq cdef cbnex)
12153 (concat " (default " cbnex ")"))) ": "))
12154 pa answ parent-target child parent old-hist)
12155 (setq old-hist org-refile-history)
12156 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12157 nil 'org-refile-history (or cdef (car org-refile-history))))
12158 (if (setq pa (org-refile--get-location answ tbl))
12159 (progn
12160 (org-refile-check-position pa)
12161 (when (or (not org-refile-history)
12162 (not (eq old-hist org-refile-history))
12163 (not (equal (car pa) (car org-refile-history))))
12164 (setq org-refile-history
12165 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12166 org-refile-history
12167 (cdr org-refile-history))))
12168 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12169 (pop org-refile-history)))
12171 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12172 (progn
12173 (setq parent (match-string 1 answ)
12174 child (match-string 2 answ))
12175 (setq parent-target (org-refile--get-location parent tbl))
12176 (when (and parent-target
12177 (or (eq new-nodes t)
12178 (and (eq new-nodes 'confirm)
12179 (y-or-n-p (format "Create new node \"%s\"? "
12180 child)))))
12181 (org-refile-new-child parent-target child)))
12182 (user-error "Invalid target location")))))
12184 (declare-function org-string-nw-p "org-macs" (s))
12185 (defun org-refile-check-position (refile-pointer)
12186 "Check if the refile pointer matches the headline to which it points."
12187 (let* ((file (nth 1 refile-pointer))
12188 (re (nth 2 refile-pointer))
12189 (pos (nth 3 refile-pointer))
12190 buffer)
12191 (if (and (not (markerp pos)) (not file))
12192 (user-error "Please indicate a target file in the refile path")
12193 (when (org-string-nw-p re)
12194 (setq buffer (if (markerp pos)
12195 (marker-buffer pos)
12196 (or (find-buffer-visiting file)
12197 (find-file-noselect file))))
12198 (with-current-buffer buffer
12199 (save-excursion
12200 (save-restriction
12201 (widen)
12202 (goto-char pos)
12203 (beginning-of-line 1)
12204 (unless (looking-at-p re)
12205 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12207 (defun org-refile-new-child (parent-target child)
12208 "Use refile target PARENT-TARGET to add new CHILD below it."
12209 (unless parent-target
12210 (error "Cannot find parent for new node"))
12211 (let ((file (nth 1 parent-target))
12212 (pos (nth 3 parent-target))
12213 level)
12214 (with-current-buffer (or (find-buffer-visiting file)
12215 (find-file-noselect file))
12216 (save-excursion
12217 (save-restriction
12218 (widen)
12219 (if pos
12220 (goto-char pos)
12221 (goto-char (point-max))
12222 (unless (bolp) (newline)))
12223 (when (looking-at org-outline-regexp)
12224 (setq level (funcall outline-level))
12225 (org-end-of-subtree t t))
12226 (org-back-over-empty-lines)
12227 (insert "\n" (make-string
12228 (if pos (org-get-valid-level level 1) 1) ?*)
12229 " " child "\n")
12230 (beginning-of-line 0)
12231 (list (concat (car parent-target) "/" child) file "" (point)))))))
12233 (defun org-olpath-completing-read (prompt collection &rest args)
12234 "Read an outline path like a file name."
12235 (let ((thetable collection))
12236 (apply #'completing-read
12237 prompt
12238 (lambda (string predicate &optional flag)
12239 (cond
12240 ((eq flag nil) (try-completion string thetable))
12241 ((eq flag t)
12242 (let ((l (length string)))
12243 (mapcar (lambda (x)
12244 (let ((r (substring x l))
12245 (f (if (string-match " ([^)]*)$" x)
12246 (match-string 0 x)
12247 "")))
12248 (if (string-match "/" r)
12249 (concat string (substring r 0 (match-end 0)) f)
12250 x)))
12251 (all-completions string thetable predicate))))
12252 ;; Exact match?
12253 ((eq flag 'lambda) (assoc string thetable))))
12254 args)))
12256 ;;;; Dynamic blocks
12258 (defun org-find-dblock (name)
12259 "Find the first dynamic block with name NAME in the buffer.
12260 If not found, stay at current position and return nil."
12261 (let ((case-fold-search t) pos)
12262 (save-excursion
12263 (goto-char (point-min))
12264 (setq pos (and (re-search-forward
12265 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12266 (match-beginning 0))))
12267 (when pos (goto-char pos))
12268 pos))
12270 (defun org-create-dblock (plist)
12271 "Create a dynamic block section, with parameters taken from PLIST.
12272 PLIST must contain a :name entry which is used as the name of the block."
12273 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12274 (end-of-line 1)
12275 (newline))
12276 (let ((col (current-column))
12277 (name (plist-get plist :name)))
12278 (insert "#+BEGIN: " name)
12279 (while plist
12280 (if (eq (car plist) :name)
12281 (setq plist (cddr plist))
12282 (insert " " (prin1-to-string (pop plist)))))
12283 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12284 (beginning-of-line -2)))
12286 (defun org-prepare-dblock ()
12287 "Prepare dynamic block for refresh.
12288 This empties the block, puts the cursor at the insert position and returns
12289 the property list including an extra property :name with the block name."
12290 (unless (looking-at org-dblock-start-re)
12291 (user-error "Not at a dynamic block"))
12292 (let* ((begdel (1+ (match-end 0)))
12293 (name (org-no-properties (match-string 1)))
12294 (params (append (list :name name)
12295 (read (concat "(" (match-string 3) ")")))))
12296 (save-excursion
12297 (beginning-of-line 1)
12298 (skip-chars-forward " \t")
12299 (setq params (plist-put params :indentation-column (current-column))))
12300 (unless (re-search-forward org-dblock-end-re nil t)
12301 (error "Dynamic block not terminated"))
12302 (setq params
12303 (append params
12304 (list :content (buffer-substring
12305 begdel (match-beginning 0)))))
12306 (delete-region begdel (match-beginning 0))
12307 (goto-char begdel)
12308 (open-line 1)
12309 params))
12311 (defun org-map-dblocks (&optional command)
12312 "Apply COMMAND to all dynamic blocks in the current buffer.
12313 If COMMAND is not given, use `org-update-dblock'."
12314 (let ((cmd (or command 'org-update-dblock)))
12315 (save-excursion
12316 (goto-char (point-min))
12317 (while (re-search-forward org-dblock-start-re nil t)
12318 (goto-char (match-beginning 0))
12319 (save-excursion
12320 (condition-case nil
12321 (funcall cmd)
12322 (error (message "Error during update of dynamic block"))))
12323 (unless (re-search-forward org-dblock-end-re nil t)
12324 (error "Dynamic block not terminated"))))))
12326 (defun org-dblock-update (&optional arg)
12327 "User command for updating dynamic blocks.
12328 Update the dynamic block at point. With prefix ARG, update all dynamic
12329 blocks in the buffer."
12330 (interactive "P")
12331 (if arg
12332 (org-update-all-dblocks)
12333 (or (looking-at org-dblock-start-re)
12334 (org-beginning-of-dblock))
12335 (org-update-dblock)))
12337 (defun org-update-dblock ()
12338 "Update the dynamic block at point.
12339 This means to empty the block, parse for parameters and then call
12340 the correct writing function."
12341 (interactive)
12342 (save-excursion
12343 (let* ((win (selected-window))
12344 (pos (point))
12345 (line (org-current-line))
12346 (params (org-prepare-dblock))
12347 (name (plist-get params :name))
12348 (indent (plist-get params :indentation-column))
12349 (cmd (intern (concat "org-dblock-write:" name))))
12350 (message "Updating dynamic block `%s' at line %d..." name line)
12351 (funcall cmd params)
12352 (message "Updating dynamic block `%s' at line %d...done" name line)
12353 (goto-char pos)
12354 (when (and indent (> indent 0))
12355 (setq indent (make-string indent ?\ ))
12356 (save-excursion
12357 (select-window win)
12358 (org-beginning-of-dblock)
12359 (forward-line 1)
12360 (while (not (looking-at org-dblock-end-re))
12361 (insert indent)
12362 (beginning-of-line 2))
12363 (when (looking-at org-dblock-end-re)
12364 (and (looking-at "[ \t]+")
12365 (replace-match ""))
12366 (insert indent)))))))
12368 (defun org-beginning-of-dblock ()
12369 "Find the beginning of the dynamic block at point.
12370 Error if there is no such block at point."
12371 (let ((pos (point))
12372 beg)
12373 (end-of-line 1)
12374 (if (and (re-search-backward org-dblock-start-re nil t)
12375 (setq beg (match-beginning 0))
12376 (re-search-forward org-dblock-end-re nil t)
12377 (> (match-end 0) pos))
12378 (goto-char beg)
12379 (goto-char pos)
12380 (error "Not in a dynamic block"))))
12382 (defun org-update-all-dblocks ()
12383 "Update all dynamic blocks in the buffer.
12384 This function can be used in a hook."
12385 (interactive)
12386 (when (derived-mode-p 'org-mode)
12387 (org-map-dblocks 'org-update-dblock)))
12390 ;;;; Completion
12392 (declare-function org-export-backend-options "ox" (cl-x) t)
12393 (defun org-get-export-keywords ()
12394 "Return a list of all currently understood export keywords.
12395 Export keywords include options, block names, attributes and
12396 keywords relative to each registered export back-end."
12397 (let (keywords)
12398 (dolist (backend
12399 (bound-and-true-p org-export-registered-backends)
12400 (delq nil keywords))
12401 ;; Back-end name (for keywords, like #+LATEX:)
12402 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12403 (dolist (option-entry (org-export-backend-options backend))
12404 ;; Back-end options.
12405 (push (nth 1 option-entry) keywords)))))
12407 (defconst org-options-keywords
12408 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12409 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12410 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12411 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12412 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12414 (defcustom org-structure-template-alist
12415 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12416 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12417 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12418 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12419 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12420 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12421 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12422 ("L" "#+LaTeX: ")
12423 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12424 ("H" "#+HTML: ")
12425 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12426 ("A" "#+ASCII: ")
12427 ("i" "#+INDEX: ?")
12428 ("I" "#+INCLUDE: %file ?"))
12429 "Structure completion elements.
12430 This is a list of abbreviation keys and values. The value gets inserted
12431 if you type `<' followed by the key and then press the completion key,
12432 usually `TAB'. %file will be replaced by a file name after prompting
12433 for the file using completion. The cursor will be placed at the position
12434 of the `?' in the template.
12435 There are two templates for each key, the first uses the original Org syntax,
12436 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12437 the default when the /org-mtags.el/ module has been loaded. See also the
12438 variable `org-mtags-prefer-muse-templates'."
12439 :group 'org-completion
12440 :type '(repeat
12441 (list
12442 (string :tag "Key")
12443 (string :tag "Template")))
12444 :version "25.1"
12445 :package-version '(Org . "8.3"))
12447 (defun org-try-structure-completion ()
12448 "Try to complete a structure template before point.
12449 This looks for strings like \"<e\" on an otherwise empty line and
12450 expands them."
12451 (let ((l (buffer-substring (point-at-bol) (point)))
12453 (when (and (looking-at "[ \t]*$")
12454 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12455 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12456 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12457 (match-beginning 1)) a)
12458 t)))
12460 (defun org-complete-expand-structure-template (start cell)
12461 "Expand a structure template."
12462 (let ((rpl (nth 1 cell))
12463 (ind ""))
12464 (delete-region start (point))
12465 (when (string-match "\\`[ \t]*#\\+" rpl)
12466 (cond
12467 ((bolp))
12468 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12469 (setq ind (buffer-substring (point-at-bol) (point))))
12470 (t (newline))))
12471 (setq start (point))
12472 (when (string-match "%file" rpl)
12473 (setq rpl (replace-match
12474 (concat
12475 "\""
12476 (save-match-data
12477 (abbreviate-file-name (read-file-name "Include file: ")))
12478 "\"")
12479 t t rpl)))
12480 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12481 (concat "\n" ind)))
12482 (insert rpl)
12483 (when (re-search-backward "\\?" start t) (delete-char 1))))
12485 ;;;; TODO, DEADLINE, Comments
12487 (defun org-toggle-comment ()
12488 "Change the COMMENT state of an entry."
12489 (interactive)
12490 (save-excursion
12491 (org-back-to-heading)
12492 (looking-at org-complex-heading-regexp)
12493 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12494 (skip-chars-forward " \t")
12495 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12496 (if (org-in-commented-heading-p t)
12497 (delete-region (point)
12498 (progn (search-forward " " (line-end-position) 'move)
12499 (skip-chars-forward " \t")
12500 (point)))
12501 (insert org-comment-string)
12502 (unless (eolp) (insert " ")))))
12504 (defvar org-last-todo-state-is-todo nil
12505 "This is non-nil when the last TODO state change led to a TODO state.
12506 If the last change removed the TODO tag or switched to DONE, then
12507 this is nil.")
12509 (defvar org-setting-tags nil) ; dynamically skipped
12511 (defvar org-todo-setup-filter-hook nil
12512 "Hook for functions that pre-filter todo specs.
12513 Each function takes a todo spec and returns either nil or the spec
12514 transformed into canonical form." )
12516 (defvar org-todo-get-default-hook nil
12517 "Hook for functions that get a default item for todo.
12518 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12519 nil or a string to be used for the todo mark." )
12521 (defvar org-agenda-headline-snapshot-before-repeat)
12523 (defun org-current-effective-time ()
12524 "Return current time adjusted for `org-extend-today-until' variable."
12525 (let* ((ct (org-current-time))
12526 (dct (decode-time ct))
12527 (ct1
12528 (cond
12529 (org-use-last-clock-out-time-as-effective-time
12530 (or (org-clock-get-last-clock-out-time) ct))
12531 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12532 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12533 (t ct))))
12534 ct1))
12536 (defun org-todo-yesterday (&optional arg)
12537 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12538 (interactive "P")
12539 (if (eq major-mode 'org-agenda-mode)
12540 (apply 'org-agenda-todo-yesterday arg)
12541 (let* ((org-use-effective-time t)
12542 (hour (nth 2 (decode-time (org-current-time))))
12543 (org-extend-today-until (1+ hour)))
12544 (org-todo arg))))
12546 (defvar org-block-entry-blocking ""
12547 "First entry preventing the TODO state change.")
12549 (defun org-cancel-repeater ()
12550 "Cancel a repeater by setting its numeric value to zero."
12551 (interactive)
12552 (save-excursion
12553 (org-back-to-heading t)
12554 (let ((bound1 (point))
12555 (bound0 (save-excursion (outline-next-heading) (point))))
12556 (when (and (re-search-forward
12557 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12558 org-deadline-time-regexp "\\)\\|\\("
12559 org-ts-regexp "\\)")
12560 bound0 t)
12561 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12562 bound1 t))
12563 (replace-match "0" t nil nil 1)))))
12565 (defvar org-state) ;; dynamically scoped into this function
12566 (defun org-todo (&optional arg)
12567 "Change the TODO state of an item.
12568 The state of an item is given by a keyword at the start of the heading,
12569 like
12570 *** TODO Write paper
12571 *** DONE Call mom
12573 The different keywords are specified in the variable `org-todo-keywords'.
12574 By default the available states are \"TODO\" and \"DONE\".
12575 So for this example: when the item starts with TODO, it is changed to DONE.
12576 When it starts with DONE, the DONE is removed. And when neither TODO nor
12577 DONE are present, add TODO at the beginning of the heading.
12579 With \\[universal-argument] prefix arg, use completion to determine the new \
12580 state.
12581 With numeric prefix arg, switch to that state.
12582 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12583 keywords (nextset).
12584 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12585 With a numeric prefix arg of 0, inhibit note taking for the change.
12586 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12588 When called through ELisp, arg is also interpreted in the following way:
12589 `none' -> empty state
12590 \"\"(empty string) -> switch to empty state
12591 `done' -> switch to DONE
12592 `nextset' -> switch to the next set of keywords
12593 `previousset' -> switch to the previous set of keywords
12594 \"WAITING\" -> switch to the specified keyword, but only if it
12595 really is a member of `org-todo-keywords'."
12596 (interactive "P")
12597 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12598 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12599 'region-start-level 'region))
12600 org-loop-over-headlines-in-active-region)
12601 (org-map-entries
12602 `(org-todo ,arg)
12603 org-loop-over-headlines-in-active-region
12604 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12605 (when (equal arg '(16)) (setq arg 'nextset))
12606 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12607 (let ((org-blocker-hook org-blocker-hook)
12608 commentp
12609 case-fold-search)
12610 (when (equal arg '(64))
12611 (setq arg nil org-blocker-hook nil))
12612 (when (and org-blocker-hook
12613 (or org-inhibit-blocking
12614 (org-entry-get nil "NOBLOCKING")))
12615 (setq org-blocker-hook nil))
12616 (save-excursion
12617 (catch 'exit
12618 (org-back-to-heading t)
12619 (when (org-in-commented-heading-p t)
12620 (org-toggle-comment)
12621 (setq commentp t))
12622 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12623 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12624 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12625 (let* ((match-data (match-data))
12626 (startpos (point-at-bol))
12627 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12628 (org-log-done org-log-done)
12629 (org-log-repeat org-log-repeat)
12630 (org-todo-log-states org-todo-log-states)
12631 (org-inhibit-logging
12632 (if (equal arg 0)
12633 (progn (setq arg nil) 'note) org-inhibit-logging))
12634 (this (match-string 1))
12635 (hl-pos (match-beginning 0))
12636 (head (org-get-todo-sequence-head this))
12637 (ass (assoc head org-todo-kwd-alist))
12638 (interpret (nth 1 ass))
12639 (done-word (nth 3 ass))
12640 (final-done-word (nth 4 ass))
12641 (org-last-state (or this ""))
12642 (completion-ignore-case t)
12643 (member (member this org-todo-keywords-1))
12644 (tail (cdr member))
12645 (org-state (cond
12646 ((and org-todo-key-trigger
12647 (or (and (equal arg '(4))
12648 (eq org-use-fast-todo-selection 'prefix))
12649 (and (not arg) org-use-fast-todo-selection
12650 (not (eq org-use-fast-todo-selection
12651 'prefix)))))
12652 ;; Use fast selection
12653 (org-fast-todo-selection))
12654 ((and (equal arg '(4))
12655 (or (not org-use-fast-todo-selection)
12656 (not org-todo-key-trigger)))
12657 ;; Read a state with completion
12658 (completing-read
12659 "State: " (mapcar #'list org-todo-keywords-1)
12660 nil t))
12661 ((eq arg 'right)
12662 (if this
12663 (if tail (car tail) nil)
12664 (car org-todo-keywords-1)))
12665 ((eq arg 'left)
12666 (unless (equal member org-todo-keywords-1)
12667 (if this
12668 (nth (- (length org-todo-keywords-1)
12669 (length tail) 2)
12670 org-todo-keywords-1)
12671 (org-last org-todo-keywords-1))))
12672 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12673 (setq arg nil))) ; hack to fall back to cycling
12674 (arg
12675 ;; user or caller requests a specific state
12676 (cond
12677 ((equal arg "") nil)
12678 ((eq arg 'none) nil)
12679 ((eq arg 'done) (or done-word (car org-done-keywords)))
12680 ((eq arg 'nextset)
12681 (or (car (cdr (member head org-todo-heads)))
12682 (car org-todo-heads)))
12683 ((eq arg 'previousset)
12684 (let ((org-todo-heads (reverse org-todo-heads)))
12685 (or (car (cdr (member head org-todo-heads)))
12686 (car org-todo-heads))))
12687 ((car (member arg org-todo-keywords-1)))
12688 ((stringp arg)
12689 (user-error "State `%s' not valid in this file" arg))
12690 ((nth (1- (prefix-numeric-value arg))
12691 org-todo-keywords-1))))
12692 ((null member) (or head (car org-todo-keywords-1)))
12693 ((equal this final-done-word) nil) ;; -> make empty
12694 ((null tail) nil) ;; -> first entry
12695 ((memq interpret '(type priority))
12696 (if (eq this-command last-command)
12697 (car tail)
12698 (if (> (length tail) 0)
12699 (or done-word (car org-done-keywords))
12700 nil)))
12702 (car tail))))
12703 (org-state (or
12704 (run-hook-with-args-until-success
12705 'org-todo-get-default-hook org-state org-last-state)
12706 org-state))
12707 (next (if org-state (concat " " org-state " ") " "))
12708 (change-plist (list :type 'todo-state-change :from this :to org-state
12709 :position startpos))
12710 dolog now-done-p)
12711 (when org-blocker-hook
12712 (setq org-last-todo-state-is-todo
12713 (not (member this org-done-keywords)))
12714 (unless (save-excursion
12715 (save-match-data
12716 (org-with-wide-buffer
12717 (run-hook-with-args-until-failure
12718 'org-blocker-hook change-plist))))
12719 (if (called-interactively-p 'interactive)
12720 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12721 this org-state org-block-entry-blocking)
12722 ;; fail silently
12723 (message "TODO state change from %s to %s blocked (by \"%s\")"
12724 this org-state org-block-entry-blocking)
12725 (throw 'exit nil))))
12726 (store-match-data match-data)
12727 (replace-match next t t)
12728 (cond ((equal this org-state)
12729 (message "TODO state was already %s" (org-trim next)))
12730 ((pos-visible-in-window-p hl-pos)
12731 (message "TODO state changed to %s" (org-trim next))))
12732 (unless head
12733 (setq head (org-get-todo-sequence-head org-state)
12734 ass (assoc head org-todo-kwd-alist)
12735 interpret (nth 1 ass)
12736 done-word (nth 3 ass)
12737 final-done-word (nth 4 ass)))
12738 (when (memq arg '(nextset previousset))
12739 (message "Keyword-Set %d/%d: %s"
12740 (- (length org-todo-sets) -1
12741 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12742 (length org-todo-sets)
12743 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12744 (setq org-last-todo-state-is-todo
12745 (not (member org-state org-done-keywords)))
12746 (setq now-done-p (and (member org-state org-done-keywords)
12747 (not (member this org-done-keywords))))
12748 (and logging (org-local-logging logging))
12749 (when (and (or org-todo-log-states org-log-done)
12750 (not (eq org-inhibit-logging t))
12751 (not (memq arg '(nextset previousset))))
12752 ;; we need to look at recording a time and note
12753 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12754 (nth 2 (assoc this org-todo-log-states))))
12755 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12756 (setq dolog 'time))
12757 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12758 (and org-state
12759 (member org-state org-not-done-keywords)
12760 (not (member this org-not-done-keywords))))
12761 ;; This is now a todo state and was not one before
12762 ;; If there was a CLOSED time stamp, get rid of it.
12763 (org-add-planning-info nil nil 'closed))
12764 (when (and now-done-p org-log-done)
12765 ;; It is now done, and it was not done before
12766 (org-add-planning-info 'closed (org-current-effective-time))
12767 (when (and (not dolog) (eq 'note org-log-done))
12768 (org-add-log-setup 'done org-state this 'note)))
12769 (when (and org-state dolog)
12770 ;; This is a non-nil state, and we need to log it
12771 (org-add-log-setup 'state org-state this dolog)))
12772 ;; Fixup tag positioning
12773 (org-todo-trigger-tag-changes org-state)
12774 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12775 (when org-provide-todo-statistics
12776 (org-update-parent-todo-statistics))
12777 (run-hooks 'org-after-todo-state-change-hook)
12778 (when (and arg (not (member org-state org-done-keywords)))
12779 (setq head (org-get-todo-sequence-head org-state)))
12780 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12781 ;; Do we need to trigger a repeat?
12782 (when now-done-p
12783 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12784 ;; This is for the agenda, take a snapshot of the headline.
12785 (save-match-data
12786 (setq org-agenda-headline-snapshot-before-repeat
12787 (org-get-heading))))
12788 (org-auto-repeat-maybe org-state))
12789 ;; Fixup cursor location if close to the keyword
12790 (when (and (outline-on-heading-p)
12791 (not (bolp))
12792 (save-excursion (beginning-of-line 1)
12793 (looking-at org-todo-line-regexp))
12794 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12795 (goto-char (or (match-end 2) (match-end 1)))
12796 (and (looking-at " ") (just-one-space)))
12797 (when org-trigger-hook
12798 (save-excursion
12799 (run-hook-with-args 'org-trigger-hook change-plist)))
12800 (when commentp (org-toggle-comment))))))))
12802 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12803 "Block turning an entry into a TODO, using the hierarchy.
12804 This checks whether the current task should be blocked from state
12805 changes. Such blocking occurs when:
12807 1. The task has children which are not all in a completed state.
12809 2. A task has a parent with the property :ORDERED:, and there
12810 are siblings prior to the current task with incomplete
12811 status.
12813 3. The parent of the task is blocked because it has siblings that should
12814 be done first, or is child of a block grandparent TODO entry."
12816 (if (not org-enforce-todo-dependencies)
12817 t ; if locally turned off don't block
12818 (catch 'dont-block
12819 ;; If this is not a todo state change, or if this entry is already DONE,
12820 ;; do not block
12821 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12822 (member (plist-get change-plist :from)
12823 (cons 'done org-done-keywords))
12824 (member (plist-get change-plist :to)
12825 (cons 'todo org-not-done-keywords))
12826 (not (plist-get change-plist :to)))
12827 (throw 'dont-block t))
12828 ;; If this task has children, and any are undone, it's blocked
12829 (save-excursion
12830 (org-back-to-heading t)
12831 (let ((this-level (funcall outline-level)))
12832 (outline-next-heading)
12833 (let ((child-level (funcall outline-level)))
12834 (while (and (not (eobp))
12835 (> child-level this-level))
12836 ;; this todo has children, check whether they are all
12837 ;; completed
12838 (when (and (not (org-entry-is-done-p))
12839 (org-entry-is-todo-p))
12840 (setq org-block-entry-blocking (org-get-heading))
12841 (throw 'dont-block nil))
12842 (outline-next-heading)
12843 (setq child-level (funcall outline-level))))))
12844 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12845 ;; any previous siblings are undone, it's blocked
12846 (save-excursion
12847 (org-back-to-heading t)
12848 (let* ((pos (point))
12849 (parent-pos (and (org-up-heading-safe) (point))))
12850 (unless parent-pos (throw 'dont-block t)) ; no parent
12851 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12852 (forward-line 1)
12853 (re-search-forward org-not-done-heading-regexp pos t))
12854 (setq org-block-entry-blocking (match-string 0))
12855 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12856 ;; Search further up the hierarchy, to see if an ancestor is blocked
12857 (while t
12858 (goto-char parent-pos)
12859 (unless (looking-at org-not-done-heading-regexp)
12860 (throw 'dont-block t)) ; do not block, parent is not a TODO
12861 (setq pos (point))
12862 (setq parent-pos (and (org-up-heading-safe) (point)))
12863 (unless parent-pos (throw 'dont-block t)) ; no parent
12864 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12865 (forward-line 1)
12866 (re-search-forward org-not-done-heading-regexp pos t)
12867 (setq org-block-entry-blocking (org-get-heading)))
12868 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12870 (defcustom org-track-ordered-property-with-tag nil
12871 "Should the ORDERED property also be shown as a tag?
12872 The ORDERED property decides if an entry should require subtasks to be
12873 completed in sequence. Since a property is not very visible, setting
12874 this option means that toggling the ORDERED property with the command
12875 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12876 not relevant for the behavior, but it makes things more visible.
12878 Note that toggling the tag with tags commands will not change the property
12879 and therefore not influence behavior!
12881 This can be t, meaning the tag ORDERED should be used, It can also be a
12882 string to select a different tag for this task."
12883 :group 'org-todo
12884 :type '(choice
12885 (const :tag "No tracking" nil)
12886 (const :tag "Track with ORDERED tag" t)
12887 (string :tag "Use other tag")))
12889 (defun org-toggle-ordered-property ()
12890 "Toggle the ORDERED property of the current entry.
12891 For better visibility, you can track the value of this property with a tag.
12892 See variable `org-track-ordered-property-with-tag'."
12893 (interactive)
12894 (let* ((t1 org-track-ordered-property-with-tag)
12895 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12896 (save-excursion
12897 (org-back-to-heading)
12898 (if (org-entry-get nil "ORDERED")
12899 (progn
12900 (org-delete-property "ORDERED")
12901 (and tag (org-toggle-tag tag 'off))
12902 (message "Subtasks can be completed in arbitrary order"))
12903 (org-entry-put nil "ORDERED" "t")
12904 (and tag (org-toggle-tag tag 'on))
12905 (message "Subtasks must be completed in sequence")))))
12907 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12908 (defun org-block-todo-from-checkboxes (change-plist)
12909 "Block turning an entry into a TODO, using checkboxes.
12910 This checks whether the current task should be blocked from state
12911 changes because there are unchecked boxes in this entry."
12912 (if (not org-enforce-todo-checkbox-dependencies)
12913 t ; if locally turned off don't block
12914 (catch 'dont-block
12915 ;; If this is not a todo state change, or if this entry is already DONE,
12916 ;; do not block
12917 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12918 (member (plist-get change-plist :from)
12919 (cons 'done org-done-keywords))
12920 (member (plist-get change-plist :to)
12921 (cons 'todo org-not-done-keywords))
12922 (not (plist-get change-plist :to)))
12923 (throw 'dont-block t))
12924 ;; If this task has checkboxes that are not checked, it's blocked
12925 (save-excursion
12926 (org-back-to-heading t)
12927 (let ((beg (point)) end)
12928 (outline-next-heading)
12929 (setq end (point))
12930 (goto-char beg)
12931 (when (org-list-search-forward
12932 (concat (org-item-beginning-re)
12933 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12934 "\\[[- ]\\]")
12935 end t)
12936 (when (boundp 'org-blocked-by-checkboxes)
12937 (setq org-blocked-by-checkboxes t))
12938 (throw 'dont-block nil))))
12939 t))) ; do not block
12941 (defun org-entry-blocked-p ()
12942 "Non-nil if entry at point is blocked."
12943 (and (not (org-entry-get nil "NOBLOCKING"))
12944 (member (org-entry-get nil "TODO") org-not-done-keywords)
12945 (not (run-hook-with-args-until-failure
12946 'org-blocker-hook
12947 (list :type 'todo-state-change
12948 :position (point)
12949 :from 'todo
12950 :to 'done)))))
12952 (defun org-update-statistics-cookies (all)
12953 "Update the statistics cookie, either from TODO or from checkboxes.
12954 This should be called with the cursor in a line with a statistics cookie."
12955 (interactive "P")
12956 (if all
12957 (progn
12958 (org-update-checkbox-count 'all)
12959 (org-map-entries 'org-update-parent-todo-statistics))
12960 (if (not (org-at-heading-p))
12961 (org-update-checkbox-count)
12962 (let ((pos (point-marker))
12963 end l1 l2)
12964 (ignore-errors (org-back-to-heading t))
12965 (if (not (org-at-heading-p))
12966 (org-update-checkbox-count)
12967 (setq l1 (org-outline-level))
12968 (setq end (save-excursion
12969 (outline-next-heading)
12970 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12971 (point)))
12972 (if (and (save-excursion
12973 (re-search-forward
12974 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12975 (not (save-excursion (re-search-forward
12976 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12977 (org-update-checkbox-count)
12978 (if (and l2 (> l2 l1))
12979 (progn
12980 (goto-char end)
12981 (org-update-parent-todo-statistics))
12982 (goto-char pos)
12983 (beginning-of-line 1)
12984 (while (re-search-forward
12985 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12986 (point-at-eol) t)
12987 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12988 (goto-char pos)
12989 (move-marker pos nil)))))
12991 (defvar org-entry-property-inherited-from) ;; defined below
12992 (defun org-update-parent-todo-statistics ()
12993 "Update any statistics cookie in the parent of the current headline.
12994 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12995 the entire subtree and this will travel up the hierarchy and update
12996 statistics everywhere."
12997 (let* ((prop (save-excursion (org-up-heading-safe)
12998 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12999 (recursive (or (not org-hierarchical-todo-statistics)
13000 (and prop (string-match "\\<recursive\\>" prop))))
13001 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13003 (first t)
13004 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13005 level ltoggle l1 new ndel
13006 (cnt-all 0) (cnt-done 0) is-percent kwd
13007 checkbox-beg cookie-present)
13008 (catch 'exit
13009 (save-excursion
13010 (beginning-of-line 1)
13011 (setq ltoggle (funcall outline-level))
13012 ;; Three situations are to consider:
13014 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13015 ;; to the top-level ancestor on the headline;
13017 ;; 2. If parent has "recursive" property, repeat up to the
13018 ;; headline setting that property, taking inheritance into
13019 ;; account;
13021 ;; 3. Else, move up to direct parent and proceed only once.
13022 (while (and (setq level (org-up-heading-safe))
13023 (or recursive first)
13024 (>= (point) lim))
13025 (setq first nil cookie-present nil)
13026 (unless (and level
13027 (not (string-match
13028 "\\<checkbox\\>"
13029 (downcase (or (org-entry-get nil "COOKIE_DATA")
13030 "")))))
13031 (throw 'exit nil))
13032 (while (re-search-forward box-re (point-at-eol) t)
13033 (setq cnt-all 0 cnt-done 0 cookie-present t)
13034 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13035 (save-match-data
13036 (unless (outline-next-heading) (throw 'exit nil))
13037 (while (and (looking-at org-complex-heading-regexp)
13038 (> (setq l1 (length (match-string 1))) level))
13039 (setq kwd (and (or recursive (= l1 ltoggle))
13040 (match-string 2)))
13041 (if (or (eq org-provide-todo-statistics 'all-headlines)
13042 (and (eq org-provide-todo-statistics t)
13043 (or (member kwd org-done-keywords)))
13044 (and (listp org-provide-todo-statistics)
13045 (stringp (car org-provide-todo-statistics))
13046 (or (member kwd org-provide-todo-statistics)
13047 (member kwd org-done-keywords)))
13048 (and (listp org-provide-todo-statistics)
13049 (listp (car org-provide-todo-statistics))
13050 (or (member kwd (car org-provide-todo-statistics))
13051 (and (member kwd org-done-keywords)
13052 (member kwd (cadr org-provide-todo-statistics))))))
13053 (setq cnt-all (1+ cnt-all))
13054 (and (eq org-provide-todo-statistics t)
13056 (setq cnt-all (1+ cnt-all))))
13057 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13058 (member kwd org-done-keywords))
13059 (and (listp org-provide-todo-statistics)
13060 (listp (car org-provide-todo-statistics))
13061 (member kwd org-done-keywords)
13062 (member kwd (cadr org-provide-todo-statistics)))
13063 (and (listp org-provide-todo-statistics)
13064 (stringp (car org-provide-todo-statistics))
13065 (member kwd org-done-keywords)))
13066 (setq cnt-done (1+ cnt-done)))
13067 (outline-next-heading)))
13068 (setq new
13069 (if is-percent
13070 (format "[%d%%]" (floor (* 100.0 cnt-done)
13071 (max 1 cnt-all)))
13072 (format "[%d/%d]" cnt-done cnt-all))
13073 ndel (- (match-end 0) checkbox-beg))
13074 (goto-char checkbox-beg)
13075 (insert new)
13076 (delete-region (point) (+ (point) ndel))
13077 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13078 (when cookie-present
13079 (run-hook-with-args 'org-after-todo-statistics-hook
13080 cnt-done (- cnt-all cnt-done))))))
13081 (run-hooks 'org-todo-statistics-hook)))
13083 (defvar org-after-todo-statistics-hook nil
13084 "Hook that is called after a TODO statistics cookie has been updated.
13085 Each function is called with two arguments: the number of not-done entries
13086 and the number of done entries.
13088 For example, the following function, when added to this hook, will switch
13089 an entry to DONE when all children are done, and back to TODO when new
13090 entries are set to a TODO status. Note that this hook is only called
13091 when there is a statistics cookie in the headline!
13093 \(defun org-summary-todo (n-done n-not-done)
13094 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13095 \(let (org-log-done org-log-states) ; turn off logging
13096 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13099 (defvar org-todo-statistics-hook nil
13100 "Hook that is run whenever Org thinks TODO statistics should be updated.
13101 This hook runs even if there is no statistics cookie present, in which case
13102 `org-after-todo-statistics-hook' would not run.")
13104 (defun org-todo-trigger-tag-changes (state)
13105 "Apply the changes defined in `org-todo-state-tags-triggers'."
13106 (let ((l org-todo-state-tags-triggers)
13107 changes)
13108 (when (or (not state) (equal state ""))
13109 (setq changes (append changes (cdr (assoc "" l)))))
13110 (when (and (stringp state) (> (length state) 0))
13111 (setq changes (append changes (cdr (assoc state l)))))
13112 (when (member state org-not-done-keywords)
13113 (setq changes (append changes (cdr (assoc 'todo l)))))
13114 (when (member state org-done-keywords)
13115 (setq changes (append changes (cdr (assoc 'done l)))))
13116 (dolist (c changes)
13117 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13119 (defun org-local-logging (value)
13120 "Get logging settings from a property VALUE."
13121 ;; Directly set the variables, they are already local.
13122 (setq org-log-done nil
13123 org-log-repeat nil
13124 org-todo-log-states nil)
13125 (dolist (w (org-split-string value))
13126 (let (a)
13127 (cond
13128 ((setq a (assoc w org-startup-options))
13129 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13130 (set (nth 1 a) (nth 2 a))))
13131 ((setq a (org-extract-log-state-settings w))
13132 (and (member (car a) org-todo-keywords-1)
13133 (push a org-todo-log-states)))))))
13135 (defun org-get-todo-sequence-head (kwd)
13136 "Return the head of the TODO sequence to which KWD belongs.
13137 If KWD is not set, check if there is a text property remembering the
13138 right sequence."
13139 (let (p)
13140 (cond
13141 ((not kwd)
13142 (or (get-text-property (point-at-bol) 'org-todo-head)
13143 (progn
13144 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13145 nil (point-at-eol)))
13146 (get-text-property p 'org-todo-head))))
13147 ((not (member kwd org-todo-keywords-1))
13148 (car org-todo-keywords-1))
13149 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13151 (defun org-fast-todo-selection ()
13152 "Fast TODO keyword selection with single keys.
13153 Returns the new TODO keyword, or nil if no state change should occur."
13154 (let* ((fulltable org-todo-key-alist)
13155 (done-keywords org-done-keywords) ;; needed for the faces.
13156 (maxlen (apply 'max (mapcar
13157 (lambda (x)
13158 (if (stringp (car x)) (string-width (car x)) 0))
13159 fulltable)))
13160 (expert nil)
13161 (fwidth (+ maxlen 3 1 3))
13162 (ncol (/ (- (window-width) 4) fwidth))
13163 tg cnt e c tbl
13164 groups ingroup)
13165 (save-excursion
13166 (save-window-excursion
13167 (if expert
13168 (set-buffer (get-buffer-create " *Org todo*"))
13169 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13170 (erase-buffer)
13171 (setq-local org-done-keywords done-keywords)
13172 (setq tbl fulltable cnt 0)
13173 (while (setq e (pop tbl))
13174 (cond
13175 ((equal e '(:startgroup))
13176 (push '() groups) (setq ingroup t)
13177 (unless (= cnt 0)
13178 (setq cnt 0)
13179 (insert "\n"))
13180 (insert "{ "))
13181 ((equal e '(:endgroup))
13182 (setq ingroup nil cnt 0)
13183 (insert "}\n"))
13184 ((equal e '(:newline))
13185 (unless (= cnt 0)
13186 (setq cnt 0)
13187 (insert "\n")
13188 (setq e (car tbl))
13189 (while (equal (car tbl) '(:newline))
13190 (insert "\n")
13191 (setq tbl (cdr tbl)))))
13193 (setq tg (car e) c (cdr e))
13194 (when ingroup (push tg (car groups)))
13195 (setq tg (org-add-props tg nil 'face
13196 (org-get-todo-face tg)))
13197 (when (and (= cnt 0) (not ingroup)) (insert " "))
13198 (insert "[" c "] " tg (make-string
13199 (- fwidth 4 (length tg)) ?\ ))
13200 (when (= (setq cnt (1+ cnt)) ncol)
13201 (insert "\n")
13202 (when ingroup (insert " "))
13203 (setq cnt 0)))))
13204 (insert "\n")
13205 (goto-char (point-min))
13206 (unless expert (org-fit-window-to-buffer))
13207 (message "[a-z..]:Set [SPC]:clear")
13208 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13209 (cond
13210 ((or (= c ?\C-g)
13211 (and (= c ?q) (not (rassoc c fulltable))))
13212 (setq quit-flag t))
13213 ((= c ?\ ) nil)
13214 ((setq e (rassoc c fulltable) tg (car e))
13216 (t (setq quit-flag t)))))))
13218 (defun org-entry-is-todo-p ()
13219 (member (org-get-todo-state) org-not-done-keywords))
13221 (defun org-entry-is-done-p ()
13222 (member (org-get-todo-state) org-done-keywords))
13224 (defun org-get-todo-state ()
13225 "Return the TODO keyword of the current subtree."
13226 (save-excursion
13227 (org-back-to-heading t)
13228 (and (looking-at org-todo-line-regexp)
13229 (match-end 2)
13230 (match-string 2))))
13232 (defun org-at-date-range-p (&optional inactive-ok)
13233 "Non-nil if point is inside a date range.
13235 When optional argument INACTIVE-OK is non-nil, also consider
13236 inactive time ranges.
13238 When this function returns a non-nil value, match data is set
13239 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13240 on INACTIVE-OK."
13241 (interactive)
13242 (save-excursion
13243 (catch 'exit
13244 (let ((pos (point)))
13245 (skip-chars-backward "^[<\r\n")
13246 (skip-chars-backward "<[")
13247 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13248 (>= (match-end 0) pos)
13249 (throw 'exit t))
13250 (skip-chars-backward "^<[\r\n")
13251 (skip-chars-backward "<[")
13252 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13253 (>= (match-end 0) pos)
13254 (throw 'exit t)))
13255 nil)))
13257 (defun org-get-repeat (&optional tagline)
13258 "Check if there is a deadline/schedule with repeater in this entry."
13259 (save-match-data
13260 (save-excursion
13261 (org-back-to-heading t)
13262 (and (re-search-forward (if tagline
13263 (concat tagline "\\s-*" org-repeat-re)
13264 org-repeat-re)
13265 (org-entry-end-position) t)
13266 (match-string-no-properties 1)))))
13268 (defvar org-last-changed-timestamp)
13269 (defvar org-last-inserted-timestamp)
13270 (defvar org-log-post-message)
13271 (defvar org-log-note-purpose)
13272 (defvar org-log-note-how nil)
13273 (defvar org-log-note-extra)
13274 (defun org-auto-repeat-maybe (done-word)
13275 "Check if the current headline contains a repeated time-stamp.
13277 If yes, set TODO state back to what it was and change the base date
13278 of repeating deadline/scheduled time stamps to new date.
13280 This function is run automatically after each state change to a DONE state."
13281 (let* ((repeat (org-get-repeat))
13282 (aa (assoc org-last-state org-todo-kwd-alist))
13283 (interpret (nth 1 aa))
13284 (head (nth 2 aa))
13285 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13286 (msg "Entry repeats: ")
13287 (org-log-done nil)
13288 (org-todo-log-states nil))
13289 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13290 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13291 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13292 org-todo-repeat-to-state)))
13293 (unless (and to-state (member to-state org-todo-keywords-1))
13294 (setq to-state (if (eq interpret 'type) org-last-state head)))
13295 (org-todo to-state))
13296 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13297 (org-entry-put nil "LAST_REPEAT" (format-time-string
13298 (org-time-stamp-format t t))))
13299 (when org-log-repeat
13300 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13301 (memq 'org-add-log-note post-command-hook))
13302 ;; We are already setup for some record.
13303 (when (eq org-log-repeat 'note)
13304 ;; Make sure we take a note, not only a time stamp.
13305 (setq org-log-note-how 'note))
13306 ;; Set up for taking a record.
13307 (org-add-log-setup 'state
13308 (or done-word (car org-done-keywords))
13309 org-last-state
13310 org-log-repeat)))
13311 (org-back-to-heading t)
13312 (org-add-planning-info nil nil 'closed)
13313 (let ((end (save-excursion (outline-next-heading) (point))))
13314 (while (re-search-forward org-ts-regexp end t)
13315 (when (save-match-data
13316 (or (org-at-planning-p)
13317 (org-at-property-p)
13318 (eq (org-element-type (save-excursion
13319 (backward-char)
13320 (org-element-context)))
13321 'timestamp)))
13322 (let ((type (cond ((match-end 1) org-scheduled-string)
13323 ((match-end 3) org-deadline-string)
13324 (t "Plain:")))
13325 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13326 (cond
13327 ((not
13328 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13329 ;; Time-stamps without a repeater are usually skipped.
13330 ;; However, a SCHEDULED time-stamp without one is
13331 ;; removed, as it is considered as no longer relevant.
13332 (when (equal type org-scheduled-string)
13333 (org-remove-timestamp-with-keyword type)))
13335 (let ((n (string-to-number (match-string 2 ts)))
13336 (what (match-string 3 ts)))
13337 (when (equal what "w") (setq n (* n 7) what "d"))
13338 (when (and (equal what "h")
13339 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13340 ts)))
13341 (user-error
13342 "Cannot repeat in Repeat in %d hour(s) because no hour \
13343 has been set"
13345 ;; Preparation, see if we need to modify the start
13346 ;; date for the change.
13347 (when (match-end 1)
13348 (let ((time (save-match-data (org-time-string-to-time ts))))
13349 (cond
13350 ((equal (match-string 1 ts) ".")
13351 ;; Shift starting date to today
13352 (org-timestamp-change
13353 (- (org-today) (time-to-days time))
13354 'day))
13355 ((equal (match-string 1 ts) "+")
13356 (let ((nshiftmax 10)
13357 (nshift 0))
13358 (while (or (= nshift 0)
13359 (not (time-less-p (current-time) time)))
13360 (when (= (cl-incf nshift) nshiftmax)
13361 (or (y-or-n-p
13362 (format "%d repeater intervals were not \
13363 enough to shift date past today. Continue? "
13364 nshift))
13365 (user-error "Abort")))
13366 (org-timestamp-change n (cdr (assoc what whata)))
13367 (org-at-timestamp-p t)
13368 (setq ts (match-string 1))
13369 (setq time
13370 (save-match-data
13371 (org-time-string-to-time ts)))))
13372 (org-timestamp-change (- n) (cdr (assoc what whata)))
13373 ;; Rematch, so that we have everything in
13374 ;; place for the real shift.
13375 (org-at-timestamp-p t)
13376 (setq ts (match-string 1))
13377 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13378 ts)))))
13379 (save-excursion
13380 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13381 (setq msg
13382 (concat
13383 msg type " " org-last-changed-timestamp " ")))))))))
13384 (setq org-log-post-message msg)
13385 (message "%s" msg))))
13387 (defun org-show-todo-tree (arg)
13388 "Make a compact tree which shows all headlines marked with TODO.
13389 The tree will show the lines where the regexp matches, and all higher
13390 headlines above the match.
13391 With a \\[universal-argument] prefix, prompt for a regexp to match.
13392 With a numeric prefix N, construct a sparse tree for the Nth element
13393 of `org-todo-keywords-1'."
13394 (interactive "P")
13395 (let ((case-fold-search nil)
13396 (kwd-re
13397 (cond ((null arg) org-not-done-regexp)
13398 ((equal arg '(4))
13399 (let ((kwd
13400 (completing-read "Keyword (or KWD1|KWD2|...): "
13401 (mapcar #'list org-todo-keywords-1))))
13402 (concat "\\("
13403 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13404 "\\)\\>")))
13405 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13406 (regexp-quote (nth (1- (prefix-numeric-value arg))
13407 org-todo-keywords-1)))
13408 (t (user-error "Invalid prefix argument: %s" arg)))))
13409 (message "%d TODO entries found"
13410 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13412 (defun org-deadline (arg &optional time)
13413 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13414 With one universal prefix argument, remove any deadline from the item.
13415 With two universal prefix arguments, prompt for a warning delay.
13416 With argument TIME, set the deadline at the corresponding date. TIME
13417 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13418 (interactive "P")
13419 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13420 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13421 'region-start-level 'region))
13422 org-loop-over-headlines-in-active-region)
13423 (org-map-entries
13424 `(org-deadline ',arg ,time)
13425 org-loop-over-headlines-in-active-region
13426 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13427 (let* ((old-date (org-entry-get nil "DEADLINE"))
13428 (old-date-time (when old-date (org-time-string-to-time old-date)))
13429 (repeater (and old-date
13430 (string-match
13431 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13432 old-date)
13433 (match-string 1 old-date))))
13434 (cond
13435 ((equal arg '(4))
13436 (when (and old-date org-log-redeadline)
13437 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13438 (org-remove-timestamp-with-keyword org-deadline-string)
13439 (message "Item no longer has a deadline."))
13440 ((equal arg '(16))
13441 (save-excursion
13442 (org-back-to-heading t)
13443 (if (re-search-forward
13444 org-deadline-time-regexp
13445 (save-excursion (outline-next-heading) (point)) t)
13446 (let* ((rpl0 (match-string 1))
13447 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13448 (replace-match
13449 (concat org-deadline-string
13450 " <" rpl
13451 (format " -%dd"
13452 (abs
13453 (- (time-to-days
13454 (save-match-data
13455 (org-read-date nil t nil "Warn starting from" old-date-time)))
13456 (time-to-days old-date-time))))
13457 ">") t t))
13458 (user-error "No deadline information to update"))))
13460 (org-add-planning-info 'deadline time 'closed)
13461 (when (and old-date
13462 org-log-redeadline
13463 (not (equal old-date org-last-inserted-timestamp)))
13464 (org-add-log-setup
13465 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13466 (when repeater
13467 (save-excursion
13468 (org-back-to-heading t)
13469 (when (re-search-forward (concat org-deadline-string " "
13470 org-last-inserted-timestamp)
13471 (save-excursion
13472 (outline-next-heading) (point)) t)
13473 (goto-char (1- (match-end 0)))
13474 (insert " " repeater)
13475 (setq org-last-inserted-timestamp
13476 (concat (substring org-last-inserted-timestamp 0 -1)
13477 " " repeater
13478 (substring org-last-inserted-timestamp -1))))))
13479 (message "Deadline on %s" org-last-inserted-timestamp))))))
13481 (defun org-schedule (arg &optional time)
13482 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13483 With one universal prefix argument, remove any scheduling date from the item.
13484 With two universal prefix arguments, prompt for a delay cookie.
13485 With argument TIME, scheduled at the corresponding date. TIME can
13486 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13487 (interactive "P")
13488 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13489 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13490 'region-start-level 'region))
13491 org-loop-over-headlines-in-active-region)
13492 (org-map-entries
13493 `(org-schedule ',arg ,time)
13494 org-loop-over-headlines-in-active-region
13495 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13496 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13497 (old-date-time (when old-date (org-time-string-to-time old-date)))
13498 (repeater (and old-date
13499 (string-match
13500 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13501 old-date)
13502 (match-string 1 old-date))))
13503 (cond
13504 ((equal arg '(4))
13505 (progn
13506 (when (and old-date org-log-reschedule)
13507 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13508 (org-remove-timestamp-with-keyword org-scheduled-string)
13509 (message "Item is no longer scheduled.")))
13510 ((equal arg '(16))
13511 (save-excursion
13512 (org-back-to-heading t)
13513 (if (re-search-forward
13514 org-scheduled-time-regexp
13515 (save-excursion (outline-next-heading) (point)) t)
13516 (let* ((rpl0 (match-string 1))
13517 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13518 (replace-match
13519 (concat org-scheduled-string
13520 " <" rpl
13521 (format " -%dd"
13522 (abs
13523 (- (time-to-days
13524 (save-match-data
13525 (org-read-date nil t nil "Delay until" old-date-time)))
13526 (time-to-days old-date-time))))
13527 ">") t t))
13528 (user-error "No scheduled information to update"))))
13530 (org-add-planning-info 'scheduled time 'closed)
13531 (when (and old-date
13532 org-log-reschedule
13533 (not (equal old-date org-last-inserted-timestamp)))
13534 (org-add-log-setup
13535 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13536 (when repeater
13537 (save-excursion
13538 (org-back-to-heading t)
13539 (when (re-search-forward (concat org-scheduled-string " "
13540 org-last-inserted-timestamp)
13541 (save-excursion
13542 (outline-next-heading) (point)) t)
13543 (goto-char (1- (match-end 0)))
13544 (insert " " repeater)
13545 (setq org-last-inserted-timestamp
13546 (concat (substring org-last-inserted-timestamp 0 -1)
13547 " " repeater
13548 (substring org-last-inserted-timestamp -1))))))
13549 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13551 (defun org-get-scheduled-time (pom &optional inherit)
13552 "Get the scheduled time as a time tuple, of a format suitable
13553 for calling org-schedule with, or if there is no scheduling,
13554 returns nil."
13555 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13556 (when time
13557 (apply 'encode-time (org-parse-time-string time)))))
13559 (defun org-get-deadline-time (pom &optional inherit)
13560 "Get the deadline as a time tuple, of a format suitable for
13561 calling org-deadline with, or if there is no scheduling, returns
13562 nil."
13563 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13564 (when time
13565 (apply 'encode-time (org-parse-time-string time)))))
13567 (defun org-remove-timestamp-with-keyword (keyword)
13568 "Remove all time stamps with KEYWORD in the current entry."
13569 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13570 beg)
13571 (save-excursion
13572 (org-back-to-heading t)
13573 (setq beg (point))
13574 (outline-next-heading)
13575 (while (re-search-backward re beg t)
13576 (replace-match "")
13577 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13578 (equal (char-before) ?\ ))
13579 (backward-delete-char 1)
13580 (when (string-match "^[ \t]*$" (buffer-substring
13581 (point-at-bol) (point-at-eol)))
13582 (delete-region (point-at-bol)
13583 (min (point-max) (1+ (point-at-eol))))))))))
13585 (defvar org-time-was-given) ; dynamically scoped parameter
13586 (defvar org-end-time-was-given) ; dynamically scoped parameter
13588 (defun org-at-planning-p ()
13589 "Non-nil when point is on a planning info line."
13590 ;; This is as accurate and faster than `org-element-at-point' since
13591 ;; planning info location is fixed in the section.
13592 (org-with-wide-buffer
13593 (beginning-of-line)
13594 (and (looking-at-p org-planning-line-re)
13595 (eq (point)
13596 (ignore-errors
13597 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13598 (org-back-to-heading t)
13599 (org-with-limited-levels (org-back-to-heading t)))
13600 (line-beginning-position 2))))))
13602 (defun org-add-planning-info (what &optional time &rest remove)
13603 "Insert new timestamp with keyword in the planning line.
13604 WHAT indicates what kind of time stamp to add. It is a symbol
13605 among `closed', `deadline', `scheduled' and nil. TIME indicates
13606 the time to use. If none is given, the user is prompted for
13607 a date. REMOVE indicates what kind of entries to remove. An old
13608 WHAT entry will also be removed."
13609 (let (org-time-was-given org-end-time-was-given default-time default-input)
13610 (catch 'exit
13611 (when (and (memq what '(scheduled deadline))
13612 (or (not time)
13613 (and (stringp time)
13614 (string-match "^[-+]+[0-9]" time))))
13615 ;; Try to get a default date/time from existing timestamp
13616 (save-excursion
13617 (org-back-to-heading t)
13618 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13619 (when (re-search-forward (if (eq what 'scheduled)
13620 org-scheduled-time-regexp
13621 org-deadline-time-regexp)
13622 end t)
13623 (setq ts (match-string 1)
13624 default-time (apply 'encode-time (org-parse-time-string ts))
13625 default-input (and ts (org-get-compact-tod ts)))))))
13626 (when what
13627 (setq time
13628 (if (stringp time)
13629 ;; This is a string (relative or absolute), set
13630 ;; proper date.
13631 (apply #'encode-time
13632 (org-read-date-analyze
13633 time default-time (decode-time default-time)))
13634 ;; If necessary, get the time from the user
13635 (or time (org-read-date nil 'to-time nil nil
13636 default-time default-input)))))
13638 (org-with-wide-buffer
13639 (org-back-to-heading t)
13640 (forward-line)
13641 (unless (bolp) (insert "\n"))
13642 (cond ((looking-at-p org-planning-line-re)
13643 ;; Move to current indentation.
13644 (skip-chars-forward " \t")
13645 ;; Check if we have to remove something.
13646 (dolist (type (if what (cons what remove) remove))
13647 (save-excursion
13648 (when (re-search-forward
13649 (cl-case type
13650 (closed org-closed-time-regexp)
13651 (deadline org-deadline-time-regexp)
13652 (scheduled org-scheduled-time-regexp)
13653 (otherwise
13654 (error "Invalid planning type: %s" type)))
13655 (line-end-position) t)
13656 ;; Delete until next keyword or end of line.
13657 (delete-region
13658 (match-beginning 0)
13659 (if (re-search-forward org-keyword-time-not-clock-regexp
13660 (line-end-position)
13662 (match-beginning 0)
13663 (line-end-position))))))
13664 ;; If there is nothing more to add and no more keyword
13665 ;; is left, remove the line completely.
13666 (if (and (looking-at-p "[ \t]*$") (not what))
13667 (delete-region (line-beginning-position)
13668 (line-beginning-position 2))
13669 ;; If we removed last keyword, do not leave trailing
13670 ;; white space at the end of line.
13671 (let ((p (point)))
13672 (save-excursion
13673 (end-of-line)
13674 (unless (= (skip-chars-backward " \t" p) 0)
13675 (delete-region (point) (line-end-position)))))))
13676 ((not what) (throw 'exit nil)) ; Nothing to do.
13677 (t (insert-before-markers "\n")
13678 (backward-char 1)
13679 (when org-adapt-indentation
13680 (indent-to-column (1+ (org-outline-level))))))
13681 (when what
13682 ;; Insert planning keyword.
13683 (insert (cl-case what
13684 (closed org-closed-string)
13685 (deadline org-deadline-string)
13686 (scheduled org-scheduled-string)
13687 (otherwise (error "Invalid planning type: %s" what)))
13688 " ")
13689 ;; Insert associated timestamp.
13690 (let ((ts (org-insert-time-stamp
13691 time
13692 (or org-time-was-given
13693 (and (eq what 'closed) org-log-done-with-time))
13694 (eq what 'closed)
13695 nil nil (list org-end-time-was-given))))
13696 (unless (eolp) (insert " "))
13697 ts))))))
13699 (defvar org-log-note-marker (make-marker)
13700 "Marker pointing at the entry where the note is to be inserted.")
13701 (defvar org-log-note-purpose nil)
13702 (defvar org-log-note-state nil)
13703 (defvar org-log-note-previous-state nil)
13704 (defvar org-log-note-extra nil)
13705 (defvar org-log-note-window-configuration nil)
13706 (defvar org-log-note-return-to (make-marker))
13707 (defvar org-log-note-effective-time nil
13708 "Remembered current time so that dynamically scoped
13709 `org-extend-today-until' affects timestamps in state change log")
13711 (defvar org-log-post-message nil
13712 "Message to be displayed after a log note has been stored.
13713 The auto-repeater uses this.")
13715 (defun org-add-note ()
13716 "Add a note to the current entry.
13717 This is done in the same way as adding a state change note."
13718 (interactive)
13719 (org-add-log-setup 'note))
13721 (defun org-log-beginning (&optional create)
13722 "Return expected start of log notes in current entry.
13723 When optional argument CREATE is non-nil, the function creates
13724 a drawer to store notes, if necessary. Returned position ignores
13725 narrowing."
13726 (org-with-wide-buffer
13727 (let ((drawer (org-log-into-drawer)))
13728 (cond
13729 (drawer
13730 (org-end-of-meta-data)
13731 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13732 (end (if (org-at-heading-p) (point)
13733 (save-excursion (outline-next-heading) (point))))
13734 (case-fold-search t))
13735 (catch 'exit
13736 ;; Try to find existing drawer.
13737 (while (re-search-forward regexp end t)
13738 (let ((element (org-element-at-point)))
13739 (when (eq (org-element-type element) 'drawer)
13740 (let ((cend (org-element-property :contents-end element)))
13741 (when (and (not org-log-states-order-reversed) cend)
13742 (goto-char cend)))
13743 (throw 'exit nil))))
13744 ;; No drawer found. Create one, if permitted.
13745 (when create
13746 (unless (bolp) (insert "\n"))
13747 (let ((beg (point)))
13748 (insert ":" drawer ":\n:END:\n")
13749 (org-indent-region beg (point)))
13750 (end-of-line -1)))))
13752 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13753 (skip-chars-forward " \t\n")
13754 (beginning-of-line)
13755 (unless org-log-states-order-reversed
13756 (org-skip-over-state-notes)
13757 (skip-chars-backward " \t\n")
13758 (forward-line)))))
13759 (if (bolp) (point) (line-beginning-position 2))))
13761 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13762 "Set up the post command hook to take a note.
13763 If this is about to TODO state change, the new state is expected in STATE.
13764 HOW is an indicator what kind of note should be created.
13765 EXTRA is additional text that will be inserted into the notes buffer."
13766 (move-marker org-log-note-marker (point))
13767 (setq org-log-note-purpose purpose
13768 org-log-note-state state
13769 org-log-note-previous-state prev-state
13770 org-log-note-how how
13771 org-log-note-extra extra
13772 org-log-note-effective-time (org-current-effective-time))
13773 (add-hook 'post-command-hook 'org-add-log-note 'append))
13775 (defun org-skip-over-state-notes ()
13776 "Skip past the list of State notes in an entry."
13777 (when (ignore-errors (goto-char (org-in-item-p)))
13778 (let* ((struct (org-list-struct))
13779 (prevs (org-list-prevs-alist struct))
13780 (regexp
13781 (concat "[ \t]*- +"
13782 (replace-regexp-in-string
13783 " +" " +"
13784 (org-replace-escapes
13785 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13786 `(("%d" . ,org-ts-regexp-inactive)
13787 ("%D" . ,org-ts-regexp)
13788 ("%s" . "\"\\S-+\"")
13789 ("%S" . "\"\\S-+\"")
13790 ("%t" . ,org-ts-regexp-inactive)
13791 ("%T" . ,org-ts-regexp)
13792 ("%u" . ".*?")
13793 ("%U" . ".*?")))))))
13794 (while (looking-at-p regexp)
13795 (goto-char (or (org-list-get-next-item (point) struct prevs)
13796 (org-list-get-item-end (point) struct)))))))
13798 (defun org-add-log-note (&optional _purpose)
13799 "Pop up a window for taking a note, and add this note later."
13800 (remove-hook 'post-command-hook 'org-add-log-note)
13801 (setq org-log-note-window-configuration (current-window-configuration))
13802 (delete-other-windows)
13803 (move-marker org-log-note-return-to (point))
13804 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13805 (goto-char org-log-note-marker)
13806 (org-switch-to-buffer-other-window "*Org Note*")
13807 (erase-buffer)
13808 (if (memq org-log-note-how '(time state))
13809 (let (current-prefix-arg) (org-store-log-note))
13810 (let ((org-inhibit-startup t)) (org-mode))
13811 (insert (format "# Insert note for %s.
13812 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13813 (cond
13814 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13815 ((eq org-log-note-purpose 'done) "closed todo item")
13816 ((eq org-log-note-purpose 'state)
13817 (format "state change from \"%s\" to \"%s\""
13818 (or org-log-note-previous-state "")
13819 (or org-log-note-state "")))
13820 ((eq org-log-note-purpose 'reschedule)
13821 "rescheduling")
13822 ((eq org-log-note-purpose 'delschedule)
13823 "no longer scheduled")
13824 ((eq org-log-note-purpose 'redeadline)
13825 "changing deadline")
13826 ((eq org-log-note-purpose 'deldeadline)
13827 "removing deadline")
13828 ((eq org-log-note-purpose 'refile)
13829 "refiling")
13830 ((eq org-log-note-purpose 'note)
13831 "this entry")
13832 (t (error "This should not happen")))))
13833 (when org-log-note-extra (insert org-log-note-extra))
13834 (setq-local org-finish-function 'org-store-log-note)
13835 (run-hooks 'org-log-buffer-setup-hook)))
13837 (defvar org-note-abort nil) ; dynamically scoped
13838 (defun org-store-log-note ()
13839 "Finish taking a log note, and insert it to where it belongs."
13840 (let ((txt (prog1 (buffer-string)
13841 (kill-buffer)))
13842 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13843 lines)
13844 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13845 (setq txt (replace-match "" t t txt)))
13846 (when (string-match "\\s-+\\'" txt)
13847 (setq txt (replace-match "" t t txt)))
13848 (setq lines (org-split-string txt "\n"))
13849 (when (org-string-nw-p note)
13850 (setq note
13851 (org-replace-escapes
13852 note
13853 (list (cons "%u" (user-login-name))
13854 (cons "%U" user-full-name)
13855 (cons "%t" (format-time-string
13856 (org-time-stamp-format 'long 'inactive)
13857 org-log-note-effective-time))
13858 (cons "%T" (format-time-string
13859 (org-time-stamp-format 'long nil)
13860 org-log-note-effective-time))
13861 (cons "%d" (format-time-string
13862 (org-time-stamp-format nil 'inactive)
13863 org-log-note-effective-time))
13864 (cons "%D" (format-time-string
13865 (org-time-stamp-format nil nil)
13866 org-log-note-effective-time))
13867 (cons "%s" (cond
13868 ((not org-log-note-state) "")
13869 ((string-match-p org-ts-regexp
13870 org-log-note-state)
13871 (format "\"[%s]\""
13872 (substring org-log-note-state 1 -1)))
13873 (t (format "\"%s\"" org-log-note-state))))
13874 (cons "%S"
13875 (cond
13876 ((not org-log-note-previous-state) "")
13877 ((string-match-p org-ts-regexp
13878 org-log-note-previous-state)
13879 (format "\"[%s]\""
13880 (substring
13881 org-log-note-previous-state 1 -1)))
13882 (t (format "\"%s\""
13883 org-log-note-previous-state)))))))
13884 (when lines (setq note (concat note " \\\\")))
13885 (push note lines))
13886 (when (and lines (not (or current-prefix-arg org-note-abort)))
13887 (with-current-buffer (marker-buffer org-log-note-marker)
13888 (org-with-wide-buffer
13889 ;; Find location for the new note.
13890 (goto-char org-log-note-marker)
13891 (set-marker org-log-note-marker nil)
13892 (goto-char (org-log-beginning t))
13893 ;; Make sure point is at the beginning of an empty line.
13894 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13895 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13896 ;; In an existing list, add a new item at the top level.
13897 ;; Otherwise, indent line like a regular one.
13898 (let ((itemp (org-in-item-p)))
13899 (if itemp
13900 (indent-line-to
13901 (let ((struct (save-excursion
13902 (goto-char itemp) (org-list-struct))))
13903 (org-list-get-ind (org-list-get-top-point struct) struct)))
13904 (org-indent-line)))
13905 (insert (org-list-bullet-string "-") (pop lines))
13906 (let ((ind (org-list-item-body-column (line-beginning-position))))
13907 (dolist (line lines)
13908 (insert "\n")
13909 (indent-line-to ind)
13910 (insert line)))
13911 (message "Note stored")
13912 (org-back-to-heading t)
13913 (org-cycle-hide-drawers 'children))
13914 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13915 ;; from within `org-add-log-note' because `buffer-undo-list'
13916 ;; is then modified outside of `org-with-remote-undo'.
13917 (when (eq this-command 'org-agenda-todo)
13918 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13919 ;; Don't add undo information when called from `org-agenda-todo'.
13920 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13921 (set-window-configuration org-log-note-window-configuration)
13922 (with-current-buffer (marker-buffer org-log-note-return-to)
13923 (goto-char org-log-note-return-to))
13924 (move-marker org-log-note-return-to nil)
13925 (when org-log-post-message (message "%s" org-log-post-message))))
13927 (defun org-remove-empty-drawer-at (pos)
13928 "Remove an empty drawer at position POS.
13929 POS may also be a marker."
13930 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13931 (org-with-wide-buffer
13932 (goto-char pos)
13933 (let ((drawer (org-element-at-point)))
13934 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13935 (not (org-element-property :contents-begin drawer)))
13936 (delete-region (org-element-property :begin drawer)
13937 (progn (goto-char (org-element-property :end drawer))
13938 (skip-chars-backward " \r\t\n")
13939 (forward-line)
13940 (point))))))))
13942 (defvar org-ts-type nil)
13943 (defun org-sparse-tree (&optional arg type)
13944 "Create a sparse tree, prompt for the details.
13945 This command can create sparse trees. You first need to select the type
13946 of match used to create the tree:
13948 t Show all TODO entries.
13949 T Show entries with a specific TODO keyword.
13950 m Show entries selected by a tags/property match.
13951 p Enter a property name and its value (both with completion on existing
13952 names/values) and show entries with that property.
13953 r Show entries matching a regular expression (`/' can be used as well).
13954 b Show deadlines and scheduled items before a date.
13955 a Show deadlines and scheduled items after a date.
13956 d Show deadlines due within `org-deadline-warning-days'.
13957 D Show deadlines and scheduled items between a date range."
13958 (interactive "P")
13959 (setq type (or type org-sparse-tree-default-date-type))
13960 (setq org-ts-type type)
13961 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13962 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13963 \[c]ycle through date types: %s"
13964 (cl-case type
13965 (all "all timestamps")
13966 (scheduled "only scheduled")
13967 (deadline "only deadline")
13968 (active "only active timestamps")
13969 (inactive "only inactive timestamps")
13970 (closed "with a closed time-stamp")
13971 (otherwise "scheduled/deadline")))
13972 (let ((answer (read-char-exclusive)))
13973 (cl-case answer
13975 (org-sparse-tree
13977 (cadr
13978 (memq type '(nil all scheduled deadline active inactive closed)))))
13979 (?d (call-interactively 'org-check-deadlines))
13980 (?b (call-interactively 'org-check-before-date))
13981 (?a (call-interactively 'org-check-after-date))
13982 (?D (call-interactively 'org-check-dates-range))
13983 (?t (call-interactively 'org-show-todo-tree))
13984 (?T (org-show-todo-tree '(4)))
13985 (?m (call-interactively 'org-match-sparse-tree))
13986 ((?p ?P)
13987 (let* ((kwd (completing-read
13988 "Property: " (mapcar #'list (org-buffer-property-keys))))
13989 (value (completing-read
13990 "Value: " (mapcar #'list (org-property-values kwd)))))
13991 (unless (string-match "\\`{.*}\\'" value)
13992 (setq value (concat "\"" value "\"")))
13993 (org-match-sparse-tree arg (concat kwd "=" value))))
13994 ((?r ?R ?/) (call-interactively 'org-occur))
13995 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13997 (defvar-local org-occur-highlights nil
13998 "List of overlays used for occur matches.")
13999 (defvar-local org-occur-parameters nil
14000 "Parameters of the active org-occur calls.
14001 This is a list, each call to org-occur pushes as cons cell,
14002 containing the regular expression and the callback, onto the list.
14003 The list can contain several entries if `org-occur' has been called
14004 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14005 will only contain one set of parameters. When the highlights are
14006 removed (for example with `C-c C-c', or with the next edit (depending
14007 on `org-remove-highlights-with-change'), this variable is emptied
14008 as well.")
14010 (defun org-occur (regexp &optional keep-previous callback)
14011 "Make a compact tree which shows all matches of REGEXP.
14013 The tree will show the lines where the regexp matches, and any other context
14014 defined in `org-show-context-detail', which see.
14016 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14017 done by a previous call to `org-occur' will be kept, to allow stacking of
14018 calls to this command.
14020 Optional argument CALLBACK can be a function of no argument. In this case,
14021 it is called with point at the end of the match, match data being set
14022 accordingly. Current match is shown only if the return value is non-nil.
14023 The function must neither move point nor alter narrowing."
14024 (interactive "sRegexp: \nP")
14025 (when (equal regexp "")
14026 (user-error "Regexp cannot be empty"))
14027 (unless keep-previous
14028 (org-remove-occur-highlights nil nil t))
14029 (push (cons regexp callback) org-occur-parameters)
14030 (let ((cnt 0))
14031 (save-excursion
14032 (goto-char (point-min))
14033 (when (or (not keep-previous) ; do not want to keep
14034 (not org-occur-highlights)) ; no previous matches
14035 ;; hide everything
14036 (org-overview))
14037 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14038 (isearch-no-upper-case-p regexp t)
14039 org-occur-case-fold-search)))
14040 (while (re-search-forward regexp nil t)
14041 (when (or (not callback)
14042 (save-match-data (funcall callback)))
14043 (setq cnt (1+ cnt))
14044 (when org-highlight-sparse-tree-matches
14045 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14046 (org-show-context 'occur-tree)))))
14047 (when org-remove-highlights-with-change
14048 (add-hook 'before-change-functions 'org-remove-occur-highlights
14049 nil 'local))
14050 (unless org-sparse-tree-open-archived-trees
14051 (org-hide-archived-subtrees (point-min) (point-max)))
14052 (run-hooks 'org-occur-hook)
14053 (when (called-interactively-p 'interactive)
14054 (message "%d match(es) for regexp %s" cnt regexp))
14055 cnt))
14057 (defun org-occur-next-match (&optional n _reset)
14058 "Function for `next-error-function' to find sparse tree matches.
14059 N is the number of matches to move, when negative move backwards.
14060 This function always goes back to the starting point when no
14061 match is found."
14062 (let* ((limit (if (< n 0) (point-min) (point-max)))
14063 (search-func (if (< n 0)
14064 'previous-single-char-property-change
14065 'next-single-char-property-change))
14066 (n (abs n))
14067 (pos (point))
14069 (catch 'exit
14070 (while (setq p1 (funcall search-func (point) 'org-type))
14071 (when (equal p1 limit)
14072 (goto-char pos)
14073 (user-error "No more matches"))
14074 (when (equal (get-char-property p1 'org-type) 'org-occur)
14075 (setq n (1- n))
14076 (when (= n 0)
14077 (goto-char p1)
14078 (throw 'exit (point))))
14079 (goto-char p1))
14080 (goto-char p1)
14081 (user-error "No more matches"))))
14083 (defun org-show-context (&optional key)
14084 "Make sure point and context are visible.
14085 Optional argument KEY, when non-nil, is a symbol. See
14086 `org-show-context-detail' for allowed values and how much is to
14087 be shown."
14088 (org-show-set-visibility
14089 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14090 ((cdr (assq key org-show-context-detail)))
14091 (t (cdr (assq 'default org-show-context-detail))))))
14093 (defun org-show-set-visibility (detail)
14094 "Set visibility around point according to DETAIL.
14095 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14096 `tree', `canonical' or t. See `org-show-context-detail' for more
14097 information."
14098 ;; Show current heading and possibly its entry, following headline
14099 ;; or all children.
14100 (if (and (org-at-heading-p) (not (eq detail 'local)))
14101 (org-flag-heading nil)
14102 (org-show-entry)
14103 ;; If point is hidden within a drawer or a block, make sure to
14104 ;; expose it.
14105 (dolist (o (overlays-at (point)))
14106 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14107 (delete-overlay o)))
14108 (unless (org-before-first-heading-p)
14109 (org-with-limited-levels
14110 (cl-case detail
14111 ((tree canonical t) (org-show-children))
14112 ((nil minimal ancestors))
14113 (t (save-excursion
14114 (outline-next-heading)
14115 (org-flag-heading nil)))))))
14116 ;; Show all siblings.
14117 (when (eq detail 'lineage) (org-show-siblings))
14118 ;; Show ancestors, possibly with their children.
14119 (when (memq detail '(ancestors lineage tree canonical t))
14120 (save-excursion
14121 (while (org-up-heading-safe)
14122 (org-flag-heading nil)
14123 (when (memq detail '(canonical t)) (org-show-entry))
14124 (when (memq detail '(tree canonical t)) (org-show-children))))))
14126 (defvar org-reveal-start-hook nil
14127 "Hook run before revealing a location.")
14129 (defun org-reveal (&optional siblings)
14130 "Show current entry, hierarchy above it, and the following headline.
14132 This can be used to show a consistent set of context around
14133 locations exposed with `org-show-context'.
14135 With optional argument SIBLINGS, on each level of the hierarchy all
14136 siblings are shown. This repairs the tree structure to what it would
14137 look like when opened with hierarchical calls to `org-cycle'.
14139 With double optional argument \\[universal-argument] \\[universal-argument], \
14140 go to the parent and show the
14141 entire tree."
14142 (interactive "P")
14143 (run-hooks 'org-reveal-start-hook)
14144 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14145 ((equal siblings '(16))
14146 (save-excursion
14147 (when (org-up-heading-safe)
14148 (org-show-subtree)
14149 (run-hook-with-args 'org-cycle-hook 'subtree))))
14150 (t (org-show-set-visibility 'lineage))))
14152 (defun org-highlight-new-match (beg end)
14153 "Highlight from BEG to END and mark the highlight is an occur headline."
14154 (let ((ov (make-overlay beg end)))
14155 (overlay-put ov 'face 'secondary-selection)
14156 (overlay-put ov 'org-type 'org-occur)
14157 (push ov org-occur-highlights)))
14159 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14160 "Remove the occur highlights from the buffer.
14161 BEG and END are ignored. If NOREMOVE is nil, remove this function
14162 from the `before-change-functions' in the current buffer."
14163 (interactive)
14164 (unless org-inhibit-highlight-removal
14165 (mapc #'delete-overlay org-occur-highlights)
14166 (setq org-occur-highlights nil)
14167 (setq org-occur-parameters nil)
14168 (unless noremove
14169 (remove-hook 'before-change-functions
14170 'org-remove-occur-highlights 'local))))
14172 ;;;; Priorities
14174 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14175 "Regular expression matching the priority indicator.")
14177 (defvar org-remove-priority-next-time nil)
14179 (defun org-priority-up ()
14180 "Increase the priority of the current item."
14181 (interactive)
14182 (org-priority 'up))
14184 (defun org-priority-down ()
14185 "Decrease the priority of the current item."
14186 (interactive)
14187 (org-priority 'down))
14189 (defun org-priority (&optional action _show)
14190 "Change the priority of an item.
14191 ACTION can be `set', `up', `down', or a character."
14192 (interactive "P")
14193 (if (equal action '(4))
14194 (org-show-priority)
14195 (unless org-enable-priority-commands
14196 (user-error "Priority commands are disabled"))
14197 (setq action (or action 'set))
14198 (let (current new news have remove)
14199 (save-excursion
14200 (org-back-to-heading t)
14201 (when (looking-at org-priority-regexp)
14202 (setq current (string-to-char (match-string 2))
14203 have t))
14204 (cond
14205 ((eq action 'remove)
14206 (setq remove t new ?\ ))
14207 ((or (eq action 'set)
14208 (integerp action))
14209 (if (not (eq action 'set))
14210 (setq new action)
14211 (message "Priority %c-%c, SPC to remove: "
14212 org-highest-priority org-lowest-priority)
14213 (save-match-data
14214 (setq new (read-char-exclusive))))
14215 (when (and (= (upcase org-highest-priority) org-highest-priority)
14216 (= (upcase org-lowest-priority) org-lowest-priority))
14217 (setq new (upcase new)))
14218 (cond ((equal new ?\ ) (setq remove t))
14219 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14220 (user-error "Priority must be between `%c' and `%c'"
14221 org-highest-priority org-lowest-priority))))
14222 ((eq action 'up)
14223 (setq new (if have
14224 (1- current) ; normal cycling
14225 ;; last priority was empty
14226 (if (eq last-command this-command)
14227 org-lowest-priority ; wrap around empty to lowest
14228 ;; default
14229 (if org-priority-start-cycle-with-default
14230 org-default-priority
14231 (1- org-default-priority))))))
14232 ((eq action 'down)
14233 (setq new (if have
14234 (1+ current) ; normal cycling
14235 ;; last priority was empty
14236 (if (eq last-command this-command)
14237 org-highest-priority ; wrap around empty to highest
14238 ;; default
14239 (if org-priority-start-cycle-with-default
14240 org-default-priority
14241 (1+ org-default-priority))))))
14242 (t (user-error "Invalid action")))
14243 (when (or (< (upcase new) org-highest-priority)
14244 (> (upcase new) org-lowest-priority))
14245 (if (and (memq action '(up down))
14246 (not have) (not (eq last-command this-command)))
14247 ;; `new' is from default priority
14248 (error
14249 "The default can not be set, see `org-default-priority' why")
14250 ;; normal cycling: `new' is beyond highest/lowest priority
14251 ;; and is wrapped around to the empty priority
14252 (setq remove t)))
14253 (setq news (format "%c" new))
14254 (if have
14255 (if remove
14256 (replace-match "" t t nil 1)
14257 (replace-match news t t nil 2))
14258 (if remove
14259 (user-error "No priority cookie found in line")
14260 (let ((case-fold-search nil))
14261 (looking-at org-todo-line-regexp))
14262 (if (match-end 2)
14263 (progn
14264 (goto-char (match-end 2))
14265 (insert " [#" news "]"))
14266 (goto-char (match-beginning 3))
14267 (insert "[#" news "] "))))
14268 (org-set-tags nil 'align))
14269 (if remove
14270 (message "Priority removed")
14271 (message "Priority of current item set to %s" news)))))
14273 (defun org-show-priority ()
14274 "Show the priority of the current item.
14275 This priority is composed of the main priority given with the [#A] cookies,
14276 and by additional input from the age of a schedules or deadline entry."
14277 (interactive)
14278 (let ((pri (if (eq major-mode 'org-agenda-mode)
14279 (org-get-at-bol 'priority)
14280 (save-excursion
14281 (save-match-data
14282 (beginning-of-line)
14283 (and (looking-at org-heading-regexp)
14284 (org-get-priority (match-string 0))))))))
14285 (message "Priority is %d" (if pri pri -1000))))
14287 (defun org-get-priority (s)
14288 "Find priority cookie and return priority."
14289 (save-match-data
14290 (if (functionp org-get-priority-function)
14291 (funcall org-get-priority-function)
14292 (if (not (string-match org-priority-regexp s))
14293 (* 1000 (- org-lowest-priority org-default-priority))
14294 (* 1000 (- org-lowest-priority
14295 (string-to-char (match-string 2 s))))))))
14297 ;;;; Tags
14299 (defvar org-agenda-archives-mode)
14300 (defvar org-map-continue-from nil
14301 "Position from where mapping should continue.
14302 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14304 (defvar org-scanner-tags nil
14305 "The current tag list while the tags scanner is running.")
14307 (defvar org-trust-scanner-tags nil
14308 "Should `org-get-tags-at' use the tags for the scanner.
14309 This is for internal dynamical scoping only.
14310 When this is non-nil, the function `org-get-tags-at' will return the value
14311 of `org-scanner-tags' instead of building the list by itself. This
14312 can lead to large speed-ups when the tags scanner is used in a file with
14313 many entries, and when the list of tags is retrieved, for example to
14314 obtain a list of properties. Building the tags list for each entry in such
14315 a file becomes an N^2 operation - but with this variable set, it scales
14316 as N.")
14318 (defvar org--matcher-tags-todo-only nil)
14320 (defun org-scan-tags (action matcher todo-only &optional start-level)
14321 "Scan headline tags with inheritance and produce output ACTION.
14323 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14324 or `agenda' to produce an entry list for an agenda view. It can also be
14325 a Lisp form or a function that should be called at each matched headline, in
14326 this case the return value is a list of all return values from these calls.
14328 MATCHER is a function accepting three arguments, returning
14329 a non-nil value whenever a given set of tags qualifies a headline
14330 for inclusion. See `org-make-tags-matcher' for more information.
14331 As a special case, it can also be set to t (respectively nil) in
14332 order to match all (respectively none) headline.
14334 When TODO-ONLY is non-nil, only lines with a not-done TODO
14335 keyword are included in the output.
14337 START-LEVEL can be a string with asterisks, reducing the scope to
14338 headlines matching this string."
14339 (require 'org-agenda)
14340 (let* ((re (concat "^"
14341 (if start-level
14342 ;; Get the correct level to match
14343 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14344 org-outline-regexp)
14345 " *\\(\\<\\("
14346 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14347 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14348 (props (list 'face 'default
14349 'done-face 'org-agenda-done
14350 'undone-face 'default
14351 'mouse-face 'highlight
14352 'org-not-done-regexp org-not-done-regexp
14353 'org-todo-regexp org-todo-regexp
14354 'org-complex-heading-regexp org-complex-heading-regexp
14355 'help-echo
14356 (format "mouse-2 or RET jump to org file %s"
14357 (abbreviate-file-name
14358 (or (buffer-file-name (buffer-base-buffer))
14359 (buffer-name (buffer-base-buffer)))))))
14360 (org-map-continue-from nil)
14361 lspos tags tags-list
14362 (tags-alist (list (cons 0 org-file-tags)))
14363 (llast 0) rtn rtn1 level category i txt
14364 todo marker entry priority
14365 ts-date ts-date-type ts-date-pair)
14366 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14367 (setq action (list 'lambda nil action)))
14368 (save-excursion
14369 (goto-char (point-min))
14370 (when (eq action 'sparse-tree)
14371 (org-overview)
14372 (org-remove-occur-highlights))
14373 (while (let (case-fold-search)
14374 (re-search-forward re nil t))
14375 (setq org-map-continue-from nil)
14376 (catch :skip
14377 (setq todo
14378 ;; TODO: is the 1-2 difference a bug?
14379 (when (match-end 1) (match-string-no-properties 2))
14380 tags (when (match-end 4) (match-string-no-properties 4)))
14381 (goto-char (setq lspos (match-beginning 0)))
14382 (setq level (org-reduced-level (org-outline-level))
14383 category (org-get-category))
14384 (when (eq action 'agenda)
14385 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14386 ts-date (car ts-date-pair)
14387 ts-date-type (cdr ts-date-pair)))
14388 (setq i llast llast level)
14389 ;; remove tag lists from same and sublevels
14390 (while (>= i level)
14391 (when (setq entry (assoc i tags-alist))
14392 (setq tags-alist (delete entry tags-alist)))
14393 (setq i (1- i)))
14394 ;; add the next tags
14395 (when tags
14396 (setq tags (org-split-string tags ":")
14397 tags-alist
14398 (cons (cons level tags) tags-alist)))
14399 ;; compile tags for current headline
14400 (setq tags-list
14401 (if org-use-tag-inheritance
14402 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14403 tags)
14404 org-scanner-tags tags-list)
14405 (when org-use-tag-inheritance
14406 (setcdr (car tags-alist)
14407 (mapcar (lambda (x)
14408 (setq x (copy-sequence x))
14409 (org-add-prop-inherited x))
14410 (cdar tags-alist))))
14411 (when (and tags org-use-tag-inheritance
14412 (or (not (eq t org-use-tag-inheritance))
14413 org-tags-exclude-from-inheritance))
14414 ;; Selective inheritance, remove uninherited ones.
14415 (setcdr (car tags-alist)
14416 (org-remove-uninherited-tags (cdar tags-alist))))
14417 (when (and
14419 ;; eval matcher only when the todo condition is OK
14420 (and (or (not todo-only) (member todo org-not-done-keywords))
14421 (if (functionp matcher)
14422 (let ((case-fold-search t) (org-trust-scanner-tags t))
14423 (funcall matcher todo tags-list level))
14424 matcher))
14426 ;; Call the skipper, but return t if it does not
14427 ;; skip, so that the `and' form continues evaluating.
14428 (progn
14429 (unless (eq action 'sparse-tree) (org-agenda-skip))
14432 ;; Check if timestamps are deselecting this entry
14433 (or (not todo-only)
14434 (and (member todo org-not-done-keywords)
14435 (or (not org-agenda-tags-todo-honor-ignore-options)
14436 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14438 ;; select this headline
14439 (cond
14440 ((eq action 'sparse-tree)
14441 (and org-highlight-sparse-tree-matches
14442 (org-get-heading) (match-end 0)
14443 (org-highlight-new-match
14444 (match-beginning 1) (match-end 1)))
14445 (org-show-context 'tags-tree))
14446 ((eq action 'agenda)
14447 (setq txt (org-agenda-format-item
14449 (concat
14450 (if (eq org-tags-match-list-sublevels 'indented)
14451 (make-string (1- level) ?.) "")
14452 (org-get-heading))
14453 (make-string level ?\s)
14454 category
14455 tags-list)
14456 priority (org-get-priority txt))
14457 (goto-char lspos)
14458 (setq marker (org-agenda-new-marker))
14459 (org-add-props txt props
14460 'org-marker marker 'org-hd-marker marker 'org-category category
14461 'todo-state todo
14462 'ts-date ts-date
14463 'priority priority
14464 'type (concat "tagsmatch" ts-date-type))
14465 (push txt rtn))
14466 ((functionp action)
14467 (setq org-map-continue-from nil)
14468 (save-excursion
14469 (setq rtn1 (funcall action))
14470 (push rtn1 rtn)))
14471 (t (user-error "Invalid action")))
14473 ;; if we are to skip sublevels, jump to end of subtree
14474 (unless org-tags-match-list-sublevels
14475 (org-end-of-subtree t)
14476 (backward-char 1))))
14477 ;; Get the correct position from where to continue
14478 (if org-map-continue-from
14479 (goto-char org-map-continue-from)
14480 (and (= (point) lspos) (end-of-line 1)))))
14481 (when (and (eq action 'sparse-tree)
14482 (not org-sparse-tree-open-archived-trees))
14483 (org-hide-archived-subtrees (point-min) (point-max)))
14484 (nreverse rtn)))
14486 (defun org-remove-uninherited-tags (tags)
14487 "Remove all tags that are not inherited from the list TAGS."
14488 (cond
14489 ((eq org-use-tag-inheritance t)
14490 (if org-tags-exclude-from-inheritance
14491 (org-delete-all org-tags-exclude-from-inheritance tags)
14492 tags))
14493 ((not org-use-tag-inheritance) nil)
14494 ((stringp org-use-tag-inheritance)
14495 (delq nil (mapcar
14496 (lambda (x)
14497 (if (and (string-match org-use-tag-inheritance x)
14498 (not (member x org-tags-exclude-from-inheritance)))
14499 x nil))
14500 tags)))
14501 ((listp org-use-tag-inheritance)
14502 (delq nil (mapcar
14503 (lambda (x)
14504 (if (member x org-use-tag-inheritance) x nil))
14505 tags)))))
14507 (defun org-match-sparse-tree (&optional todo-only match)
14508 "Create a sparse tree according to tags string MATCH.
14509 MATCH can contain positive and negative selection of tags, like
14510 \"+WORK+URGENT-WITHBOSS\".
14511 If optional argument TODO-ONLY is non-nil, only select lines that are
14512 also TODO lines."
14513 (interactive "P")
14514 (org-agenda-prepare-buffers (list (current-buffer)))
14515 (let ((org--matcher-tags-todo-only todo-only))
14516 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14517 org--matcher-tags-todo-only)))
14519 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14521 (defvar org-cached-props nil)
14522 (defun org-cached-entry-get (pom property)
14523 (if (or (eq t org-use-property-inheritance)
14524 (and (stringp org-use-property-inheritance)
14525 (let ((case-fold-search t))
14526 (string-match-p org-use-property-inheritance property)))
14527 (and (listp org-use-property-inheritance)
14528 (member-ignore-case property org-use-property-inheritance)))
14529 ;; Caching is not possible, check it directly.
14530 (org-entry-get pom property 'inherit)
14531 ;; Get all properties, so we can do complicated checks easily.
14532 (cdr (assoc-string property
14533 (or org-cached-props
14534 (setq org-cached-props (org-entry-properties pom)))
14535 t))))
14537 (defun org-global-tags-completion-table (&optional files)
14538 "Return the list of all tags in all agenda buffer/files.
14539 Optional FILES argument is a list of files which can be used
14540 instead of the agenda files."
14541 (save-excursion
14542 (org-uniquify
14543 (delq nil
14544 (apply #'append
14545 (mapcar
14546 (lambda (file)
14547 (set-buffer (find-file-noselect file))
14548 (mapcar (lambda (x)
14549 (and (stringp (car-safe x))
14550 (list (car-safe x))))
14551 (or org-current-tag-alist (org-get-buffer-tags))))
14552 (if (car-safe files) files
14553 (org-agenda-files))))))))
14555 (defun org-make-tags-matcher (match)
14556 "Create the TAGS/TODO matcher form for the selection string MATCH.
14558 Returns a cons of the selection string MATCH and a function
14559 implementing the matcher.
14561 The matcher is to be called at an Org entry, with point on the
14562 headline, and returns non-nil if the entry matches the selection
14563 string MATCH. It must be called with three arguments: the TODO
14564 keyword at the entry (or nil if none), the list of all tags at
14565 the entry including inherited ones and the reduced level of the
14566 headline. Additionally, the category of the entry, if any, must
14567 be specified as the text property `org-category' on the headline.
14569 This function sets the variable `org--matcher-tags-todo-only' to
14570 a non-nil value if the matcher restricts matching to TODO
14571 entries, otherwise it is not touched.
14573 See also `org-scan-tags'."
14574 (unless match
14575 ;; Get a new match request, with completion against the global
14576 ;; tags table and the local tags in current buffer.
14577 (let ((org-last-tags-completion-table
14578 (org-uniquify
14579 (delq nil (append (org-get-buffer-tags)
14580 (org-global-tags-completion-table))))))
14581 (setq match
14582 (completing-read
14583 "Match: "
14584 'org-tags-completion-function nil nil nil 'org-tags-history))))
14586 (let ((match0 match)
14587 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14588 (start 0)
14589 tagsmatch todomatch tagsmatcher todomatcher)
14591 ;; Expand group tags.
14592 (setq match (org-tags-expand match))
14594 ;; Check if there is a TODO part of this match, which would be the
14595 ;; part after a "/". To make sure that this slash is not part of
14596 ;; a property value to be matched against, we also check that
14597 ;; there is no / after that slash. First, find the last slash.
14598 (let ((s 0))
14599 (while (string-match "/+" match s)
14600 (setq start (match-beginning 0))
14601 (setq s (match-end 0))))
14602 (if (and (string-match "/+" match start)
14603 (not (string-match-p "\"" match start)))
14604 ;; Match contains also a TODO-matching request.
14605 (progn
14606 (setq tagsmatch (substring match 0 (match-beginning 0)))
14607 (setq todomatch (substring match (match-end 0)))
14608 (when (string-match "\\`!" todomatch)
14609 (setq org--matcher-tags-todo-only t)
14610 (setq todomatch (substring todomatch 1)))
14611 (when (string-match "\\`\\s-*\\'" todomatch)
14612 (setq todomatch nil)))
14613 ;; Only matching tags.
14614 (setq tagsmatch match)
14615 (setq todomatch nil))
14617 ;; Make the tags matcher.
14618 (when (org-string-nw-p tagsmatch)
14619 (let ((orlist nil)
14620 (orterms (org-split-string tagsmatch "|"))
14621 term)
14622 (while (setq term (pop orterms))
14623 (while (and (equal (substring term -1) "\\") orterms)
14624 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14625 (while (string-match re term)
14626 (let* ((rest (substring term (match-end 0)))
14627 (minus (and (match-end 1)
14628 (equal (match-string 1 term) "-")))
14629 (tag (save-match-data
14630 (replace-regexp-in-string
14631 "\\\\-" "-" (match-string 2 term))))
14632 (regexp (eq (string-to-char tag) ?{))
14633 (levelp (match-end 4))
14634 (propp (match-end 5))
14636 (cond
14637 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14638 (levelp
14639 `(,(org-op-to-function (match-string 3 term))
14640 level
14641 ,(string-to-number (match-string 4 term))))
14642 (propp
14643 (let* ((gv (pcase (upcase (match-string 5 term))
14644 ("CATEGORY"
14645 '(get-text-property (point) 'org-category))
14646 ("TODO" 'todo)
14647 (p `(org-cached-entry-get nil ,p))))
14648 (pv (match-string 7 term))
14649 (regexp (eq (string-to-char pv) ?{))
14650 (strp (eq (string-to-char pv) ?\"))
14651 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14652 (po (org-op-to-function (match-string 6 term)
14653 (if timep 'time strp))))
14654 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14655 (when timep (setq pv (org-matcher-time pv)))
14656 (cond ((and regexp (eq po 'org<>))
14657 `(not (string-match ,pv (or ,gv ""))))
14658 (regexp `(string-match ,pv (or ,gv "")))
14659 (strp `(,po (or ,gv "") ,pv))
14661 `(,po
14662 (string-to-number (or ,gv ""))
14663 ,(string-to-number pv))))))
14664 (t `(member ,tag tags-list)))))
14665 (push (if minus `(not ,mm) mm) tagsmatcher)
14666 (setq term rest)))
14667 (push `(and ,@tagsmatcher) orlist)
14668 (setq tagsmatcher nil))
14669 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14671 ;; Make the TODO matcher.
14672 (when (org-string-nw-p todomatch)
14673 (let ((orlist nil))
14674 (dolist (term (org-split-string todomatch "|"))
14675 (while (string-match re term)
14676 (let* ((minus (and (match-end 1)
14677 (equal (match-string 1 term) "-")))
14678 (kwd (match-string 2 term))
14679 (regexp (eq (string-to-char kwd) ?{))
14680 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14681 `(equal todo ,kwd))))
14682 (push (if minus `(not ,mm) mm) todomatcher))
14683 (setq term (substring term (match-end 0))))
14684 (push (if (> (length todomatcher) 1)
14685 (cons 'and todomatcher)
14686 (car todomatcher))
14687 orlist)
14688 (setq todomatcher nil))
14689 (setq todomatcher (cons 'or orlist))))
14691 ;; Return the string and function of the matcher. If no
14692 ;; tags-specific or todo-specific matcher exists, match
14693 ;; everything.
14694 (let ((matcher (if (and tagsmatcher todomatcher)
14695 `(and ,tagsmatcher ,todomatcher)
14696 (or tagsmatcher todomatcher t))))
14697 (when org--matcher-tags-todo-only
14698 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14699 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14701 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14702 "Expand group tags in MATCH.
14704 This replaces every group tag in MATCH with a regexp tag search.
14705 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14706 will be replaced like this:
14708 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14709 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14710 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14712 Replacing by a regexp preserves the structure of the match.
14713 E.g., this expansion
14715 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14717 will match anything tagged with \"Lab\" and \"Home\", or tagged
14718 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14720 A group tag in MATCH can contain regular expressions of its own.
14721 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14722 will be replaced like this:
14724 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14726 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14727 assumed to be a single group tag, and the function will return
14728 the list of tags in this group.
14730 When DOWNCASE is non-nil, expand downcased TAGS."
14731 (if org-group-tags
14732 (let* ((case-fold-search t)
14733 (stable org-mode-syntax-table)
14734 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14735 (taggroups (if downcased
14736 (mapcar (lambda (tg) (mapcar #'downcase tg))
14737 taggroups)
14738 taggroups))
14739 (taggroups-keys (mapcar #'car taggroups))
14740 (return-match (if downcased (downcase match) match))
14741 (count 0)
14742 (work-already-expanded tags-already-expanded)
14743 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14744 ;; @ and _ are allowed as word-components in tags.
14745 (modify-syntax-entry ?@ "w" stable)
14746 (modify-syntax-entry ?_ "w" stable)
14747 ;; Temporarily replace regexp-expressions in the match-expression.
14748 (while (string-match "{.+?}" return-match)
14749 (cl-incf count)
14750 (push (match-string 0 return-match) regexps-in-match)
14751 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14752 (while (and taggroups-keys
14753 (with-syntax-table stable
14754 (string-match
14755 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14756 (regexp-opt taggroups-keys) "\\>\\)")
14757 return-match)))
14758 (let* ((dir (match-string 1 return-match))
14759 (tag (match-string 2 return-match))
14760 (tag (if downcased (downcase tag) tag)))
14761 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14762 (member tag work-already-expanded))
14763 (setq tags-in-group (assoc tag taggroups))
14764 (push tag work-already-expanded)
14765 ;; Recursively expand each tag in the group, if the tag hasn't
14766 ;; already been expanded. Restore the match-data after all recursive calls.
14767 (save-match-data
14768 (let (tags-expanded)
14769 (dolist (x (cdr tags-in-group))
14770 (if (and (member x taggroups-keys)
14771 (not (member x work-already-expanded)))
14772 (setq tags-expanded
14773 (delete-dups
14774 (append
14775 (org-tags-expand x t downcased
14776 work-already-expanded)
14777 tags-expanded)))
14778 (setq tags-expanded
14779 (append (list x) tags-expanded)))
14780 (setq work-already-expanded
14781 (delete-dups
14782 (append tags-expanded
14783 work-already-expanded))))
14784 (setq tags-in-group
14785 (delete-dups (cons (car tags-in-group)
14786 tags-expanded)))))
14787 ;; Filter tag-regexps from tags.
14788 (setq regexp-in-group-escaped
14789 (delq nil (mapcar (lambda (x)
14790 (if (stringp x)
14791 (and (equal "{" (substring x 0 1))
14792 (equal "}" (substring x -1))
14795 tags-in-group))
14796 regexp-in-group
14797 (mapcar (lambda (x)
14798 (substring x 1 -1))
14799 regexp-in-group-escaped)
14800 tags-in-group
14801 (delq nil (mapcar (lambda (x)
14802 (if (stringp x)
14803 (and (not (equal "{" (substring x 0 1)))
14804 (not (equal "}" (substring x -1)))
14807 tags-in-group)))
14808 ;; If single-as-list, do no more in the while-loop.
14809 (if (not single-as-list)
14810 (progn
14811 (when regexp-in-group
14812 (setq regexp-in-group
14813 (concat "\\|"
14814 (mapconcat 'identity regexp-in-group
14815 "\\|"))))
14816 (setq tags-in-group
14817 (concat dir
14818 "{\\<"
14819 (regexp-opt tags-in-group)
14820 "\\>"
14821 regexp-in-group
14822 "}"))
14823 (when (stringp tags-in-group)
14824 (org-add-props tags-in-group '(grouptag t)))
14825 (setq return-match
14826 (replace-match tags-in-group t t return-match)))
14827 (setq tags-in-group
14828 (append regexp-in-group-escaped tags-in-group))))
14829 (setq taggroups-keys (delete tag taggroups-keys))))
14830 ;; Add the regular expressions back into the match-expression again.
14831 (while regexps-in-match
14832 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14833 (pop regexps-in-match)
14834 return-match t t))
14835 (cl-decf count))
14836 (if single-as-list
14837 (if tags-in-group tags-in-group (list return-match))
14838 return-match))
14839 (if single-as-list
14840 (list (if downcased (downcase match) match))
14841 match)))
14843 (defun org-op-to-function (op &optional stringp)
14844 "Turn an operator into the appropriate function."
14845 (setq op
14846 (cond
14847 ((equal op "<" ) '(< string< org-time<))
14848 ((equal op ">" ) '(> org-string> org-time>))
14849 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14850 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14851 ((member op '("=" "==")) '(= string= org-time=))
14852 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14853 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14855 (defun org<> (a b) (not (= a b)))
14856 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14857 (defun org-string>= (a b) (not (string< a b)))
14858 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14859 (defun org-string<> (a b) (not (string= a b)))
14860 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14861 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14862 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14863 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14864 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14865 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14866 (defun org-2ft (s)
14867 "Convert S to a floating point time.
14868 If S is already a number, just return it. If it is a string, parse
14869 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14870 (cond
14871 ((numberp s) s)
14872 ((stringp s)
14873 (condition-case nil
14874 (float-time (apply 'encode-time (org-parse-time-string s)))
14875 (error 0.)))
14876 (t 0.)))
14878 (defun org-time-today ()
14879 "Time in seconds today at 0:00.
14880 Returns the float number of seconds since the beginning of the
14881 epoch to the beginning of today (00:00)."
14882 (float-time (apply 'encode-time
14883 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14885 (defun org-matcher-time (s)
14886 "Interpret a time comparison value."
14887 (save-match-data
14888 (cond
14889 ((string= s "<now>") (float-time))
14890 ((string= s "<today>") (org-time-today))
14891 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14892 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14893 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14894 (+ (org-time-today)
14895 (* (string-to-number (match-string 1 s))
14896 (cdr (assoc (match-string 2 s)
14897 '(("d" . 86400.0) ("w" . 604800.0)
14898 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14899 (t (org-2ft s)))))
14901 (defun org-match-any-p (re list)
14902 "Does re match any element of list?"
14903 (setq list (mapcar (lambda (x) (string-match re x)) list))
14904 (delq nil list))
14906 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14907 (defvar org-tags-overlay (make-overlay 1 1))
14908 (delete-overlay org-tags-overlay)
14910 (defun org-get-local-tags-at (&optional pos)
14911 "Get a list of tags defined in the current headline."
14912 (org-get-tags-at pos 'local))
14914 (defun org-get-local-tags ()
14915 "Get a list of tags defined in the current headline."
14916 (org-get-tags-at nil 'local))
14918 (defun org-get-tags-at (&optional pos local)
14919 "Get a list of all headline tags applicable at POS.
14920 POS defaults to point. If tags are inherited, the list contains
14921 the targets in the same sequence as the headlines appear, i.e.
14922 the tags of the current headline come last.
14923 When LOCAL is non-nil, only return tags from the current headline,
14924 ignore inherited ones."
14925 (interactive)
14926 (if (and org-trust-scanner-tags
14927 (or (not pos) (equal pos (point)))
14928 (not local))
14929 org-scanner-tags
14930 (let (tags ltags lastpos parent)
14931 (save-excursion
14932 (save-restriction
14933 (widen)
14934 (goto-char (or pos (point)))
14935 (save-match-data
14936 (catch 'done
14937 (condition-case nil
14938 (progn
14939 (org-back-to-heading t)
14940 (while (not (equal lastpos (point)))
14941 (setq lastpos (point))
14942 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14943 (setq ltags (org-split-string
14944 (match-string-no-properties 1) ":"))
14945 (when parent
14946 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14947 (setq tags (append
14948 (if parent
14949 (org-remove-uninherited-tags ltags)
14950 ltags)
14951 tags)))
14952 (or org-use-tag-inheritance (throw 'done t))
14953 (when local (throw 'done t))
14954 (or (org-up-heading-safe) (error nil))
14955 (setq parent t)))
14956 (error nil)))))
14957 (if local
14958 tags
14959 (reverse (delete-dups
14960 (reverse (append
14961 (org-remove-uninherited-tags
14962 org-file-tags)
14963 tags)))))))))
14965 (defun org-add-prop-inherited (s)
14966 (add-text-properties 0 (length s) '(inherited t) s)
14969 (defun org-toggle-tag (tag &optional onoff)
14970 "Toggle the tag TAG for the current line.
14971 If ONOFF is `on' or `off', don't toggle but set to this state."
14972 (let (res current)
14973 (save-excursion
14974 (org-back-to-heading t)
14975 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14976 (point-at-eol) t)
14977 (progn
14978 (setq current (match-string 1))
14979 (replace-match ""))
14980 (setq current ""))
14981 (setq current (nreverse (org-split-string current ":")))
14982 (cond
14983 ((eq onoff 'on)
14984 (setq res t)
14985 (or (member tag current) (push tag current)))
14986 ((eq onoff 'off)
14987 (or (not (member tag current)) (setq current (delete tag current))))
14988 (t (if (member tag current)
14989 (setq current (delete tag current))
14990 (setq res t)
14991 (push tag current))))
14992 (end-of-line 1)
14993 (if current
14994 (progn
14995 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14996 (org-set-tags nil t))
14997 (delete-horizontal-space))
14998 (run-hooks 'org-after-tags-change-hook))
14999 res))
15001 (defun org-align-tags-here (to-col)
15002 ;; Assumes that this is a headline
15003 "Align tags on the current headline to TO-COL."
15004 (let ((pos (point)) (col (current-column)) ncol tags-l p)
15005 (beginning-of-line 1)
15006 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15007 (< pos (match-beginning 2)))
15008 (progn
15009 (setq tags-l (string-width (match-string 2)))
15010 (goto-char (match-beginning 1))
15011 (insert " ")
15012 (delete-region (point) (1+ (match-beginning 2)))
15013 (setq ncol (max (current-column)
15014 (1+ col)
15015 (if (> to-col 0)
15016 to-col
15017 (- (abs to-col) tags-l))))
15018 (setq p (point))
15019 (insert (make-string (- ncol (current-column)) ?\ ))
15020 (setq ncol (current-column))
15021 (when indent-tabs-mode (tabify p (point-at-eol)))
15022 (org-move-to-column (min ncol col)))
15023 (goto-char pos))))
15025 (defun org-set-tags-command (&optional arg just-align)
15026 "Call the set-tags command for the current entry."
15027 (interactive "P")
15028 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15029 (org-set-tags arg just-align)
15030 (save-excursion
15031 (unless (and (org-region-active-p)
15032 org-loop-over-headlines-in-active-region)
15033 (org-back-to-heading t))
15034 (org-set-tags arg just-align))))
15036 (defun org-set-tags-to (data)
15037 "Set the tags of the current entry to DATA, replacing the current tags.
15038 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15039 If DATA is nil or the empty string, any tags will be removed."
15040 (interactive "sTags: ")
15041 (setq data
15042 (cond
15043 ((eq data nil) "")
15044 ((equal data "") "")
15045 ((stringp data)
15046 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15047 ":"))
15048 ((listp data)
15049 (concat ":" (mapconcat 'identity data ":") ":"))))
15050 (when data
15051 (save-excursion
15052 (org-back-to-heading t)
15053 (when (looking-at org-complex-heading-regexp)
15054 (if (match-end 5)
15055 (progn
15056 (goto-char (match-beginning 5))
15057 (insert data)
15058 (delete-region (point) (point-at-eol))
15059 (org-set-tags nil 'align))
15060 (goto-char (point-at-eol))
15061 (insert " " data)
15062 (org-set-tags nil 'align)))
15063 (beginning-of-line 1)
15064 (when (looking-at ".*?\\([ \t]+\\)$")
15065 (delete-region (match-beginning 1) (match-end 1))))))
15067 (defun org-align-all-tags ()
15068 "Align the tags in all headings."
15069 (interactive)
15070 (save-excursion
15071 (or (ignore-errors (org-back-to-heading t))
15072 (outline-next-heading))
15073 (if (org-at-heading-p)
15074 (org-set-tags t)
15075 (message "No headings"))))
15077 (defvar org-indent-indentation-per-level)
15078 (defun org-set-tags (&optional arg just-align)
15079 "Set the tags for the current headline.
15080 With prefix ARG, realign all tags in headings in the current buffer.
15081 When JUST-ALIGN is non-nil, only align tags."
15082 (interactive "P")
15083 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15084 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15085 'region-start-level
15086 'region))
15087 org-loop-over-headlines-in-active-region)
15088 (org-map-entries
15089 ;; We don't use ARG and JUST-ALIGN here because these args
15090 ;; are not useful when looping over headlines.
15091 #'org-set-tags
15092 org-loop-over-headlines-in-active-region
15094 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15095 (let ((org-setting-tags t))
15096 (if arg
15097 (save-excursion
15098 (goto-char (point-min))
15099 (while (re-search-forward org-outline-regexp-bol nil t)
15100 (org-set-tags nil t)
15101 (end-of-line))
15102 (message "All tags realigned to column %d" org-tags-column))
15103 (let* ((current (org-get-tags-string))
15104 (col (current-column))
15105 (tags
15106 (if just-align current
15107 ;; Get a new set of tags from the user.
15108 (save-excursion
15109 (let* ((seen)
15110 (table
15111 (setq
15112 org-last-tags-completion-table
15113 ;; Uniquify tags in alists, yet preserve
15114 ;; structure (i.e., keywords).
15115 (delq nil
15116 (mapcar
15117 (lambda (pair)
15118 (let ((head (car pair)))
15119 (cond ((symbolp head) pair)
15120 ((member head seen) nil)
15121 (t (push head seen)
15122 pair))))
15123 (append
15124 (or org-current-tag-alist
15125 (org-get-buffer-tags))
15126 (and
15127 org-complete-tags-always-offer-all-agenda-tags
15128 (org-global-tags-completion-table
15129 (org-agenda-files))))))))
15130 (current-tags (org-split-string current ":"))
15131 (inherited-tags
15132 (nreverse (nthcdr (length current-tags)
15133 (nreverse (org-get-tags-at))))))
15134 (replace-regexp-in-string
15135 "\\([-+&]+\\|,\\)"
15137 (if (or (eq t org-use-fast-tag-selection)
15138 (and org-use-fast-tag-selection
15139 (delq nil (mapcar #'cdr table))))
15140 (org-fast-tag-selection
15141 current-tags inherited-tags table
15142 (and org-fast-tag-selection-include-todo
15143 org-todo-key-alist))
15144 (let ((org-add-colon-after-tag-completion
15145 (< 1 (length table))))
15146 (org-trim
15147 (completing-read
15148 "Tags: "
15149 #'org-tags-completion-function
15150 nil nil current 'org-tags-history))))))))))
15152 (when org-tags-sort-function
15153 (setq tags
15154 (mapconcat
15155 #'identity
15156 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15157 org-tags-sort-function)
15158 ":")))
15160 (if (not (org-string-nw-p tags)) (setq tags "")
15161 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15162 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15164 ;; Insert new tags at the correct column
15165 (beginning-of-line)
15166 (let ((level (if (looking-at org-outline-regexp)
15167 (- (match-end 0) (point) 1)
15168 1)))
15169 (cond
15170 ((and (equal current "") (equal tags "")))
15171 ((re-search-forward
15172 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15173 (line-end-position)
15175 (if (equal tags "") (replace-match "" t t)
15176 (goto-char (match-beginning 0))
15177 (let* ((c0 (current-column))
15178 ;; Compute offset for the case of org-indent-mode
15179 ;; active.
15180 (di (if (bound-and-true-p org-indent-mode)
15181 (* (1- org-indent-indentation-per-level)
15182 (1- level))
15184 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15185 (tc (+ org-tags-column
15186 (if (> org-tags-column 0) (- di) di)))
15187 (c1 (max (1+ c0)
15188 (if (> tc 0) tc
15189 (- (- tc) (string-width tags)))))
15190 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15191 (replace-match rpl t t)
15192 (when indent-tabs-mode (tabify p0 (point))))))
15193 (t (error "Tags alignment failed"))))
15194 (org-move-to-column col))
15195 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15197 (defun org-change-tag-in-region (beg end tag off)
15198 "Add or remove TAG for each entry in the region.
15199 This works in the agenda, and also in an org-mode buffer."
15200 (interactive
15201 (list (region-beginning) (region-end)
15202 (let ((org-last-tags-completion-table
15203 (if (derived-mode-p 'org-mode)
15204 (org-uniquify
15205 (delq nil (append (org-get-buffer-tags)
15206 (org-global-tags-completion-table))))
15207 (org-global-tags-completion-table))))
15208 (completing-read
15209 "Tag: " 'org-tags-completion-function nil nil nil
15210 'org-tags-history))
15211 (progn
15212 (message "[s]et or [r]emove? ")
15213 (equal (read-char-exclusive) ?r))))
15214 (when (fboundp 'deactivate-mark) (deactivate-mark))
15215 (let ((agendap (equal major-mode 'org-agenda-mode))
15216 l1 l2 m buf pos newhead (cnt 0))
15217 (goto-char end)
15218 (setq l2 (1- (org-current-line)))
15219 (goto-char beg)
15220 (setq l1 (org-current-line))
15221 (cl-loop for l from l1 to l2 do
15222 (org-goto-line l)
15223 (setq m (get-text-property (point) 'org-hd-marker))
15224 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15225 (and agendap m))
15226 (setq buf (if agendap (marker-buffer m) (current-buffer))
15227 pos (if agendap m (point)))
15228 (with-current-buffer buf
15229 (save-excursion
15230 (save-restriction
15231 (goto-char pos)
15232 (setq cnt (1+ cnt))
15233 (org-toggle-tag tag (if off 'off 'on))
15234 (setq newhead (org-get-heading)))))
15235 (and agendap (org-agenda-change-all-lines newhead m))))
15236 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15238 (defun org-tags-completion-function (string _predicate &optional flag)
15239 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15240 (confirm (lambda (x) (stringp (car x)))))
15241 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15242 (setq s1 (match-string 1 string)
15243 s2 (match-string 2 string))
15244 (setq s1 "" s2 string))
15245 (cond
15246 ((eq flag nil)
15247 ;; try completion
15248 (setq rtn (try-completion s2 ctable confirm))
15249 (when (stringp rtn)
15250 (setq rtn
15251 (concat s1 s2 (substring rtn (length s2))
15252 (if (and org-add-colon-after-tag-completion
15253 (assoc rtn ctable))
15254 ":" ""))))
15255 rtn)
15256 ((eq flag t)
15257 ;; all-completions
15258 (all-completions s2 ctable confirm))
15259 ((eq flag 'lambda)
15260 ;; exact match?
15261 (assoc s2 ctable)))))
15263 (defun org-fast-tag-insert (kwd tags face &optional end)
15264 "Insert KDW, and the TAGS, the latter with face FACE.
15265 Also insert END."
15266 (insert (format "%-12s" (concat kwd ":"))
15267 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15268 (or end "")))
15270 (defun org-fast-tag-show-exit (flag)
15271 (save-excursion
15272 (org-goto-line 3)
15273 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15274 (replace-match ""))
15275 (when flag
15276 (end-of-line 1)
15277 (org-move-to-column (- (window-width) 19) t)
15278 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15280 (defun org-set-current-tags-overlay (current prefix)
15281 "Add an overlay to CURRENT tag with PREFIX."
15282 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15283 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15284 (org-overlay-display org-tags-overlay (concat prefix s))))
15286 (defvar org-last-tag-selection-key nil)
15287 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15288 "Fast tag selection with single keys.
15289 CURRENT is the current list of tags in the headline, INHERITED is the
15290 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15291 possibly with grouping information. TODO-TABLE is a similar table with
15292 TODO keywords, should these have keys assigned to them.
15293 If the keys are nil, a-z are automatically assigned.
15294 Returns the new tags string, or nil to not change the current settings."
15295 (let* ((fulltable (append table todo-table))
15296 (maxlen (apply 'max (mapcar
15297 (lambda (x)
15298 (if (stringp (car x)) (string-width (car x)) 0))
15299 fulltable)))
15300 (buf (current-buffer))
15301 (expert (eq org-fast-tag-selection-single-key 'expert))
15302 (buffer-tags nil)
15303 (fwidth (+ maxlen 3 1 3))
15304 (ncol (/ (- (window-width) 4) fwidth))
15305 (i-face 'org-done)
15306 (c-face 'org-todo)
15307 tg cnt e c char c1 c2 ntable tbl rtn
15308 ov-start ov-end ov-prefix
15309 (exit-after-next org-fast-tag-selection-single-key)
15310 (done-keywords org-done-keywords)
15311 groups ingroup intaggroup)
15312 (save-excursion
15313 (beginning-of-line 1)
15314 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15315 (setq ov-start (match-beginning 1)
15316 ov-end (match-end 1)
15317 ov-prefix "")
15318 (setq ov-start (1- (point-at-eol))
15319 ov-end (1+ ov-start))
15320 (skip-chars-forward "^\n\r")
15321 (setq ov-prefix
15322 (concat
15323 (buffer-substring (1- (point)) (point))
15324 (if (> (current-column) org-tags-column)
15326 (make-string (- org-tags-column (current-column)) ?\ ))))))
15327 (move-overlay org-tags-overlay ov-start ov-end)
15328 (save-window-excursion
15329 (if expert
15330 (set-buffer (get-buffer-create " *Org tags*"))
15331 (delete-other-windows)
15332 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15333 (org-switch-to-buffer-other-window " *Org tags*"))
15334 (erase-buffer)
15335 (setq-local org-done-keywords done-keywords)
15336 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15337 (org-fast-tag-insert "Current" current c-face "\n\n")
15338 (org-fast-tag-show-exit exit-after-next)
15339 (org-set-current-tags-overlay current ov-prefix)
15340 (setq tbl fulltable char ?a cnt 0)
15341 (while (setq e (pop tbl))
15342 (cond
15343 ((eq (car e) :startgroup)
15344 (push '() groups) (setq ingroup t)
15345 (unless (zerop cnt)
15346 (setq cnt 0)
15347 (insert "\n"))
15348 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15349 ((eq (car e) :endgroup)
15350 (setq ingroup nil cnt 0)
15351 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15352 ((eq (car e) :startgrouptag)
15353 (setq intaggroup t)
15354 (unless (zerop cnt)
15355 (setq cnt 0)
15356 (insert "\n"))
15357 (insert "[ "))
15358 ((eq (car e) :endgrouptag)
15359 (setq intaggroup nil cnt 0)
15360 (insert "]\n"))
15361 ((equal e '(:newline))
15362 (unless (zerop cnt)
15363 (setq cnt 0)
15364 (insert "\n")
15365 (setq e (car tbl))
15366 (while (equal (car tbl) '(:newline))
15367 (insert "\n")
15368 (setq tbl (cdr tbl)))))
15369 ((equal e '(:grouptags)) (insert " : "))
15371 (setq tg (copy-sequence (car e)) c2 nil)
15372 (if (cdr e)
15373 (setq c (cdr e))
15374 ;; automatically assign a character.
15375 (setq c1 (string-to-char
15376 (downcase (substring
15377 tg (if (= (string-to-char tg) ?@) 1 0)))))
15378 (if (or (rassoc c1 ntable) (rassoc c1 table))
15379 (while (or (rassoc char ntable) (rassoc char table))
15380 (setq char (1+ char)))
15381 (setq c2 c1))
15382 (setq c (or c2 char)))
15383 (when ingroup (push tg (car groups)))
15384 (setq tg (org-add-props tg nil 'face
15385 (cond
15386 ((not (assoc tg table))
15387 (org-get-todo-face tg))
15388 ((member tg current) c-face)
15389 ((member tg inherited) i-face))))
15390 (when (equal (caar tbl) :grouptags)
15391 (org-add-props tg nil 'face 'org-tag-group))
15392 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15393 (insert "[" c "] " tg (make-string
15394 (- fwidth 4 (length tg)) ?\ ))
15395 (push (cons tg c) ntable)
15396 (when (= (cl-incf cnt) ncol)
15397 (insert "\n")
15398 (when (or ingroup intaggroup) (insert " "))
15399 (setq cnt 0)))))
15400 (setq ntable (nreverse ntable))
15401 (insert "\n")
15402 (goto-char (point-min))
15403 (unless expert (org-fit-window-to-buffer))
15404 (setq rtn
15405 (catch 'exit
15406 (while t
15407 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15408 (if (not groups) "no " "")
15409 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15410 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15411 (setq org-last-tag-selection-key c)
15412 (cond
15413 ((= c ?\r) (throw 'exit t))
15414 ((= c ?!)
15415 (setq groups (not groups))
15416 (goto-char (point-min))
15417 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15418 ((= c ?\C-c)
15419 (if (not expert)
15420 (org-fast-tag-show-exit
15421 (setq exit-after-next (not exit-after-next)))
15422 (setq expert nil)
15423 (delete-other-windows)
15424 (set-window-buffer (split-window-vertically) " *Org tags*")
15425 (org-switch-to-buffer-other-window " *Org tags*")
15426 (org-fit-window-to-buffer)))
15427 ((or (= c ?\C-g)
15428 (and (= c ?q) (not (rassoc c ntable))))
15429 (delete-overlay org-tags-overlay)
15430 (setq quit-flag t))
15431 ((= c ?\ )
15432 (setq current nil)
15433 (when exit-after-next (setq exit-after-next 'now)))
15434 ((= c ?\t)
15435 (condition-case nil
15436 (setq tg (completing-read
15437 "Tag: "
15438 (or buffer-tags
15439 (with-current-buffer buf
15440 (setq buffer-tags
15441 (org-get-buffer-tags))))))
15442 (quit (setq tg "")))
15443 (when (string-match "\\S-" tg)
15444 (cl-pushnew (list tg) buffer-tags :test #'equal)
15445 (if (member tg current)
15446 (setq current (delete tg current))
15447 (push tg current)))
15448 (when exit-after-next (setq exit-after-next 'now)))
15449 ((setq e (rassoc c todo-table) tg (car e))
15450 (with-current-buffer buf
15451 (save-excursion (org-todo tg)))
15452 (when exit-after-next (setq exit-after-next 'now)))
15453 ((setq e (rassoc c ntable) tg (car e))
15454 (if (member tg current)
15455 (setq current (delete tg current))
15456 (cl-loop for g in groups do
15457 (when (member tg g)
15458 (dolist (x g) (setq current (delete x current)))))
15459 (push tg current))
15460 (when exit-after-next (setq exit-after-next 'now))))
15462 ;; Create a sorted list
15463 (setq current
15464 (sort current
15465 (lambda (a b)
15466 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15467 (when (eq exit-after-next 'now) (throw 'exit t))
15468 (goto-char (point-min))
15469 (beginning-of-line 2)
15470 (delete-region (point) (point-at-eol))
15471 (org-fast-tag-insert "Current" current c-face)
15472 (org-set-current-tags-overlay current ov-prefix)
15473 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15474 (setq tg (match-string 1))
15475 (add-text-properties
15476 (match-beginning 1) (match-end 1)
15477 (list 'face
15478 (cond
15479 ((member tg current) c-face)
15480 ((member tg inherited) i-face)
15481 (t (get-text-property (match-beginning 1) 'face))))))
15482 (goto-char (point-min)))))
15483 (delete-overlay org-tags-overlay)
15484 (if rtn
15485 (mapconcat 'identity current ":")
15486 nil))))
15488 (defun org-get-tags-string ()
15489 "Get the TAGS string in the current headline."
15490 (unless (org-at-heading-p t)
15491 (user-error "Not on a heading"))
15492 (save-excursion
15493 (beginning-of-line 1)
15494 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15495 (match-string-no-properties 1)
15496 "")))
15498 (defun org-get-tags ()
15499 "Get the list of tags specified in the current headline."
15500 (org-split-string (org-get-tags-string) ":"))
15502 (defun org-get-buffer-tags ()
15503 "Get a table of all tags used in the buffer, for completion."
15504 (org-with-wide-buffer
15505 (goto-char (point-min))
15506 (let ((tag-re (concat org-outline-regexp-bol
15507 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15508 tags)
15509 (while (re-search-forward tag-re nil t)
15510 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15511 (push tag tags)))
15512 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15514 ;;;; The mapping API
15516 (defvar org-agenda-skip-comment-trees)
15517 (defvar org-agenda-skip-function)
15518 (defun org-map-entries (func &optional match scope &rest skip)
15519 "Call FUNC at each headline selected by MATCH in SCOPE.
15521 FUNC is a function or a lisp form. The function will be called without
15522 arguments, with the cursor positioned at the beginning of the headline.
15523 The return values of all calls to the function will be collected and
15524 returned as a list.
15526 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15527 does not need to preserve point. After evaluation, the cursor will be
15528 moved to the end of the line (presumably of the headline of the
15529 processed entry) and search continues from there. Under some
15530 circumstances, this may not produce the wanted results. For example,
15531 if you have removed (e.g. archived) the current (sub)tree it could
15532 mean that the next entry will be skipped entirely. In such cases, you
15533 can specify the position from where search should continue by making
15534 FUNC set the variable `org-map-continue-from' to the desired buffer
15535 position.
15537 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15538 Only headlines that are matched by this query will be considered during
15539 the iteration. When MATCH is nil or t, all headlines will be
15540 visited by the iteration.
15542 SCOPE determines the scope of this command. It can be any of:
15544 nil The current buffer, respecting the restriction if any
15545 tree The subtree started with the entry at point
15546 region The entries within the active region, if any
15547 region-start-level
15548 The entries within the active region, but only those at
15549 the same level than the first one.
15550 file The current buffer, without restriction
15551 file-with-archives
15552 The current buffer, and any archives associated with it
15553 agenda All agenda files
15554 agenda-with-archives
15555 All agenda files with any archive files associated with them
15556 \(file1 file2 ...)
15557 If this is a list, all files in the list will be scanned
15559 The remaining args are treated as settings for the skipping facilities of
15560 the scanner. The following items can be given here:
15562 archive skip trees with the archive tag
15563 comment skip trees with the COMMENT keyword
15564 function or Emacs Lisp form:
15565 will be used as value for `org-agenda-skip-function', so
15566 whenever the function returns a position, FUNC will not be
15567 called for that entry and search will continue from the
15568 position returned
15570 If your function needs to retrieve the tags including inherited tags
15571 at the *current* entry, you can use the value of the variable
15572 `org-scanner-tags' which will be much faster than getting the value
15573 with `org-get-tags-at'. If your function gets properties with
15574 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15575 to t around the call to `org-entry-properties' to get the same speedup.
15576 Note that if your function moves around to retrieve tags and properties at
15577 a *different* entry, you cannot use these techniques."
15578 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15579 (not (org-region-active-p)))
15580 (let* ((org-agenda-archives-mode nil) ; just to make sure
15581 (org-agenda-skip-archived-trees (memq 'archive skip))
15582 (org-agenda-skip-comment-trees (memq 'comment skip))
15583 (org-agenda-skip-function
15584 (car (org-delete-all '(comment archive) skip)))
15585 (org-tags-match-list-sublevels t)
15586 (start-level (eq scope 'region-start-level))
15587 matcher res
15588 org-todo-keywords-for-agenda
15589 org-done-keywords-for-agenda
15590 org-todo-keyword-alist-for-agenda
15591 org-tag-alist-for-agenda
15592 org--matcher-tags-todo-only)
15594 (cond
15595 ((eq match t) (setq matcher t))
15596 ((eq match nil) (setq matcher t))
15597 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15599 (save-excursion
15600 (save-restriction
15601 (cond ((eq scope 'tree)
15602 (org-back-to-heading t)
15603 (org-narrow-to-subtree)
15604 (setq scope nil))
15605 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15606 (org-region-active-p))
15607 ;; If needed, set start-level to a string like "2"
15608 (when start-level
15609 (save-excursion
15610 (goto-char (region-beginning))
15611 (unless (org-at-heading-p) (outline-next-heading))
15612 (setq start-level (org-current-level))))
15613 (narrow-to-region (region-beginning)
15614 (save-excursion
15615 (goto-char (region-end))
15616 (unless (and (bolp) (org-at-heading-p))
15617 (outline-next-heading))
15618 (point)))
15619 (setq scope nil)))
15621 (if (not scope)
15622 (progn
15623 (org-agenda-prepare-buffers
15624 (and buffer-file-name (list buffer-file-name)))
15625 (setq res
15626 (org-scan-tags
15627 func matcher org--matcher-tags-todo-only start-level)))
15628 ;; Get the right scope
15629 (cond
15630 ((and scope (listp scope) (symbolp (car scope)))
15631 (setq scope (eval scope)))
15632 ((eq scope 'agenda)
15633 (setq scope (org-agenda-files t)))
15634 ((eq scope 'agenda-with-archives)
15635 (setq scope (org-agenda-files t))
15636 (setq scope (org-add-archive-files scope)))
15637 ((eq scope 'file)
15638 (setq scope (and buffer-file-name (list buffer-file-name))))
15639 ((eq scope 'file-with-archives)
15640 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15641 (org-agenda-prepare-buffers scope)
15642 (dolist (file scope)
15643 (with-current-buffer (org-find-base-buffer-visiting file)
15644 (save-excursion
15645 (save-restriction
15646 (widen)
15647 (goto-char (point-min))
15648 (setq res
15649 (append
15651 (org-scan-tags
15652 func matcher org--matcher-tags-todo-only))))))))))
15653 res)))
15655 ;;; Properties API
15657 (defconst org-special-properties
15658 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15659 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15660 "The special properties valid in Org mode.
15661 These are properties that are not defined in the property drawer,
15662 but in some other way.")
15664 (defconst org-default-properties
15665 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15666 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15667 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15668 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15669 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15670 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15671 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15672 "Some properties that are used by Org mode for various purposes.
15673 Being in this list makes sure that they are offered for completion.")
15675 (defun org--valid-property-p (property)
15676 "Non nil when string PROPERTY is a valid property name."
15677 (not
15678 (or (equal property "")
15679 (string-match-p "\\s-" property))))
15681 (defun org--update-property-plist (key val props)
15682 "Associate KEY to VAL in alist PROPS.
15683 Modifications are made by side-effect. Return new alist."
15684 (let* ((appending (string= (substring key -1) "+"))
15685 (key (if appending (substring key 0 -1) key))
15686 (old (assoc-string key props t)))
15687 (if (not old) (cons (cons key val) props)
15688 (setcdr old (if appending (concat (cdr old) " " val) val))
15689 props)))
15691 (defun org-get-property-block (&optional beg force)
15692 "Return the (beg . end) range of the body of the property drawer.
15693 BEG is the beginning of the current subtree, or of the part
15694 before the first headline. If it is not given, it will be found.
15695 If the drawer does not exist, create it if FORCE is non-nil, or
15696 return nil."
15697 (org-with-wide-buffer
15698 (when beg (goto-char beg))
15699 (unless (org-before-first-heading-p)
15700 (let ((beg (cond (beg)
15701 ((or (not (featurep 'org-inlinetask))
15702 (org-inlinetask-in-task-p))
15703 (org-back-to-heading t))
15704 (t (org-with-limited-levels (org-back-to-heading t))))))
15705 (forward-line)
15706 (when (looking-at-p org-planning-line-re) (forward-line))
15707 (cond ((looking-at org-property-drawer-re)
15708 (forward-line)
15709 (cons (point) (progn (goto-char (match-end 0))
15710 (line-beginning-position))))
15711 (force
15712 (goto-char beg)
15713 (org-insert-property-drawer)
15714 (let ((pos (save-excursion (search-forward ":END:")
15715 (line-beginning-position))))
15716 (cons pos pos))))))))
15718 (defun org-at-property-p ()
15719 "Non-nil when point is inside a property drawer.
15720 See `org-property-re' for match data, if applicable."
15721 (save-excursion
15722 (beginning-of-line)
15723 (and (looking-at org-property-re)
15724 (let ((property-drawer (save-match-data (org-get-property-block))))
15725 (and property-drawer
15726 (>= (point) (car property-drawer))
15727 (< (point) (cdr property-drawer)))))))
15729 (defun org-property-action ()
15730 "Do an action on properties."
15731 (interactive)
15732 (unless (org-at-property-p) (user-error "Not at a property"))
15733 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15734 (let ((c (read-char-exclusive)))
15735 (cl-case c
15736 (?s (call-interactively #'org-set-property))
15737 (?d (call-interactively #'org-delete-property))
15738 (?D (call-interactively #'org-delete-property-globally))
15739 (?c (call-interactively #'org-compute-property-at-point))
15740 (otherwise (user-error "No such property action %c" c)))))
15742 (defun org-inc-effort ()
15743 "Increment the value of the effort property in the current entry."
15744 (interactive)
15745 (org-set-effort nil t))
15747 (defvar org-clock-effort) ; Defined in org-clock.el.
15748 (defvar org-clock-current-task) ; Defined in org-clock.el.
15749 (defun org-set-effort (&optional value increment)
15750 "Set the effort property of the current entry.
15751 With numerical prefix arg, use the nth allowed value, 0 stands for the
15752 10th allowed value.
15754 When INCREMENT is non-nil, set the property to the next allowed value."
15755 (interactive "P")
15756 (when (equal value 0) (setq value 10))
15757 (let* ((completion-ignore-case t)
15758 (prop org-effort-property)
15759 (cur (org-entry-get nil prop))
15760 (allowed (org-property-get-allowed-values nil prop 'table))
15761 (existing (mapcar 'list (org-property-values prop)))
15762 (heading (nth 4 (org-heading-components)))
15764 (val (cond
15765 ((stringp value) value)
15766 ((and allowed (integerp value))
15767 (or (car (nth (1- value) allowed))
15768 (car (org-last allowed))))
15769 ((and allowed increment)
15770 (or (cl-caadr (member (list cur) allowed))
15771 (user-error "Allowed effort values are not set")))
15772 (allowed
15773 (message "Select 1-9,0, [RET%s]: %s"
15774 (if cur (concat "=" cur) "")
15775 (mapconcat 'car allowed " "))
15776 (setq rpl (read-char-exclusive))
15777 (if (equal rpl ?\r)
15779 (setq rpl (- rpl ?0))
15780 (when (equal rpl 0) (setq rpl 10))
15781 (if (and (> rpl 0) (<= rpl (length allowed)))
15782 (car (nth (1- rpl) allowed))
15783 (org-completing-read "Effort: " allowed nil))))
15785 (org-completing-read
15786 (concat "Effort" (and cur (string-match "\\S-" cur)
15787 (concat " [" cur "]"))
15788 ": ")
15789 existing nil nil "" nil cur)))))
15790 (unless (equal (org-entry-get nil prop) val)
15791 (org-entry-put nil prop val))
15792 (org-refresh-property
15793 '((effort . identity)
15794 (effort-minutes . org-duration-string-to-minutes))
15795 val)
15796 (when (equal heading (bound-and-true-p org-clock-current-task))
15797 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15798 (org-clock-update-mode-line))
15799 (message "%s is now %s" prop val)))
15801 (defun org-entry-properties (&optional pom which)
15802 "Get all properties of the current entry.
15804 When POM is a buffer position, get all properties from the entry
15805 there instead.
15807 This includes the TODO keyword, the tags, time strings for
15808 deadline, scheduled, and clocking, and any additional properties
15809 defined in the entry.
15811 If WHICH is nil or `all', get all properties. If WHICH is
15812 `special' or `standard', only get that subclass. If WHICH is
15813 a string, only get that property.
15815 Return value is an alist. Keys are properties, as upcased
15816 strings."
15817 (org-with-point-at pom
15818 (when (and (derived-mode-p 'org-mode)
15819 (ignore-errors (org-back-to-heading t)))
15820 (catch 'exit
15821 (let* ((beg (point))
15822 (specific (and (stringp which) (upcase which)))
15823 (which (cond ((not specific) which)
15824 ((member specific org-special-properties) 'special)
15825 (t 'standard)))
15826 props)
15827 ;; Get the special properties, like TODO and TAGS.
15828 (when (memq which '(nil all special))
15829 (when (or (not specific) (string= specific "CLOCKSUM"))
15830 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15831 (when clocksum
15832 (push (cons "CLOCKSUM"
15833 (org-minutes-to-clocksum-string clocksum))
15834 props)))
15835 (when specific (throw 'exit props)))
15836 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15837 (let ((clocksumt (get-text-property (point)
15838 :org-clock-minutes-today)))
15839 (when clocksumt
15840 (push (cons "CLOCKSUM_T"
15841 (org-minutes-to-clocksum-string clocksumt))
15842 props)))
15843 (when specific (throw 'exit props)))
15844 (when (or (not specific) (string= specific "ITEM"))
15845 (when (looking-at org-complex-heading-regexp)
15846 (push (cons "ITEM"
15847 (let ((title (match-string-no-properties 4)))
15848 (if (org-string-nw-p title)
15849 (org-remove-tabs title)
15850 "")))
15851 props))
15852 (when specific (throw 'exit props)))
15853 (when (or (not specific) (string= specific "TODO"))
15854 (let ((case-fold-search nil))
15855 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15856 (push (cons "TODO" (match-string-no-properties 2)) props)))
15857 (when specific (throw 'exit props)))
15858 (when (or (not specific) (string= specific "PRIORITY"))
15859 (push (cons "PRIORITY"
15860 (if (looking-at org-priority-regexp)
15861 (match-string-no-properties 2)
15862 (char-to-string org-default-priority)))
15863 props)
15864 (when specific (throw 'exit props)))
15865 (when (or (not specific) (string= specific "FILE"))
15866 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15867 props)
15868 (when specific (throw 'exit props)))
15869 (when (or (not specific) (string= specific "TAGS"))
15870 (let ((value (org-string-nw-p (org-get-tags-string))))
15871 (when value (push (cons "TAGS" value) props)))
15872 (when specific (throw 'exit props)))
15873 (when (or (not specific) (string= specific "ALLTAGS"))
15874 (let ((value (org-get-tags-at)))
15875 (when value
15876 (push (cons "ALLTAGS"
15877 (format ":%s:" (mapconcat #'identity value ":")))
15878 props)))
15879 (when specific (throw 'exit props)))
15880 (when (or (not specific) (string= specific "BLOCKED"))
15881 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15882 (when specific (throw 'exit props)))
15883 (when (or (not specific)
15884 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15885 (forward-line)
15886 (when (looking-at-p org-planning-line-re)
15887 (end-of-line)
15888 (let ((bol (line-beginning-position))
15889 ;; Backward compatibility: time keywords used to
15890 ;; be configurable (before 8.3). Make sure we
15891 ;; get the correct keyword.
15892 (key-assoc `(("CLOSED" . ,org-closed-string)
15893 ("DEADLINE" . ,org-deadline-string)
15894 ("SCHEDULED" . ,org-scheduled-string))))
15895 (dolist (pair (if specific (list (assoc specific key-assoc))
15896 key-assoc))
15897 (save-excursion
15898 (when (search-backward (cdr pair) bol t)
15899 (goto-char (match-end 0))
15900 (skip-chars-forward " \t")
15901 (and (looking-at org-ts-regexp-both)
15902 (push (cons (car pair)
15903 (match-string-no-properties 0))
15904 props)))))))
15905 (when specific (throw 'exit props)))
15906 (when (or (not specific)
15907 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15908 (let ((find-ts
15909 (lambda (end ts)
15910 ;; Fix next time-stamp before END. TS is the
15911 ;; list of time-stamps found so far.
15912 (let ((ts ts)
15913 (regexp (cond
15914 ((string= specific "TIMESTAMP")
15915 org-ts-regexp)
15916 ((string= specific "TIMESTAMP_IA")
15917 org-ts-regexp-inactive)
15918 ((assoc "TIMESTAMP_IA" ts)
15919 org-ts-regexp)
15920 ((assoc "TIMESTAMP" ts)
15921 org-ts-regexp-inactive)
15922 (t org-ts-regexp-both))))
15923 (catch 'next
15924 (while (re-search-forward regexp end t)
15925 (backward-char)
15926 (let ((object (org-element-context)))
15927 ;; Accept to match timestamps in node
15928 ;; properties, too.
15929 (when (memq (org-element-type object)
15930 '(node-property timestamp))
15931 (let ((type
15932 (org-element-property :type object)))
15933 (cond
15934 ((and (memq type '(active active-range))
15935 (not (equal specific "TIMESTAMP_IA")))
15936 (unless (assoc "TIMESTAMP" ts)
15937 (push (cons "TIMESTAMP"
15938 (org-element-property
15939 :raw-value object))
15941 (when specific (throw 'exit ts))))
15942 ((and (memq type '(inactive inactive-range))
15943 (not (string= specific "TIMESTAMP")))
15944 (unless (assoc "TIMESTAMP_IA" ts)
15945 (push (cons "TIMESTAMP_IA"
15946 (org-element-property
15947 :raw-value object))
15949 (when specific (throw 'exit ts))))))
15950 ;; Both timestamp types are found,
15951 ;; move to next part.
15952 (when (= (length ts) 2) (throw 'next ts)))))
15953 ts)))))
15954 (goto-char beg)
15955 ;; First look for timestamps within headline.
15956 (let ((ts (funcall find-ts (line-end-position) nil)))
15957 (if (= (length ts) 2) (setq props (nconc ts props))
15958 (forward-line)
15959 ;; Then find timestamps in the section, skipping
15960 ;; planning line.
15961 (when (looking-at-p org-planning-line-re)
15962 (forward-line))
15963 (let ((end (save-excursion (outline-next-heading))))
15964 (setq props (nconc (funcall find-ts end ts) props))))))))
15965 ;; Get the standard properties, like :PROP:.
15966 (when (memq which '(nil all standard))
15967 ;; If we are looking after a specific property, delegate
15968 ;; to `org-entry-get', which is faster. However, make an
15969 ;; exception for "CATEGORY", since it can be also set
15970 ;; through keywords (i.e. #+CATEGORY).
15971 (if (and specific (not (equal specific "CATEGORY")))
15972 (let ((value (org-entry-get beg specific nil t)))
15973 (throw 'exit (and value (list (cons specific value)))))
15974 (let ((range (org-get-property-block beg)))
15975 (when range
15976 (let ((end (cdr range)) seen-base)
15977 (goto-char (car range))
15978 ;; Unlike to `org--update-property-plist', we
15979 ;; handle the case where base values is found
15980 ;; after its extension. We also forbid standard
15981 ;; properties to be named as special properties.
15982 (while (re-search-forward org-property-re end t)
15983 (let* ((key (upcase (match-string-no-properties 2)))
15984 (extendp (string-match-p "\\+\\'" key))
15985 (key-base (if extendp (substring key 0 -1) key))
15986 (value (match-string-no-properties 3)))
15987 (cond
15988 ((member-ignore-case key-base org-special-properties))
15989 (extendp
15990 (setq props
15991 (org--update-property-plist key value props)))
15992 ((member key seen-base))
15993 (t (push key seen-base)
15994 (let ((p (assoc-string key props t)))
15995 (if p (setcdr p (concat value " " (cdr p)))
15996 (push (cons key value) props))))))))))))
15997 (unless (assoc "CATEGORY" props)
15998 (push (cons "CATEGORY" (org-get-category beg)) props)
15999 (when (string= specific "CATEGORY") (throw 'exit props)))
16000 ;; Return value.
16001 props)))))
16003 (defun org-property--local-values (property literal-nil)
16004 "Return value for PROPERTY in current entry.
16005 Value is a list whose car is the base value for PROPERTY and cdr
16006 a list of accumulated values. Return nil if neither is found in
16007 the entry. Also return nil when PROPERTY is set to \"nil\",
16008 unless LITERAL-NIL is non-nil."
16009 (let ((range (org-get-property-block)))
16010 (when range
16011 (goto-char (car range))
16012 (let* ((case-fold-search t)
16013 (end (cdr range))
16014 (value
16015 ;; Base value.
16016 (save-excursion
16017 (let ((v (and (re-search-forward
16018 (org-re-property property nil t) end t)
16019 (match-string-no-properties 3))))
16020 (list (if literal-nil v (org-not-nil v)))))))
16021 ;; Find additional values.
16022 (let* ((property+ (org-re-property (concat property "+") nil t)))
16023 (while (re-search-forward property+ end t)
16024 (push (match-string-no-properties 3) value)))
16025 ;; Return final values.
16026 (and (not (equal value '(nil))) (nreverse value))))))
16028 (defun org-entry-get (pom property &optional inherit literal-nil)
16029 "Get value of PROPERTY for entry or content at point-or-marker POM.
16031 If INHERIT is non-nil and the entry does not have the property,
16032 then also check higher levels of the hierarchy. If INHERIT is
16033 the symbol `selective', use inheritance only if the setting in
16034 `org-use-property-inheritance' selects PROPERTY for inheritance.
16036 If the property is present but empty, the return value is the
16037 empty string. If the property is not present at all, nil is
16038 returned. In any other case, return the value as a string.
16039 Search is case-insensitive.
16041 If LITERAL-NIL is set, return the string value \"nil\" as
16042 a string, do not interpret it as the list atom nil. This is used
16043 for inheritance when a \"nil\" value can supersede a non-nil
16044 value higher up the hierarchy."
16045 (org-with-point-at pom
16046 (cond
16047 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16048 ;; We need a special property. Use `org-entry-properties' to
16049 ;; retrieve it, but specify the wanted property.
16050 (cdr (assoc-string property (org-entry-properties nil property))))
16051 ((and inherit
16052 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16053 (org-entry-get-with-inheritance property literal-nil))
16055 (let* ((local (org-property--local-values property literal-nil))
16056 (value (and local (mapconcat #'identity (delq nil local) " "))))
16057 (if literal-nil value (org-not-nil value)))))))
16059 (defun org-property-or-variable-value (var &optional inherit)
16060 "Check if there is a property fixing the value of VAR.
16061 If yes, return this value. If not, return the current value of the variable."
16062 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16063 (if (and prop (stringp prop) (string-match "\\S-" prop))
16064 (read prop)
16065 (symbol-value var))))
16067 (defun org-entry-delete (pom property)
16068 "Delete PROPERTY from entry at point-or-marker POM.
16069 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16070 non-nil when a property was removed."
16071 (unless (member property org-special-properties)
16072 (org-with-point-at pom
16073 (let ((range (org-get-property-block)))
16074 (when range
16075 (let* ((begin (car range))
16076 (origin (cdr range))
16077 (end (copy-marker origin))
16078 (re (org-re-property
16079 (concat (regexp-quote property) "\\+?") t t)))
16080 (goto-char begin)
16081 (while (re-search-forward re end t)
16082 (delete-region (match-beginning 0) (line-beginning-position 2)))
16083 ;; If drawer is empty, remove it altogether.
16084 (when (= begin end)
16085 (delete-region (line-beginning-position 0)
16086 (line-beginning-position 2)))
16087 ;; Return non-nil if some property was removed.
16088 (prog1 (/= end origin) (set-marker end nil))))))))
16090 ;; Multi-values properties are properties that contain multiple values
16091 ;; These values are assumed to be single words, separated by whitespace.
16092 (defun org-entry-add-to-multivalued-property (pom property value)
16093 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16094 (let* ((old (org-entry-get pom property))
16095 (values (and old (org-split-string old "[ \t]"))))
16096 (setq value (org-entry-protect-space value))
16097 (unless (member value values)
16098 (setq values (append values (list value)))
16099 (org-entry-put pom property
16100 (mapconcat 'identity values " ")))))
16102 (defun org-entry-remove-from-multivalued-property (pom property value)
16103 "Remove VALUE from 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 (when (member value values)
16108 (setq values (delete value values))
16109 (org-entry-put pom property
16110 (mapconcat 'identity values " ")))))
16112 (defun org-entry-member-in-multivalued-property (pom property value)
16113 "Is VALUE one of the 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 (member value values)))
16119 (defun org-entry-get-multivalued-property (pom property)
16120 "Return a list of values in a multivalued property."
16121 (let* ((value (org-entry-get pom property))
16122 (values (and value (org-split-string value "[ \t]"))))
16123 (mapcar 'org-entry-restore-space values)))
16125 (defun org-entry-put-multivalued-property (pom property &rest values)
16126 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16127 VALUES should be a list of strings. Spaces will be protected."
16128 (org-entry-put pom property
16129 (mapconcat 'org-entry-protect-space values " "))
16130 (let* ((value (org-entry-get pom property))
16131 (values (and value (org-split-string value "[ \t]"))))
16132 (mapcar 'org-entry-restore-space values)))
16134 (defun org-entry-protect-space (s)
16135 "Protect spaces and newline in string S."
16136 (while (string-match " " s)
16137 (setq s (replace-match "%20" t t s)))
16138 (while (string-match "\n" s)
16139 (setq s (replace-match "%0A" t t s)))
16142 (defun org-entry-restore-space (s)
16143 "Restore spaces and newline in string S."
16144 (while (string-match "%20" s)
16145 (setq s (replace-match " " t t s)))
16146 (while (string-match "%0A" s)
16147 (setq s (replace-match "\n" t t s)))
16150 (defvar org-entry-property-inherited-from (make-marker)
16151 "Marker pointing to the entry from where a property was inherited.
16152 Each call to `org-entry-get-with-inheritance' will set this marker to the
16153 location of the entry where the inheritance search matched. If there was
16154 no match, the marker will point nowhere.
16155 Note that also `org-entry-get' calls this function, if the INHERIT flag
16156 is set.")
16158 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16159 "Get PROPERTY of entry or content at point, search higher levels if needed.
16160 The search will stop at the first ancestor which has the property defined.
16161 If the value found is \"nil\", return nil to show that the property
16162 should be considered as undefined (this is the meaning of nil here).
16163 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16164 (move-marker org-entry-property-inherited-from nil)
16165 (org-with-wide-buffer
16166 (let (value)
16167 (catch 'exit
16168 (while t
16169 (let ((v (org-property--local-values property literal-nil)))
16170 (when v
16171 (setq value
16172 (concat (mapconcat #'identity (delq nil v) " ")
16173 (and value " ")
16174 value)))
16175 (cond
16176 ((car v)
16177 (org-back-to-heading t)
16178 (move-marker org-entry-property-inherited-from (point))
16179 (throw 'exit nil))
16180 ((org-up-heading-safe))
16182 (let ((global
16183 (cdr (or (assoc-string property org-file-properties t)
16184 (assoc-string property org-global-properties t)
16185 (assoc-string property org-global-properties-fixed t)))))
16186 (cond ((not global))
16187 (value (setq value (concat global " " value)))
16188 (t (setq value global))))
16189 (throw 'exit nil))))))
16190 (if literal-nil value (org-not-nil value)))))
16192 (defvar org-property-changed-functions nil
16193 "Hook called when the value of a property has changed.
16194 Each hook function should accept two arguments, the name of the property
16195 and the new value.")
16197 (defun org-entry-put (pom property value)
16198 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16200 If the value is nil, it is converted to the empty string. If it
16201 is not a string, an error is raised. Also raise an error on
16202 invalid property names.
16204 PROPERTY can be any regular property (see
16205 `org-special-properties'). It can also be \"TODO\",
16206 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16208 For the last two properties, VALUE may have any of the special
16209 values \"earlier\" and \"later\". The function then increases or
16210 decreases scheduled or deadline date by one day."
16211 (cond ((null value) (setq value ""))
16212 ((not (stringp value)) (error "Properties values should be strings"))
16213 ((not (org--valid-property-p property))
16214 (user-error "Invalid property name: \"%s\"" property)))
16215 (org-with-point-at pom
16216 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16217 (org-back-to-heading t)
16218 (org-with-limited-levels (org-back-to-heading t)))
16219 (let ((beg (point)))
16220 (cond
16221 ((equal property "TODO")
16222 (cond ((not (org-string-nw-p value)) (setq value 'none))
16223 ((not (member value org-todo-keywords-1))
16224 (user-error "\"%s\" is not a valid TODO state" value)))
16225 (org-todo value)
16226 (org-set-tags nil 'align))
16227 ((equal property "PRIORITY")
16228 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16229 (org-set-tags nil 'align))
16230 ((equal property "SCHEDULED")
16231 (forward-line)
16232 (if (and (looking-at-p org-planning-line-re)
16233 (re-search-forward
16234 org-scheduled-time-regexp (line-end-position) t))
16235 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16236 ((string= value "later") (org-timestamp-change 1 'day))
16237 ((string= value "") (org-schedule '(4)))
16238 (t (org-schedule nil value)))
16239 (if (member value '("earlier" "later" ""))
16240 (call-interactively #'org-schedule)
16241 (org-schedule nil value))))
16242 ((equal property "DEADLINE")
16243 (forward-line)
16244 (if (and (looking-at-p org-planning-line-re)
16245 (re-search-forward
16246 org-deadline-time-regexp (line-end-position) t))
16247 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16248 ((string= value "later") (org-timestamp-change 1 'day))
16249 ((string= value "") (org-deadline '(4)))
16250 (t (org-deadline nil value)))
16251 (if (member value '("earlier" "later" ""))
16252 (call-interactively #'org-deadline)
16253 (org-deadline nil value))))
16254 ((member property org-special-properties)
16255 (error "The %s property cannot be set with `org-entry-put'" property))
16257 (let* ((range (org-get-property-block beg 'force))
16258 (end (cdr range))
16259 (case-fold-search t))
16260 (goto-char (car range))
16261 (if (re-search-forward (org-re-property property nil t) end t)
16262 (progn (delete-region (match-beginning 0) (match-end 0))
16263 (goto-char (match-beginning 0)))
16264 (goto-char end)
16265 (insert "\n")
16266 (backward-char))
16267 (insert ":" property ":")
16268 (when value (insert " " value))
16269 (org-indent-line)))))
16270 (run-hook-with-args 'org-property-changed-functions property value)))
16272 (defun org-buffer-property-keys
16273 (&optional specials defaults columns ignore-malformed)
16274 "Get all property keys in the current buffer.
16276 When SPECIALS is non-nil, also list the special properties that
16277 reflect things like tags and TODO state.
16279 When DEFAULTS is non-nil, also include properties that has
16280 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16281 DESCRIPTION, LOCATION, and LOGGING and others.
16283 When COLUMNS in non-nil, also include property names given in
16284 COLUMN formats in the current buffer.
16286 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16287 automatically performed, such drawers will be silently ignored."
16288 (let ((case-fold-search t)
16289 (props (append
16290 (and specials org-special-properties)
16291 (and defaults (cons org-effort-property org-default-properties))
16292 nil)))
16293 (org-with-wide-buffer
16294 (goto-char (point-min))
16295 (while (re-search-forward org-property-start-re nil t)
16296 (let ((range (org-get-property-block)))
16297 (catch 'skip
16298 (unless range
16299 (when (and (not ignore-malformed)
16300 (not (org-before-first-heading-p))
16301 (y-or-n-p (format "Malformed drawer at %d, repair?"
16302 (line-beginning-position))))
16303 (org-get-property-block nil t))
16304 (throw 'skip nil))
16305 (goto-char (car range))
16306 (let ((begin (car range))
16307 (end (cdr range)))
16308 ;; Make sure that found property block is not located
16309 ;; before current point, as it would generate an infloop.
16310 ;; It can happen, for example, in the following
16311 ;; situation:
16313 ;; * Headline
16314 ;; :PROPERTIES:
16315 ;; ...
16316 ;; :END:
16317 ;; *************** Inlinetask
16318 ;; #+BEGIN_EXAMPLE
16319 ;; :PROPERTIES:
16320 ;; #+END_EXAMPLE
16322 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16323 (while (< (point) end)
16324 (let ((p (progn (looking-at org-property-re)
16325 (match-string-no-properties 2))))
16326 ;; Only add true property name, not extension symbol.
16327 (push (if (not (string-match-p "\\+\\'" p)) p
16328 (substring p 0 -1))
16329 props))
16330 (forward-line))))
16331 (outline-next-heading)))
16332 (when columns
16333 (goto-char (point-min))
16334 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16335 (let ((element (org-element-at-point)))
16336 (when (memq (org-element-type element) '(keyword node-property))
16337 (let ((value (org-element-property :value element))
16338 (start 0))
16339 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16340 (setq start (match-end 0))
16341 (let ((p (match-string-no-properties 1 value)))
16342 (unless (member-ignore-case p org-special-properties)
16343 (push p props))))))))))
16344 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16346 (defun org-property-values (key)
16347 "List all non-nil values of property KEY in current buffer."
16348 (org-with-wide-buffer
16349 (goto-char (point-min))
16350 (let ((case-fold-search t)
16351 (re (org-re-property key))
16352 values)
16353 (while (re-search-forward re nil t)
16354 (push (org-entry-get (point) key) values))
16355 (delete-dups values))))
16357 (defun org-insert-property-drawer ()
16358 "Insert a property drawer into the current entry."
16359 (org-with-wide-buffer
16360 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16361 (org-back-to-heading t)
16362 (org-with-limited-levels (org-back-to-heading t)))
16363 (forward-line)
16364 (when (looking-at-p org-planning-line-re) (forward-line))
16365 (unless (looking-at-p org-property-drawer-re)
16366 ;; Make sure we start editing a line from current entry, not from
16367 ;; next one. It prevents extending text properties or overlays
16368 ;; belonging to the latter.
16369 (when (bolp) (backward-char))
16370 (let ((begin (1+ (point)))
16371 (inhibit-read-only t))
16372 (insert "\n:PROPERTIES:\n:END:")
16373 (when (eobp) (insert "\n"))
16374 (org-indent-region begin (point))))))
16376 (defun org-insert-drawer (&optional arg drawer)
16377 "Insert a drawer at point.
16379 When optional argument ARG is non-nil, insert a property drawer.
16381 Optional argument DRAWER, when non-nil, is a string representing
16382 drawer's name. Otherwise, the user is prompted for a name.
16384 If a region is active, insert the drawer around that region
16385 instead.
16387 Point is left between drawer's boundaries."
16388 (interactive "P")
16389 (let* ((drawer (if arg "PROPERTIES"
16390 (or drawer (read-from-minibuffer "Drawer: ")))))
16391 (cond
16392 ;; With C-u, fall back on `org-insert-property-drawer'
16393 (arg (org-insert-property-drawer))
16394 ;; Check validity of suggested drawer's name.
16395 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16396 (user-error "Invalid drawer name"))
16397 ;; With an active region, insert a drawer at point.
16398 ((not (org-region-active-p))
16399 (progn
16400 (unless (bolp) (insert "\n"))
16401 (insert (format ":%s:\n\n:END:\n" drawer))
16402 (forward-line -2)))
16403 ;; Otherwise, insert the drawer at point
16405 (let ((rbeg (region-beginning))
16406 (rend (copy-marker (region-end))))
16407 (unwind-protect
16408 (progn
16409 (goto-char rbeg)
16410 (beginning-of-line)
16411 (when (save-excursion
16412 (re-search-forward org-outline-regexp-bol rend t))
16413 (user-error "Drawers cannot contain headlines"))
16414 ;; Position point at the beginning of the first
16415 ;; non-blank line in region. Insert drawer's opening
16416 ;; there, then indent it.
16417 (org-skip-whitespace)
16418 (beginning-of-line)
16419 (insert ":" drawer ":\n")
16420 (forward-line -1)
16421 (indent-for-tab-command)
16422 ;; Move point to the beginning of the first blank line
16423 ;; after the last non-blank line in region. Insert
16424 ;; drawer's closing, then indent it.
16425 (goto-char rend)
16426 (skip-chars-backward " \r\t\n")
16427 (insert "\n:END:")
16428 (deactivate-mark t)
16429 (indent-for-tab-command)
16430 (unless (eolp) (insert "\n")))
16431 ;; Clear marker, whatever the outcome of insertion is.
16432 (set-marker rend nil)))))))
16434 (defvar org-property-set-functions-alist nil
16435 "Property set function alist.
16436 Each entry should have the following format:
16438 (PROPERTY . READ-FUNCTION)
16440 The read function will be called with the same argument as
16441 `org-completing-read'.")
16443 (defun org-set-property-function (property)
16444 "Get the function that should be used to set PROPERTY.
16445 This is computed according to `org-property-set-functions-alist'."
16446 (or (cdr (assoc property org-property-set-functions-alist))
16447 'org-completing-read))
16449 (defun org-read-property-value (property)
16450 "Read PROPERTY value from user."
16451 (let* ((completion-ignore-case t)
16452 (allowed (org-property-get-allowed-values nil property 'table))
16453 (cur (org-entry-get nil property))
16454 (prompt (concat property " value"
16455 (if (and cur (string-match "\\S-" cur))
16456 (concat " [" cur "]") "") ": "))
16457 (set-function (org-set-property-function property))
16458 (val (if allowed
16459 (funcall set-function prompt allowed nil
16460 (not (get-text-property 0 'org-unrestricted
16461 (caar allowed))))
16462 (funcall set-function prompt
16463 (mapcar 'list (org-property-values property))
16464 nil nil "" nil cur))))
16465 (org-trim val)))
16467 (defvar org-last-set-property nil)
16468 (defvar org-last-set-property-value nil)
16469 (defun org-read-property-name ()
16470 "Read a property name."
16471 (let ((completion-ignore-case t)
16472 (default-prop (or (and (org-at-property-p)
16473 (match-string-no-properties 2))
16474 org-last-set-property)))
16475 (org-completing-read
16476 (concat "Property"
16477 (if default-prop (concat " [" default-prop "]") "")
16478 ": ")
16479 (mapcar #'list (org-buffer-property-keys nil t t))
16480 nil nil nil nil default-prop)))
16482 (defun org-set-property-and-value (use-last)
16483 "Allow to set [PROPERTY]: [value] direction from prompt.
16484 When use-default, don't even ask, just use the last
16485 \"[PROPERTY]: [value]\" string from the history."
16486 (interactive "P")
16487 (let* ((completion-ignore-case t)
16488 (pv (or (and use-last org-last-set-property-value)
16489 (org-completing-read
16490 "Enter a \"[Property]: [value]\" pair: "
16491 nil nil nil nil nil
16492 org-last-set-property-value)))
16493 prop val)
16494 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16495 (setq prop (match-string 1 pv)
16496 val (match-string 2 pv))
16497 (org-set-property prop val))))
16499 (defun org-set-property (property value)
16500 "In the current entry, set PROPERTY to VALUE.
16502 When called interactively, this will prompt for a property name, offering
16503 completion on existing and default properties. And then it will prompt
16504 for a value, offering completion either on allowed values (via an inherited
16505 xxx_ALL property) or on existing values in other instances of this property
16506 in the current file.
16508 Throw an error when trying to set a property with an invalid name."
16509 (interactive (list nil nil))
16510 (let ((property (or property (org-read-property-name))))
16511 ;; `org-entry-put' also makes the following check, but this one
16512 ;; avoids polluting `org-last-set-property' and
16513 ;; `org-last-set-property-value' needlessly.
16514 (unless (org--valid-property-p property)
16515 (user-error "Invalid property name: \"%s\"" property))
16516 (let ((value (or value (org-read-property-value property)))
16517 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16518 (setq org-last-set-property property)
16519 (setq org-last-set-property-value (concat property ": " value))
16520 ;; Possibly postprocess the inserted value:
16521 (when fn (setq value (funcall fn value)))
16522 (unless (equal (org-entry-get nil property) value)
16523 (org-entry-put nil property value)))))
16525 (defun org-find-property (property &optional value)
16526 "Find first entry in buffer that sets PROPERTY.
16528 When optional argument VALUE is non-nil, only consider an entry
16529 if it contains PROPERTY set to this value. If PROPERTY should be
16530 explicitly set to nil, use string \"nil\" for VALUE.
16532 Return position where the entry begins, or nil if there is no
16533 such entry. If narrowing is in effect, only search the visible
16534 part of the buffer."
16535 (save-excursion
16536 (goto-char (point-min))
16537 (let ((case-fold-search t)
16538 (re (org-re-property property nil (not value) value)))
16539 (catch 'exit
16540 (while (re-search-forward re nil t)
16541 (when (if value (org-at-property-p)
16542 (org-entry-get (point) property nil t))
16543 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16545 (defun org-delete-property (property)
16546 "In the current entry, delete PROPERTY."
16547 (interactive
16548 (let* ((completion-ignore-case t)
16549 (cat (org-entry-get (point) "CATEGORY"))
16550 (props0 (org-entry-properties nil 'standard))
16551 (props (if cat props0
16552 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16553 (prop (if (< 1 (length props))
16554 (completing-read "Property: " props nil t)
16555 (caar props))))
16556 (list prop)))
16557 (if (not property)
16558 (message "No property to delete in this entry")
16559 (org-entry-delete nil property)
16560 (message "Property \"%s\" deleted" property)))
16562 (defun org-delete-property-globally (property)
16563 "Remove PROPERTY globally, from all entries.
16564 This function ignores narrowing, if any."
16565 (interactive
16566 (let* ((completion-ignore-case t)
16567 (prop (completing-read
16568 "Globally remove property: "
16569 (mapcar #'list (org-buffer-property-keys)))))
16570 (list prop)))
16571 (org-with-wide-buffer
16572 (goto-char (point-min))
16573 (let ((count 0)
16574 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16575 (while (re-search-forward re nil t)
16576 (when (org-entry-delete (point) property) (cl-incf count)))
16577 (message "Property \"%s\" removed from %d entries" property count))))
16579 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16581 (defun org-compute-property-at-point ()
16582 "Compute the property at point.
16583 This looks for an enclosing column format, extracts the operator and
16584 then applies it to the property in the column format's scope."
16585 (interactive)
16586 (unless (org-at-property-p)
16587 (user-error "Not at a property"))
16588 (let ((prop (match-string-no-properties 2)))
16589 (org-columns-get-format-and-top-level)
16590 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16591 (user-error "No operator defined for property %s" prop))
16592 (org-columns-compute prop)))
16594 (defvar org-property-allowed-value-functions nil
16595 "Hook for functions supplying allowed values for a specific property.
16596 The functions must take a single argument, the name of the property, and
16597 return a flat list of allowed values. If \":ETC\" is one of
16598 the values, this means that these values are intended as defaults for
16599 completion, but that other values should be allowed too.
16600 The functions must return nil if they are not responsible for this
16601 property.")
16603 (defun org-property-get-allowed-values (pom property &optional table)
16604 "Get allowed values for the property PROPERTY.
16605 When TABLE is non-nil, return an alist that can directly be used for
16606 completion."
16607 (let (vals)
16608 (cond
16609 ((equal property "TODO")
16610 (setq vals (org-with-point-at pom
16611 (append org-todo-keywords-1 '("")))))
16612 ((equal property "PRIORITY")
16613 (let ((n org-lowest-priority))
16614 (while (>= n org-highest-priority)
16615 (push (char-to-string n) vals)
16616 (setq n (1- n)))))
16617 ((equal property "CATEGORY"))
16618 ((member property org-special-properties))
16619 ((setq vals (run-hook-with-args-until-success
16620 'org-property-allowed-value-functions property)))
16622 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16623 (when (and vals (string-match "\\S-" vals))
16624 (setq vals (car (read-from-string (concat "(" vals ")"))))
16625 (setq vals (mapcar (lambda (x)
16626 (cond ((stringp x) x)
16627 ((numberp x) (number-to-string x))
16628 ((symbolp x) (symbol-name x))
16629 (t "???")))
16630 vals)))))
16631 (when (member ":ETC" vals)
16632 (setq vals (remove ":ETC" vals))
16633 (org-add-props (car vals) '(org-unrestricted t)))
16634 (if table (mapcar 'list vals) vals)))
16636 (defun org-property-previous-allowed-value (&optional _previous)
16637 "Switch to the next allowed value for this property."
16638 (interactive)
16639 (org-property-next-allowed-value t))
16641 (defun org-property-next-allowed-value (&optional previous)
16642 "Switch to the next allowed value for this property."
16643 (interactive)
16644 (unless (org-at-property-p)
16645 (user-error "Not at a property"))
16646 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16647 (key (match-string 2))
16648 (value (match-string 3))
16649 (allowed (or (org-property-get-allowed-values (point) key)
16650 (and (member value '("[ ]" "[-]" "[X]"))
16651 '("[ ]" "[X]"))))
16652 (heading (save-match-data (nth 4 (org-heading-components))))
16653 nval)
16654 (unless allowed
16655 (user-error "Allowed values for this property have not been defined"))
16656 (when previous (setq allowed (reverse allowed)))
16657 (when (member value allowed)
16658 (setq nval (car (cdr (member value allowed)))))
16659 (setq nval (or nval (car allowed)))
16660 (when (equal nval value)
16661 (user-error "Only one allowed value for this property"))
16662 (org-at-property-p)
16663 (replace-match (concat " :" key ": " nval) t t)
16664 (org-indent-line)
16665 (beginning-of-line 1)
16666 (skip-chars-forward " \t")
16667 (when (equal prop org-effort-property)
16668 (org-refresh-property
16669 '((effort . identity)
16670 (effort-minutes . org-duration-string-to-minutes))
16671 nval)
16672 (when (string= org-clock-current-task heading)
16673 (setq org-clock-effort nval)
16674 (org-clock-update-mode-line)))
16675 (run-hook-with-args 'org-property-changed-functions key nval)))
16677 (defun org-find-olp (path &optional this-buffer)
16678 "Return a marker pointing to the entry at outline path OLP.
16679 If anything goes wrong, throw an error.
16680 You can wrap this call to catch the error like this:
16682 \(condition-case msg
16683 \(org-mobile-locate-entry (match-string 4))
16684 \(error (nth 1 msg)))
16686 The return value will then be either a string with the error message,
16687 or a marker if everything is OK.
16689 If THIS-BUFFER is set, the outline path does not contain a file,
16690 only headings."
16691 (let* ((file (if this-buffer buffer-file-name (pop path)))
16692 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16693 (level 1)
16694 (lmin 1)
16695 (lmax 1)
16696 end found flevel)
16697 (unless buffer (error "File not found :%s" file))
16698 (with-current-buffer buffer
16699 (org-with-wide-buffer
16700 (goto-char (point-min))
16701 (dolist (heading path)
16702 (let ((re (format org-complex-heading-regexp-format
16703 (regexp-quote heading)))
16704 (cnt 0))
16705 (while (re-search-forward re end t)
16706 (setq level (- (match-end 1) (match-beginning 1)))
16707 (when (and (>= level lmin) (<= level lmax))
16708 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16709 (when (= cnt 0)
16710 (error "Heading not found on level %d: %s" lmax heading))
16711 (when (> cnt 1)
16712 (error "Heading not unique on level %d: %s" lmax heading))
16713 (goto-char found)
16714 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16715 (setq end (save-excursion (org-end-of-subtree t t)))))
16716 (when (org-at-heading-p)
16717 (point-marker))))))
16719 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16720 "Find node HEADING in BUFFER.
16721 Return a marker to the heading if it was found, or nil if not.
16722 If POS-ONLY is set, return just the position instead of a marker.
16724 The heading text must match exact, but it may have a TODO keyword,
16725 a priority cookie and tags in the standard locations."
16726 (with-current-buffer (or buffer (current-buffer))
16727 (save-excursion
16728 (save-restriction
16729 (widen)
16730 (goto-char (point-min))
16731 (let (case-fold-search)
16732 (when (re-search-forward
16733 (format org-complex-heading-regexp-format
16734 (regexp-quote heading)) nil t)
16735 (if pos-only
16736 (match-beginning 0)
16737 (move-marker (make-marker) (match-beginning 0)))))))))
16739 (defun org-find-exact-heading-in-directory (heading &optional dir)
16740 "Find Org node headline HEADING in all .org files in directory DIR.
16741 When the target headline is found, return a marker to this location."
16742 (let ((files (directory-files (or dir default-directory)
16743 t "\\`[^.#].*\\.org\\'"))
16744 visiting m buffer)
16745 (catch 'found
16746 (dolist (file files)
16747 (message "trying %s" file)
16748 (setq visiting (org-find-base-buffer-visiting file))
16749 (setq buffer (or visiting (find-file-noselect file)))
16750 (setq m (org-find-exact-headline-in-buffer
16751 heading buffer))
16752 (when (and (not m) (not visiting)) (kill-buffer buffer))
16753 (and m (throw 'found m))))))
16755 (defun org-find-entry-with-id (ident)
16756 "Locate the entry that contains the ID property with exact value IDENT.
16757 IDENT can be a string, a symbol or a number, this function will search for
16758 the string representation of it.
16759 Return the position where this entry starts, or nil if there is no such entry."
16760 (interactive "sID: ")
16761 (let ((id (cond
16762 ((stringp ident) ident)
16763 ((symbolp ident) (symbol-name ident))
16764 ((numberp ident) (number-to-string ident))
16765 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16766 (org-with-wide-buffer (org-find-property "ID" id))))
16768 ;;;; Timestamps
16770 (defvar org-last-changed-timestamp nil)
16771 (defvar org-last-inserted-timestamp nil
16772 "The last time stamp inserted with `org-insert-time-stamp'.")
16773 (defvar org-ts-what) ; dynamically scoped parameter
16775 (defun org-time-stamp (arg &optional inactive)
16776 "Prompt for a date/time and insert a time stamp.
16778 If the user specifies a time like HH:MM or if this command is
16779 called with at least one prefix argument, the time stamp contains
16780 the date and the time. Otherwise, only the date is included.
16782 All parts of a date not specified by the user are filled in from
16783 the timestamp at point, if any, or the current date/time
16784 otherwise.
16786 If there is already a timestamp at the cursor, it is replaced.
16788 With two universal prefix arguments, insert an active timestamp
16789 with the current time without prompting the user.
16791 When called from lisp, the timestamp is inactive if INACTIVE is
16792 non-nil."
16793 (interactive "P")
16794 (let* ((ts (cond
16795 ((org-at-date-range-p t)
16796 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16797 ((org-at-timestamp-p t) (match-string 0))))
16798 ;; Default time is either the timestamp at point or today.
16799 ;; When entering a range, only the range start is considered.
16800 (default-time (if (not ts) (current-time)
16801 (apply #'encode-time (org-parse-time-string ts))))
16802 (default-input (and ts (org-get-compact-tod ts)))
16803 (repeater (and ts
16804 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16805 (match-string 0 ts)))
16806 org-time-was-given
16807 org-end-time-was-given
16808 (time
16809 (and (if (equal arg '(16)) (current-time)
16810 ;; Preserve `this-command' and `last-command'.
16811 (let ((this-command this-command)
16812 (last-command last-command))
16813 (org-read-date
16814 arg 'totime nil nil default-time default-input
16815 inactive))))))
16816 (cond
16817 ((and ts
16818 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16819 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16820 (insert "--")
16821 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16823 ;; Make sure we're on a timestamp. When in the middle of a date
16824 ;; range, move arbitrarily to range end.
16825 (unless (org-at-timestamp-p t)
16826 (skip-chars-forward "-")
16827 (org-at-timestamp-p t))
16828 (replace-match "")
16829 (setq org-last-changed-timestamp
16830 (org-insert-time-stamp
16831 time (or org-time-was-given arg)
16832 inactive nil nil (list org-end-time-was-given)))
16833 (when repeater
16834 (backward-char)
16835 (insert " " repeater)
16836 (setq org-last-changed-timestamp
16837 (concat (substring org-last-inserted-timestamp 0 -1)
16838 " " repeater ">")))
16839 (message "Timestamp updated"))
16840 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16841 (t (org-insert-time-stamp
16842 time (or org-time-was-given arg) inactive nil nil
16843 (list org-end-time-was-given))))))
16845 ;; FIXME: can we use this for something else, like computing time differences?
16846 (defun org-get-compact-tod (s)
16847 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16848 (let* ((t1 (match-string 1 s))
16849 (h1 (string-to-number (match-string 2 s)))
16850 (m1 (string-to-number (match-string 3 s)))
16851 (t2 (and (match-end 4) (match-string 5 s)))
16852 (h2 (and t2 (string-to-number (match-string 6 s))))
16853 (m2 (and t2 (string-to-number (match-string 7 s))))
16854 dh dm)
16855 (if (not t2)
16857 (setq dh (- h2 h1) dm (- m2 m1))
16858 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16859 (concat t1 "+" (number-to-string dh)
16860 (and (/= 0 dm) (format ":%02d" dm)))))))
16862 (defun org-time-stamp-inactive (&optional arg)
16863 "Insert an inactive time stamp.
16864 An inactive time stamp is enclosed in square brackets instead of angle
16865 brackets. It is inactive in the sense that it does not trigger agenda entries,
16866 does not link to the calendar and cannot be changed with the S-cursor keys.
16867 So these are more for recording a certain time/date."
16868 (interactive "P")
16869 (org-time-stamp arg 'inactive))
16871 (defvar org-date-ovl (make-overlay 1 1))
16872 (overlay-put org-date-ovl 'face 'org-date-selected)
16873 (delete-overlay org-date-ovl)
16875 (defvar org-ans1) ; dynamically scoped parameter
16876 (defvar org-ans2) ; dynamically scoped parameter
16878 (defvar org-plain-time-of-day-regexp) ; defined below
16880 (defvar org-overriding-default-time nil) ; dynamically scoped
16881 (defvar org-read-date-overlay nil)
16882 (defvar org-dcst nil) ; dynamically scoped
16883 (defvar org-read-date-history nil)
16884 (defvar org-read-date-final-answer nil)
16885 (defvar org-read-date-analyze-futurep nil)
16886 (defvar org-read-date-analyze-forced-year nil)
16887 (defvar org-read-date-inactive)
16889 (defvar org-read-date-minibuffer-local-map
16890 (let* ((map (make-sparse-keymap)))
16891 (set-keymap-parent map minibuffer-local-map)
16892 (org-defkey map (kbd ".")
16893 (lambda () (interactive)
16894 ;; Are we at the beginning of the prompt?
16895 (if (looking-back "^[^:]+: "
16896 (let ((inhibit-field-text-motion t))
16897 (line-beginning-position)))
16898 (org-eval-in-calendar '(calendar-goto-today))
16899 (insert "."))))
16900 (org-defkey map (kbd "C-.")
16901 (lambda () (interactive)
16902 (org-eval-in-calendar '(calendar-goto-today))))
16903 (org-defkey map [(meta shift left)]
16904 (lambda () (interactive)
16905 (org-eval-in-calendar '(calendar-backward-month 1))))
16906 (org-defkey map [(meta shift right)]
16907 (lambda () (interactive)
16908 (org-eval-in-calendar '(calendar-forward-month 1))))
16909 (org-defkey map [(meta shift up)]
16910 (lambda () (interactive)
16911 (org-eval-in-calendar '(calendar-backward-year 1))))
16912 (org-defkey map [(meta shift down)]
16913 (lambda () (interactive)
16914 (org-eval-in-calendar '(calendar-forward-year 1))))
16915 (org-defkey map [?\e (shift left)]
16916 (lambda () (interactive)
16917 (org-eval-in-calendar '(calendar-backward-month 1))))
16918 (org-defkey map [?\e (shift right)]
16919 (lambda () (interactive)
16920 (org-eval-in-calendar '(calendar-forward-month 1))))
16921 (org-defkey map [?\e (shift up)]
16922 (lambda () (interactive)
16923 (org-eval-in-calendar '(calendar-backward-year 1))))
16924 (org-defkey map [?\e (shift down)]
16925 (lambda () (interactive)
16926 (org-eval-in-calendar '(calendar-forward-year 1))))
16927 (org-defkey map [(shift up)]
16928 (lambda () (interactive)
16929 (org-eval-in-calendar '(calendar-backward-week 1))))
16930 (org-defkey map [(shift down)]
16931 (lambda () (interactive)
16932 (org-eval-in-calendar '(calendar-forward-week 1))))
16933 (org-defkey map [(shift left)]
16934 (lambda () (interactive)
16935 (org-eval-in-calendar '(calendar-backward-day 1))))
16936 (org-defkey map [(shift right)]
16937 (lambda () (interactive)
16938 (org-eval-in-calendar '(calendar-forward-day 1))))
16939 (org-defkey map "!"
16940 (lambda () (interactive)
16941 (org-eval-in-calendar '(diary-view-entries))
16942 (message "")))
16943 (org-defkey map ">"
16944 (lambda () (interactive)
16945 (org-eval-in-calendar '(calendar-scroll-left 1))))
16946 (org-defkey map "<"
16947 (lambda () (interactive)
16948 (org-eval-in-calendar '(calendar-scroll-right 1))))
16949 (org-defkey map "\C-v"
16950 (lambda () (interactive)
16951 (org-eval-in-calendar
16952 '(calendar-scroll-left-three-months 1))))
16953 (org-defkey map "\M-v"
16954 (lambda () (interactive)
16955 (org-eval-in-calendar
16956 '(calendar-scroll-right-three-months 1))))
16957 map)
16958 "Keymap for minibuffer commands when using `org-read-date'.")
16960 (defvar org-def)
16961 (defvar org-defdecode)
16962 (defvar org-with-time)
16964 (defvar calendar-setup) ; Dynamically scoped.
16965 (defun org-read-date (&optional with-time to-time from-string prompt
16966 default-time default-input inactive)
16967 "Read a date, possibly a time, and make things smooth for the user.
16968 The prompt will suggest to enter an ISO date, but you can also enter anything
16969 which will at least partially be understood by `parse-time-string'.
16970 Unrecognized parts of the date will default to the current day, month, year,
16971 hour and minute. If this command is called to replace a timestamp at point,
16972 or to enter the second timestamp of a range, the default time is taken
16973 from the existing stamp. Furthermore, the command prefers the future,
16974 so if you are giving a date where the year is not given, and the day-month
16975 combination is already past in the current year, it will assume you
16976 mean next year. For details, see the manual. A few examples:
16978 3-2-5 --> 2003-02-05
16979 feb 15 --> currentyear-02-15
16980 2/15 --> currentyear-02-15
16981 sep 12 9 --> 2009-09-12
16982 12:45 --> today 12:45
16983 22 sept 0:34 --> currentyear-09-22 0:34
16984 12 --> currentyear-currentmonth-12
16985 Fri --> nearest Friday after today
16986 -Tue --> last Tuesday
16987 etc.
16989 Furthermore you can specify a relative date by giving, as the *first* thing
16990 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16991 change in days weeks, months, years.
16992 With a single plus or minus, the date is relative to today. With a double
16993 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16994 +4d --> four days from today
16995 +4 --> same as above
16996 +2w --> two weeks from today
16997 ++5 --> five days from default date
16999 The function understands only English month and weekday abbreviations.
17001 While prompting, a calendar is popped up - you can also select the
17002 date with the mouse (button 1). The calendar shows a period of three
17003 months. To scroll it to other months, use the keys `>' and `<'.
17004 If you don't like the calendar, turn it off with
17005 (setq org-read-date-popup-calendar nil)
17007 With optional argument TO-TIME, the date will immediately be converted
17008 to an internal time.
17009 With an optional argument WITH-TIME, the prompt will suggest to
17010 also insert a time. Note that when WITH-TIME is not set, you can
17011 still enter a time, and this function will inform the calling routine
17012 about this change. The calling routine may then choose to change the
17013 format used to insert the time stamp into the buffer to include the time.
17014 With optional argument FROM-STRING, read from this string instead from
17015 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17016 the time/date that is used for everything that is not specified by the
17017 user."
17018 (require 'parse-time)
17019 (let* ((org-with-time with-time)
17020 (org-time-stamp-rounding-minutes
17021 (if (equal org-with-time '(16))
17022 '(0 0)
17023 org-time-stamp-rounding-minutes))
17024 (org-dcst org-display-custom-times)
17025 (ct (org-current-time))
17026 (org-def (or org-overriding-default-time default-time ct))
17027 (org-defdecode (decode-time org-def))
17028 (cur-frame (selected-frame))
17029 (mouse-autoselect-window nil) ; Don't let the mouse jump
17030 (calendar-setup
17031 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17032 (calendar-move-hook nil)
17033 (calendar-view-diary-initially-flag nil)
17034 (calendar-view-holidays-initially-flag nil)
17035 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17036 ;; Rationalize `org-def' and `org-defdecode', if required.
17037 (when (< (nth 2 org-defdecode) org-extend-today-until)
17038 (setf (nth 2 org-defdecode) -1)
17039 (setf (nth 1 org-defdecode) 59)
17040 (setq org-def (apply #'encode-time org-defdecode))
17041 (setq org-defdecode (decode-time org-def)))
17042 (let* ((timestr (format-time-string
17043 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17044 org-def))
17045 (prompt (concat (if prompt (concat prompt " ") "")
17046 (format "Date+time [%s]: " timestr))))
17047 (cond
17048 (from-string (setq ans from-string))
17049 (org-read-date-popup-calendar
17050 (save-excursion
17051 (save-window-excursion
17052 (calendar)
17053 (when (eq calendar-setup 'calendar-only)
17054 (setq cal-frame
17055 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17056 (select-frame cal-frame))
17057 (org-eval-in-calendar '(setq cursor-type nil) t)
17058 (unwind-protect
17059 (progn
17060 (calendar-forward-day (- (time-to-days org-def)
17061 (calendar-absolute-from-gregorian
17062 (calendar-current-date))))
17063 (org-eval-in-calendar nil t)
17064 (let* ((old-map (current-local-map))
17065 (map (copy-keymap calendar-mode-map))
17066 (minibuffer-local-map
17067 (copy-keymap org-read-date-minibuffer-local-map)))
17068 (org-defkey map (kbd "RET") 'org-calendar-select)
17069 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17070 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17071 (unwind-protect
17072 (progn
17073 (use-local-map map)
17074 (setq org-read-date-inactive inactive)
17075 (add-hook 'post-command-hook 'org-read-date-display)
17076 (setq org-ans0
17077 (read-string prompt
17078 default-input
17079 'org-read-date-history
17080 nil))
17081 ;; org-ans0: from prompt
17082 ;; org-ans1: from mouse click
17083 ;; org-ans2: from calendar motion
17084 (setq ans
17085 (concat org-ans0 " " (or org-ans1 org-ans2))))
17086 (remove-hook 'post-command-hook 'org-read-date-display)
17087 (use-local-map old-map)
17088 (when org-read-date-overlay
17089 (delete-overlay org-read-date-overlay)
17090 (setq org-read-date-overlay nil)))))
17091 (bury-buffer "*Calendar*")
17092 (when cal-frame
17093 (delete-frame cal-frame)
17094 (select-frame-set-input-focus cur-frame))))))
17096 (t ; Naked prompt only
17097 (unwind-protect
17098 (setq ans (read-string prompt default-input
17099 'org-read-date-history timestr))
17100 (when org-read-date-overlay
17101 (delete-overlay org-read-date-overlay)
17102 (setq org-read-date-overlay nil))))))
17104 (setq final (org-read-date-analyze ans org-def org-defdecode))
17106 (when org-read-date-analyze-forced-year
17107 (message "Year was forced into %s"
17108 (if org-read-date-force-compatible-dates
17109 "compatible range (1970-2037)"
17110 "range representable on this machine"))
17111 (ding))
17113 ;; One round trip to get rid of 34th of August and stuff like that....
17114 (setq final (decode-time (apply 'encode-time final)))
17116 (setq org-read-date-final-answer ans)
17118 (if to-time
17119 (apply 'encode-time final)
17120 (if (and (boundp 'org-time-was-given) org-time-was-given)
17121 (format "%04d-%02d-%02d %02d:%02d"
17122 (nth 5 final) (nth 4 final) (nth 3 final)
17123 (nth 2 final) (nth 1 final))
17124 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17126 (defun org-read-date-display ()
17127 "Display the current date prompt interpretation in the minibuffer."
17128 (when org-read-date-display-live
17129 (when org-read-date-overlay
17130 (delete-overlay org-read-date-overlay))
17131 (when (minibufferp (current-buffer))
17132 (save-excursion
17133 (end-of-line 1)
17134 (while (not (equal (buffer-substring
17135 (max (point-min) (- (point) 4)) (point))
17136 " "))
17137 (insert " ")))
17138 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17139 " " (or org-ans1 org-ans2)))
17140 (org-end-time-was-given nil)
17141 (f (org-read-date-analyze ans org-def org-defdecode))
17142 (fmts (if org-dcst
17143 org-time-stamp-custom-formats
17144 org-time-stamp-formats))
17145 (fmt (if (or org-with-time
17146 (and (boundp 'org-time-was-given) org-time-was-given))
17147 (cdr fmts)
17148 (car fmts)))
17149 (txt (format-time-string fmt (apply 'encode-time f)))
17150 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17151 (txt (concat "=> " txt)))
17152 (when (and org-end-time-was-given
17153 (string-match org-plain-time-of-day-regexp txt))
17154 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17155 org-end-time-was-given
17156 (substring txt (match-end 0)))))
17157 (when org-read-date-analyze-futurep
17158 (setq txt (concat txt " (=>F)")))
17159 (setq org-read-date-overlay
17160 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17161 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17163 (defun org-read-date-analyze (ans def defdecode)
17164 "Analyze the combined answer of the date prompt."
17165 ;; FIXME: cleanup and comment
17166 ;; Pass `current-time' result to `decode-time' (instead of calling
17167 ;; without arguments) so that only `current-time' has to be
17168 ;; overriden in tests.
17169 (let ((org-def def)
17170 (org-defdecode defdecode)
17171 (nowdecode (decode-time (current-time)))
17172 delta deltan deltaw deltadef year month day
17173 hour minute second wday pm h2 m2 tl wday1
17174 iso-year iso-weekday iso-week iso-date futurep kill-year)
17175 (setq org-read-date-analyze-futurep nil
17176 org-read-date-analyze-forced-year nil)
17177 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17178 (setq ans "+0"))
17180 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17181 (setq ans (replace-match "" t t ans)
17182 deltan (car delta)
17183 deltaw (nth 1 delta)
17184 deltadef (nth 2 delta)))
17186 ;; Check if there is an iso week date in there. If yes, store the
17187 ;; info and postpone interpreting it until the rest of the parsing
17188 ;; is done.
17189 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17190 (setq iso-year (when (match-end 1)
17191 (org-small-year-to-year
17192 (string-to-number (match-string 1 ans))))
17193 iso-weekday (when (match-end 3)
17194 (string-to-number (match-string 3 ans)))
17195 iso-week (string-to-number (match-string 2 ans)))
17196 (setq ans (replace-match "" t t ans)))
17198 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17199 (when (string-match
17200 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17201 (setq year (if (match-end 2)
17202 (string-to-number (match-string 2 ans))
17203 (progn (setq kill-year t)
17204 (string-to-number (format-time-string "%Y"))))
17205 month (string-to-number (match-string 3 ans))
17206 day (string-to-number (match-string 4 ans)))
17207 (setq year (org-small-year-to-year year))
17208 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17209 t nil ans)))
17211 ;; Help matching dotted european dates
17212 (when (string-match
17213 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17214 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17215 (setq kill-year t)
17216 (string-to-number (format-time-string "%Y")))
17217 day (string-to-number (match-string 1 ans))
17218 month (string-to-number (match-string 2 ans))
17219 ans (replace-match (format "%04d-%02d-%02d" year month day)
17220 t nil ans)))
17222 ;; Help matching american dates, like 5/30 or 5/30/7
17223 (when (string-match
17224 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17225 (setq year (if (match-end 4)
17226 (string-to-number (match-string 4 ans))
17227 (progn (setq kill-year t)
17228 (string-to-number (format-time-string "%Y"))))
17229 month (string-to-number (match-string 1 ans))
17230 day (string-to-number (match-string 2 ans)))
17231 (setq year (org-small-year-to-year year))
17232 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17233 t nil ans)))
17234 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17235 ;; If there is a time with am/pm, and *no* time without it, we convert
17236 ;; so that matching will be successful.
17237 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17238 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17239 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17240 (setq hour (string-to-number (match-string 1 ans))
17241 minute (if (match-end 3)
17242 (string-to-number (match-string 3 ans))
17244 pm (equal ?p
17245 (string-to-char (downcase (match-string 4 ans)))))
17246 (if (and (= hour 12) (not pm))
17247 (setq hour 0)
17248 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17249 (setq ans (replace-match (format "%02d:%02d" hour minute)
17250 t t ans))))
17252 ;; Check if a time range is given as a duration
17253 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17254 (setq hour (string-to-number (match-string 1 ans))
17255 h2 (+ hour (string-to-number (match-string 3 ans)))
17256 minute (string-to-number (match-string 2 ans))
17257 m2 (+ minute (if (match-end 5) (string-to-number
17258 (match-string 5 ans))0)))
17259 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17260 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17261 t t ans)))
17263 ;; Check if there is a time range
17264 (when (boundp 'org-end-time-was-given)
17265 (setq org-time-was-given nil)
17266 (when (and (string-match org-plain-time-of-day-regexp ans)
17267 (match-end 8))
17268 (setq org-end-time-was-given (match-string 8 ans))
17269 (setq ans (concat (substring ans 0 (match-beginning 7))
17270 (substring ans (match-end 7))))))
17272 (setq tl (parse-time-string ans)
17273 day (or (nth 3 tl) (nth 3 org-defdecode))
17274 month
17275 (cond ((nth 4 tl))
17276 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17277 ;; Day was specified. Make sure DAY+MONTH
17278 ;; combination happens in the future.
17279 ((nth 3 tl)
17280 (setq futurep t)
17281 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17282 (nth 4 nowdecode)))
17283 (t (nth 4 org-defdecode)))
17284 year
17285 (cond ((and (not kill-year) (nth 5 tl)))
17286 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17287 ;; Month was guessed in the future and is at least
17288 ;; equal to NOWDECODE's. Fix year accordingly.
17289 (futurep
17290 (if (or (> month (nth 4 nowdecode))
17291 (>= day (nth 3 nowdecode)))
17292 (nth 5 nowdecode)
17293 (1+ (nth 5 nowdecode))))
17294 ;; Month was specified. Make sure MONTH+YEAR
17295 ;; combination happens in the future.
17296 ((nth 4 tl)
17297 (setq futurep t)
17298 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17299 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17300 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17301 (t (nth 5 nowdecode))))
17302 (t (nth 5 org-defdecode)))
17303 hour (or (nth 2 tl) (nth 2 org-defdecode))
17304 minute (or (nth 1 tl) (nth 1 org-defdecode))
17305 second (or (nth 0 tl) 0)
17306 wday (nth 6 tl))
17308 (when (and (eq org-read-date-prefer-future 'time)
17309 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17310 (equal day (nth 3 nowdecode))
17311 (equal month (nth 4 nowdecode))
17312 (equal year (nth 5 nowdecode))
17313 (nth 2 tl)
17314 (or (< (nth 2 tl) (nth 2 nowdecode))
17315 (and (= (nth 2 tl) (nth 2 nowdecode))
17316 (nth 1 tl)
17317 (< (nth 1 tl) (nth 1 nowdecode)))))
17318 (setq day (1+ day)
17319 futurep t))
17321 ;; Special date definitions below
17322 (cond
17323 (iso-week
17324 ;; There was an iso week
17325 (require 'cal-iso)
17326 (setq futurep nil)
17327 (setq year (or iso-year year)
17328 day (or iso-weekday wday 1)
17329 wday nil ; to make sure that the trigger below does not match
17330 iso-date (calendar-gregorian-from-absolute
17331 (calendar-iso-to-absolute
17332 (list iso-week day year))))
17333 ; FIXME: Should we also push ISO weeks into the future?
17334 ; (when (and org-read-date-prefer-future
17335 ; (not iso-year)
17336 ; (< (calendar-absolute-from-gregorian iso-date)
17337 ; (time-to-days (current-time))))
17338 ; (setq year (1+ year)
17339 ; iso-date (calendar-gregorian-from-absolute
17340 ; (calendar-iso-to-absolute
17341 ; (list iso-week day year)))))
17342 (setq month (car iso-date)
17343 year (nth 2 iso-date)
17344 day (nth 1 iso-date)))
17345 (deltan
17346 (setq futurep nil)
17347 (unless deltadef
17348 ;; Pass `current-time' result to `decode-time' (instead of
17349 ;; calling without arguments) so that only `current-time' has
17350 ;; to be overriden in tests.
17351 (let ((now (decode-time (current-time))))
17352 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17353 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17354 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17355 ((equal deltaw "m") (setq month (+ month deltan)))
17356 ((equal deltaw "y") (setq year (+ year deltan)))))
17357 ((and wday (not (nth 3 tl)))
17358 ;; Weekday was given, but no day, so pick that day in the week
17359 ;; on or after the derived date.
17360 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17361 (unless (equal wday wday1)
17362 (setq day (+ day (% (- wday wday1 -7) 7))))))
17363 (when (and (boundp 'org-time-was-given)
17364 (nth 2 tl))
17365 (setq org-time-was-given t))
17366 (when (< year 100) (setq year (+ 2000 year)))
17367 ;; Check of the date is representable
17368 (if org-read-date-force-compatible-dates
17369 (progn
17370 (when (< year 1970)
17371 (setq year 1970 org-read-date-analyze-forced-year t))
17372 (when (> year 2037)
17373 (setq year 2037 org-read-date-analyze-forced-year t)))
17374 (condition-case nil
17375 (ignore (encode-time second minute hour day month year))
17376 (error
17377 (setq year (nth 5 org-defdecode))
17378 (setq org-read-date-analyze-forced-year t))))
17379 (setq org-read-date-analyze-futurep futurep)
17380 (list second minute hour day month year)))
17382 (defvar parse-time-weekdays)
17383 (defun org-read-date-get-relative (s today default)
17384 "Check string S for special relative date string.
17385 TODAY and DEFAULT are internal times, for today and for a default.
17386 Return shift list (N what def-flag)
17387 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17388 N is the number of WHATs to shift.
17389 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17390 the DEFAULT date rather than TODAY."
17391 (require 'parse-time)
17392 (when (and
17393 (string-match
17394 (concat
17395 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17396 "\\([0-9]+\\)?"
17397 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17398 "\\([ \t]\\|$\\)") s)
17399 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17400 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17401 (string-to-char (substring (match-string 1 s) -1))
17402 ?+))
17403 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17404 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17405 (what (if (match-end 3) (match-string 3 s) "d"))
17406 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17407 (date (if rel default today))
17408 (wday (nth 6 (decode-time date)))
17409 delta)
17410 (if wday1
17411 (progn
17412 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17413 (when (= delta 0) (setq delta 7))
17414 (when (= dir ?-)
17415 (setq delta (- delta 7))
17416 (when (= delta 0) (setq delta -7)))
17417 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17418 (list delta "d" rel))
17419 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17421 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17422 "Turn a user-specified date into the internal representation.
17423 The internal representation needed by the calendar is (month day year).
17424 This is a wrapper to handle the brain-dead convention in calendar that
17425 user function argument order change dependent on argument order."
17426 (pcase calendar-date-style
17427 (`american (list arg1 arg2 arg3))
17428 (`european (list arg2 arg1 arg3))
17429 (`iso (list arg2 arg3 arg1))))
17431 (defun org-eval-in-calendar (form &optional keepdate)
17432 "Eval FORM in the calendar window and return to current window.
17433 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17434 (let ((sf (selected-frame))
17435 (sw (selected-window)))
17436 (select-window (get-buffer-window "*Calendar*" t))
17437 (eval form)
17438 (when (and (not keepdate) (calendar-cursor-to-date))
17439 (let* ((date (calendar-cursor-to-date))
17440 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17441 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17442 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17443 (select-window sw)
17444 (select-frame-set-input-focus sf)))
17446 (defun org-calendar-select ()
17447 "Return to `org-read-date' with the date currently selected.
17448 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17449 (interactive)
17450 (when (calendar-cursor-to-date)
17451 (let* ((date (calendar-cursor-to-date))
17452 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17453 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17454 (when (active-minibuffer-window) (exit-minibuffer))))
17456 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17457 "Insert a date stamp for the date given by the internal TIME.
17458 See `format-time-string' for the format of TIME.
17459 WITH-HM means use the stamp format that includes the time of the day.
17460 INACTIVE means use square brackets instead of angular ones, so that the
17461 stamp will not contribute to the agenda.
17462 PRE and POST are optional strings to be inserted before and after the
17463 stamp.
17464 The command returns the inserted time stamp."
17465 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17466 stamp)
17467 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17468 (insert-before-markers (or pre ""))
17469 (when (listp extra)
17470 (setq extra (car extra))
17471 (if (and (stringp extra)
17472 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17473 (setq extra (format "-%02d:%02d"
17474 (string-to-number (match-string 1 extra))
17475 (string-to-number (match-string 2 extra))))
17476 (setq extra nil)))
17477 (when extra
17478 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17479 (insert-before-markers (setq stamp (format-time-string fmt time)))
17480 (insert-before-markers (or post ""))
17481 (setq org-last-inserted-timestamp stamp)))
17483 (defun org-toggle-time-stamp-overlays ()
17484 "Toggle the use of custom time stamp formats."
17485 (interactive)
17486 (setq org-display-custom-times (not org-display-custom-times))
17487 (unless org-display-custom-times
17488 (let ((p (point-min)) (bmp (buffer-modified-p)))
17489 (while (setq p (next-single-property-change p 'display))
17490 (when (and (get-text-property p 'display)
17491 (eq (get-text-property p 'face) 'org-date))
17492 (remove-text-properties
17493 p (setq p (next-single-property-change p 'display))
17494 '(display t))))
17495 (set-buffer-modified-p bmp)))
17496 (org-restart-font-lock)
17497 (setq org-table-may-need-update t)
17498 (if org-display-custom-times
17499 (message "Time stamps are overlaid with custom format")
17500 (message "Time stamp overlays removed")))
17502 (defun org-display-custom-time (beg end)
17503 "Overlay modified time stamp format over timestamp between BEG and END."
17504 (let* ((ts (buffer-substring beg end))
17505 t1 w1 with-hm tf time str w2 (off 0))
17506 (save-match-data
17507 (setq t1 (org-parse-time-string ts t))
17508 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17509 (setq off (- (match-end 0) (match-beginning 0)))))
17510 (setq end (- end off))
17511 (setq w1 (- end beg)
17512 with-hm (and (nth 1 t1) (nth 2 t1))
17513 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17514 time (org-fix-decoded-time t1)
17515 str (org-add-props
17516 (format-time-string
17517 (substring tf 1 -1) (apply 'encode-time time))
17518 nil 'mouse-face 'highlight)
17519 w2 (length str))
17520 (unless (= w2 w1)
17521 (add-text-properties (1+ beg) (+ 2 beg)
17522 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17523 (put-text-property beg end 'display str)))
17525 (defun org-fix-decoded-time (time)
17526 "Set 0 instead of nil for the first 6 elements of time.
17527 Don't touch the rest."
17528 (let ((n 0))
17529 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17531 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17532 "Difference between TIMESTAMP-STRING and now in days.
17533 If SECONDS is non-nil, return the difference in seconds."
17534 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17535 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17536 (funcall fdiff (current-time)))))
17538 (defun org-deadline-close-p (timestamp-string &optional ndays)
17539 "Is the time in TIMESTAMP-STRING close to the current date?"
17540 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17541 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17542 (not (org-entry-is-done-p))))
17544 (defun org-get-wdays (ts &optional delay zero-delay)
17545 "Get the deadline lead time appropriate for timestring TS.
17546 When DELAY is non-nil, get the delay time for scheduled items
17547 instead of the deadline lead time. When ZERO-DELAY is non-nil
17548 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17549 don't try to find the delay cookie in the scheduled timestamp."
17550 (let ((tv (if delay org-scheduled-delay-days
17551 org-deadline-warning-days)))
17552 (cond
17553 ((or (and delay (< tv 0))
17554 (and delay zero-delay (<= tv 0))
17555 (and (not delay) (<= tv 0)))
17556 ;; Enforce this value no matter what
17557 (- tv))
17558 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17559 ;; lead time is specified.
17560 (floor (* (string-to-number (match-string 1 ts))
17561 (cdr (assoc (match-string 2 ts)
17562 '(("d" . 1) ("w" . 7)
17563 ("m" . 30.4) ("y" . 365.25)
17564 ("h" . 0.041667)))))))
17565 ;; go for the default.
17566 (t tv))))
17568 (defun org-calendar-select-mouse (ev)
17569 "Return to `org-read-date' with the date currently selected.
17570 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17571 (interactive "e")
17572 (mouse-set-point ev)
17573 (when (calendar-cursor-to-date)
17574 (let* ((date (calendar-cursor-to-date))
17575 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17576 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17577 (when (active-minibuffer-window) (exit-minibuffer))))
17579 (defun org-check-deadlines (ndays)
17580 "Check if there are any deadlines due or past due.
17581 A deadline is considered due if it happens within `org-deadline-warning-days'
17582 days from today's date. If the deadline appears in an entry marked DONE,
17583 it is not shown. The prefix arg NDAYS can be used to test that many
17584 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17585 (interactive "P")
17586 (let* ((org-warn-days
17587 (cond
17588 ((equal ndays '(4)) 100000)
17589 (ndays (prefix-numeric-value ndays))
17590 (t (abs org-deadline-warning-days))))
17591 (case-fold-search nil)
17592 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17593 (callback
17594 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17595 (message "%d deadlines past-due or due within %d days"
17596 (org-occur regexp nil callback)
17597 org-warn-days)))
17599 (defsubst org-re-timestamp (type)
17600 "Return a regexp for timestamp TYPE.
17601 Allowed values for TYPE are:
17603 all: all timestamps
17604 active: only active timestamps (<...>)
17605 inactive: only inactive timestamps ([...])
17606 scheduled: only scheduled timestamps
17607 deadline: only deadline timestamps
17608 closed: only closed time-stamps
17610 When TYPE is nil, fall back on returning a regexp that matches
17611 both scheduled and deadline timestamps."
17612 (cl-case type
17613 (all org-ts-regexp-both)
17614 (active org-ts-regexp)
17615 (inactive org-ts-regexp-inactive)
17616 (scheduled org-scheduled-time-regexp)
17617 (deadline org-deadline-time-regexp)
17618 (closed org-closed-time-regexp)
17619 (otherwise
17620 (concat "\\<"
17621 (regexp-opt (list org-deadline-string org-scheduled-string))
17622 " *<\\([^>]+\\)>"))))
17624 (defun org-check-before-date (d)
17625 "Check if there are deadlines or scheduled entries before date D."
17626 (interactive (list (org-read-date)))
17627 (let* ((case-fold-search nil)
17628 (regexp (org-re-timestamp org-ts-type))
17629 (ts-type org-ts-type)
17630 (callback
17631 (lambda ()
17632 (let ((match (match-string 1)))
17633 (and (if (memq ts-type '(active inactive all))
17634 (eq (org-element-type (save-excursion
17635 (backward-char)
17636 (org-element-context)))
17637 'timestamp)
17638 (org-at-planning-p))
17639 (time-less-p
17640 (org-time-string-to-time match)
17641 (org-time-string-to-time d)))))))
17642 (message "%d entries before %s"
17643 (org-occur regexp nil callback)
17644 d)))
17646 (defun org-check-after-date (d)
17647 "Check if there are deadlines or scheduled entries after date D."
17648 (interactive (list (org-read-date)))
17649 (let* ((case-fold-search nil)
17650 (regexp (org-re-timestamp org-ts-type))
17651 (ts-type org-ts-type)
17652 (callback
17653 (lambda ()
17654 (let ((match (match-string 1)))
17655 (and (if (memq ts-type '(active inactive all))
17656 (eq (org-element-type (save-excursion
17657 (backward-char)
17658 (org-element-context)))
17659 'timestamp)
17660 (org-at-planning-p))
17661 (not (time-less-p
17662 (org-time-string-to-time match)
17663 (org-time-string-to-time d))))))))
17664 (message "%d entries after %s"
17665 (org-occur regexp nil callback)
17666 d)))
17668 (defun org-check-dates-range (start-date end-date)
17669 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17670 (interactive (list (org-read-date nil nil nil "Range starts")
17671 (org-read-date nil nil nil "Range end")))
17672 (let ((case-fold-search nil)
17673 (regexp (org-re-timestamp org-ts-type))
17674 (callback
17675 (let ((type org-ts-type))
17676 (lambda ()
17677 (let ((match (match-string 1)))
17678 (and
17679 (if (memq type '(active inactive all))
17680 (eq (org-element-type (save-excursion
17681 (backward-char)
17682 (org-element-context)))
17683 'timestamp)
17684 (org-at-planning-p))
17685 (not (time-less-p
17686 (org-time-string-to-time match)
17687 (org-time-string-to-time start-date)))
17688 (time-less-p
17689 (org-time-string-to-time match)
17690 (org-time-string-to-time end-date))))))))
17691 (message "%d entries between %s and %s"
17692 (org-occur regexp nil callback) start-date end-date)))
17694 (defun org-evaluate-time-range (&optional to-buffer)
17695 "Evaluate a time range by computing the difference between start and end.
17696 Normally the result is just printed in the echo area, but with prefix arg
17697 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17698 If the time range is actually in a table, the result is inserted into the
17699 next column.
17700 For time difference computation, a year is assumed to be exactly 365
17701 days in order to avoid rounding problems."
17702 (interactive "P")
17704 (org-clock-update-time-maybe)
17705 (save-excursion
17706 (unless (org-at-date-range-p t)
17707 (goto-char (point-at-bol))
17708 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17709 (unless (org-at-date-range-p t)
17710 (user-error "Not at a time-stamp range, and none found in current line")))
17711 (let* ((ts1 (match-string 1))
17712 (ts2 (match-string 2))
17713 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17714 (match-end (match-end 0))
17715 (time1 (org-time-string-to-time ts1))
17716 (time2 (org-time-string-to-time ts2))
17717 (t1 (float-time time1))
17718 (t2 (float-time time2))
17719 (diff (abs (- t2 t1)))
17720 (negative (< (- t2 t1) 0))
17721 ;; (ys (floor (* 365 24 60 60)))
17722 (ds (* 24 60 60))
17723 (hs (* 60 60))
17724 (fy "%dy %dd %02d:%02d")
17725 (fy1 "%dy %dd")
17726 (fd "%dd %02d:%02d")
17727 (fd1 "%dd")
17728 (fh "%02d:%02d")
17729 y d h m align)
17730 (if havetime
17731 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17733 d (floor (/ diff ds)) diff (mod diff ds)
17734 h (floor (/ diff hs)) diff (mod diff hs)
17735 m (floor (/ diff 60)))
17736 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17738 d (floor (+ (/ diff ds) 0.5))
17739 h 0 m 0))
17740 (if (not to-buffer)
17741 (message "%s" (org-make-tdiff-string y d h m))
17742 (if (org-at-table-p)
17743 (progn
17744 (goto-char match-end)
17745 (setq align t)
17746 (and (looking-at " *|") (goto-char (match-end 0))))
17747 (goto-char match-end))
17748 (when (looking-at
17749 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17750 (replace-match ""))
17751 (when negative (insert " -"))
17752 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17753 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17754 (insert " " (format fh h m))))
17755 (when align (org-table-align))
17756 (message "Time difference inserted")))))
17758 (defun org-make-tdiff-string (y d h m)
17759 (let ((fmt "")
17760 (l nil))
17761 (when (> y 0)
17762 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17763 (push y l))
17764 (when (> d 0)
17765 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17766 (push d l))
17767 (when (> h 0)
17768 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17769 (push h l))
17770 (when (> m 0)
17771 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17772 (push m l))
17773 (apply 'format fmt (nreverse l))))
17775 (defun org-time-string-to-time (s &optional buffer pos)
17776 "Convert a timestamp string into internal time."
17777 (condition-case errdata
17778 (apply 'encode-time (org-parse-time-string s))
17779 (error (error "Bad timestamp `%s'%s\nError was: %s"
17780 s (if (not (and buffer pos))
17782 (format-message " at %d in buffer `%s'" pos buffer))
17783 (cdr errdata)))))
17785 (defun org-time-string-to-seconds (s)
17786 "Convert a timestamp string to a number of seconds."
17787 (float-time (org-time-string-to-time s)))
17789 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17791 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17792 "Convert time stamp S to an absolute day number.
17794 If DAYNR in non-nil, and there is a specifier for a cyclic time
17795 stamp, get the closest date to DAYNR. If PREFER is
17796 `past' (respectively `future') return a date past (respectively
17797 after) or equal to DAYNR.
17799 POS is the location of time stamp S, as a buffer position in
17800 BUFFER.
17802 Diary sexp timestamps are matched against DAYNR, when non-nil.
17803 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17804 signalled."
17805 (cond
17806 ((string-match "\\`%%\\((.*)\\)" s)
17807 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17808 ;; only able to match individual dates. If it fails, raise an
17809 ;; error.
17810 (if (and daynr
17811 (org-diary-sexp-entry
17812 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17813 daynr
17814 (signal 'org-diary-sexp-no-match (list s))))
17815 ((and daynr show-all) (org-closest-date s daynr prefer))
17816 (t (time-to-days
17817 (condition-case errdata
17818 (apply #'encode-time (org-parse-time-string s))
17819 (error (error "Bad timestamp `%s'%s\nError was: %s"
17821 (if (not (and buffer pos)) ""
17822 (format-message " at %d in buffer `%s'" pos buffer))
17823 (cdr errdata))))))))
17825 (defun org-days-to-iso-week (days)
17826 "Return the iso week number."
17827 (require 'cal-iso)
17828 (car (calendar-iso-from-absolute days)))
17830 (defun org-small-year-to-year (year)
17831 "Convert 2-digit years into 4-digit years.
17832 YEAR is expanded into one of the 30 next years, if possible, or
17833 into a past one. Any year larger than 99 is returned unchanged."
17834 (if (>= year 100) year
17835 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17836 (century (/ current 100))
17837 (offset (- year (% current 100))))
17838 (cond ((> offset 30) (+ (* (1- century) 100) year))
17839 ((> offset -70) (+ (* century 100) year))
17840 (t (+ (* (1+ century) 100) year))))))
17842 (defun org-time-from-absolute (d)
17843 "Return the time corresponding to date D.
17844 D may be an absolute day number, or a calendar-type list (month day year)."
17845 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17846 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17848 (defvar org-agenda-current-date)
17849 (defun org-calendar-holiday ()
17850 "List of holidays, for Diary display in Org mode."
17851 (require 'holidays)
17852 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17853 (and hl (mapconcat #'identity hl "; "))))
17855 (defun org-diary-sexp-entry (sexp entry d)
17856 "Process a SEXP diary ENTRY for date D."
17857 (require 'diary-lib)
17858 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17859 ;; dynamically.
17860 (let* ((sexp `(let ((entry ,entry)
17861 (date ',d))
17862 ,(car (read-from-string sexp))))
17863 (result (if calendar-debug-sexp (eval sexp)
17864 (condition-case nil
17865 (eval sexp)
17866 (error
17867 (beep)
17868 (message "Bad sexp at line %d in %s: %s"
17869 (org-current-line)
17870 (buffer-file-name) sexp)
17871 (sleep-for 2))))))
17872 (cond ((stringp result) (split-string result "; "))
17873 ((and (consp result)
17874 (not (consp (cdr result)))
17875 (stringp (cdr result))) (cdr result))
17876 ((and (consp result)
17877 (stringp (car result))) result)
17878 (result entry))))
17880 (defun org-diary-to-ical-string (frombuf)
17881 "Get iCalendar entries from diary entries in buffer FROMBUF.
17882 This uses the icalendar.el library."
17883 (let* ((tmpdir temporary-file-directory)
17884 (tmpfile (make-temp-name
17885 (expand-file-name "orgics" tmpdir)))
17886 buf rtn b e)
17887 (with-current-buffer frombuf
17888 (icalendar-export-region (point-min) (point-max) tmpfile)
17889 (setq buf (find-buffer-visiting tmpfile))
17890 (set-buffer buf)
17891 (goto-char (point-min))
17892 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17893 (setq b (match-beginning 0)))
17894 (goto-char (point-max))
17895 (when (re-search-backward "^END:VEVENT" nil t)
17896 (setq e (match-end 0)))
17897 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17898 (kill-buffer buf)
17899 (delete-file tmpfile)
17900 rtn))
17902 (defun org-closest-date (start current prefer)
17903 "Return closest date to CURRENT starting from START.
17905 CURRENT and START are both time stamps.
17907 When PREFER is `past', return a date that is either CURRENT or
17908 past. When PREFER is `future', return a date that is either
17909 CURRENT or future.
17911 Only time stamps with a repeater are modified. Any other time
17912 stamp stay unchanged. In any case, return value is an absolute
17913 day number."
17914 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17915 ;; No repeater. Do not shift time stamp.
17916 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17917 (let ((value (string-to-number (match-string 1 start)))
17918 (type (match-string 2 start)))
17919 (if (= 0 value)
17920 ;; Repeater with a 0-value is considered as void.
17921 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17922 (let* ((base (org-date-to-gregorian start))
17923 (target (org-date-to-gregorian current))
17924 (sday (calendar-absolute-from-gregorian base))
17925 (cday (calendar-absolute-from-gregorian target))
17926 n1 n2)
17927 ;; If START is already past CURRENT, just return START.
17928 (if (<= cday sday) sday
17929 ;; Compute closest date before (N1) and closest date past
17930 ;; (N2) CURRENT.
17931 (pcase type
17932 ("h"
17933 (let ((missing-hours
17934 (mod (+ (- (* 24 (- cday sday))
17935 (nth 2 (org-parse-time-string start)))
17936 org-extend-today-until)
17937 value)))
17938 (setf n1 (if (= missing-hours 0) cday
17939 (- cday (1+ (/ missing-hours 24)))))
17940 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17941 ((or "d" "w")
17942 (let ((value (if (equal type "w") (* 7 value) value)))
17943 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17944 (setf n2 (+ n1 value))))
17945 ("m"
17946 (let* ((add-months
17947 (lambda (d n)
17948 ;; Add N months to gregorian date D, i.e.,
17949 ;; a list (MONTH DAY YEAR). Return a valid
17950 ;; gregorian date.
17951 (let ((m (+ (nth 0 d) n)))
17952 (list (mod m 12)
17953 (nth 1 d)
17954 (+ (/ m 12) (nth 2 d))))))
17955 (months ; Complete months to TARGET.
17956 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17957 (- (nth 0 target) (nth 0 base))
17958 ;; If START's day is greater than
17959 ;; TARGET's, remove incomplete month.
17960 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17961 value)
17962 value))
17963 (before (funcall add-months base months)))
17964 (setf n1 (calendar-absolute-from-gregorian before))
17965 (setf n2
17966 (calendar-absolute-from-gregorian
17967 (funcall add-months before value)))))
17969 (let* ((d (nth 1 base))
17970 (m (nth 0 base))
17971 (y (nth 2 base))
17972 (years ; Complete years to TARGET.
17973 (* (/ (- (nth 2 target)
17975 ;; If START's month and day are
17976 ;; greater than TARGET's, remove
17977 ;; incomplete year.
17978 (if (or (> (nth 0 target) m)
17979 (and (= (nth 0 target) m)
17980 (> (nth 1 target) d)))
17983 value)
17984 value))
17985 (before (list m d (+ y years))))
17986 (setf n1 (calendar-absolute-from-gregorian before))
17987 (setf n2 (calendar-absolute-from-gregorian
17988 (list m d (+ (nth 2 before) value)))))))
17989 ;; Handle PREFER parameter, if any.
17990 (cond
17991 ((eq prefer 'past) (if (= cday n2) n2 n1))
17992 ((eq prefer 'future) (if (= cday n1) n1 n2))
17993 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17995 (defun org-date-to-gregorian (d)
17996 "Turn any specification of date D into a Gregorian date for the calendar."
17997 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17998 ((and (listp d) (= (length d) 3)) d)
17999 ((stringp d)
18000 (let ((d (org-parse-time-string d)))
18001 (list (nth 4 d) (nth 3 d) (nth 5 d))))
18002 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
18004 (defun org-parse-time-string (s &optional nodefault)
18005 "Parse the standard Org-mode time string.
18006 This should be a lot faster than the normal `parse-time-string'.
18007 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18008 hour and minute fields will be nil if not given."
18009 (cond ((string-match org-ts-regexp0 s)
18010 (list 0
18011 (when (or (match-beginning 8) (not nodefault))
18012 (string-to-number (or (match-string 8 s) "0")))
18013 (when (or (match-beginning 7) (not nodefault))
18014 (string-to-number (or (match-string 7 s) "0")))
18015 (string-to-number (match-string 4 s))
18016 (string-to-number (match-string 3 s))
18017 (string-to-number (match-string 2 s))
18018 nil nil nil))
18019 ((string-match "^<[^>]+>$" s)
18020 (decode-time (seconds-to-time (org-matcher-time s))))
18021 (t (error "Not a standard Org-mode time string: %s" s))))
18023 (defun org-timestamp-up (&optional arg)
18024 "Increase the date item at the cursor by one.
18025 If the cursor is on the year, change the year. If it is on the month,
18026 the day or the time, change that.
18027 With prefix ARG, change by that many units."
18028 (interactive "p")
18029 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18031 (defun org-timestamp-down (&optional arg)
18032 "Decrease the date item at the cursor by one.
18033 If the cursor is on the year, change the year. If it is on the month,
18034 the day or the time, change that.
18035 With prefix ARG, change by that many units."
18036 (interactive "p")
18037 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18039 (defun org-timestamp-up-day (&optional arg)
18040 "Increase the date in the time stamp by one day.
18041 With prefix ARG, change that many days."
18042 (interactive "p")
18043 (if (and (not (org-at-timestamp-p t))
18044 (org-at-heading-p))
18045 (org-todo 'up)
18046 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18048 (defun org-timestamp-down-day (&optional arg)
18049 "Decrease the date in the time stamp by one day.
18050 With prefix ARG, change that many days."
18051 (interactive "p")
18052 (if (and (not (org-at-timestamp-p t))
18053 (org-at-heading-p))
18054 (org-todo 'down)
18055 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18057 (defun org-at-timestamp-p (&optional inactive-ok)
18058 "Non-nil if point is inside a timestamp.
18060 When optional argument INACTIVE-OK is non-nil, also consider
18061 inactive timestamps.
18063 When this function returns a non-nil value, match data is set
18064 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18065 INACTIVE-OK."
18066 (interactive)
18067 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18068 (pos (point))
18069 (ans (or (looking-at tsr)
18070 (save-excursion
18071 (skip-chars-backward "^[<\n\r\t")
18072 (when (> (point) (point-min)) (backward-char 1))
18073 (and (looking-at tsr)
18074 (> (- (match-end 0) pos) -1))))))
18075 (and ans
18076 (boundp 'org-ts-what)
18077 (setq org-ts-what
18078 (cond
18079 ((= pos (match-beginning 0)) 'bracket)
18080 ;; Point is considered to be "on the bracket" whether
18081 ;; it's really on it or right after it.
18082 ((= pos (1- (match-end 0))) 'bracket)
18083 ((= pos (match-end 0)) 'after)
18084 ((org-pos-in-match-range pos 2) 'year)
18085 ((org-pos-in-match-range pos 3) 'month)
18086 ((org-pos-in-match-range pos 7) 'hour)
18087 ((org-pos-in-match-range pos 8) 'minute)
18088 ((or (org-pos-in-match-range pos 4)
18089 (org-pos-in-match-range pos 5)) 'day)
18090 ((and (> pos (or (match-end 8) (match-end 5)))
18091 (< pos (match-end 0)))
18092 (- pos (or (match-end 8) (match-end 5))))
18093 (t 'day))))
18094 ans))
18096 (defun org-toggle-timestamp-type ()
18097 "Toggle the type (<active> or [inactive]) of a time stamp."
18098 (interactive)
18099 (when (org-at-timestamp-p t)
18100 (let ((beg (match-beginning 0)) (end (match-end 0))
18101 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18102 (save-excursion
18103 (goto-char beg)
18104 (while (re-search-forward "[][<>]" end t)
18105 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18106 t t)))
18107 (message "Timestamp is now %sactive"
18108 (if (equal (char-after beg) ?<) "" "in")))))
18110 (defun org-at-clock-log-p nil
18111 "Is the cursor on the clock log line?"
18112 (save-excursion
18113 (move-beginning-of-line 1)
18114 (looking-at org-clock-line-re)))
18116 (defvar org-clock-history) ; defined in org-clock.el
18117 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18118 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18119 "Change the date in the time stamp at point.
18120 The date will be changed by N times WHAT. WHAT can be `day', `month',
18121 `year', `minute', `second'. If WHAT is not given, the cursor position
18122 in the timestamp determines what will be changed.
18123 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18124 (let ((origin (point)) origin-cat
18125 with-hm inactive
18126 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18127 org-ts-what
18128 extra rem
18129 ts time time0 fixnext clrgx)
18130 (unless (org-at-timestamp-p t)
18131 (user-error "Not at a timestamp"))
18132 (if (and (not what) (eq org-ts-what 'bracket))
18133 (org-toggle-timestamp-type)
18134 ;; Point isn't on brackets. Remember the part of the time-stamp
18135 ;; the point was in. Indeed, size of time-stamps may change,
18136 ;; but point must be kept in the same category nonetheless.
18137 (setq origin-cat org-ts-what)
18138 (when (and (not what) (not (eq org-ts-what 'day))
18139 org-display-custom-times
18140 (get-text-property (point) 'display)
18141 (not (get-text-property (1- (point)) 'display)))
18142 (setq org-ts-what 'day))
18143 (setq org-ts-what (or what org-ts-what)
18144 inactive (= (char-after (match-beginning 0)) ?\[)
18145 ts (match-string 0))
18146 (replace-match "")
18147 (when (string-match
18148 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18150 (setq extra (match-string 1 ts))
18151 (when suppress-tmp-delay
18152 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18153 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18154 (setq with-hm t))
18155 (setq time0 (org-parse-time-string ts))
18156 (when (and updown
18157 (eq org-ts-what 'minute)
18158 (not current-prefix-arg))
18159 ;; This looks like s-up and s-down. Change by one rounding step.
18160 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18161 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18162 (setcar (cdr time0) (+ (nth 1 time0)
18163 (if (> n 0) (- rem) (- dm rem))))))
18164 (setq time
18165 (apply #'encode-time
18166 (or (car time0) 0)
18167 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18168 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18169 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18170 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18171 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18172 (nthcdr 6 time0)))
18173 (when (and (member org-ts-what '(hour minute))
18174 extra
18175 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18176 (setq extra (org-modify-ts-extra
18177 extra
18178 (if (eq org-ts-what 'hour) 2 5)
18179 n dm)))
18180 (when (integerp org-ts-what)
18181 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18182 (when (eq what 'calendar)
18183 (let ((cal-date (org-get-date-from-calendar)))
18184 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18185 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18186 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18187 (setcar time0 (or (car time0) 0))
18188 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18189 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18190 (setq time (apply 'encode-time time0))))
18191 ;; Insert the new time-stamp, and ensure point stays in the same
18192 ;; category as before (i.e. not after the last position in that
18193 ;; category).
18194 (let ((pos (point)))
18195 ;; Stay before inserted string. `save-excursion' is of no use.
18196 (setq org-last-changed-timestamp
18197 (org-insert-time-stamp time with-hm inactive nil nil extra))
18198 (goto-char pos))
18199 (save-match-data
18200 (looking-at org-ts-regexp3)
18201 (goto-char (cond
18202 ;; `day' category ends before `hour' if any, or at
18203 ;; the end of the day name.
18204 ((eq origin-cat 'day)
18205 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18206 ((eq origin-cat 'hour) (min (match-end 7) origin))
18207 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18208 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18209 ;; `year' and `month' have both fixed size: point
18210 ;; couldn't have moved into another part.
18211 (t origin))))
18212 ;; Update clock if on a CLOCK line.
18213 (org-clock-update-time-maybe)
18214 ;; Maybe adjust the closest clock in `org-clock-history'
18215 (when org-clock-adjust-closest
18216 (if (not (and (org-at-clock-log-p)
18217 (< 1 (length (delq nil (mapcar 'marker-position
18218 org-clock-history))))))
18219 (message "No clock to adjust")
18220 (cond ((save-excursion ; fix previous clock?
18221 (re-search-backward org-ts-regexp0 nil t)
18222 (looking-back (concat org-clock-string " \\[")
18223 (line-beginning-position)))
18224 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18225 ((save-excursion ; fix next clock?
18226 (re-search-backward org-ts-regexp0 nil t)
18227 (looking-at (concat org-ts-regexp0 "\\] =>")))
18228 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18229 (save-window-excursion
18230 ;; Find closest clock to point, adjust the previous/next one in history
18231 (let* ((p (save-excursion (org-back-to-heading t)))
18232 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18233 (clfixnth
18234 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18235 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18236 (if (not clfixpos)
18237 (message "No clock to adjust")
18238 (save-excursion
18239 (org-goto-marker-or-bmk clfixpos)
18240 (org-show-subtree)
18241 (when (re-search-forward clrgx nil t)
18242 (goto-char (match-beginning 1))
18243 (let (org-clock-adjust-closest)
18244 (org-timestamp-change n org-ts-what updown))
18245 (message "Clock adjusted in %s for heading: %s"
18246 (file-name-nondirectory (buffer-file-name))
18247 (org-get-heading t t)))))))))
18248 ;; Try to recenter the calendar window, if any.
18249 (when (and org-calendar-follow-timestamp-change
18250 (get-buffer-window "*Calendar*" t)
18251 (memq org-ts-what '(day month year)))
18252 (org-recenter-calendar (time-to-days time))))))
18254 (defun org-modify-ts-extra (s pos n dm)
18255 "Change the different parts of the lead-time and repeat fields in timestamp."
18256 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18257 ng h m new rem)
18258 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18259 (cond
18260 ((or (org-pos-in-match-range pos 2)
18261 (org-pos-in-match-range pos 3))
18262 (setq m (string-to-number (match-string 3 s))
18263 h (string-to-number (match-string 2 s)))
18264 (if (org-pos-in-match-range pos 2)
18265 (setq h (+ h n))
18266 (setq n (* dm (with-no-warnings (signum n))))
18267 (unless (= 0 (setq rem (% m dm)))
18268 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18269 (setq m (+ m n)))
18270 (when (< m 0) (setq m (+ m 60) h (1- h)))
18271 (when (> m 59) (setq m (- m 60) h (1+ h)))
18272 (setq h (mod h 24))
18273 (setq ng 1 new (format "-%02d:%02d" h m)))
18274 ((org-pos-in-match-range pos 6)
18275 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18276 ((org-pos-in-match-range pos 5)
18277 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18279 ((org-pos-in-match-range pos 9)
18280 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18281 ((org-pos-in-match-range pos 8)
18282 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18284 (when ng
18285 (setq s (concat
18286 (substring s 0 (match-beginning ng))
18288 (substring s (match-end ng))))))
18291 (defun org-recenter-calendar (d)
18292 "If the calendar is visible, recenter it to date D."
18293 (let ((cwin (get-buffer-window "*Calendar*" t)))
18294 (when cwin
18295 (let ((calendar-move-hook nil))
18296 (with-selected-window cwin
18297 (calendar-goto-date
18298 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18300 (defun org-goto-calendar (&optional arg)
18301 "Go to the Emacs calendar at the current date.
18302 If there is a time stamp in the current line, go to that date.
18303 A prefix ARG can be used to force the current date."
18304 (interactive "P")
18305 (let ((tsr org-ts-regexp) diff
18306 (calendar-move-hook nil)
18307 (calendar-view-holidays-initially-flag nil)
18308 (calendar-view-diary-initially-flag nil))
18309 (when (or (org-at-timestamp-p)
18310 (save-excursion
18311 (beginning-of-line 1)
18312 (looking-at (concat ".*" tsr))))
18313 (let ((d1 (time-to-days (current-time)))
18314 (d2 (time-to-days
18315 (org-time-string-to-time (match-string 1)))))
18316 (setq diff (- d2 d1))))
18317 (calendar)
18318 (calendar-goto-today)
18319 (when (and diff (not arg)) (calendar-forward-day diff))))
18321 (defun org-get-date-from-calendar ()
18322 "Return a list (month day year) of date at point in calendar."
18323 (with-current-buffer "*Calendar*"
18324 (save-match-data
18325 (calendar-cursor-to-date))))
18327 (defun org-date-from-calendar ()
18328 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18329 If there is already a time stamp at the cursor position, update it."
18330 (interactive)
18331 (if (org-at-timestamp-p t)
18332 (org-timestamp-change 0 'calendar)
18333 (let ((cal-date (org-get-date-from-calendar)))
18334 (org-insert-time-stamp
18335 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18337 (defcustom org-effort-durations
18338 `(("min" . 1)
18339 ("h" . 60)
18340 ("d" . ,(* 60 8))
18341 ("w" . ,(* 60 8 5))
18342 ("m" . ,(* 60 8 5 4))
18343 ("y" . ,(* 60 8 5 40)))
18344 "Conversion factor to minutes for an effort modifier.
18346 Each entry has the form (MODIFIER . MINUTES).
18348 In an effort string, a number followed by MODIFIER is multiplied
18349 by the specified number of MINUTES to obtain an effort in
18350 minutes.
18352 For example, if the value of this variable is ((\"hours\" . 60)), then an
18353 effort string \"2hours\" is equivalent to 120 minutes."
18354 :group 'org-agenda
18355 :version "25.1"
18356 :package-version '(Org . "8.3")
18357 :type '(alist :key-type (string :tag "Modifier")
18358 :value-type (number :tag "Minutes")))
18360 (defun org-minutes-to-clocksum-string (m)
18361 "Format number of minutes as a clocksum string.
18362 The format is determined by `org-time-clocksum-format',
18363 `org-time-clocksum-use-fractional' and
18364 `org-time-clocksum-fractional-format' and
18365 `org-time-clocksum-use-effort-durations'."
18366 (let ((clocksum "")
18367 (m (round m)) ; Don't allow fractions of minutes
18368 h d w mo y fmt n)
18369 (setq h (if org-time-clocksum-use-effort-durations
18370 (cdr (assoc "h" org-effort-durations)) 60)
18371 d (if org-time-clocksum-use-effort-durations
18372 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18373 w (if org-time-clocksum-use-effort-durations
18374 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18375 mo (if org-time-clocksum-use-effort-durations
18376 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18377 y (if org-time-clocksum-use-effort-durations
18378 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18379 ;; fractional format
18380 (if org-time-clocksum-use-fractional
18381 (cond
18382 ;; single format string
18383 ((stringp org-time-clocksum-fractional-format)
18384 (format org-time-clocksum-fractional-format (/ m (float h))))
18385 ;; choice of fractional formats for different time units
18386 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18387 (> (/ (truncate m) (* y d h)) 0))
18388 (format fmt (/ m (* y d (float h)))))
18389 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18390 (> (/ (truncate m) (* mo d h)) 0))
18391 (format fmt (/ m (* mo d (float h)))))
18392 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18393 (> (/ (truncate m) (* w d h)) 0))
18394 (format fmt (/ m (* w d (float h)))))
18395 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18396 (> (/ (truncate m) (* d h)) 0))
18397 (format fmt (/ m (* d (float h)))))
18398 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18399 (> (/ (truncate m) h) 0))
18400 (format fmt (/ m (float h))))
18401 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18402 (format fmt m))
18403 ;; fall back to smallest time unit with a format
18404 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18405 (format fmt (/ m (float h))))
18406 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18407 (format fmt (/ m (* d (float h)))))
18408 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18409 (format fmt (/ m (* w d (float h)))))
18410 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18411 (format fmt (/ m (* mo d (float h)))))
18412 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18413 (format fmt (/ m (* y d (float h))))))
18414 ;; standard (non-fractional) format, with single format string
18415 (if (stringp org-time-clocksum-format)
18416 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18417 ;; separate formats components
18418 (and (setq fmt (plist-get org-time-clocksum-format :years))
18419 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18420 (plist-get org-time-clocksum-format :require-years))
18421 (setq clocksum (concat clocksum (format fmt n))
18422 m (- m (* n y d h))))
18423 (and (setq fmt (plist-get org-time-clocksum-format :months))
18424 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18425 (plist-get org-time-clocksum-format :require-months))
18426 (setq clocksum (concat clocksum (format fmt n))
18427 m (- m (* n mo d h))))
18428 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18429 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18430 (plist-get org-time-clocksum-format :require-weeks))
18431 (setq clocksum (concat clocksum (format fmt n))
18432 m (- m (* n w d h))))
18433 (and (setq fmt (plist-get org-time-clocksum-format :days))
18434 (or (> (setq n (/ (truncate m) (* d h))) 0)
18435 (plist-get org-time-clocksum-format :require-days))
18436 (setq clocksum (concat clocksum (format fmt n))
18437 m (- m (* n d h))))
18438 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18439 (or (> (setq n (/ (truncate m) h)) 0)
18440 (plist-get org-time-clocksum-format :require-hours))
18441 (setq clocksum (concat clocksum (format fmt n))
18442 m (- m (* n h))))
18443 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18444 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18445 (setq clocksum (concat clocksum (format fmt m))))
18446 ;; return formatted time duration
18447 clocksum))))
18449 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18450 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18451 "Org mode version 8.0")
18453 (defun org-hours-to-clocksum-string (n)
18454 (org-minutes-to-clocksum-string (* n 60)))
18456 (defun org-hh:mm-string-to-minutes (s)
18457 "Convert a string H:MM to a number of minutes.
18458 If the string is just a number, interpret it as minutes.
18459 In fact, the first hh:mm or number in the string will be taken,
18460 there can be extra stuff in the string.
18461 If no number is found, the return value is 0."
18462 (cond
18463 ((integerp s) s)
18464 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18465 (+ (* (string-to-number (match-string 1 s)) 60)
18466 (string-to-number (match-string 2 s))))
18467 ((string-match "\\([0-9]+\\)" s)
18468 (string-to-number (match-string 1 s)))
18469 (t 0)))
18471 (defcustom org-image-actual-width t
18472 "Should we use the actual width of images when inlining them?
18474 When set to t, always use the image width.
18476 When set to a number, use imagemagick (when available) to set
18477 the image's width to this value.
18479 When set to a number in a list, try to get the width from any
18480 #+ATTR.* keyword if it matches a width specification like
18482 #+ATTR_HTML: :width 300px
18484 and fall back on that number if none is found.
18486 When set to nil, try to get the width from an #+ATTR.* keyword
18487 and fall back on the original width if none is found.
18489 This requires Emacs >= 24.1, build with imagemagick support."
18490 :group 'org-appearance
18491 :version "24.4"
18492 :package-version '(Org . "8.0")
18493 :type '(choice
18494 (const :tag "Use the image width" t)
18495 (integer :tag "Use a number of pixels")
18496 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18497 (const :tag "Use #+ATTR* or don't resize" nil)))
18499 (defcustom org-agenda-inhibit-startup nil
18500 "Inhibit startup when preparing agenda buffers.
18501 When this variable is t, the initialization of the Org agenda
18502 buffers is inhibited: e.g. the visibility state is not set, the
18503 tables are not re-aligned, etc."
18504 :type 'boolean
18505 :version "24.3"
18506 :group 'org-agenda)
18508 (defcustom org-agenda-ignore-properties nil
18509 "Avoid updating text properties when building the agenda.
18510 Properties are used to prepare buffers for effort estimates,
18511 appointments, statistics and subtree-local categories.
18512 If you don't use these in the agenda, you can add them to this
18513 list and agenda building will be a bit faster.
18514 The value is a list, with zero or more of the symbols `effort', `appt',
18515 `stats' or `category'."
18516 :type '(set :greedy t
18517 (const effort)
18518 (const appt)
18519 (const stats)
18520 (const category))
18521 :version "25.1"
18522 :package-version '(Org . "8.3")
18523 :group 'org-agenda)
18525 (defun org-duration-string-to-minutes (s &optional output-to-string)
18526 "Convert a duration string S to minutes.
18528 A bare number is interpreted as minutes, modifiers can be set by
18529 customizing `org-effort-durations' (which see).
18531 Entries containing a colon are interpreted as H:MM by
18532 `org-hh:mm-string-to-minutes'."
18533 (let ((result 0)
18534 (re (concat "\\([0-9.]+\\) *\\("
18535 (regexp-opt (mapcar 'car org-effort-durations))
18536 "\\)")))
18537 (while (string-match re s)
18538 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18539 (string-to-number (match-string 1 s))))
18540 (setq s (replace-match "" nil t s)))
18541 (setq result (floor result))
18542 (cl-incf result (org-hh:mm-string-to-minutes s))
18543 (if output-to-string (number-to-string result) result)))
18545 ;;;; Files
18547 (defun org-save-all-org-buffers ()
18548 "Save all Org-mode buffers without user confirmation."
18549 (interactive)
18550 (message "Saving all Org-mode buffers...")
18551 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18552 (when (featurep 'org-id) (org-id-locations-save))
18553 (message "Saving all Org-mode buffers... done"))
18555 (defun org-revert-all-org-buffers ()
18556 "Revert all Org-mode buffers.
18557 Prompt for confirmation when there are unsaved changes.
18558 Be sure you know what you are doing before letting this function
18559 overwrite your changes.
18561 This function is useful in a setup where one tracks org files
18562 with a version control system, to revert on one machine after pulling
18563 changes from another. I believe the procedure must be like this:
18565 1. M-x org-save-all-org-buffers
18566 2. Pull changes from the other machine, resolve conflicts
18567 3. M-x org-revert-all-org-buffers"
18568 (interactive)
18569 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18570 (user-error "Abort"))
18571 (save-excursion
18572 (save-window-excursion
18573 (dolist (b (buffer-list))
18574 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18575 (with-current-buffer b buffer-file-name))
18576 (pop-to-buffer-same-window b)
18577 (revert-buffer t 'no-confirm)))
18578 (when (and (featurep 'org-id) org-id-track-globally)
18579 (org-id-locations-load)))))
18581 ;;;; Agenda files
18583 ;;;###autoload
18584 (defun org-switchb (&optional arg)
18585 "Switch between Org buffers.
18587 With \\[universal-argument] prefix, restrict available buffers to files.
18589 With \\[universal-argument] \\[universal-argument] \
18590 prefix, restrict available buffers to agenda files."
18591 (interactive "P")
18592 (let ((blist (org-buffer-list
18593 (cond ((equal arg '(4)) 'files)
18594 ((equal arg '(16)) 'agenda)))))
18595 (pop-to-buffer-same-window
18596 (completing-read "Org buffer: "
18597 (mapcar #'list (mapcar #'buffer-name blist))
18598 nil t))))
18600 (defun org-buffer-list (&optional predicate exclude-tmp)
18601 "Return a list of Org buffers.
18602 PREDICATE can be `export', `files' or `agenda'.
18604 export restrict the list to Export buffers.
18605 files restrict the list to buffers visiting Org files.
18606 agenda restrict the list to buffers visiting agenda files.
18608 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18609 (let* ((bfn nil)
18610 (agenda-files (and (eq predicate 'agenda)
18611 (mapcar 'file-truename (org-agenda-files t))))
18612 (filter
18613 (cond
18614 ((eq predicate 'files)
18615 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18616 ((eq predicate 'export)
18617 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18618 ((eq predicate 'agenda)
18619 (lambda (b)
18620 (with-current-buffer b
18621 (and (derived-mode-p 'org-mode)
18622 (setq bfn (buffer-file-name b))
18623 (member (file-truename bfn) agenda-files)))))
18624 (t (lambda (b) (with-current-buffer b
18625 (or (derived-mode-p 'org-mode)
18626 (string-match "\\*Org .*Export"
18627 (buffer-name b)))))))))
18628 (delq nil
18629 (mapcar
18630 (lambda(b)
18631 (if (and (funcall filter b)
18632 (or (not exclude-tmp)
18633 (not (string-match "tmp" (buffer-name b)))))
18635 nil))
18636 (buffer-list)))))
18638 (defun org-agenda-files (&optional unrestricted archives)
18639 "Get the list of agenda files.
18640 Optional UNRESTRICTED means return the full list even if a restriction
18641 is currently in place.
18642 When ARCHIVES is t, include all archive files that are really being
18643 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18644 `org-agenda-archives-mode' is t."
18645 (let ((files
18646 (cond
18647 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18648 ((stringp org-agenda-files) (org-read-agenda-file-list))
18649 ((listp org-agenda-files) org-agenda-files)
18650 (t (error "Invalid value of `org-agenda-files'")))))
18651 (setq files (apply 'append
18652 (mapcar (lambda (f)
18653 (if (file-directory-p f)
18654 (directory-files
18655 f t org-agenda-file-regexp)
18656 (list f)))
18657 files)))
18658 (when org-agenda-skip-unavailable-files
18659 (setq files (delq nil
18660 (mapcar (function
18661 (lambda (file)
18662 (and (file-readable-p file) file)))
18663 files))))
18664 (when (or (eq archives t)
18665 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18666 (setq files (org-add-archive-files files)))
18667 files))
18669 (defun org-agenda-file-p (&optional file)
18670 "Return non-nil, if FILE is an agenda file.
18671 If FILE is omitted, use the file associated with the current
18672 buffer."
18673 (let ((fname (or file (buffer-file-name))))
18674 (and fname
18675 (member (file-truename fname)
18676 (mapcar #'file-truename (org-agenda-files t))))))
18678 (defun org-edit-agenda-file-list ()
18679 "Edit the list of agenda files.
18680 Depending on setup, this either uses customize to edit the variable
18681 `org-agenda-files', or it visits the file that is holding the list. In the
18682 latter case, the buffer is set up in a way that saving it automatically kills
18683 the buffer and restores the previous window configuration."
18684 (interactive)
18685 (if (stringp org-agenda-files)
18686 (let ((cw (current-window-configuration)))
18687 (find-file org-agenda-files)
18688 (setq-local org-window-configuration cw)
18689 (add-hook 'after-save-hook
18690 (lambda ()
18691 (set-window-configuration
18692 (prog1 org-window-configuration
18693 (kill-buffer (current-buffer))))
18694 (org-install-agenda-files-menu)
18695 (message "New agenda file list installed"))
18696 nil 'local)
18697 (message "%s" (substitute-command-keys
18698 "Edit list and finish with \\[save-buffer]")))
18699 (customize-variable 'org-agenda-files)))
18701 (defun org-store-new-agenda-file-list (list)
18702 "Set new value for the agenda file list and save it correctly."
18703 (if (stringp org-agenda-files)
18704 (let ((fe (org-read-agenda-file-list t)) b u)
18705 (while (setq b (find-buffer-visiting org-agenda-files))
18706 (kill-buffer b))
18707 (with-temp-file org-agenda-files
18708 (insert
18709 (mapconcat
18710 (lambda (f) ;; Keep un-expanded entries.
18711 (if (setq u (assoc f fe))
18712 (cdr u)
18714 list "\n")
18715 "\n")))
18716 (let ((org-mode-hook nil) (org-inhibit-startup t)
18717 (org-insert-mode-line-in-empty-file nil))
18718 (setq org-agenda-files list)
18719 (customize-save-variable 'org-agenda-files org-agenda-files))))
18721 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18722 "Read the list of agenda files from a file.
18723 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18724 filenames, used by `org-store-new-agenda-file-list' to write back
18725 un-expanded file names."
18726 (when (file-directory-p org-agenda-files)
18727 (error "`org-agenda-files' cannot be a single directory"))
18728 (when (stringp org-agenda-files)
18729 (with-temp-buffer
18730 (insert-file-contents org-agenda-files)
18731 (mapcar
18732 (lambda (f)
18733 (let ((e (expand-file-name (substitute-in-file-name f)
18734 org-directory)))
18735 (if pair-with-expansion
18736 (cons e f)
18737 e)))
18738 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18740 ;;;###autoload
18741 (defun org-cycle-agenda-files ()
18742 "Cycle through the files in `org-agenda-files'.
18743 If the current buffer visits an agenda file, find the next one in the list.
18744 If the current buffer does not, find the first agenda file."
18745 (interactive)
18746 (let* ((fs (or (org-agenda-files t)
18747 (user-error "No agenda files")))
18748 (files (copy-sequence fs))
18749 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18750 file)
18751 (when tcf
18752 (while (and (setq file (pop files))
18753 (not (equal (file-truename file) tcf)))))
18754 (find-file (car (or files fs)))
18755 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18757 (defun org-agenda-file-to-front (&optional to-end)
18758 "Move/add the current file to the top of the agenda file list.
18759 If the file is not present in the list, it is added to the front. If it is
18760 present, it is moved there. With optional argument TO-END, add/move to the
18761 end of the list."
18762 (interactive "P")
18763 (let ((org-agenda-skip-unavailable-files nil)
18764 (file-alist (mapcar (lambda (x)
18765 (cons (file-truename x) x))
18766 (org-agenda-files t)))
18767 (ctf (file-truename
18768 (or buffer-file-name
18769 (user-error "Please save the current buffer to a file"))))
18770 x had)
18771 (setq x (assoc ctf file-alist) had x)
18773 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18774 (if to-end
18775 (setq file-alist (append (delq x file-alist) (list x)))
18776 (setq file-alist (cons x (delq x file-alist))))
18777 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18778 (org-install-agenda-files-menu)
18779 (message "File %s to %s of agenda file list"
18780 (if had "moved" "added") (if to-end "end" "front"))))
18782 (defun org-remove-file (&optional file)
18783 "Remove current file from the list of files in variable `org-agenda-files'.
18784 These are the files which are being checked for agenda entries.
18785 Optional argument FILE means use this file instead of the current."
18786 (interactive)
18787 (let* ((org-agenda-skip-unavailable-files nil)
18788 (file (or file buffer-file-name
18789 (user-error "Current buffer does not visit a file")))
18790 (true-file (file-truename file))
18791 (afile (abbreviate-file-name file))
18792 (files (delq nil (mapcar
18793 (lambda (x)
18794 (unless (equal true-file
18795 (file-truename x))
18797 (org-agenda-files t)))))
18798 (if (not (= (length files) (length (org-agenda-files t))))
18799 (progn
18800 (org-store-new-agenda-file-list files)
18801 (org-install-agenda-files-menu)
18802 (message "Removed from Org Agenda list: %s" afile))
18803 (message "File was not in list: %s (not removed)" afile))))
18805 (defun org-file-menu-entry (file)
18806 (vector file (list 'find-file file) t))
18808 (defun org-check-agenda-file (file)
18809 "Make sure FILE exists. If not, ask user what to do."
18810 (unless (file-exists-p file)
18811 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18812 (abbreviate-file-name file))
18813 (let ((r (downcase (read-char-exclusive))))
18814 (cond
18815 ((equal r ?r)
18816 (org-remove-file file)
18817 (throw 'nextfile t))
18818 (t (user-error "Abort"))))))
18820 (defun org-get-agenda-file-buffer (file)
18821 "Get an agenda buffer visiting FILE.
18822 If the buffer needs to be created, add it to the list of buffers
18823 which might be released later."
18824 (let ((buf (org-find-base-buffer-visiting file)))
18825 (if buf
18826 buf ; just return it
18827 ;; Make a new buffer and remember it
18828 (setq buf (find-file-noselect file))
18829 (when buf (push buf org-agenda-new-buffers))
18830 buf)))
18832 (defun org-release-buffers (blist)
18833 "Release all buffers in list, asking the user for confirmation when needed.
18834 When a buffer is unmodified, it is just killed. When modified, it is saved
18835 \(if the user agrees) and then killed."
18836 (let (file)
18837 (dolist (buf blist)
18838 (setq file (buffer-file-name buf))
18839 (when (and (buffer-modified-p buf)
18840 file
18841 (y-or-n-p (format "Save file %s? " file)))
18842 (with-current-buffer buf (save-buffer)))
18843 (kill-buffer buf))))
18845 (defun org-agenda-prepare-buffers (files)
18846 "Create buffers for all agenda files, protect archived trees and comments."
18847 (interactive)
18848 (let ((pa '(:org-archived t))
18849 (pc '(:org-comment t))
18850 (pall '(:org-archived t :org-comment t))
18851 (inhibit-read-only t)
18852 (org-inhibit-startup org-agenda-inhibit-startup)
18853 (rea (concat ":" org-archive-tag ":"))
18854 re pos)
18855 (setq org-tag-alist-for-agenda nil
18856 org-tag-groups-alist-for-agenda nil)
18857 (save-excursion
18858 (save-restriction
18859 (dolist (file files)
18860 (catch 'nextfile
18861 (if (bufferp file)
18862 (set-buffer file)
18863 (org-check-agenda-file file)
18864 (set-buffer (org-get-agenda-file-buffer file)))
18865 (widen)
18866 (org-set-regexps-and-options 'tags-only)
18867 (setq pos (point))
18868 (or (memq 'category org-agenda-ignore-properties)
18869 (org-refresh-category-properties))
18870 (or (memq 'stats org-agenda-ignore-properties)
18871 (org-refresh-stats-properties))
18872 (or (memq 'effort org-agenda-ignore-properties)
18873 (org-refresh-effort-properties))
18874 (or (memq 'appt org-agenda-ignore-properties)
18875 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18876 (setq org-todo-keywords-for-agenda
18877 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18878 (setq org-done-keywords-for-agenda
18879 (append org-done-keywords-for-agenda org-done-keywords))
18880 (setq org-todo-keyword-alist-for-agenda
18881 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18882 (setq org-tag-alist-for-agenda
18883 (org-uniquify
18884 (append org-tag-alist-for-agenda
18885 org-current-tag-alist)))
18886 ;; Merge current file's tag groups into global
18887 ;; `org-tag-groups-alist-for-agenda'.
18888 (when org-group-tags
18889 (dolist (alist org-tag-groups-alist)
18890 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18891 (if old
18892 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18893 (push alist org-tag-groups-alist-for-agenda)))))
18894 (org-with-silent-modifications
18895 (save-excursion
18896 (remove-text-properties (point-min) (point-max) pall)
18897 (when org-agenda-skip-archived-trees
18898 (goto-char (point-min))
18899 (while (re-search-forward rea nil t)
18900 (when (org-at-heading-p t)
18901 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18902 (goto-char (point-min))
18903 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18904 (while (re-search-forward re nil t)
18905 (when (save-match-data (org-in-commented-heading-p t))
18906 (add-text-properties
18907 (match-beginning 0) (org-end-of-subtree t) pc)))))
18908 (goto-char pos)))))
18909 (setq org-todo-keywords-for-agenda
18910 (org-uniquify org-todo-keywords-for-agenda))
18911 (setq org-todo-keyword-alist-for-agenda
18912 (org-uniquify org-todo-keyword-alist-for-agenda))))
18915 ;;;; CDLaTeX minor mode
18917 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18918 "Keymap for the minor `org-cdlatex-mode'.")
18920 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18921 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18922 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18923 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18924 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18926 (defvar org-cdlatex-texmathp-advice-is-done nil
18927 "Flag remembering if we have applied the advice to texmathp already.")
18929 (define-minor-mode org-cdlatex-mode
18930 "Toggle the minor `org-cdlatex-mode'.
18931 This mode supports entering LaTeX environment and math in LaTeX fragments
18932 in Org-mode.
18933 \\{org-cdlatex-mode-map}"
18934 nil " OCDL" nil
18935 (when org-cdlatex-mode
18936 (require 'cdlatex)
18937 (run-hooks 'cdlatex-mode-hook)
18938 (cdlatex-compute-tables))
18939 (unless org-cdlatex-texmathp-advice-is-done
18940 (setq org-cdlatex-texmathp-advice-is-done t)
18941 (defadvice texmathp (around org-math-always-on activate)
18942 "Always return t in org-mode buffers.
18943 This is because we want to insert math symbols without dollars even outside
18944 the LaTeX math segments. If Orgmode thinks that point is actually inside
18945 an embedded LaTeX fragment, let texmathp do its job.
18946 \\[org-cdlatex-mode-map]"
18947 (interactive)
18948 (let (p)
18949 (cond
18950 ((not (derived-mode-p 'org-mode)) ad-do-it)
18951 ((eq this-command 'cdlatex-math-symbol)
18952 (setq ad-return-value t
18953 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18955 (let ((p (org-inside-LaTeX-fragment-p)))
18956 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18957 (setq ad-return-value t
18958 texmathp-why '("Org-mode embedded math" . 0))
18959 (when p ad-do-it)))))))))
18961 (defun turn-on-org-cdlatex ()
18962 "Unconditionally turn on `org-cdlatex-mode'."
18963 (org-cdlatex-mode 1))
18965 (defun org-try-cdlatex-tab ()
18966 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18967 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18968 - inside a LaTeX fragment, or
18969 - after the first word in a line, where an abbreviation expansion could
18970 insert a LaTeX environment."
18971 (when org-cdlatex-mode
18972 (cond
18973 ;; Before any word on the line: No expansion possible.
18974 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18975 ;; Just after first word on the line: Expand it. Make sure it
18976 ;; cannot happen on headlines, though.
18977 ((save-excursion
18978 (skip-chars-backward "a-zA-Z0-9*")
18979 (skip-chars-backward " \t")
18980 (and (bolp) (not (org-at-heading-p))))
18981 (cdlatex-tab) t)
18982 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18984 (defun org-cdlatex-underscore-caret (&optional _arg)
18985 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18986 Revert to the normal definition outside of these fragments."
18987 (interactive "P")
18988 (if (org-inside-LaTeX-fragment-p)
18989 (call-interactively 'cdlatex-sub-superscript)
18990 (let (org-cdlatex-mode)
18991 (call-interactively (key-binding (vector last-input-event))))))
18993 (defun org-cdlatex-math-modify (&optional _arg)
18994 "Execute `cdlatex-math-modify' in LaTeX fragments.
18995 Revert to the normal definition outside of these fragments."
18996 (interactive "P")
18997 (if (org-inside-LaTeX-fragment-p)
18998 (call-interactively 'cdlatex-math-modify)
18999 (let (org-cdlatex-mode)
19000 (call-interactively (key-binding (vector last-input-event))))))
19002 (defun org-cdlatex-environment-indent (&optional environment item)
19003 "Execute `cdlatex-environment' and indent the inserted environment.
19005 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
19007 The inserted environment is indented to current indentation
19008 unless point is at the beginning of the line, in which the
19009 environment remains unintended."
19010 (interactive)
19011 ;; cdlatex-environment always return nil. Therefore, capture output
19012 ;; first and determine if an environment was selected.
19013 (let* ((beg (point-marker))
19014 (end (copy-marker (point) t))
19015 (inserted (progn
19016 (ignore-errors (cdlatex-environment environment item))
19017 (< beg end)))
19018 ;; Figure out how many lines to move forward after the
19019 ;; environment has been inserted.
19020 (lines (when inserted
19021 (save-excursion
19022 (- (cl-loop while (< beg (point))
19023 with x = 0
19024 do (forward-line -1)
19025 (cl-incf x)
19026 finally return x)
19027 (if (progn (goto-char beg)
19028 (and (progn (skip-chars-forward " \t") (eolp))
19029 (progn (skip-chars-backward " \t") (bolp))))
19030 1 0)))))
19031 (env (org-trim (delete-and-extract-region beg end))))
19032 (when inserted
19033 ;; Get indentation of next line unless at column 0.
19034 (let ((ind (if (bolp) 0
19035 (save-excursion
19036 (org-return-indent)
19037 (prog1 (org-get-indentation)
19038 (when (progn (skip-chars-forward " \t") (eolp))
19039 (delete-region beg (point)))))))
19040 (bol (progn (skip-chars-backward " \t") (bolp))))
19041 ;; Insert a newline before environment unless at column zero
19042 ;; to "escape" the current line. Insert a newline if
19043 ;; something is one the same line as \end{ENVIRONMENT}.
19044 (insert
19045 (concat (unless bol "\n") env
19046 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19047 (unless (zerop ind)
19048 (save-excursion
19049 (goto-char beg)
19050 (while (< (point) end)
19051 (unless (eolp) (indent-line-to ind))
19052 (forward-line))))
19053 (goto-char beg)
19054 (forward-line lines)
19055 (indent-line-to ind)))
19056 (set-marker beg nil)
19057 (set-marker end nil)))
19060 ;;;; LaTeX fragments
19062 (defun org-inside-LaTeX-fragment-p ()
19063 "Test if point is inside a LaTeX fragment.
19064 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19065 sequence appearing also before point.
19066 Even though the matchers for math are configurable, this function assumes
19067 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19068 delimiters are skipped when they have been removed by customization.
19069 The return value is nil, or a cons cell with the delimiter and the
19070 position of this delimiter.
19072 This function does a reasonably good job, but can locally be fooled by
19073 for example currency specifications. For example it will assume being in
19074 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19075 fragments that are properly closed, but during editing, we have to live
19076 with the uncertainty caused by missing closing delimiters. This function
19077 looks only before point, not after."
19078 (catch 'exit
19079 (let ((pos (point))
19080 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19081 (lim (progn
19082 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19083 (point)))
19084 dd-on str (start 0) m re)
19085 (goto-char pos)
19086 (when dodollar
19087 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19088 re (nth 1 (assoc "$" org-latex-regexps)))
19089 (while (string-match re str start)
19090 (cond
19091 ((= (match-end 0) (length str))
19092 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19093 ((= (match-end 0) (- (length str) 5))
19094 (throw 'exit nil))
19095 (t (setq start (match-end 0))))))
19096 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19097 (goto-char pos)
19098 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19099 (and (match-beginning 2) (throw 'exit nil))
19100 ;; count $$
19101 (while (re-search-backward "\\$\\$" lim t)
19102 (setq dd-on (not dd-on)))
19103 (goto-char pos)
19104 (when dd-on (cons "$$" m))))))
19106 (defun org-inside-latex-macro-p ()
19107 "Is point inside a LaTeX macro or its arguments?"
19108 (save-match-data
19109 (org-in-regexp
19110 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19112 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19113 "Build an overlay between BEG and END using IMAGE file.
19114 Argument IMAGETYPE is the extension of the displayed image,
19115 as a string. It defaults to \"png\"."
19116 (let ((ov (make-overlay beg end))
19117 (imagetype (or (intern imagetype) 'png)))
19118 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19119 (overlay-put ov 'evaporate t)
19120 (overlay-put ov
19121 'modification-hooks
19122 (list (lambda (o _flag _beg _end &optional _l)
19123 (delete-overlay o))))
19124 (overlay-put ov
19125 'display
19126 (list 'image :type imagetype :file image :ascent 'center))))
19128 (defun org--list-latex-overlays (&optional beg end)
19129 "List all Org LaTeX overlays in current buffer.
19130 Limit to overlays between BEG and END when those are provided."
19131 (cl-remove-if-not
19132 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19133 (overlays-in (or beg (point-min)) (or end (point-max)))))
19135 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19136 "Remove all overlays with LaTeX fragment images in current buffer.
19137 When optional arguments BEG and END are non-nil, remove all
19138 overlays between them instead. Return a non-nil value when some
19139 overlays were removed, nil otherwise."
19140 (let ((overlays (org--list-latex-overlays beg end)))
19141 (mapc #'delete-overlay overlays)
19142 overlays))
19144 (defun org-toggle-latex-fragment (&optional arg)
19145 "Preview the LaTeX fragment at point, or all locally or globally.
19147 If the cursor is on a LaTeX fragment, create the image and overlay
19148 it over the source code, if there is none. Remove it otherwise.
19149 If there is no fragment at point, display all fragments in the
19150 current section.
19152 With prefix ARG, preview or clear image for all fragments in the
19153 current subtree or in the whole buffer when used before the first
19154 headline. With a double prefix ARG \\[universal-argument] \
19155 \\[universal-argument] preview or clear images
19156 for all fragments in the buffer."
19157 (interactive "P")
19158 (when (display-graphic-p)
19159 (catch 'exit
19160 (save-excursion
19161 (let (beg end msg)
19162 (cond
19163 ((or (equal arg '(16))
19164 (and (equal arg '(4))
19165 (org-with-limited-levels (org-before-first-heading-p))))
19166 (if (org-remove-latex-fragment-image-overlays)
19167 (progn (message "LaTeX fragments images removed from buffer")
19168 (throw 'exit nil))
19169 (setq msg "Creating images for buffer...")))
19170 ((equal arg '(4))
19171 (org-with-limited-levels (org-back-to-heading t))
19172 (setq beg (point))
19173 (setq end (progn (org-end-of-subtree t) (point)))
19174 (if (org-remove-latex-fragment-image-overlays beg end)
19175 (progn
19176 (message "LaTeX fragment images removed from subtree")
19177 (throw 'exit nil))
19178 (setq msg "Creating images for subtree...")))
19179 ((let ((datum (org-element-context)))
19180 (when (memq (org-element-type datum)
19181 '(latex-environment latex-fragment))
19182 (setq beg (org-element-property :begin datum))
19183 (setq end (org-element-property :end datum))
19184 (if (org-remove-latex-fragment-image-overlays beg end)
19185 (progn (message "LaTeX fragment image removed")
19186 (throw 'exit nil))
19187 (setq msg "Creating image...")))))
19189 (org-with-limited-levels
19190 (setq beg (if (org-at-heading-p) (line-beginning-position)
19191 (outline-previous-heading)
19192 (point)))
19193 (setq end (progn (outline-next-heading) (point)))
19194 (if (org-remove-latex-fragment-image-overlays beg end)
19195 (progn
19196 (message "LaTeX fragment images removed from section")
19197 (throw 'exit nil))
19198 (setq msg "Creating images for section...")))))
19199 (let ((file (buffer-file-name (buffer-base-buffer))))
19200 (org-format-latex
19201 (concat org-preview-latex-image-directory "org-ltximg")
19202 beg end
19203 ;; Emacs cannot overlay images from remote hosts. Create
19204 ;; it in `temporary-file-directory' instead.
19205 (if (or (not file) (file-remote-p file))
19206 temporary-file-directory
19207 default-directory)
19208 'overlays msg 'forbuffer org-preview-latex-default-process))
19209 (message (concat msg "done")))))))
19211 (defun org-format-latex
19212 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19213 "Replace LaTeX fragments with links to an image.
19215 The function takes care of creating the replacement image.
19217 Only consider fragments between BEG and END when those are
19218 provided.
19220 When optional argument OVERLAYS is non-nil, display the image on
19221 top of the fragment instead of replacing it.
19223 PROCESSING-TYPE is the conversion method to use, as a symbol.
19225 Some of the options can be changed using the variable
19226 `org-format-latex-options', which see."
19227 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19228 (unless (eq processing-type 'verbatim)
19229 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19230 (cnt 0)
19231 checkdir-flag)
19232 (goto-char (or beg (point-min)))
19233 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19234 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19235 (overlay-recenter (or end (point-max))))
19236 (while (re-search-forward math-regexp end t)
19237 (unless (and overlays
19238 (eq (get-char-property (point) 'org-overlay-type)
19239 'org-latex-overlay))
19240 (let* ((context (org-element-context))
19241 (type (org-element-type context)))
19242 (when (memq type '(latex-environment latex-fragment))
19243 (let ((block-type (eq type 'latex-environment))
19244 (value (org-element-property :value context))
19245 (beg (org-element-property :begin context))
19246 (end (save-excursion
19247 (goto-char (org-element-property :end context))
19248 (skip-chars-backward " \r\t\n")
19249 (point))))
19250 (cond
19251 ((eq processing-type 'mathjax)
19252 ;; Prepare for MathJax processing.
19253 (if (not (string-match "\\`\\$\\$?" value))
19254 (goto-char end)
19255 (delete-region beg end)
19256 (if (string= (match-string 0 value) "$$")
19257 (insert "\\[" (substring value 2 -2) "\\]")
19258 (insert "\\(" (substring value 1 -1) "\\)"))))
19259 ((assq processing-type org-preview-latex-process-alist)
19260 ;; Process to an image.
19261 (cl-incf cnt)
19262 (goto-char beg)
19263 (let* ((processing-info
19264 (cdr (assq processing-type org-preview-latex-process-alist)))
19265 (face (face-at-point))
19266 ;; Get the colors from the face at point.
19268 (let ((color (plist-get org-format-latex-options
19269 :foreground)))
19270 (if (and forbuffer (eq color 'auto))
19271 (face-attribute face :foreground nil 'default)
19272 color)))
19274 (let ((color (plist-get org-format-latex-options
19275 :background)))
19276 (if (and forbuffer (eq color 'auto))
19277 (face-attribute face :background nil 'default)
19278 color)))
19279 (hash (sha1 (prin1-to-string
19280 (list org-format-latex-header
19281 org-latex-default-packages-alist
19282 org-latex-packages-alist
19283 org-format-latex-options
19284 forbuffer value fg bg))))
19285 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19286 (absprefix (expand-file-name prefix dir))
19287 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19288 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19289 (sep (and block-type "\n\n"))
19290 (link (concat sep "[[file:" linkfile "]]" sep))
19291 (options
19292 (org-combine-plists
19293 org-format-latex-options
19294 `(:foreground ,fg :background ,bg))))
19295 (when msg (message msg cnt))
19296 (unless checkdir-flag ; Ensure the directory exists.
19297 (setq checkdir-flag t)
19298 (let ((todir (file-name-directory absprefix)))
19299 (unless (file-directory-p todir)
19300 (make-directory todir t))))
19301 (unless (file-exists-p movefile)
19302 (org-create-formula-image
19303 value movefile options forbuffer processing-type))
19304 (if overlays
19305 (progn
19306 (dolist (o (overlays-in beg end))
19307 (when (eq (overlay-get o 'org-overlay-type)
19308 'org-latex-overlay)
19309 (delete-overlay o)))
19310 (org--format-latex-make-overlay beg end movefile imagetype)
19311 (goto-char end))
19312 (delete-region beg end)
19313 (insert
19314 (org-add-props link
19315 (list 'org-latex-src
19316 (replace-regexp-in-string "\"" "" value)
19317 'org-latex-src-embed-type
19318 (if block-type 'paragraph 'character)))))))
19319 ((eq processing-type 'mathml)
19320 ;; Process to MathML.
19321 (unless (org-format-latex-mathml-available-p)
19322 (user-error "LaTeX to MathML converter not configured"))
19323 (cl-incf cnt)
19324 (when msg (message msg cnt))
19325 (goto-char beg)
19326 (delete-region beg end)
19327 (insert (org-format-latex-as-mathml
19328 value block-type prefix dir)))
19330 (error "Unknown conversion process %s for LaTeX fragments"
19331 processing-type)))))))))))
19333 (defun org-create-math-formula (latex-frag &optional mathml-file)
19334 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19335 Use `org-latex-to-mathml-convert-command'. If the conversion is
19336 sucessful, return the portion between \"<math...> </math>\"
19337 elements otherwise return nil. When MATHML-FILE is specified,
19338 write the results in to that file. When invoked as an
19339 interactive command, prompt for LATEX-FRAG, with initial value
19340 set to the current active region and echo the results for user
19341 inspection."
19342 (interactive (list (let ((frag (when (org-region-active-p)
19343 (buffer-substring-no-properties
19344 (region-beginning) (region-end)))))
19345 (read-string "LaTeX Fragment: " frag nil frag))))
19346 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19347 (let* ((tmp-in-file
19348 (let ((file (file-relative-name
19349 (make-temp-name (expand-file-name "ltxmathml-in")))))
19350 (write-region latex-frag nil file)
19351 file))
19352 (tmp-out-file (file-relative-name
19353 (make-temp-name (expand-file-name "ltxmathml-out"))))
19354 (cmd (format-spec
19355 org-latex-to-mathml-convert-command
19356 `((?j . ,(and org-latex-to-mathml-jar-file
19357 (shell-quote-argument
19358 (expand-file-name
19359 org-latex-to-mathml-jar-file))))
19360 (?I . ,(shell-quote-argument tmp-in-file))
19361 (?i . ,latex-frag)
19362 (?o . ,(shell-quote-argument tmp-out-file)))))
19363 mathml shell-command-output)
19364 (when (called-interactively-p 'any)
19365 (unless (org-format-latex-mathml-available-p)
19366 (user-error "LaTeX to MathML converter not configured")))
19367 (message "Running %s" cmd)
19368 (setq shell-command-output (shell-command-to-string cmd))
19369 (setq mathml
19370 (when (file-readable-p tmp-out-file)
19371 (with-current-buffer (find-file-noselect tmp-out-file t)
19372 (goto-char (point-min))
19373 (when (re-search-forward
19374 (concat
19375 (regexp-quote
19376 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19377 "[^>]*?>"
19378 "\\(.\\|\n\\)*"
19379 "</math>")
19380 nil t)
19381 (prog1 (match-string 0) (kill-buffer))))))
19382 (cond
19383 (mathml
19384 (setq mathml
19385 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19386 (when mathml-file
19387 (write-region mathml nil mathml-file))
19388 (when (called-interactively-p 'any)
19389 (message mathml)))
19390 ((message "LaTeX to MathML conversion failed")
19391 (message shell-command-output)))
19392 (delete-file tmp-in-file)
19393 (when (file-exists-p tmp-out-file)
19394 (delete-file tmp-out-file))
19395 mathml))
19397 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19398 prefix &optional dir)
19399 "Use `org-create-math-formula' but check local cache first."
19400 (let* ((absprefix (expand-file-name prefix dir))
19401 (print-length nil) (print-level nil)
19402 (formula-id (concat
19403 "formula-"
19404 (sha1
19405 (prin1-to-string
19406 (list latex-frag
19407 org-latex-to-mathml-convert-command)))))
19408 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19409 (formula-cache-dir (file-name-directory formula-cache)))
19411 (unless (file-directory-p formula-cache-dir)
19412 (make-directory formula-cache-dir t))
19414 (unless (file-exists-p formula-cache)
19415 (org-create-math-formula latex-frag formula-cache))
19417 (if (file-exists-p formula-cache)
19418 ;; Successful conversion. Return the link to MathML file.
19419 (org-add-props
19420 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19421 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19422 'org-latex-src-embed-type (if latex-frag-type
19423 'paragraph 'character)))
19424 ;; Failed conversion. Return the LaTeX fragment verbatim
19425 latex-frag)))
19427 (declare-function org-export-get-backend "ox" (name))
19428 (declare-function org-export--get-global-options "ox" (&optional backend))
19429 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19430 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19431 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19432 (defun org-create-formula--latex-header ()
19433 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19434 (let ((info (org-combine-plists (org-export--get-global-options
19435 (org-export-get-backend 'latex))
19436 (org-export--get-inbuffer-options
19437 (org-export-get-backend 'latex)))))
19438 (org-latex-guess-babel-language
19439 (org-latex-guess-inputenc
19440 (org-splice-latex-header
19441 org-format-latex-header
19442 org-latex-default-packages-alist
19443 org-latex-packages-alist t
19444 (plist-get info :latex-header)))
19445 info)))
19447 (defun org--get-display-dpi ()
19448 "Get the DPI of the display.
19450 Assumes that the display has the same pixel width in the
19451 horizontal and vertical directions."
19452 (if (display-graphic-p)
19453 (round (/ (display-pixel-height)
19454 (/ (display-mm-height) 25.4)))
19455 (error "Attempt to calculate the dpi of a non-graphic display")))
19457 (defun org-create-formula-image
19458 (string tofile options buffer &optional processing-type)
19459 "Create an image from LaTeX source using external processes.
19461 The LaTeX STRING is saved to a temporary LaTeX file, then
19462 converted to an image file by process PROCESSING-TYPE defined in
19463 `org-preview-latex-process-alist'. A nil value defaults to
19464 `org-preview-latex-default-process'.
19466 The generated image file is eventually moved to TOFILE.
19468 The OPTIONS argument controls the size, foreground color and
19469 background color of the generated image.
19471 When BUFFER non-nil, this function is used for LaTeX previewing.
19472 Otherwise, it is used to deal with LaTeX snippets showed in
19473 a HTML file."
19474 (let* ((processing-type (or processing-type
19475 org-preview-latex-default-process))
19476 (processing-info
19477 (cdr (assq processing-type org-preview-latex-process-alist)))
19478 (programs (plist-get processing-info :programs))
19479 (error-message (or (plist-get processing-info :message) ""))
19480 (use-xcolor (plist-get processing-info :use-xcolor))
19481 (image-input-type (plist-get processing-info :image-input-type))
19482 (image-output-type (plist-get processing-info :image-output-type))
19483 (post-clean (or (plist-get processing-info :post-clean)
19484 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19485 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19486 (latex-header (or (plist-get processing-info :latex-header)
19487 (org-create-formula--latex-header)))
19488 (latex-compiler (plist-get processing-info :latex-compiler))
19489 (image-converter (plist-get processing-info :image-converter))
19490 (tmpdir temporary-file-directory)
19491 (texfilebase (make-temp-name
19492 (expand-file-name "orgtex" tmpdir)))
19493 (texfile (concat texfilebase ".tex"))
19494 (font-height (face-attribute 'default :height nil))
19495 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19496 '(1.0 . 1.0)))
19497 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19498 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19499 (dpi (* scale (floor (if buffer font-height 140.0))))
19500 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19501 "Black"))
19502 (bg (or (plist-get options (if buffer :background :html-background))
19503 "Transparent"))
19504 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19505 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19506 (dolist (program programs)
19507 (org-check-external-command program error-message))
19508 (if use-xcolor
19509 (progn (if (eq fg 'default)
19510 (setq fg (org-latex-color :foreground))
19511 (setq fg (org-latex-color-format fg)))
19512 (if (eq bg 'default)
19513 (setq bg (org-latex-color :background))
19514 (setq bg (org-latex-color-format
19515 (if (string= bg "Transparent") "white" bg))))
19516 (with-temp-file texfile
19517 (insert latex-header)
19518 (insert "\n\\begin{document}\n"
19519 "\\definecolor{fg}{rgb}{" fg "}\n"
19520 "\\definecolor{bg}{rgb}{" bg "}\n"
19521 "\n\\pagecolor{bg}\n"
19522 "\n{\\color{fg}\n"
19523 string
19524 "\n}\n"
19525 "\n\\end{document}\n")))
19526 (if (eq fg 'default)
19527 (setq fg (org-dvipng-color :foreground))
19528 (unless (string= fg "Transparent")
19529 (setq fg (org-dvipng-color-format fg))))
19530 (if (eq bg 'default)
19531 (setq bg (org-dvipng-color :background))
19532 (unless (string= bg "Transparent")
19533 (setq bg (org-dvipng-color-format bg))))
19534 (with-temp-file texfile
19535 (insert latex-header)
19536 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19538 (let* ((err-msg (format "Please adjust '%s' part of \
19539 `org-preview-latex-process-alist'."
19540 processing-type))
19541 (image-input-file
19542 (org-compile-file
19543 texfile latex-compiler image-input-type err-msg log-buf))
19544 (image-output-file
19545 (org-compile-file
19546 image-input-file image-converter image-output-type err-msg log-buf
19547 `((?F . ,(shell-quote-argument fg))
19548 (?B . ,(shell-quote-argument bg))
19549 (?D . ,(shell-quote-argument (format "%s" dpi)))
19550 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19551 (copy-file image-output-file tofile 'replace)
19552 (dolist (e post-clean)
19553 (when (file-exists-p (concat texfilebase e))
19554 (delete-file (concat texfilebase e))))
19555 image-output-file)))
19557 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19558 "Fill a LaTeX header template TPL.
19559 In the template, the following place holders will be recognized:
19561 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19562 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19563 [PACKAGES] \\usepackage statements for PKG
19564 [NO-PACKAGES] do not include PKG
19565 [EXTRA] the string EXTRA
19566 [NO-EXTRA] do not include EXTRA
19568 For backward compatibility, if both the positive and the negative place
19569 holder is missing, the positive one (without the \"NO-\") will be
19570 assumed to be present at the end of the template.
19571 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19572 EXTRA is a string.
19573 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19574 (let (rpl (end ""))
19575 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19576 (setq rpl (if (or (match-end 1) (not def-pkg))
19577 "" (org-latex-packages-to-string def-pkg snippets-p t))
19578 tpl (replace-match rpl t t tpl))
19579 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19581 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19582 (setq rpl (if (or (match-end 1) (not pkg))
19583 "" (org-latex-packages-to-string pkg snippets-p t))
19584 tpl (replace-match rpl t t tpl))
19585 (when pkg (setq end
19586 (concat end "\n"
19587 (org-latex-packages-to-string pkg snippets-p)))))
19589 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19590 (setq rpl (if (or (match-end 1) (not extra))
19591 "" (concat extra "\n"))
19592 tpl (replace-match rpl t t tpl))
19593 (when (and extra (string-match "\\S-" extra))
19594 (setq end (concat end "\n" extra))))
19596 (if (string-match "\\S-" end)
19597 (concat tpl "\n" end)
19598 tpl)))
19600 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19601 "Turn an alist of packages into a string with the \\usepackage macros."
19602 (setq pkg (mapconcat (lambda(p)
19603 (cond
19604 ((stringp p) p)
19605 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19606 (format "%% Package %s omitted" (cadr p)))
19607 ((equal "" (car p))
19608 (format "\\usepackage{%s}" (cadr p)))
19610 (format "\\usepackage[%s]{%s}"
19611 (car p) (cadr p)))))
19613 "\n"))
19614 (if newline (concat pkg "\n") pkg))
19616 (defun org-dvipng-color (attr)
19617 "Return a RGB color specification for dvipng."
19618 (apply #'format "rgb %s %s %s"
19619 (mapcar #'org-normalize-color
19620 (color-values (face-attribute 'default attr nil)))))
19622 (defun org-dvipng-color-format (color-name)
19623 "Convert COLOR-NAME to a RGB color value for dvipng."
19624 (apply 'format "rgb %s %s %s"
19625 (mapcar 'org-normalize-color
19626 (color-values color-name))))
19628 (defun org-latex-color (attr)
19629 "Return a RGB color for the LaTeX color package."
19630 (apply #'format "%s,%s,%s"
19631 (mapcar #'org-normalize-color
19632 (color-values (face-attribute 'default attr nil)))))
19634 (defun org-latex-color-format (color-name)
19635 "Convert COLOR-NAME to a RGB color value."
19636 (apply 'format "%s,%s,%s"
19637 (mapcar 'org-normalize-color
19638 (color-values color-name))))
19640 (defun org-normalize-color (value)
19641 "Return string to be used as color value for an RGB component."
19642 (format "%g" (/ value 65535.0)))
19646 ;; Image display
19648 (defvar-local org-inline-image-overlays nil)
19650 (defun org-toggle-inline-images (&optional include-linked)
19651 "Toggle the display of inline images.
19652 INCLUDE-LINKED is passed to `org-display-inline-images'."
19653 (interactive "P")
19654 (if org-inline-image-overlays
19655 (progn
19656 (org-remove-inline-images)
19657 (when (called-interactively-p 'interactive)
19658 (message "Inline image display turned off")))
19659 (org-display-inline-images include-linked)
19660 (when (called-interactively-p 'interactive)
19661 (message (if org-inline-image-overlays
19662 (format "%d images displayed inline"
19663 (length org-inline-image-overlays))
19664 "No images to display inline")))))
19666 (defun org-redisplay-inline-images ()
19667 "Refresh the display of inline images."
19668 (interactive)
19669 (if (not org-inline-image-overlays)
19670 (org-toggle-inline-images)
19671 (org-toggle-inline-images)
19672 (org-toggle-inline-images)))
19674 (defun org-display-inline-images (&optional include-linked refresh beg end)
19675 "Display inline images.
19677 An inline image is a link which follows either of these
19678 conventions:
19680 1. Its path is a file with an extension matching return value
19681 from `image-file-name-regexp' and it has no contents.
19683 2. Its description consists in a single link of the previous
19684 type.
19686 When optional argument INCLUDE-LINKED is non-nil, also links with
19687 a text description part will be inlined. This can be nice for
19688 a quick look at those images, but it does not reflect what
19689 exported files will look like.
19691 When optional argument REFRESH is non-nil, refresh existing
19692 images between BEG and END. This will create new image displays
19693 only if necessary. BEG and END default to the buffer
19694 boundaries."
19695 (interactive "P")
19696 (when (display-graphic-p)
19697 (unless refresh
19698 (org-remove-inline-images)
19699 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19700 (org-with-wide-buffer
19701 (goto-char (or beg (point-min)))
19702 (let ((case-fold-search t)
19703 (file-extension-re (image-file-name-regexp)))
19704 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19705 (let ((link (save-match-data (org-element-context))))
19706 ;; Check if we're at an inline image.
19707 (when (and (equal (org-element-property :type link) "file")
19708 (or include-linked
19709 (not (org-element-property :contents-begin link)))
19710 (let ((parent (org-element-property :parent link)))
19711 (or (not (eq (org-element-type parent) 'link))
19712 (not (cdr (org-element-contents parent)))))
19713 (string-match-p file-extension-re
19714 (org-element-property :path link)))
19715 (let ((file (expand-file-name
19716 (org-link-unescape
19717 (org-element-property :path link)))))
19718 (when (file-exists-p file)
19719 (let ((width
19720 ;; Apply `org-image-actual-width' specifications.
19721 (cond
19722 ((not (image-type-available-p 'imagemagick)) nil)
19723 ((eq org-image-actual-width t) nil)
19724 ((listp org-image-actual-width)
19726 ;; First try to find a width among
19727 ;; attributes associated to the paragraph
19728 ;; containing link.
19729 (let ((paragraph
19730 (let ((e link))
19731 (while (and (setq e (org-element-property
19732 :parent e))
19733 (not (eq (org-element-type e)
19734 'paragraph))))
19735 e)))
19736 (when paragraph
19737 (save-excursion
19738 (goto-char (org-element-property :begin paragraph))
19739 (when
19740 (re-search-forward
19741 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19742 (org-element-property
19743 :post-affiliated paragraph)
19745 (string-to-number (match-string 1))))))
19746 ;; Otherwise, fall-back to provided number.
19747 (car org-image-actual-width)))
19748 ((numberp org-image-actual-width)
19749 org-image-actual-width)))
19750 (old (get-char-property-and-overlay
19751 (org-element-property :begin link)
19752 'org-image-overlay)))
19753 (if (and (car-safe old) refresh)
19754 (image-refresh (overlay-get (cdr old) 'display))
19755 (let ((image (create-image file
19756 (and width 'imagemagick)
19758 :width width)))
19759 (when image
19760 (let* ((link
19761 ;; If inline image is the description
19762 ;; of another link, be sure to
19763 ;; consider the latter as the one to
19764 ;; apply the overlay on.
19765 (let ((parent
19766 (org-element-property :parent link)))
19767 (if (eq (org-element-type parent) 'link)
19768 parent
19769 link)))
19770 (ov (make-overlay
19771 (org-element-property :begin link)
19772 (progn
19773 (goto-char
19774 (org-element-property :end link))
19775 (skip-chars-backward " \t")
19776 (point)))))
19777 (overlay-put ov 'display image)
19778 (overlay-put ov 'face 'default)
19779 (overlay-put ov 'org-image-overlay t)
19780 (overlay-put
19781 ov 'modification-hooks
19782 (list 'org-display-inline-remove-overlay))
19783 (push ov org-inline-image-overlays)))))))))))))))
19785 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19786 "Remove inline-display overlay if a corresponding region is modified."
19787 (let ((inhibit-modification-hooks t))
19788 (when (and ov after)
19789 (delete ov org-inline-image-overlays)
19790 (delete-overlay ov))))
19792 (defun org-remove-inline-images ()
19793 "Remove inline display of images."
19794 (interactive)
19795 (mapc #'delete-overlay org-inline-image-overlays)
19796 (setq org-inline-image-overlays nil))
19798 ;;;; Key bindings
19800 ;; Outline functions from `outline-mode-prefix-map'
19801 ;; that can be remapped in Org:
19802 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19803 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19804 (define-key org-mode-map [remap outline-forward-same-level]
19805 'org-forward-heading-same-level)
19806 (define-key org-mode-map [remap outline-backward-same-level]
19807 'org-backward-heading-same-level)
19808 (define-key org-mode-map [remap outline-show-branches]
19809 'org-kill-note-or-show-branches)
19810 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19811 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19812 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19813 (define-key org-mode-map [remap outline-next-visible-heading]
19814 'org-next-visible-heading)
19815 (define-key org-mode-map [remap outline-previous-visible-heading]
19816 'org-previous-visible-heading)
19817 (define-key org-mode-map [remap show-children] 'org-show-children)
19819 ;; Outline functions from `outline-mode-prefix-map' that can not
19820 ;; be remapped in Org:
19822 ;; - the column "key binding" shows whether the Outline function is still
19823 ;; available in Org mode on the same key that it has been bound to in
19824 ;; Outline mode:
19825 ;; - "overridden": key used for a different functionality in Org mode
19826 ;; - else: key still bound to the same Outline function in Org mode
19828 ;; | Outline function | key binding | Org replacement |
19829 ;; |------------------------------------+-------------+--------------------------|
19830 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19831 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19832 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19833 ;; | `show-entry' | overridden | no replacement |
19834 ;; | `show-branches' | `C-c C-k' | still same function |
19835 ;; | `show-subtree' | overridden | visibility cycling |
19836 ;; | `show-all' | overridden | no replacement |
19837 ;; | `hide-subtree' | overridden | visibility cycling |
19838 ;; | `hide-body' | overridden | no replacement |
19839 ;; | `hide-entry' | overridden | visibility cycling |
19840 ;; | `hide-leaves' | overridden | no replacement |
19841 ;; | `hide-sublevels' | overridden | no replacement |
19842 ;; | `hide-other' | overridden | no replacement |
19844 ;; Make `C-c C-x' a prefix key
19845 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19847 ;; TAB key with modifiers
19848 (org-defkey org-mode-map "\C-i" 'org-cycle)
19849 (org-defkey org-mode-map [(tab)] 'org-cycle)
19850 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19851 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19852 ;; The following line is necessary under Suse GNU/Linux
19853 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19854 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19855 (define-key org-mode-map [backtab] 'org-shifttab)
19857 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19858 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19859 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19861 ;; Cursor keys with modifiers
19862 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19863 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19864 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19865 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19867 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19868 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19869 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19870 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19871 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19872 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19874 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19875 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19876 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19877 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19879 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19880 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19881 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19882 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19884 ;; Babel keys
19885 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19886 (dolist (pair org-babel-key-bindings)
19887 (define-key org-babel-map (car pair) (cdr pair)))
19889 ;;; Extra keys for tty access.
19890 ;; We only set them when really needed because otherwise the
19891 ;; menus don't show the simple keys
19893 (when (or org-use-extra-keys (not window-system))
19894 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19895 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19896 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19897 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19898 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19899 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19900 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19901 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19902 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19903 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19904 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19905 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19906 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19907 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19908 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19909 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19910 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19911 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19912 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19913 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19914 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19915 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19916 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19917 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19918 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19919 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19920 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19921 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19923 ;; All the other keys
19925 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19926 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19927 (if (boundp 'narrow-map)
19928 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19929 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19930 (if (boundp 'narrow-map)
19931 (org-defkey narrow-map "b" 'org-narrow-to-block)
19932 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19933 (if (boundp 'narrow-map)
19934 (org-defkey narrow-map "e" 'org-narrow-to-element)
19935 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19936 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19937 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19938 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19939 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19940 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19941 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19942 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19943 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19944 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19945 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19946 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19947 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19948 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19949 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19950 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19951 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19952 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19953 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19954 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19955 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19956 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19957 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19958 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19959 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19960 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19961 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19962 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19963 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19964 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19965 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19966 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19967 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19968 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19969 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19970 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19971 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19972 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19973 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19974 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19975 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19976 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19977 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19978 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19979 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19980 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19981 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19982 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19983 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19984 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19985 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19986 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19987 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19988 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19989 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19990 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19991 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19992 (org-defkey org-mode-map "\C-c^" 'org-sort)
19993 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19994 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19995 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19996 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19997 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19998 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19999 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
20000 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
20001 (org-defkey org-mode-map "\C-m" 'org-return)
20002 (org-defkey org-mode-map "\C-j" 'org-return-indent)
20003 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20004 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20005 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20006 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20007 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
20008 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20009 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
20010 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
20011 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20012 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20013 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20014 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
20015 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20016 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20017 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20018 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20019 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20020 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20021 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20022 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20023 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20024 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20025 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20026 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20028 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20029 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20030 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20032 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20033 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20034 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20035 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20036 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20037 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20038 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20039 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20040 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20041 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20042 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20043 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20044 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20045 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20046 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20047 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20048 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20049 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20050 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20051 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20052 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20053 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20055 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20056 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20057 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20058 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20059 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20061 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20063 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20065 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20066 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20068 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20071 (defconst org-speed-commands-default
20073 ("Outline Navigation")
20074 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20075 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20076 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20077 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20078 ("F" . org-next-block)
20079 ("B" . org-previous-block)
20080 ("u" . (org-speed-move-safe 'outline-up-heading))
20081 ("j" . org-goto)
20082 ("g" . (org-refile t))
20083 ("Outline Visibility")
20084 ("c" . org-cycle)
20085 ("C" . org-shifttab)
20086 (" " . org-display-outline-path)
20087 ("s" . org-narrow-to-subtree)
20088 ("=" . org-columns)
20089 ("Outline Structure Editing")
20090 ("U" . org-metaup)
20091 ("D" . org-metadown)
20092 ("r" . org-metaright)
20093 ("l" . org-metaleft)
20094 ("R" . org-shiftmetaright)
20095 ("L" . org-shiftmetaleft)
20096 ("i" . (progn (forward-char 1) (call-interactively
20097 'org-insert-heading-respect-content)))
20098 ("^" . org-sort)
20099 ("w" . org-refile)
20100 ("a" . org-archive-subtree-default-with-confirmation)
20101 ("@" . org-mark-subtree)
20102 ("#" . org-toggle-comment)
20103 ("Clock Commands")
20104 ("I" . org-clock-in)
20105 ("O" . org-clock-out)
20106 ("Meta Data Editing")
20107 ("t" . org-todo)
20108 ("," . (org-priority))
20109 ("0" . (org-priority ?\ ))
20110 ("1" . (org-priority ?A))
20111 ("2" . (org-priority ?B))
20112 ("3" . (org-priority ?C))
20113 (":" . org-set-tags-command)
20114 ("e" . org-set-effort)
20115 ("E" . org-inc-effort)
20116 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20117 (org-entry-put (point) "APPT_WARNTIME" m)))
20118 ("Agenda Views etc")
20119 ("v" . org-agenda)
20120 ("/" . org-sparse-tree)
20121 ("Misc")
20122 ("o" . org-open-at-point)
20123 ("?" . org-speed-command-help)
20124 ("<" . (org-agenda-set-restriction-lock 'subtree))
20125 (">" . (org-agenda-remove-restriction-lock))
20127 "The default speed commands.")
20129 (defun org-print-speed-command (e)
20130 (if (> (length (car e)) 1)
20131 (progn
20132 (princ "\n")
20133 (princ (car e))
20134 (princ "\n")
20135 (princ (make-string (length (car e)) ?-))
20136 (princ "\n"))
20137 (princ (car e))
20138 (princ " ")
20139 (if (symbolp (cdr e))
20140 (princ (symbol-name (cdr e)))
20141 (prin1 (cdr e)))
20142 (princ "\n")))
20144 (defun org-speed-command-help ()
20145 "Show the available speed commands."
20146 (interactive)
20147 (if (not org-use-speed-commands)
20148 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20149 (with-output-to-temp-buffer "*Help*"
20150 (princ "User-defined Speed commands\n===========================\n")
20151 (mapc #'org-print-speed-command org-speed-commands-user)
20152 (princ "\n")
20153 (princ "Built-in Speed commands\n=======================\n")
20154 (mapc #'org-print-speed-command org-speed-commands-default))
20155 (with-current-buffer "*Help*"
20156 (setq truncate-lines t))))
20158 (defun org-speed-move-safe (cmd)
20159 "Execute CMD, but make sure that the cursor always ends up in a headline.
20160 If not, return to the original position and throw an error."
20161 (interactive)
20162 (let ((pos (point)))
20163 (call-interactively cmd)
20164 (unless (and (bolp) (org-at-heading-p))
20165 (goto-char pos)
20166 (error "Boundary reached while executing %s" cmd))))
20168 (defvar org-self-insert-command-undo-counter 0)
20170 (defvar org-table-auto-blank-field) ; defined in org-table.el
20171 (defvar org-speed-command nil)
20173 (defun org-speed-command-activate (keys)
20174 "Hook for activating single-letter speed commands.
20175 `org-speed-commands-default' specifies a minimal command set.
20176 Use `org-speed-commands-user' for further customization."
20177 (when (or (and (bolp) (looking-at org-outline-regexp))
20178 (and (functionp org-use-speed-commands)
20179 (funcall org-use-speed-commands)))
20180 (cdr (assoc keys (append org-speed-commands-user
20181 org-speed-commands-default)))))
20183 (defun org-babel-speed-command-activate (keys)
20184 "Hook for activating single-letter code block commands."
20185 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20186 (cdr (assoc keys org-babel-key-bindings))))
20188 (defcustom org-speed-command-hook
20189 '(org-speed-command-default-hook org-babel-speed-command-hook)
20190 "Hook for activating speed commands at strategic locations.
20191 Hook functions are called in sequence until a valid handler is
20192 found.
20194 Each hook takes a single argument, a user-pressed command key
20195 which is also a `self-insert-command' from the global map.
20197 Within the hook, examine the cursor position and the command key
20198 and return nil or a valid handler as appropriate. Handler could
20199 be one of an interactive command, a function, or a form.
20201 Set `org-use-speed-commands' to non-nil value to enable this
20202 hook. The default setting is `org-speed-command-activate'."
20203 :group 'org-structure
20204 :version "24.1"
20205 :type 'hook)
20207 (defun org-self-insert-command (N)
20208 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20209 If the cursor is in a table looking at whitespace, the whitespace is
20210 overwritten, and the table is not marked as requiring realignment."
20211 (interactive "p")
20212 (org-check-before-invisible-edit 'insert)
20213 (cond
20214 ((and org-use-speed-commands
20215 (let ((kv (this-command-keys-vector)))
20216 (setq org-speed-command
20217 (run-hook-with-args-until-success
20218 'org-speed-command-hook
20219 (make-string 1 (aref kv (1- (length kv))))))))
20220 (cond
20221 ((commandp org-speed-command)
20222 (setq this-command org-speed-command)
20223 (call-interactively org-speed-command))
20224 ((functionp org-speed-command)
20225 (funcall org-speed-command))
20226 ((and org-speed-command (listp org-speed-command))
20227 (eval org-speed-command))
20228 (t (let (org-use-speed-commands)
20229 (call-interactively 'org-self-insert-command)))))
20230 ((and
20231 (org-at-table-p)
20232 (progn
20233 ;; Check if we blank the field, and if that triggers align.
20234 (and (featurep 'org-table) org-table-auto-blank-field
20235 (memq last-command
20236 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20237 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20238 ;; Got extra space, this field does not determine
20239 ;; column width.
20240 (let (org-table-may-need-update) (org-table-blank-field))
20241 ;; No extra space, this field may determine column
20242 ;; width.
20243 (org-table-blank-field)))
20245 (eq N 1)
20246 (looking-at "[^|\n]* \\( \\)|"))
20247 ;; There is room for insertion without re-aligning the table.
20248 (delete-region (match-beginning 1) (match-end 1))
20249 (self-insert-command N))
20251 (setq org-table-may-need-update t)
20252 (self-insert-command N)
20253 (org-fix-tags-on-the-fly)
20254 (when org-self-insert-cluster-for-undo
20255 (if (not (eq last-command 'org-self-insert-command))
20256 (setq org-self-insert-command-undo-counter 1)
20257 (if (>= org-self-insert-command-undo-counter 20)
20258 (setq org-self-insert-command-undo-counter 1)
20259 (and (> org-self-insert-command-undo-counter 0)
20260 buffer-undo-list (listp buffer-undo-list)
20261 (not (cadr buffer-undo-list)) ; remove nil entry
20262 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20263 (setq org-self-insert-command-undo-counter
20264 (1+ org-self-insert-command-undo-counter))))))))
20266 (defun org-check-before-invisible-edit (kind)
20267 "Check is editing if kind KIND would be dangerous with invisible text around.
20268 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20269 ;; First, try to get out of here as quickly as possible, to reduce overhead
20270 (when (and org-catch-invisible-edits
20271 (or (not (boundp 'visible-mode)) (not visible-mode))
20272 (or (get-char-property (point) 'invisible)
20273 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20274 ;; OK, we need to take a closer look
20275 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20276 (invisible-before-point (unless (bobp) (get-char-property
20277 (1- (point)) 'invisible)))
20278 (border-and-ok-direction
20280 ;; Check if we are acting predictably before invisible text
20281 (and invisible-at-point (not invisible-before-point)
20282 (memq kind '(insert delete-backward)))
20283 ;; Check if we are acting predictably after invisible text
20284 ;; This works not well, and I have turned it off. It seems
20285 ;; better to always show and stop after invisible text.
20286 ;; (and (not invisible-at-point) invisible-before-point
20287 ;; (memq kind '(insert delete)))
20289 (when (or (memq invisible-at-point '(outline org-hide-block t))
20290 (memq invisible-before-point '(outline org-hide-block t)))
20291 (when (eq org-catch-invisible-edits 'error)
20292 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20293 (if (and org-custom-properties-overlays
20294 (y-or-n-p "Display invisible properties in this buffer? "))
20295 (org-toggle-custom-properties-visibility)
20296 ;; Make the area visible
20297 (save-excursion
20298 (when invisible-before-point
20299 (goto-char (previous-single-char-property-change
20300 (point) 'invisible)))
20301 (outline-show-subtree))
20302 (cond
20303 ((eq org-catch-invisible-edits 'show)
20304 ;; That's it, we do the edit after showing
20305 (message
20306 "Unfolding invisible region around point before editing")
20307 (sit-for 1))
20308 ((and (eq org-catch-invisible-edits 'smart)
20309 border-and-ok-direction)
20310 (message "Unfolding invisible region around point before editing"))
20312 ;; Don't do the edit, make the user repeat it in full visibility
20313 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20315 (defun org-fix-tags-on-the-fly ()
20316 (when (and (equal (char-after (point-at-bol)) ?*)
20317 (org-at-heading-p))
20318 (org-align-tags-here org-tags-column)))
20320 (defun org-delete-backward-char (N)
20321 "Like `delete-backward-char', insert whitespace at field end in tables.
20322 When deleting backwards, in tables this function will insert whitespace in
20323 front of the next \"|\" separator, to keep the table aligned. The table will
20324 still be marked for re-alignment if the field did fill the entire column,
20325 because, in this case the deletion might narrow the column."
20326 (interactive "p")
20327 (save-match-data
20328 (org-check-before-invisible-edit 'delete-backward)
20329 (if (and (org-at-table-p)
20330 (eq N 1)
20331 (string-match "|" (buffer-substring (point-at-bol) (point)))
20332 (looking-at ".*?|"))
20333 (let ((pos (point))
20334 (noalign (looking-at "[^|\n\r]* |"))
20335 (c org-table-may-need-update))
20336 (backward-delete-char N)
20337 (unless overwrite-mode
20338 (skip-chars-forward "^|")
20339 (insert " ")
20340 (goto-char (1- pos)))
20341 ;; noalign: if there were two spaces at the end, this field
20342 ;; does not determine the width of the column.
20343 (when noalign (setq org-table-may-need-update c)))
20344 (backward-delete-char N)
20345 (org-fix-tags-on-the-fly))))
20347 (defun org-delete-char (N)
20348 "Like `delete-char', but insert whitespace at field end in tables.
20349 When deleting characters, in tables this function will insert whitespace in
20350 front of the next \"|\" separator, to keep the table aligned. The table will
20351 still be marked for re-alignment if the field did fill the entire column,
20352 because, in this case the deletion might narrow the column."
20353 (interactive "p")
20354 (save-match-data
20355 (org-check-before-invisible-edit 'delete)
20356 (if (and (org-at-table-p)
20357 (not (bolp))
20358 (not (= (char-after) ?|))
20359 (eq N 1))
20360 (if (looking-at ".*?|")
20361 (let ((pos (point))
20362 (noalign (looking-at "[^|\n\r]* |"))
20363 (c org-table-may-need-update))
20364 (replace-match
20365 (concat (substring (match-string 0) 1 -1) " |") nil t)
20366 (goto-char pos)
20367 ;; noalign: if there were two spaces at the end, this field
20368 ;; does not determine the width of the column.
20369 (when noalign (setq org-table-may-need-update c)))
20370 (delete-char N))
20371 (delete-char N)
20372 (org-fix-tags-on-the-fly))))
20374 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20375 (put 'org-self-insert-command 'delete-selection
20376 (lambda ()
20377 (not (run-hook-with-args-until-success
20378 'self-insert-uses-region-functions))))
20379 (put 'orgtbl-self-insert-command 'delete-selection
20380 (lambda ()
20381 (not (run-hook-with-args-until-success
20382 'self-insert-uses-region-functions))))
20383 (put 'org-delete-char 'delete-selection 'supersede)
20384 (put 'org-delete-backward-char 'delete-selection 'supersede)
20385 (put 'org-yank 'delete-selection 'yank)
20387 ;; Make `flyspell-mode' delay after some commands
20388 (put 'org-self-insert-command 'flyspell-delayed t)
20389 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20390 (put 'org-delete-char 'flyspell-delayed t)
20391 (put 'org-delete-backward-char 'flyspell-delayed t)
20393 ;; Make pabbrev-mode expand after org-mode commands
20394 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20395 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20397 (defun org-remap (map &rest commands)
20398 "In MAP, remap the functions given in COMMANDS.
20399 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20400 (let (new old)
20401 (while commands
20402 (setq old (pop commands) new (pop commands))
20403 (if (fboundp 'command-remapping)
20404 (org-defkey map (vector 'remap old) new)
20405 (substitute-key-definition old new map global-map)))))
20407 (defun org-transpose-words ()
20408 "Transpose words for Org.
20409 This uses the `org-mode-transpose-word-syntax-table' syntax
20410 table, which interprets characters in `org-emphasis-alist' as
20411 word constituents."
20412 (interactive)
20413 (with-syntax-table org-mode-transpose-word-syntax-table
20414 (call-interactively 'transpose-words)))
20415 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20417 (when (eq org-enable-table-editor 'optimized)
20418 ;; If the user wants maximum table support, we need to hijack
20419 ;; some standard editing functions
20420 (org-remap org-mode-map
20421 'self-insert-command 'org-self-insert-command
20422 'delete-char 'org-delete-char
20423 'delete-backward-char 'org-delete-backward-char)
20424 (org-defkey org-mode-map "|" 'org-force-self-insert))
20426 (defvar org-ctrl-c-ctrl-c-hook nil
20427 "Hook for functions attaching themselves to `C-c C-c'.
20429 This can be used to add additional functionality to the C-c C-c
20430 key which executes context-dependent commands. This hook is run
20431 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20432 run after the last test.
20434 Each function will be called with no arguments. The function
20435 must check if the context is appropriate for it to act. If yes,
20436 it should do its thing and then return a non-nil value. If the
20437 context is wrong, just do nothing and return nil.")
20439 (defvar org-ctrl-c-ctrl-c-final-hook nil
20440 "Hook for functions attaching themselves to `C-c C-c'.
20442 This can be used to add additional functionality to the C-c C-c
20443 key which executes context-dependent commands. This hook is run
20444 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20445 before the first test.
20447 Each function will be called with no arguments. The function
20448 must check if the context is appropriate for it to act. If yes,
20449 it should do its thing and then return a non-nil value. If the
20450 context is wrong, just do nothing and return nil.")
20452 (defvar org-tab-first-hook nil
20453 "Hook for functions to attach themselves to TAB.
20454 See `org-ctrl-c-ctrl-c-hook' for more information.
20455 This hook runs as the first action when TAB is pressed, even before
20456 `org-cycle' messes around with the `outline-regexp' to cater for
20457 inline tasks and plain list item folding.
20458 If any function in this hook returns t, any other actions that
20459 would have been caused by TAB (such as table field motion or visibility
20460 cycling) will not occur.")
20462 (defvar org-tab-after-check-for-table-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 after it has been established that the cursor is not in a
20466 table, but before checking if the cursor is in a headline or if global cycling
20467 should be done.
20468 If any function in this hook returns t, not other actions like visibility
20469 cycling will be done.")
20471 (defvar org-tab-after-check-for-cycling-hook nil
20472 "Hook for functions to attach themselves to TAB.
20473 See `org-ctrl-c-ctrl-c-hook' for more information.
20474 This hook runs after it has been established that not table field motion and
20475 not visibility should be done because of current context. This is probably
20476 the place where a package like yasnippets can hook in.")
20478 (defvar org-tab-before-tab-emulation-hook nil
20479 "Hook for functions to attach themselves to TAB.
20480 See `org-ctrl-c-ctrl-c-hook' for more information.
20481 This hook runs after every other options for TAB have been exhausted, but
20482 before indentation and \t insertion takes place.")
20484 (defvar org-metaleft-hook nil
20485 "Hook for functions attaching themselves to `M-left'.
20486 See `org-ctrl-c-ctrl-c-hook' for more information.")
20487 (defvar org-metaright-hook nil
20488 "Hook for functions attaching themselves to `M-right'.
20489 See `org-ctrl-c-ctrl-c-hook' for more information.")
20490 (defvar org-metaup-hook nil
20491 "Hook for functions attaching themselves to `M-up'.
20492 See `org-ctrl-c-ctrl-c-hook' for more information.")
20493 (defvar org-metadown-hook nil
20494 "Hook for functions attaching themselves to `M-down'.
20495 See `org-ctrl-c-ctrl-c-hook' for more information.")
20496 (defvar org-shiftmetaleft-hook nil
20497 "Hook for functions attaching themselves to `M-S-left'.
20498 See `org-ctrl-c-ctrl-c-hook' for more information.")
20499 (defvar org-shiftmetaright-hook nil
20500 "Hook for functions attaching themselves to `M-S-right'.
20501 See `org-ctrl-c-ctrl-c-hook' for more information.")
20502 (defvar org-shiftmetaup-hook nil
20503 "Hook for functions attaching themselves to `M-S-up'.
20504 See `org-ctrl-c-ctrl-c-hook' for more information.")
20505 (defvar org-shiftmetadown-hook nil
20506 "Hook for functions attaching themselves to `M-S-down'.
20507 See `org-ctrl-c-ctrl-c-hook' for more information.")
20508 (defvar org-metareturn-hook nil
20509 "Hook for functions attaching themselves to `M-RET'.
20510 See `org-ctrl-c-ctrl-c-hook' for more information.")
20511 (defvar org-shiftup-hook nil
20512 "Hook for functions attaching themselves to `S-up'.
20513 See `org-ctrl-c-ctrl-c-hook' for more information.")
20514 (defvar org-shiftup-final-hook nil
20515 "Hook for functions attaching themselves to `S-up'.
20516 This one runs after all other options except shift-select have been excluded.
20517 See `org-ctrl-c-ctrl-c-hook' for more information.")
20518 (defvar org-shiftdown-hook nil
20519 "Hook for functions attaching themselves to `S-down'.
20520 See `org-ctrl-c-ctrl-c-hook' for more information.")
20521 (defvar org-shiftdown-final-hook nil
20522 "Hook for functions attaching themselves to `S-down'.
20523 This one runs after all other options except shift-select have been excluded.
20524 See `org-ctrl-c-ctrl-c-hook' for more information.")
20525 (defvar org-shiftleft-hook nil
20526 "Hook for functions attaching themselves to `S-left'.
20527 See `org-ctrl-c-ctrl-c-hook' for more information.")
20528 (defvar org-shiftleft-final-hook nil
20529 "Hook for functions attaching themselves to `S-left'.
20530 This one runs after all other options except shift-select have been excluded.
20531 See `org-ctrl-c-ctrl-c-hook' for more information.")
20532 (defvar org-shiftright-hook nil
20533 "Hook for functions attaching themselves to `S-right'.
20534 See `org-ctrl-c-ctrl-c-hook' for more information.")
20535 (defvar org-shiftright-final-hook nil
20536 "Hook for functions attaching themselves to `S-right'.
20537 This one runs after all other options except shift-select have been excluded.
20538 See `org-ctrl-c-ctrl-c-hook' for more information.")
20540 (defun org-modifier-cursor-error ()
20541 "Throw an error, a modified cursor command was applied in wrong context."
20542 (user-error "This command is active in special context like tables, headlines or items"))
20544 (defun org-shiftselect-error ()
20545 "Throw an error because Shift-Cursor command was applied in wrong context."
20546 (if (and (boundp 'shift-select-mode) shift-select-mode)
20547 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20548 (user-error "This command works only in special context like headlines or timestamps")))
20550 (defun org-call-for-shift-select (cmd)
20551 (let ((this-command-keys-shift-translated t))
20552 (call-interactively cmd)))
20554 (defun org-shifttab (&optional arg)
20555 "Global visibility cycling or move to previous table field.
20556 Call `org-table-previous-field' within a table.
20557 When ARG is nil, cycle globally through visibility states.
20558 When ARG is a numeric prefix, show contents of this level."
20559 (interactive "P")
20560 (cond
20561 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20562 ((integerp arg)
20563 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20564 (message "Content view to level: %d" arg)
20565 (org-content (prefix-numeric-value arg2))
20566 (org-cycle-show-empty-lines t)
20567 (setq org-cycle-global-status 'overview)))
20568 (t (call-interactively 'org-global-cycle))))
20570 (defun org-shiftmetaleft ()
20571 "Promote subtree or delete table column.
20572 Calls `org-promote-subtree', `org-outdent-item-tree', or
20573 `org-table-delete-column', depending on context. See the
20574 individual commands for more information."
20575 (interactive)
20576 (cond
20577 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20578 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20579 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20580 ((if (not (org-region-active-p)) (org-at-item-p)
20581 (save-excursion (goto-char (region-beginning))
20582 (org-at-item-p)))
20583 (call-interactively 'org-outdent-item-tree))
20584 (t (org-modifier-cursor-error))))
20586 (defun org-shiftmetaright ()
20587 "Demote subtree or insert table column.
20588 Calls `org-demote-subtree', `org-indent-item-tree', or
20589 `org-table-insert-column', depending on context. See the
20590 individual commands for more information."
20591 (interactive)
20592 (cond
20593 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20594 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20595 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20596 ((if (not (org-region-active-p)) (org-at-item-p)
20597 (save-excursion (goto-char (region-beginning))
20598 (org-at-item-p)))
20599 (call-interactively 'org-indent-item-tree))
20600 (t (org-modifier-cursor-error))))
20602 (defun org-shiftmetaup (&optional _arg)
20603 "Drag the line at point up.
20604 In a table, kill the current row.
20605 On a clock timestamp, update the value of the timestamp like `S-<up>'
20606 but also adjust the previous clocked item in the clock history.
20607 Everywhere else, drag the line at point up."
20608 (interactive "P")
20609 (cond
20610 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20611 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20612 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20613 (call-interactively 'org-timestamp-up)))
20614 (t (call-interactively 'org-drag-line-backward))))
20616 (defun org-shiftmetadown (&optional _arg)
20617 "Drag the line at point down.
20618 In a table, insert an empty row at the current line.
20619 On a clock timestamp, update the value of the timestamp like `S-<down>'
20620 but also adjust the previous clocked item in the clock history.
20621 Everywhere else, drag the line at point down."
20622 (interactive "P")
20623 (cond
20624 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20625 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20626 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20627 (call-interactively 'org-timestamp-down)))
20628 (t (call-interactively 'org-drag-line-forward))))
20630 (defsubst org-hidden-tree-error ()
20631 (user-error
20632 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20634 (defun org-metaleft (&optional _arg)
20635 "Promote heading, list item at point or move table column left.
20637 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20638 depending on context. With no specific context, calls the Emacs
20639 default `backward-word'. See the individual commands for more
20640 information.
20642 This function runs the hook `org-metaleft-hook' as a first step,
20643 and returns at first non-nil value."
20644 (interactive "P")
20645 (cond
20646 ((run-hook-with-args-until-success 'org-metaleft-hook))
20647 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20648 ((org-with-limited-levels
20649 (or (org-at-heading-p)
20650 (and (org-region-active-p)
20651 (save-excursion
20652 (goto-char (region-beginning))
20653 (org-at-heading-p)))))
20654 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20655 (call-interactively 'org-do-promote))
20656 ;; At an inline task.
20657 ((org-at-heading-p)
20658 (call-interactively 'org-inlinetask-promote))
20659 ((or (org-at-item-p)
20660 (and (org-region-active-p)
20661 (save-excursion
20662 (goto-char (region-beginning))
20663 (org-at-item-p))))
20664 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20665 (call-interactively 'org-outdent-item))
20666 (t (call-interactively 'backward-word))))
20668 (defun org-metaright (&optional _arg)
20669 "Demote heading, list item at point or move table column right.
20671 In front of a drawer or a block keyword, indent it correctly.
20673 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20674 `org-indnet-drawer' or `org-indent-block' depending on context.
20675 With no specific context, calls the Emacs default `forward-word'.
20676 See the individual commands for more information.
20678 This function runs the hook `org-metaright-hook' as a first step,
20679 and returns at first non-nil value."
20680 (interactive "P")
20681 (cond
20682 ((run-hook-with-args-until-success 'org-metaright-hook))
20683 ((org-at-table-p) (call-interactively 'org-table-move-column))
20684 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20685 ((org-at-block-p) (call-interactively 'org-indent-block))
20686 ((org-with-limited-levels
20687 (or (org-at-heading-p)
20688 (and (org-region-active-p)
20689 (save-excursion
20690 (goto-char (region-beginning))
20691 (org-at-heading-p)))))
20692 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20693 (call-interactively 'org-do-demote))
20694 ;; At an inline task.
20695 ((org-at-heading-p)
20696 (call-interactively 'org-inlinetask-demote))
20697 ((or (org-at-item-p)
20698 (and (org-region-active-p)
20699 (save-excursion
20700 (goto-char (region-beginning))
20701 (org-at-item-p))))
20702 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20703 (call-interactively 'org-indent-item))
20704 (t (call-interactively 'forward-word))))
20706 (defun org-check-for-hidden (what)
20707 "Check if there are hidden headlines/items in the current visual line.
20708 WHAT can be either `headlines' or `items'. If the current line is
20709 an outline or item heading and it has a folded subtree below it,
20710 this function returns t, nil otherwise."
20711 (let ((re (cond
20712 ((eq what 'headlines) org-outline-regexp-bol)
20713 ((eq what 'items) (org-item-beginning-re))
20714 (t (error "This should not happen"))))
20715 beg end)
20716 (save-excursion
20717 (catch 'exit
20718 (unless (org-region-active-p)
20719 (setq beg (point-at-bol))
20720 (beginning-of-line 2)
20721 (while (and (not (eobp)) ;; this is like `next-line'
20722 (get-char-property (1- (point)) 'invisible))
20723 (beginning-of-line 2))
20724 (setq end (point))
20725 (goto-char beg)
20726 (goto-char (point-at-eol))
20727 (setq end (max end (point)))
20728 (while (re-search-forward re end t)
20729 (when (get-char-property (match-beginning 0) 'invisible)
20730 (throw 'exit t))))
20731 nil))))
20733 (defun org-metaup (&optional _arg)
20734 "Move subtree up or move table row up.
20735 Calls `org-move-subtree-up' or `org-table-move-row' or
20736 `org-move-item-up', depending on context. See the individual commands
20737 for more information."
20738 (interactive "P")
20739 (cond
20740 ((run-hook-with-args-until-success 'org-metaup-hook))
20741 ((org-region-active-p)
20742 (let* ((a (min (region-beginning) (region-end)))
20743 (b (1- (max (region-beginning) (region-end))))
20744 (c (save-excursion (goto-char a)
20745 (move-beginning-of-line 0)))
20746 (d (save-excursion (goto-char a)
20747 (move-end-of-line 0) (point))))
20748 (transpose-regions a b c d)
20749 (goto-char c)))
20750 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20751 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20752 ((org-at-item-p) (call-interactively 'org-move-item-up))
20753 (t (org-drag-element-backward))))
20755 (defun org-metadown (&optional _arg)
20756 "Move subtree down or move table row down.
20757 Calls `org-move-subtree-down' or `org-table-move-row' or
20758 `org-move-item-down', depending on context. See the individual
20759 commands for more information."
20760 (interactive "P")
20761 (cond
20762 ((run-hook-with-args-until-success 'org-metadown-hook))
20763 ((org-region-active-p)
20764 (let* ((a (min (region-beginning) (region-end)))
20765 (b (max (region-beginning) (region-end)))
20766 (c (save-excursion (goto-char b)
20767 (move-beginning-of-line 1)))
20768 (d (save-excursion (goto-char b)
20769 (move-end-of-line 1) (1+ (point)))))
20770 (transpose-regions a b c d)
20771 (goto-char d)))
20772 ((org-at-table-p) (call-interactively 'org-table-move-row))
20773 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20774 ((org-at-item-p) (call-interactively 'org-move-item-down))
20775 (t (org-drag-element-forward))))
20777 (defun org-shiftup (&optional arg)
20778 "Increase item in timestamp or increase priority of current headline.
20779 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20780 depending on context. See the individual commands for more information."
20781 (interactive "P")
20782 (cond
20783 ((run-hook-with-args-until-success 'org-shiftup-hook))
20784 ((and org-support-shift-select (org-region-active-p))
20785 (org-call-for-shift-select 'previous-line))
20786 ((org-at-timestamp-p t)
20787 (call-interactively (if org-edit-timestamp-down-means-later
20788 'org-timestamp-down 'org-timestamp-up)))
20789 ((and (not (eq org-support-shift-select 'always))
20790 org-enable-priority-commands
20791 (org-at-heading-p))
20792 (call-interactively 'org-priority-up))
20793 ((and (not org-support-shift-select) (org-at-item-p))
20794 (call-interactively 'org-previous-item))
20795 ((org-clocktable-try-shift 'up arg))
20796 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20797 (org-support-shift-select
20798 (org-call-for-shift-select 'previous-line))
20799 (t (org-shiftselect-error))))
20801 (defun org-shiftdown (&optional arg)
20802 "Decrease item in timestamp or decrease priority of current headline.
20803 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20804 depending on context. See the individual commands for more information."
20805 (interactive "P")
20806 (cond
20807 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20808 ((and org-support-shift-select (org-region-active-p))
20809 (org-call-for-shift-select 'next-line))
20810 ((org-at-timestamp-p t)
20811 (call-interactively (if org-edit-timestamp-down-means-later
20812 'org-timestamp-up 'org-timestamp-down)))
20813 ((and (not (eq org-support-shift-select 'always))
20814 org-enable-priority-commands
20815 (org-at-heading-p))
20816 (call-interactively 'org-priority-down))
20817 ((and (not org-support-shift-select) (org-at-item-p))
20818 (call-interactively 'org-next-item))
20819 ((org-clocktable-try-shift 'down arg))
20820 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20821 (org-support-shift-select
20822 (org-call-for-shift-select 'next-line))
20823 (t (org-shiftselect-error))))
20825 (defun org-shiftright (&optional arg)
20826 "Cycle the thing at point or in the current line, depending on context.
20827 Depending on context, this does one of the following:
20829 - switch a timestamp at point one day into the future
20830 - on a headline, switch to the next TODO keyword.
20831 - on an item, switch entire list to the next bullet type
20832 - on a property line, switch to the next allowed value
20833 - on a clocktable definition line, move time block into the future"
20834 (interactive "P")
20835 (cond
20836 ((run-hook-with-args-until-success 'org-shiftright-hook))
20837 ((and org-support-shift-select (org-region-active-p))
20838 (org-call-for-shift-select 'forward-char))
20839 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20840 ((and (not (eq org-support-shift-select 'always))
20841 (org-at-heading-p))
20842 (let ((org-inhibit-logging
20843 (not org-treat-S-cursor-todo-selection-as-state-change))
20844 (org-inhibit-blocking
20845 (not org-treat-S-cursor-todo-selection-as-state-change)))
20846 (org-call-with-arg 'org-todo 'right)))
20847 ((or (and org-support-shift-select
20848 (not (eq org-support-shift-select 'always))
20849 (org-at-item-bullet-p))
20850 (and (not org-support-shift-select) (org-at-item-p)))
20851 (org-call-with-arg 'org-cycle-list-bullet nil))
20852 ((and (not (eq org-support-shift-select 'always))
20853 (org-at-property-p))
20854 (call-interactively 'org-property-next-allowed-value))
20855 ((org-clocktable-try-shift 'right arg))
20856 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20857 (org-support-shift-select
20858 (org-call-for-shift-select 'forward-char))
20859 (t (org-shiftselect-error))))
20861 (defun org-shiftleft (&optional arg)
20862 "Cycle the thing at point or in the current line, depending on context.
20863 Depending on context, this does one of the following:
20865 - switch a timestamp at point one day into the past
20866 - on a headline, switch to the previous TODO keyword.
20867 - on an item, switch entire list to the previous bullet type
20868 - on a property line, switch to the previous allowed value
20869 - on a clocktable definition line, move time block into the past"
20870 (interactive "P")
20871 (cond
20872 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20873 ((and org-support-shift-select (org-region-active-p))
20874 (org-call-for-shift-select 'backward-char))
20875 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20876 ((and (not (eq org-support-shift-select 'always))
20877 (org-at-heading-p))
20878 (let ((org-inhibit-logging
20879 (not org-treat-S-cursor-todo-selection-as-state-change))
20880 (org-inhibit-blocking
20881 (not org-treat-S-cursor-todo-selection-as-state-change)))
20882 (org-call-with-arg 'org-todo 'left)))
20883 ((or (and org-support-shift-select
20884 (not (eq org-support-shift-select 'always))
20885 (org-at-item-bullet-p))
20886 (and (not org-support-shift-select) (org-at-item-p)))
20887 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20888 ((and (not (eq org-support-shift-select 'always))
20889 (org-at-property-p))
20890 (call-interactively 'org-property-previous-allowed-value))
20891 ((org-clocktable-try-shift 'left arg))
20892 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20893 (org-support-shift-select
20894 (org-call-for-shift-select 'backward-char))
20895 (t (org-shiftselect-error))))
20897 (defun org-shiftcontrolright ()
20898 "Switch to next TODO set."
20899 (interactive)
20900 (cond
20901 ((and org-support-shift-select (org-region-active-p))
20902 (org-call-for-shift-select 'forward-word))
20903 ((and (not (eq org-support-shift-select 'always))
20904 (org-at-heading-p))
20905 (org-call-with-arg 'org-todo 'nextset))
20906 (org-support-shift-select
20907 (org-call-for-shift-select 'forward-word))
20908 (t (org-shiftselect-error))))
20910 (defun org-shiftcontrolleft ()
20911 "Switch to previous TODO set."
20912 (interactive)
20913 (cond
20914 ((and org-support-shift-select (org-region-active-p))
20915 (org-call-for-shift-select 'backward-word))
20916 ((and (not (eq org-support-shift-select 'always))
20917 (org-at-heading-p))
20918 (org-call-with-arg 'org-todo 'previousset))
20919 (org-support-shift-select
20920 (org-call-for-shift-select 'backward-word))
20921 (t (org-shiftselect-error))))
20923 (defun org-shiftcontrolup (&optional n)
20924 "Change timestamps synchronously up in CLOCK log lines.
20925 Optional argument N tells to change by that many units."
20926 (interactive "P")
20927 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20928 (let (org-support-shift-select)
20929 (org-clock-timestamps-up n))
20930 (user-error "Not at a clock log")))
20932 (defun org-shiftcontroldown (&optional n)
20933 "Change timestamps synchronously down in CLOCK log lines.
20934 Optional argument N tells to change by that many units."
20935 (interactive "P")
20936 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20937 (let (org-support-shift-select)
20938 (org-clock-timestamps-down n))
20939 (user-error "Not at a clock log")))
20941 (defun org-increase-number-at-point (&optional inc)
20942 "Increment the number at point.
20943 With an optional prefix numeric argument INC, increment using
20944 this numeric value."
20945 (interactive "p")
20946 (if (not (number-at-point))
20947 (user-error "Not on a number")
20948 (unless inc (setq inc 1))
20949 (let ((pos (point))
20950 (beg (skip-chars-backward "-+^/*0-9eE."))
20951 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20952 (setq nap (buffer-substring-no-properties
20953 (+ pos beg) (+ pos beg end)))
20954 (delete-region (+ pos beg) (+ pos beg end))
20955 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20956 (when (org-at-table-p)
20957 (org-table-align)
20958 (org-table-end-of-field 1))))
20960 (defun org-decrease-number-at-point (&optional inc)
20961 "Decrement the number at point.
20962 With an optional prefix numeric argument INC, decrement using
20963 this numeric value."
20964 (interactive "p")
20965 (org-increase-number-at-point (- (or inc 1))))
20967 (defun org-ctrl-c-ret ()
20968 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20969 (interactive)
20970 (cond
20971 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20972 (t (call-interactively 'org-insert-heading))))
20974 (defun org-find-visible ()
20975 (let ((s (point)))
20976 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20977 (get-char-property s 'invisible)))
20979 (defun org-find-invisible ()
20980 (let ((s (point)))
20981 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20982 (not (get-char-property s 'invisible))))
20985 (defun org-copy-visible (beg end)
20986 "Copy the visible parts of the region."
20987 (interactive "r")
20988 (let (snippets s)
20989 (save-excursion
20990 (save-restriction
20991 (narrow-to-region beg end)
20992 (setq s (goto-char (point-min)))
20993 (while (not (= (point) (point-max)))
20994 (goto-char (org-find-invisible))
20995 (push (buffer-substring s (point)) snippets)
20996 (setq s (goto-char (org-find-visible))))))
20997 (kill-new (apply 'concat (nreverse snippets)))))
20999 (defun org-copy-special ()
21000 "Copy region in table or copy current subtree.
21001 Calls `org-table-copy' or `org-copy-subtree', depending on context.
21002 See the individual commands for more information."
21003 (interactive)
21004 (call-interactively
21005 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
21007 (defun org-cut-special ()
21008 "Cut region in table or cut current subtree.
21009 Calls `org-table-copy' or `org-cut-subtree', depending on context.
21010 See the individual commands for more information."
21011 (interactive)
21012 (call-interactively
21013 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
21015 (defun org-paste-special (arg)
21016 "Paste rectangular region into table, or past subtree relative to level.
21017 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21018 See the individual commands for more information."
21019 (interactive "P")
21020 (if (org-at-table-p)
21021 (org-table-paste-rectangle)
21022 (org-paste-subtree arg)))
21024 (defsubst org-in-fixed-width-region-p ()
21025 "Is point in a fixed-width region?"
21026 (save-match-data
21027 (eq 'fixed-width (org-element-type (org-element-at-point)))))
21029 (defun org-edit-special (&optional arg)
21030 "Call a special editor for the element at point.
21031 When at a table, call the formula editor with `org-table-edit-formulas'.
21032 When in a source code block, call `org-edit-src-code'.
21033 When in a fixed-width region, call `org-edit-fixed-width-region'.
21034 When in an export block, call `org-edit-export-block'.
21035 When at an #+INCLUDE keyword, visit the included file.
21036 When at a footnote reference, call `org-edit-footnote-reference'
21037 On a link, call `ffap' to visit the link at point.
21038 Otherwise, return a user error."
21039 (interactive "P")
21040 (let ((element (org-element-at-point)))
21041 (cl-assert (not buffer-read-only) nil
21042 "Buffer is read-only: %s" (buffer-name))
21043 (pcase (org-element-type element)
21044 (`src-block
21045 (if (not arg) (org-edit-src-code)
21046 (let* ((info (org-babel-get-src-block-info))
21047 (lang (nth 0 info))
21048 (params (nth 2 info))
21049 (session (cdr (assq :session params))))
21050 (if (not session) (org-edit-src-code)
21051 ;; At a src-block with a session and function called with
21052 ;; an ARG: switch to the buffer related to the inferior
21053 ;; process.
21054 (switch-to-buffer
21055 (funcall (intern (concat "org-babel-prep-session:" lang))
21056 session params))))))
21057 (`keyword
21058 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21059 (org-open-link-from-string
21060 (format "[[%s]]"
21061 (expand-file-name
21062 (let ((value (org-element-property :value element)))
21063 (cond ((not (org-string-nw-p value))
21064 (user-error "No file to edit"))
21065 ((string-match "\\`\"\\(.*?\\)\"" value)
21066 (match-string 1 value))
21067 ((string-match "\\`[^ \t\"]\\S-*" value)
21068 (match-string 0 value))
21069 (t (user-error "No valid file specified")))))))
21070 (user-error "No special environment to edit here")))
21071 (`table
21072 (if (eq (org-element-property :type element) 'table.el)
21073 (org-edit-table.el)
21074 (call-interactively 'org-table-edit-formulas)))
21075 ;; Only Org tables contain `table-row' type elements.
21076 (`table-row (call-interactively 'org-table-edit-formulas))
21077 (`example-block (org-edit-src-code))
21078 (`export-block (org-edit-export-block))
21079 (`fixed-width (org-edit-fixed-width-region))
21081 ;; No notable element at point. Though, we may be at a link or
21082 ;; a footnote reference, which are objects. Thus, scan deeper.
21083 (let ((context (org-element-context element)))
21084 (pcase (org-element-type context)
21085 (`footnote-reference (org-edit-footnote-reference))
21086 (`inline-src-block (org-edit-inline-src-code))
21087 (`link (call-interactively #'ffap))
21088 (_ (user-error "No special environment to edit here"))))))))
21090 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21091 (defun org-ctrl-c-ctrl-c (&optional arg)
21092 "Set tags in headline, or update according to changed information at point.
21094 This command does many different things, depending on context:
21096 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21097 this is what we do.
21099 - If the cursor is on a statistics cookie, update it.
21101 - If the cursor is in a headline, prompt for tags and insert them
21102 into the current line, aligned to `org-tags-column'. When called
21103 with prefix arg, realign all tags in the current buffer.
21105 - If the cursor is in one of the special #+KEYWORD lines, this
21106 triggers scanning the buffer for these lines and updating the
21107 information.
21109 - If the cursor is inside a table, realign the table. This command
21110 works even if the automatic table editor has been turned off.
21112 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21113 the entire table.
21115 - If the cursor is at a footnote reference or definition, jump to
21116 the corresponding definition or references, respectively.
21118 - If the cursor is a the beginning of a dynamic block, update it.
21120 - If the current buffer is a capture buffer, close note and file it.
21122 - If the cursor is on a <<<target>>>, update radio targets and
21123 corresponding links in this buffer.
21125 - If the cursor is on a numbered item in a plain list, renumber the
21126 ordered list.
21128 - If the cursor is on a checkbox, toggle it.
21130 - If the cursor is on a code block, evaluate it. The variable
21131 `org-confirm-babel-evaluate' can be used to control prompting
21132 before code block evaluation, by default every code block
21133 evaluation requires confirmation. Code block evaluation can be
21134 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21135 (interactive "P")
21136 (cond
21137 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21138 org-occur-highlights)
21139 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21140 (org-remove-occur-highlights)
21141 (message "Temporary highlights/overlays removed from current buffer"))
21142 ((and (local-variable-p 'org-finish-function (current-buffer))
21143 (fboundp org-finish-function))
21144 (funcall org-finish-function))
21145 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21147 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21148 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21149 (user-error "C-c C-c can do nothing useful at this location"))
21150 (let* ((context (org-element-context))
21151 (type (org-element-type context)))
21152 (cl-case type
21153 ;; When at a link, act according to the parent instead.
21154 (link (setq context (org-element-property :parent context))
21155 (setq type (org-element-type context)))
21156 ;; Unsupported object types: refer to the first supported
21157 ;; element or object containing it.
21158 ((bold code entity export-snippet inline-babel-call inline-src-block
21159 italic latex-fragment line-break macro strike-through subscript
21160 superscript underline verbatim)
21161 (setq context
21162 (org-element-lineage
21163 context '(radio-target paragraph verse-block table-cell)))))
21164 ;; For convenience: at the first line of a paragraph on the
21165 ;; same line as an item, apply function on that item instead.
21166 (when (eq type 'paragraph)
21167 (let ((parent (org-element-property :parent context)))
21168 (when (and (eq (org-element-type parent) 'item)
21169 (= (line-beginning-position)
21170 (org-element-property :begin parent)))
21171 (setq context parent type 'item))))
21172 ;; Act according to type of element or object at point.
21173 (cl-case type
21174 (clock (org-clock-update-time-maybe))
21175 (dynamic-block
21176 (save-excursion
21177 (goto-char (org-element-property :post-affiliated context))
21178 (org-update-dblock)))
21179 (footnote-definition
21180 (goto-char (org-element-property :post-affiliated context))
21181 (call-interactively 'org-footnote-action))
21182 (footnote-reference (call-interactively 'org-footnote-action))
21183 ((headline inlinetask)
21184 (save-excursion (goto-char (org-element-property :begin context))
21185 (call-interactively 'org-set-tags)))
21186 (item
21187 ;; At an item: a double C-u set checkbox to "[-]"
21188 ;; unconditionally, whereas a single one will toggle its
21189 ;; presence. Without a universal argument, if the item
21190 ;; has a checkbox, toggle it. Otherwise repair the list.
21191 (let* ((box (org-element-property :checkbox context))
21192 (struct (org-element-property :structure context))
21193 (old-struct (copy-tree struct))
21194 (parents (org-list-parents-alist struct))
21195 (prevs (org-list-prevs-alist struct))
21196 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21197 (org-list-set-checkbox
21198 (org-element-property :begin context) struct
21199 (cond ((equal arg '(16)) "[-]")
21200 ((and (not box) (equal arg '(4))) "[ ]")
21201 ((or (not box) (equal arg '(4))) nil)
21202 ((eq box 'on) "[ ]")
21203 (t "[X]")))
21204 ;; Mimic `org-list-write-struct' but with grabbing
21205 ;; a return value from `org-list-struct-fix-box'.
21206 (org-list-struct-fix-ind struct parents 2)
21207 (org-list-struct-fix-item-end struct)
21208 (org-list-struct-fix-bul struct prevs)
21209 (org-list-struct-fix-ind struct parents)
21210 (let ((block-item
21211 (org-list-struct-fix-box struct parents prevs orderedp)))
21212 (if (and box (equal struct old-struct))
21213 (if (equal arg '(16))
21214 (message "Checkboxes already reset")
21215 (user-error "Cannot toggle this checkbox: %s"
21216 (if (eq box 'on)
21217 "all subitems checked"
21218 "unchecked subitems")))
21219 (org-list-struct-apply-struct struct old-struct)
21220 (org-update-checkbox-count-maybe))
21221 (when block-item
21222 (message "Checkboxes were removed due to empty box at line %d"
21223 (org-current-line block-item))))))
21224 (keyword
21225 (let ((org-inhibit-startup-visibility-stuff t)
21226 (org-startup-align-all-tables nil))
21227 (when (boundp 'org-table-coordinate-overlays)
21228 (mapc #'delete-overlay org-table-coordinate-overlays)
21229 (setq org-table-coordinate-overlays nil))
21230 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21231 (message "Local setup has been refreshed"))
21232 (plain-list
21233 ;; At a plain list, with a double C-u argument, set
21234 ;; checkboxes of each item to "[-]", whereas a single one
21235 ;; will toggle their presence according to the state of the
21236 ;; first item in the list. Without an argument, repair the
21237 ;; list.
21238 (let* ((begin (org-element-property :contents-begin context))
21239 (beginm (move-marker (make-marker) begin))
21240 (struct (org-element-property :structure context))
21241 (old-struct (copy-tree struct))
21242 (first-box (save-excursion
21243 (goto-char begin)
21244 (looking-at org-list-full-item-re)
21245 (match-string-no-properties 3)))
21246 (new-box (cond ((equal arg '(16)) "[-]")
21247 ((equal arg '(4)) (unless first-box "[ ]"))
21248 ((equal first-box "[X]") "[ ]")
21249 (t "[X]"))))
21250 (cond
21251 (arg
21252 (dolist (pos
21253 (org-list-get-all-items
21254 begin struct (org-list-prevs-alist struct)))
21255 (org-list-set-checkbox pos struct new-box)))
21256 ((and first-box (eq (point) begin))
21257 ;; For convenience, when point is at bol on the first
21258 ;; item of the list and no argument is provided, simply
21259 ;; toggle checkbox of that item, if any.
21260 (org-list-set-checkbox begin struct new-box)))
21261 (org-list-write-struct
21262 struct (org-list-parents-alist struct) old-struct)
21263 (org-update-checkbox-count-maybe)
21264 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21265 ((property-drawer node-property)
21266 (call-interactively 'org-property-action))
21267 ((radio-target target)
21268 (call-interactively 'org-update-radio-target-regexp))
21269 (statistics-cookie
21270 (call-interactively 'org-update-statistics-cookies))
21271 ((table table-cell table-row)
21272 ;; At a table, recalculate every field and align it. Also
21273 ;; send the table if necessary. If the table has
21274 ;; a `table.el' type, just give up. At a table row or
21275 ;; cell, maybe recalculate line but always align table.
21276 (if (eq (org-element-property :type context) 'table.el)
21277 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21278 Use \\[org-edit-special] to edit table.el tables"))
21279 (let ((org-enable-table-editor t))
21280 (if (or (eq type 'table)
21281 ;; Check if point is at a TBLFM line.
21282 (and (eq type 'table-row)
21283 (= (point) (org-element-property :end context))))
21284 (save-excursion
21285 (if (org-at-TBLFM-p)
21286 (progn (require 'org-table)
21287 (org-table-calc-current-TBLFM))
21288 (goto-char (org-element-property :contents-begin context))
21289 (org-call-with-arg 'org-table-recalculate (or arg t))
21290 (orgtbl-send-table 'maybe)))
21291 (org-table-maybe-eval-formula)
21292 (cond (arg (call-interactively 'org-table-recalculate))
21293 ((org-table-maybe-recalculate-line))
21294 (t (org-table-align)))))))
21295 (timestamp (org-timestamp-change 0 'day))
21296 (otherwise
21297 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21298 (user-error
21299 "C-c C-c can do nothing useful at this location")))))))))
21301 (defun org-mode-restart ()
21302 (interactive)
21303 (let ((indent-status (bound-and-true-p org-indent-mode)))
21304 (funcall major-mode)
21305 (hack-local-variables)
21306 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21307 (org-indent-mode -1)))
21308 (message "%s restarted" major-mode))
21310 (defun org-kill-note-or-show-branches ()
21311 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21312 (interactive)
21313 (if (not org-finish-function)
21314 (progn
21315 (outline-hide-subtree)
21316 (call-interactively 'outline-show-branches))
21317 (let ((org-note-abort t))
21318 (funcall org-finish-function))))
21320 (defun org-delete-indentation (&optional ARG)
21321 "Join current line to previous and fix whitespace at join.
21323 If previous line is a headline add to headline title. Otherwise
21324 the function calls `delete-indentation'.
21326 With argument, join this line to following line."
21327 (interactive "*P")
21328 (if (save-excursion
21329 (if ARG (beginning-of-line)
21330 (forward-line -1))
21331 (looking-at org-complex-heading-regexp))
21332 ;; At headline.
21333 (let ((tags-column (when (match-beginning 5)
21334 (save-excursion (goto-char (match-beginning 5))
21335 (current-column))))
21336 (string (concat " " (progn (when ARG (forward-line 1))
21337 (org-trim (delete-and-extract-region
21338 (line-beginning-position)
21339 (line-end-position)))))))
21340 (unless (bobp) (delete-region (point) (1- (point))))
21341 (goto-char (or (match-end 4)
21342 (match-beginning 5)
21343 (match-end 0)))
21344 (skip-chars-backward " \t")
21345 (save-excursion (insert string))
21346 ;; Adjust alignment of tags.
21347 (when tags-column
21348 (org-align-tags-here (if org-auto-align-tags
21349 org-tags-column
21350 tags-column))))
21351 (delete-indentation ARG)))
21353 (defun org-open-line (n)
21354 "Insert a new row in tables, call `open-line' elsewhere.
21355 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21356 (interactive "*p")
21357 (cond
21358 ((not org-special-ctrl-o)
21359 (open-line n))
21360 ((org-at-table-p)
21361 (org-table-insert-row))
21363 (open-line n))))
21365 (defun org-return (&optional indent)
21366 "Goto next table row or insert a newline.
21368 Calls `org-table-next-row' or `newline', depending on context.
21370 When optional INDENT argument is non-nil, call
21371 `newline-and-indent' instead of `newline'.
21373 When `org-return-follows-link' is non-nil and point is on
21374 a timestamp or a link, call `org-open-at-point'. However, it
21375 will not happen if point is in a table or on a \"dead\"
21376 object (e.g., within a comment). In these case, you need to use
21377 `org-open-at-point' directly."
21378 (interactive)
21379 (let ((context (if org-return-follows-link (org-element-context)
21380 (org-element-at-point))))
21381 (cond
21382 ;; In a table, call `org-table-next-row'.
21383 ((or (and (eq (org-element-type context) 'table)
21384 (>= (point) (org-element-property :contents-begin context))
21385 (< (point) (org-element-property :contents-end context)))
21386 (org-element-lineage context '(table-row table-cell) t))
21387 (org-table-justify-field-maybe)
21388 (call-interactively #'org-table-next-row))
21389 ;; On a link or a timestamp, call `org-open-at-point' if
21390 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21391 ;; locations, e.g., in a comment, as `org-open-at-point'.
21392 ((and org-return-follows-link
21393 (or (org-in-regexp org-ts-regexp-both nil t)
21394 (org-in-regexp org-tsr-regexp-both nil t)
21395 (org-in-regexp org-any-link-re nil t)))
21396 (call-interactively #'org-open-at-point))
21397 ;; Insert newline in heading, but preserve tags.
21398 ((and (not (bolp))
21399 (save-excursion (beginning-of-line)
21400 (looking-at org-complex-heading-regexp)))
21401 ;; At headline. Split line. However, if point is on keyword,
21402 ;; priority cookie or tags, do not break any of them: add
21403 ;; a newline after the headline instead.
21404 (let ((tags-column (and (match-beginning 5)
21405 (save-excursion (goto-char (match-beginning 5))
21406 (current-column))))
21407 (string
21408 (when (and (match-end 4)
21409 (>= (point)
21410 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21411 (<= (point) (match-end 4)))
21412 (delete-and-extract-region (point) (match-end 4)))))
21413 (when (and tags-column string) ; Adjust tag alignment.
21414 (org-align-tags-here
21415 (if org-auto-align-tags org-tags-column tags-column)))
21416 (end-of-line)
21417 (org-show-entry)
21418 (if indent (newline-and-indent) (newline))
21419 (when string (save-excursion (insert (org-trim string))))))
21420 ;; In a list, make sure indenting keeps trailing text within.
21421 ((and indent
21422 (not (eolp))
21423 (org-element-lineage context '(item)))
21424 (let ((trailing-data
21425 (delete-and-extract-region (point) (line-end-position))))
21426 (newline-and-indent)
21427 (save-excursion (insert trailing-data))))
21428 (t (if indent (newline-and-indent) (newline))))))
21430 (defun org-return-indent ()
21431 "Goto next table row or insert a newline and indent.
21432 Calls `org-table-next-row' or `newline-and-indent', depending on
21433 context. See the individual commands for more information."
21434 (interactive)
21435 (org-return t))
21437 (defun org-ctrl-c-star ()
21438 "Compute table, or change heading status of lines.
21439 Calls `org-table-recalculate' or `org-toggle-heading',
21440 depending on context."
21441 (interactive)
21442 (cond
21443 ((org-at-table-p)
21444 (call-interactively 'org-table-recalculate))
21446 ;; Convert all lines in region to list items
21447 (call-interactively 'org-toggle-heading))))
21449 (defun org-ctrl-c-minus ()
21450 "Insert separator line in table or modify bullet status of line.
21451 Also turns a plain line or a region of lines into list items.
21452 Calls `org-table-insert-hline', `org-toggle-item', or
21453 `org-cycle-list-bullet', depending on context."
21454 (interactive)
21455 (cond
21456 ((org-at-table-p)
21457 (call-interactively 'org-table-insert-hline))
21458 ((org-region-active-p)
21459 (call-interactively 'org-toggle-item))
21460 ((org-in-item-p)
21461 (call-interactively 'org-cycle-list-bullet))
21463 (call-interactively 'org-toggle-item))))
21465 (defun org-toggle-heading (&optional nstars)
21466 "Convert headings to normal text, or items or text to headings.
21467 If there is no active region, only convert the current line.
21469 With a \\[universal-argument] prefix, convert the whole list at
21470 point into heading.
21472 In a region:
21474 - If the first non blank line is a headline, remove the stars
21475 from all headlines in the region.
21477 - If it is a normal line, turn each and every normal line (i.e.,
21478 not an heading or an item) in the region into headings. If you
21479 want to convert only the first line of this region, use one
21480 universal prefix argument.
21482 - If it is a plain list item, turn all plain list items into headings.
21484 When converting a line into a heading, the number of stars is chosen
21485 such that the lines become children of the current entry. However,
21486 when a numeric prefix argument is given, its value determines the
21487 number of stars to add."
21488 (interactive "P")
21489 (let ((skip-blanks
21490 (function
21491 ;; Return beginning of first non-blank line, starting from
21492 ;; line at POS.
21493 (lambda (pos)
21494 (save-excursion
21495 (goto-char pos)
21496 (while (org-at-comment-p) (forward-line))
21497 (skip-chars-forward " \r\t\n")
21498 (point-at-bol)))))
21499 beg end toggled)
21500 ;; Determine boundaries of changes. If a universal prefix has
21501 ;; been given, put the list in a region. If region ends at a bol,
21502 ;; do not consider the last line to be in the region.
21504 (when (and current-prefix-arg (org-at-item-p))
21505 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21506 (org-mark-element))
21508 (if (org-region-active-p)
21509 (setq beg (funcall skip-blanks (region-beginning))
21510 end (copy-marker (save-excursion
21511 (goto-char (region-end))
21512 (if (bolp) (point) (point-at-eol)))))
21513 (setq beg (funcall skip-blanks (point-at-bol))
21514 end (copy-marker (point-at-eol))))
21515 ;; Ensure inline tasks don't count as headings.
21516 (org-with-limited-levels
21517 (save-excursion
21518 (goto-char beg)
21519 (cond
21520 ;; Case 1. Started at an heading: de-star headings.
21521 ((org-at-heading-p)
21522 (while (< (point) end)
21523 (when (org-at-heading-p t)
21524 (looking-at org-outline-regexp) (replace-match "")
21525 (setq toggled t))
21526 (forward-line)))
21527 ;; Case 2. Started at an item: change items into headlines.
21528 ;; One star will be added by `org-list-to-subtree'.
21529 ((org-at-item-p)
21530 (while (< (point) end)
21531 (when (org-at-item-p)
21532 ;; Pay attention to cases when region ends before list.
21533 (let* ((struct (org-list-struct))
21534 (list-end
21535 (min (org-list-get-bottom-point struct) (1+ end))))
21536 (save-restriction
21537 (narrow-to-region (point) list-end)
21538 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21539 (setq toggled t))
21540 (forward-line)))
21541 ;; Case 3. Started at normal text: make every line an heading,
21542 ;; skipping headlines and items.
21543 (t (let* ((stars
21544 (make-string
21545 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21546 (add-stars
21547 (cond (nstars "") ; stars from prefix only
21548 ((equal stars "") "*") ; before first heading
21549 (org-odd-levels-only "**") ; inside heading, odd
21550 (t "*"))) ; inside heading, oddeven
21551 (rpl (concat stars add-stars " "))
21552 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21553 (while (< (point) (if (equal nstars '(4)) lend end))
21554 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21555 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21556 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21557 (forward-line)))))))
21558 (unless toggled (message "Cannot toggle heading from here"))))
21560 (defun org-meta-return (&optional _arg)
21561 "Insert a new heading or wrap a region in a table.
21562 Calls `org-insert-heading' or `org-table-wrap-region', depending
21563 on context. See the individual commands for more information."
21564 (interactive)
21565 (org-check-before-invisible-edit 'insert)
21566 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21567 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21568 #'org-insert-heading))))
21570 ;;; Menu entries
21572 (defsubst org-in-subtree-not-table-p ()
21573 "Are we in a subtree and not in a table?"
21574 (and (not (org-before-first-heading-p))
21575 (not (org-at-table-p))))
21577 ;; Define the Org-mode menus
21578 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21579 '("Tbl"
21580 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21581 ["Next Field" org-cycle (org-at-table-p)]
21582 ["Previous Field" org-shifttab (org-at-table-p)]
21583 ["Next Row" org-return (org-at-table-p)]
21584 "--"
21585 ["Blank Field" org-table-blank-field (org-at-table-p)]
21586 ["Edit Field" org-table-edit-field (org-at-table-p)]
21587 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21588 "--"
21589 ("Column"
21590 ["Move Column Left" org-metaleft (org-at-table-p)]
21591 ["Move Column Right" org-metaright (org-at-table-p)]
21592 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21593 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21594 ("Row"
21595 ["Move Row Up" org-metaup (org-at-table-p)]
21596 ["Move Row Down" org-metadown (org-at-table-p)]
21597 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21598 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21599 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21600 "--"
21601 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21602 ("Rectangle"
21603 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21604 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21605 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21606 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21607 "--"
21608 ("Calculate"
21609 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21610 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21611 ["Edit Formulas" org-edit-special (org-at-table-p)]
21612 "--"
21613 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21614 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21615 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21616 "--"
21617 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21618 "--"
21619 ["Sum Column/Rectangle" org-table-sum
21620 (or (org-at-table-p) (org-region-active-p))]
21621 ["Which Column?" org-table-current-column (org-at-table-p)])
21622 ["Debug Formulas"
21623 org-table-toggle-formula-debugger
21624 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21625 ["Show Col/Row Numbers"
21626 org-table-toggle-coordinate-overlays
21627 :style toggle
21628 :selected (bound-and-true-p org-table-overlay-coordinates)]
21629 "--"
21630 ["Create" org-table-create (and (not (org-at-table-p))
21631 org-enable-table-editor)]
21632 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21633 ["Import from File" org-table-import (not (org-at-table-p))]
21634 ["Export to File" org-table-export (org-at-table-p)]
21635 "--"
21636 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21637 "--"
21638 ("Plot"
21639 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21640 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21642 (easy-menu-define org-org-menu org-mode-map "Org menu"
21643 '("Org"
21644 ("Show/Hide"
21645 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21646 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21647 ["Sparse Tree..." org-sparse-tree t]
21648 ["Reveal Context" org-reveal t]
21649 ["Show All" outline-show-all t]
21650 "--"
21651 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21652 "--"
21653 ["New Heading" org-insert-heading t]
21654 ("Navigate Headings"
21655 ["Up" outline-up-heading t]
21656 ["Next" outline-next-visible-heading t]
21657 ["Previous" outline-previous-visible-heading t]
21658 ["Next Same Level" outline-forward-same-level t]
21659 ["Previous Same Level" outline-backward-same-level t]
21660 "--"
21661 ["Jump" org-goto t])
21662 ("Edit Structure"
21663 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21664 "--"
21665 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21666 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21667 "--"
21668 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21669 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21670 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21671 "--"
21672 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21673 "--"
21674 ["Copy visible text" org-copy-visible t]
21675 "--"
21676 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21677 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21678 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21679 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21680 "--"
21681 ["Sort Region/Children" org-sort t]
21682 "--"
21683 ["Convert to odd levels" org-convert-to-odd-levels t]
21684 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21685 ("Editing"
21686 ["Emphasis..." org-emphasize t]
21687 ["Edit Source Example" org-edit-special t]
21688 "--"
21689 ["Footnote new/jump" org-footnote-action t]
21690 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21691 ("Archive"
21692 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21693 "--"
21694 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21695 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21696 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21698 "--"
21699 ("Hyperlinks"
21700 ["Store Link (Global)" org-store-link t]
21701 ["Find existing link to here" org-occur-link-in-agenda-files t]
21702 ["Insert Link" org-insert-link t]
21703 ["Follow Link" org-open-at-point t]
21704 "--"
21705 ["Next link" org-next-link t]
21706 ["Previous link" org-previous-link t]
21707 "--"
21708 ["Descriptive Links"
21709 org-toggle-link-display
21710 :style radio
21711 :selected org-descriptive-links
21713 ["Literal Links"
21714 org-toggle-link-display
21715 :style radio
21716 :selected (not org-descriptive-links)])
21717 "--"
21718 ("TODO Lists"
21719 ["TODO/DONE/-" org-todo t]
21720 ("Select keyword"
21721 ["Next keyword" org-shiftright (org-at-heading-p)]
21722 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21723 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21724 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21725 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21726 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21727 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21728 "--"
21729 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21730 :selected org-enforce-todo-dependencies :style toggle :active t]
21731 "Settings for tree at point"
21732 ["Do Children sequentially" org-toggle-ordered-property :style radio
21733 :selected (org-entry-get nil "ORDERED")
21734 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21735 ["Do Children parallel" org-toggle-ordered-property :style radio
21736 :selected (not (org-entry-get nil "ORDERED"))
21737 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21738 "--"
21739 ["Set Priority" org-priority t]
21740 ["Priority Up" org-shiftup t]
21741 ["Priority Down" org-shiftdown t]
21742 "--"
21743 ["Get news from all feeds" org-feed-update-all t]
21744 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21745 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21746 ("TAGS and Properties"
21747 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21748 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21749 "--"
21750 ["Set property" org-set-property (not (org-before-first-heading-p))]
21751 ["Column view of properties" org-columns t]
21752 ["Insert Column View DBlock" org-columns-insert-dblock t])
21753 ("Dates and Scheduling"
21754 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21755 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21756 ("Change Date"
21757 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21758 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21759 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21760 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21761 ["Compute Time Range" org-evaluate-time-range t]
21762 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21763 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21764 "--"
21765 ["Custom time format" org-toggle-time-stamp-overlays
21766 :style radio :selected org-display-custom-times]
21767 "--"
21768 ["Goto Calendar" org-goto-calendar t]
21769 ["Date from Calendar" org-date-from-calendar t]
21770 "--"
21771 ["Start/Restart Timer" org-timer-start t]
21772 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21773 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21774 ["Insert Timer String" org-timer t]
21775 ["Insert Timer Item" org-timer-item t])
21776 ("Logging work"
21777 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21778 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21779 ["Clock out" org-clock-out t]
21780 ["Clock cancel" org-clock-cancel t]
21781 "--"
21782 ["Mark as default task" org-clock-mark-default-task t]
21783 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21784 ["Goto running clock" org-clock-goto t]
21785 "--"
21786 ["Display times" org-clock-display t]
21787 ["Create clock table" org-clock-report t]
21788 "--"
21789 ["Record DONE time"
21790 (progn (setq org-log-done (not org-log-done))
21791 (message "Switching to %s will %s record a timestamp"
21792 (car org-done-keywords)
21793 (if org-log-done "automatically" "not")))
21794 :style toggle :selected org-log-done])
21795 "--"
21796 ["Agenda Command..." org-agenda t]
21797 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21798 ("File List for Agenda")
21799 ("Special views current file"
21800 ["TODO Tree" org-show-todo-tree t]
21801 ["Check Deadlines" org-check-deadlines t]
21802 ["Timeline" org-timeline t]
21803 ["Tags/Property tree" org-match-sparse-tree t])
21804 "--"
21805 ["Export/Publish..." org-export-dispatch t]
21806 ("LaTeX"
21807 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21808 :selected org-cdlatex-mode]
21809 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21810 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21811 ["Modify math symbol" org-cdlatex-math-modify
21812 (org-inside-LaTeX-fragment-p)]
21813 ["Insert citation" org-reftex-citation t])
21814 "--"
21815 ("MobileOrg"
21816 ["Push Files and Views" org-mobile-push t]
21817 ["Get Captured and Flagged" org-mobile-pull t]
21818 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21819 "--"
21820 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21821 "--"
21822 ("Documentation"
21823 ["Show Version" org-version t]
21824 ["Info Documentation" org-info t])
21825 ("Customize"
21826 ["Browse Org Group" org-customize t]
21827 "--"
21828 ["Expand This Menu" org-create-customize-menu
21829 (fboundp 'customize-menu-create)])
21830 ["Send bug report" org-submit-bug-report t]
21831 "--"
21832 ("Refresh/Reload"
21833 ["Refresh setup current buffer" org-mode-restart t]
21834 ["Reload Org (after update)" org-reload t]
21835 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21838 (defun org-info (&optional node)
21839 "Read documentation for Org-mode in the info system.
21840 With optional NODE, go directly to that node."
21841 (interactive)
21842 (info (format "(org)%s" (or node ""))))
21844 ;;;###autoload
21845 (defun org-submit-bug-report ()
21846 "Submit a bug report on Org-mode via mail.
21848 Don't hesitate to report any problems or inaccurate documentation.
21850 If you don't have setup sending mail from (X)Emacs, please copy the
21851 output buffer into your mail program, as it gives us important
21852 information about your Org-mode version and configuration."
21853 (interactive)
21854 (require 'reporter)
21855 (defvar reporter-prompt-for-summary-p)
21856 (org-load-modules-maybe)
21857 (org-require-autoloaded-modules)
21858 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21859 (reporter-submit-bug-report
21860 "emacs-orgmode@gnu.org"
21861 (org-version nil 'full)
21862 (let (list)
21863 (save-window-excursion
21864 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21865 (delete-other-windows)
21866 (erase-buffer)
21867 (insert "You are about to submit a bug report to the Org-mode mailing list.
21869 We would like to add your full Org-mode and Outline configuration to the
21870 bug report. This greatly simplifies the work of the maintainer and
21871 other experts on the mailing list.
21873 HOWEVER, some variables you have customized may contain private
21874 information. The names of customers, colleagues, or friends, might
21875 appear in the form of file names, tags, todo states, or search strings.
21876 If you answer yes to the prompt, you might want to check and remove
21877 such private information before sending the email.")
21878 (add-text-properties (point-min) (point-max) '(face org-warning))
21879 (when (yes-or-no-p "Include your Org-mode configuration ")
21880 (mapatoms
21881 (lambda (v)
21882 (and (boundp v)
21883 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21884 (or (and (symbol-value v)
21885 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21886 (and
21887 (get v 'custom-type) (get v 'standard-value)
21888 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21889 (push v list)))))
21890 (kill-buffer (get-buffer "*Warn about privacy*"))
21891 list))
21892 nil nil
21893 "Remember to cover the basics, that is, what you expected to happen and
21894 what in fact did happen. You don't know how to make a good report? See
21896 http://orgmode.org/manual/Feedback.html#Feedback
21898 Your bug report will be posted to the Org-mode mailing list.
21899 ------------------------------------------------------------------------")
21900 (save-excursion
21901 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21902 (replace-match "\\1Bug: \\3 [\\2]")))))
21905 (defun org-install-agenda-files-menu ()
21906 (let ((bl (buffer-list)))
21907 (save-excursion
21908 (while bl
21909 (set-buffer (pop bl))
21910 (when (derived-mode-p 'org-mode) (setq bl nil)))
21911 (when (derived-mode-p 'org-mode)
21912 (easy-menu-change
21913 '("Org") "File List for Agenda"
21914 (append
21915 (list
21916 ["Edit File List" (org-edit-agenda-file-list) t]
21917 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21918 ["Remove Current File from List" org-remove-file t]
21919 ["Cycle through agenda files" org-cycle-agenda-files t]
21920 ["Occur in all agenda files" org-occur-in-agenda-files t]
21921 "--")
21922 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21924 ;;;; Documentation
21926 (defun org-require-autoloaded-modules ()
21927 (interactive)
21928 (mapc #'require
21929 '(org-agenda org-archive org-attach org-clock org-colview org-id
21930 org-table org-timer)))
21932 ;;;###autoload
21933 (defun org-reload (&optional uncompiled)
21934 "Reload all org lisp files.
21935 With prefix arg UNCOMPILED, load the uncompiled versions."
21936 (interactive "P")
21937 (require 'loadhist)
21938 (let* ((org-dir (org-find-library-dir "org"))
21939 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21940 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21941 (remove-re (format "\\`%s\\'"
21942 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21943 (feats (delete-dups
21944 (mapcar 'file-name-sans-extension
21945 (mapcar 'file-name-nondirectory
21946 (delq nil
21947 (mapcar 'feature-file
21948 features))))))
21949 (lfeat (append
21950 (sort
21951 (setq feats
21952 (delq nil (mapcar
21953 (lambda (f)
21954 (if (and (string-match feature-re f)
21955 (not (string-match remove-re f)))
21956 f nil))
21957 feats)))
21958 'string-lessp)
21959 (list "org-version" "org")))
21960 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21961 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21962 load-uncore load-misses)
21963 (setq load-misses
21964 (delq 't
21965 (mapcar (lambda (f)
21966 (or (org-load-noerror-mustsuffix (concat org-dir f))
21967 (and (string= org-dir contrib-dir)
21968 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21969 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21970 (add-to-list 'load-uncore f 'append)
21973 lfeat)))
21974 (when load-uncore
21975 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21976 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21977 (if load-misses
21978 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21979 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21980 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21982 ;;;###autoload
21983 (defun org-customize ()
21984 "Call the customize function with org as argument."
21985 (interactive)
21986 (org-load-modules-maybe)
21987 (org-require-autoloaded-modules)
21988 (customize-browse 'org))
21990 (defun org-create-customize-menu ()
21991 "Create a full customization menu for Org-mode, insert it into the menu."
21992 (interactive)
21993 (org-load-modules-maybe)
21994 (org-require-autoloaded-modules)
21995 (if (fboundp 'customize-menu-create)
21996 (progn
21997 (easy-menu-change
21998 '("Org") "Customize"
21999 `(["Browse Org group" org-customize t]
22000 "--"
22001 ,(customize-menu-create 'org)
22002 ["Set" Custom-set t]
22003 ["Save" Custom-save t]
22004 ["Reset to Current" Custom-reset-current t]
22005 ["Reset to Saved" Custom-reset-saved t]
22006 ["Reset to Standard Settings" Custom-reset-standard t]))
22007 (message "\"Org\"-menu now contains full customization menu"))
22008 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22010 ;;;; Miscellaneous stuff
22012 ;;; Generally useful functions
22014 (defun org-get-at-eol (property n)
22015 "Get text property PROPERTY at the end of line less N characters."
22016 (get-text-property (- (point-at-eol) n) property))
22018 (defun org-find-text-property-in-string (prop s)
22019 "Return the first non-nil value of property PROP in string S."
22020 (or (get-text-property 0 prop s)
22021 (get-text-property (or (next-single-property-change 0 prop s) 0)
22022 prop s)))
22024 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22025 "Display the given MESSAGE as a warning."
22026 (if (fboundp 'display-warning)
22027 (display-warning 'org message :warning)
22028 (let ((buf (get-buffer-create "*Org warnings*")))
22029 (with-current-buffer buf
22030 (goto-char (point-max))
22031 (insert "Warning (Org): " message)
22032 (unless (bolp)
22033 (newline)))
22034 (display-buffer buf)
22035 (sit-for 0))))
22037 (defun org-eval (form)
22038 "Eval FORM and return result."
22039 (condition-case error
22040 (eval form)
22041 (error (format "%%![Error: %s]" error))))
22043 (defun org-in-clocktable-p ()
22044 "Check if the cursor is in a clocktable."
22045 (let ((pos (point)) start)
22046 (save-excursion
22047 (end-of-line 1)
22048 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22049 (setq start (match-beginning 0))
22050 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22051 (>= (match-end 0) pos)
22052 start))))
22054 (defun org-in-verbatim-emphasis ()
22055 (save-match-data
22056 (and (org-in-regexp org-emph-re 2)
22057 (>= (point) (match-beginning 3))
22058 (<= (point) (match-end 4))
22059 (member (match-string 3) '("=" "~")))))
22061 (defun org-overlay-display (ovl text &optional face evap)
22062 "Make overlay OVL display TEXT with face FACE."
22063 (overlay-put ovl 'display text)
22064 (if face (overlay-put ovl 'face face))
22065 (if evap (overlay-put ovl 'evaporate t)))
22067 (defun org-overlay-before-string (ovl text &optional face evap)
22068 "Make overlay OVL display TEXT with face FACE."
22069 (if face (org-add-props text nil 'face face))
22070 (overlay-put ovl 'before-string text)
22071 (if evap (overlay-put ovl 'evaporate t)))
22073 (defun org-find-overlays (prop &optional pos delete)
22074 "Find all overlays specifying PROP at POS or point.
22075 If DELETE is non-nil, delete all those overlays."
22076 (let (found)
22077 (dolist (ov (overlays-at (or pos (point))) found)
22078 (cond ((not (overlay-get ov prop)))
22079 (delete (delete-overlay ov))
22080 (t (push ov found))))))
22082 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22083 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22084 (if (and marker (marker-buffer marker)
22085 (buffer-live-p (marker-buffer marker)))
22086 (progn
22087 (pop-to-buffer-same-window (marker-buffer marker))
22088 (when (or (> marker (point-max)) (< marker (point-min)))
22089 (widen))
22090 (goto-char marker)
22091 (org-show-context 'org-goto))
22092 (if bookmark
22093 (bookmark-jump bookmark)
22094 (error "Cannot find location"))))
22096 (defun org-quote-csv-field (s)
22097 "Quote field for inclusion in CSV material."
22098 (if (string-match "[\",]" s)
22099 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22102 (defun org-force-self-insert (N)
22103 "Needed to enforce self-insert under remapping."
22104 (interactive "p")
22105 (self-insert-command N))
22107 (defun org-string-width (s)
22108 "Compute width of string, ignoring invisible characters.
22109 This ignores character with invisibility property `org-link', and also
22110 characters with property `org-cwidth', because these will become invisible
22111 upon the next fontification round."
22112 (let (b l)
22113 (when (or (eq t buffer-invisibility-spec)
22114 (assq 'org-link buffer-invisibility-spec))
22115 (while (setq b (text-property-any 0 (length s)
22116 'invisible 'org-link s))
22117 (setq s (concat (substring s 0 b)
22118 (substring s (or (next-single-property-change
22119 b 'invisible s)
22120 (length s)))))))
22121 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22122 (setq s (concat (substring s 0 b)
22123 (substring s (or (next-single-property-change
22124 b 'org-cwidth s)
22125 (length s))))))
22126 (setq l (string-width s) b -1)
22127 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22128 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22131 (defun org-shorten-string (s maxlength)
22132 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22133 If the string is shorter or has length MAXLENGTH, just return the
22134 original string. If it is longer, the functions finds a space in the
22135 string, breaks this string off at that locations and adds three dots
22136 as ellipsis. Including the ellipsis, the string will not be longer
22137 than MAXLENGTH. If finding a good breaking point in the string does
22138 not work, the string is just chopped off in the middle of a word
22139 if necessary."
22140 (if (<= (length s) maxlength)
22142 (let* ((n (max (- maxlength 4) 1))
22143 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22144 (if (string-match re s)
22145 (concat (match-string 1 s) "...")
22146 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22148 (defun org-get-indentation (&optional line)
22149 "Get the indentation of the current line, interpreting tabs.
22150 When LINE is given, assume it represents a line and compute its indentation."
22151 (if line
22152 (when (string-match "^ *" (org-remove-tabs line))
22153 (match-end 0))
22154 (save-excursion
22155 (beginning-of-line 1)
22156 (skip-chars-forward " \t")
22157 (current-column))))
22159 (defun org-get-string-indentation (s)
22160 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22161 (let ((n -1) (i 0) (w tab-width) c)
22162 (catch 'exit
22163 (while (< (setq n (1+ n)) (length s))
22164 (setq c (aref s n))
22165 (cond ((= c ?\ ) (setq i (1+ i)))
22166 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22167 (t (throw 'exit t)))))
22170 (defun org-remove-tabs (s &optional width)
22171 "Replace tabulators in S with spaces.
22172 Assumes that s is a single line, starting in column 0."
22173 (setq width (or width tab-width))
22174 (while (string-match "\t" s)
22175 (setq s (replace-match
22176 (make-string
22177 (- (* width (/ (+ (match-beginning 0) width) width))
22178 (match-beginning 0)) ?\ )
22179 t t s)))
22182 (defun org-fix-indentation (line ind)
22183 "Fix indentation in LINE.
22184 IND is a cons cell with target and minimum indentation.
22185 If the current indentation in LINE is smaller than the minimum,
22186 leave it alone. If it is larger than ind, set it to the target."
22187 (let* ((l (org-remove-tabs line))
22188 (i (org-get-indentation l))
22189 (i1 (car ind)) (i2 (cdr ind)))
22190 (when (>= i i2) (setq l (substring line i2)))
22191 (if (> i1 0)
22192 (concat (make-string i1 ?\ ) l)
22193 l)))
22195 (defun org-remove-indentation (code &optional n)
22196 "Remove maximum common indentation in string CODE and return it.
22197 N may optionally be the number of columns to remove. Return CODE
22198 as-is if removal failed."
22199 (with-temp-buffer
22200 (insert code)
22201 (if (org-do-remove-indentation n) (buffer-string) code)))
22203 (defun org-do-remove-indentation (&optional n)
22204 "Remove the maximum common indentation from the buffer.
22205 When optional argument N is a positive integer, remove exactly
22206 that much characters from indentation, if possible. Return nil
22207 if it fails."
22208 (catch :exit
22209 (goto-char (point-min))
22210 ;; Find maximum common indentation, if not specified.
22211 (let ((n (or n
22212 (let ((min-ind (point-max)))
22213 (save-excursion
22214 (while (re-search-forward "^[ \t]*\\S-" nil t)
22215 (let ((ind (1- (current-column))))
22216 (if (zerop ind) (throw :exit nil)
22217 (setq min-ind (min min-ind ind))))))
22218 min-ind))))
22219 (if (zerop n) (throw :exit nil)
22220 ;; Remove exactly N indentation, but give up if not possible.
22221 (while (not (eobp))
22222 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22223 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22224 ((< ind n) (throw :exit nil))
22225 (t (indent-line-to (- ind n))))
22226 (forward-line)))
22227 ;; Signal success.
22228 t))))
22230 (defun org-fill-template (template alist)
22231 "Find each %key of ALIST in TEMPLATE and replace it."
22232 (let ((case-fold-search nil))
22233 (dolist (entry (sort (copy-sequence alist)
22234 (lambda (a b) (< (length (car a)) (length (car b))))))
22235 (setq template
22236 (replace-regexp-in-string
22237 (concat "%" (regexp-quote (car entry)))
22238 (or (cdr entry) "") template t t)))
22239 template))
22241 (defun org-base-buffer (buffer)
22242 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22243 (if (not buffer)
22244 buffer
22245 (or (buffer-base-buffer buffer)
22246 buffer)))
22248 (defun org-wrap (string &optional width lines)
22249 "Wrap string to either a number of lines, or a width in characters.
22250 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22251 that costs. If there is a word longer than WIDTH, the text is actually
22252 wrapped to the length of that word.
22253 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22254 many lines, whatever width that takes.
22255 The return value is a list of lines, without newlines at the end."
22256 (let* ((words (org-split-string string "[ \t\n]+"))
22257 (maxword (apply 'max (mapcar 'org-string-width words)))
22258 w ll)
22259 (cond (width
22260 (org-do-wrap words (max maxword width)))
22261 (lines
22262 (setq w maxword)
22263 (setq ll (org-do-wrap words maxword))
22264 (if (<= (length ll) lines)
22266 (setq ll words)
22267 (while (> (length ll) lines)
22268 (setq w (1+ w))
22269 (setq ll (org-do-wrap words w)))
22270 ll))
22271 (t (error "Cannot wrap this")))))
22273 (defun org-do-wrap (words width)
22274 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22275 (let (lines line)
22276 (while words
22277 (setq line (pop words))
22278 (while (and words (< (+ (length line) (length (car words))) width))
22279 (setq line (concat line " " (pop words))))
22280 (setq lines (push line lines)))
22281 (nreverse lines)))
22283 (defun org-split-string (string &optional separators)
22284 "Splits STRING into substrings at SEPARATORS.
22285 SEPARATORS is a regular expression.
22286 No empty strings are returned if there are matches at the beginning
22287 and end of string."
22288 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22289 (let ((start 0) notfirst list)
22290 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22291 (if (and notfirst
22292 (= start (match-beginning 0))
22293 (< start (length string)))
22294 (1+ start) start))
22295 (< (match-beginning 0) (length string)))
22296 (setq notfirst t)
22297 (or (eq (match-beginning 0) 0)
22298 (and (eq (match-beginning 0) (match-end 0))
22299 (eq (match-beginning 0) start))
22300 (push (substring string start (match-beginning 0)) list))
22301 (setq start (match-end 0)))
22302 (or (eq start (length string))
22303 (push (substring string start) list))
22304 (nreverse list)))
22306 (defun org-quote-vert (s)
22307 "Replace \"|\" with \"\\vert\"."
22308 (while (string-match "|" s)
22309 (setq s (replace-match "\\vert" t t s)))
22312 (defun org-uuidgen-p (s)
22313 "Is S an ID created by UUIDGEN?"
22314 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22316 (defun org-in-src-block-p (&optional inside)
22317 "Whether point is in a code source block.
22318 When INSIDE is non-nil, don't consider we are within a src block
22319 when point is at #+BEGIN_SRC or #+END_SRC."
22320 (let ((case-fold-search t))
22321 (or (and (eq (get-char-property (point) 'src-block) t))
22322 (and (not inside)
22323 (save-match-data
22324 (save-excursion
22325 (beginning-of-line)
22326 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22328 (defun org-context ()
22329 "Return a list of contexts of the current cursor position.
22330 If several contexts apply, all are returned.
22331 Each context entry is a list with a symbol naming the context, and
22332 two positions indicating start and end of the context. Possible
22333 contexts are:
22335 :headline anywhere in a headline
22336 :headline-stars on the leading stars in a headline
22337 :todo-keyword on a TODO keyword (including DONE) in a headline
22338 :tags on the TAGS in a headline
22339 :priority on the priority cookie in a headline
22340 :item on the first line of a plain list item
22341 :item-bullet on the bullet/number of a plain list item
22342 :checkbox on the checkbox in a plain list item
22343 :table in an org-mode table
22344 :table-special on a special filed in a table
22345 :table-table in a table.el table
22346 :clocktable in a clocktable
22347 :src-block in a source block
22348 :link on a hyperlink
22349 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22350 :target on a <<target>>
22351 :radio-target on a <<<radio-target>>>
22352 :latex-fragment on a LaTeX fragment
22353 :latex-preview on a LaTeX fragment with overlaid preview image
22355 This function expects the position to be visible because it uses font-lock
22356 faces as a help to recognize the following contexts: :table-special, :link,
22357 and :keyword."
22358 (let* ((f (get-text-property (point) 'face))
22359 (faces (if (listp f) f (list f)))
22360 (case-fold-search t)
22361 (p (point)) clist o)
22362 ;; First the large context
22363 (cond
22364 ((org-at-heading-p t)
22365 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22366 (when (progn
22367 (beginning-of-line 1)
22368 (looking-at org-todo-line-tags-regexp))
22369 (push (org-point-in-group p 1 :headline-stars) clist)
22370 (push (org-point-in-group p 2 :todo-keyword) clist)
22371 (push (org-point-in-group p 4 :tags) clist))
22372 (goto-char p)
22373 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22374 (when (looking-at "\\[#[A-Z0-9]\\]")
22375 (push (org-point-in-group p 0 :priority) clist)))
22377 ((org-at-item-p)
22378 (push (org-point-in-group p 2 :item-bullet) clist)
22379 (push (list :item (point-at-bol)
22380 (save-excursion (org-end-of-item) (point)))
22381 clist)
22382 (and (org-at-item-checkbox-p)
22383 (push (org-point-in-group p 0 :checkbox) clist)))
22385 ((org-at-table-p)
22386 (push (list :table (org-table-begin) (org-table-end)) clist)
22387 (when (memq 'org-formula faces)
22388 (push (list :table-special
22389 (previous-single-property-change p 'face)
22390 (next-single-property-change p 'face)) clist)))
22391 ((org-at-table-p 'any)
22392 (push (list :table-table) clist)))
22393 (goto-char p)
22395 (let ((case-fold-search t))
22396 ;; New the "medium" contexts: clocktables, source blocks
22397 (cond ((org-in-clocktable-p)
22398 (push (list :clocktable
22399 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22400 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22401 (match-beginning 1))
22402 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22403 (match-end 0))) clist))
22404 ((org-in-src-block-p)
22405 (push (list :src-block
22406 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22407 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22408 (match-beginning 1))
22409 (and (search-forward "#+END_SRC" nil t)
22410 (match-beginning 0))) clist))))
22411 (goto-char p)
22413 ;; Now the small context
22414 (cond
22415 ((org-at-timestamp-p)
22416 (push (org-point-in-group p 0 :timestamp) clist))
22417 ((memq 'org-link faces)
22418 (push (list :link
22419 (previous-single-property-change p 'face)
22420 (next-single-property-change p 'face)) clist))
22421 ((memq 'org-special-keyword faces)
22422 (push (list :keyword
22423 (previous-single-property-change p 'face)
22424 (next-single-property-change p 'face)) clist))
22425 ((org-at-target-p)
22426 (push (org-point-in-group p 0 :target) clist)
22427 (goto-char (1- (match-beginning 0)))
22428 (when (looking-at org-radio-target-regexp)
22429 (push (org-point-in-group p 0 :radio-target) clist))
22430 (goto-char p))
22431 ((setq o (cl-some
22432 (lambda (o)
22433 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22435 (overlays-at (point))))
22436 (push (list :latex-fragment
22437 (overlay-start o) (overlay-end o)) clist)
22438 (push (list :latex-preview
22439 (overlay-start o) (overlay-end o)) clist))
22440 ((org-inside-LaTeX-fragment-p)
22441 ;; FIXME: positions wrong.
22442 (push (list :latex-fragment (point) (point)) clist)))
22444 (setq clist (nreverse (delq nil clist)))
22445 clist))
22447 (defun org-in-regexp (regexp &optional nlines visually)
22448 "Check if point is inside a match of REGEXP.
22450 Normally only the current line is checked, but you can include
22451 NLINES extra lines around point into the search. If VISUALLY is
22452 set, require that the cursor is not after the match but really
22453 on, so that the block visually is on the match.
22455 Return nil or a cons cell (BEG . END) where BEG and END are,
22456 respectively, the positions at the beginning and the end of the
22457 match."
22458 (catch :exit
22459 (let ((pos (point))
22460 (eol (line-end-position (if nlines (1+ nlines) 1))))
22461 (save-excursion
22462 (beginning-of-line (- 1 (or nlines 0)))
22463 (while (and (re-search-forward regexp eol t)
22464 (<= (match-beginning 0) pos))
22465 (let ((end (match-end 0)))
22466 (when (or (> end pos) (and (= end pos) (not visually)))
22467 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22469 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22470 "Non-nil when point is between matches of START-RE and END-RE.
22472 Also return a non-nil value when point is on one of the matches.
22474 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22475 buffer positions. Default values are the positions of headlines
22476 surrounding the point.
22478 The functions returns a cons cell whose car (resp. cdr) is the
22479 position before START-RE (resp. after END-RE)."
22480 (save-match-data
22481 (let ((pos (point))
22482 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22483 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22484 beg end)
22485 (save-excursion
22486 ;; Point is on a block when on START-RE or if START-RE can be
22487 ;; found before it...
22488 (and (or (org-in-regexp start-re)
22489 (re-search-backward start-re limit-up t))
22490 (setq beg (match-beginning 0))
22491 ;; ... and END-RE after it...
22492 (goto-char (match-end 0))
22493 (re-search-forward end-re limit-down t)
22494 (> (setq end (match-end 0)) pos)
22495 ;; ... without another START-RE in-between.
22496 (goto-char (match-beginning 0))
22497 (not (re-search-backward start-re (1+ beg) t))
22498 ;; Return value.
22499 (cons beg end))))))
22501 (defun org-in-block-p (names)
22502 "Non-nil when point belongs to a block whose name belongs to NAMES.
22504 NAMES is a list of strings containing names of blocks.
22506 Return first block name matched, or nil. Beware that in case of
22507 nested blocks, the returned name may not belong to the closest
22508 block from point."
22509 (save-match-data
22510 (catch 'exit
22511 (let ((case-fold-search t)
22512 (lim-up (save-excursion (outline-previous-heading)))
22513 (lim-down (save-excursion (outline-next-heading))))
22514 (dolist (name names)
22515 (let ((n (regexp-quote name)))
22516 (when (org-between-regexps-p
22517 (concat "^[ \t]*#\\+begin_" n)
22518 (concat "^[ \t]*#\\+end_" n)
22519 lim-up lim-down)
22520 (throw 'exit n)))))
22521 nil)))
22523 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22524 "Call `multi-occur' with buffers for all agenda files."
22525 (interactive "sOrg-files matching: ")
22526 (let* ((files (org-agenda-files))
22527 (tnames (mapcar #'file-truename files))
22528 (extra org-agenda-text-search-extra-files))
22529 (when (eq (car extra) 'agenda-archives)
22530 (setq extra (cdr extra))
22531 (setq files (org-add-archive-files files)))
22532 (dolist (f extra)
22533 (unless (member (file-truename f) tnames)
22534 (unless (member f files) (setq files (append files (list f))))
22535 (setq tnames (append tnames (list (file-truename f))))))
22536 (multi-occur
22537 (mapcar (lambda (x)
22538 (with-current-buffer
22539 ;; FIXME: Why not just (find-file-noselect x)?
22540 ;; Is it to avoid the "revert buffer" prompt?
22541 (or (get-file-buffer x) (find-file-noselect x))
22542 (widen)
22543 (current-buffer)))
22544 files)
22545 regexp)))
22547 (add-hook 'occur-mode-find-occurrence-hook
22548 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22550 (defun org-occur-link-in-agenda-files ()
22551 "Create a link and search for it in the agendas.
22552 The link is not stored in `org-stored-links', it is just created
22553 for the search purpose."
22554 (interactive)
22555 (let ((link (condition-case nil
22556 (org-store-link nil)
22557 (error "Unable to create a link to here"))))
22558 (org-occur-in-agenda-files (regexp-quote link))))
22560 (defun org-reverse-string (string)
22561 "Return the reverse of STRING."
22562 (apply 'string (reverse (string-to-list string))))
22564 ;; defsubst org-uniquify must be defined before first use
22566 (defun org-uniquify-alist (alist)
22567 "Merge elements of ALIST with the same key.
22569 For example, in this alist:
22571 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22572 => \\='((a 1 3) (b 2))
22574 merge (a 1) and (a 3) into (a 1 3).
22576 The function returns the new ALIST."
22577 (let (rtn)
22578 (dolist (e alist rtn)
22579 (let (n)
22580 (if (not (assoc (car e) rtn))
22581 (push e rtn)
22582 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22583 (setq rtn (assq-delete-all (car e) rtn))
22584 (push n rtn))))))
22586 (defun org-delete-all (elts list)
22587 "Remove all elements in ELTS from LIST.
22588 Comparison is done with `equal'. It is a destructive operation
22589 that may remove elements by altering the list structure."
22590 (while elts
22591 (setq list (delete (pop elts) list)))
22592 list)
22594 (defun org-back-over-empty-lines ()
22595 "Move backwards over whitespace, to the beginning of the first empty line.
22596 Returns the number of empty lines passed."
22597 (let ((pos (point)))
22598 (if (cdr (assoc 'heading org-blank-before-new-entry))
22599 (skip-chars-backward " \t\n\r")
22600 (unless (eobp)
22601 (forward-line -1)))
22602 (beginning-of-line 2)
22603 (goto-char (min (point) pos))
22604 (count-lines (point) pos)))
22606 (defun org-skip-whitespace ()
22607 (skip-chars-forward " \t\n\r"))
22609 (defun org-point-in-group (point group &optional context)
22610 "Check if POINT is in match-group GROUP.
22611 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22612 match. If the match group does not exist or point is not inside it,
22613 return nil."
22614 (and (match-beginning group)
22615 (>= point (match-beginning group))
22616 (<= point (match-end group))
22617 (if context
22618 (list context (match-beginning group) (match-end group))
22619 t)))
22621 (defun org-switch-to-buffer-other-window (&rest args)
22622 "Switch to buffer in a second window on the current frame.
22623 In particular, do not allow pop-up frames.
22624 Returns the newly created buffer."
22625 (org-no-popups
22626 (apply 'switch-to-buffer-other-window args)))
22628 (defun org-combine-plists (&rest plists)
22629 "Create a single property list from all plists in PLISTS.
22630 The process starts by copying the first list, and then setting properties
22631 from the other lists. Settings in the last list are the most significant
22632 ones and overrule settings in the other lists."
22633 (let ((rtn (copy-sequence (pop plists)))
22634 p v ls)
22635 (while plists
22636 (setq ls (pop plists))
22637 (while ls
22638 (setq p (pop ls) v (pop ls))
22639 (setq rtn (plist-put rtn p v))))
22640 rtn))
22642 (defun org-replace-escapes (string table)
22643 "Replace %-escapes in STRING with values in TABLE.
22644 TABLE is an association list with keys like \"%a\" and string values.
22645 The sequences in STRING may contain normal field width and padding information,
22646 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22647 so values can contain further %-escapes if they are define later in TABLE."
22648 (let ((tbl (copy-alist table))
22649 (case-fold-search nil)
22650 (pchg 0)
22651 re rpl)
22652 (dolist (e tbl)
22653 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22654 (when (and (cdr e) (string-match re (cdr e)))
22655 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22656 (safe "SREF"))
22657 (add-text-properties 0 3 (list 'sref sref) safe)
22658 (setcdr e (replace-match safe t t (cdr e)))))
22659 (while (string-match re string)
22660 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22661 (cdr e)))
22662 (setq string (replace-match rpl t t string))))
22663 (while (setq pchg (next-property-change pchg string))
22664 (let ((sref (get-text-property pchg 'sref string)))
22665 (when (and sref (string-match "SREF" string pchg))
22666 (setq string (replace-match sref t t string)))))
22667 string))
22669 (defun org-sublist (list start end)
22670 "Return a section of LIST, from START to END.
22672 Counting starts at 1."
22673 (cl-subseq list (1- start) end))
22674 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22676 (defun org-find-base-buffer-visiting (file)
22677 "Like `find-buffer-visiting' but always return the base buffer and
22678 not an indirect buffer."
22679 (let ((buf (or (get-file-buffer file)
22680 (find-buffer-visiting file))))
22681 (if buf
22682 (or (buffer-base-buffer buf) buf)
22683 nil)))
22685 ;;; TODO: Only called once, from ox-odt which should probably use
22686 ;;; org-export-inline-image-p or something.
22687 (defun org-file-image-p (file)
22688 "Return non-nil if FILE is an image."
22689 (save-match-data
22690 (string-match (image-file-name-regexp) file)))
22692 (defun org-get-cursor-date (&optional with-time)
22693 "Return the date at cursor in as a time.
22694 This works in the calendar and in the agenda, anywhere else it just
22695 returns the current time.
22696 If WITH-TIME is non-nil, returns the time of the event at point (in
22697 the agenda) or the current time of the day."
22698 (let (date day defd tp hod mod)
22699 (when with-time
22700 (setq tp (get-text-property (point) 'time))
22701 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22702 (setq hod (string-to-number (match-string 1 tp))
22703 mod (string-to-number (match-string 2 tp))))
22704 (or tp (let ((now (decode-time)))
22705 (setq hod (nth 2 now)
22706 mod (nth 1 now)))))
22707 (cond
22708 ((eq major-mode 'calendar-mode)
22709 (setq date (calendar-cursor-to-date)
22710 defd (encode-time 0 (or mod 0) (or hod 0)
22711 (nth 1 date) (nth 0 date) (nth 2 date))))
22712 ((eq major-mode 'org-agenda-mode)
22713 (setq day (get-text-property (point) 'day))
22714 (when day
22715 (setq date (calendar-gregorian-from-absolute day)
22716 defd (encode-time 0 (or mod 0) (or hod 0)
22717 (nth 1 date) (nth 0 date) (nth 2 date))))))
22718 (or defd (current-time))))
22720 (defun org-mark-subtree (&optional up)
22721 "Mark the current subtree.
22722 This puts point at the start of the current subtree, and mark at
22723 the end. If a numeric prefix UP is given, move up into the
22724 hierarchy of headlines by UP levels before marking the subtree."
22725 (interactive "P")
22726 (org-with-limited-levels
22727 (cond ((org-at-heading-p) (beginning-of-line))
22728 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22729 (t (outline-previous-visible-heading 1))))
22730 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22731 (if (called-interactively-p 'any)
22732 (call-interactively 'org-mark-element)
22733 (org-mark-element)))
22735 (defun org-file-newer-than-p (file time)
22736 "Non-nil if FILE is newer than TIME.
22737 FILE is a filename, as a string, TIME is a list of integers, as
22738 returned by, e.g., `current-time'."
22739 (and (file-exists-p file)
22740 ;; Only compare times up to whole seconds as some file-systems
22741 ;; (e.g. HFS+) do not retain any finer granularity. As
22742 ;; a consequence, make sure we return non-nil when the two
22743 ;; times are equal.
22744 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22745 (cl-subseq time 0 2)))))
22747 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22748 "Compile a SOURCE file using PROCESS.
22750 PROCESS is either a function or a list of shell commands, as
22751 strings. EXT is a file extension, without the leading dot, as
22752 a string. It is used to check if the process actually succeeded.
22754 PROCESS must create a file with the same base name and directory
22755 as SOURCE, but ending with EXT. The function then returns its
22756 filename. Otherwise, it raises an error. The error message can
22757 then be refined by providing string ERR-MSG, which is appended to
22758 the standard message.
22760 If PROCESS is a function, it is called with a single argument:
22761 the SOURCE file.
22763 If it is a list of commands, each of them is called using
22764 `shell-command'. By default, in each command, %b, %f, %F and %o
22765 are replaced with, respectively, SOURCE base name, name, full
22766 name and directory. It is possible, however, to use more
22767 place-holders by specifying them in optional argument SPEC, as an
22768 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22770 When PROCESS is a list of commands, optional argument LOG-BUF can
22771 be set to a buffer or a buffer name. `shell-command' then uses
22772 it for output.
22774 `default-directory' is set to SOURCE directory during the whole
22775 process."
22776 (let* ((source-name (file-name-nondirectory source))
22777 (base-name (file-name-sans-extension source-name))
22778 (full-name (file-truename source))
22779 (out-dir (file-name-directory source))
22780 (time (current-time))
22781 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22782 (save-window-excursion
22783 (let ((default-directory (file-name-directory full-name)))
22784 (pcase process
22785 ((pred functionp) (funcall process (shell-quote-argument source)))
22786 ((pred consp)
22787 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22788 (spec (append spec
22789 `((?b . ,(shell-quote-argument base-name))
22790 (?f . ,(shell-quote-argument source-name))
22791 (?F . ,(shell-quote-argument full-name))
22792 (?o . ,(shell-quote-argument out-dir))))))
22793 (dolist (command process)
22794 (shell-command (format-spec command spec) log-buf))))
22795 (_ (error "No valid command to process %S%s" source err-msg)))))
22796 ;; Check for process failure.
22797 (let ((output (concat out-dir base-name "." ext)))
22798 (unless (org-file-newer-than-p output time)
22799 (error (format "File %S wasn't produced%s" output err-msg)))
22800 output)))
22802 ;;; Indentation
22804 (defun org--get-expected-indentation (element contentsp)
22805 "Expected indentation column for current line, according to ELEMENT.
22806 ELEMENT is an element containing point. CONTENTSP is non-nil
22807 when indentation is to be computed according to contents of
22808 ELEMENT."
22809 (let ((type (org-element-type element))
22810 (start (org-element-property :begin element))
22811 (post-affiliated (org-element-property :post-affiliated element)))
22812 (org-with-wide-buffer
22813 (cond
22814 (contentsp
22815 (cl-case type
22816 ((diary-sexp footnote-definition) 0)
22817 ((headline inlinetask nil)
22818 (if (not org-adapt-indentation) 0
22819 (let ((level (org-current-level)))
22820 (if level (1+ level) 0))))
22821 ((item plain-list) (org-list-item-body-column post-affiliated))
22823 (goto-char start)
22824 (org-get-indentation))))
22825 ((memq type '(headline inlinetask nil))
22826 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22827 (org--get-expected-indentation element t)
22829 ((memq type '(diary-sexp footnote-definition)) 0)
22830 ;; First paragraph of a footnote definition or an item.
22831 ;; Indent like parent.
22832 ((< (line-beginning-position) start)
22833 (org--get-expected-indentation
22834 (org-element-property :parent element) t))
22835 ;; At first line: indent according to previous sibling, if any,
22836 ;; ignoring footnote definitions and inline tasks, or parent's
22837 ;; contents.
22838 ((= (line-beginning-position) start)
22839 (catch 'exit
22840 (while t
22841 (if (= (point-min) start) (throw 'exit 0)
22842 (goto-char (1- start))
22843 (let* ((previous (org-element-at-point))
22844 (parent previous))
22845 (while (and parent (<= (org-element-property :end parent) start))
22846 (setq previous parent
22847 parent (org-element-property :parent parent)))
22848 (cond
22849 ((not previous) (throw 'exit 0))
22850 ((> (org-element-property :end previous) start)
22851 (throw 'exit (org--get-expected-indentation previous t)))
22852 ((memq (org-element-type previous)
22853 '(footnote-definition inlinetask))
22854 (setq start (org-element-property :begin previous)))
22855 (t (goto-char (org-element-property :begin previous))
22856 (throw 'exit
22857 (if (bolp) (org-get-indentation)
22858 ;; At first paragraph in an item or
22859 ;; a footnote definition.
22860 (org--get-expected-indentation
22861 (org-element-property :parent previous) t))))))))))
22862 ;; Otherwise, move to the first non-blank line above.
22864 (beginning-of-line)
22865 (let ((pos (point)))
22866 (skip-chars-backward " \r\t\n")
22867 (cond
22868 ;; Two blank lines end a footnote definition or a plain
22869 ;; list. When we indent an empty line after them, the
22870 ;; containing list or footnote definition is over, so it
22871 ;; qualifies as a previous sibling. Therefore, we indent
22872 ;; like its first line.
22873 ((and (memq type '(footnote-definition plain-list))
22874 (> (count-lines (point) pos) 2))
22875 (goto-char start)
22876 (org-get-indentation))
22877 ;; Line above is the first one of a paragraph at the
22878 ;; beginning of an item or a footnote definition. Indent
22879 ;; like parent.
22880 ((< (line-beginning-position) start)
22881 (org--get-expected-indentation
22882 (org-element-property :parent element) t))
22883 ;; Line above is the beginning of an element, i.e., point
22884 ;; was originally on the blank lines between element's start
22885 ;; and contents.
22886 ((= (line-beginning-position) post-affiliated)
22887 (org--get-expected-indentation element t))
22888 ;; POS is after contents in a greater element. Indent like
22889 ;; the beginning of the element.
22891 ;; As a special case, if point is at the end of a footnote
22892 ;; definition or an item, indent like the very last element
22893 ;; within. If that last element is an item, indent like its
22894 ;; contents.
22895 ((and (not (eq type 'paragraph))
22896 (let ((cend (org-element-property :contents-end element)))
22897 (and cend (<= cend pos))))
22898 (if (memq type '(footnote-definition item plain-list))
22899 (let ((last (org-element-at-point)))
22900 (org--get-expected-indentation
22901 last (eq (org-element-type last) 'item)))
22902 (goto-char start)
22903 (org-get-indentation)))
22904 ;; In any other case, indent like the current line.
22905 (t (org-get-indentation)))))))))
22907 (defun org--align-node-property ()
22908 "Align node property at point.
22909 Alignment is done according to `org-property-format', which see."
22910 (when (save-excursion
22911 (beginning-of-line)
22912 (looking-at org-property-re))
22913 (replace-match
22914 (concat (match-string 4)
22915 (org-trim
22916 (format org-property-format (match-string 1) (match-string 3))))
22917 t t)))
22919 (defun org-indent-line ()
22920 "Indent line depending on context.
22922 Indentation is done according to the following rules:
22924 - Footnote definitions, diary sexps, headlines and inline tasks
22925 have to start at column 0.
22927 - On the very first line of an element, consider, in order, the
22928 next rules until one matches:
22930 1. If there's a sibling element before, ignoring footnote
22931 definitions and inline tasks, indent like its first line.
22933 2. If element has a parent, indent like its contents. More
22934 precisely, if parent is an item, indent after the
22935 description part, if any, or the bullet (see
22936 `org-list-description-max-indent'). Else, indent like
22937 parent's first line.
22939 3. Otherwise, indent relatively to current level, if
22940 `org-adapt-indentation' is non-nil, or to left margin.
22942 - On a blank line at the end of an element, indent according to
22943 the type of the element. More precisely
22945 1. If element is a plain list, an item, or a footnote
22946 definition, indent like the very last element within.
22948 2. If element is a paragraph, indent like its last non blank
22949 line.
22951 3. Otherwise, indent like its very first line.
22953 - In the code part of a source block, use language major mode
22954 to indent current line if `org-src-tab-acts-natively' is
22955 non-nil. If it is nil, do nothing.
22957 - Otherwise, indent like the first non-blank line above.
22959 The function doesn't indent an item as it could break the whole
22960 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22961 \\[org-shiftmetaright].
22963 Also align node properties according to `org-property-format'."
22964 (interactive)
22965 (cond
22966 (orgstruct-is-++
22967 (let ((indent-line-function
22968 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22969 (indent-according-to-mode)))
22970 ((org-at-heading-p) 'noindent)
22972 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22973 (type (org-element-type element)))
22974 (cond ((and (memq type '(plain-list item))
22975 (= (line-beginning-position)
22976 (org-element-property :post-affiliated element)))
22977 'noindent)
22978 ((and (eq type 'src-block)
22979 org-src-tab-acts-natively
22980 (> (line-beginning-position)
22981 (org-element-property :post-affiliated element))
22982 (< (line-beginning-position)
22983 (org-with-wide-buffer
22984 (goto-char (org-element-property :end element))
22985 (skip-chars-backward " \r\t\n")
22986 (line-beginning-position))))
22987 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22989 (let ((column (org--get-expected-indentation element nil)))
22990 ;; Preserve current column.
22991 (if (<= (current-column) (current-indentation))
22992 (indent-line-to column)
22993 (save-excursion (indent-line-to column))))
22994 ;; Align node property. Also preserve current column.
22995 (when (eq type 'node-property)
22996 (let ((column (current-column)))
22997 (org--align-node-property)
22998 (org-move-to-column column)))))))))
23000 (defun org-indent-region (start end)
23001 "Indent each non-blank line in the region.
23002 Called from a program, START and END specify the region to
23003 indent. The function will not indent contents of example blocks,
23004 verse blocks and export blocks as leading white spaces are
23005 assumed to be significant there."
23006 (interactive "r")
23007 (save-excursion
23008 (goto-char start)
23009 (skip-chars-forward " \r\t\n")
23010 (unless (eobp) (beginning-of-line))
23011 (let ((indent-to
23012 (lambda (ind pos)
23013 ;; Set IND as indentation for all lines between point and
23014 ;; POS. Blank lines are ignored. Leave point after POS
23015 ;; once done.
23016 (let ((limit (copy-marker pos)))
23017 (while (< (point) limit)
23018 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23019 (forward-line))
23020 (set-marker limit nil))))
23021 (end (copy-marker end)))
23022 (while (< (point) end)
23023 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23024 (let* ((element (org-element-at-point))
23025 (type (org-element-type element))
23026 (element-end (copy-marker (org-element-property :end element)))
23027 (ind (org--get-expected-indentation element nil)))
23028 (cond
23029 ((or (memq type '(paragraph table table-row))
23030 (not (or (org-element-property :contents-begin element)
23031 (memq type
23032 '(example-block export-block src-block)))))
23033 ;; Elements here are indented as a single block. Also
23034 ;; align node properties.
23035 (when (eq type 'node-property)
23036 (org--align-node-property)
23037 (beginning-of-line))
23038 (funcall indent-to ind (min element-end end)))
23040 ;; Elements in this category consist of three parts:
23041 ;; before the contents, the contents, and after the
23042 ;; contents. The contents are treated specially,
23043 ;; according to the element type, or not indented at
23044 ;; all. Other parts are indented as a single block.
23045 (let* ((post (copy-marker
23046 (org-element-property :post-affiliated element)))
23047 (cbeg
23048 (copy-marker
23049 (cond
23050 ((not (org-element-property :contents-begin element))
23051 ;; Fake contents for source blocks.
23052 (org-with-wide-buffer
23053 (goto-char post)
23054 (forward-line)
23055 (point)))
23056 ((memq type '(footnote-definition item plain-list))
23057 ;; Contents in these elements could start on
23058 ;; the same line as the beginning of the
23059 ;; element. Make sure we start indenting
23060 ;; from the second line.
23061 (org-with-wide-buffer
23062 (goto-char post)
23063 (end-of-line)
23064 (skip-chars-forward " \r\t\n")
23065 (if (eobp) (point) (line-beginning-position))))
23066 (t (org-element-property :contents-begin element)))))
23067 (cend (copy-marker
23068 (or (org-element-property :contents-end element)
23069 ;; Fake contents for source blocks.
23070 (org-with-wide-buffer
23071 (goto-char element-end)
23072 (skip-chars-backward " \r\t\n")
23073 (line-beginning-position)))
23074 t)))
23075 ;; Do not change items indentation individually as it
23076 ;; might break the list as a whole. On the other
23077 ;; hand, when at a plain list, indent it as a whole.
23078 (cond ((eq type 'plain-list)
23079 (let ((offset (- ind (org-get-indentation))))
23080 (unless (zerop offset)
23081 (indent-rigidly (org-element-property :begin element)
23082 (org-element-property :end element)
23083 offset))
23084 (goto-char cbeg)))
23085 ((eq type 'item) (goto-char cbeg))
23086 (t (funcall indent-to ind (min cbeg end))))
23087 (when (< (point) end)
23088 (cl-case type
23089 ((example-block export-block verse-block))
23090 (src-block
23091 ;; In a source block, indent source code
23092 ;; according to language major mode, but only if
23093 ;; `org-src-tab-acts-natively' is non-nil.
23094 (when (and (< (point) end) org-src-tab-acts-natively)
23095 (ignore-errors
23096 (org-babel-do-in-edit-buffer
23097 (indent-region (point-min) (point-max))))))
23098 (t (org-indent-region (point) (min cend end))))
23099 (goto-char (min cend end))
23100 (when (< (point) end)
23101 (funcall indent-to ind (min element-end end))))
23102 (set-marker post nil)
23103 (set-marker cbeg nil)
23104 (set-marker cend nil))))
23105 (set-marker element-end nil))))
23106 (set-marker end nil))))
23108 (defun org-indent-drawer ()
23109 "Indent the drawer at point."
23110 (interactive)
23111 (unless (save-excursion
23112 (beginning-of-line)
23113 (looking-at-p org-drawer-regexp))
23114 (user-error "Not at a drawer"))
23115 (let ((element (org-element-at-point)))
23116 (unless (memq (org-element-type element) '(drawer property-drawer))
23117 (user-error "Not at a drawer"))
23118 (org-with-wide-buffer
23119 (org-indent-region (org-element-property :begin element)
23120 (org-element-property :end element))))
23121 (message "Drawer at point indented"))
23123 (defun org-indent-block ()
23124 "Indent the block at point."
23125 (interactive)
23126 (unless (save-excursion
23127 (beginning-of-line)
23128 (let ((case-fold-search t))
23129 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23130 (user-error "Not at a block"))
23131 (let ((element (org-element-at-point)))
23132 (unless (memq (org-element-type element)
23133 '(comment-block center-block dynamic-block example-block
23134 export-block quote-block special-block
23135 src-block verse-block))
23136 (user-error "Not at a block"))
23137 (org-with-wide-buffer
23138 (org-indent-region (org-element-property :begin element)
23139 (org-element-property :end element))))
23140 (message "Block at point indented"))
23143 ;;; Filling
23145 ;; We use our own fill-paragraph and auto-fill functions.
23147 ;; `org-fill-paragraph' relies on adaptive filling and context
23148 ;; checking. Appropriate `fill-prefix' is computed with
23149 ;; `org-adaptive-fill-function'.
23151 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23152 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23153 ;; `org-adaptive-fill-function' value. Internally,
23154 ;; `org-comment-line-break-function' breaks the line.
23156 ;; `org-setup-filling' installs filling and auto-filling related
23157 ;; variables during `org-mode' initialization.
23159 (defvar org-element-paragraph-separate) ; org-element.el
23160 (defun org-setup-filling ()
23161 (require 'org-element)
23162 ;; Prevent auto-fill from inserting unwanted new items.
23163 (when (boundp 'fill-nobreak-predicate)
23164 (setq-local
23165 fill-nobreak-predicate
23166 (org-uniquify
23167 (append fill-nobreak-predicate
23168 '(org-fill-line-break-nobreak-p
23169 org-fill-paragraph-with-timestamp-nobreak-p)))))
23170 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23171 (setq-local paragraph-start paragraph-ending)
23172 (setq-local paragraph-separate paragraph-ending))
23173 (setq-local fill-paragraph-function 'org-fill-paragraph)
23174 (setq-local auto-fill-inhibit-regexp nil)
23175 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23176 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23177 (setq-local comment-line-break-function 'org-comment-line-break-function))
23179 (defun org-fill-line-break-nobreak-p ()
23180 "Non-nil when a new line at point would create an Org line break."
23181 (save-excursion
23182 (skip-chars-backward "[ \t]")
23183 (skip-chars-backward "\\\\")
23184 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23186 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23187 "Non-nil when a new line at point would split a timestamp."
23188 (and (org-at-timestamp-p t)
23189 (not (looking-at org-ts-regexp-both))))
23191 (declare-function message-in-body-p "message" ())
23192 (defvar orgtbl-line-start-regexp) ; From org-table.el
23193 (defun org-adaptive-fill-function ()
23194 "Compute a fill prefix for the current line.
23195 Return fill prefix, as a string, or nil if current line isn't
23196 meant to be filled. For convenience, if `adaptive-fill-regexp'
23197 matches in paragraphs or comments, use it."
23198 (catch 'exit
23199 (when (derived-mode-p 'message-mode)
23200 (save-excursion
23201 (beginning-of-line)
23202 (cond ((not (message-in-body-p)) (throw 'exit nil))
23203 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23204 ((looking-at message-cite-prefix-regexp)
23205 (throw 'exit (match-string-no-properties 0)))
23206 ((looking-at org-outline-regexp)
23207 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23208 (org-with-wide-buffer
23209 (unless (org-at-heading-p)
23210 (let* ((p (line-beginning-position))
23211 (element (save-excursion
23212 (beginning-of-line)
23213 (org-element-at-point)))
23214 (type (org-element-type element))
23215 (post-affiliated (org-element-property :post-affiliated element)))
23216 (unless (< p post-affiliated)
23217 (cl-case type
23218 (comment
23219 (save-excursion
23220 (beginning-of-line)
23221 (looking-at "[ \t]*")
23222 (concat (match-string 0) "# ")))
23223 (footnote-definition "")
23224 ((item plain-list)
23225 (make-string (org-list-item-body-column post-affiliated) ?\s))
23226 (paragraph
23227 ;; Fill prefix is usually the same as the current line,
23228 ;; unless the paragraph is at the beginning of an item.
23229 (let ((parent (org-element-property :parent element)))
23230 (save-excursion
23231 (beginning-of-line)
23232 (cond ((eq (org-element-type parent) 'item)
23233 (make-string (org-list-item-body-column
23234 (org-element-property :begin parent))
23235 ?\s))
23236 ((and adaptive-fill-regexp
23237 ;; Locally disable
23238 ;; `adaptive-fill-function' to let
23239 ;; `fill-context-prefix' handle
23240 ;; `adaptive-fill-regexp' variable.
23241 (let (adaptive-fill-function)
23242 (fill-context-prefix
23243 post-affiliated
23244 (org-element-property :end element)))))
23245 ((looking-at "[ \t]+") (match-string 0))
23246 (t "")))))
23247 (comment-block
23248 ;; Only fill contents if P is within block boundaries.
23249 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23250 (forward-line)
23251 (point)))
23252 (cend (save-excursion
23253 (goto-char (org-element-property :end element))
23254 (skip-chars-backward " \r\t\n")
23255 (line-beginning-position))))
23256 (when (and (>= p cbeg) (< p cend))
23257 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23258 (match-string 0)
23259 "")))))))))))
23261 (declare-function message-goto-body "message" ())
23262 (defvar message-cite-prefix-regexp) ; From message.el
23263 (defun org-fill-paragraph (&optional justify)
23264 "Fill element at point, when applicable.
23266 This function only applies to comment blocks, comments, example
23267 blocks and paragraphs. Also, as a special case, re-align table
23268 when point is at one.
23270 If JUSTIFY is non-nil (interactively, with prefix argument),
23271 justify as well. If `sentence-end-double-space' is non-nil, then
23272 period followed by one space does not end a sentence, so don't
23273 break a line there. The variable `fill-column' controls the
23274 width for filling.
23276 For convenience, when point is at a plain list, an item or
23277 a footnote definition, try to fill the first paragraph within."
23278 (interactive)
23279 (if (and (derived-mode-p 'message-mode)
23280 (or (not (message-in-body-p))
23281 (save-excursion (move-beginning-of-line 1)
23282 (looking-at message-cite-prefix-regexp))))
23283 ;; First ensure filling is correct in message-mode.
23284 (let ((fill-paragraph-function
23285 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23286 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23287 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23288 (paragraph-separate
23289 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23290 (fill-paragraph nil))
23291 (with-syntax-table org-mode-transpose-word-syntax-table
23292 ;; Move to end of line in order to get the first paragraph
23293 ;; within a plain list or a footnote definition.
23294 (let ((element (save-excursion
23295 (end-of-line)
23296 (or (ignore-errors (org-element-at-point))
23297 (user-error "An element cannot be parsed line %d"
23298 (line-number-at-pos (point)))))))
23299 ;; First check if point is in a blank line at the beginning of
23300 ;; the buffer. In that case, ignore filling.
23301 (cl-case (org-element-type element)
23302 ;; Use major mode filling function is src blocks.
23303 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23304 ;; Align Org tables, leave table.el tables as-is.
23305 (table-row (org-table-align) t)
23306 (table
23307 (when (eq (org-element-property :type element) 'org)
23308 (save-excursion
23309 (goto-char (org-element-property :post-affiliated element))
23310 (org-table-align)))
23312 (paragraph
23313 ;; Paragraphs may contain `line-break' type objects.
23314 (let ((beg (max (point-min)
23315 (org-element-property :contents-begin element)))
23316 (end (min (point-max)
23317 (org-element-property :contents-end element))))
23318 ;; Do nothing if point is at an affiliated keyword.
23319 (if (< (line-end-position) beg) t
23320 (when (derived-mode-p 'message-mode)
23321 ;; In `message-mode', do not fill following citation
23322 ;; in current paragraph nor text before message body.
23323 (let ((body-start (save-excursion (message-goto-body))))
23324 (when body-start (setq beg (max body-start beg))))
23325 (when (save-excursion
23326 (re-search-forward
23327 (concat "^" message-cite-prefix-regexp) end t))
23328 (setq end (match-beginning 0))))
23329 ;; Fill paragraph, taking line breaks into account.
23330 (save-excursion
23331 (goto-char beg)
23332 (let ((cuts (list beg)))
23333 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23334 (when (eq 'line-break
23335 (org-element-type
23336 (save-excursion (backward-char)
23337 (org-element-context))))
23338 (push (point) cuts)))
23339 (dolist (c (delq end cuts))
23340 (fill-region-as-paragraph c end justify)
23341 (setq end c))))
23342 t)))
23343 ;; Contents of `comment-block' type elements should be
23344 ;; filled as plain text, but only if point is within block
23345 ;; markers.
23346 (comment-block
23347 (let* ((case-fold-search t)
23348 (beg (save-excursion
23349 (goto-char (org-element-property :begin element))
23350 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23351 (forward-line)
23352 (point)))
23353 (end (save-excursion
23354 (goto-char (org-element-property :end element))
23355 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23356 (line-beginning-position))))
23357 (if (or (< (point) beg) (> (point) end)) t
23358 (fill-region-as-paragraph
23359 (save-excursion (end-of-line)
23360 (re-search-backward "^[ \t]*$" beg 'move)
23361 (line-beginning-position))
23362 (save-excursion (beginning-of-line)
23363 (re-search-forward "^[ \t]*$" end 'move)
23364 (line-beginning-position))
23365 justify))))
23366 ;; Fill comments.
23367 (comment
23368 (let ((begin (org-element-property :post-affiliated element))
23369 (end (org-element-property :end element)))
23370 (when (and (>= (point) begin) (<= (point) end))
23371 (let ((begin (save-excursion
23372 (end-of-line)
23373 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23374 (progn (forward-line) (point))
23375 begin)))
23376 (end (save-excursion
23377 (end-of-line)
23378 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23379 (1- (line-beginning-position))
23380 (skip-chars-backward " \r\t\n")
23381 (line-end-position)))))
23382 ;; Do not fill comments when at a blank line.
23383 (when (> end begin)
23384 (let ((fill-prefix
23385 (save-excursion
23386 (beginning-of-line)
23387 (looking-at "[ \t]*#")
23388 (let ((comment-prefix (match-string 0)))
23389 (goto-char (match-end 0))
23390 (if (looking-at adaptive-fill-regexp)
23391 (concat comment-prefix (match-string 0))
23392 (concat comment-prefix " "))))))
23393 (save-excursion
23394 (fill-region-as-paragraph begin end justify))))))
23396 ;; Ignore every other element.
23397 (otherwise t))))))
23399 (defun org-auto-fill-function ()
23400 "Auto-fill function."
23401 ;; Check if auto-filling is meaningful.
23402 (let ((fc (current-fill-column)))
23403 (when (and fc (> (current-column) fc))
23404 (let* ((fill-prefix (org-adaptive-fill-function))
23405 ;; Enforce empty fill prefix, if required. Otherwise, it
23406 ;; will be computed again.
23407 (adaptive-fill-mode (not (equal fill-prefix ""))))
23408 (when fill-prefix (do-auto-fill))))))
23410 (defun org-comment-line-break-function (&optional soft)
23411 "Break line at point and indent, continuing comment if within one.
23412 The inserted newline is marked hard if variable
23413 `use-hard-newlines' is true, unless optional argument SOFT is
23414 non-nil."
23415 (if soft (insert-and-inherit ?\n) (newline 1))
23416 (save-excursion (forward-char -1) (delete-horizontal-space))
23417 (delete-horizontal-space)
23418 (indent-to-left-margin)
23419 (insert-before-markers-and-inherit fill-prefix))
23422 ;;; Fixed Width Areas
23424 (defun org-toggle-fixed-width ()
23425 "Toggle fixed-width markup.
23427 Add or remove fixed-width markup on current line, whenever it
23428 makes sense. Return an error otherwise.
23430 If a region is active and if it contains only fixed-width areas
23431 or blank lines, remove all fixed-width markup in it. If the
23432 region contains anything else, convert all non-fixed-width lines
23433 to fixed-width ones.
23435 Blank lines at the end of the region are ignored unless the
23436 region only contains such lines."
23437 (interactive)
23438 (if (not (org-region-active-p))
23439 ;; No region:
23441 ;; Remove fixed width marker only in a fixed-with element.
23443 ;; Add fixed width maker in paragraphs, in blank lines after
23444 ;; elements or at the beginning of a headline or an inlinetask,
23445 ;; and before any one-line elements (e.g., a clock).
23446 (progn
23447 (beginning-of-line)
23448 (let* ((element (org-element-at-point))
23449 (type (org-element-type element)))
23450 (cond
23451 ((and (eq type 'fixed-width)
23452 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23453 (replace-match
23454 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23455 ((and (memq type '(babel-call clock comment diary-sexp headline
23456 horizontal-rule keyword paragraph
23457 planning))
23458 (<= (org-element-property :post-affiliated element) (point)))
23459 (skip-chars-forward " \t")
23460 (insert ": "))
23461 ((and (looking-at-p "[ \t]*$")
23462 (or (eq type 'inlinetask)
23463 (save-excursion
23464 (skip-chars-forward " \r\t\n")
23465 (<= (org-element-property :end element) (point)))))
23466 (delete-region (point) (line-end-position))
23467 (org-indent-line)
23468 (insert ": "))
23469 (t (user-error "Cannot insert a fixed-width line here")))))
23470 ;; Region active.
23471 (let* ((begin (save-excursion
23472 (goto-char (region-beginning))
23473 (line-beginning-position)))
23474 (end (copy-marker
23475 (save-excursion
23476 (goto-char (region-end))
23477 (unless (eolp) (beginning-of-line))
23478 (if (save-excursion (re-search-backward "\\S-" begin t))
23479 (progn (skip-chars-backward " \r\t\n") (point))
23480 (point)))))
23481 (all-fixed-width-p
23482 (catch 'not-all-p
23483 (save-excursion
23484 (goto-char begin)
23485 (skip-chars-forward " \r\t\n")
23486 (when (eobp) (throw 'not-all-p nil))
23487 (while (< (point) end)
23488 (let ((element (org-element-at-point)))
23489 (if (eq (org-element-type element) 'fixed-width)
23490 (goto-char (org-element-property :end element))
23491 (throw 'not-all-p nil))))
23492 t))))
23493 (if all-fixed-width-p
23494 (save-excursion
23495 (goto-char begin)
23496 (while (< (point) end)
23497 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23498 (replace-match
23499 "" nil nil nil
23500 (if (= (line-end-position) (match-end 0)) 0 1)))
23501 (forward-line)))
23502 (let ((min-ind (point-max)))
23503 ;; Find minimum indentation across all lines.
23504 (save-excursion
23505 (goto-char begin)
23506 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23507 (setq min-ind 0)
23508 (catch 'zerop
23509 (while (< (point) end)
23510 (unless (looking-at-p "[ \t]*$")
23511 (let ((ind (org-get-indentation)))
23512 (setq min-ind (min min-ind ind))
23513 (when (zerop ind) (throw 'zerop t))))
23514 (forward-line)))))
23515 ;; Loop over all lines and add fixed-width markup everywhere
23516 ;; but in fixed-width lines.
23517 (save-excursion
23518 (goto-char begin)
23519 (while (< (point) end)
23520 (cond
23521 ((org-at-heading-p)
23522 (insert ": ")
23523 (forward-line)
23524 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23525 (insert ":")
23526 (forward-line)))
23527 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23528 (let* ((element (org-element-at-point))
23529 (element-end (org-element-property :end element)))
23530 (if (eq (org-element-type element) 'fixed-width)
23531 (progn (goto-char element-end)
23532 (skip-chars-backward " \r\t\n")
23533 (forward-line))
23534 (let ((limit (min end element-end)))
23535 (while (< (point) limit)
23536 (org-move-to-column min-ind t)
23537 (insert ": ")
23538 (forward-line))))))
23540 (org-move-to-column min-ind t)
23541 (insert ": ")
23542 (forward-line)))))))
23543 (set-marker end nil))))
23546 ;;; Comments
23548 ;; Org comments syntax is quite complex. It requires the entire line
23549 ;; to be just a comment. Also, even with the right syntax at the
23550 ;; beginning of line, some some elements (i.e. verse-block or
23551 ;; example-block) don't accept comments. Usual Emacs comment commands
23552 ;; cannot cope with those requirements. Therefore, Org replaces them.
23554 ;; Org still relies on `comment-dwim', but cannot trust
23555 ;; `comment-only-p'. So, `comment-region-function' and
23556 ;; `uncomment-region-function' both point
23557 ;; to`org-comment-or-uncomment-region'. Eventually,
23558 ;; `org-insert-comment' takes care of insertion of comments at the
23559 ;; beginning of line.
23561 ;; `org-setup-comments-handling' install comments related variables
23562 ;; during `org-mode' initialization.
23564 (defun org-setup-comments-handling ()
23565 (interactive)
23566 (setq-local comment-use-syntax nil)
23567 (setq-local comment-start "# ")
23568 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23569 (setq-local comment-insert-comment-function 'org-insert-comment)
23570 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23571 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23573 (defun org-insert-comment ()
23574 "Insert an empty comment above current line.
23575 If the line is empty, insert comment at its beginning. When
23576 point is within a source block, comment according to the related
23577 major mode."
23578 (if (let ((element (org-element-at-point)))
23579 (and (eq (org-element-type element) 'src-block)
23580 (< (save-excursion
23581 (goto-char (org-element-property :post-affiliated element))
23582 (line-end-position))
23583 (point))
23584 (> (save-excursion
23585 (goto-char (org-element-property :end element))
23586 (skip-chars-backward " \r\t\n")
23587 (line-beginning-position))
23588 (point))))
23589 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23590 (beginning-of-line)
23591 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23592 (open-line 1))
23593 (org-indent-line)
23594 (insert "# ")))
23596 (defvar comment-empty-lines) ; From newcomment.el.
23597 (defun org-comment-or-uncomment-region (beg end &rest _)
23598 "Comment or uncomment each non-blank line in the region.
23599 Uncomment each non-blank line between BEG and END if it only
23600 contains commented lines. Otherwise, comment them. If region is
23601 strictly within a source block, use appropriate comment syntax."
23602 (if (let ((element (org-element-at-point)))
23603 (and (eq (org-element-type element) 'src-block)
23604 (< (save-excursion
23605 (goto-char (org-element-property :post-affiliated element))
23606 (line-end-position))
23607 beg)
23608 (>= (save-excursion
23609 (goto-char (org-element-property :end element))
23610 (skip-chars-backward " \r\t\n")
23611 (line-beginning-position))
23612 end)))
23613 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23614 (save-restriction
23615 ;; Restrict region
23616 (narrow-to-region (save-excursion (goto-char beg)
23617 (skip-chars-forward " \r\t\n" end)
23618 (line-beginning-position))
23619 (save-excursion (goto-char end)
23620 (skip-chars-backward " \r\t\n" beg)
23621 (line-end-position)))
23622 (let ((uncommentp
23623 ;; UNCOMMENTP is non-nil when every non blank line between
23624 ;; BEG and END is a comment.
23625 (save-excursion
23626 (goto-char (point-min))
23627 (while (and (not (eobp))
23628 (let ((element (org-element-at-point)))
23629 (and (eq (org-element-type element) 'comment)
23630 (goto-char (min (point-max)
23631 (org-element-property
23632 :end element)))))))
23633 (eobp))))
23634 (if uncommentp
23635 ;; Only blank lines and comments in region: uncomment it.
23636 (save-excursion
23637 (goto-char (point-min))
23638 (while (not (eobp))
23639 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23640 (replace-match "" nil nil nil 1))
23641 (forward-line)))
23642 ;; Comment each line in region.
23643 (let ((min-indent (point-max)))
23644 ;; First find the minimum indentation across all lines.
23645 (save-excursion
23646 (goto-char (point-min))
23647 (while (and (not (eobp)) (not (zerop min-indent)))
23648 (unless (looking-at "[ \t]*$")
23649 (setq min-indent (min min-indent (current-indentation))))
23650 (forward-line)))
23651 ;; Then loop over all lines.
23652 (save-excursion
23653 (goto-char (point-min))
23654 (while (not (eobp))
23655 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23656 ;; Don't get fooled by invisible text (e.g. link path)
23657 ;; when moving to column MIN-INDENT.
23658 (let ((buffer-invisibility-spec nil))
23659 (org-move-to-column min-indent t))
23660 (insert comment-start))
23661 (forward-line)))))))))
23663 (defun org-comment-dwim (_arg)
23664 "Call `comment-dwim' within a source edit buffer if needed."
23665 (interactive "*P")
23666 (if (org-in-src-block-p)
23667 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23668 (call-interactively 'comment-dwim)))
23671 ;;; Timestamps API
23673 ;; This section contains tools to operate on timestamp objects, as
23674 ;; returned by, e.g. `org-element-context'.
23676 (defun org-timestamp--to-internal-time (timestamp &optional end)
23677 "Encode TIMESTAMP object into Emacs internal time.
23678 Use end of date range or time range when END is non-nil."
23679 (apply #'encode-time
23680 (cons 0
23681 (mapcar
23682 (lambda (prop) (or (org-element-property prop timestamp) 0))
23683 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23684 '(:minute-start :hour-start :day-start :month-start
23685 :year-start))))))
23687 (defun org-timestamp-has-time-p (timestamp)
23688 "Non-nil when TIMESTAMP has a time specified."
23689 (org-element-property :hour-start timestamp))
23691 (defun org-timestamp-format (timestamp format &optional end utc)
23692 "Format a TIMESTAMP object into a string.
23694 FORMAT is a format specifier to be passed to
23695 `format-time-string'.
23697 When optional argument END is non-nil, use end of date-range or
23698 time-range, if possible.
23700 When optional argument UTC is non-nil, time will be expressed as
23701 Universal Time."
23702 (format-time-string
23703 format (org-timestamp--to-internal-time timestamp end)
23704 (and utc t)))
23706 (defun org-timestamp-split-range (timestamp &optional end)
23707 "Extract a TIMESTAMP object from a date or time range.
23709 END, when non-nil, means extract the end of the range.
23710 Otherwise, extract its start.
23712 Return a new timestamp object."
23713 (let ((type (org-element-property :type timestamp)))
23714 (if (memq type '(active inactive diary)) timestamp
23715 (let ((split-ts (org-element-copy timestamp)))
23716 ;; Set new type.
23717 (org-element-put-property
23718 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23719 ;; Copy start properties over end properties if END is
23720 ;; non-nil. Otherwise, copy end properties over `start' ones.
23721 (let ((p-alist '((:minute-start . :minute-end)
23722 (:hour-start . :hour-end)
23723 (:day-start . :day-end)
23724 (:month-start . :month-end)
23725 (:year-start . :year-end))))
23726 (dolist (p-cell p-alist)
23727 (org-element-put-property
23728 split-ts
23729 (funcall (if end #'car #'cdr) p-cell)
23730 (org-element-property
23731 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23732 ;; Eventually refresh `:raw-value'.
23733 (org-element-put-property split-ts :raw-value nil)
23734 (org-element-put-property
23735 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23737 (defun org-timestamp-translate (timestamp &optional boundary)
23738 "Translate TIMESTAMP object to custom format.
23740 Format string is defined in `org-time-stamp-custom-formats',
23741 which see.
23743 When optional argument BOUNDARY is non-nil, it is either the
23744 symbol `start' or `end'. In this case, only translate the
23745 starting or ending part of TIMESTAMP if it is a date or time
23746 range. Otherwise, translate both parts.
23748 Return timestamp as-is if `org-display-custom-times' is nil or if
23749 it has a `diary' type."
23750 (let ((type (org-element-property :type timestamp)))
23751 (if (or (not org-display-custom-times) (eq type 'diary))
23752 (org-element-interpret-data timestamp)
23753 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23754 org-time-stamp-custom-formats)))
23755 (if (and (not boundary) (memq type '(active-range inactive-range)))
23756 (concat (org-timestamp-format timestamp fmt)
23757 "--"
23758 (org-timestamp-format timestamp fmt t))
23759 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23763 ;;; Other stuff.
23765 (defvar reftex-docstruct-symbol)
23766 (defvar reftex-cite-format)
23767 (defvar org--rds)
23769 (defun org-reftex-citation ()
23770 "Use reftex-citation to insert a citation into the buffer.
23771 This looks for a line like
23773 #+BIBLIOGRAPHY: foo plain option:-d
23775 and derives from it that foo.bib is the bibliography file relevant
23776 for this document. It then installs the necessary environment for RefTeX
23777 to work in this buffer and calls `reftex-citation' to insert a citation
23778 into the buffer.
23780 Export of such citations to both LaTeX and HTML is handled by the contributed
23781 package ox-bibtex by Taru Karttunen."
23782 (interactive)
23783 (let ((reftex-docstruct-symbol 'org--rds)
23784 (reftex-cite-format "\\cite{%l}")
23785 org--rds bib)
23786 (save-excursion
23787 (save-restriction
23788 (widen)
23789 (let ((case-fold-search t)
23790 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23791 (if (not (save-excursion
23792 (or (re-search-forward re nil t)
23793 (re-search-backward re nil t))))
23794 (user-error "No bibliography defined in file")
23795 (setq bib (concat (match-string 1) ".bib")
23796 org--rds (list (list 'bib bib)))))))
23797 (call-interactively 'reftex-citation)))
23799 ;;;; Functions extending outline functionality
23801 (defun org-beginning-of-line (&optional arg)
23802 "Go to the beginning of the current line. If that is invisible, continue
23803 to a visible line beginning. This makes the function of C-a more intuitive.
23804 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23805 first attempt, and only move to after the tags when the cursor is already
23806 beyond the end of the headline."
23807 (interactive "P")
23808 (let ((pos (point))
23809 (special (if (consp org-special-ctrl-a/e)
23810 (car org-special-ctrl-a/e)
23811 org-special-ctrl-a/e))
23812 deactivate-mark refpos)
23813 (call-interactively (if (bound-and-true-p visual-line-mode)
23814 #'beginning-of-visual-line
23815 #'move-beginning-of-line))
23816 (cond
23817 ((or arg (not special)))
23818 ((and (looking-at org-complex-heading-regexp)
23819 (eq (char-after (match-end 1)) ?\s))
23820 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23821 (point-at-eol)))
23822 (goto-char
23823 (if (eq special t)
23824 (cond ((> pos refpos) refpos)
23825 ((= pos (point)) refpos)
23826 (t (point)))
23827 (cond ((> pos (point)) (point))
23828 ((not (eq last-command this-command)) (point))
23829 (t refpos)))))
23830 ((org-at-item-p)
23831 ;; Being at an item and not looking at an the item means point
23832 ;; was previously moved to beginning of a visual line, which
23833 ;; doesn't contain the item. Therefore, do nothing special,
23834 ;; just stay here.
23835 (when (looking-at org-list-full-item-re)
23836 ;; Set special position at first white space character after
23837 ;; bullet, and check-box, if any.
23838 (let ((after-bullet
23839 (let ((box (match-end 3)))
23840 (if (not box) (match-end 1)
23841 (let ((after (char-after box)))
23842 (if (and after (= after ? )) (1+ box) box))))))
23843 ;; Special case: Move point to special position when
23844 ;; currently after it or at beginning of line.
23845 (if (eq special t)
23846 (when (or (> pos after-bullet) (= (point) pos))
23847 (goto-char after-bullet))
23848 ;; Reversed case: Move point to special position when
23849 ;; point was already at beginning of line and command is
23850 ;; repeated.
23851 (when (and (= (point) pos) (eq last-command this-command))
23852 (goto-char after-bullet))))))))
23853 (setq disable-point-adjustment
23854 (or (not (invisible-p (point)))
23855 (not (invisible-p (max (point-min) (1- (point))))))))
23857 (defun org-end-of-line (&optional arg)
23858 "Go to the end of the line.
23859 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23860 tags on the first attempt, and only move to after the tags when
23861 the cursor is already beyond the end of the headline."
23862 (interactive "P")
23863 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23864 org-special-ctrl-a/e))
23865 (move-fun (cond ((bound-and-true-p visual-line-mode)
23866 'end-of-visual-line)
23867 ((fboundp 'move-end-of-line) 'move-end-of-line)
23868 (t 'end-of-line)))
23869 deactivate-mark)
23870 (if (or (not special) arg) (call-interactively move-fun)
23871 (let* ((element (save-excursion (beginning-of-line)
23872 (org-element-at-point)))
23873 (type (org-element-type element)))
23874 (cond
23875 ((memq type '(headline inlinetask))
23876 (let ((pos (point)))
23877 (beginning-of-line 1)
23878 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23879 (if (eq special t)
23880 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23881 (goto-char (match-beginning 1))
23882 (goto-char (match-end 0)))
23883 (if (or (< pos (match-end 0))
23884 (not (eq this-command last-command)))
23885 (goto-char (match-end 0))
23886 (goto-char (match-beginning 1))))
23887 (call-interactively move-fun))))
23888 ((outline-invisible-p (line-end-position))
23889 ;; If element is hidden, `move-end-of-line' would put point
23890 ;; after it. Use `end-of-line' to stay on current line.
23891 (call-interactively 'end-of-line))
23892 (t (call-interactively move-fun))))))
23893 (setq disable-point-adjustment
23894 (or (not (invisible-p (point)))
23895 (not (invisible-p (max (point-min) (1- (point))))))))
23897 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23898 (define-key org-mode-map "\C-e" 'org-end-of-line)
23900 (defun org-backward-sentence (&optional _arg)
23901 "Go to beginning of sentence, or beginning of table field.
23902 This will call `backward-sentence' or `org-table-beginning-of-field',
23903 depending on context."
23904 (interactive)
23905 (let* ((element (org-element-at-point))
23906 (contents-begin (org-element-property :contents-begin element))
23907 (table (org-element-lineage element '(table) t)))
23908 (if (and table
23909 (> (point) contents-begin)
23910 (<= (point) (org-element-property :contents-end table)))
23911 (call-interactively #'org-table-beginning-of-field)
23912 (save-restriction
23913 (when (and contents-begin
23914 (< (point-min) contents-begin)
23915 (> (point) contents-begin))
23916 (narrow-to-region contents-begin
23917 (org-element-property :contents-end element)))
23918 (call-interactively #'backward-sentence)))))
23920 (defun org-forward-sentence (&optional _arg)
23921 "Go to end of sentence, or end of table field.
23922 This will call `forward-sentence' or `org-table-end-of-field',
23923 depending on context."
23924 (interactive)
23925 (let* ((element (org-element-at-point))
23926 (contents-end (org-element-property :contents-end element))
23927 (table (org-element-lineage element '(table) t)))
23928 (if (and table
23929 (>= (point) (org-element-property :contents-begin table))
23930 (< (point) contents-end))
23931 (call-interactively #'org-table-end-of-field)
23932 (save-restriction
23933 (when (and contents-end
23934 (> (point-max) contents-end)
23935 ;; Skip blank lines between elements.
23936 (< (org-element-property :end element)
23937 (save-excursion (goto-char contents-end)
23938 (skip-chars-forward " \r\t\n"))))
23939 (narrow-to-region (org-element-property :contents-begin element)
23940 contents-end))
23941 (call-interactively #'forward-sentence)))))
23943 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23944 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23946 (defun org-kill-line (&optional _arg)
23947 "Kill line, to tags or end of line."
23948 (interactive)
23949 (cond
23950 ((or (not org-special-ctrl-k)
23951 (bolp)
23952 (not (org-at-heading-p)))
23953 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23954 org-ctrl-k-protect-subtree
23955 (or (eq org-ctrl-k-protect-subtree 'error)
23956 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23957 (user-error "C-k aborted as it would kill a hidden subtree"))
23958 (call-interactively
23959 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23960 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23961 (kill-region (point) (match-beginning 1))
23962 (org-set-tags nil t))
23963 (t (kill-region (point) (point-at-eol)))))
23965 (define-key org-mode-map "\C-k" 'org-kill-line)
23967 (defun org-yank (&optional arg)
23968 "Yank. If the kill is a subtree, treat it specially.
23969 This command will look at the current kill and check if is a single
23970 subtree, or a series of subtrees[1]. If it passes the test, and if the
23971 cursor is at the beginning of a line or after the stars of a currently
23972 empty headline, then the yank is handled specially. How exactly depends
23973 on the value of the following variables.
23975 `org-yank-folded-subtrees'
23976 By default, this variable is non-nil, which results in subtree(s)
23977 being folded after insertion, but only if doing so would now
23978 swallow text after the yanked text.
23980 `org-yank-adjusted-subtrees'
23981 When non-nil (the default value is nil), the subtree will be
23982 promoted or demoted in order to fit into the local outline tree
23983 structure, which means that the level will be adjusted so that it
23984 becomes the smaller one of the two *visible* surrounding headings.
23986 Any prefix to this command will cause `yank' to be called directly with
23987 no special treatment. In particular, a simple \\[universal-argument] prefix \
23988 will just
23989 plainly yank the text as it is.
23991 \[1] The test checks if the first non-white line is a heading
23992 and if there are no other headings with fewer stars."
23993 (interactive "P")
23994 (org-yank-generic 'yank arg))
23996 (defun org-yank-generic (command arg)
23997 "Perform some yank-like command.
23999 This function implements the behavior described in the `org-yank'
24000 documentation. However, it has been generalized to work for any
24001 interactive command with similar behavior."
24003 ;; pretend to be command COMMAND
24004 (setq this-command command)
24006 (if arg
24007 (call-interactively command)
24009 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24010 (and (org-kill-is-subtree-p)
24011 (or (bolp)
24012 (and (looking-at "[ \t]*$")
24013 (string-match
24014 "\\`\\*+\\'"
24015 (buffer-substring (point-at-bol) (point)))))))
24016 swallowp)
24017 (cond
24018 ((and subtreep org-yank-folded-subtrees)
24019 (let ((beg (point))
24020 end)
24021 (if (and subtreep org-yank-adjusted-subtrees)
24022 (org-paste-subtree nil nil 'for-yank)
24023 (call-interactively command))
24025 (setq end (point))
24026 (goto-char beg)
24027 (when (and (bolp) subtreep
24028 (not (setq swallowp
24029 (org-yank-folding-would-swallow-text beg end))))
24030 (org-with-limited-levels
24031 (or (looking-at org-outline-regexp)
24032 (re-search-forward org-outline-regexp-bol end t))
24033 (while (and (< (point) end) (looking-at org-outline-regexp))
24034 (outline-hide-subtree)
24035 (org-cycle-show-empty-lines 'folded)
24036 (condition-case nil
24037 (outline-forward-same-level 1)
24038 (error (goto-char end))))))
24039 (when swallowp
24040 (message
24041 "Inserted text not folded because that would swallow text"))
24043 (goto-char end)
24044 (skip-chars-forward " \t\n\r")
24045 (beginning-of-line 1)
24046 (push-mark beg 'nomsg)))
24047 ((and subtreep org-yank-adjusted-subtrees)
24048 (let ((beg (point-at-bol)))
24049 (org-paste-subtree nil nil 'for-yank)
24050 (push-mark beg 'nomsg)))
24052 (call-interactively command))))))
24054 (defun org-yank-folding-would-swallow-text (beg end)
24055 "Would hide-subtree at BEG swallow any text after END?"
24056 (let (level)
24057 (org-with-limited-levels
24058 (save-excursion
24059 (goto-char beg)
24060 (when (or (looking-at org-outline-regexp)
24061 (re-search-forward org-outline-regexp-bol end t))
24062 (setq level (org-outline-level)))
24063 (goto-char end)
24064 (skip-chars-forward " \t\r\n\v\f")
24065 (not (or (eobp)
24066 (and (bolp) (looking-at-p org-outline-regexp)
24067 (<= (org-outline-level) level))))))))
24069 (define-key org-mode-map "\C-y" 'org-yank)
24071 (defun org-truely-invisible-p ()
24072 "Check if point is at a character currently not visible.
24073 This version does not only check the character property, but also
24074 `visible-mode'."
24075 ;; Early versions of noutline don't have `outline-invisible-p'.
24076 (unless (bound-and-true-p visible-mode)
24077 (outline-invisible-p)))
24079 (defun org-invisible-p2 ()
24080 "Check if point is at a character currently not visible."
24081 (save-excursion
24082 (when (and (eolp) (not (bobp))) (backward-char 1))
24083 ;; Early versions of noutline don't have `outline-invisible-p'.
24084 (outline-invisible-p)))
24086 (defun org-back-to-heading (&optional invisible-ok)
24087 "Call `outline-back-to-heading', but provide a better error message."
24088 (condition-case nil
24089 (outline-back-to-heading invisible-ok)
24090 (error (error "Before first headline at position %d in buffer %s"
24091 (point) (current-buffer)))))
24093 (defun org-before-first-heading-p ()
24094 "Before first heading?"
24095 (save-excursion
24096 (end-of-line)
24097 (null (re-search-backward org-outline-regexp-bol nil t))))
24099 (defun org-at-heading-p (&optional ignored)
24100 (outline-on-heading-p t))
24102 (defun org-in-commented-heading-p (&optional no-inheritance)
24103 "Non-nil if point is under a commented heading.
24104 This function also checks ancestors of the current headline,
24105 unless optional argument NO-INHERITANCE is non-nil."
24106 (cond
24107 ((org-before-first-heading-p) nil)
24108 ((let ((headline (nth 4 (org-heading-components))))
24109 (and headline
24110 (let ((case-fold-search nil))
24111 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24112 headline)))))
24113 (no-inheritance nil)
24115 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24117 (defun org-at-comment-p nil
24118 "Is cursor in a commented line?"
24119 (save-excursion
24120 (save-match-data
24121 (beginning-of-line)
24122 (looking-at "^[ \t]*# "))))
24124 (defun org-at-drawer-p nil
24125 "Is cursor at a drawer keyword?"
24126 (save-excursion
24127 (move-beginning-of-line 1)
24128 (looking-at org-drawer-regexp)))
24130 (defun org-at-block-p nil
24131 "Is cursor at a block keyword?"
24132 (save-excursion
24133 (move-beginning-of-line 1)
24134 (looking-at org-block-regexp)))
24136 (defun org-point-at-end-of-empty-headline ()
24137 "If point is at the end of an empty headline, return t, else nil.
24138 If the heading only contains a TODO keyword, it is still still considered
24139 empty."
24140 (and (looking-at "[ \t]*$")
24141 (when org-todo-line-regexp
24142 (save-excursion
24143 (beginning-of-line 1)
24144 (let ((case-fold-search nil))
24145 (looking-at org-todo-line-regexp)
24146 (string= (match-string 3) ""))))))
24148 (defun org-at-heading-or-item-p ()
24149 (or (org-at-heading-p) (org-at-item-p)))
24151 (defun org-at-target-p ()
24152 (or (org-in-regexp org-radio-target-regexp)
24153 (org-in-regexp org-target-regexp)))
24154 ;; Compatibility alias with Org versions < 7.8.03
24155 (defalias 'org-on-target-p 'org-at-target-p)
24157 (defun org-up-heading-all (arg)
24158 "Move to the heading line of which the present line is a subheading.
24159 This function considers both visible and invisible heading lines.
24160 With argument, move up ARG levels."
24161 (outline-up-heading arg t))
24163 (defun org-up-heading-safe ()
24164 "Move to the heading line of which the present line is a subheading.
24165 This version will not throw an error. It will return the level of the
24166 headline found, or nil if no higher level is found.
24168 Also, this function will be a lot faster than `outline-up-heading',
24169 because it relies on stars being the outline starters. This can really
24170 make a significant difference in outlines with very many siblings."
24171 (when (ignore-errors (org-back-to-heading t))
24172 (let ((level-up (1- (funcall outline-level))))
24173 (and (> level-up 0)
24174 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24175 (funcall outline-level)))))
24177 (defun org-first-sibling-p ()
24178 "Is this heading the first child of its parents?"
24179 (interactive)
24180 (let ((re org-outline-regexp-bol)
24181 level l)
24182 (unless (org-at-heading-p t)
24183 (user-error "Not at a heading"))
24184 (setq level (funcall outline-level))
24185 (save-excursion
24186 (if (not (re-search-backward re nil t))
24188 (setq l (funcall outline-level))
24189 (< l level)))))
24191 (defun org-goto-sibling (&optional previous)
24192 "Goto the next sibling, even if it is invisible.
24193 When PREVIOUS is set, go to the previous sibling instead. Returns t
24194 when a sibling was found. When none is found, return nil and don't
24195 move point."
24196 (let ((fun (if previous 're-search-backward 're-search-forward))
24197 (pos (point))
24198 (re org-outline-regexp-bol)
24199 level l)
24200 (when (ignore-errors (org-back-to-heading t))
24201 (setq level (funcall outline-level))
24202 (catch 'exit
24203 (or previous (forward-char 1))
24204 (while (funcall fun re nil t)
24205 (setq l (funcall outline-level))
24206 (when (< l level) (goto-char pos) (throw 'exit nil))
24207 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24208 (goto-char pos)
24209 nil))))
24211 (defun org-show-siblings ()
24212 "Show all siblings of the current headline."
24213 (save-excursion
24214 (while (org-goto-sibling) (org-flag-heading nil)))
24215 (save-excursion
24216 (while (org-goto-sibling 'previous)
24217 (org-flag-heading nil))))
24219 (defun org-goto-first-child ()
24220 "Goto the first child, even if it is invisible.
24221 Return t when a child was found. Otherwise don't move point and
24222 return nil."
24223 (let (level (pos (point)) (re org-outline-regexp-bol))
24224 (when (ignore-errors (org-back-to-heading t))
24225 (setq level (outline-level))
24226 (forward-char 1)
24227 (if (and (re-search-forward re nil t) (> (outline-level) level))
24228 (progn (goto-char (match-beginning 0)) t)
24229 (goto-char pos) nil))))
24231 (defun org-show-hidden-entry ()
24232 "Show an entry where even the heading is hidden."
24233 (save-excursion
24234 (org-show-entry)))
24236 (defun org-flag-heading (flag &optional entry)
24237 "Flag the current heading. FLAG non-nil means make invisible.
24238 When ENTRY is non-nil, show the entire entry."
24239 (save-excursion
24240 (org-back-to-heading t)
24241 ;; Check if we should show the entire entry
24242 (if entry
24243 (progn
24244 (org-show-entry)
24245 (save-excursion
24246 (and (outline-next-heading)
24247 (org-flag-heading nil))))
24248 (outline-flag-region (max (point-min) (1- (point)))
24249 (save-excursion (outline-end-of-heading) (point))
24250 flag))))
24252 (defun org-get-next-sibling ()
24253 "Move to next heading of the same level, and return point.
24254 If there is no such heading, return nil.
24255 This is like outline-next-sibling, but invisible headings are ok."
24256 (let ((level (funcall outline-level)))
24257 (outline-next-heading)
24258 (while (and (not (eobp)) (> (funcall outline-level) level))
24259 (outline-next-heading))
24260 (unless (or (eobp) (< (funcall outline-level) level))
24261 (point))))
24263 (defun org-get-last-sibling ()
24264 "Move to previous heading of the same level, and return point.
24265 If there is no such heading, return nil."
24266 (let ((opoint (point))
24267 (level (funcall outline-level)))
24268 (outline-previous-heading)
24269 (when (and (/= (point) opoint) (outline-on-heading-p t))
24270 (while (and (> (funcall outline-level) level)
24271 (not (bobp)))
24272 (outline-previous-heading))
24273 (unless (< (funcall outline-level) level)
24274 (point)))))
24276 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24277 "Goto to the end of a subtree."
24278 ;; This contains an exact copy of the original function, but it uses
24279 ;; `org-back-to-heading', to make it work also in invisible
24280 ;; trees. And is uses an invisible-ok argument.
24281 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24282 ;; Furthermore, when used inside Org, finding the end of a large subtree
24283 ;; with many children and grandchildren etc, this can be much faster
24284 ;; than the outline version.
24285 (org-back-to-heading invisible-ok)
24286 (let ((first t)
24287 (level (funcall outline-level)))
24288 (if (and (derived-mode-p 'org-mode) (< level 1000))
24289 ;; A true heading (not a plain list item), in Org-mode
24290 ;; This means we can easily find the end by looking
24291 ;; only for the right number of stars. Using a regexp to do
24292 ;; this is so much faster than using a Lisp loop.
24293 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24294 (forward-char 1)
24295 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24296 ;; something else, do it the slow way
24297 (while (and (not (eobp))
24298 (or first (> (funcall outline-level) level)))
24299 (setq first nil)
24300 (outline-next-heading)))
24301 (unless to-heading
24302 (when (memq (preceding-char) '(?\n ?\^M))
24303 ;; Go to end of line before heading
24304 (forward-char -1)
24305 (when (memq (preceding-char) '(?\n ?\^M))
24306 ;; leave blank line before heading
24307 (forward-char -1)))))
24308 (point))
24310 (defun org-end-of-meta-data (&optional full)
24311 "Skip planning line and properties drawer in current entry.
24312 When optional argument FULL is non-nil, also skip empty lines,
24313 clocking lines and regular drawers at the beginning of the
24314 entry."
24315 (org-back-to-heading t)
24316 (forward-line)
24317 (when (looking-at-p org-planning-line-re) (forward-line))
24318 (when (looking-at org-property-drawer-re)
24319 (goto-char (match-end 0))
24320 (forward-line))
24321 (when (and full (not (org-at-heading-p)))
24322 (catch 'exit
24323 (let ((end (save-excursion (outline-next-heading) (point)))
24324 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24325 (while (not (eobp))
24326 (cond ((looking-at-p org-drawer-regexp)
24327 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24328 (forward-line)
24329 (throw 'exit t)))
24330 ((looking-at-p re) (forward-line))
24331 (t (throw 'exit t))))))))
24333 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24334 "Move forward to the ARG'th subheading at same level as this one.
24335 Stop at the first and last subheadings of a superior heading.
24336 Normally this only looks at visible headings, but when INVISIBLE-OK is
24337 non-nil it will also look at invisible ones."
24338 (interactive "p")
24339 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24340 (if (and arg (< arg 0))
24341 (goto-char (point-min))
24342 (outline-next-heading))
24343 (org-at-heading-p)
24344 (let ((level (- (match-end 0) (match-beginning 0) 1))
24345 (f (if (and arg (< arg 0))
24346 're-search-backward
24347 're-search-forward))
24348 (count (if arg (abs arg) 1))
24349 (result (point)))
24350 (while (and (prog1 (> count 0)
24351 (forward-char (if (and arg (< arg 0)) -1 1)))
24352 (funcall f org-outline-regexp-bol nil 'move))
24353 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24354 (cond ((< l level) (setq count 0))
24355 ((and (= l level)
24356 (or invisible-ok
24357 (progn
24358 (goto-char (line-beginning-position))
24359 (not (outline-invisible-p)))))
24360 (setq count (1- count))
24361 (when (eq l level)
24362 (setq result (point)))))))
24363 (goto-char result))
24364 (beginning-of-line 1)))
24366 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24367 "Move backward to the ARG'th subheading at same level as this one.
24368 Stop at the first and last subheadings of a superior heading."
24369 (interactive "p")
24370 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24372 (defun org-next-visible-heading (arg)
24373 "Move to the next visible heading.
24375 This function wraps `outline-next-visible-heading' with
24376 `org-with-limited-levels' in order to skip over inline tasks and
24377 respect customization of `org-odd-levels-only'."
24378 (interactive "p")
24379 (org-with-limited-levels
24380 (outline-next-visible-heading arg)))
24382 (defun org-previous-visible-heading (arg)
24383 "Move to the previous visible heading.
24385 This function wraps `outline-previous-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-previous-visible-heading arg)))
24392 (defun org-next-block (arg &optional backward block-regexp)
24393 "Jump to the next block.
24395 With a prefix argument ARG, jump forward ARG many blocks.
24397 When BACKWARD is non-nil, jump to the previous block.
24399 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24400 Match data is set according to this regexp when the function
24401 returns.
24403 Return point at beginning of the opening line of found block.
24404 Throw an error if no block is found."
24405 (interactive "p")
24406 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24407 (case-fold-search t)
24408 (search-fn (if backward #'re-search-backward #'re-search-forward))
24409 (count (or arg 1))
24410 (origin (point))
24411 last-element)
24412 (if backward (beginning-of-line) (end-of-line))
24413 (while (and (> count 0) (funcall search-fn re nil t))
24414 (let ((element (save-excursion
24415 (goto-char (match-beginning 0))
24416 (save-match-data (org-element-at-point)))))
24417 (when (and (memq (org-element-type element)
24418 '(center-block comment-block dynamic-block
24419 example-block export-block quote-block
24420 special-block src-block verse-block))
24421 (<= (match-beginning 0)
24422 (org-element-property :post-affiliated element)))
24423 (setq last-element element)
24424 (cl-decf count))))
24425 (if (= count 0)
24426 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24427 (save-match-data (org-show-context)))
24428 (goto-char origin)
24429 (user-error "No %s code blocks" (if backward "previous" "further")))))
24431 (defun org-previous-block (arg &optional block-regexp)
24432 "Jump to the previous block.
24433 With a prefix argument ARG, jump backward ARG many source blocks.
24434 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24435 (interactive "p")
24436 (org-next-block arg t block-regexp))
24438 (defun org-forward-paragraph ()
24439 "Move forward to beginning of next paragraph or equivalent.
24441 The function moves point to the beginning of the next visible
24442 structural element, which can be a paragraph, a table, a list
24443 item, etc. It also provides some special moves for convenience:
24445 - On an affiliated keyword, jump to the beginning of the
24446 relative element.
24447 - On an item or a footnote definition, move to the second
24448 element inside, if any.
24449 - On a table or a property drawer, jump after it.
24450 - On a verse or source block, stop after blank lines."
24451 (interactive)
24452 (when (eobp) (user-error "Cannot move further down"))
24453 (let* ((deactivate-mark nil)
24454 (element (org-element-at-point))
24455 (type (org-element-type element))
24456 (post-affiliated (org-element-property :post-affiliated element))
24457 (contents-begin (org-element-property :contents-begin element))
24458 (contents-end (org-element-property :contents-end element))
24459 (end (let ((end (org-element-property :end element)) (parent element))
24460 (while (and (setq parent (org-element-property :parent parent))
24461 (= (org-element-property :contents-end parent) end))
24462 (setq end (org-element-property :end parent)))
24463 end)))
24464 (cond ((not element)
24465 (skip-chars-forward " \r\t\n")
24466 (or (eobp) (beginning-of-line)))
24467 ;; On affiliated keywords, move to element's beginning.
24468 ((< (point) post-affiliated)
24469 (goto-char post-affiliated))
24470 ;; At a table row, move to the end of the table. Similarly,
24471 ;; at a node property, move to the end of the property
24472 ;; drawer.
24473 ((memq type '(node-property table-row))
24474 (goto-char (org-element-property
24475 :end (org-element-property :parent element))))
24476 ((memq type '(property-drawer table)) (goto-char end))
24477 ;; Consider blank lines as separators in verse and source
24478 ;; blocks to ease editing.
24479 ((memq type '(src-block verse-block))
24480 (when (eq type 'src-block)
24481 (setq contents-end
24482 (save-excursion (goto-char end)
24483 (skip-chars-backward " \r\t\n")
24484 (line-beginning-position))))
24485 (beginning-of-line)
24486 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24487 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24488 (goto-char end)
24489 (skip-chars-forward " \r\t\n")
24490 (if (= (point) contents-end) (goto-char end)
24491 (beginning-of-line))))
24492 ;; With no contents, just skip element.
24493 ((not contents-begin) (goto-char end))
24494 ;; If contents are invisible, skip the element altogether.
24495 ((outline-invisible-p (line-end-position))
24496 (cl-case type
24497 (headline
24498 (org-with-limited-levels (outline-next-visible-heading 1)))
24499 ;; At a plain list, make sure we move to the next item
24500 ;; instead of skipping the whole list.
24501 (plain-list (forward-char)
24502 (org-forward-paragraph))
24503 (otherwise (goto-char end))))
24504 ((>= (point) contents-end) (goto-char end))
24505 ((>= (point) contents-begin)
24506 ;; This can only happen on paragraphs and plain lists.
24507 (cl-case type
24508 (paragraph (goto-char end))
24509 ;; At a plain list, try to move to second element in
24510 ;; first item, if possible.
24511 (plain-list (end-of-line)
24512 (org-forward-paragraph))))
24513 ;; When contents start on the middle of a line (e.g. in
24514 ;; items and footnote definitions), try to reach first
24515 ;; element starting after current line.
24516 ((> (line-end-position) contents-begin)
24517 (end-of-line)
24518 (org-forward-paragraph))
24519 (t (goto-char contents-begin)))))
24521 (defun org-backward-paragraph ()
24522 "Move backward to start of previous paragraph or equivalent.
24524 The function moves point to the beginning of the current
24525 structural element, which can be a paragraph, a table, a list
24526 item, etc., or to the beginning of the previous visible one if
24527 point is already there. It also provides some special moves for
24528 convenience:
24530 - On an affiliated keyword, jump to the first one.
24531 - On a table or a property drawer, move to its beginning.
24532 - On a verse or source block, stop before blank lines."
24533 (interactive)
24534 (when (bobp) (user-error "Cannot move further up"))
24535 (let* ((deactivate-mark nil)
24536 (element (org-element-at-point))
24537 (type (org-element-type element))
24538 (contents-begin (org-element-property :contents-begin element))
24539 (contents-end (org-element-property :contents-end element))
24540 (post-affiliated (org-element-property :post-affiliated element))
24541 (begin (org-element-property :begin element)))
24542 (cond
24543 ((not element) (goto-char (point-min)))
24544 ((= (point) begin)
24545 (backward-char)
24546 (org-backward-paragraph))
24547 ((<= (point) post-affiliated) (goto-char begin))
24548 ((memq type '(node-property table-row))
24549 (goto-char (org-element-property
24550 :post-affiliated (org-element-property :parent element))))
24551 ((memq type '(property-drawer table)) (goto-char begin))
24552 ((memq type '(src-block verse-block))
24553 (when (eq type 'src-block)
24554 (setq contents-begin
24555 (save-excursion (goto-char begin) (forward-line) (point))))
24556 (if (= (point) contents-begin) (goto-char post-affiliated)
24557 ;; Inside a verse block, see blank lines as paragraph
24558 ;; separators.
24559 (let ((origin (point)))
24560 (skip-chars-backward " \r\t\n" contents-begin)
24561 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24562 (skip-chars-forward " \r\t\n" origin)
24563 (if (= (point) origin) (goto-char contents-begin)
24564 (beginning-of-line))))))
24565 ((not contents-begin) (goto-char (or post-affiliated begin)))
24566 ((eq type 'paragraph)
24567 (goto-char contents-begin)
24568 ;; When at first paragraph in an item or a footnote definition,
24569 ;; move directly to beginning of line.
24570 (let ((parent-contents
24571 (org-element-property
24572 :contents-begin (org-element-property :parent element))))
24573 (when (and parent-contents (= parent-contents contents-begin))
24574 (beginning-of-line))))
24575 ;; At the end of a greater element, move to the beginning of the
24576 ;; last element within.
24577 ((>= (point) contents-end)
24578 (goto-char (1- contents-end))
24579 (org-backward-paragraph))
24580 (t (goto-char (or post-affiliated begin))))
24581 ;; Ensure we never leave point invisible.
24582 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24584 (defun org-forward-element ()
24585 "Move forward by one element.
24586 Move to the next element at the same level, when possible."
24587 (interactive)
24588 (cond ((eobp) (user-error "Cannot move further down"))
24589 ((org-with-limited-levels (org-at-heading-p))
24590 (let ((origin (point)))
24591 (goto-char (org-end-of-subtree nil t))
24592 (unless (org-with-limited-levels (org-at-heading-p))
24593 (goto-char origin)
24594 (user-error "Cannot move further down"))))
24596 (let* ((elem (org-element-at-point))
24597 (end (org-element-property :end elem))
24598 (parent (org-element-property :parent elem)))
24599 (cond ((and parent (= (org-element-property :contents-end parent) end))
24600 (goto-char (org-element-property :end parent)))
24601 ((integer-or-marker-p end) (goto-char end))
24602 (t (message "No element at point")))))))
24604 (defun org-backward-element ()
24605 "Move backward by one element.
24606 Move to the previous element at the same level, when possible."
24607 (interactive)
24608 (cond ((bobp) (user-error "Cannot move further up"))
24609 ((org-with-limited-levels (org-at-heading-p))
24610 ;; At a headline, move to the previous one, if any, or stay
24611 ;; here.
24612 (let ((origin (point)))
24613 (org-with-limited-levels (org-backward-heading-same-level 1))
24614 ;; When current headline has no sibling above, move to its
24615 ;; parent.
24616 (when (= (point) origin)
24617 (or (org-with-limited-levels (org-up-heading-safe))
24618 (progn (goto-char origin)
24619 (user-error "Cannot move further up"))))))
24621 (let* ((elem (org-element-at-point))
24622 (beg (org-element-property :begin elem)))
24623 (cond
24624 ;; Move to beginning of current element if point isn't
24625 ;; there already.
24626 ((null beg) (message "No element at point"))
24627 ((/= (point) beg) (goto-char beg))
24628 (t (goto-char beg)
24629 (skip-chars-backward " \r\t\n")
24630 (unless (bobp)
24631 (let ((prev (org-element-at-point)))
24632 (goto-char (org-element-property :begin prev))
24633 (while (and (setq prev (org-element-property :parent prev))
24634 (<= (org-element-property :end prev) beg))
24635 (goto-char (org-element-property :begin prev)))))))))))
24637 (defun org-up-element ()
24638 "Move to upper element."
24639 (interactive)
24640 (if (org-with-limited-levels (org-at-heading-p))
24641 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24642 (let* ((elem (org-element-at-point))
24643 (parent (org-element-property :parent elem)))
24644 (if parent (goto-char (org-element-property :begin parent))
24645 (if (org-with-limited-levels (org-before-first-heading-p))
24646 (user-error "No surrounding element")
24647 (org-with-limited-levels (org-back-to-heading)))))))
24649 (defvar org-element-greater-elements)
24650 (defun org-down-element ()
24651 "Move to inner element."
24652 (interactive)
24653 (let ((element (org-element-at-point)))
24654 (cond
24655 ((memq (org-element-type element) '(plain-list table))
24656 (goto-char (org-element-property :contents-begin element))
24657 (forward-char))
24658 ((memq (org-element-type element) org-element-greater-elements)
24659 ;; If contents are hidden, first disclose them.
24660 (when (outline-invisible-p (line-end-position)) (org-cycle))
24661 (goto-char (or (org-element-property :contents-begin element)
24662 (user-error "No content for this element"))))
24663 (t (user-error "No inner element")))))
24665 (defun org-drag-element-backward ()
24666 "Move backward element at point."
24667 (interactive)
24668 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24669 (let* ((elem (org-element-at-point))
24670 (prev-elem
24671 (save-excursion
24672 (goto-char (org-element-property :begin elem))
24673 (skip-chars-backward " \r\t\n")
24674 (unless (bobp)
24675 (let* ((beg (org-element-property :begin elem))
24676 (prev (org-element-at-point))
24677 (up prev))
24678 (while (and (setq up (org-element-property :parent up))
24679 (<= (org-element-property :end up) beg))
24680 (setq prev up))
24681 prev)))))
24682 ;; Error out if no previous element or previous element is
24683 ;; a parent of the current one.
24684 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24685 (user-error "Cannot drag element backward")
24686 (let ((pos (point)))
24687 (org-element-swap-A-B prev-elem elem)
24688 (goto-char (+ (org-element-property :begin prev-elem)
24689 (- pos (org-element-property :begin elem)))))))))
24691 (defun org-drag-element-forward ()
24692 "Move forward element at point."
24693 (interactive)
24694 (let* ((pos (point))
24695 (elem (org-element-at-point)))
24696 (when (= (point-max) (org-element-property :end elem))
24697 (user-error "Cannot drag element forward"))
24698 (goto-char (org-element-property :end elem))
24699 (let ((next-elem (org-element-at-point)))
24700 (when (or (org-element-nested-p elem next-elem)
24701 (and (eq (org-element-type next-elem) 'headline)
24702 (not (eq (org-element-type elem) 'headline))))
24703 (goto-char pos)
24704 (user-error "Cannot drag element forward"))
24705 ;; Compute new position of point: it's shifted by NEXT-ELEM
24706 ;; body's length (without final blanks) and by the length of
24707 ;; blanks between ELEM and NEXT-ELEM.
24708 (let ((size-next (- (save-excursion
24709 (goto-char (org-element-property :end next-elem))
24710 (skip-chars-backward " \r\t\n")
24711 (forward-line)
24712 ;; Small correction if buffer doesn't end
24713 ;; with a newline character.
24714 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24715 (org-element-property :begin next-elem)))
24716 (size-blank (- (org-element-property :end elem)
24717 (save-excursion
24718 (goto-char (org-element-property :end elem))
24719 (skip-chars-backward " \r\t\n")
24720 (forward-line)
24721 (point)))))
24722 (org-element-swap-A-B elem next-elem)
24723 (goto-char (+ pos size-next size-blank))))))
24725 (defun org-drag-line-forward (arg)
24726 "Drag the line at point ARG lines forward."
24727 (interactive "p")
24728 (dotimes (_ (abs arg))
24729 (let ((c (current-column)))
24730 (if (< 0 arg)
24731 (progn
24732 (beginning-of-line 2)
24733 (transpose-lines 1)
24734 (beginning-of-line 0))
24735 (transpose-lines 1)
24736 (beginning-of-line -1))
24737 (org-move-to-column c))))
24739 (defun org-drag-line-backward (arg)
24740 "Drag the line at point ARG lines backward."
24741 (interactive "p")
24742 (org-drag-line-forward (- arg)))
24744 (defun org-mark-element ()
24745 "Put point at beginning of this element, mark at end.
24747 Interactively, if this command is repeated or (in Transient Mark
24748 mode) if the mark is active, it marks the next element after the
24749 ones already marked."
24750 (interactive)
24751 (let (deactivate-mark)
24752 (if (and (called-interactively-p 'any)
24753 (or (and (eq last-command this-command) (mark t))
24754 (and transient-mark-mode mark-active)))
24755 (set-mark
24756 (save-excursion
24757 (goto-char (mark))
24758 (goto-char (org-element-property :end (org-element-at-point)))))
24759 (let ((element (org-element-at-point)))
24760 (end-of-line)
24761 (push-mark (org-element-property :end element) t t)
24762 (goto-char (org-element-property :begin element))))))
24764 (defun org-narrow-to-element ()
24765 "Narrow buffer to current element."
24766 (interactive)
24767 (let ((elem (org-element-at-point)))
24768 (cond
24769 ((eq (car elem) 'headline)
24770 (narrow-to-region
24771 (org-element-property :begin elem)
24772 (org-element-property :end elem)))
24773 ((memq (car elem) org-element-greater-elements)
24774 (narrow-to-region
24775 (org-element-property :contents-begin elem)
24776 (org-element-property :contents-end elem)))
24778 (narrow-to-region
24779 (org-element-property :begin elem)
24780 (org-element-property :end elem))))))
24782 (defun org-transpose-element ()
24783 "Transpose current and previous elements, keeping blank lines between.
24784 Point is moved after both elements."
24785 (interactive)
24786 (org-skip-whitespace)
24787 (let ((end (org-element-property :end (org-element-at-point))))
24788 (org-drag-element-backward)
24789 (goto-char end)))
24791 (defun org-unindent-buffer ()
24792 "Un-indent the visible part of the buffer.
24793 Relative indentation (between items, inside blocks, etc.) isn't
24794 modified."
24795 (interactive)
24796 (unless (eq major-mode 'org-mode)
24797 (user-error "Cannot un-indent a buffer not in Org mode"))
24798 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24799 (unindent-tree
24800 (lambda (contents)
24801 (dolist (element (reverse contents))
24802 (if (memq (org-element-type element) '(headline section))
24803 (funcall unindent-tree (org-element-contents element))
24804 (save-excursion
24805 (save-restriction
24806 (narrow-to-region
24807 (org-element-property :begin element)
24808 (org-element-property :end element))
24809 (org-do-remove-indentation))))))))
24810 (funcall unindent-tree (org-element-contents parse-tree))))
24812 (defun org-show-children (&optional level)
24813 "Show all direct subheadings of this heading.
24814 Prefix arg LEVEL is how many levels below the current level
24815 should be shown. Default is enough to cause the following
24816 heading to appear."
24817 (interactive "p")
24818 ;; If `orgstruct-mode' is active, use the slower version.
24819 (if orgstruct-mode (call-interactively #'outline-show-children)
24820 (save-excursion
24821 (org-back-to-heading t)
24822 (let* ((current-level (funcall outline-level))
24823 (max-level (org-get-valid-level
24824 current-level
24825 (if level (prefix-numeric-value level) 1)))
24826 (end (save-excursion (org-end-of-subtree t t)))
24827 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24828 (past-first-child nil)
24829 ;; Make sure to skip inlinetasks.
24830 (re (format regexp-fmt
24831 current-level
24832 (cond
24833 ((not (featurep 'org-inlinetask)) "")
24834 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24836 (t (1- org-inlinetask-min-level))))))
24837 ;; Display parent heading.
24838 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24839 (forward-line)
24840 ;; Display children. First child may be deeper than expected
24841 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24842 ;; MAX-LEVEL accordingly.
24843 (while (re-search-forward re end t)
24844 (unless past-first-child
24845 (setq re (format regexp-fmt
24846 current-level
24847 (max (funcall outline-level) max-level)))
24848 (setq past-first-child t))
24849 (outline-flag-region
24850 (line-end-position 0) (line-end-position) nil))))))
24852 (defun org-show-subtree ()
24853 "Show everything after this heading at deeper levels."
24854 (interactive)
24855 (outline-flag-region
24856 (point)
24857 (save-excursion
24858 (org-end-of-subtree t t))
24859 nil))
24861 (defun org-show-entry ()
24862 "Show the body directly following this heading.
24863 Show the heading too, if it is currently invisible."
24864 (interactive)
24865 (save-excursion
24866 (ignore-errors
24867 (org-back-to-heading t)
24868 (outline-flag-region
24869 (max (point-min) (1- (point)))
24870 (save-excursion
24871 (if (re-search-forward
24872 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24873 (match-beginning 1)
24874 (point-max)))
24875 nil)
24876 (org-cycle-hide-drawers 'children))))
24878 (defun org-make-options-regexp (kwds &optional extra)
24879 "Make a regular expression for keyword lines.
24880 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24881 when non-nil, is a regexp matching keywords names."
24882 (concat "^[ \t]*#\\+\\("
24883 (regexp-opt kwds)
24884 (and extra (concat (and kwds "\\|") extra))
24885 "\\):[ \t]*\\(.*\\)"))
24887 ;;;; Integration with and fixes for other packages
24889 ;;; Imenu support
24891 (defvar-local org-imenu-markers nil
24892 "All markers currently used by Imenu.")
24894 (defun org-imenu-new-marker (&optional pos)
24895 "Return a new marker for use by Imenu, and remember the marker."
24896 (let ((m (make-marker)))
24897 (move-marker m (or pos (point)))
24898 (push m org-imenu-markers)
24901 (defun org-imenu-get-tree ()
24902 "Produce the index for Imenu."
24903 (dolist (x org-imenu-markers) (move-marker x nil))
24904 (setq org-imenu-markers nil)
24905 (let* ((case-fold-search nil)
24906 (n org-imenu-depth)
24907 (re (concat "^" (org-get-limited-outline-regexp)))
24908 (subs (make-vector (1+ n) nil))
24909 (last-level 0)
24910 m level head0 head)
24911 (save-excursion
24912 (save-restriction
24913 (widen)
24914 (goto-char (point-max))
24915 (while (re-search-backward re nil t)
24916 (setq level (org-reduced-level (funcall outline-level)))
24917 (when (and (<= level n)
24918 (looking-at org-complex-heading-regexp)
24919 (setq head0 (match-string-no-properties 4)))
24920 (setq head (org-link-display-format head0)
24921 m (org-imenu-new-marker))
24922 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24923 (if (>= level last-level)
24924 (push (cons head m) (aref subs level))
24925 (push (cons head (aref subs (1+ level))) (aref subs level))
24926 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24927 (setq last-level level)))))
24928 (aref subs 1)))
24930 (eval-after-load "imenu"
24931 '(progn
24932 (add-hook 'imenu-after-jump-hook
24933 (lambda ()
24934 (when (derived-mode-p 'org-mode)
24935 (org-show-context 'org-goto))))))
24937 (defun org-link-display-format (s)
24938 "Replace links in string S with their description.
24939 If there is no description, use the link target."
24940 (save-match-data
24941 (replace-regexp-in-string
24942 org-bracket-link-analytic-regexp
24943 (lambda (m)
24944 (if (match-end 5) (match-string 5 m)
24945 (concat (match-string 1 m) (match-string 3 m))))
24946 s nil t)))
24948 (defun org-toggle-link-display ()
24949 "Toggle the literal or descriptive display of links."
24950 (interactive)
24951 (if org-descriptive-links
24952 (progn (org-remove-from-invisibility-spec '(org-link))
24953 (org-restart-font-lock)
24954 (setq org-descriptive-links nil))
24955 (progn (add-to-invisibility-spec '(org-link))
24956 (org-restart-font-lock)
24957 (setq org-descriptive-links t))))
24959 ;; Speedbar support
24961 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24962 "Overlay marking the agenda restriction line in speedbar.")
24963 (overlay-put org-speedbar-restriction-lock-overlay
24964 'face 'org-agenda-restriction-lock)
24965 (overlay-put org-speedbar-restriction-lock-overlay
24966 'help-echo "Agendas are currently limited to this item.")
24967 (delete-overlay org-speedbar-restriction-lock-overlay)
24969 (defun org-speedbar-set-agenda-restriction ()
24970 "Restrict future agenda commands to the location at point in speedbar.
24971 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24972 (interactive)
24973 (require 'org-agenda)
24974 (let (p m tp np dir txt)
24975 (cond
24976 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24977 'org-imenu t))
24978 (setq m (get-text-property p 'org-imenu-marker))
24979 (with-current-buffer (marker-buffer m)
24980 (goto-char m)
24981 (org-agenda-set-restriction-lock 'subtree)))
24982 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24983 'speedbar-function 'speedbar-find-file))
24984 (setq tp (previous-single-property-change
24985 (1+ p) 'speedbar-function)
24986 np (next-single-property-change
24987 tp 'speedbar-function)
24988 dir (speedbar-line-directory)
24989 txt (buffer-substring-no-properties (or tp (point-min))
24990 (or np (point-max))))
24991 (with-current-buffer (find-file-noselect
24992 (let ((default-directory dir))
24993 (expand-file-name txt)))
24994 (unless (derived-mode-p 'org-mode)
24995 (user-error "Cannot restrict to non-Org-mode file"))
24996 (org-agenda-set-restriction-lock 'file)))
24997 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24998 (move-overlay org-speedbar-restriction-lock-overlay
24999 (point-at-bol) (point-at-eol))
25000 (setq current-prefix-arg nil)
25001 (org-agenda-maybe-redo)))
25003 (defvar speedbar-file-key-map)
25004 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25005 (eval-after-load "speedbar"
25006 '(progn
25007 (speedbar-add-supported-extension ".org")
25008 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25009 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25010 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25011 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25012 (add-hook 'speedbar-visiting-tag-hook
25013 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25015 ;;; Fixes and Hacks for problems with other packages
25017 (defun org--flyspell-object-check-p (element)
25018 "Non-nil when Flyspell can check object at point.
25019 ELEMENT is the element at point."
25020 (let ((object (save-excursion
25021 (when (looking-at-p "\\>") (backward-char))
25022 (org-element-context element))))
25023 (cl-case (org-element-type object)
25024 ;; Prevent checks in links due to keybinding conflict with
25025 ;; Flyspell.
25026 ((code entity export-snippet inline-babel-call
25027 inline-src-block line-break latex-fragment link macro
25028 statistics-cookie target timestamp verbatim)
25029 nil)
25030 (footnote-reference
25031 ;; Only in inline footnotes, within the definition.
25032 (and (eq (org-element-property :type object) 'inline)
25033 (< (save-excursion
25034 (goto-char (org-element-property :begin object))
25035 (search-forward ":" nil t 2))
25036 (point))))
25037 (otherwise t))))
25039 (defun org-mode-flyspell-verify ()
25040 "Function used for `flyspell-generic-check-word-predicate'."
25041 (if (org-at-heading-p)
25042 ;; At a headline or an inlinetask, check title only. This is
25043 ;; faster than relying on `org-element-at-point'.
25044 (and (save-excursion (beginning-of-line)
25045 (and (let ((case-fold-search t))
25046 (not (looking-at "\\*+ END[ \t]*$")))
25047 (looking-at org-complex-heading-regexp)))
25048 (match-beginning 4)
25049 (>= (point) (match-beginning 4))
25050 (or (not (match-beginning 5))
25051 (< (point) (match-beginning 5))))
25052 (let* ((element (org-element-at-point))
25053 (post-affiliated (org-element-property :post-affiliated element)))
25054 (cond
25055 ;; Ignore checks in all affiliated keywords but captions.
25056 ((< (point) post-affiliated)
25057 (and (save-excursion
25058 (beginning-of-line)
25059 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25060 (> (point) (match-end 0))
25061 (org--flyspell-object-check-p element)))
25062 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25063 ((let ((log (org-log-into-drawer)))
25064 (and log
25065 (let ((drawer (org-element-lineage element '(drawer))))
25066 (and drawer
25067 (eq (compare-strings
25068 log nil nil
25069 (org-element-property :drawer-name drawer) nil nil t)
25070 t)))))
25071 nil)
25073 (cl-case (org-element-type element)
25074 ((comment quote-section) t)
25075 (comment-block
25076 ;; Allow checks between block markers, not on them.
25077 (and (> (line-beginning-position) post-affiliated)
25078 (save-excursion
25079 (end-of-line)
25080 (skip-chars-forward " \r\t\n")
25081 (< (point) (org-element-property :end element)))))
25082 ;; Arbitrary list of keywords where checks are meaningful.
25083 ;; Make sure point is on the value part of the element.
25084 (keyword
25085 (and (member (org-element-property :key element)
25086 '("DESCRIPTION" "TITLE"))
25087 (save-excursion
25088 (search-backward ":" (line-beginning-position) t))))
25089 ;; Check is globally allowed in paragraphs verse blocks and
25090 ;; table rows (after affiliated keywords) but some objects
25091 ;; must not be affected.
25092 ((paragraph table-row verse-block)
25093 (let ((cbeg (org-element-property :contents-begin element))
25094 (cend (org-element-property :contents-end element)))
25095 (and cbeg (>= (point) cbeg) (< (point) cend)
25096 (org--flyspell-object-check-p element))))))))))
25097 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25099 (defun org-remove-flyspell-overlays-in (beg end)
25100 "Remove flyspell overlays in region."
25101 (and (bound-and-true-p flyspell-mode)
25102 (fboundp 'flyspell-delete-region-overlays)
25103 (flyspell-delete-region-overlays beg end)))
25105 (defvar flyspell-delayed-commands)
25106 (eval-after-load "flyspell"
25107 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25109 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25110 (eval-after-load "bookmark"
25111 '(if (boundp 'bookmark-after-jump-hook)
25112 ;; We can use the hook
25113 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25114 ;; Hook not available, use advice
25115 (defadvice bookmark-jump (after org-make-visible activate)
25116 "Make the position visible."
25117 (org-bookmark-jump-unhide))))
25119 ;; Make sure saveplace shows the location if it was hidden
25120 (eval-after-load "saveplace"
25121 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25122 "Make the position visible."
25123 (org-bookmark-jump-unhide)))
25125 ;; Make sure ecb shows the location if it was hidden
25126 (eval-after-load "ecb"
25127 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25128 "Make hierarchy visible when jumping into location from ECB tree buffer."
25129 (when (derived-mode-p 'org-mode)
25130 (org-show-context))))
25132 (defun org-bookmark-jump-unhide ()
25133 "Unhide the current position, to show the bookmark location."
25134 (and (derived-mode-p 'org-mode)
25135 (or (outline-invisible-p)
25136 (save-excursion (goto-char (max (point-min) (1- (point))))
25137 (outline-invisible-p)))
25138 (org-show-context 'bookmark-jump)))
25140 (defun org-mark-jump-unhide ()
25141 "Make the point visible with `org-show-context' after jumping to the mark."
25142 (when (and (derived-mode-p 'org-mode)
25143 (outline-invisible-p))
25144 (org-show-context 'mark-goto)))
25146 (eval-after-load "simple"
25147 '(defadvice pop-to-mark-command (after org-make-visible activate)
25148 "Make the point visible with `org-show-context'."
25149 (org-mark-jump-unhide)))
25151 (eval-after-load "simple"
25152 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25153 "Make the point visible with `org-show-context'."
25154 (org-mark-jump-unhide)))
25156 (eval-after-load "simple"
25157 '(defadvice pop-global-mark (after org-make-visible activate)
25158 "Make the point visible with `org-show-context'."
25159 (org-mark-jump-unhide)))
25161 ;; Make session.el ignore our circular variable
25162 (defvar session-globals-exclude)
25163 (eval-after-load "session"
25164 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25166 ;;;; Finish up
25168 (provide 'org)
25170 (run-hooks 'org-load-hook)
25172 ;;; org.el ends here