org-src: Move function within library
[org-mode/org-tableheadings.git] / lisp / org.el
blob483bea12e98443eab587c2db4d51d9cb9f5a4d53
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 (org-with-limited-levels
9898 (setq org-store-link-plist nil)
9899 (let (link cpltxt desc description search
9900 txt custom-id agenda-link sfuns sfunsn)
9901 (cond
9903 ;; Store a link using an external link type
9904 ((and (not (equal arg '(16)))
9905 (setq sfuns
9906 (delq
9907 nil (mapcar (lambda (f)
9908 (let (fs) (if (funcall f) (push f fs))))
9909 (org-store-link-functions)))
9910 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9911 (or (and (cdr sfuns)
9912 (funcall (intern
9913 (completing-read
9914 "Which function for creating the link? "
9915 sfunsn nil t (car sfunsn)))))
9916 (funcall (caar sfuns)))
9917 (setq link (plist-get org-store-link-plist :link)
9918 desc (or (plist-get org-store-link-plist
9919 :description)
9920 link))))
9922 ;; Store a link from a source code buffer.
9923 ((org-src-edit-buffer-p)
9924 (cond
9925 ((save-excursion
9926 (beginning-of-line)
9927 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9928 "[ \t]*$")))
9929 (setq link (format "(%s)" (match-string-no-properties 1))))
9930 ((called-interactively-p 'any)
9931 (let (label)
9932 (while (or (not label)
9933 (org-with-wide-buffer
9934 (goto-char (point-min))
9935 (re-search-forward
9936 (regexp-quote (format org-coderef-label-format label))
9937 nil t)))
9938 (when label (message "Label exists already") (sit-for 2))
9939 (setq label (read-string "Code line label: " label)))
9940 (end-of-line)
9941 (setq link (format org-coderef-label-format label))
9942 (let ((gc (- 79 (length link))))
9943 (if (< (current-column) gc) (org-move-to-column gc t)
9944 (insert " ")))
9945 (insert link)
9946 (setq link (concat "(" label ")") desc nil)))
9947 (t (setq link nil))))
9949 ;; We are in the agenda, link to referenced location
9950 ((equal (bound-and-true-p org-agenda-buffer-name) (buffer-name))
9951 (let ((m (or (get-text-property (point) 'org-hd-marker)
9952 (get-text-property (point) 'org-marker))))
9953 (when m
9954 (org-with-point-at m
9955 (setq agenda-link
9956 (if (called-interactively-p 'any)
9957 (call-interactively 'org-store-link)
9958 (org-store-link nil)))))))
9960 ((eq major-mode 'calendar-mode)
9961 (let ((cd (calendar-cursor-to-date)))
9962 (setq link
9963 (format-time-string
9964 (car org-time-stamp-formats)
9965 (apply 'encode-time
9966 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9967 nil nil nil))))
9968 (org-store-link-props :type "calendar" :date cd)))
9970 ((eq major-mode 'help-mode)
9971 (setq link (concat "help:" (save-excursion
9972 (goto-char (point-min))
9973 (looking-at "^[^ ]+")
9974 (match-string 0))))
9975 (org-store-link-props :type "help"))
9977 ((eq major-mode 'w3-mode)
9978 (setq cpltxt (if (and (buffer-name)
9979 (not (string-match "Untitled" (buffer-name))))
9980 (buffer-name)
9981 (url-view-url t))
9982 link (url-view-url t))
9983 (org-store-link-props :type "w3" :url (url-view-url t)))
9985 ((eq major-mode 'image-mode)
9986 (setq cpltxt (concat "file:"
9987 (abbreviate-file-name buffer-file-name))
9988 link cpltxt)
9989 (org-store-link-props :type "image" :file buffer-file-name))
9991 ;; In dired, store a link to the file of the current line
9992 ((derived-mode-p 'dired-mode)
9993 (let ((file (dired-get-filename nil t)))
9994 (setq file (if file
9995 (abbreviate-file-name
9996 (expand-file-name (dired-get-filename nil t)))
9997 ;; otherwise, no file so use current directory.
9998 default-directory))
9999 (setq cpltxt (concat "file:" file)
10000 link cpltxt)))
10002 ((setq search (run-hook-with-args-until-success
10003 'org-create-file-search-functions))
10004 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10005 "::" search))
10006 (setq cpltxt (or description link)))
10008 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
10009 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
10010 (cond
10011 ;; Store a link using the target at point
10012 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
10013 (setq cpltxt
10014 (concat "file:"
10015 (abbreviate-file-name
10016 (buffer-file-name (buffer-base-buffer)))
10017 "::" (match-string 1))
10018 link cpltxt))
10019 ((and (featurep 'org-id)
10020 (or (eq org-id-link-to-org-use-id t)
10021 (and (called-interactively-p 'any)
10022 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
10023 (and (eq org-id-link-to-org-use-id
10024 'create-if-interactive-and-no-custom-id)
10025 (not custom-id))))
10026 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
10027 ;; Store a link using the ID at point
10028 (setq link (condition-case nil
10029 (prog1 (org-id-store-link)
10030 (setq desc (or (plist-get org-store-link-plist
10031 :description)
10032 "")))
10033 (error
10034 ;; Probably before first headline, link only to file
10035 (concat "file:"
10036 (abbreviate-file-name
10037 (buffer-file-name (buffer-base-buffer))))))))
10039 ;; Just link to current headline
10040 (setq cpltxt (concat "file:"
10041 (abbreviate-file-name
10042 (buffer-file-name (buffer-base-buffer)))))
10043 ;; Add a context search string
10044 (when (org-xor org-context-in-file-links arg)
10045 (let* ((element (org-element-at-point))
10046 (name (org-element-property :name element)))
10047 (setq txt (cond
10048 ((org-at-heading-p) nil)
10049 (name)
10050 ((org-region-active-p)
10051 (buffer-substring (region-beginning) (region-end)))))
10052 (when (or (null txt) (string-match "\\S-" txt))
10053 (setq cpltxt
10054 (concat cpltxt "::"
10055 (condition-case nil
10056 (org-make-org-heading-search-string txt)
10057 (error "")))
10058 desc (or name
10059 (nth 4 (ignore-errors (org-heading-components)))
10060 "NONE")))))
10061 (when (string-match "::\\'" cpltxt)
10062 (setq cpltxt (substring cpltxt 0 -2)))
10063 (setq link cpltxt))))
10065 ((buffer-file-name (buffer-base-buffer))
10066 ;; Just link to this file here.
10067 (setq cpltxt (concat "file:"
10068 (abbreviate-file-name
10069 (buffer-file-name (buffer-base-buffer)))))
10070 ;; Add a context string.
10071 (when (org-xor org-context-in-file-links arg)
10072 (setq txt (if (org-region-active-p)
10073 (buffer-substring (region-beginning) (region-end))
10074 (buffer-substring (point-at-bol) (point-at-eol))))
10075 ;; Only use search option if there is some text.
10076 (when (string-match "\\S-" txt)
10077 (setq cpltxt
10078 (concat cpltxt "::" (org-make-org-heading-search-string txt))
10079 desc "NONE")))
10080 (setq link cpltxt))
10082 ((called-interactively-p 'interactive)
10083 (user-error "No method for storing a link from this buffer"))
10085 (t (setq link nil)))
10087 ;; We're done setting link and desc, clean up
10088 (when (consp link) (setq cpltxt (car link) link (cdr link)))
10089 (setq link (or link cpltxt)
10090 desc (or desc cpltxt))
10091 (cond ((not desc))
10092 ((equal desc "NONE") (setq desc nil))
10093 (t (setq desc
10094 (replace-regexp-in-string
10095 org-bracket-link-analytic-regexp
10096 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
10097 desc))))
10098 ;; Return the link
10099 (if (not (and (or (called-interactively-p 'any)
10100 executing-kbd-macro)
10101 link))
10102 (or agenda-link (and link (org-make-link-string link desc)))
10103 (push (list link desc) org-stored-links)
10104 (message "Stored: %s" (or desc link))
10105 (when custom-id
10106 (setq link (concat "file:" (abbreviate-file-name
10107 (buffer-file-name)) "::#" custom-id))
10108 (push (list link desc) org-stored-links))
10109 (car org-stored-links))))))
10111 (defun org-store-link-props (&rest plist)
10112 "Store link properties, extract names, addresses and dates."
10113 (let ((x (plist-get plist :from)))
10114 (when x
10115 (let ((adr (mail-extract-address-components x)))
10116 (setq plist (plist-put plist :fromname (car adr)))
10117 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10118 (let ((x (plist-get plist :to)))
10119 (when x
10120 (let ((adr (mail-extract-address-components x)))
10121 (setq plist (plist-put plist :toname (car adr)))
10122 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10123 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10124 (when x
10125 (setq plist (plist-put plist :date-timestamp
10126 (format-time-string
10127 (org-time-stamp-format t) x)))
10128 (setq plist (plist-put plist :date-timestamp-inactive
10129 (format-time-string
10130 (org-time-stamp-format t t) x)))))
10131 (let ((from (plist-get plist :from))
10132 (to (plist-get plist :to)))
10133 (when (and from to org-from-is-user-regexp)
10134 (setq plist
10135 (plist-put plist :fromto
10136 (if (string-match org-from-is-user-regexp from)
10137 (concat "to %t")
10138 (concat "from %f"))))))
10139 (setq org-store-link-plist plist))
10141 (defun org-add-link-props (&rest plist)
10142 "Add these properties to the link property list."
10143 (let (key value)
10144 (while plist
10145 (setq key (pop plist) value (pop plist))
10146 (setq org-store-link-plist
10147 (plist-put org-store-link-plist key value)))))
10149 (defun org-email-link-description (&optional fmt)
10150 "Return the description part of an email link.
10151 This takes information from `org-store-link-plist' and formats it
10152 according to FMT (default from `org-email-link-description-format')."
10153 (setq fmt (or fmt org-email-link-description-format))
10154 (let* ((p org-store-link-plist)
10155 (to (plist-get p :toaddress))
10156 (from (plist-get p :fromaddress))
10157 (table
10158 (list
10159 (cons "%c" (plist-get p :fromto))
10160 (cons "%F" (plist-get p :from))
10161 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10162 (cons "%T" (plist-get p :to))
10163 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10164 (cons "%s" (plist-get p :subject))
10165 (cons "%d" (plist-get p :date))
10166 (cons "%m" (plist-get p :message-id)))))
10167 (when (string-match "%c" fmt)
10168 ;; Check if the user wrote this message
10169 (if (and org-from-is-user-regexp from to
10170 (save-match-data (string-match org-from-is-user-regexp from)))
10171 (setq fmt (replace-match "to %t" t t fmt))
10172 (setq fmt (replace-match "from %f" t t fmt))))
10173 (org-replace-escapes fmt table)))
10175 (defun org-make-org-heading-search-string (&optional string)
10176 "Make search string for the current headline or STRING."
10177 (let ((s (or string
10178 (and (derived-mode-p 'org-mode)
10179 (save-excursion
10180 (org-back-to-heading t)
10181 (org-element-property :raw-value (org-element-at-point))))))
10182 (lines org-context-in-file-links))
10183 (or string (setq s (concat "*" s))) ; Add * for headlines
10184 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10185 (when (and string (integerp lines) (> lines 0))
10186 (let ((slines (org-split-string s "\n")))
10187 (when (< lines (length slines))
10188 (setq s (mapconcat
10189 'identity
10190 (reverse (nthcdr (- (length slines) lines)
10191 (reverse slines))) "\n")))))
10192 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10194 (defun org-make-link-string (link &optional description)
10195 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10196 (unless (org-string-nw-p link) (error "Empty link"))
10197 (let ((uri (cond ((string-match org-link-types-re link)
10198 (concat (match-string 1 link)
10199 (org-link-escape (substring link (match-end 1)))))
10200 ;; For readability, url-encode internal links only
10201 ;; when absolutely needed (i.e, when they contain
10202 ;; square brackets). File links however, are
10203 ;; encoded since, e.g., spaces are significant.
10204 ((or (file-name-absolute-p link)
10205 (string-match-p "\\`\\.\\.?/\\|[][]" link))
10206 (org-link-escape link))
10207 (t link)))
10208 (description
10209 (and (org-string-nw-p description)
10210 ;; Remove brackets from description, as they are fatal.
10211 (replace-regexp-in-string
10212 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10213 (org-trim description)))))
10214 (format "[[%s]%s]"
10216 (if description (format "[%s]" description) ""))))
10218 (defconst org-link-escape-chars
10219 ;;%20 %5B %5D %25
10220 '(?\s ?\[ ?\] ?%)
10221 "List of characters that should be escaped in a link when stored to Org.
10222 This is the list that is used for internal purposes.")
10224 (defun org-link-escape (text &optional table merge)
10225 "Return percent escaped representation of TEXT.
10226 TEXT is a string with the text to escape.
10227 Optional argument TABLE is a list with characters that should be
10228 escaped. When nil, `org-link-escape-chars' is used.
10229 If optional argument MERGE is set, merge TABLE into
10230 `org-link-escape-chars'."
10231 (let ((characters-to-encode
10232 (cond ((null table) org-link-escape-chars)
10233 (merge (append org-link-escape-chars table))
10234 (t table))))
10235 (mapconcat
10236 (lambda (c)
10237 (if (or (memq c characters-to-encode)
10238 (and org-url-hexify-p (or (< c 32) (> c 126))))
10239 (mapconcat (lambda (e) (format "%%%.2X" e))
10240 (or (encode-coding-char c 'utf-8)
10241 (error "Unable to percent escape character: %c" c))
10243 (char-to-string c)))
10244 text "")))
10246 (defun org-link-unescape (str)
10247 "Unhex hexified Unicode parts in string STR.
10248 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10249 reciprocal of `org-link-escape', which see."
10250 (if (org-string-nw-p str)
10251 (replace-regexp-in-string
10252 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10253 str))
10255 (defun org-link-unescape-compound (hex)
10256 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10257 Note: this function also decodes single byte encodings like
10258 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10259 (save-match-data
10260 (let* ((bytes (cdr (split-string hex "%")))
10261 (ret "")
10262 (eat 0)
10263 (sum 0))
10264 (while bytes
10265 (let* ((val (string-to-number (pop bytes) 16))
10266 (shift-xor
10267 (if (= 0 eat)
10268 (cond
10269 ((>= val 252) (cons 6 252))
10270 ((>= val 248) (cons 5 248))
10271 ((>= val 240) (cons 4 240))
10272 ((>= val 224) (cons 3 224))
10273 ((>= val 192) (cons 2 192))
10274 (t (cons 0 0)))
10275 (cons 6 128))))
10276 (when (>= val 192) (setq eat (car shift-xor)))
10277 (setq val (logxor val (cdr shift-xor)))
10278 (setq sum (+ (lsh sum (car shift-xor)) val))
10279 (when (> eat 0) (setq eat (- eat 1)))
10280 (cond
10281 ((= 0 eat) ;multi byte
10282 (setq ret (concat ret (char-to-string sum)))
10283 (setq sum 0))
10284 ((not bytes) ; single byte(s)
10285 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10286 ret)))
10288 (defun org-link-unescape-single-byte-sequence (hex)
10289 "Unhexify hex-encoded single byte character sequences."
10290 (mapconcat (lambda (byte)
10291 (char-to-string (string-to-number byte 16)))
10292 (cdr (split-string hex "%")) ""))
10294 (defun org-xor (a b)
10295 "Exclusive or."
10296 (if a (not b) b))
10298 (defun org-fixup-message-id-for-http (s)
10299 "Replace special characters in a message id, so it can be used in an http query."
10300 (when (string-match "%" s)
10301 (setq s (mapconcat (lambda (c)
10302 (if (eq c ?%)
10303 "%25"
10304 (char-to-string c)))
10305 s "")))
10306 (while (string-match "<" s)
10307 (setq s (replace-match "%3C" t t s)))
10308 (while (string-match ">" s)
10309 (setq s (replace-match "%3E" t t s)))
10310 (while (string-match "@" s)
10311 (setq s (replace-match "%40" t t s)))
10314 (defun org-link-prettify (link)
10315 "Return a human-readable representation of LINK.
10316 The car of LINK must be a raw link.
10317 The cdr of LINK must be either a link description or nil."
10318 (let ((desc (or (cadr link) "<no description>")))
10319 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10320 "<" (car link) ">")))
10322 ;;;###autoload
10323 (defun org-insert-link-global ()
10324 "Insert a link like Org-mode does.
10325 This command can be called in any mode to insert a link in Org-mode syntax."
10326 (interactive)
10327 (org-load-modules-maybe)
10328 (org-run-like-in-org-mode 'org-insert-link))
10330 (defun org-insert-all-links (arg &optional pre post)
10331 "Insert all links in `org-stored-links'.
10332 When a universal prefix, do not delete the links from `org-stored-links'.
10333 When `ARG' is a number, insert the last N link(s).
10334 `PRE' and `POST' are optional arguments to define a string to
10335 prepend or to append."
10336 (interactive "P")
10337 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10338 (links (copy-sequence org-stored-links))
10339 (pr (or pre "- "))
10340 (po (or post "\n"))
10341 (cnt 1) l)
10342 (if (null org-stored-links)
10343 (message "No link to insert")
10344 (while (and (or (listp arg) (>= arg cnt))
10345 (setq l (if (listp arg)
10346 (pop links)
10347 (pop org-stored-links))))
10348 (setq cnt (1+ cnt))
10349 (insert pr)
10350 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10351 (insert po)))))
10353 (defun org-insert-last-stored-link (arg)
10354 "Insert the last link stored in `org-stored-links'."
10355 (interactive "p")
10356 (org-insert-all-links arg "" "\n"))
10358 (defun org-link-fontify-links-to-this-file ()
10359 "Fontify links to the current file in `org-stored-links'."
10360 (let ((f (buffer-file-name)) a b)
10361 (setq a (mapcar (lambda(l)
10362 (let ((ll (car l)))
10363 (when (and (string-match "^file:\\(.+\\)::" ll)
10364 (equal f (expand-file-name (match-string 1 ll))))
10365 ll)))
10366 org-stored-links))
10367 (when (featurep 'org-id)
10368 (setq b (mapcar (lambda(l)
10369 (let ((ll (car l)))
10370 (when (and (string-match "^id:\\(.+\\)$" ll)
10371 (equal f (expand-file-name
10372 (or (org-id-find-id-file
10373 (match-string 1 ll)) ""))))
10374 ll)))
10375 org-stored-links)))
10376 (mapcar (lambda(l)
10377 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10378 (delq nil (append a b)))))
10380 (defvar org--links-history nil)
10381 (defun org-insert-link (&optional complete-file link-location default-description)
10382 "Insert a link. At the prompt, enter the link.
10384 Completion can be used to insert any of the link protocol prefixes like
10385 http or ftp in use.
10387 The history can be used to select a link previously stored with
10388 `org-store-link'. When the empty string is entered (i.e. if you just
10389 press RET at the prompt), the link defaults to the most recently
10390 stored link. As SPC triggers completion in the minibuffer, you need to
10391 use M-SPC or C-q SPC to force the insertion of a space character.
10393 You will also be prompted for a description, and if one is given, it will
10394 be displayed in the buffer instead of the link.
10396 If there is already a link at point, this command will allow you to edit link
10397 and description parts.
10399 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10400 be selected using completion. The path to the file will be relative to the
10401 current directory if the file is in the current directory or a subdirectory.
10402 Otherwise, the link will be the absolute path as completed in the minibuffer
10403 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10404 option `org-link-file-path-type'.
10406 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10407 the current directory or below.
10409 With three \\[universal-argument] prefixes, negate the meaning of
10410 `org-keep-stored-link-after-insertion'.
10412 If `org-make-link-description-function' is non-nil, this function will be
10413 called with the link target, and the result will be the default
10414 link description.
10416 If the LINK-LOCATION parameter is non-nil, this value will be
10417 used as the link location instead of reading one interactively.
10419 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10420 be used as the default description."
10421 (interactive "P")
10422 (let* ((wcf (current-window-configuration))
10423 (origbuf (current-buffer))
10424 (region (when (org-region-active-p)
10425 (buffer-substring (region-beginning) (region-end))))
10426 (remove (and region (list (region-beginning) (region-end))))
10427 (desc region)
10428 (link link-location)
10429 (abbrevs org-link-abbrev-alist-local)
10430 entry all-prefixes auto-desc)
10431 (cond
10432 (link-location) ; specified by arg, just use it.
10433 ((org-in-regexp org-bracket-link-regexp 1)
10434 ;; We do have a link at point, and we are going to edit it.
10435 (setq remove (list (match-beginning 0) (match-end 0)))
10436 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10437 (setq link (read-string "Link: "
10438 (org-link-unescape
10439 (match-string-no-properties 1)))))
10440 ((or (org-in-regexp org-angle-link-re)
10441 (org-in-regexp org-plain-link-re))
10442 ;; Convert to bracket link
10443 (setq remove (list (match-beginning 0) (match-end 0))
10444 link (read-string "Link: "
10445 (org-remove-angle-brackets (match-string 0)))))
10446 ((member complete-file '((4) (16)))
10447 ;; Completing read for file names.
10448 (setq link (org-file-complete-link complete-file)))
10450 ;; Read link, with completion for stored links.
10451 (org-link-fontify-links-to-this-file)
10452 (org-switch-to-buffer-other-window "*Org Links*")
10453 (with-current-buffer "*Org Links*"
10454 (erase-buffer)
10455 (insert "Insert a link.
10456 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10457 (when org-stored-links
10458 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10459 (insert (mapconcat 'org-link-prettify
10460 (reverse org-stored-links) "\n")))
10461 (goto-char (point-min)))
10462 (let ((cw (selected-window)))
10463 (select-window (get-buffer-window "*Org Links*" 'visible))
10464 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10465 (unless (pos-visible-in-window-p (point-max))
10466 (org-fit-window-to-buffer))
10467 (and (window-live-p cw) (select-window cw)))
10468 (setq all-prefixes (append (mapcar 'car abbrevs)
10469 (mapcar 'car org-link-abbrev-alist)
10470 (org-link-types)))
10471 (unwind-protect
10472 ;; Fake a link history, containing the stored links.
10473 (let ((org--links-history
10474 (append (mapcar #'car org-stored-links)
10475 org-insert-link-history)))
10476 (setq link
10477 (org-completing-read
10478 "Link: "
10479 (append
10480 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10481 (mapcar #'car org-stored-links))
10482 nil nil nil
10483 'org--links-history
10484 (caar org-stored-links)))
10485 (unless (org-string-nw-p link) (user-error "No link selected"))
10486 (dolist (l org-stored-links)
10487 (when (equal link (cadr l))
10488 (setq link (car l))
10489 (setq auto-desc t)))
10490 (when (or (member link all-prefixes)
10491 (and (equal ":" (substring link -1))
10492 (member (substring link 0 -1) all-prefixes)
10493 (setq link (substring link 0 -1))))
10494 (setq link (with-current-buffer origbuf
10495 (org-link-try-special-completion link)))))
10496 (set-window-configuration wcf)
10497 (kill-buffer "*Org Links*"))
10498 (setq entry (assoc link org-stored-links))
10499 (or entry (push link org-insert-link-history))
10500 (setq desc (or desc (nth 1 entry)))))
10502 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10503 (not org-keep-stored-link-after-insertion))
10504 (setq org-stored-links (delq (assoc link org-stored-links)
10505 org-stored-links)))
10507 (when (and (string-match org-plain-link-re link)
10508 (not (string-match org-ts-regexp link)))
10509 ;; URL-like link, normalize the use of angular brackets.
10510 (setq link (org-remove-angle-brackets link)))
10512 ;; Check if we are linking to the current file with a search
10513 ;; option If yes, simplify the link by using only the search
10514 ;; option.
10515 (when (and buffer-file-name
10516 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10517 (let* ((path (match-string 1 link))
10518 (case-fold-search nil)
10519 (search (match-string 2 link)))
10520 (save-match-data
10521 (when (equal (file-truename buffer-file-name) (file-truename path))
10522 ;; We are linking to this same file, with a search option
10523 (setq link search)))))
10525 ;; Check if we can/should use a relative path. If yes, simplify the link
10526 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10527 (let* ((type (match-string 1 link))
10528 (path (match-string 2 link))
10529 (origpath path)
10530 (case-fold-search nil))
10531 (cond
10532 ((or (eq org-link-file-path-type 'absolute)
10533 (equal complete-file '(16)))
10534 (setq path (abbreviate-file-name (expand-file-name path))))
10535 ((eq org-link-file-path-type 'noabbrev)
10536 (setq path (expand-file-name path)))
10537 ((eq org-link-file-path-type 'relative)
10538 (setq path (file-relative-name path)))
10540 (save-match-data
10541 (if (string-match (concat "^" (regexp-quote
10542 (expand-file-name
10543 (file-name-as-directory
10544 default-directory))))
10545 (expand-file-name path))
10546 ;; We are linking a file with relative path name.
10547 (setq path (substring (expand-file-name path)
10548 (match-end 0)))
10549 (setq path (abbreviate-file-name (expand-file-name path)))))))
10550 (setq link (concat type path))
10551 (when (equal desc origpath)
10552 (setq desc path))))
10554 (if org-make-link-description-function
10555 (setq desc
10556 (or (condition-case nil
10557 (funcall org-make-link-description-function link desc)
10558 (error (progn (message "Can't get link description from `%s'"
10559 (symbol-name org-make-link-description-function))
10560 (sit-for 2) nil)))
10561 (read-string "Description: " default-description)))
10562 (if default-description (setq desc default-description)
10563 (setq desc (or (and auto-desc desc)
10564 (read-string "Description: " desc)))))
10566 (unless (string-match "\\S-" desc) (setq desc nil))
10567 (when remove (apply 'delete-region remove))
10568 (insert (org-make-link-string link desc))
10569 ;; Redisplay so as the new link has proper invisible characters.
10570 (sit-for 0)))
10572 (defun org-link-try-special-completion (type)
10573 "If there is completion support for link type TYPE, offer it."
10574 (let ((fun (org-link-get-parameter type :complete)))
10575 (if (functionp fun)
10576 (funcall fun)
10577 (read-string "Link (no completion support): " (concat type ":")))))
10579 (defun org-file-complete-link (&optional arg)
10580 "Create a file link using completion."
10581 (let ((file (read-file-name "File: "))
10582 (pwd (file-name-as-directory (expand-file-name ".")))
10583 (pwd1 (file-name-as-directory (abbreviate-file-name
10584 (expand-file-name ".")))))
10585 (cond ((equal arg '(16))
10586 (concat "file:"
10587 (abbreviate-file-name (expand-file-name file))))
10588 ((string-match
10589 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10590 (concat "file:" (match-string 1 file)))
10591 ((string-match
10592 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10593 (expand-file-name file))
10594 (concat "file:"
10595 (match-string 1 (expand-file-name file))))
10596 (t (concat "file:" file)))))
10598 (defun org-completing-read (&rest args)
10599 "Completing-read with SPACE being a normal character."
10600 (let ((enable-recursive-minibuffers t)
10601 (minibuffer-local-completion-map
10602 (copy-keymap minibuffer-local-completion-map)))
10603 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10604 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10605 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10606 'org-time-stamp-inactive)
10607 (apply #'completing-read args)))
10609 ;;; Opening/following a link
10611 (defvar org-link-search-failed nil)
10613 (defvar org-open-link-functions nil
10614 "Hook for functions finding a plain text link.
10615 These functions must take a single argument, the link content.
10616 They will be called for links that look like [[link text][description]]
10617 when LINK TEXT does not have a protocol like \"http:\" and does not look
10618 like a filename (e.g. \"./blue.png\").
10620 These functions will be called *before* Org attempts to resolve the
10621 link by doing text searches in the current buffer - so if you want a
10622 link \"[[target]]\" to still find \"<<target>>\", your function should
10623 handle this as a special case.
10625 When the function does handle the link, it must return a non-nil value.
10626 If it decides that it is not responsible for this link, it must return
10627 nil to indicate that that Org-mode can continue with other options
10628 like exact and fuzzy text search.")
10630 (defun org-next-link (&optional search-backward)
10631 "Move forward to the next link.
10632 If the link is in hidden text, expose it."
10633 (interactive "P")
10634 (when (and org-link-search-failed (eq this-command last-command))
10635 (goto-char (point-min))
10636 (message "Link search wrapped back to beginning of buffer"))
10637 (setq org-link-search-failed nil)
10638 (let* ((pos (point))
10639 (ct (org-context))
10640 (a (assoc :link ct))
10641 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10642 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10643 ((looking-at org-any-link-re)
10644 ;; Don't stay stuck at link without an org-link face
10645 (forward-char (if search-backward -1 1))))
10646 (if (funcall srch-fun org-any-link-re nil t)
10647 (progn
10648 (goto-char (match-beginning 0))
10649 (when (outline-invisible-p) (org-show-context)))
10650 (goto-char pos)
10651 (setq org-link-search-failed t)
10652 (message "No further link found"))))
10654 (defun org-previous-link ()
10655 "Move backward to the previous link.
10656 If the link is in hidden text, expose it."
10657 (interactive)
10658 (funcall 'org-next-link t))
10660 (defun org-translate-link (s)
10661 "Translate a link string if a translation function has been defined."
10662 (with-temp-buffer
10663 (insert (org-trim s))
10664 (org-trim (org-element-interpret-data (org-element-context)))))
10666 (defun org-translate-link-from-planner (type path)
10667 "Translate a link from Emacs Planner syntax so that Org can follow it.
10668 This is still an experimental function, your mileage may vary."
10669 (cond
10670 ((member type '("http" "https" "news" "ftp"))
10671 ;; standard Internet links are the same.
10672 nil)
10673 ((and (equal type "irc") (string-match "^//" path))
10674 ;; Planner has two / at the beginning of an irc link, we have 1.
10675 ;; We should have zero, actually....
10676 (setq path (substring path 1)))
10677 ((and (equal type "lisp") (string-match "^/" path))
10678 ;; Planner has a slash, we do not.
10679 (setq type "elisp" path (substring path 1)))
10680 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10681 ;; A typical message link. Planner has the id after the final slash,
10682 ;; we separate it with a hash mark
10683 (setq path (concat (match-string 1 path) "#"
10684 (org-remove-angle-brackets (match-string 2 path))))))
10685 (cons type path))
10687 (defun org-find-file-at-mouse (ev)
10688 "Open file link or URL at mouse."
10689 (interactive "e")
10690 (mouse-set-point ev)
10691 (org-open-at-point 'in-emacs))
10693 (defun org-open-at-mouse (ev)
10694 "Open file link or URL at mouse.
10695 See the docstring of `org-open-file' for details."
10696 (interactive "e")
10697 (mouse-set-point ev)
10698 (when (eq major-mode 'org-agenda-mode)
10699 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10700 (org-open-at-point))
10702 (defvar org-window-config-before-follow-link nil
10703 "The window configuration before following a link.
10704 This is saved in case the need arises to restore it.")
10706 ;;;###autoload
10707 (defun org-open-at-point-global ()
10708 "Follow a link or time-stamp like Org mode does.
10709 This command can be called in any mode to follow an external link
10710 or a time-stamp that has Org mode syntax. Its behavior is
10711 undefined when called on internal links (e.g., fuzzy links).
10712 Raise an error when there is nothing to follow. "
10713 (interactive)
10714 (cond ((org-in-regexp org-any-link-re)
10715 (org-open-link-from-string (match-string-no-properties 0)))
10716 ((or (org-in-regexp org-ts-regexp-both nil t)
10717 (org-in-regexp org-tsr-regexp-both nil t))
10718 (org-follow-timestamp-link))
10719 (t (user-error "No link found"))))
10721 ;;;###autoload
10722 (defun org-open-link-from-string (s &optional arg reference-buffer)
10723 "Open a link in the string S, as if it was in Org-mode."
10724 (interactive "sLink: \nP")
10725 (let ((reference-buffer (or reference-buffer (current-buffer))))
10726 (with-temp-buffer
10727 (let ((org-inhibit-startup (not reference-buffer)))
10728 (org-mode)
10729 (insert s)
10730 (goto-char (point-min))
10731 (when reference-buffer
10732 (setq org-link-abbrev-alist-local
10733 (with-current-buffer reference-buffer
10734 org-link-abbrev-alist-local)))
10735 (org-open-at-point arg reference-buffer)))))
10737 (defvar org-open-at-point-functions nil
10738 "Hook that is run when following a link at point.
10740 Functions in this hook must return t if they identify and follow
10741 a link at point. If they don't find anything interesting at point,
10742 they must return nil.")
10744 (defvar org-link-search-inhibit-query nil)
10745 (defvar clean-buffer-list-kill-buffer-names) ;Defined in midnight.el
10746 (defun org--open-doi-link (path)
10747 "Open a \"doi\" type link.
10748 PATH is a the path to search for, as a string."
10749 (browse-url (url-encode-url (concat org-doi-server-url path))))
10751 (defun org--open-elisp-link (path)
10752 "Open a \"elisp\" type link.
10753 PATH is the sexp to evaluate, as a string."
10754 (let ((cmd path))
10755 (if (or (and (org-string-nw-p
10756 org-confirm-elisp-link-not-regexp)
10757 (string-match-p org-confirm-elisp-link-not-regexp cmd))
10758 (not org-confirm-elisp-link-function)
10759 (funcall org-confirm-elisp-link-function
10760 (format "Execute \"%s\" as elisp? "
10761 (org-add-props cmd nil 'face 'org-warning))))
10762 (message "%s => %s" cmd
10763 (if (eq (string-to-char cmd) ?\()
10764 (eval (read cmd))
10765 (call-interactively (read cmd))))
10766 (user-error "Abort"))))
10768 (defun org--open-help-link (path)
10769 "Open a \"help\" type link.
10770 PATH is a symbol name, as a string."
10771 (pcase (intern path)
10772 ((and (pred fboundp) variable) (describe-function variable))
10773 ((and (pred boundp) function) (describe-variable function))
10774 (name (user-error "Unknown function or variable: %s" name))))
10776 (defun org--open-shell-link (path)
10777 "Open a \"shell\" type link.
10778 PATH is the command to execute, as a string."
10779 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10780 (cmd path))
10781 (if (or (and (org-string-nw-p
10782 org-confirm-shell-link-not-regexp)
10783 (string-match
10784 org-confirm-shell-link-not-regexp cmd))
10785 (not org-confirm-shell-link-function)
10786 (funcall org-confirm-shell-link-function
10787 (format "Execute \"%s\" in shell? "
10788 (org-add-props cmd nil
10789 'face 'org-warning))))
10790 (progn
10791 (message "Executing %s" cmd)
10792 (shell-command cmd buf)
10793 (when (featurep 'midnight)
10794 (setq clean-buffer-list-kill-buffer-names
10795 (cons (buffer-name buf)
10796 clean-buffer-list-kill-buffer-names))))
10797 (user-error "Abort"))))
10799 (defun org-open-at-point (&optional arg reference-buffer)
10800 "Open link, timestamp, footnote or tags at point.
10802 When point is on a link, follow it. Normally, files will be
10803 opened by an appropriate application. If the optional prefix
10804 argument ARG is non-nil, Emacs will visit the file. With
10805 a double prefix argument, try to open outside of Emacs, in the
10806 application the system uses for this file type.
10808 When point is on a timestamp, open the agenda at the day
10809 specified.
10811 When point is a footnote definition, move to the first reference
10812 found. If it is on a reference, move to the associated
10813 definition.
10815 When point is on a headline, display a list of every link in the
10816 entry, so it is possible to pick one, or all, of them. If point
10817 is on a tag, call `org-tags-view' instead.
10819 When optional argument REFERENCE-BUFFER is non-nil, it should
10820 specify a buffer from where the link search should happen. This
10821 is used internally by `org-open-link-from-string'.
10823 On top of syntactically correct links, this function will open
10824 the link at point in comments or comment blocks and the first
10825 link in a property drawer line."
10826 (interactive "P")
10827 ;; On a code block, open block's results.
10828 (unless (call-interactively 'org-babel-open-src-block-result)
10829 (org-load-modules-maybe)
10830 (setq org-window-config-before-follow-link (current-window-configuration))
10831 (org-remove-occur-highlights nil nil t)
10832 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10833 (let* ((context
10834 ;; Only consider supported types, even if they are not
10835 ;; the closest one.
10836 (org-element-lineage
10837 (org-element-context)
10838 '(clock comment comment-block footnote-definition
10839 footnote-reference headline inlinetask keyword link
10840 node-property timestamp)
10842 (type (org-element-type context))
10843 (value (org-element-property :value context)))
10844 (cond
10845 ((not context) (user-error "No link found"))
10846 ;; Exception: open timestamps and links in properties
10847 ;; drawers, keywords and comments.
10848 ((memq type '(comment comment-block keyword node-property))
10849 (call-interactively #'org-open-at-point-global))
10850 ;; On a headline or an inlinetask, but not on a timestamp,
10851 ;; a link, a footnote reference or on tags.
10852 ((and (memq type '(headline inlinetask))
10853 ;; Not on tags.
10854 (progn (save-excursion (beginning-of-line)
10855 (looking-at org-complex-heading-regexp))
10856 (or (not (match-beginning 5))
10857 (< (point) (match-beginning 5)))))
10858 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10859 (links (car data))
10860 (links-end (cdr data)))
10861 (if links
10862 (dolist (link (if (stringp links) (list links) links))
10863 (search-forward link nil links-end)
10864 (goto-char (match-beginning 0))
10865 (org-open-at-point))
10866 (require 'org-attach)
10867 (org-attach-reveal 'if-exists))))
10868 ;; On a clock line, make sure point is on the timestamp
10869 ;; before opening it.
10870 ((and (eq type 'clock)
10871 value
10872 (>= (point) (org-element-property :begin value))
10873 (<= (point) (org-element-property :end value)))
10874 (org-follow-timestamp-link))
10875 ;; Do nothing on white spaces after an object.
10876 ((>= (point)
10877 (save-excursion
10878 (goto-char (org-element-property :end context))
10879 (skip-chars-backward " \t")
10880 (point)))
10881 (user-error "No link found"))
10882 ((eq type 'timestamp) (org-follow-timestamp-link))
10883 ;; On tags within a headline or an inlinetask.
10884 ((and (memq type '(headline inlinetask))
10885 (progn (save-excursion (beginning-of-line)
10886 (looking-at org-complex-heading-regexp))
10887 (and (match-beginning 5)
10888 (>= (point) (match-beginning 5)))))
10889 (org-tags-view arg (substring (match-string 5) 0 -1)))
10890 ((eq type 'link)
10891 ;; When link is located within the description of another
10892 ;; link (e.g., an inline image), always open the parent
10893 ;; link.
10894 (let* ((link (let ((up (org-element-property :parent context)))
10895 (if (eq (org-element-type up) 'link) up context)))
10896 (type (org-element-property :type link))
10897 (path (org-link-unescape (org-element-property :path link))))
10898 ;; Switch back to REFERENCE-BUFFER needed when called in
10899 ;; a temporary buffer through `org-open-link-from-string'.
10900 (with-current-buffer (or reference-buffer (current-buffer))
10901 (cond
10902 ((equal type "file")
10903 (if (string-match "[*?{]" (file-name-nondirectory path))
10904 (dired path)
10905 ;; Look into `org-link-parameters' in order to find
10906 ;; a DEDICATED-FUNCTION to open file. The function
10907 ;; will be applied on raw link instead of parsed
10908 ;; link due to the limitation in `org-add-link-type'
10909 ;; ("open" function called with a single argument).
10910 ;; If no such function is found, fallback to
10911 ;; `org-open-file'.
10912 (let* ((option (org-element-property :search-option link))
10913 (app (org-element-property :application link))
10914 (dedicated-function
10915 (org-link-get-parameter
10916 (if app (concat type "+" app) type)
10917 :follow)))
10918 (if dedicated-function
10919 (funcall dedicated-function
10920 (concat path
10921 (and option (concat "::" option))))
10922 (apply #'org-open-file
10923 path
10924 (cond (arg)
10925 ((equal app "emacs") 'emacs)
10926 ((equal app "sys") 'system))
10927 (cond ((not option) nil)
10928 ((string-match-p "\\`[0-9]+\\'" option)
10929 (list (string-to-number option)))
10930 (t (list nil
10931 (org-link-unescape option)))))))))
10932 ((functionp (org-link-get-parameter type :follow))
10933 (funcall (org-link-get-parameter type :follow) path))
10934 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10935 (unless (run-hook-with-args-until-success
10936 'org-open-link-functions path)
10937 (if (not arg) (org-mark-ring-push)
10938 (switch-to-buffer-other-window
10939 (org-get-buffer-for-internal-link (current-buffer))))
10940 (let ((destination
10941 (org-with-wide-buffer
10942 (if (equal type "radio")
10943 (org-search-radio-target
10944 (org-element-property :path link))
10945 (org-link-search
10946 (if (member type '("custom-id" "coderef"))
10947 (org-element-property :raw-link link)
10948 path)
10949 ;; Prevent fuzzy links from matching
10950 ;; themselves.
10951 (and (equal type "fuzzy")
10952 (+ 2 (org-element-property :begin link)))))
10953 (point))))
10954 (unless (and (<= (point-min) destination)
10955 (>= (point-max) destination))
10956 (widen))
10957 (goto-char destination))))
10958 (t (browse-url-at-point))))))
10959 ;; On a footnote reference or at a footnote definition's label.
10960 ((or (eq type 'footnote-reference)
10961 (and (eq type 'footnote-definition)
10962 (save-excursion
10963 ;; Do not validate action when point is on the
10964 ;; spaces right after the footnote label, in
10965 ;; order to be on par with behaviour on links.
10966 (skip-chars-forward " \t")
10967 (let ((begin
10968 (org-element-property :contents-begin context)))
10969 (if begin (< (point) begin)
10970 (= (org-element-property :post-affiliated context)
10971 (line-beginning-position)))))))
10972 (org-footnote-action))
10973 (t (user-error "No link found")))))
10974 (run-hook-with-args 'org-follow-link-hook)))
10976 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10977 "Offer links in the current entry and return the selected link.
10978 If there is only one link, return it.
10979 If NTH is an integer, return the NTH link found.
10980 If ZERO is a string, check also this string for a link, and if
10981 there is one, return it."
10982 (with-current-buffer buffer
10983 (save-excursion
10984 (save-restriction
10985 (widen)
10986 (goto-char marker)
10987 (let ((cnt ?0)
10988 have-zero end links link c)
10989 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10990 (push (match-string 0 zero) links)
10991 (setq cnt (1- cnt) have-zero t))
10992 (save-excursion
10993 (org-back-to-heading t)
10994 (setq end (save-excursion (outline-next-heading) (point)))
10995 (while (re-search-forward org-any-link-re end t)
10996 (push (match-string 0) links))
10997 (setq links (org-uniquify (reverse links))))
10998 (cond
10999 ((null links)
11000 (message "No links"))
11001 ((equal (length links) 1)
11002 (setq link (car links)))
11003 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
11004 (setq link (nth (if have-zero nth (1- nth)) links)))
11005 (t ; we have to select a link
11006 (save-excursion
11007 (save-window-excursion
11008 (delete-other-windows)
11009 (with-output-to-temp-buffer "*Select Link*"
11010 (dolist (l links)
11011 (cond
11012 ((not (string-match org-bracket-link-regexp l))
11013 (princ (format "[%c] %s\n" (cl-incf cnt)
11014 (org-remove-angle-brackets l))))
11015 ((match-end 3)
11016 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
11017 (match-string 3 l) (match-string 1 l))))
11018 (t (princ (format "[%c] %s\n" (cl-incf cnt)
11019 (match-string 1 l)))))))
11020 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
11021 (message "Select link to open, RET to open all:")
11022 (setq c (read-char-exclusive))
11023 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
11024 (when (equal c ?q) (user-error "Abort"))
11025 (if (equal c ?\C-m)
11026 (setq link links)
11027 (setq nth (- c ?0))
11028 (when have-zero (setq nth (1+ nth)))
11029 (unless (and (integerp nth) (>= (length links) nth))
11030 (user-error "Invalid link selection"))
11031 (setq link (nth (1- nth) links)))))
11032 (cons link end))))))
11034 ;; TODO: These functions are deprecated since `org-open-at-point'
11035 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
11036 (defun org-open-file-with-system (path)
11037 "Open file at PATH using the system way of opening it."
11038 (org-open-file path 'system))
11039 (defun org-open-file-with-emacs (path)
11040 "Open file at PATH in Emacs."
11041 (org-open-file path 'emacs))
11044 ;;; File search
11046 (defvar org-create-file-search-functions nil
11047 "List of functions to construct the right search string for a file link.
11048 These functions are called in turn with point at the location to
11049 which the link should point.
11051 A function in the hook should first test if it would like to
11052 handle this file type, for example by checking the `major-mode'
11053 or the file extension. If it decides not to handle this file, it
11054 should just return nil to give other functions a chance. If it
11055 does handle the file, it must return the search string to be used
11056 when following the link. The search string will be part of the
11057 file link, given after a double colon, and `org-open-at-point'
11058 will automatically search for it. If special measures must be
11059 taken to make the search successful, another function should be
11060 added to the companion hook `org-execute-file-search-functions',
11061 which see.
11063 A function in this hook may also use `setq' to set the variable
11064 `description' to provide a suggestion for the descriptive text to
11065 be used for this link when it gets inserted into an Org-mode
11066 buffer with \\[org-insert-link].")
11068 (defvar org-execute-file-search-functions nil
11069 "List of functions to execute a file search triggered by a link.
11071 Functions added to this hook must accept a single argument, the
11072 search string that was part of the file link, the part after the
11073 double colon. The function must first check if it would like to
11074 handle this search, for example by checking the `major-mode' or
11075 the file extension. If it decides not to handle this search, it
11076 should just return nil to give other functions a chance. If it
11077 does handle the search, it must return a non-nil value to keep
11078 other functions from trying.
11080 Each function can access the current prefix argument through the
11081 variable `current-prefix-arg'. Note that a single prefix is used
11082 to force opening a link in Emacs, so it may be good to only use a
11083 numeric or double prefix to guide the search function.
11085 In case this is needed, a function in this hook can also restore
11086 the window configuration before `org-open-at-point' was called using:
11088 \(set-window-configuration org-window-config-before-follow-link)")
11090 (defun org-search-radio-target (target)
11091 "Search a radio target matching TARGET in current buffer.
11092 White spaces are not significant."
11093 (let ((re (format "<<<%s>>>"
11094 (mapconcat #'regexp-quote
11095 (org-split-string target "[ \t\n]+")
11096 "[ \t]+\\(?:\n[ \t]*\\)?")))
11097 (origin (point)))
11098 (goto-char (point-min))
11099 (catch :radio-match
11100 (while (re-search-forward re nil t)
11101 (backward-char)
11102 (let ((object (org-element-context)))
11103 (when (eq (org-element-type object) 'radio-target)
11104 (goto-char (org-element-property :begin object))
11105 (org-show-context 'link-search)
11106 (throw :radio-match nil))))
11107 (goto-char origin)
11108 (user-error "No match for radio target: %s" target))))
11110 (defun org-link-search (s &optional avoid-pos stealth)
11111 "Search for a search string S.
11113 If S starts with \"#\", it triggers a custom ID search.
11115 If S is enclosed within parenthesis, it initiates a coderef
11116 search.
11118 If S is surrounded by forward slashes, it is interpreted as
11119 a regular expression. In Org mode files, this will create an
11120 `org-occur' sparse tree. In ordinary files, `occur' will be used
11121 to list matches. If the current buffer is in `dired-mode', grep
11122 will be used to search in all files.
11124 When AVOID-POS is given, ignore matches near that position.
11126 When optional argument STEALTH is non-nil, do not modify
11127 visibility around point, thus ignoring `org-show-context-detail'
11128 variable.
11130 Search is case-insensitive and ignores white spaces. Return type
11131 of matched result, with is either `dedicated' or `fuzzy'."
11132 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11133 (let* ((case-fold-search t)
11134 (origin (point))
11135 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11136 (words (org-split-string s "[ \t\n]+"))
11137 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11138 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11139 type)
11140 (cond
11141 ;; Check if there are any special search functions.
11142 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11143 ((eq (string-to-char s) ?#)
11144 ;; Look for a custom ID S if S starts with "#".
11145 (let* ((id (substring normalized 1))
11146 (match (org-find-property "CUSTOM_ID" id)))
11147 (if match (progn (goto-char match) (setf type 'dedicated))
11148 (error "No match for custom ID: %s" id))))
11149 ((string-match "\\`(\\(.*\\))\\'" normalized)
11150 ;; Look for coderef targets if S is enclosed within parenthesis.
11151 (let ((coderef (match-string-no-properties 1 normalized))
11152 (re (substring s-single-re 1 -1)))
11153 (goto-char (point-min))
11154 (catch :coderef-match
11155 (while (re-search-forward re nil t)
11156 (let ((element (org-element-at-point)))
11157 (when (and (memq (org-element-type element)
11158 '(example-block src-block))
11159 ;; Build proper regexp according to current
11160 ;; block's label format.
11161 (let ((label-fmt
11162 (regexp-quote
11163 (or (org-element-property :label-fmt element)
11164 org-coderef-label-format))))
11165 (save-excursion
11166 (beginning-of-line)
11167 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11168 (format label-fmt coderef))))))
11169 (setq type 'dedicated)
11170 (goto-char (match-beginning 1))
11171 (throw :coderef-match nil))))
11172 (goto-char origin)
11173 (error "No match for coderef: %s" coderef))))
11174 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11175 ;; Look for a regular expression.
11176 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11177 (match-string 1 s)))
11178 ;; Fuzzy links.
11180 (let ((starred (eq (string-to-char normalized) ?*)))
11181 (cond
11182 ;; Look for targets, only if not in a headline search.
11183 ((and (not starred)
11184 (let ((target (format "<<%s>>" s-multi-re)))
11185 (catch :target-match
11186 (goto-char (point-min))
11187 (while (re-search-forward target nil t)
11188 (backward-char)
11189 (let ((context (org-element-context)))
11190 (when (eq (org-element-type context) 'target)
11191 (setq type 'dedicated)
11192 (goto-char (org-element-property :begin context))
11193 (throw :target-match t))))
11194 nil))))
11195 ;; Look for elements named after S, only if not in a headline
11196 ;; search.
11197 ((and (not starred)
11198 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11199 (catch :name-match
11200 (goto-char (point-min))
11201 (while (re-search-forward name nil t)
11202 (let ((element (org-element-at-point)))
11203 (when (equal (org-split-string
11204 (org-element-property :name element)
11205 "[ \t]+")
11206 words)
11207 (setq type 'dedicated)
11208 (beginning-of-line)
11209 (throw :name-match t))))
11210 nil))))
11211 ;; Regular text search. Prefer headlines in Org mode
11212 ;; buffers.
11213 ((and (derived-mode-p 'org-mode)
11214 (let* ((wspace "[ \t]")
11215 (wspaceopt (concat wspace "*"))
11216 (cookie (concat "\\(?:"
11217 wspaceopt
11218 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11219 wspaceopt
11220 "\\)"))
11221 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11222 (re (concat
11223 org-outline-regexp-bol
11224 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11225 "\\(?:\\[#.\\][ \t]+\\)?"
11226 "\\(?:" org-comment-string "[ \t]+\\)?"
11227 sep "?"
11228 (let ((title (mapconcat #'regexp-quote
11229 words
11230 sep)))
11231 (if starred (substring title 1) title))
11232 sep "?"
11233 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11234 "[ \t]*$")))
11235 (goto-char (point-min))
11236 (re-search-forward re nil t)))
11237 (goto-char (match-beginning 0))
11238 (setq type 'dedicated))
11239 ;; Offer to create non-existent headline depending on
11240 ;; `org-link-search-must-match-exact-headline'.
11241 ((and (derived-mode-p 'org-mode)
11242 (not org-link-search-inhibit-query)
11243 (eq org-link-search-must-match-exact-headline 'query-to-create)
11244 (yes-or-no-p "No match - create this as a new heading? "))
11245 (goto-char (point-max))
11246 (unless (bolp) (newline))
11247 (org-insert-heading nil t t)
11248 (insert s "\n")
11249 (beginning-of-line 0))
11250 ;; Only headlines are looked after. No need to process
11251 ;; further: throw an error.
11252 ((and (derived-mode-p 'org-mode)
11253 (or starred org-link-search-must-match-exact-headline))
11254 (goto-char origin)
11255 (error "No match for fuzzy expression: %s" normalized))
11256 ;; Regular text search.
11257 ((catch :fuzzy-match
11258 (goto-char (point-min))
11259 (while (re-search-forward s-multi-re nil t)
11260 ;; Skip match if it contains AVOID-POS or it is included
11261 ;; in a link with a description but outside the
11262 ;; description.
11263 (unless (or (and avoid-pos
11264 (<= (match-beginning 0) avoid-pos)
11265 (> (match-end 0) avoid-pos))
11266 (and (save-match-data
11267 (org-in-regexp org-bracket-link-regexp))
11268 (match-beginning 3)
11269 (or (> (match-beginning 3) (point))
11270 (<= (match-end 3) (point)))
11271 (org-element-lineage
11272 (save-match-data (org-element-context))
11273 '(link) t)))
11274 (goto-char (match-beginning 0))
11275 (setq type 'fuzzy)
11276 (throw :fuzzy-match t)))
11277 nil))
11278 ;; All failed. Throw an error.
11279 (t (goto-char origin)
11280 (error "No match for fuzzy expression: %s" normalized))))))
11281 ;; Disclose surroundings of match, if appropriate.
11282 (when (and (derived-mode-p 'org-mode) (not stealth))
11283 (org-show-context 'link-search))
11284 type))
11286 (defun org-get-buffer-for-internal-link (buffer)
11287 "Return a buffer to be used for displaying the link target of internal links."
11288 (cond
11289 ((not org-display-internal-link-with-indirect-buffer)
11290 buffer)
11291 ((string-match "(Clone)$" (buffer-name buffer))
11292 (message "Buffer is already a clone, not making another one")
11293 ;; we also do not modify visibility in this case
11294 buffer)
11295 (t ; make a new indirect buffer for displaying the link
11296 (let* ((bn (buffer-name buffer))
11297 (ibn (concat bn "(Clone)"))
11298 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11299 (with-current-buffer ib (org-overview))
11300 ib))))
11302 (defun org-do-occur (regexp &optional cleanup)
11303 "Call the Emacs command `occur'.
11304 If CLEANUP is non-nil, remove the printout of the regular expression
11305 in the *Occur* buffer. This is useful if the regex is long and not useful
11306 to read."
11307 (occur regexp)
11308 (when cleanup
11309 (let ((cwin (selected-window)) win beg end)
11310 (when (setq win (get-buffer-window "*Occur*"))
11311 (select-window win))
11312 (goto-char (point-min))
11313 (when (re-search-forward "match[a-z]+" nil t)
11314 (setq beg (match-end 0))
11315 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11316 (setq end (1- (match-beginning 0)))))
11317 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11318 (goto-char (point-min))
11319 (select-window cwin))))
11321 ;;; The mark ring for links jumps
11323 (defvar org-mark-ring nil
11324 "Mark ring for positions before jumps in Org-mode.")
11325 (defvar org-mark-ring-last-goto nil
11326 "Last position in the mark ring used to go back.")
11327 ;; Fill and close the ring
11328 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11329 (dotimes (_ org-mark-ring-length)
11330 (push (make-marker) org-mark-ring))
11331 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11332 org-mark-ring)
11334 (defun org-mark-ring-push (&optional pos buffer)
11335 "Put the current position or POS into the mark ring and rotate it."
11336 (interactive)
11337 (setq pos (or pos (point)))
11338 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11339 (move-marker (car org-mark-ring)
11340 (or pos (point))
11341 (or buffer (current-buffer)))
11342 (message "%s"
11343 (substitute-command-keys
11344 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11346 (defun org-mark-ring-goto (&optional n)
11347 "Jump to the previous position in the mark ring.
11348 With prefix arg N, jump back that many stored positions. When
11349 called several times in succession, walk through the entire ring.
11350 Org-mode commands jumping to a different position in the current file,
11351 or to another Org-mode file, automatically push the old position
11352 onto the ring."
11353 (interactive "p")
11354 (let (p m)
11355 (if (eq last-command this-command)
11356 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11357 (setq p org-mark-ring))
11358 (setq org-mark-ring-last-goto p)
11359 (setq m (car p))
11360 (pop-to-buffer-same-window (marker-buffer m))
11361 (goto-char m)
11362 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11364 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11365 ;;; Emacs 24.4+
11366 (defun org-remove-angle-brackets (s)
11367 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11368 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11370 (defun org-add-angle-brackets (s)
11371 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11372 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11374 (defun org-remove-double-quotes (s)
11375 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11376 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11379 ;;; Following specific links
11381 (defvar org-agenda-buffer-tmp-name)
11382 (defvar org-agenda-start-on-weekday)
11383 (defun org-follow-timestamp-link ()
11384 "Open an agenda view for the time-stamp date/range at point."
11385 (cond
11386 ((org-at-date-range-p t)
11387 (let ((org-agenda-start-on-weekday)
11388 (t1 (match-string 1))
11389 (t2 (match-string 2)) tt1 tt2)
11390 (setq tt1 (time-to-days (org-time-string-to-time t1))
11391 tt2 (time-to-days (org-time-string-to-time t2)))
11392 (let ((org-agenda-buffer-tmp-name
11393 (format "*Org Agenda(a:%s)"
11394 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11395 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11396 ((org-at-timestamp-p t)
11397 (let ((org-agenda-buffer-tmp-name
11398 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11399 (org-agenda-list nil (time-to-days (org-time-string-to-time
11400 (substring (match-string 1) 0 10)))
11401 1)))
11402 (t (error "This should not happen"))))
11405 ;;; Following file links
11406 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11407 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11408 (declare-function mailcap-mime-info
11409 "mailcap" (string &optional request no-decode))
11410 (defvar org-wait nil)
11411 (defun org-open-file (path &optional in-emacs line search)
11412 "Open the file at PATH.
11413 First, this expands any special file name abbreviations. Then the
11414 configuration variable `org-file-apps' is checked if it contains an
11415 entry for this file type, and if yes, the corresponding command is launched.
11417 If no application is found, Emacs simply visits the file.
11419 With optional prefix argument IN-EMACS, Emacs will visit the file.
11420 With a double \\[universal-argument] \\[universal-argument] \
11421 prefix arg, Org tries to avoid opening in Emacs
11422 and to use an external application to visit the file.
11424 Optional LINE specifies a line to go to, optional SEARCH a string
11425 to search for. If LINE or SEARCH is given, the file will be
11426 opened in Emacs, unless an entry from org-file-apps that makes
11427 use of groups in a regexp matches.
11429 If you want to change the way frames are used when following a
11430 link, please customize `org-link-frame-setup'.
11432 If the file does not exist, an error is thrown."
11433 (let* ((file (if (equal path "")
11434 buffer-file-name
11435 (substitute-in-file-name (expand-file-name path))))
11436 (file-apps (append org-file-apps (org-default-apps)))
11437 (apps (cl-remove-if
11438 'org-file-apps-entry-match-against-dlink-p file-apps))
11439 (apps-dlink (cl-remove-if-not
11440 'org-file-apps-entry-match-against-dlink-p file-apps))
11441 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11442 (dirp (unless remp (file-directory-p file)))
11443 (file (if (and dirp org-open-directory-means-index-dot-org)
11444 (concat (file-name-as-directory file) "index.org")
11445 file))
11446 (a-m-a-p (assq 'auto-mode apps))
11447 (dfile (downcase file))
11448 ;; Reconstruct the original link from the PATH, LINE and
11449 ;; SEARCH args.
11450 (link (cond (line (concat file "::" (number-to-string line)))
11451 (search (concat file "::" search))
11452 (t file)))
11453 (dlink (downcase link))
11454 (old-buffer (current-buffer))
11455 (old-pos (point))
11456 (old-mode major-mode)
11457 (ext
11458 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11459 (match-string 1 dfile)))
11460 cmd link-match-data)
11461 (cond
11462 ((member in-emacs '((16) system))
11463 (setq cmd (cdr (assq 'system apps))))
11464 (in-emacs (setq cmd 'emacs))
11466 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11467 (and dirp (cdr (assq 'directory apps)))
11468 ;; First, try matching against apps-dlink if we
11469 ;; get a match here, store the match data for
11470 ;; later.
11471 (let ((match (assoc-default dlink apps-dlink
11472 'string-match)))
11473 (if match
11474 (progn (setq link-match-data (match-data))
11475 match)
11476 (progn (setq in-emacs (or in-emacs line search))
11477 nil))) ; if we have no match in apps-dlink,
11478 ; always open the file in emacs if line or search
11479 ; is given (for backwards compatibility)
11480 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11481 'string-match)
11482 (cdr (assoc ext apps))
11483 (cdr (assq t apps))))))
11484 (when (eq cmd 'system)
11485 (setq cmd (cdr (assoc 'system apps))))
11486 (when (eq cmd 'default)
11487 (setq cmd (cdr (assoc t apps))))
11488 (when (eq cmd 'mailcap)
11489 (require 'mailcap)
11490 (mailcap-parse-mailcaps)
11491 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11492 (command (mailcap-mime-info mime-type)))
11493 (if (stringp command)
11494 (setq cmd command)
11495 (setq cmd 'emacs))))
11496 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11497 (not (file-exists-p file))
11498 (not org-open-non-existing-files))
11499 (user-error "No such file: %s" file))
11500 (cond
11501 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11502 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11503 (while (string-match "['\"]%s['\"]" cmd)
11504 (setq cmd (replace-match "%s" t t cmd)))
11505 (while (string-match "%s" cmd)
11506 (setq cmd (replace-match
11507 (save-match-data
11508 (shell-quote-argument
11509 (convert-standard-filename file)))
11510 t t cmd)))
11512 ;; Replace "%1", "%2" etc. in command with group matches from regex
11513 (save-match-data
11514 (let ((match-index 1)
11515 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11516 (set-match-data link-match-data)
11517 (while (<= match-index number-of-groups)
11518 (let ((regex (concat "%" (number-to-string match-index)))
11519 (replace-with (match-string match-index dlink)))
11520 (while (string-match regex cmd)
11521 (setq cmd (replace-match replace-with t t cmd))))
11522 (setq match-index (+ match-index 1)))))
11524 (save-window-excursion
11525 (message "Running %s...done" cmd)
11526 (start-process-shell-command cmd nil cmd)
11527 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11528 ((or (stringp cmd)
11529 (eq cmd 'emacs))
11530 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11531 (widen)
11532 (cond (line (org-goto-line line)
11533 (when (derived-mode-p 'org-mode) (org-reveal)))
11534 (search (org-link-search search))))
11535 ((functionp cmd)
11536 (save-match-data
11537 (set-match-data link-match-data)
11538 (condition-case nil
11539 (funcall cmd file link)
11540 ;; FIXME: Remove this check when most default installations
11541 ;; of Emacs have at least Org 9.0.
11542 ((debug wrong-number-of-arguments wrong-type-argument
11543 invalid-function)
11544 (user-error "Please see Org News for version 9.0 about \
11545 `org-file-apps'--Lisp error: %S" cmd)))))
11546 ((consp cmd)
11547 ;; FIXME: Remove this check when most default installations of
11548 ;; Emacs have at least Org 9.0.
11549 ;; Heads-up instead of silently fall back to
11550 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11551 ;; with sexp instead of a function for `cmd'.
11552 (user-error "Please see Org News for version 9.0 about \
11553 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11554 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11555 (and (derived-mode-p 'org-mode)
11556 (eq old-mode 'org-mode)
11557 (or (not (eq old-buffer (current-buffer)))
11558 (not (eq old-pos (point))))
11559 (org-mark-ring-push old-pos old-buffer))))
11561 (defun org-file-apps-entry-match-against-dlink-p (entry)
11562 "This function returns non-nil if `entry' uses a regular
11563 expression which should be matched against the whole link by
11564 org-open-file.
11566 It assumes that is the case when the entry uses a regular
11567 expression which has at least one grouping construct and the
11568 action is either a lisp form or a command string containing
11569 `%1', i.e. using at least one subexpression match as a
11570 parameter."
11571 (let ((selector (car entry))
11572 (action (cdr entry)))
11573 (if (stringp selector)
11574 (and (> (regexp-opt-depth selector) 0)
11575 (or (and (stringp action)
11576 (string-match "%[0-9]" action))
11577 (consp action)))
11578 nil)))
11580 (defun org-default-apps ()
11581 "Return the default applications for this operating system."
11582 (cond
11583 ((eq system-type 'darwin)
11584 org-file-apps-defaults-macosx)
11585 ((eq system-type 'windows-nt)
11586 org-file-apps-defaults-windowsnt)
11587 (t org-file-apps-defaults-gnu)))
11589 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11590 "Convert extensions to regular expressions in the cars of LIST.
11591 Also, weed out any non-string entries, because the return value is used
11592 only for regexp matching.
11593 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11594 point to the symbol `emacs', indicating that the file should
11595 be opened in Emacs."
11596 (append
11597 (delq nil
11598 (mapcar (lambda (x)
11599 (unless (not (stringp (car x)))
11600 (if (string-match "\\W" (car x))
11602 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11603 list))
11604 (when add-auto-mode
11605 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11607 (defvar ange-ftp-name-format)
11608 (defun org-file-remote-p (file)
11609 "Test whether FILE specifies a location on a remote system.
11610 Return non-nil if the location is indeed remote.
11612 For example, the filename \"/user@host:/foo\" specifies a location
11613 on the system \"/user@host:\"."
11614 (cond ((fboundp 'file-remote-p)
11615 (file-remote-p file))
11616 ((fboundp 'tramp-handle-file-remote-p)
11617 (tramp-handle-file-remote-p file))
11618 ((and (boundp 'ange-ftp-name-format)
11619 (string-match (car ange-ftp-name-format) file))
11620 t)))
11623 ;;;; Refiling
11625 (defun org-get-org-file ()
11626 "Read a filename, with default directory `org-directory'."
11627 (let ((default (or org-default-notes-file remember-data-file)))
11628 (read-file-name (format "File name [%s]: " default)
11629 (file-name-as-directory org-directory)
11630 default)))
11632 (defun org-notes-order-reversed-p ()
11633 "Check if the current file should receive notes in reversed order."
11634 (cond
11635 ((not org-reverse-note-order) nil)
11636 ((eq t org-reverse-note-order) t)
11637 ((not (listp org-reverse-note-order)) nil)
11638 (t (catch 'exit
11639 (dolist (entry org-reverse-note-order)
11640 (when (string-match (car entry) buffer-file-name)
11641 (throw 'exit (cdr entry))))))))
11643 (defvar org-refile-target-table nil
11644 "The list of refile targets, created by `org-refile'.")
11646 (defvar org-agenda-new-buffers nil
11647 "Buffers created to visit agenda files.")
11649 (defvar org-refile-cache nil
11650 "Cache for refile targets.")
11652 (defvar org-refile-markers nil
11653 "All the markers used for caching refile locations.")
11655 (defun org-refile-marker (pos)
11656 "Get a new refile marker, but only if caching is in use."
11657 (if (not org-refile-use-cache)
11659 (let ((m (make-marker)))
11660 (move-marker m pos)
11661 (push m org-refile-markers)
11662 m)))
11664 (defun org-refile-cache-clear ()
11665 "Clear the refile cache and disable all the markers."
11666 (dolist (m org-refile-markers) (move-marker m nil))
11667 (setq org-refile-markers nil)
11668 (setq org-refile-cache nil)
11669 (message "Refile cache has been cleared"))
11671 (defun org-refile-cache-check-set (set)
11672 "Check if all the markers in the cache still have live buffers."
11673 (let (marker)
11674 (catch 'exit
11675 (while (and set (setq marker (nth 3 (pop set))))
11676 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11677 (when (and marker (null (marker-buffer marker)))
11678 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11679 (sit-for 3)
11680 (throw 'exit nil)))
11681 t)))
11683 (defun org-refile-cache-put (set &rest identifiers)
11684 "Push the refile targets SET into the cache, under IDENTIFIERS."
11685 (let* ((key (sha1 (prin1-to-string identifiers)))
11686 (entry (assoc key org-refile-cache)))
11687 (if entry
11688 (setcdr entry set)
11689 (push (cons key set) org-refile-cache))))
11691 (defun org-refile-cache-get (&rest identifiers)
11692 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11693 (cond
11694 ((not org-refile-cache) nil)
11695 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11697 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11698 org-refile-cache))))
11699 (and set (org-refile-cache-check-set set) set)))))
11701 (defvar org-outline-path-cache nil
11702 "Alist between buffer positions and outline paths.
11703 It value is an alist (POSITION . PATH) where POSITION is the
11704 buffer position at the beginning of an entry and PATH is a list
11705 of strings describing the outline path for that entry, in reverse
11706 order.")
11708 (defun org-refile-get-targets (&optional default-buffer)
11709 "Produce a table with refile targets."
11710 (let ((case-fold-search nil)
11711 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11712 (entries (or org-refile-targets '((nil . (:level . 1)))))
11713 targets tgs files desc descre)
11714 (message "Getting targets...")
11715 (with-current-buffer (or default-buffer (current-buffer))
11716 (dolist (entry entries)
11717 (setq files (car entry) desc (cdr entry))
11718 (cond
11719 ((null files) (setq files (list (current-buffer))))
11720 ((eq files 'org-agenda-files)
11721 (setq files (org-agenda-files 'unrestricted)))
11722 ((and (symbolp files) (fboundp files))
11723 (setq files (funcall files)))
11724 ((and (symbolp files) (boundp files))
11725 (setq files (symbol-value files))))
11726 (when (stringp files) (setq files (list files)))
11727 (cond
11728 ((eq (car desc) :tag)
11729 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11730 ((eq (car desc) :todo)
11731 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11732 ((eq (car desc) :regexp)
11733 (setq descre (cdr desc)))
11734 ((eq (car desc) :level)
11735 (setq descre (concat "^\\*\\{" (number-to-string
11736 (if org-odd-levels-only
11737 (1- (* 2 (cdr desc)))
11738 (cdr desc)))
11739 "\\}[ \t]")))
11740 ((eq (car desc) :maxlevel)
11741 (setq descre (concat "^\\*\\{1," (number-to-string
11742 (if org-odd-levels-only
11743 (1- (* 2 (cdr desc)))
11744 (cdr desc)))
11745 "\\}[ \t]")))
11746 (t (error "Bad refiling target description %s" desc)))
11747 (dolist (f files)
11748 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11750 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11751 (progn
11752 (when (bufferp f)
11753 (setq f (buffer-file-name (buffer-base-buffer f))))
11754 (setq f (and f (expand-file-name f)))
11755 (when (eq org-refile-use-outline-path 'file)
11756 (push (list (file-name-nondirectory f) f nil nil) tgs))
11757 (org-with-wide-buffer
11758 (goto-char (point-min))
11759 (setq org-outline-path-cache nil)
11760 (while (re-search-forward descre nil t)
11761 (beginning-of-line)
11762 (looking-at org-complex-heading-regexp)
11763 (let ((begin (point))
11764 (heading (match-string-no-properties 4)))
11765 (unless (or (and
11766 org-refile-target-verify-function
11767 (not
11768 (funcall org-refile-target-verify-function)))
11769 (not heading))
11770 (let ((re (format org-complex-heading-regexp-format
11771 (regexp-quote heading)))
11772 (target
11773 (if (not org-refile-use-outline-path) heading
11774 (mapconcat
11775 #'org-protect-slash
11776 (append
11777 (pcase org-refile-use-outline-path
11778 (`file (list (file-name-nondirectory
11779 (buffer-file-name
11780 (buffer-base-buffer)))))
11781 (`full-file-path
11782 (list (buffer-file-name
11783 (buffer-base-buffer))))
11784 (_ nil))
11785 (org-get-outline-path t t))
11786 "/"))))
11787 (push (list target f re (org-refile-marker (point)))
11788 tgs)))
11789 (when (= (point) begin)
11790 ;; Verification function has not moved point.
11791 (end-of-line)))))))
11792 (when org-refile-use-cache
11793 (org-refile-cache-put tgs (buffer-file-name) descre))
11794 (setq targets (append tgs targets))))))
11795 (message "Getting targets...done")
11796 (nreverse targets)))
11798 (defun org-protect-slash (s)
11799 (while (string-match "/" s)
11800 (setq s (replace-match "\\" t t s)))
11803 (defun org--get-outline-path-1 (&optional use-cache)
11804 "Return outline path to current headline.
11806 Outline path is a list of strings, in reverse order. When
11807 optional argument USE-CACHE is non-nil, make use of a cache. See
11808 `org-get-outline-path' for details.
11810 Assume buffer is widened and point is on a headline."
11811 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11812 (let ((p (point))
11813 (heading (progn
11814 (looking-at org-complex-heading-regexp)
11815 (if (not (match-end 4)) ""
11816 ;; Remove statistics cookies.
11817 (org-trim
11818 (org-link-display-format
11819 (replace-regexp-in-string
11820 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11821 (match-string-no-properties 4))))))))
11822 (if (org-up-heading-safe)
11823 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11824 (when use-cache
11825 (push (cons p path) org-outline-path-cache))
11826 path)
11827 ;; This is a new root node. Since we assume we are moving
11828 ;; forward, we can drop previous cache so as to limit number
11829 ;; of associations there.
11830 (let ((path (list heading)))
11831 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11832 path)))))
11834 (defun org-get-outline-path (&optional with-self use-cache)
11835 "Return the outline path to the current entry.
11837 An outline path is a list of ancestors for current headline, as
11838 a list of strings. Statistics cookies are removed and links are
11839 replaced with their description, if any, or their path otherwise.
11841 When optional argument WITH-SELF is non-nil, the path also
11842 includes the current headline.
11844 When optional argument USE-CACHE is non-nil, cache outline paths
11845 between calls to this function so as to avoid backtracking. This
11846 argument is useful when planning to find more than one outline
11847 path in the same document. In that case, there are two
11848 conditions to satisfy:
11849 - `org-outline-path-cache' is set to nil before starting the
11850 process;
11851 - outline paths are computed by increasing buffer positions."
11852 (org-with-wide-buffer
11853 (and (or (and with-self (org-back-to-heading t))
11854 (org-up-heading-safe))
11855 (reverse (org--get-outline-path-1 use-cache)))))
11857 (defun org-format-outline-path (path &optional width prefix separator)
11858 "Format the outline path PATH for display.
11859 WIDTH is the maximum number of characters that is available.
11860 PREFIX is a prefix to be included in the returned string,
11861 such as the file name.
11862 SEPARATOR is inserted between the different parts of the path,
11863 the default is \"/\"."
11864 (setq width (or width 79))
11865 (setq path (delq nil path))
11866 (unless (> width 0)
11867 (user-error "Argument `width' must be positive"))
11868 (setq separator (or separator "/"))
11869 (let* ((org-odd-levels-only nil)
11870 (fpath (concat
11871 prefix (and prefix path separator)
11872 (mapconcat
11873 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11874 (cl-loop for head in path
11875 for n from 0
11876 collect (org-add-props
11877 head nil 'face
11878 (nth (% n org-n-level-faces) org-level-faces)))
11879 separator))))
11880 (when (> (length fpath) width)
11881 (if (< width 7)
11882 ;; It's unlikely that `width' will be this small, but don't
11883 ;; waste characters by adding ".." if it is.
11884 (setq fpath (substring fpath 0 width))
11885 (setf (substring fpath (- width 2)) "..")))
11886 fpath))
11888 (defun org-display-outline-path (&optional file current separator just-return-string)
11889 "Display the current outline path in the echo area.
11891 If FILE is non-nil, prepend the output with the file name.
11892 If CURRENT is non-nil, append the current heading to the output.
11893 SEPARATOR is passed through to `org-format-outline-path'. It separates
11894 the different parts of the path and defaults to \"/\".
11895 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11896 (interactive "P")
11897 (let* (case-fold-search
11898 (bfn (buffer-file-name (buffer-base-buffer)))
11899 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11900 res)
11901 (when current (setq path (append path
11902 (save-excursion
11903 (org-back-to-heading t)
11904 (when (looking-at org-complex-heading-regexp)
11905 (list (match-string 4)))))))
11906 (setq res
11907 (org-format-outline-path
11908 path
11909 (1- (frame-width))
11910 (and file bfn (concat (file-name-nondirectory bfn) separator))
11911 separator))
11912 (if just-return-string
11913 (org-no-properties res)
11914 (org-unlogged-message "%s" res))))
11916 (defvar org-refile-history nil
11917 "History for refiling operations.")
11919 (defvar org-after-refile-insert-hook nil
11920 "Hook run after `org-refile' has inserted its stuff at the new location.
11921 Note that this is still *before* the stuff will be removed from
11922 the *old* location.")
11924 (defvar org-capture-last-stored-marker)
11925 (defvar org-refile-keep nil
11926 "Non-nil means `org-refile' will copy instead of refile.")
11928 (defun org-copy ()
11929 "Like `org-refile', but copy."
11930 (interactive)
11931 (let ((org-refile-keep t))
11932 (funcall 'org-refile nil nil nil "Copy")))
11934 (defun org-refile (&optional arg default-buffer rfloc msg)
11935 "Move the entry or entries at point to another heading.
11936 The list of target headings is compiled using the information in
11937 `org-refile-targets', which see.
11939 At the target location, the entry is filed as a subitem of the
11940 target heading. Depending on `org-reverse-note-order', the new
11941 subitem will either be the first or the last subitem.
11943 If there is an active region, all entries in that region will be
11944 refiled. However, the region must fulfill the requirement that
11945 the first heading sets the top-level of the moved text.
11947 With prefix arg ARG, the command will only visit the target
11948 location and not actually move anything.
11950 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11951 refiling operation has put the subtree.
11953 With a numeric prefix argument of `2', refile to the running clock.
11955 With a numeric prefix argument of `3', emulate `org-refile-keep'
11956 being set to t and copy to the target location, don't move it.
11957 Beware that keeping refiled entries may result in duplicated ID
11958 properties.
11960 RFLOC can be a refile location obtained in a different way.
11962 MSG is a string to replace \"Refile\" in the default prompt with
11963 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11965 See also `org-refile-use-outline-path'.
11967 If you are using target caching (see `org-refile-use-cache'), you
11968 have to clear the target cache in order to find new targets.
11969 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11970 prefix argument (`C-u C-u C-u C-c C-w')."
11971 (interactive "P")
11972 (if (member arg '(0 (64)))
11973 (org-refile-cache-clear)
11974 (let* ((actionmsg (cond (msg msg)
11975 ((equal arg 3) "Refile (and keep)")
11976 (t "Refile")))
11977 (regionp (org-region-active-p))
11978 (region-start (and regionp (region-beginning)))
11979 (region-end (and regionp (region-end)))
11980 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11981 pos it nbuf file level reversed)
11982 (setq last-command nil)
11983 (when regionp
11984 (goto-char region-start)
11985 (or (bolp) (goto-char (point-at-bol)))
11986 (setq region-start (point))
11987 (unless (or (org-kill-is-subtree-p
11988 (buffer-substring region-start region-end))
11989 (prog1 org-refile-active-region-within-subtree
11990 (let ((s (point-at-eol)))
11991 (org-toggle-heading)
11992 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11993 (user-error "The region is not a (sequence of) subtree(s)")))
11994 (if (equal arg '(16))
11995 (org-refile-goto-last-stored)
11996 (when (or
11997 (and (equal arg 2)
11998 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11999 (prog1
12000 (setq it (list (or org-clock-heading "running clock")
12001 (buffer-file-name
12002 (marker-buffer org-clock-hd-marker))
12004 (marker-position org-clock-hd-marker)))
12005 (setq arg nil)))
12006 (setq it
12007 (or rfloc
12008 (let (heading-text)
12009 (save-excursion
12010 (unless (and arg (listp arg))
12011 (org-back-to-heading t)
12012 (setq heading-text
12013 (replace-regexp-in-string
12014 org-bracket-link-regexp
12015 "\\3"
12016 (or (nth 4 (org-heading-components))
12017 ""))))
12018 (org-refile-get-location
12019 (cond ((and arg (listp arg)) "Goto")
12020 (regionp (concat actionmsg " region to"))
12021 (t (concat actionmsg " subtree \""
12022 heading-text "\" to")))
12023 default-buffer
12024 (and (not (equal '(4) arg))
12025 org-refile-allow-creating-parent-nodes)))))))
12026 (setq file (nth 1 it)
12027 pos (nth 3 it))
12028 (when (and (not arg)
12030 (equal (buffer-file-name) file)
12031 (if regionp
12032 (and (>= pos region-start)
12033 (<= pos region-end))
12034 (and (>= pos (point))
12035 (< pos (save-excursion
12036 (org-end-of-subtree t t))))))
12037 (error "Cannot refile to position inside the tree or region"))
12038 (setq nbuf (or (find-buffer-visiting file)
12039 (find-file-noselect file)))
12040 (if (and arg (not (equal arg 3)))
12041 (progn
12042 (pop-to-buffer-same-window nbuf)
12043 (goto-char pos)
12044 (org-show-context 'org-goto))
12045 (if regionp
12046 (progn
12047 (org-kill-new (buffer-substring region-start region-end))
12048 (org-save-markers-in-region region-start region-end))
12049 (org-copy-subtree 1 nil t))
12050 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
12051 (find-file-noselect file)))
12052 (setq reversed (org-notes-order-reversed-p))
12053 (save-excursion
12054 (save-restriction
12055 (widen)
12056 (if pos
12057 (progn
12058 (goto-char pos)
12059 (looking-at org-outline-regexp)
12060 (setq level (org-get-valid-level (funcall outline-level) 1))
12061 (goto-char
12062 (if reversed
12063 (or (outline-next-heading) (point-max))
12064 (or (save-excursion (org-get-next-sibling))
12065 (org-end-of-subtree t t)
12066 (point-max)))))
12067 (setq level 1)
12068 (if (not reversed)
12069 (goto-char (point-max))
12070 (goto-char (point-min))
12071 (or (outline-next-heading) (goto-char (point-max)))))
12072 (unless (bolp) (newline))
12073 (org-paste-subtree level nil nil t)
12074 (when org-log-refile
12075 (org-add-log-setup 'refile nil nil org-log-refile)
12076 (unless (eq org-log-refile 'note)
12077 (save-excursion (org-add-log-note))))
12078 (and org-auto-align-tags
12079 (let ((org-loop-over-headlines-in-active-region nil))
12080 (org-set-tags nil t)))
12081 (let ((bookmark-name (plist-get org-bookmark-names-plist
12082 :last-refile)))
12083 (when bookmark-name
12084 (with-demoted-errors
12085 (bookmark-set bookmark-name))))
12086 ;; If we are refiling for capture, make sure that the
12087 ;; last-capture pointers point here
12088 (when (bound-and-true-p org-capture-is-refiling)
12089 (let ((bookmark-name (plist-get org-bookmark-names-plist
12090 :last-capture-marker)))
12091 (when bookmark-name
12092 (with-demoted-errors
12093 (bookmark-set bookmark-name))))
12094 (move-marker org-capture-last-stored-marker (point)))
12095 (when (fboundp 'deactivate-mark) (deactivate-mark))
12096 (run-hooks 'org-after-refile-insert-hook))))
12097 (unless org-refile-keep
12098 (if regionp
12099 (delete-region (point) (+ (point) (- region-end region-start)))
12100 (delete-region
12101 (and (org-back-to-heading t) (point))
12102 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12103 (when (featurep 'org-inlinetask)
12104 (org-inlinetask-remove-END-maybe))
12105 (setq org-markers-to-move nil)
12106 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12108 (defun org-refile-goto-last-stored ()
12109 "Go to the location where the last refile was stored."
12110 (interactive)
12111 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12112 (message "This is the location of the last refile"))
12114 (defun org-refile--get-location (refloc tbl)
12115 "When user refile to REFLOC, find the associated target in TBL.
12116 Also check `org-refile-target-table'."
12117 (car (delq
12119 (mapcar
12120 (lambda (r) (or (assoc r tbl)
12121 (assoc r org-refile-target-table)))
12122 (list (replace-regexp-in-string "/$" "" refloc)
12123 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12125 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12126 "Prompt the user for a refile location, using PROMPT.
12127 PROMPT should not be suffixed with a colon and a space, because
12128 this function appends the default value from
12129 `org-refile-history' automatically, if that is not empty."
12130 (let ((org-refile-targets org-refile-targets)
12131 (org-refile-use-outline-path org-refile-use-outline-path))
12132 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12133 (unless org-refile-target-table
12134 (user-error "No refile targets"))
12135 (let* ((cbuf (current-buffer))
12136 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12137 (cfunc (if (and org-refile-use-outline-path
12138 org-outline-path-complete-in-steps)
12139 #'org-olpath-completing-read
12140 #'completing-read))
12141 (extra (if org-refile-use-outline-path "/" ""))
12142 (cbnex (concat (buffer-name) extra))
12143 (filename (and cfn (expand-file-name cfn)))
12144 (tbl (mapcar
12145 (lambda (x)
12146 (if (and (not (member org-refile-use-outline-path
12147 '(file full-file-path)))
12148 (not (equal filename (nth 1 x))))
12149 (cons (concat (car x) extra " ("
12150 (file-name-nondirectory (nth 1 x)) ")")
12151 (cdr x))
12152 (cons (concat (car x) extra) (cdr x))))
12153 org-refile-target-table))
12154 (completion-ignore-case t)
12155 cdef
12156 (prompt (concat prompt
12157 (or (and (car org-refile-history)
12158 (concat " (default " (car org-refile-history) ")"))
12159 (and (assoc cbnex tbl) (setq cdef cbnex)
12160 (concat " (default " cbnex ")"))) ": "))
12161 pa answ parent-target child parent old-hist)
12162 (setq old-hist org-refile-history)
12163 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12164 nil 'org-refile-history (or cdef (car org-refile-history))))
12165 (if (setq pa (org-refile--get-location answ tbl))
12166 (progn
12167 (org-refile-check-position pa)
12168 (when (or (not org-refile-history)
12169 (not (eq old-hist org-refile-history))
12170 (not (equal (car pa) (car org-refile-history))))
12171 (setq org-refile-history
12172 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12173 org-refile-history
12174 (cdr org-refile-history))))
12175 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12176 (pop org-refile-history)))
12178 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12179 (progn
12180 (setq parent (match-string 1 answ)
12181 child (match-string 2 answ))
12182 (setq parent-target (org-refile--get-location parent tbl))
12183 (when (and parent-target
12184 (or (eq new-nodes t)
12185 (and (eq new-nodes 'confirm)
12186 (y-or-n-p (format "Create new node \"%s\"? "
12187 child)))))
12188 (org-refile-new-child parent-target child)))
12189 (user-error "Invalid target location")))))
12191 (declare-function org-string-nw-p "org-macs" (s))
12192 (defun org-refile-check-position (refile-pointer)
12193 "Check if the refile pointer matches the headline to which it points."
12194 (let* ((file (nth 1 refile-pointer))
12195 (re (nth 2 refile-pointer))
12196 (pos (nth 3 refile-pointer))
12197 buffer)
12198 (if (and (not (markerp pos)) (not file))
12199 (user-error "Please indicate a target file in the refile path")
12200 (when (org-string-nw-p re)
12201 (setq buffer (if (markerp pos)
12202 (marker-buffer pos)
12203 (or (find-buffer-visiting file)
12204 (find-file-noselect file))))
12205 (with-current-buffer buffer
12206 (save-excursion
12207 (save-restriction
12208 (widen)
12209 (goto-char pos)
12210 (beginning-of-line 1)
12211 (unless (looking-at-p re)
12212 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12214 (defun org-refile-new-child (parent-target child)
12215 "Use refile target PARENT-TARGET to add new CHILD below it."
12216 (unless parent-target
12217 (error "Cannot find parent for new node"))
12218 (let ((file (nth 1 parent-target))
12219 (pos (nth 3 parent-target))
12220 level)
12221 (with-current-buffer (or (find-buffer-visiting file)
12222 (find-file-noselect file))
12223 (save-excursion
12224 (save-restriction
12225 (widen)
12226 (if pos
12227 (goto-char pos)
12228 (goto-char (point-max))
12229 (unless (bolp) (newline)))
12230 (when (looking-at org-outline-regexp)
12231 (setq level (funcall outline-level))
12232 (org-end-of-subtree t t))
12233 (org-back-over-empty-lines)
12234 (insert "\n" (make-string
12235 (if pos (org-get-valid-level level 1) 1) ?*)
12236 " " child "\n")
12237 (beginning-of-line 0)
12238 (list (concat (car parent-target) "/" child) file "" (point)))))))
12240 (defun org-olpath-completing-read (prompt collection &rest args)
12241 "Read an outline path like a file name."
12242 (let ((thetable collection))
12243 (apply #'completing-read
12244 prompt
12245 (lambda (string predicate &optional flag)
12246 (cond
12247 ((eq flag nil) (try-completion string thetable))
12248 ((eq flag t)
12249 (let ((l (length string)))
12250 (mapcar (lambda (x)
12251 (let ((r (substring x l))
12252 (f (if (string-match " ([^)]*)$" x)
12253 (match-string 0 x)
12254 "")))
12255 (if (string-match "/" r)
12256 (concat string (substring r 0 (match-end 0)) f)
12257 x)))
12258 (all-completions string thetable predicate))))
12259 ;; Exact match?
12260 ((eq flag 'lambda) (assoc string thetable))))
12261 args)))
12263 ;;;; Dynamic blocks
12265 (defun org-find-dblock (name)
12266 "Find the first dynamic block with name NAME in the buffer.
12267 If not found, stay at current position and return nil."
12268 (let ((case-fold-search t) pos)
12269 (save-excursion
12270 (goto-char (point-min))
12271 (setq pos (and (re-search-forward
12272 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12273 (match-beginning 0))))
12274 (when pos (goto-char pos))
12275 pos))
12277 (defun org-create-dblock (plist)
12278 "Create a dynamic block section, with parameters taken from PLIST.
12279 PLIST must contain a :name entry which is used as the name of the block."
12280 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12281 (end-of-line 1)
12282 (newline))
12283 (let ((col (current-column))
12284 (name (plist-get plist :name)))
12285 (insert "#+BEGIN: " name)
12286 (while plist
12287 (if (eq (car plist) :name)
12288 (setq plist (cddr plist))
12289 (insert " " (prin1-to-string (pop plist)))))
12290 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12291 (beginning-of-line -2)))
12293 (defun org-prepare-dblock ()
12294 "Prepare dynamic block for refresh.
12295 This empties the block, puts the cursor at the insert position and returns
12296 the property list including an extra property :name with the block name."
12297 (unless (looking-at org-dblock-start-re)
12298 (user-error "Not at a dynamic block"))
12299 (let* ((begdel (1+ (match-end 0)))
12300 (name (org-no-properties (match-string 1)))
12301 (params (append (list :name name)
12302 (read (concat "(" (match-string 3) ")")))))
12303 (save-excursion
12304 (beginning-of-line 1)
12305 (skip-chars-forward " \t")
12306 (setq params (plist-put params :indentation-column (current-column))))
12307 (unless (re-search-forward org-dblock-end-re nil t)
12308 (error "Dynamic block not terminated"))
12309 (setq params
12310 (append params
12311 (list :content (buffer-substring
12312 begdel (match-beginning 0)))))
12313 (delete-region begdel (match-beginning 0))
12314 (goto-char begdel)
12315 (open-line 1)
12316 params))
12318 (defun org-map-dblocks (&optional command)
12319 "Apply COMMAND to all dynamic blocks in the current buffer.
12320 If COMMAND is not given, use `org-update-dblock'."
12321 (let ((cmd (or command 'org-update-dblock)))
12322 (save-excursion
12323 (goto-char (point-min))
12324 (while (re-search-forward org-dblock-start-re nil t)
12325 (goto-char (match-beginning 0))
12326 (save-excursion
12327 (condition-case nil
12328 (funcall cmd)
12329 (error (message "Error during update of dynamic block"))))
12330 (unless (re-search-forward org-dblock-end-re nil t)
12331 (error "Dynamic block not terminated"))))))
12333 (defun org-dblock-update (&optional arg)
12334 "User command for updating dynamic blocks.
12335 Update the dynamic block at point. With prefix ARG, update all dynamic
12336 blocks in the buffer."
12337 (interactive "P")
12338 (if arg
12339 (org-update-all-dblocks)
12340 (or (looking-at org-dblock-start-re)
12341 (org-beginning-of-dblock))
12342 (org-update-dblock)))
12344 (defun org-update-dblock ()
12345 "Update the dynamic block at point.
12346 This means to empty the block, parse for parameters and then call
12347 the correct writing function."
12348 (interactive)
12349 (save-excursion
12350 (let* ((win (selected-window))
12351 (pos (point))
12352 (line (org-current-line))
12353 (params (org-prepare-dblock))
12354 (name (plist-get params :name))
12355 (indent (plist-get params :indentation-column))
12356 (cmd (intern (concat "org-dblock-write:" name))))
12357 (message "Updating dynamic block `%s' at line %d..." name line)
12358 (funcall cmd params)
12359 (message "Updating dynamic block `%s' at line %d...done" name line)
12360 (goto-char pos)
12361 (when (and indent (> indent 0))
12362 (setq indent (make-string indent ?\ ))
12363 (save-excursion
12364 (select-window win)
12365 (org-beginning-of-dblock)
12366 (forward-line 1)
12367 (while (not (looking-at org-dblock-end-re))
12368 (insert indent)
12369 (beginning-of-line 2))
12370 (when (looking-at org-dblock-end-re)
12371 (and (looking-at "[ \t]+")
12372 (replace-match ""))
12373 (insert indent)))))))
12375 (defun org-beginning-of-dblock ()
12376 "Find the beginning of the dynamic block at point.
12377 Error if there is no such block at point."
12378 (let ((pos (point))
12379 beg)
12380 (end-of-line 1)
12381 (if (and (re-search-backward org-dblock-start-re nil t)
12382 (setq beg (match-beginning 0))
12383 (re-search-forward org-dblock-end-re nil t)
12384 (> (match-end 0) pos))
12385 (goto-char beg)
12386 (goto-char pos)
12387 (error "Not in a dynamic block"))))
12389 (defun org-update-all-dblocks ()
12390 "Update all dynamic blocks in the buffer.
12391 This function can be used in a hook."
12392 (interactive)
12393 (when (derived-mode-p 'org-mode)
12394 (org-map-dblocks 'org-update-dblock)))
12397 ;;;; Completion
12399 (declare-function org-export-backend-options "ox" (cl-x) t)
12400 (defun org-get-export-keywords ()
12401 "Return a list of all currently understood export keywords.
12402 Export keywords include options, block names, attributes and
12403 keywords relative to each registered export back-end."
12404 (let (keywords)
12405 (dolist (backend
12406 (bound-and-true-p org-export-registered-backends)
12407 (delq nil keywords))
12408 ;; Back-end name (for keywords, like #+LATEX:)
12409 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12410 (dolist (option-entry (org-export-backend-options backend))
12411 ;; Back-end options.
12412 (push (nth 1 option-entry) keywords)))))
12414 (defconst org-options-keywords
12415 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12416 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12417 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12418 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12419 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12421 (defcustom org-structure-template-alist
12422 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12423 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12424 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12425 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12426 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12427 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12428 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12429 ("L" "#+LaTeX: ")
12430 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12431 ("H" "#+HTML: ")
12432 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12433 ("A" "#+ASCII: ")
12434 ("i" "#+INDEX: ?")
12435 ("I" "#+INCLUDE: %file ?"))
12436 "Structure completion elements.
12437 This is a list of abbreviation keys and values. The value gets inserted
12438 if you type `<' followed by the key and then press the completion key,
12439 usually `TAB'. %file will be replaced by a file name after prompting
12440 for the file using completion. The cursor will be placed at the position
12441 of the `?' in the template.
12442 There are two templates for each key, the first uses the original Org syntax,
12443 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12444 the default when the /org-mtags.el/ module has been loaded. See also the
12445 variable `org-mtags-prefer-muse-templates'."
12446 :group 'org-completion
12447 :type '(repeat
12448 (list
12449 (string :tag "Key")
12450 (string :tag "Template")))
12451 :version "25.1"
12452 :package-version '(Org . "8.3"))
12454 (defun org-try-structure-completion ()
12455 "Try to complete a structure template before point.
12456 This looks for strings like \"<e\" on an otherwise empty line and
12457 expands them."
12458 (let ((l (buffer-substring (point-at-bol) (point)))
12460 (when (and (looking-at "[ \t]*$")
12461 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12462 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12463 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12464 (match-beginning 1)) a)
12465 t)))
12467 (defun org-complete-expand-structure-template (start cell)
12468 "Expand a structure template."
12469 (let ((rpl (nth 1 cell))
12470 (ind ""))
12471 (delete-region start (point))
12472 (when (string-match "\\`[ \t]*#\\+" rpl)
12473 (cond
12474 ((bolp))
12475 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12476 (setq ind (buffer-substring (point-at-bol) (point))))
12477 (t (newline))))
12478 (setq start (point))
12479 (when (string-match "%file" rpl)
12480 (setq rpl (replace-match
12481 (concat
12482 "\""
12483 (save-match-data
12484 (abbreviate-file-name (read-file-name "Include file: ")))
12485 "\"")
12486 t t rpl)))
12487 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12488 (concat "\n" ind)))
12489 (insert rpl)
12490 (when (re-search-backward "\\?" start t) (delete-char 1))))
12492 ;;;; TODO, DEADLINE, Comments
12494 (defun org-toggle-comment ()
12495 "Change the COMMENT state of an entry."
12496 (interactive)
12497 (save-excursion
12498 (org-back-to-heading)
12499 (looking-at org-complex-heading-regexp)
12500 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12501 (skip-chars-forward " \t")
12502 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12503 (if (org-in-commented-heading-p t)
12504 (delete-region (point)
12505 (progn (search-forward " " (line-end-position) 'move)
12506 (skip-chars-forward " \t")
12507 (point)))
12508 (insert org-comment-string)
12509 (unless (eolp) (insert " ")))))
12511 (defvar org-last-todo-state-is-todo nil
12512 "This is non-nil when the last TODO state change led to a TODO state.
12513 If the last change removed the TODO tag or switched to DONE, then
12514 this is nil.")
12516 (defvar org-setting-tags nil) ; dynamically skipped
12518 (defvar org-todo-setup-filter-hook nil
12519 "Hook for functions that pre-filter todo specs.
12520 Each function takes a todo spec and returns either nil or the spec
12521 transformed into canonical form." )
12523 (defvar org-todo-get-default-hook nil
12524 "Hook for functions that get a default item for todo.
12525 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12526 nil or a string to be used for the todo mark." )
12528 (defvar org-agenda-headline-snapshot-before-repeat)
12530 (defun org-current-effective-time ()
12531 "Return current time adjusted for `org-extend-today-until' variable."
12532 (let* ((ct (org-current-time))
12533 (dct (decode-time ct))
12534 (ct1
12535 (cond
12536 (org-use-last-clock-out-time-as-effective-time
12537 (or (org-clock-get-last-clock-out-time) ct))
12538 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12539 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12540 (t ct))))
12541 ct1))
12543 (defun org-todo-yesterday (&optional arg)
12544 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12545 (interactive "P")
12546 (if (eq major-mode 'org-agenda-mode)
12547 (apply 'org-agenda-todo-yesterday arg)
12548 (let* ((org-use-effective-time t)
12549 (hour (nth 2 (decode-time (org-current-time))))
12550 (org-extend-today-until (1+ hour)))
12551 (org-todo arg))))
12553 (defvar org-block-entry-blocking ""
12554 "First entry preventing the TODO state change.")
12556 (defun org-cancel-repeater ()
12557 "Cancel a repeater by setting its numeric value to zero."
12558 (interactive)
12559 (save-excursion
12560 (org-back-to-heading t)
12561 (let ((bound1 (point))
12562 (bound0 (save-excursion (outline-next-heading) (point))))
12563 (when (and (re-search-forward
12564 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12565 org-deadline-time-regexp "\\)\\|\\("
12566 org-ts-regexp "\\)")
12567 bound0 t)
12568 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12569 bound1 t))
12570 (replace-match "0" t nil nil 1)))))
12572 (defvar org-state) ;; dynamically scoped into this function
12573 (defun org-todo (&optional arg)
12574 "Change the TODO state of an item.
12575 The state of an item is given by a keyword at the start of the heading,
12576 like
12577 *** TODO Write paper
12578 *** DONE Call mom
12580 The different keywords are specified in the variable `org-todo-keywords'.
12581 By default the available states are \"TODO\" and \"DONE\".
12582 So for this example: when the item starts with TODO, it is changed to DONE.
12583 When it starts with DONE, the DONE is removed. And when neither TODO nor
12584 DONE are present, add TODO at the beginning of the heading.
12586 With \\[universal-argument] prefix arg, use completion to determine the new \
12587 state.
12588 With numeric prefix arg, switch to that state.
12589 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12590 keywords (nextset).
12591 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12592 With a numeric prefix arg of 0, inhibit note taking for the change.
12593 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12595 When called through ELisp, arg is also interpreted in the following way:
12596 `none' -> empty state
12597 \"\"(empty string) -> switch to empty state
12598 `done' -> switch to DONE
12599 `nextset' -> switch to the next set of keywords
12600 `previousset' -> switch to the previous set of keywords
12601 \"WAITING\" -> switch to the specified keyword, but only if it
12602 really is a member of `org-todo-keywords'."
12603 (interactive "P")
12604 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12605 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12606 'region-start-level 'region))
12607 org-loop-over-headlines-in-active-region)
12608 (org-map-entries
12609 `(org-todo ,arg)
12610 org-loop-over-headlines-in-active-region
12611 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12612 (when (equal arg '(16)) (setq arg 'nextset))
12613 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12614 (let ((org-blocker-hook org-blocker-hook)
12615 commentp
12616 case-fold-search)
12617 (when (equal arg '(64))
12618 (setq arg nil org-blocker-hook nil))
12619 (when (and org-blocker-hook
12620 (or org-inhibit-blocking
12621 (org-entry-get nil "NOBLOCKING")))
12622 (setq org-blocker-hook nil))
12623 (save-excursion
12624 (catch 'exit
12625 (org-back-to-heading t)
12626 (when (org-in-commented-heading-p t)
12627 (org-toggle-comment)
12628 (setq commentp t))
12629 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12630 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12631 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12632 (let* ((match-data (match-data))
12633 (startpos (point-at-bol))
12634 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12635 (org-log-done org-log-done)
12636 (org-log-repeat org-log-repeat)
12637 (org-todo-log-states org-todo-log-states)
12638 (org-inhibit-logging
12639 (if (equal arg 0)
12640 (progn (setq arg nil) 'note) org-inhibit-logging))
12641 (this (match-string 1))
12642 (hl-pos (match-beginning 0))
12643 (head (org-get-todo-sequence-head this))
12644 (ass (assoc head org-todo-kwd-alist))
12645 (interpret (nth 1 ass))
12646 (done-word (nth 3 ass))
12647 (final-done-word (nth 4 ass))
12648 (org-last-state (or this ""))
12649 (completion-ignore-case t)
12650 (member (member this org-todo-keywords-1))
12651 (tail (cdr member))
12652 (org-state (cond
12653 ((and org-todo-key-trigger
12654 (or (and (equal arg '(4))
12655 (eq org-use-fast-todo-selection 'prefix))
12656 (and (not arg) org-use-fast-todo-selection
12657 (not (eq org-use-fast-todo-selection
12658 'prefix)))))
12659 ;; Use fast selection
12660 (org-fast-todo-selection))
12661 ((and (equal arg '(4))
12662 (or (not org-use-fast-todo-selection)
12663 (not org-todo-key-trigger)))
12664 ;; Read a state with completion
12665 (completing-read
12666 "State: " (mapcar #'list org-todo-keywords-1)
12667 nil t))
12668 ((eq arg 'right)
12669 (if this
12670 (if tail (car tail) nil)
12671 (car org-todo-keywords-1)))
12672 ((eq arg 'left)
12673 (unless (equal member org-todo-keywords-1)
12674 (if this
12675 (nth (- (length org-todo-keywords-1)
12676 (length tail) 2)
12677 org-todo-keywords-1)
12678 (org-last org-todo-keywords-1))))
12679 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12680 (setq arg nil))) ; hack to fall back to cycling
12681 (arg
12682 ;; user or caller requests a specific state
12683 (cond
12684 ((equal arg "") nil)
12685 ((eq arg 'none) nil)
12686 ((eq arg 'done) (or done-word (car org-done-keywords)))
12687 ((eq arg 'nextset)
12688 (or (car (cdr (member head org-todo-heads)))
12689 (car org-todo-heads)))
12690 ((eq arg 'previousset)
12691 (let ((org-todo-heads (reverse org-todo-heads)))
12692 (or (car (cdr (member head org-todo-heads)))
12693 (car org-todo-heads))))
12694 ((car (member arg org-todo-keywords-1)))
12695 ((stringp arg)
12696 (user-error "State `%s' not valid in this file" arg))
12697 ((nth (1- (prefix-numeric-value arg))
12698 org-todo-keywords-1))))
12699 ((null member) (or head (car org-todo-keywords-1)))
12700 ((equal this final-done-word) nil) ;; -> make empty
12701 ((null tail) nil) ;; -> first entry
12702 ((memq interpret '(type priority))
12703 (if (eq this-command last-command)
12704 (car tail)
12705 (if (> (length tail) 0)
12706 (or done-word (car org-done-keywords))
12707 nil)))
12709 (car tail))))
12710 (org-state (or
12711 (run-hook-with-args-until-success
12712 'org-todo-get-default-hook org-state org-last-state)
12713 org-state))
12714 (next (if org-state (concat " " org-state " ") " "))
12715 (change-plist (list :type 'todo-state-change :from this :to org-state
12716 :position startpos))
12717 dolog now-done-p)
12718 (when org-blocker-hook
12719 (setq org-last-todo-state-is-todo
12720 (not (member this org-done-keywords)))
12721 (unless (save-excursion
12722 (save-match-data
12723 (org-with-wide-buffer
12724 (run-hook-with-args-until-failure
12725 'org-blocker-hook change-plist))))
12726 (if (called-interactively-p 'interactive)
12727 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12728 this org-state org-block-entry-blocking)
12729 ;; fail silently
12730 (message "TODO state change from %s to %s blocked (by \"%s\")"
12731 this org-state org-block-entry-blocking)
12732 (throw 'exit nil))))
12733 (store-match-data match-data)
12734 (replace-match next t t)
12735 (cond ((equal this org-state)
12736 (message "TODO state was already %s" (org-trim next)))
12737 ((pos-visible-in-window-p hl-pos)
12738 (message "TODO state changed to %s" (org-trim next))))
12739 (unless head
12740 (setq head (org-get-todo-sequence-head org-state)
12741 ass (assoc head org-todo-kwd-alist)
12742 interpret (nth 1 ass)
12743 done-word (nth 3 ass)
12744 final-done-word (nth 4 ass)))
12745 (when (memq arg '(nextset previousset))
12746 (message "Keyword-Set %d/%d: %s"
12747 (- (length org-todo-sets) -1
12748 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12749 (length org-todo-sets)
12750 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12751 (setq org-last-todo-state-is-todo
12752 (not (member org-state org-done-keywords)))
12753 (setq now-done-p (and (member org-state org-done-keywords)
12754 (not (member this org-done-keywords))))
12755 (and logging (org-local-logging logging))
12756 (when (and (or org-todo-log-states org-log-done)
12757 (not (eq org-inhibit-logging t))
12758 (not (memq arg '(nextset previousset))))
12759 ;; we need to look at recording a time and note
12760 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12761 (nth 2 (assoc this org-todo-log-states))))
12762 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12763 (setq dolog 'time))
12764 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12765 (and org-state
12766 (member org-state org-not-done-keywords)
12767 (not (member this org-not-done-keywords))))
12768 ;; This is now a todo state and was not one before
12769 ;; If there was a CLOSED time stamp, get rid of it.
12770 (org-add-planning-info nil nil 'closed))
12771 (when (and now-done-p org-log-done)
12772 ;; It is now done, and it was not done before
12773 (org-add-planning-info 'closed (org-current-effective-time))
12774 (when (and (not dolog) (eq 'note org-log-done))
12775 (org-add-log-setup 'done org-state this 'note)))
12776 (when (and org-state dolog)
12777 ;; This is a non-nil state, and we need to log it
12778 (org-add-log-setup 'state org-state this dolog)))
12779 ;; Fixup tag positioning
12780 (org-todo-trigger-tag-changes org-state)
12781 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12782 (when org-provide-todo-statistics
12783 (org-update-parent-todo-statistics))
12784 (run-hooks 'org-after-todo-state-change-hook)
12785 (when (and arg (not (member org-state org-done-keywords)))
12786 (setq head (org-get-todo-sequence-head org-state)))
12787 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12788 ;; Do we need to trigger a repeat?
12789 (when now-done-p
12790 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12791 ;; This is for the agenda, take a snapshot of the headline.
12792 (save-match-data
12793 (setq org-agenda-headline-snapshot-before-repeat
12794 (org-get-heading))))
12795 (org-auto-repeat-maybe org-state))
12796 ;; Fixup cursor location if close to the keyword
12797 (when (and (outline-on-heading-p)
12798 (not (bolp))
12799 (save-excursion (beginning-of-line 1)
12800 (looking-at org-todo-line-regexp))
12801 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12802 (goto-char (or (match-end 2) (match-end 1)))
12803 (and (looking-at " ") (just-one-space)))
12804 (when org-trigger-hook
12805 (save-excursion
12806 (run-hook-with-args 'org-trigger-hook change-plist)))
12807 (when commentp (org-toggle-comment))))))))
12809 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12810 "Block turning an entry into a TODO, using the hierarchy.
12811 This checks whether the current task should be blocked from state
12812 changes. Such blocking occurs when:
12814 1. The task has children which are not all in a completed state.
12816 2. A task has a parent with the property :ORDERED:, and there
12817 are siblings prior to the current task with incomplete
12818 status.
12820 3. The parent of the task is blocked because it has siblings that should
12821 be done first, or is child of a block grandparent TODO entry."
12823 (if (not org-enforce-todo-dependencies)
12824 t ; if locally turned off don't block
12825 (catch 'dont-block
12826 ;; If this is not a todo state change, or if this entry is already DONE,
12827 ;; do not block
12828 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12829 (member (plist-get change-plist :from)
12830 (cons 'done org-done-keywords))
12831 (member (plist-get change-plist :to)
12832 (cons 'todo org-not-done-keywords))
12833 (not (plist-get change-plist :to)))
12834 (throw 'dont-block t))
12835 ;; If this task has children, and any are undone, it's blocked
12836 (save-excursion
12837 (org-back-to-heading t)
12838 (let ((this-level (funcall outline-level)))
12839 (outline-next-heading)
12840 (let ((child-level (funcall outline-level)))
12841 (while (and (not (eobp))
12842 (> child-level this-level))
12843 ;; this todo has children, check whether they are all
12844 ;; completed
12845 (when (and (not (org-entry-is-done-p))
12846 (org-entry-is-todo-p))
12847 (setq org-block-entry-blocking (org-get-heading))
12848 (throw 'dont-block nil))
12849 (outline-next-heading)
12850 (setq child-level (funcall outline-level))))))
12851 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12852 ;; any previous siblings are undone, it's blocked
12853 (save-excursion
12854 (org-back-to-heading t)
12855 (let* ((pos (point))
12856 (parent-pos (and (org-up-heading-safe) (point))))
12857 (unless parent-pos (throw 'dont-block t)) ; no parent
12858 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12859 (forward-line 1)
12860 (re-search-forward org-not-done-heading-regexp pos t))
12861 (setq org-block-entry-blocking (match-string 0))
12862 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12863 ;; Search further up the hierarchy, to see if an ancestor is blocked
12864 (while t
12865 (goto-char parent-pos)
12866 (unless (looking-at org-not-done-heading-regexp)
12867 (throw 'dont-block t)) ; do not block, parent is not a TODO
12868 (setq pos (point))
12869 (setq parent-pos (and (org-up-heading-safe) (point)))
12870 (unless parent-pos (throw 'dont-block t)) ; no parent
12871 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12872 (forward-line 1)
12873 (re-search-forward org-not-done-heading-regexp pos t)
12874 (setq org-block-entry-blocking (org-get-heading)))
12875 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12877 (defcustom org-track-ordered-property-with-tag nil
12878 "Should the ORDERED property also be shown as a tag?
12879 The ORDERED property decides if an entry should require subtasks to be
12880 completed in sequence. Since a property is not very visible, setting
12881 this option means that toggling the ORDERED property with the command
12882 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12883 not relevant for the behavior, but it makes things more visible.
12885 Note that toggling the tag with tags commands will not change the property
12886 and therefore not influence behavior!
12888 This can be t, meaning the tag ORDERED should be used, It can also be a
12889 string to select a different tag for this task."
12890 :group 'org-todo
12891 :type '(choice
12892 (const :tag "No tracking" nil)
12893 (const :tag "Track with ORDERED tag" t)
12894 (string :tag "Use other tag")))
12896 (defun org-toggle-ordered-property ()
12897 "Toggle the ORDERED property of the current entry.
12898 For better visibility, you can track the value of this property with a tag.
12899 See variable `org-track-ordered-property-with-tag'."
12900 (interactive)
12901 (let* ((t1 org-track-ordered-property-with-tag)
12902 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12903 (save-excursion
12904 (org-back-to-heading)
12905 (if (org-entry-get nil "ORDERED")
12906 (progn
12907 (org-delete-property "ORDERED")
12908 (and tag (org-toggle-tag tag 'off))
12909 (message "Subtasks can be completed in arbitrary order"))
12910 (org-entry-put nil "ORDERED" "t")
12911 (and tag (org-toggle-tag tag 'on))
12912 (message "Subtasks must be completed in sequence")))))
12914 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12915 (defun org-block-todo-from-checkboxes (change-plist)
12916 "Block turning an entry into a TODO, using checkboxes.
12917 This checks whether the current task should be blocked from state
12918 changes because there are unchecked boxes in this entry."
12919 (if (not org-enforce-todo-checkbox-dependencies)
12920 t ; if locally turned off don't block
12921 (catch 'dont-block
12922 ;; If this is not a todo state change, or if this entry is already DONE,
12923 ;; do not block
12924 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12925 (member (plist-get change-plist :from)
12926 (cons 'done org-done-keywords))
12927 (member (plist-get change-plist :to)
12928 (cons 'todo org-not-done-keywords))
12929 (not (plist-get change-plist :to)))
12930 (throw 'dont-block t))
12931 ;; If this task has checkboxes that are not checked, it's blocked
12932 (save-excursion
12933 (org-back-to-heading t)
12934 (let ((beg (point)) end)
12935 (outline-next-heading)
12936 (setq end (point))
12937 (goto-char beg)
12938 (when (org-list-search-forward
12939 (concat (org-item-beginning-re)
12940 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12941 "\\[[- ]\\]")
12942 end t)
12943 (when (boundp 'org-blocked-by-checkboxes)
12944 (setq org-blocked-by-checkboxes t))
12945 (throw 'dont-block nil))))
12946 t))) ; do not block
12948 (defun org-entry-blocked-p ()
12949 "Non-nil if entry at point is blocked."
12950 (and (not (org-entry-get nil "NOBLOCKING"))
12951 (member (org-entry-get nil "TODO") org-not-done-keywords)
12952 (not (run-hook-with-args-until-failure
12953 'org-blocker-hook
12954 (list :type 'todo-state-change
12955 :position (point)
12956 :from 'todo
12957 :to 'done)))))
12959 (defun org-update-statistics-cookies (all)
12960 "Update the statistics cookie, either from TODO or from checkboxes.
12961 This should be called with the cursor in a line with a statistics cookie."
12962 (interactive "P")
12963 (if all
12964 (progn
12965 (org-update-checkbox-count 'all)
12966 (org-map-entries 'org-update-parent-todo-statistics))
12967 (if (not (org-at-heading-p))
12968 (org-update-checkbox-count)
12969 (let ((pos (point-marker))
12970 end l1 l2)
12971 (ignore-errors (org-back-to-heading t))
12972 (if (not (org-at-heading-p))
12973 (org-update-checkbox-count)
12974 (setq l1 (org-outline-level))
12975 (setq end (save-excursion
12976 (outline-next-heading)
12977 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12978 (point)))
12979 (if (and (save-excursion
12980 (re-search-forward
12981 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12982 (not (save-excursion (re-search-forward
12983 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12984 (org-update-checkbox-count)
12985 (if (and l2 (> l2 l1))
12986 (progn
12987 (goto-char end)
12988 (org-update-parent-todo-statistics))
12989 (goto-char pos)
12990 (beginning-of-line 1)
12991 (while (re-search-forward
12992 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12993 (point-at-eol) t)
12994 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12995 (goto-char pos)
12996 (move-marker pos nil)))))
12998 (defvar org-entry-property-inherited-from) ;; defined below
12999 (defun org-update-parent-todo-statistics ()
13000 "Update any statistics cookie in the parent of the current headline.
13001 When `org-hierarchical-todo-statistics' is nil, statistics will cover
13002 the entire subtree and this will travel up the hierarchy and update
13003 statistics everywhere."
13004 (let* ((prop (save-excursion (org-up-heading-safe)
13005 (org-entry-get nil "COOKIE_DATA" 'inherit)))
13006 (recursive (or (not org-hierarchical-todo-statistics)
13007 (and prop (string-match "\\<recursive\\>" prop))))
13008 (lim (or (and prop (marker-position org-entry-property-inherited-from))
13010 (first t)
13011 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
13012 level ltoggle l1 new ndel
13013 (cnt-all 0) (cnt-done 0) is-percent kwd
13014 checkbox-beg cookie-present)
13015 (catch 'exit
13016 (save-excursion
13017 (beginning-of-line 1)
13018 (setq ltoggle (funcall outline-level))
13019 ;; Three situations are to consider:
13021 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
13022 ;; to the top-level ancestor on the headline;
13024 ;; 2. If parent has "recursive" property, repeat up to the
13025 ;; headline setting that property, taking inheritance into
13026 ;; account;
13028 ;; 3. Else, move up to direct parent and proceed only once.
13029 (while (and (setq level (org-up-heading-safe))
13030 (or recursive first)
13031 (>= (point) lim))
13032 (setq first nil cookie-present nil)
13033 (unless (and level
13034 (not (string-match
13035 "\\<checkbox\\>"
13036 (downcase (or (org-entry-get nil "COOKIE_DATA")
13037 "")))))
13038 (throw 'exit nil))
13039 (while (re-search-forward box-re (point-at-eol) t)
13040 (setq cnt-all 0 cnt-done 0 cookie-present t)
13041 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
13042 (save-match-data
13043 (unless (outline-next-heading) (throw 'exit nil))
13044 (while (and (looking-at org-complex-heading-regexp)
13045 (> (setq l1 (length (match-string 1))) level))
13046 (setq kwd (and (or recursive (= l1 ltoggle))
13047 (match-string 2)))
13048 (if (or (eq org-provide-todo-statistics 'all-headlines)
13049 (and (eq org-provide-todo-statistics t)
13050 (or (member kwd org-done-keywords)))
13051 (and (listp org-provide-todo-statistics)
13052 (stringp (car org-provide-todo-statistics))
13053 (or (member kwd org-provide-todo-statistics)
13054 (member kwd org-done-keywords)))
13055 (and (listp org-provide-todo-statistics)
13056 (listp (car org-provide-todo-statistics))
13057 (or (member kwd (car org-provide-todo-statistics))
13058 (and (member kwd org-done-keywords)
13059 (member kwd (cadr org-provide-todo-statistics))))))
13060 (setq cnt-all (1+ cnt-all))
13061 (and (eq org-provide-todo-statistics t)
13063 (setq cnt-all (1+ cnt-all))))
13064 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
13065 (member kwd org-done-keywords))
13066 (and (listp org-provide-todo-statistics)
13067 (listp (car org-provide-todo-statistics))
13068 (member kwd org-done-keywords)
13069 (member kwd (cadr org-provide-todo-statistics)))
13070 (and (listp org-provide-todo-statistics)
13071 (stringp (car org-provide-todo-statistics))
13072 (member kwd org-done-keywords)))
13073 (setq cnt-done (1+ cnt-done)))
13074 (outline-next-heading)))
13075 (setq new
13076 (if is-percent
13077 (format "[%d%%]" (floor (* 100.0 cnt-done)
13078 (max 1 cnt-all)))
13079 (format "[%d/%d]" cnt-done cnt-all))
13080 ndel (- (match-end 0) checkbox-beg))
13081 (goto-char checkbox-beg)
13082 (insert new)
13083 (delete-region (point) (+ (point) ndel))
13084 (when org-auto-align-tags (org-fix-tags-on-the-fly)))
13085 (when cookie-present
13086 (run-hook-with-args 'org-after-todo-statistics-hook
13087 cnt-done (- cnt-all cnt-done))))))
13088 (run-hooks 'org-todo-statistics-hook)))
13090 (defvar org-after-todo-statistics-hook nil
13091 "Hook that is called after a TODO statistics cookie has been updated.
13092 Each function is called with two arguments: the number of not-done entries
13093 and the number of done entries.
13095 For example, the following function, when added to this hook, will switch
13096 an entry to DONE when all children are done, and back to TODO when new
13097 entries are set to a TODO status. Note that this hook is only called
13098 when there is a statistics cookie in the headline!
13100 \(defun org-summary-todo (n-done n-not-done)
13101 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13102 \(let (org-log-done org-log-states) ; turn off logging
13103 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13106 (defvar org-todo-statistics-hook nil
13107 "Hook that is run whenever Org thinks TODO statistics should be updated.
13108 This hook runs even if there is no statistics cookie present, in which case
13109 `org-after-todo-statistics-hook' would not run.")
13111 (defun org-todo-trigger-tag-changes (state)
13112 "Apply the changes defined in `org-todo-state-tags-triggers'."
13113 (let ((l org-todo-state-tags-triggers)
13114 changes)
13115 (when (or (not state) (equal state ""))
13116 (setq changes (append changes (cdr (assoc "" l)))))
13117 (when (and (stringp state) (> (length state) 0))
13118 (setq changes (append changes (cdr (assoc state l)))))
13119 (when (member state org-not-done-keywords)
13120 (setq changes (append changes (cdr (assoc 'todo l)))))
13121 (when (member state org-done-keywords)
13122 (setq changes (append changes (cdr (assoc 'done l)))))
13123 (dolist (c changes)
13124 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13126 (defun org-local-logging (value)
13127 "Get logging settings from a property VALUE."
13128 ;; Directly set the variables, they are already local.
13129 (setq org-log-done nil
13130 org-log-repeat nil
13131 org-todo-log-states nil)
13132 (dolist (w (org-split-string value))
13133 (let (a)
13134 (cond
13135 ((setq a (assoc w org-startup-options))
13136 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13137 (set (nth 1 a) (nth 2 a))))
13138 ((setq a (org-extract-log-state-settings w))
13139 (and (member (car a) org-todo-keywords-1)
13140 (push a org-todo-log-states)))))))
13142 (defun org-get-todo-sequence-head (kwd)
13143 "Return the head of the TODO sequence to which KWD belongs.
13144 If KWD is not set, check if there is a text property remembering the
13145 right sequence."
13146 (let (p)
13147 (cond
13148 ((not kwd)
13149 (or (get-text-property (point-at-bol) 'org-todo-head)
13150 (progn
13151 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13152 nil (point-at-eol)))
13153 (get-text-property p 'org-todo-head))))
13154 ((not (member kwd org-todo-keywords-1))
13155 (car org-todo-keywords-1))
13156 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13158 (defun org-fast-todo-selection ()
13159 "Fast TODO keyword selection with single keys.
13160 Returns the new TODO keyword, or nil if no state change should occur."
13161 (let* ((fulltable org-todo-key-alist)
13162 (done-keywords org-done-keywords) ;; needed for the faces.
13163 (maxlen (apply 'max (mapcar
13164 (lambda (x)
13165 (if (stringp (car x)) (string-width (car x)) 0))
13166 fulltable)))
13167 (expert nil)
13168 (fwidth (+ maxlen 3 1 3))
13169 (ncol (/ (- (window-width) 4) fwidth))
13170 tg cnt e c tbl
13171 groups ingroup)
13172 (save-excursion
13173 (save-window-excursion
13174 (if expert
13175 (set-buffer (get-buffer-create " *Org todo*"))
13176 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13177 (erase-buffer)
13178 (setq-local org-done-keywords done-keywords)
13179 (setq tbl fulltable cnt 0)
13180 (while (setq e (pop tbl))
13181 (cond
13182 ((equal e '(:startgroup))
13183 (push '() groups) (setq ingroup t)
13184 (unless (= cnt 0)
13185 (setq cnt 0)
13186 (insert "\n"))
13187 (insert "{ "))
13188 ((equal e '(:endgroup))
13189 (setq ingroup nil cnt 0)
13190 (insert "}\n"))
13191 ((equal e '(:newline))
13192 (unless (= cnt 0)
13193 (setq cnt 0)
13194 (insert "\n")
13195 (setq e (car tbl))
13196 (while (equal (car tbl) '(:newline))
13197 (insert "\n")
13198 (setq tbl (cdr tbl)))))
13200 (setq tg (car e) c (cdr e))
13201 (when ingroup (push tg (car groups)))
13202 (setq tg (org-add-props tg nil 'face
13203 (org-get-todo-face tg)))
13204 (when (and (= cnt 0) (not ingroup)) (insert " "))
13205 (insert "[" c "] " tg (make-string
13206 (- fwidth 4 (length tg)) ?\ ))
13207 (when (= (setq cnt (1+ cnt)) ncol)
13208 (insert "\n")
13209 (when ingroup (insert " "))
13210 (setq cnt 0)))))
13211 (insert "\n")
13212 (goto-char (point-min))
13213 (unless expert (org-fit-window-to-buffer))
13214 (message "[a-z..]:Set [SPC]:clear")
13215 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13216 (cond
13217 ((or (= c ?\C-g)
13218 (and (= c ?q) (not (rassoc c fulltable))))
13219 (setq quit-flag t))
13220 ((= c ?\ ) nil)
13221 ((setq e (rassoc c fulltable) tg (car e))
13223 (t (setq quit-flag t)))))))
13225 (defun org-entry-is-todo-p ()
13226 (member (org-get-todo-state) org-not-done-keywords))
13228 (defun org-entry-is-done-p ()
13229 (member (org-get-todo-state) org-done-keywords))
13231 (defun org-get-todo-state ()
13232 "Return the TODO keyword of the current subtree."
13233 (save-excursion
13234 (org-back-to-heading t)
13235 (and (looking-at org-todo-line-regexp)
13236 (match-end 2)
13237 (match-string 2))))
13239 (defun org-at-date-range-p (&optional inactive-ok)
13240 "Non-nil if point is inside a date range.
13242 When optional argument INACTIVE-OK is non-nil, also consider
13243 inactive time ranges.
13245 When this function returns a non-nil value, match data is set
13246 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13247 on INACTIVE-OK."
13248 (interactive)
13249 (save-excursion
13250 (catch 'exit
13251 (let ((pos (point)))
13252 (skip-chars-backward "^[<\r\n")
13253 (skip-chars-backward "<[")
13254 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13255 (>= (match-end 0) pos)
13256 (throw 'exit t))
13257 (skip-chars-backward "^<[\r\n")
13258 (skip-chars-backward "<[")
13259 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13260 (>= (match-end 0) pos)
13261 (throw 'exit t)))
13262 nil)))
13264 (defun org-get-repeat (&optional tagline)
13265 "Check if there is a deadline/schedule with repeater in this entry."
13266 (save-match-data
13267 (save-excursion
13268 (org-back-to-heading t)
13269 (and (re-search-forward (if tagline
13270 (concat tagline "\\s-*" org-repeat-re)
13271 org-repeat-re)
13272 (org-entry-end-position) t)
13273 (match-string-no-properties 1)))))
13275 (defvar org-last-changed-timestamp)
13276 (defvar org-last-inserted-timestamp)
13277 (defvar org-log-post-message)
13278 (defvar org-log-note-purpose)
13279 (defvar org-log-note-how nil)
13280 (defvar org-log-note-extra)
13281 (defun org-auto-repeat-maybe (done-word)
13282 "Check if the current headline contains a repeated time-stamp.
13284 If yes, set TODO state back to what it was and change the base date
13285 of repeating deadline/scheduled time stamps to new date.
13287 This function is run automatically after each state change to a DONE state."
13288 (let* ((repeat (org-get-repeat))
13289 (aa (assoc org-last-state org-todo-kwd-alist))
13290 (interpret (nth 1 aa))
13291 (head (nth 2 aa))
13292 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13293 (msg "Entry repeats: ")
13294 (org-log-done nil)
13295 (org-todo-log-states nil))
13296 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13297 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13298 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13299 org-todo-repeat-to-state)))
13300 (unless (and to-state (member to-state org-todo-keywords-1))
13301 (setq to-state (if (eq interpret 'type) org-last-state head)))
13302 (org-todo to-state))
13303 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13304 (org-entry-put nil "LAST_REPEAT" (format-time-string
13305 (org-time-stamp-format t t))))
13306 (when org-log-repeat
13307 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13308 (memq 'org-add-log-note post-command-hook))
13309 ;; We are already setup for some record.
13310 (when (eq org-log-repeat 'note)
13311 ;; Make sure we take a note, not only a time stamp.
13312 (setq org-log-note-how 'note))
13313 ;; Set up for taking a record.
13314 (org-add-log-setup 'state
13315 (or done-word (car org-done-keywords))
13316 org-last-state
13317 org-log-repeat)))
13318 (org-back-to-heading t)
13319 (org-add-planning-info nil nil 'closed)
13320 (let ((end (save-excursion (outline-next-heading) (point))))
13321 (while (re-search-forward org-ts-regexp end t)
13322 (when (save-match-data
13323 (or (org-at-planning-p)
13324 (org-at-property-p)
13325 (eq (org-element-type (save-excursion
13326 (backward-char)
13327 (org-element-context)))
13328 'timestamp)))
13329 (let ((type (cond ((match-end 1) org-scheduled-string)
13330 ((match-end 3) org-deadline-string)
13331 (t "Plain:")))
13332 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13333 (cond
13334 ((not
13335 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13336 ;; Time-stamps without a repeater are usually skipped.
13337 ;; However, a SCHEDULED time-stamp without one is
13338 ;; removed, as it is considered as no longer relevant.
13339 (when (equal type org-scheduled-string)
13340 (org-remove-timestamp-with-keyword type)))
13342 (let ((n (string-to-number (match-string 2 ts)))
13343 (what (match-string 3 ts)))
13344 (when (equal what "w") (setq n (* n 7) what "d"))
13345 (when (and (equal what "h")
13346 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13347 ts)))
13348 (user-error
13349 "Cannot repeat in Repeat in %d hour(s) because no hour \
13350 has been set"
13352 ;; Preparation, see if we need to modify the start
13353 ;; date for the change.
13354 (when (match-end 1)
13355 (let ((time (save-match-data (org-time-string-to-time ts))))
13356 (cond
13357 ((equal (match-string 1 ts) ".")
13358 ;; Shift starting date to today
13359 (org-timestamp-change
13360 (- (org-today) (time-to-days time))
13361 'day))
13362 ((equal (match-string 1 ts) "+")
13363 (let ((nshiftmax 10)
13364 (nshift 0))
13365 (while (or (= nshift 0)
13366 (not (time-less-p (current-time) time)))
13367 (when (= (cl-incf nshift) nshiftmax)
13368 (or (y-or-n-p
13369 (format "%d repeater intervals were not \
13370 enough to shift date past today. Continue? "
13371 nshift))
13372 (user-error "Abort")))
13373 (org-timestamp-change n (cdr (assoc what whata)))
13374 (org-at-timestamp-p t)
13375 (setq ts (match-string 1))
13376 (setq time
13377 (save-match-data
13378 (org-time-string-to-time ts)))))
13379 (org-timestamp-change (- n) (cdr (assoc what whata)))
13380 ;; Rematch, so that we have everything in
13381 ;; place for the real shift.
13382 (org-at-timestamp-p t)
13383 (setq ts (match-string 1))
13384 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13385 ts)))))
13386 (save-excursion
13387 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13388 (setq msg
13389 (concat
13390 msg type " " org-last-changed-timestamp " ")))))))))
13391 (setq org-log-post-message msg)
13392 (message "%s" msg))))
13394 (defun org-show-todo-tree (arg)
13395 "Make a compact tree which shows all headlines marked with TODO.
13396 The tree will show the lines where the regexp matches, and all higher
13397 headlines above the match.
13398 With a \\[universal-argument] prefix, prompt for a regexp to match.
13399 With a numeric prefix N, construct a sparse tree for the Nth element
13400 of `org-todo-keywords-1'."
13401 (interactive "P")
13402 (let ((case-fold-search nil)
13403 (kwd-re
13404 (cond ((null arg) org-not-done-regexp)
13405 ((equal arg '(4))
13406 (let ((kwd
13407 (completing-read "Keyword (or KWD1|KWD2|...): "
13408 (mapcar #'list org-todo-keywords-1))))
13409 (concat "\\("
13410 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13411 "\\)\\>")))
13412 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13413 (regexp-quote (nth (1- (prefix-numeric-value arg))
13414 org-todo-keywords-1)))
13415 (t (user-error "Invalid prefix argument: %s" arg)))))
13416 (message "%d TODO entries found"
13417 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13419 (defun org-deadline (arg &optional time)
13420 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13421 With one universal prefix argument, remove any deadline from the item.
13422 With two universal prefix arguments, prompt for a warning delay.
13423 With argument TIME, set the deadline at the corresponding date. TIME
13424 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13425 (interactive "P")
13426 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13427 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13428 'region-start-level 'region))
13429 org-loop-over-headlines-in-active-region)
13430 (org-map-entries
13431 `(org-deadline ',arg ,time)
13432 org-loop-over-headlines-in-active-region
13433 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13434 (let* ((old-date (org-entry-get nil "DEADLINE"))
13435 (old-date-time (when old-date (org-time-string-to-time old-date)))
13436 (repeater (and old-date
13437 (string-match
13438 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13439 old-date)
13440 (match-string 1 old-date))))
13441 (cond
13442 ((equal arg '(4))
13443 (when (and old-date org-log-redeadline)
13444 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13445 (org-remove-timestamp-with-keyword org-deadline-string)
13446 (message "Item no longer has a deadline."))
13447 ((equal arg '(16))
13448 (save-excursion
13449 (org-back-to-heading t)
13450 (if (re-search-forward
13451 org-deadline-time-regexp
13452 (save-excursion (outline-next-heading) (point)) t)
13453 (let* ((rpl0 (match-string 1))
13454 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13455 (replace-match
13456 (concat org-deadline-string
13457 " <" rpl
13458 (format " -%dd"
13459 (abs
13460 (- (time-to-days
13461 (save-match-data
13462 (org-read-date nil t nil "Warn starting from" old-date-time)))
13463 (time-to-days old-date-time))))
13464 ">") t t))
13465 (user-error "No deadline information to update"))))
13467 (org-add-planning-info 'deadline time 'closed)
13468 (when (and old-date
13469 org-log-redeadline
13470 (not (equal old-date org-last-inserted-timestamp)))
13471 (org-add-log-setup
13472 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13473 (when repeater
13474 (save-excursion
13475 (org-back-to-heading t)
13476 (when (re-search-forward (concat org-deadline-string " "
13477 org-last-inserted-timestamp)
13478 (save-excursion
13479 (outline-next-heading) (point)) t)
13480 (goto-char (1- (match-end 0)))
13481 (insert " " repeater)
13482 (setq org-last-inserted-timestamp
13483 (concat (substring org-last-inserted-timestamp 0 -1)
13484 " " repeater
13485 (substring org-last-inserted-timestamp -1))))))
13486 (message "Deadline on %s" org-last-inserted-timestamp))))))
13488 (defun org-schedule (arg &optional time)
13489 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13490 With one universal prefix argument, remove any scheduling date from the item.
13491 With two universal prefix arguments, prompt for a delay cookie.
13492 With argument TIME, scheduled at the corresponding date. TIME can
13493 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13494 (interactive "P")
13495 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13496 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13497 'region-start-level 'region))
13498 org-loop-over-headlines-in-active-region)
13499 (org-map-entries
13500 `(org-schedule ',arg ,time)
13501 org-loop-over-headlines-in-active-region
13502 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13503 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13504 (old-date-time (when old-date (org-time-string-to-time old-date)))
13505 (repeater (and old-date
13506 (string-match
13507 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13508 old-date)
13509 (match-string 1 old-date))))
13510 (cond
13511 ((equal arg '(4))
13512 (progn
13513 (when (and old-date org-log-reschedule)
13514 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13515 (org-remove-timestamp-with-keyword org-scheduled-string)
13516 (message "Item is no longer scheduled.")))
13517 ((equal arg '(16))
13518 (save-excursion
13519 (org-back-to-heading t)
13520 (if (re-search-forward
13521 org-scheduled-time-regexp
13522 (save-excursion (outline-next-heading) (point)) t)
13523 (let* ((rpl0 (match-string 1))
13524 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13525 (replace-match
13526 (concat org-scheduled-string
13527 " <" rpl
13528 (format " -%dd"
13529 (abs
13530 (- (time-to-days
13531 (save-match-data
13532 (org-read-date nil t nil "Delay until" old-date-time)))
13533 (time-to-days old-date-time))))
13534 ">") t t))
13535 (user-error "No scheduled information to update"))))
13537 (org-add-planning-info 'scheduled time 'closed)
13538 (when (and old-date
13539 org-log-reschedule
13540 (not (equal old-date org-last-inserted-timestamp)))
13541 (org-add-log-setup
13542 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13543 (when repeater
13544 (save-excursion
13545 (org-back-to-heading t)
13546 (when (re-search-forward (concat org-scheduled-string " "
13547 org-last-inserted-timestamp)
13548 (save-excursion
13549 (outline-next-heading) (point)) t)
13550 (goto-char (1- (match-end 0)))
13551 (insert " " repeater)
13552 (setq org-last-inserted-timestamp
13553 (concat (substring org-last-inserted-timestamp 0 -1)
13554 " " repeater
13555 (substring org-last-inserted-timestamp -1))))))
13556 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13558 (defun org-get-scheduled-time (pom &optional inherit)
13559 "Get the scheduled time as a time tuple, of a format suitable
13560 for calling org-schedule with, or if there is no scheduling,
13561 returns nil."
13562 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13563 (when time
13564 (apply 'encode-time (org-parse-time-string time)))))
13566 (defun org-get-deadline-time (pom &optional inherit)
13567 "Get the deadline as a time tuple, of a format suitable for
13568 calling org-deadline with, or if there is no scheduling, returns
13569 nil."
13570 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13571 (when time
13572 (apply 'encode-time (org-parse-time-string time)))))
13574 (defun org-remove-timestamp-with-keyword (keyword)
13575 "Remove all time stamps with KEYWORD in the current entry."
13576 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13577 beg)
13578 (save-excursion
13579 (org-back-to-heading t)
13580 (setq beg (point))
13581 (outline-next-heading)
13582 (while (re-search-backward re beg t)
13583 (replace-match "")
13584 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13585 (equal (char-before) ?\ ))
13586 (backward-delete-char 1)
13587 (when (string-match "^[ \t]*$" (buffer-substring
13588 (point-at-bol) (point-at-eol)))
13589 (delete-region (point-at-bol)
13590 (min (point-max) (1+ (point-at-eol))))))))))
13592 (defvar org-time-was-given) ; dynamically scoped parameter
13593 (defvar org-end-time-was-given) ; dynamically scoped parameter
13595 (defun org-at-planning-p ()
13596 "Non-nil when point is on a planning info line."
13597 ;; This is as accurate and faster than `org-element-at-point' since
13598 ;; planning info location is fixed in the section.
13599 (org-with-wide-buffer
13600 (beginning-of-line)
13601 (and (looking-at-p org-planning-line-re)
13602 (eq (point)
13603 (ignore-errors
13604 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13605 (org-back-to-heading t)
13606 (org-with-limited-levels (org-back-to-heading t)))
13607 (line-beginning-position 2))))))
13609 (defun org-add-planning-info (what &optional time &rest remove)
13610 "Insert new timestamp with keyword in the planning line.
13611 WHAT indicates what kind of time stamp to add. It is a symbol
13612 among `closed', `deadline', `scheduled' and nil. TIME indicates
13613 the time to use. If none is given, the user is prompted for
13614 a date. REMOVE indicates what kind of entries to remove. An old
13615 WHAT entry will also be removed."
13616 (let (org-time-was-given org-end-time-was-given default-time default-input)
13617 (catch 'exit
13618 (when (and (memq what '(scheduled deadline))
13619 (or (not time)
13620 (and (stringp time)
13621 (string-match "^[-+]+[0-9]" time))))
13622 ;; Try to get a default date/time from existing timestamp
13623 (save-excursion
13624 (org-back-to-heading t)
13625 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13626 (when (re-search-forward (if (eq what 'scheduled)
13627 org-scheduled-time-regexp
13628 org-deadline-time-regexp)
13629 end t)
13630 (setq ts (match-string 1)
13631 default-time (apply 'encode-time (org-parse-time-string ts))
13632 default-input (and ts (org-get-compact-tod ts)))))))
13633 (when what
13634 (setq time
13635 (if (stringp time)
13636 ;; This is a string (relative or absolute), set
13637 ;; proper date.
13638 (apply #'encode-time
13639 (org-read-date-analyze
13640 time default-time (decode-time default-time)))
13641 ;; If necessary, get the time from the user
13642 (or time (org-read-date nil 'to-time nil nil
13643 default-time default-input)))))
13645 (org-with-wide-buffer
13646 (org-back-to-heading t)
13647 (forward-line)
13648 (unless (bolp) (insert "\n"))
13649 (cond ((looking-at-p org-planning-line-re)
13650 ;; Move to current indentation.
13651 (skip-chars-forward " \t")
13652 ;; Check if we have to remove something.
13653 (dolist (type (if what (cons what remove) remove))
13654 (save-excursion
13655 (when (re-search-forward
13656 (cl-case type
13657 (closed org-closed-time-regexp)
13658 (deadline org-deadline-time-regexp)
13659 (scheduled org-scheduled-time-regexp)
13660 (otherwise
13661 (error "Invalid planning type: %s" type)))
13662 (line-end-position) t)
13663 ;; Delete until next keyword or end of line.
13664 (delete-region
13665 (match-beginning 0)
13666 (if (re-search-forward org-keyword-time-not-clock-regexp
13667 (line-end-position)
13669 (match-beginning 0)
13670 (line-end-position))))))
13671 ;; If there is nothing more to add and no more keyword
13672 ;; is left, remove the line completely.
13673 (if (and (looking-at-p "[ \t]*$") (not what))
13674 (delete-region (line-beginning-position)
13675 (line-beginning-position 2))
13676 ;; If we removed last keyword, do not leave trailing
13677 ;; white space at the end of line.
13678 (let ((p (point)))
13679 (save-excursion
13680 (end-of-line)
13681 (unless (= (skip-chars-backward " \t" p) 0)
13682 (delete-region (point) (line-end-position)))))))
13683 ((not what) (throw 'exit nil)) ; Nothing to do.
13684 (t (insert-before-markers "\n")
13685 (backward-char 1)
13686 (when org-adapt-indentation
13687 (indent-to-column (1+ (org-outline-level))))))
13688 (when what
13689 ;; Insert planning keyword.
13690 (insert (cl-case what
13691 (closed org-closed-string)
13692 (deadline org-deadline-string)
13693 (scheduled org-scheduled-string)
13694 (otherwise (error "Invalid planning type: %s" what)))
13695 " ")
13696 ;; Insert associated timestamp.
13697 (let ((ts (org-insert-time-stamp
13698 time
13699 (or org-time-was-given
13700 (and (eq what 'closed) org-log-done-with-time))
13701 (eq what 'closed)
13702 nil nil (list org-end-time-was-given))))
13703 (unless (eolp) (insert " "))
13704 ts))))))
13706 (defvar org-log-note-marker (make-marker)
13707 "Marker pointing at the entry where the note is to be inserted.")
13708 (defvar org-log-note-purpose nil)
13709 (defvar org-log-note-state nil)
13710 (defvar org-log-note-previous-state nil)
13711 (defvar org-log-note-extra nil)
13712 (defvar org-log-note-window-configuration nil)
13713 (defvar org-log-note-return-to (make-marker))
13714 (defvar org-log-note-effective-time nil
13715 "Remembered current time so that dynamically scoped
13716 `org-extend-today-until' affects timestamps in state change log")
13718 (defvar org-log-post-message nil
13719 "Message to be displayed after a log note has been stored.
13720 The auto-repeater uses this.")
13722 (defun org-add-note ()
13723 "Add a note to the current entry.
13724 This is done in the same way as adding a state change note."
13725 (interactive)
13726 (org-add-log-setup 'note))
13728 (defun org-log-beginning (&optional create)
13729 "Return expected start of log notes in current entry.
13730 When optional argument CREATE is non-nil, the function creates
13731 a drawer to store notes, if necessary. Returned position ignores
13732 narrowing."
13733 (org-with-wide-buffer
13734 (let ((drawer (org-log-into-drawer)))
13735 (cond
13736 (drawer
13737 (org-end-of-meta-data)
13738 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13739 (end (if (org-at-heading-p) (point)
13740 (save-excursion (outline-next-heading) (point))))
13741 (case-fold-search t))
13742 (catch 'exit
13743 ;; Try to find existing drawer.
13744 (while (re-search-forward regexp end t)
13745 (let ((element (org-element-at-point)))
13746 (when (eq (org-element-type element) 'drawer)
13747 (let ((cend (org-element-property :contents-end element)))
13748 (when (and (not org-log-states-order-reversed) cend)
13749 (goto-char cend)))
13750 (throw 'exit nil))))
13751 ;; No drawer found. Create one, if permitted.
13752 (when create
13753 (unless (bolp) (insert "\n"))
13754 (let ((beg (point)))
13755 (insert ":" drawer ":\n:END:\n")
13756 (org-indent-region beg (point)))
13757 (end-of-line -1)))))
13759 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13760 (skip-chars-forward " \t\n")
13761 (beginning-of-line)
13762 (unless org-log-states-order-reversed
13763 (org-skip-over-state-notes)
13764 (skip-chars-backward " \t\n")
13765 (forward-line)))))
13766 (if (bolp) (point) (line-beginning-position 2))))
13768 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13769 "Set up the post command hook to take a note.
13770 If this is about to TODO state change, the new state is expected in STATE.
13771 HOW is an indicator what kind of note should be created.
13772 EXTRA is additional text that will be inserted into the notes buffer."
13773 (move-marker org-log-note-marker (point))
13774 (setq org-log-note-purpose purpose
13775 org-log-note-state state
13776 org-log-note-previous-state prev-state
13777 org-log-note-how how
13778 org-log-note-extra extra
13779 org-log-note-effective-time (org-current-effective-time))
13780 (add-hook 'post-command-hook 'org-add-log-note 'append))
13782 (defun org-skip-over-state-notes ()
13783 "Skip past the list of State notes in an entry."
13784 (when (ignore-errors (goto-char (org-in-item-p)))
13785 (let* ((struct (org-list-struct))
13786 (prevs (org-list-prevs-alist struct))
13787 (regexp
13788 (concat "[ \t]*- +"
13789 (replace-regexp-in-string
13790 " +" " +"
13791 (org-replace-escapes
13792 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13793 `(("%d" . ,org-ts-regexp-inactive)
13794 ("%D" . ,org-ts-regexp)
13795 ("%s" . "\"\\S-+\"")
13796 ("%S" . "\"\\S-+\"")
13797 ("%t" . ,org-ts-regexp-inactive)
13798 ("%T" . ,org-ts-regexp)
13799 ("%u" . ".*?")
13800 ("%U" . ".*?")))))))
13801 (while (looking-at-p regexp)
13802 (goto-char (or (org-list-get-next-item (point) struct prevs)
13803 (org-list-get-item-end (point) struct)))))))
13805 (defun org-add-log-note (&optional _purpose)
13806 "Pop up a window for taking a note, and add this note later."
13807 (remove-hook 'post-command-hook 'org-add-log-note)
13808 (setq org-log-note-window-configuration (current-window-configuration))
13809 (delete-other-windows)
13810 (move-marker org-log-note-return-to (point))
13811 (pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13812 (goto-char org-log-note-marker)
13813 (org-switch-to-buffer-other-window "*Org Note*")
13814 (erase-buffer)
13815 (if (memq org-log-note-how '(time state))
13816 (let (current-prefix-arg) (org-store-log-note))
13817 (let ((org-inhibit-startup t)) (org-mode))
13818 (insert (format "# Insert note for %s.
13819 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13820 (cond
13821 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13822 ((eq org-log-note-purpose 'done) "closed todo item")
13823 ((eq org-log-note-purpose 'state)
13824 (format "state change from \"%s\" to \"%s\""
13825 (or org-log-note-previous-state "")
13826 (or org-log-note-state "")))
13827 ((eq org-log-note-purpose 'reschedule)
13828 "rescheduling")
13829 ((eq org-log-note-purpose 'delschedule)
13830 "no longer scheduled")
13831 ((eq org-log-note-purpose 'redeadline)
13832 "changing deadline")
13833 ((eq org-log-note-purpose 'deldeadline)
13834 "removing deadline")
13835 ((eq org-log-note-purpose 'refile)
13836 "refiling")
13837 ((eq org-log-note-purpose 'note)
13838 "this entry")
13839 (t (error "This should not happen")))))
13840 (when org-log-note-extra (insert org-log-note-extra))
13841 (setq-local org-finish-function 'org-store-log-note)
13842 (run-hooks 'org-log-buffer-setup-hook)))
13844 (defvar org-note-abort nil) ; dynamically scoped
13845 (defun org-store-log-note ()
13846 "Finish taking a log note, and insert it to where it belongs."
13847 (let ((txt (prog1 (buffer-string)
13848 (kill-buffer)))
13849 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13850 lines)
13851 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13852 (setq txt (replace-match "" t t txt)))
13853 (when (string-match "\\s-+\\'" txt)
13854 (setq txt (replace-match "" t t txt)))
13855 (setq lines (org-split-string txt "\n"))
13856 (when (org-string-nw-p note)
13857 (setq note
13858 (org-replace-escapes
13859 note
13860 (list (cons "%u" (user-login-name))
13861 (cons "%U" user-full-name)
13862 (cons "%t" (format-time-string
13863 (org-time-stamp-format 'long 'inactive)
13864 org-log-note-effective-time))
13865 (cons "%T" (format-time-string
13866 (org-time-stamp-format 'long nil)
13867 org-log-note-effective-time))
13868 (cons "%d" (format-time-string
13869 (org-time-stamp-format nil 'inactive)
13870 org-log-note-effective-time))
13871 (cons "%D" (format-time-string
13872 (org-time-stamp-format nil nil)
13873 org-log-note-effective-time))
13874 (cons "%s" (cond
13875 ((not org-log-note-state) "")
13876 ((string-match-p org-ts-regexp
13877 org-log-note-state)
13878 (format "\"[%s]\""
13879 (substring org-log-note-state 1 -1)))
13880 (t (format "\"%s\"" org-log-note-state))))
13881 (cons "%S"
13882 (cond
13883 ((not org-log-note-previous-state) "")
13884 ((string-match-p org-ts-regexp
13885 org-log-note-previous-state)
13886 (format "\"[%s]\""
13887 (substring
13888 org-log-note-previous-state 1 -1)))
13889 (t (format "\"%s\""
13890 org-log-note-previous-state)))))))
13891 (when lines (setq note (concat note " \\\\")))
13892 (push note lines))
13893 (when (and lines (not (or current-prefix-arg org-note-abort)))
13894 (with-current-buffer (marker-buffer org-log-note-marker)
13895 (org-with-wide-buffer
13896 ;; Find location for the new note.
13897 (goto-char org-log-note-marker)
13898 (set-marker org-log-note-marker nil)
13899 (goto-char (org-log-beginning t))
13900 ;; Make sure point is at the beginning of an empty line.
13901 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13902 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13903 ;; In an existing list, add a new item at the top level.
13904 ;; Otherwise, indent line like a regular one.
13905 (let ((itemp (org-in-item-p)))
13906 (if itemp
13907 (indent-line-to
13908 (let ((struct (save-excursion
13909 (goto-char itemp) (org-list-struct))))
13910 (org-list-get-ind (org-list-get-top-point struct) struct)))
13911 (org-indent-line)))
13912 (insert (org-list-bullet-string "-") (pop lines))
13913 (let ((ind (org-list-item-body-column (line-beginning-position))))
13914 (dolist (line lines)
13915 (insert "\n")
13916 (indent-line-to ind)
13917 (insert line)))
13918 (message "Note stored")
13919 (org-back-to-heading t)
13920 (org-cycle-hide-drawers 'children))
13921 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13922 ;; from within `org-add-log-note' because `buffer-undo-list'
13923 ;; is then modified outside of `org-with-remote-undo'.
13924 (when (eq this-command 'org-agenda-todo)
13925 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13926 ;; Don't add undo information when called from `org-agenda-todo'.
13927 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13928 (set-window-configuration org-log-note-window-configuration)
13929 (with-current-buffer (marker-buffer org-log-note-return-to)
13930 (goto-char org-log-note-return-to))
13931 (move-marker org-log-note-return-to nil)
13932 (when org-log-post-message (message "%s" org-log-post-message))))
13934 (defun org-remove-empty-drawer-at (pos)
13935 "Remove an empty drawer at position POS.
13936 POS may also be a marker."
13937 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13938 (org-with-wide-buffer
13939 (goto-char pos)
13940 (let ((drawer (org-element-at-point)))
13941 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13942 (not (org-element-property :contents-begin drawer)))
13943 (delete-region (org-element-property :begin drawer)
13944 (progn (goto-char (org-element-property :end drawer))
13945 (skip-chars-backward " \r\t\n")
13946 (forward-line)
13947 (point))))))))
13949 (defvar org-ts-type nil)
13950 (defun org-sparse-tree (&optional arg type)
13951 "Create a sparse tree, prompt for the details.
13952 This command can create sparse trees. You first need to select the type
13953 of match used to create the tree:
13955 t Show all TODO entries.
13956 T Show entries with a specific TODO keyword.
13957 m Show entries selected by a tags/property match.
13958 p Enter a property name and its value (both with completion on existing
13959 names/values) and show entries with that property.
13960 r Show entries matching a regular expression (`/' can be used as well).
13961 b Show deadlines and scheduled items before a date.
13962 a Show deadlines and scheduled items after a date.
13963 d Show deadlines due within `org-deadline-warning-days'.
13964 D Show deadlines and scheduled items between a date range."
13965 (interactive "P")
13966 (setq type (or type org-sparse-tree-default-date-type))
13967 (setq org-ts-type type)
13968 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13969 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13970 \[c]ycle through date types: %s"
13971 (cl-case type
13972 (all "all timestamps")
13973 (scheduled "only scheduled")
13974 (deadline "only deadline")
13975 (active "only active timestamps")
13976 (inactive "only inactive timestamps")
13977 (closed "with a closed time-stamp")
13978 (otherwise "scheduled/deadline")))
13979 (let ((answer (read-char-exclusive)))
13980 (cl-case answer
13982 (org-sparse-tree
13984 (cadr
13985 (memq type '(nil all scheduled deadline active inactive closed)))))
13986 (?d (call-interactively 'org-check-deadlines))
13987 (?b (call-interactively 'org-check-before-date))
13988 (?a (call-interactively 'org-check-after-date))
13989 (?D (call-interactively 'org-check-dates-range))
13990 (?t (call-interactively 'org-show-todo-tree))
13991 (?T (org-show-todo-tree '(4)))
13992 (?m (call-interactively 'org-match-sparse-tree))
13993 ((?p ?P)
13994 (let* ((kwd (completing-read
13995 "Property: " (mapcar #'list (org-buffer-property-keys))))
13996 (value (completing-read
13997 "Value: " (mapcar #'list (org-property-values kwd)))))
13998 (unless (string-match "\\`{.*}\\'" value)
13999 (setq value (concat "\"" value "\"")))
14000 (org-match-sparse-tree arg (concat kwd "=" value))))
14001 ((?r ?R ?/) (call-interactively 'org-occur))
14002 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
14004 (defvar-local org-occur-highlights nil
14005 "List of overlays used for occur matches.")
14006 (defvar-local org-occur-parameters nil
14007 "Parameters of the active org-occur calls.
14008 This is a list, each call to org-occur pushes as cons cell,
14009 containing the regular expression and the callback, onto the list.
14010 The list can contain several entries if `org-occur' has been called
14011 several time with the KEEP-PREVIOUS argument. Otherwise, this list
14012 will only contain one set of parameters. When the highlights are
14013 removed (for example with `C-c C-c', or with the next edit (depending
14014 on `org-remove-highlights-with-change'), this variable is emptied
14015 as well.")
14017 (defun org-occur (regexp &optional keep-previous callback)
14018 "Make a compact tree which shows all matches of REGEXP.
14020 The tree will show the lines where the regexp matches, and any other context
14021 defined in `org-show-context-detail', which see.
14023 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
14024 done by a previous call to `org-occur' will be kept, to allow stacking of
14025 calls to this command.
14027 Optional argument CALLBACK can be a function of no argument. In this case,
14028 it is called with point at the end of the match, match data being set
14029 accordingly. Current match is shown only if the return value is non-nil.
14030 The function must neither move point nor alter narrowing."
14031 (interactive "sRegexp: \nP")
14032 (when (equal regexp "")
14033 (user-error "Regexp cannot be empty"))
14034 (unless keep-previous
14035 (org-remove-occur-highlights nil nil t))
14036 (push (cons regexp callback) org-occur-parameters)
14037 (let ((cnt 0))
14038 (save-excursion
14039 (goto-char (point-min))
14040 (when (or (not keep-previous) ; do not want to keep
14041 (not org-occur-highlights)) ; no previous matches
14042 ;; hide everything
14043 (org-overview))
14044 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
14045 (isearch-no-upper-case-p regexp t)
14046 org-occur-case-fold-search)))
14047 (while (re-search-forward regexp nil t)
14048 (when (or (not callback)
14049 (save-match-data (funcall callback)))
14050 (setq cnt (1+ cnt))
14051 (when org-highlight-sparse-tree-matches
14052 (org-highlight-new-match (match-beginning 0) (match-end 0)))
14053 (org-show-context 'occur-tree)))))
14054 (when org-remove-highlights-with-change
14055 (add-hook 'before-change-functions 'org-remove-occur-highlights
14056 nil 'local))
14057 (unless org-sparse-tree-open-archived-trees
14058 (org-hide-archived-subtrees (point-min) (point-max)))
14059 (run-hooks 'org-occur-hook)
14060 (when (called-interactively-p 'interactive)
14061 (message "%d match(es) for regexp %s" cnt regexp))
14062 cnt))
14064 (defun org-occur-next-match (&optional n _reset)
14065 "Function for `next-error-function' to find sparse tree matches.
14066 N is the number of matches to move, when negative move backwards.
14067 This function always goes back to the starting point when no
14068 match is found."
14069 (let* ((limit (if (< n 0) (point-min) (point-max)))
14070 (search-func (if (< n 0)
14071 'previous-single-char-property-change
14072 'next-single-char-property-change))
14073 (n (abs n))
14074 (pos (point))
14076 (catch 'exit
14077 (while (setq p1 (funcall search-func (point) 'org-type))
14078 (when (equal p1 limit)
14079 (goto-char pos)
14080 (user-error "No more matches"))
14081 (when (equal (get-char-property p1 'org-type) 'org-occur)
14082 (setq n (1- n))
14083 (when (= n 0)
14084 (goto-char p1)
14085 (throw 'exit (point))))
14086 (goto-char p1))
14087 (goto-char p1)
14088 (user-error "No more matches"))))
14090 (defun org-show-context (&optional key)
14091 "Make sure point and context are visible.
14092 Optional argument KEY, when non-nil, is a symbol. See
14093 `org-show-context-detail' for allowed values and how much is to
14094 be shown."
14095 (org-show-set-visibility
14096 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14097 ((cdr (assq key org-show-context-detail)))
14098 (t (cdr (assq 'default org-show-context-detail))))))
14100 (defun org-show-set-visibility (detail)
14101 "Set visibility around point according to DETAIL.
14102 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14103 `tree', `canonical' or t. See `org-show-context-detail' for more
14104 information."
14105 ;; Show current heading and possibly its entry, following headline
14106 ;; or all children.
14107 (if (and (org-at-heading-p) (not (eq detail 'local)))
14108 (org-flag-heading nil)
14109 (org-show-entry)
14110 ;; If point is hidden within a drawer or a block, make sure to
14111 ;; expose it.
14112 (dolist (o (overlays-at (point)))
14113 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14114 (delete-overlay o)))
14115 (unless (org-before-first-heading-p)
14116 (org-with-limited-levels
14117 (cl-case detail
14118 ((tree canonical t) (org-show-children))
14119 ((nil minimal ancestors))
14120 (t (save-excursion
14121 (outline-next-heading)
14122 (org-flag-heading nil)))))))
14123 ;; Show all siblings.
14124 (when (eq detail 'lineage) (org-show-siblings))
14125 ;; Show ancestors, possibly with their children.
14126 (when (memq detail '(ancestors lineage tree canonical t))
14127 (save-excursion
14128 (while (org-up-heading-safe)
14129 (org-flag-heading nil)
14130 (when (memq detail '(canonical t)) (org-show-entry))
14131 (when (memq detail '(tree canonical t)) (org-show-children))))))
14133 (defvar org-reveal-start-hook nil
14134 "Hook run before revealing a location.")
14136 (defun org-reveal (&optional siblings)
14137 "Show current entry, hierarchy above it, and the following headline.
14139 This can be used to show a consistent set of context around
14140 locations exposed with `org-show-context'.
14142 With optional argument SIBLINGS, on each level of the hierarchy all
14143 siblings are shown. This repairs the tree structure to what it would
14144 look like when opened with hierarchical calls to `org-cycle'.
14146 With double optional argument \\[universal-argument] \\[universal-argument], \
14147 go to the parent and show the
14148 entire tree."
14149 (interactive "P")
14150 (run-hooks 'org-reveal-start-hook)
14151 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14152 ((equal siblings '(16))
14153 (save-excursion
14154 (when (org-up-heading-safe)
14155 (org-show-subtree)
14156 (run-hook-with-args 'org-cycle-hook 'subtree))))
14157 (t (org-show-set-visibility 'lineage))))
14159 (defun org-highlight-new-match (beg end)
14160 "Highlight from BEG to END and mark the highlight is an occur headline."
14161 (let ((ov (make-overlay beg end)))
14162 (overlay-put ov 'face 'secondary-selection)
14163 (overlay-put ov 'org-type 'org-occur)
14164 (push ov org-occur-highlights)))
14166 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14167 "Remove the occur highlights from the buffer.
14168 BEG and END are ignored. If NOREMOVE is nil, remove this function
14169 from the `before-change-functions' in the current buffer."
14170 (interactive)
14171 (unless org-inhibit-highlight-removal
14172 (mapc #'delete-overlay org-occur-highlights)
14173 (setq org-occur-highlights nil)
14174 (setq org-occur-parameters nil)
14175 (unless noremove
14176 (remove-hook 'before-change-functions
14177 'org-remove-occur-highlights 'local))))
14179 ;;;; Priorities
14181 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14182 "Regular expression matching the priority indicator.")
14184 (defvar org-remove-priority-next-time nil)
14186 (defun org-priority-up ()
14187 "Increase the priority of the current item."
14188 (interactive)
14189 (org-priority 'up))
14191 (defun org-priority-down ()
14192 "Decrease the priority of the current item."
14193 (interactive)
14194 (org-priority 'down))
14196 (defun org-priority (&optional action _show)
14197 "Change the priority of an item.
14198 ACTION can be `set', `up', `down', or a character."
14199 (interactive "P")
14200 (if (equal action '(4))
14201 (org-show-priority)
14202 (unless org-enable-priority-commands
14203 (user-error "Priority commands are disabled"))
14204 (setq action (or action 'set))
14205 (let (current new news have remove)
14206 (save-excursion
14207 (org-back-to-heading t)
14208 (when (looking-at org-priority-regexp)
14209 (setq current (string-to-char (match-string 2))
14210 have t))
14211 (cond
14212 ((eq action 'remove)
14213 (setq remove t new ?\ ))
14214 ((or (eq action 'set)
14215 (integerp action))
14216 (if (not (eq action 'set))
14217 (setq new action)
14218 (message "Priority %c-%c, SPC to remove: "
14219 org-highest-priority org-lowest-priority)
14220 (save-match-data
14221 (setq new (read-char-exclusive))))
14222 (when (and (= (upcase org-highest-priority) org-highest-priority)
14223 (= (upcase org-lowest-priority) org-lowest-priority))
14224 (setq new (upcase new)))
14225 (cond ((equal new ?\ ) (setq remove t))
14226 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14227 (user-error "Priority must be between `%c' and `%c'"
14228 org-highest-priority org-lowest-priority))))
14229 ((eq action 'up)
14230 (setq new (if have
14231 (1- current) ; normal cycling
14232 ;; last priority was empty
14233 (if (eq last-command this-command)
14234 org-lowest-priority ; wrap around empty to lowest
14235 ;; default
14236 (if org-priority-start-cycle-with-default
14237 org-default-priority
14238 (1- org-default-priority))))))
14239 ((eq action 'down)
14240 (setq new (if have
14241 (1+ current) ; normal cycling
14242 ;; last priority was empty
14243 (if (eq last-command this-command)
14244 org-highest-priority ; wrap around empty to highest
14245 ;; default
14246 (if org-priority-start-cycle-with-default
14247 org-default-priority
14248 (1+ org-default-priority))))))
14249 (t (user-error "Invalid action")))
14250 (when (or (< (upcase new) org-highest-priority)
14251 (> (upcase new) org-lowest-priority))
14252 (if (and (memq action '(up down))
14253 (not have) (not (eq last-command this-command)))
14254 ;; `new' is from default priority
14255 (error
14256 "The default can not be set, see `org-default-priority' why")
14257 ;; normal cycling: `new' is beyond highest/lowest priority
14258 ;; and is wrapped around to the empty priority
14259 (setq remove t)))
14260 (setq news (format "%c" new))
14261 (if have
14262 (if remove
14263 (replace-match "" t t nil 1)
14264 (replace-match news t t nil 2))
14265 (if remove
14266 (user-error "No priority cookie found in line")
14267 (let ((case-fold-search nil))
14268 (looking-at org-todo-line-regexp))
14269 (if (match-end 2)
14270 (progn
14271 (goto-char (match-end 2))
14272 (insert " [#" news "]"))
14273 (goto-char (match-beginning 3))
14274 (insert "[#" news "] "))))
14275 (org-set-tags nil 'align))
14276 (if remove
14277 (message "Priority removed")
14278 (message "Priority of current item set to %s" news)))))
14280 (defun org-show-priority ()
14281 "Show the priority of the current item.
14282 This priority is composed of the main priority given with the [#A] cookies,
14283 and by additional input from the age of a schedules or deadline entry."
14284 (interactive)
14285 (let ((pri (if (eq major-mode 'org-agenda-mode)
14286 (org-get-at-bol 'priority)
14287 (save-excursion
14288 (save-match-data
14289 (beginning-of-line)
14290 (and (looking-at org-heading-regexp)
14291 (org-get-priority (match-string 0))))))))
14292 (message "Priority is %d" (if pri pri -1000))))
14294 (defun org-get-priority (s)
14295 "Find priority cookie and return priority."
14296 (save-match-data
14297 (if (functionp org-get-priority-function)
14298 (funcall org-get-priority-function)
14299 (if (not (string-match org-priority-regexp s))
14300 (* 1000 (- org-lowest-priority org-default-priority))
14301 (* 1000 (- org-lowest-priority
14302 (string-to-char (match-string 2 s))))))))
14304 ;;;; Tags
14306 (defvar org-agenda-archives-mode)
14307 (defvar org-map-continue-from nil
14308 "Position from where mapping should continue.
14309 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14311 (defvar org-scanner-tags nil
14312 "The current tag list while the tags scanner is running.")
14314 (defvar org-trust-scanner-tags nil
14315 "Should `org-get-tags-at' use the tags for the scanner.
14316 This is for internal dynamical scoping only.
14317 When this is non-nil, the function `org-get-tags-at' will return the value
14318 of `org-scanner-tags' instead of building the list by itself. This
14319 can lead to large speed-ups when the tags scanner is used in a file with
14320 many entries, and when the list of tags is retrieved, for example to
14321 obtain a list of properties. Building the tags list for each entry in such
14322 a file becomes an N^2 operation - but with this variable set, it scales
14323 as N.")
14325 (defvar org--matcher-tags-todo-only nil)
14327 (defun org-scan-tags (action matcher todo-only &optional start-level)
14328 "Scan headline tags with inheritance and produce output ACTION.
14330 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14331 or `agenda' to produce an entry list for an agenda view. It can also be
14332 a Lisp form or a function that should be called at each matched headline, in
14333 this case the return value is a list of all return values from these calls.
14335 MATCHER is a function accepting three arguments, returning
14336 a non-nil value whenever a given set of tags qualifies a headline
14337 for inclusion. See `org-make-tags-matcher' for more information.
14338 As a special case, it can also be set to t (respectively nil) in
14339 order to match all (respectively none) headline.
14341 When TODO-ONLY is non-nil, only lines with a not-done TODO
14342 keyword are included in the output.
14344 START-LEVEL can be a string with asterisks, reducing the scope to
14345 headlines matching this string."
14346 (require 'org-agenda)
14347 (let* ((re (concat "^"
14348 (if start-level
14349 ;; Get the correct level to match
14350 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14351 org-outline-regexp)
14352 " *\\(\\<\\("
14353 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14354 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14355 (props (list 'face 'default
14356 'done-face 'org-agenda-done
14357 'undone-face 'default
14358 'mouse-face 'highlight
14359 'org-not-done-regexp org-not-done-regexp
14360 'org-todo-regexp org-todo-regexp
14361 'org-complex-heading-regexp org-complex-heading-regexp
14362 'help-echo
14363 (format "mouse-2 or RET jump to org file %s"
14364 (abbreviate-file-name
14365 (or (buffer-file-name (buffer-base-buffer))
14366 (buffer-name (buffer-base-buffer)))))))
14367 (org-map-continue-from nil)
14368 lspos tags tags-list
14369 (tags-alist (list (cons 0 org-file-tags)))
14370 (llast 0) rtn rtn1 level category i txt
14371 todo marker entry priority
14372 ts-date ts-date-type ts-date-pair)
14373 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14374 (setq action (list 'lambda nil action)))
14375 (save-excursion
14376 (goto-char (point-min))
14377 (when (eq action 'sparse-tree)
14378 (org-overview)
14379 (org-remove-occur-highlights))
14380 (while (let (case-fold-search)
14381 (re-search-forward re nil t))
14382 (setq org-map-continue-from nil)
14383 (catch :skip
14384 (setq todo
14385 ;; TODO: is the 1-2 difference a bug?
14386 (when (match-end 1) (match-string-no-properties 2))
14387 tags (when (match-end 4) (match-string-no-properties 4)))
14388 (goto-char (setq lspos (match-beginning 0)))
14389 (setq level (org-reduced-level (org-outline-level))
14390 category (org-get-category))
14391 (when (eq action 'agenda)
14392 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14393 ts-date (car ts-date-pair)
14394 ts-date-type (cdr ts-date-pair)))
14395 (setq i llast llast level)
14396 ;; remove tag lists from same and sublevels
14397 (while (>= i level)
14398 (when (setq entry (assoc i tags-alist))
14399 (setq tags-alist (delete entry tags-alist)))
14400 (setq i (1- i)))
14401 ;; add the next tags
14402 (when tags
14403 (setq tags (org-split-string tags ":")
14404 tags-alist
14405 (cons (cons level tags) tags-alist)))
14406 ;; compile tags for current headline
14407 (setq tags-list
14408 (if org-use-tag-inheritance
14409 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14410 tags)
14411 org-scanner-tags tags-list)
14412 (when org-use-tag-inheritance
14413 (setcdr (car tags-alist)
14414 (mapcar (lambda (x)
14415 (setq x (copy-sequence x))
14416 (org-add-prop-inherited x))
14417 (cdar tags-alist))))
14418 (when (and tags org-use-tag-inheritance
14419 (or (not (eq t org-use-tag-inheritance))
14420 org-tags-exclude-from-inheritance))
14421 ;; Selective inheritance, remove uninherited ones.
14422 (setcdr (car tags-alist)
14423 (org-remove-uninherited-tags (cdar tags-alist))))
14424 (when (and
14426 ;; eval matcher only when the todo condition is OK
14427 (and (or (not todo-only) (member todo org-not-done-keywords))
14428 (if (functionp matcher)
14429 (let ((case-fold-search t) (org-trust-scanner-tags t))
14430 (funcall matcher todo tags-list level))
14431 matcher))
14433 ;; Call the skipper, but return t if it does not
14434 ;; skip, so that the `and' form continues evaluating.
14435 (progn
14436 (unless (eq action 'sparse-tree) (org-agenda-skip))
14439 ;; Check if timestamps are deselecting this entry
14440 (or (not todo-only)
14441 (and (member todo org-not-done-keywords)
14442 (or (not org-agenda-tags-todo-honor-ignore-options)
14443 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14445 ;; select this headline
14446 (cond
14447 ((eq action 'sparse-tree)
14448 (and org-highlight-sparse-tree-matches
14449 (org-get-heading) (match-end 0)
14450 (org-highlight-new-match
14451 (match-beginning 1) (match-end 1)))
14452 (org-show-context 'tags-tree))
14453 ((eq action 'agenda)
14454 (setq txt (org-agenda-format-item
14456 (concat
14457 (if (eq org-tags-match-list-sublevels 'indented)
14458 (make-string (1- level) ?.) "")
14459 (org-get-heading))
14460 (make-string level ?\s)
14461 category
14462 tags-list)
14463 priority (org-get-priority txt))
14464 (goto-char lspos)
14465 (setq marker (org-agenda-new-marker))
14466 (org-add-props txt props
14467 'org-marker marker 'org-hd-marker marker 'org-category category
14468 'todo-state todo
14469 'ts-date ts-date
14470 'priority priority
14471 'type (concat "tagsmatch" ts-date-type))
14472 (push txt rtn))
14473 ((functionp action)
14474 (setq org-map-continue-from nil)
14475 (save-excursion
14476 (setq rtn1 (funcall action))
14477 (push rtn1 rtn)))
14478 (t (user-error "Invalid action")))
14480 ;; if we are to skip sublevels, jump to end of subtree
14481 (unless org-tags-match-list-sublevels
14482 (org-end-of-subtree t)
14483 (backward-char 1))))
14484 ;; Get the correct position from where to continue
14485 (if org-map-continue-from
14486 (goto-char org-map-continue-from)
14487 (and (= (point) lspos) (end-of-line 1)))))
14488 (when (and (eq action 'sparse-tree)
14489 (not org-sparse-tree-open-archived-trees))
14490 (org-hide-archived-subtrees (point-min) (point-max)))
14491 (nreverse rtn)))
14493 (defun org-remove-uninherited-tags (tags)
14494 "Remove all tags that are not inherited from the list TAGS."
14495 (cond
14496 ((eq org-use-tag-inheritance t)
14497 (if org-tags-exclude-from-inheritance
14498 (org-delete-all org-tags-exclude-from-inheritance tags)
14499 tags))
14500 ((not org-use-tag-inheritance) nil)
14501 ((stringp org-use-tag-inheritance)
14502 (delq nil (mapcar
14503 (lambda (x)
14504 (if (and (string-match org-use-tag-inheritance x)
14505 (not (member x org-tags-exclude-from-inheritance)))
14506 x nil))
14507 tags)))
14508 ((listp org-use-tag-inheritance)
14509 (delq nil (mapcar
14510 (lambda (x)
14511 (if (member x org-use-tag-inheritance) x nil))
14512 tags)))))
14514 (defun org-match-sparse-tree (&optional todo-only match)
14515 "Create a sparse tree according to tags string MATCH.
14516 MATCH can contain positive and negative selection of tags, like
14517 \"+WORK+URGENT-WITHBOSS\".
14518 If optional argument TODO-ONLY is non-nil, only select lines that are
14519 also TODO lines."
14520 (interactive "P")
14521 (org-agenda-prepare-buffers (list (current-buffer)))
14522 (let ((org--matcher-tags-todo-only todo-only))
14523 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14524 org--matcher-tags-todo-only)))
14526 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14528 (defvar org-cached-props nil)
14529 (defun org-cached-entry-get (pom property)
14530 (if (or (eq t org-use-property-inheritance)
14531 (and (stringp org-use-property-inheritance)
14532 (let ((case-fold-search t))
14533 (string-match-p org-use-property-inheritance property)))
14534 (and (listp org-use-property-inheritance)
14535 (member-ignore-case property org-use-property-inheritance)))
14536 ;; Caching is not possible, check it directly.
14537 (org-entry-get pom property 'inherit)
14538 ;; Get all properties, so we can do complicated checks easily.
14539 (cdr (assoc-string property
14540 (or org-cached-props
14541 (setq org-cached-props (org-entry-properties pom)))
14542 t))))
14544 (defun org-global-tags-completion-table (&optional files)
14545 "Return the list of all tags in all agenda buffer/files.
14546 Optional FILES argument is a list of files which can be used
14547 instead of the agenda files."
14548 (save-excursion
14549 (org-uniquify
14550 (delq nil
14551 (apply #'append
14552 (mapcar
14553 (lambda (file)
14554 (set-buffer (find-file-noselect file))
14555 (mapcar (lambda (x)
14556 (and (stringp (car-safe x))
14557 (list (car-safe x))))
14558 (or org-current-tag-alist (org-get-buffer-tags))))
14559 (if (car-safe files) files
14560 (org-agenda-files))))))))
14562 (defun org-make-tags-matcher (match)
14563 "Create the TAGS/TODO matcher form for the selection string MATCH.
14565 Returns a cons of the selection string MATCH and a function
14566 implementing the matcher.
14568 The matcher is to be called at an Org entry, with point on the
14569 headline, and returns non-nil if the entry matches the selection
14570 string MATCH. It must be called with three arguments: the TODO
14571 keyword at the entry (or nil if none), the list of all tags at
14572 the entry including inherited ones and the reduced level of the
14573 headline. Additionally, the category of the entry, if any, must
14574 be specified as the text property `org-category' on the headline.
14576 This function sets the variable `org--matcher-tags-todo-only' to
14577 a non-nil value if the matcher restricts matching to TODO
14578 entries, otherwise it is not touched.
14580 See also `org-scan-tags'."
14581 (unless match
14582 ;; Get a new match request, with completion against the global
14583 ;; tags table and the local tags in current buffer.
14584 (let ((org-last-tags-completion-table
14585 (org-uniquify
14586 (delq nil (append (org-get-buffer-tags)
14587 (org-global-tags-completion-table))))))
14588 (setq match
14589 (completing-read
14590 "Match: "
14591 'org-tags-completion-function nil nil nil 'org-tags-history))))
14593 (let ((match0 match)
14594 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14595 (start 0)
14596 tagsmatch todomatch tagsmatcher todomatcher)
14598 ;; Expand group tags.
14599 (setq match (org-tags-expand match))
14601 ;; Check if there is a TODO part of this match, which would be the
14602 ;; part after a "/". To make sure that this slash is not part of
14603 ;; a property value to be matched against, we also check that
14604 ;; there is no / after that slash. First, find the last slash.
14605 (let ((s 0))
14606 (while (string-match "/+" match s)
14607 (setq start (match-beginning 0))
14608 (setq s (match-end 0))))
14609 (if (and (string-match "/+" match start)
14610 (not (string-match-p "\"" match start)))
14611 ;; Match contains also a TODO-matching request.
14612 (progn
14613 (setq tagsmatch (substring match 0 (match-beginning 0)))
14614 (setq todomatch (substring match (match-end 0)))
14615 (when (string-match "\\`!" todomatch)
14616 (setq org--matcher-tags-todo-only t)
14617 (setq todomatch (substring todomatch 1)))
14618 (when (string-match "\\`\\s-*\\'" todomatch)
14619 (setq todomatch nil)))
14620 ;; Only matching tags.
14621 (setq tagsmatch match)
14622 (setq todomatch nil))
14624 ;; Make the tags matcher.
14625 (when (org-string-nw-p tagsmatch)
14626 (let ((orlist nil)
14627 (orterms (org-split-string tagsmatch "|"))
14628 term)
14629 (while (setq term (pop orterms))
14630 (while (and (equal (substring term -1) "\\") orterms)
14631 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14632 (while (string-match re term)
14633 (let* ((rest (substring term (match-end 0)))
14634 (minus (and (match-end 1)
14635 (equal (match-string 1 term) "-")))
14636 (tag (save-match-data
14637 (replace-regexp-in-string
14638 "\\\\-" "-" (match-string 2 term))))
14639 (regexp (eq (string-to-char tag) ?{))
14640 (levelp (match-end 4))
14641 (propp (match-end 5))
14643 (cond
14644 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14645 (levelp
14646 `(,(org-op-to-function (match-string 3 term))
14647 level
14648 ,(string-to-number (match-string 4 term))))
14649 (propp
14650 (let* ((gv (pcase (upcase (match-string 5 term))
14651 ("CATEGORY"
14652 '(get-text-property (point) 'org-category))
14653 ("TODO" 'todo)
14654 (p `(org-cached-entry-get nil ,p))))
14655 (pv (match-string 7 term))
14656 (regexp (eq (string-to-char pv) ?{))
14657 (strp (eq (string-to-char pv) ?\"))
14658 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14659 (po (org-op-to-function (match-string 6 term)
14660 (if timep 'time strp))))
14661 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14662 (when timep (setq pv (org-matcher-time pv)))
14663 (cond ((and regexp (eq po 'org<>))
14664 `(not (string-match ,pv (or ,gv ""))))
14665 (regexp `(string-match ,pv (or ,gv "")))
14666 (strp `(,po (or ,gv "") ,pv))
14668 `(,po
14669 (string-to-number (or ,gv ""))
14670 ,(string-to-number pv))))))
14671 (t `(member ,tag tags-list)))))
14672 (push (if minus `(not ,mm) mm) tagsmatcher)
14673 (setq term rest)))
14674 (push `(and ,@tagsmatcher) orlist)
14675 (setq tagsmatcher nil))
14676 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14678 ;; Make the TODO matcher.
14679 (when (org-string-nw-p todomatch)
14680 (let ((orlist nil))
14681 (dolist (term (org-split-string todomatch "|"))
14682 (while (string-match re term)
14683 (let* ((minus (and (match-end 1)
14684 (equal (match-string 1 term) "-")))
14685 (kwd (match-string 2 term))
14686 (regexp (eq (string-to-char kwd) ?{))
14687 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14688 `(equal todo ,kwd))))
14689 (push (if minus `(not ,mm) mm) todomatcher))
14690 (setq term (substring term (match-end 0))))
14691 (push (if (> (length todomatcher) 1)
14692 (cons 'and todomatcher)
14693 (car todomatcher))
14694 orlist)
14695 (setq todomatcher nil))
14696 (setq todomatcher (cons 'or orlist))))
14698 ;; Return the string and function of the matcher. If no
14699 ;; tags-specific or todo-specific matcher exists, match
14700 ;; everything.
14701 (let ((matcher (if (and tagsmatcher todomatcher)
14702 `(and ,tagsmatcher ,todomatcher)
14703 (or tagsmatcher todomatcher t))))
14704 (when org--matcher-tags-todo-only
14705 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14706 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14708 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14709 "Expand group tags in MATCH.
14711 This replaces every group tag in MATCH with a regexp tag search.
14712 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14713 will be replaced like this:
14715 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14716 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14717 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14719 Replacing by a regexp preserves the structure of the match.
14720 E.g., this expansion
14722 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14724 will match anything tagged with \"Lab\" and \"Home\", or tagged
14725 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14727 A group tag in MATCH can contain regular expressions of its own.
14728 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14729 will be replaced like this:
14731 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14733 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14734 assumed to be a single group tag, and the function will return
14735 the list of tags in this group.
14737 When DOWNCASE is non-nil, expand downcased TAGS."
14738 (if org-group-tags
14739 (let* ((case-fold-search t)
14740 (stable org-mode-syntax-table)
14741 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14742 (taggroups (if downcased
14743 (mapcar (lambda (tg) (mapcar #'downcase tg))
14744 taggroups)
14745 taggroups))
14746 (taggroups-keys (mapcar #'car taggroups))
14747 (return-match (if downcased (downcase match) match))
14748 (count 0)
14749 (work-already-expanded tags-already-expanded)
14750 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14751 ;; @ and _ are allowed as word-components in tags.
14752 (modify-syntax-entry ?@ "w" stable)
14753 (modify-syntax-entry ?_ "w" stable)
14754 ;; Temporarily replace regexp-expressions in the match-expression.
14755 (while (string-match "{.+?}" return-match)
14756 (cl-incf count)
14757 (push (match-string 0 return-match) regexps-in-match)
14758 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14759 (while (and taggroups-keys
14760 (with-syntax-table stable
14761 (string-match
14762 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14763 (regexp-opt taggroups-keys) "\\>\\)")
14764 return-match)))
14765 (let* ((dir (match-string 1 return-match))
14766 (tag (match-string 2 return-match))
14767 (tag (if downcased (downcase tag) tag)))
14768 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14769 (member tag work-already-expanded))
14770 (setq tags-in-group (assoc tag taggroups))
14771 (push tag work-already-expanded)
14772 ;; Recursively expand each tag in the group, if the tag hasn't
14773 ;; already been expanded. Restore the match-data after all recursive calls.
14774 (save-match-data
14775 (let (tags-expanded)
14776 (dolist (x (cdr tags-in-group))
14777 (if (and (member x taggroups-keys)
14778 (not (member x work-already-expanded)))
14779 (setq tags-expanded
14780 (delete-dups
14781 (append
14782 (org-tags-expand x t downcased
14783 work-already-expanded)
14784 tags-expanded)))
14785 (setq tags-expanded
14786 (append (list x) tags-expanded)))
14787 (setq work-already-expanded
14788 (delete-dups
14789 (append tags-expanded
14790 work-already-expanded))))
14791 (setq tags-in-group
14792 (delete-dups (cons (car tags-in-group)
14793 tags-expanded)))))
14794 ;; Filter tag-regexps from tags.
14795 (setq regexp-in-group-escaped
14796 (delq nil (mapcar (lambda (x)
14797 (if (stringp x)
14798 (and (equal "{" (substring x 0 1))
14799 (equal "}" (substring x -1))
14802 tags-in-group))
14803 regexp-in-group
14804 (mapcar (lambda (x)
14805 (substring x 1 -1))
14806 regexp-in-group-escaped)
14807 tags-in-group
14808 (delq nil (mapcar (lambda (x)
14809 (if (stringp x)
14810 (and (not (equal "{" (substring x 0 1)))
14811 (not (equal "}" (substring x -1)))
14814 tags-in-group)))
14815 ;; If single-as-list, do no more in the while-loop.
14816 (if (not single-as-list)
14817 (progn
14818 (when regexp-in-group
14819 (setq regexp-in-group
14820 (concat "\\|"
14821 (mapconcat 'identity regexp-in-group
14822 "\\|"))))
14823 (setq tags-in-group
14824 (concat dir
14825 "{\\<"
14826 (regexp-opt tags-in-group)
14827 "\\>"
14828 regexp-in-group
14829 "}"))
14830 (when (stringp tags-in-group)
14831 (org-add-props tags-in-group '(grouptag t)))
14832 (setq return-match
14833 (replace-match tags-in-group t t return-match)))
14834 (setq tags-in-group
14835 (append regexp-in-group-escaped tags-in-group))))
14836 (setq taggroups-keys (delete tag taggroups-keys))))
14837 ;; Add the regular expressions back into the match-expression again.
14838 (while regexps-in-match
14839 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14840 (pop regexps-in-match)
14841 return-match t t))
14842 (cl-decf count))
14843 (if single-as-list
14844 (if tags-in-group tags-in-group (list return-match))
14845 return-match))
14846 (if single-as-list
14847 (list (if downcased (downcase match) match))
14848 match)))
14850 (defun org-op-to-function (op &optional stringp)
14851 "Turn an operator into the appropriate function."
14852 (setq op
14853 (cond
14854 ((equal op "<" ) '(< string< org-time<))
14855 ((equal op ">" ) '(> org-string> org-time>))
14856 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14857 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14858 ((member op '("=" "==")) '(= string= org-time=))
14859 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14860 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14862 (defun org<> (a b) (not (= a b)))
14863 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14864 (defun org-string>= (a b) (not (string< a b)))
14865 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14866 (defun org-string<> (a b) (not (string= a b)))
14867 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14868 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14869 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14870 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14871 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14872 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14873 (defun org-2ft (s)
14874 "Convert S to a floating point time.
14875 If S is already a number, just return it. If it is a string, parse
14876 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14877 (cond
14878 ((numberp s) s)
14879 ((stringp s)
14880 (condition-case nil
14881 (float-time (apply 'encode-time (org-parse-time-string s)))
14882 (error 0.)))
14883 (t 0.)))
14885 (defun org-time-today ()
14886 "Time in seconds today at 0:00.
14887 Returns the float number of seconds since the beginning of the
14888 epoch to the beginning of today (00:00)."
14889 (float-time (apply 'encode-time
14890 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14892 (defun org-matcher-time (s)
14893 "Interpret a time comparison value."
14894 (save-match-data
14895 (cond
14896 ((string= s "<now>") (float-time))
14897 ((string= s "<today>") (org-time-today))
14898 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14899 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14900 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14901 (+ (org-time-today)
14902 (* (string-to-number (match-string 1 s))
14903 (cdr (assoc (match-string 2 s)
14904 '(("d" . 86400.0) ("w" . 604800.0)
14905 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14906 (t (org-2ft s)))))
14908 (defun org-match-any-p (re list)
14909 "Does re match any element of list?"
14910 (setq list (mapcar (lambda (x) (string-match re x)) list))
14911 (delq nil list))
14913 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14914 (defvar org-tags-overlay (make-overlay 1 1))
14915 (delete-overlay org-tags-overlay)
14917 (defun org-get-local-tags-at (&optional pos)
14918 "Get a list of tags defined in the current headline."
14919 (org-get-tags-at pos 'local))
14921 (defun org-get-local-tags ()
14922 "Get a list of tags defined in the current headline."
14923 (org-get-tags-at nil 'local))
14925 (defun org-get-tags-at (&optional pos local)
14926 "Get a list of all headline tags applicable at POS.
14927 POS defaults to point. If tags are inherited, the list contains
14928 the targets in the same sequence as the headlines appear, i.e.
14929 the tags of the current headline come last.
14930 When LOCAL is non-nil, only return tags from the current headline,
14931 ignore inherited ones."
14932 (interactive)
14933 (if (and org-trust-scanner-tags
14934 (or (not pos) (equal pos (point)))
14935 (not local))
14936 org-scanner-tags
14937 (let (tags ltags lastpos parent)
14938 (save-excursion
14939 (save-restriction
14940 (widen)
14941 (goto-char (or pos (point)))
14942 (save-match-data
14943 (catch 'done
14944 (condition-case nil
14945 (progn
14946 (org-back-to-heading t)
14947 (while (not (equal lastpos (point)))
14948 (setq lastpos (point))
14949 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14950 (setq ltags (org-split-string
14951 (match-string-no-properties 1) ":"))
14952 (when parent
14953 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14954 (setq tags (append
14955 (if parent
14956 (org-remove-uninherited-tags ltags)
14957 ltags)
14958 tags)))
14959 (or org-use-tag-inheritance (throw 'done t))
14960 (when local (throw 'done t))
14961 (or (org-up-heading-safe) (error nil))
14962 (setq parent t)))
14963 (error nil)))))
14964 (if local
14965 tags
14966 (reverse (delete-dups
14967 (reverse (append
14968 (org-remove-uninherited-tags
14969 org-file-tags)
14970 tags)))))))))
14972 (defun org-add-prop-inherited (s)
14973 (add-text-properties 0 (length s) '(inherited t) s)
14976 (defun org-toggle-tag (tag &optional onoff)
14977 "Toggle the tag TAG for the current line.
14978 If ONOFF is `on' or `off', don't toggle but set to this state."
14979 (let (res current)
14980 (save-excursion
14981 (org-back-to-heading t)
14982 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14983 (point-at-eol) t)
14984 (progn
14985 (setq current (match-string 1))
14986 (replace-match ""))
14987 (setq current ""))
14988 (setq current (nreverse (org-split-string current ":")))
14989 (cond
14990 ((eq onoff 'on)
14991 (setq res t)
14992 (or (member tag current) (push tag current)))
14993 ((eq onoff 'off)
14994 (or (not (member tag current)) (setq current (delete tag current))))
14995 (t (if (member tag current)
14996 (setq current (delete tag current))
14997 (setq res t)
14998 (push tag current))))
14999 (end-of-line 1)
15000 (if current
15001 (progn
15002 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
15003 (org-set-tags nil t))
15004 (delete-horizontal-space))
15005 (run-hooks 'org-after-tags-change-hook))
15006 res))
15008 (defun org-align-tags-here (to-col)
15009 ;; Assumes that this is a headline
15010 "Align tags on the current headline to TO-COL."
15011 (let ((pos (point)) (col (current-column)) ncol tags-l p)
15012 (beginning-of-line 1)
15013 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15014 (< pos (match-beginning 2)))
15015 (progn
15016 (setq tags-l (string-width (match-string 2)))
15017 (goto-char (match-beginning 1))
15018 (insert " ")
15019 (delete-region (point) (1+ (match-beginning 2)))
15020 (setq ncol (max (current-column)
15021 (1+ col)
15022 (if (> to-col 0)
15023 to-col
15024 (- (abs to-col) tags-l))))
15025 (setq p (point))
15026 (insert (make-string (- ncol (current-column)) ?\ ))
15027 (setq ncol (current-column))
15028 (when indent-tabs-mode (tabify p (point-at-eol)))
15029 (org-move-to-column (min ncol col)))
15030 (goto-char pos))))
15032 (defun org-set-tags-command (&optional arg just-align)
15033 "Call the set-tags command for the current entry."
15034 (interactive "P")
15035 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
15036 (org-set-tags arg just-align)
15037 (save-excursion
15038 (unless (and (org-region-active-p)
15039 org-loop-over-headlines-in-active-region)
15040 (org-back-to-heading t))
15041 (org-set-tags arg just-align))))
15043 (defun org-set-tags-to (data)
15044 "Set the tags of the current entry to DATA, replacing the current tags.
15045 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
15046 If DATA is nil or the empty string, any tags will be removed."
15047 (interactive "sTags: ")
15048 (setq data
15049 (cond
15050 ((eq data nil) "")
15051 ((equal data "") "")
15052 ((stringp data)
15053 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
15054 ":"))
15055 ((listp data)
15056 (concat ":" (mapconcat 'identity data ":") ":"))))
15057 (when data
15058 (save-excursion
15059 (org-back-to-heading t)
15060 (when (looking-at org-complex-heading-regexp)
15061 (if (match-end 5)
15062 (progn
15063 (goto-char (match-beginning 5))
15064 (insert data)
15065 (delete-region (point) (point-at-eol))
15066 (org-set-tags nil 'align))
15067 (goto-char (point-at-eol))
15068 (insert " " data)
15069 (org-set-tags nil 'align)))
15070 (beginning-of-line 1)
15071 (when (looking-at ".*?\\([ \t]+\\)$")
15072 (delete-region (match-beginning 1) (match-end 1))))))
15074 (defun org-align-all-tags ()
15075 "Align the tags in all headings."
15076 (interactive)
15077 (save-excursion
15078 (or (ignore-errors (org-back-to-heading t))
15079 (outline-next-heading))
15080 (if (org-at-heading-p)
15081 (org-set-tags t)
15082 (message "No headings"))))
15084 (defvar org-indent-indentation-per-level)
15085 (defun org-set-tags (&optional arg just-align)
15086 "Set the tags for the current headline.
15087 With prefix ARG, realign all tags in headings in the current buffer.
15088 When JUST-ALIGN is non-nil, only align tags."
15089 (interactive "P")
15090 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15091 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15092 'region-start-level
15093 'region))
15094 org-loop-over-headlines-in-active-region)
15095 (org-map-entries
15096 ;; We don't use ARG and JUST-ALIGN here because these args
15097 ;; are not useful when looping over headlines.
15098 #'org-set-tags
15099 org-loop-over-headlines-in-active-region
15101 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15102 (let ((org-setting-tags t))
15103 (if arg
15104 (save-excursion
15105 (goto-char (point-min))
15106 (while (re-search-forward org-outline-regexp-bol nil t)
15107 (org-set-tags nil t)
15108 (end-of-line))
15109 (message "All tags realigned to column %d" org-tags-column))
15110 (let* ((current (org-get-tags-string))
15111 (col (current-column))
15112 (tags
15113 (if just-align current
15114 ;; Get a new set of tags from the user.
15115 (save-excursion
15116 (let* ((seen)
15117 (table
15118 (setq
15119 org-last-tags-completion-table
15120 ;; Uniquify tags in alists, yet preserve
15121 ;; structure (i.e., keywords).
15122 (delq nil
15123 (mapcar
15124 (lambda (pair)
15125 (let ((head (car pair)))
15126 (cond ((symbolp head) pair)
15127 ((member head seen) nil)
15128 (t (push head seen)
15129 pair))))
15130 (append
15131 (or org-current-tag-alist
15132 (org-get-buffer-tags))
15133 (and
15134 org-complete-tags-always-offer-all-agenda-tags
15135 (org-global-tags-completion-table
15136 (org-agenda-files))))))))
15137 (current-tags (org-split-string current ":"))
15138 (inherited-tags
15139 (nreverse (nthcdr (length current-tags)
15140 (nreverse (org-get-tags-at))))))
15141 (replace-regexp-in-string
15142 "\\([-+&]+\\|,\\)"
15144 (if (or (eq t org-use-fast-tag-selection)
15145 (and org-use-fast-tag-selection
15146 (delq nil (mapcar #'cdr table))))
15147 (org-fast-tag-selection
15148 current-tags inherited-tags table
15149 (and org-fast-tag-selection-include-todo
15150 org-todo-key-alist))
15151 (let ((org-add-colon-after-tag-completion
15152 (< 1 (length table))))
15153 (org-trim
15154 (completing-read
15155 "Tags: "
15156 #'org-tags-completion-function
15157 nil nil current 'org-tags-history))))))))))
15159 (when org-tags-sort-function
15160 (setq tags
15161 (mapconcat
15162 #'identity
15163 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15164 org-tags-sort-function)
15165 ":")))
15167 (if (not (org-string-nw-p tags)) (setq tags "")
15168 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15169 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15171 ;; Insert new tags at the correct column
15172 (beginning-of-line)
15173 (let ((level (if (looking-at org-outline-regexp)
15174 (- (match-end 0) (point) 1)
15175 1)))
15176 (cond
15177 ((and (equal current "") (equal tags "")))
15178 ((re-search-forward
15179 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15180 (line-end-position)
15182 (if (equal tags "") (replace-match "" t t)
15183 (goto-char (match-beginning 0))
15184 (let* ((c0 (current-column))
15185 ;; Compute offset for the case of org-indent-mode
15186 ;; active.
15187 (di (if (bound-and-true-p org-indent-mode)
15188 (* (1- org-indent-indentation-per-level)
15189 (1- level))
15191 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15192 (tc (+ org-tags-column
15193 (if (> org-tags-column 0) (- di) di)))
15194 (c1 (max (1+ c0)
15195 (if (> tc 0) tc
15196 (- (- tc) (string-width tags)))))
15197 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15198 (replace-match rpl t t)
15199 (when indent-tabs-mode (tabify p0 (point))))))
15200 (t (error "Tags alignment failed"))))
15201 (org-move-to-column col))
15202 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15204 (defun org-change-tag-in-region (beg end tag off)
15205 "Add or remove TAG for each entry in the region.
15206 This works in the agenda, and also in an org-mode buffer."
15207 (interactive
15208 (list (region-beginning) (region-end)
15209 (let ((org-last-tags-completion-table
15210 (if (derived-mode-p 'org-mode)
15211 (org-uniquify
15212 (delq nil (append (org-get-buffer-tags)
15213 (org-global-tags-completion-table))))
15214 (org-global-tags-completion-table))))
15215 (completing-read
15216 "Tag: " 'org-tags-completion-function nil nil nil
15217 'org-tags-history))
15218 (progn
15219 (message "[s]et or [r]emove? ")
15220 (equal (read-char-exclusive) ?r))))
15221 (when (fboundp 'deactivate-mark) (deactivate-mark))
15222 (let ((agendap (equal major-mode 'org-agenda-mode))
15223 l1 l2 m buf pos newhead (cnt 0))
15224 (goto-char end)
15225 (setq l2 (1- (org-current-line)))
15226 (goto-char beg)
15227 (setq l1 (org-current-line))
15228 (cl-loop for l from l1 to l2 do
15229 (org-goto-line l)
15230 (setq m (get-text-property (point) 'org-hd-marker))
15231 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15232 (and agendap m))
15233 (setq buf (if agendap (marker-buffer m) (current-buffer))
15234 pos (if agendap m (point)))
15235 (with-current-buffer buf
15236 (save-excursion
15237 (save-restriction
15238 (goto-char pos)
15239 (setq cnt (1+ cnt))
15240 (org-toggle-tag tag (if off 'off 'on))
15241 (setq newhead (org-get-heading)))))
15242 (and agendap (org-agenda-change-all-lines newhead m))))
15243 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15245 (defun org-tags-completion-function (string _predicate &optional flag)
15246 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15247 (confirm (lambda (x) (stringp (car x)))))
15248 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15249 (setq s1 (match-string 1 string)
15250 s2 (match-string 2 string))
15251 (setq s1 "" s2 string))
15252 (cond
15253 ((eq flag nil)
15254 ;; try completion
15255 (setq rtn (try-completion s2 ctable confirm))
15256 (when (stringp rtn)
15257 (setq rtn
15258 (concat s1 s2 (substring rtn (length s2))
15259 (if (and org-add-colon-after-tag-completion
15260 (assoc rtn ctable))
15261 ":" ""))))
15262 rtn)
15263 ((eq flag t)
15264 ;; all-completions
15265 (all-completions s2 ctable confirm))
15266 ((eq flag 'lambda)
15267 ;; exact match?
15268 (assoc s2 ctable)))))
15270 (defun org-fast-tag-insert (kwd tags face &optional end)
15271 "Insert KDW, and the TAGS, the latter with face FACE.
15272 Also insert END."
15273 (insert (format "%-12s" (concat kwd ":"))
15274 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15275 (or end "")))
15277 (defun org-fast-tag-show-exit (flag)
15278 (save-excursion
15279 (org-goto-line 3)
15280 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15281 (replace-match ""))
15282 (when flag
15283 (end-of-line 1)
15284 (org-move-to-column (- (window-width) 19) t)
15285 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15287 (defun org-set-current-tags-overlay (current prefix)
15288 "Add an overlay to CURRENT tag with PREFIX."
15289 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15290 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15291 (org-overlay-display org-tags-overlay (concat prefix s))))
15293 (defvar org-last-tag-selection-key nil)
15294 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15295 "Fast tag selection with single keys.
15296 CURRENT is the current list of tags in the headline, INHERITED is the
15297 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15298 possibly with grouping information. TODO-TABLE is a similar table with
15299 TODO keywords, should these have keys assigned to them.
15300 If the keys are nil, a-z are automatically assigned.
15301 Returns the new tags string, or nil to not change the current settings."
15302 (let* ((fulltable (append table todo-table))
15303 (maxlen (apply 'max (mapcar
15304 (lambda (x)
15305 (if (stringp (car x)) (string-width (car x)) 0))
15306 fulltable)))
15307 (buf (current-buffer))
15308 (expert (eq org-fast-tag-selection-single-key 'expert))
15309 (buffer-tags nil)
15310 (fwidth (+ maxlen 3 1 3))
15311 (ncol (/ (- (window-width) 4) fwidth))
15312 (i-face 'org-done)
15313 (c-face 'org-todo)
15314 tg cnt e c char c1 c2 ntable tbl rtn
15315 ov-start ov-end ov-prefix
15316 (exit-after-next org-fast-tag-selection-single-key)
15317 (done-keywords org-done-keywords)
15318 groups ingroup intaggroup)
15319 (save-excursion
15320 (beginning-of-line 1)
15321 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15322 (setq ov-start (match-beginning 1)
15323 ov-end (match-end 1)
15324 ov-prefix "")
15325 (setq ov-start (1- (point-at-eol))
15326 ov-end (1+ ov-start))
15327 (skip-chars-forward "^\n\r")
15328 (setq ov-prefix
15329 (concat
15330 (buffer-substring (1- (point)) (point))
15331 (if (> (current-column) org-tags-column)
15333 (make-string (- org-tags-column (current-column)) ?\ ))))))
15334 (move-overlay org-tags-overlay ov-start ov-end)
15335 (save-window-excursion
15336 (if expert
15337 (set-buffer (get-buffer-create " *Org tags*"))
15338 (delete-other-windows)
15339 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15340 (org-switch-to-buffer-other-window " *Org tags*"))
15341 (erase-buffer)
15342 (setq-local org-done-keywords done-keywords)
15343 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15344 (org-fast-tag-insert "Current" current c-face "\n\n")
15345 (org-fast-tag-show-exit exit-after-next)
15346 (org-set-current-tags-overlay current ov-prefix)
15347 (setq tbl fulltable char ?a cnt 0)
15348 (while (setq e (pop tbl))
15349 (cond
15350 ((eq (car e) :startgroup)
15351 (push '() groups) (setq ingroup t)
15352 (unless (zerop cnt)
15353 (setq cnt 0)
15354 (insert "\n"))
15355 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15356 ((eq (car e) :endgroup)
15357 (setq ingroup nil cnt 0)
15358 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15359 ((eq (car e) :startgrouptag)
15360 (setq intaggroup t)
15361 (unless (zerop cnt)
15362 (setq cnt 0)
15363 (insert "\n"))
15364 (insert "[ "))
15365 ((eq (car e) :endgrouptag)
15366 (setq intaggroup nil cnt 0)
15367 (insert "]\n"))
15368 ((equal e '(:newline))
15369 (unless (zerop cnt)
15370 (setq cnt 0)
15371 (insert "\n")
15372 (setq e (car tbl))
15373 (while (equal (car tbl) '(:newline))
15374 (insert "\n")
15375 (setq tbl (cdr tbl)))))
15376 ((equal e '(:grouptags)) (insert " : "))
15378 (setq tg (copy-sequence (car e)) c2 nil)
15379 (if (cdr e)
15380 (setq c (cdr e))
15381 ;; automatically assign a character.
15382 (setq c1 (string-to-char
15383 (downcase (substring
15384 tg (if (= (string-to-char tg) ?@) 1 0)))))
15385 (if (or (rassoc c1 ntable) (rassoc c1 table))
15386 (while (or (rassoc char ntable) (rassoc char table))
15387 (setq char (1+ char)))
15388 (setq c2 c1))
15389 (setq c (or c2 char)))
15390 (when ingroup (push tg (car groups)))
15391 (setq tg (org-add-props tg nil 'face
15392 (cond
15393 ((not (assoc tg table))
15394 (org-get-todo-face tg))
15395 ((member tg current) c-face)
15396 ((member tg inherited) i-face))))
15397 (when (equal (caar tbl) :grouptags)
15398 (org-add-props tg nil 'face 'org-tag-group))
15399 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15400 (insert "[" c "] " tg (make-string
15401 (- fwidth 4 (length tg)) ?\ ))
15402 (push (cons tg c) ntable)
15403 (when (= (cl-incf cnt) ncol)
15404 (insert "\n")
15405 (when (or ingroup intaggroup) (insert " "))
15406 (setq cnt 0)))))
15407 (setq ntable (nreverse ntable))
15408 (insert "\n")
15409 (goto-char (point-min))
15410 (unless expert (org-fit-window-to-buffer))
15411 (setq rtn
15412 (catch 'exit
15413 (while t
15414 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15415 (if (not groups) "no " "")
15416 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15417 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15418 (setq org-last-tag-selection-key c)
15419 (cond
15420 ((= c ?\r) (throw 'exit t))
15421 ((= c ?!)
15422 (setq groups (not groups))
15423 (goto-char (point-min))
15424 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15425 ((= c ?\C-c)
15426 (if (not expert)
15427 (org-fast-tag-show-exit
15428 (setq exit-after-next (not exit-after-next)))
15429 (setq expert nil)
15430 (delete-other-windows)
15431 (set-window-buffer (split-window-vertically) " *Org tags*")
15432 (org-switch-to-buffer-other-window " *Org tags*")
15433 (org-fit-window-to-buffer)))
15434 ((or (= c ?\C-g)
15435 (and (= c ?q) (not (rassoc c ntable))))
15436 (delete-overlay org-tags-overlay)
15437 (setq quit-flag t))
15438 ((= c ?\ )
15439 (setq current nil)
15440 (when exit-after-next (setq exit-after-next 'now)))
15441 ((= c ?\t)
15442 (condition-case nil
15443 (setq tg (completing-read
15444 "Tag: "
15445 (or buffer-tags
15446 (with-current-buffer buf
15447 (setq buffer-tags
15448 (org-get-buffer-tags))))))
15449 (quit (setq tg "")))
15450 (when (string-match "\\S-" tg)
15451 (cl-pushnew (list tg) buffer-tags :test #'equal)
15452 (if (member tg current)
15453 (setq current (delete tg current))
15454 (push tg current)))
15455 (when exit-after-next (setq exit-after-next 'now)))
15456 ((setq e (rassoc c todo-table) tg (car e))
15457 (with-current-buffer buf
15458 (save-excursion (org-todo tg)))
15459 (when exit-after-next (setq exit-after-next 'now)))
15460 ((setq e (rassoc c ntable) tg (car e))
15461 (if (member tg current)
15462 (setq current (delete tg current))
15463 (cl-loop for g in groups do
15464 (when (member tg g)
15465 (dolist (x g) (setq current (delete x current)))))
15466 (push tg current))
15467 (when exit-after-next (setq exit-after-next 'now))))
15469 ;; Create a sorted list
15470 (setq current
15471 (sort current
15472 (lambda (a b)
15473 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15474 (when (eq exit-after-next 'now) (throw 'exit t))
15475 (goto-char (point-min))
15476 (beginning-of-line 2)
15477 (delete-region (point) (point-at-eol))
15478 (org-fast-tag-insert "Current" current c-face)
15479 (org-set-current-tags-overlay current ov-prefix)
15480 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15481 (setq tg (match-string 1))
15482 (add-text-properties
15483 (match-beginning 1) (match-end 1)
15484 (list 'face
15485 (cond
15486 ((member tg current) c-face)
15487 ((member tg inherited) i-face)
15488 (t (get-text-property (match-beginning 1) 'face))))))
15489 (goto-char (point-min)))))
15490 (delete-overlay org-tags-overlay)
15491 (if rtn
15492 (mapconcat 'identity current ":")
15493 nil))))
15495 (defun org-get-tags-string ()
15496 "Get the TAGS string in the current headline."
15497 (unless (org-at-heading-p t)
15498 (user-error "Not on a heading"))
15499 (save-excursion
15500 (beginning-of-line 1)
15501 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15502 (match-string-no-properties 1)
15503 "")))
15505 (defun org-get-tags ()
15506 "Get the list of tags specified in the current headline."
15507 (org-split-string (org-get-tags-string) ":"))
15509 (defun org-get-buffer-tags ()
15510 "Get a table of all tags used in the buffer, for completion."
15511 (org-with-wide-buffer
15512 (goto-char (point-min))
15513 (let ((tag-re (concat org-outline-regexp-bol
15514 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15515 tags)
15516 (while (re-search-forward tag-re nil t)
15517 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15518 (push tag tags)))
15519 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15521 ;;;; The mapping API
15523 (defvar org-agenda-skip-comment-trees)
15524 (defvar org-agenda-skip-function)
15525 (defun org-map-entries (func &optional match scope &rest skip)
15526 "Call FUNC at each headline selected by MATCH in SCOPE.
15528 FUNC is a function or a lisp form. The function will be called without
15529 arguments, with the cursor positioned at the beginning of the headline.
15530 The return values of all calls to the function will be collected and
15531 returned as a list.
15533 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15534 does not need to preserve point. After evaluation, the cursor will be
15535 moved to the end of the line (presumably of the headline of the
15536 processed entry) and search continues from there. Under some
15537 circumstances, this may not produce the wanted results. For example,
15538 if you have removed (e.g. archived) the current (sub)tree it could
15539 mean that the next entry will be skipped entirely. In such cases, you
15540 can specify the position from where search should continue by making
15541 FUNC set the variable `org-map-continue-from' to the desired buffer
15542 position.
15544 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15545 Only headlines that are matched by this query will be considered during
15546 the iteration. When MATCH is nil or t, all headlines will be
15547 visited by the iteration.
15549 SCOPE determines the scope of this command. It can be any of:
15551 nil The current buffer, respecting the restriction if any
15552 tree The subtree started with the entry at point
15553 region The entries within the active region, if any
15554 region-start-level
15555 The entries within the active region, but only those at
15556 the same level than the first one.
15557 file The current buffer, without restriction
15558 file-with-archives
15559 The current buffer, and any archives associated with it
15560 agenda All agenda files
15561 agenda-with-archives
15562 All agenda files with any archive files associated with them
15563 \(file1 file2 ...)
15564 If this is a list, all files in the list will be scanned
15566 The remaining args are treated as settings for the skipping facilities of
15567 the scanner. The following items can be given here:
15569 archive skip trees with the archive tag
15570 comment skip trees with the COMMENT keyword
15571 function or Emacs Lisp form:
15572 will be used as value for `org-agenda-skip-function', so
15573 whenever the function returns a position, FUNC will not be
15574 called for that entry and search will continue from the
15575 position returned
15577 If your function needs to retrieve the tags including inherited tags
15578 at the *current* entry, you can use the value of the variable
15579 `org-scanner-tags' which will be much faster than getting the value
15580 with `org-get-tags-at'. If your function gets properties with
15581 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15582 to t around the call to `org-entry-properties' to get the same speedup.
15583 Note that if your function moves around to retrieve tags and properties at
15584 a *different* entry, you cannot use these techniques."
15585 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15586 (not (org-region-active-p)))
15587 (let* ((org-agenda-archives-mode nil) ; just to make sure
15588 (org-agenda-skip-archived-trees (memq 'archive skip))
15589 (org-agenda-skip-comment-trees (memq 'comment skip))
15590 (org-agenda-skip-function
15591 (car (org-delete-all '(comment archive) skip)))
15592 (org-tags-match-list-sublevels t)
15593 (start-level (eq scope 'region-start-level))
15594 matcher res
15595 org-todo-keywords-for-agenda
15596 org-done-keywords-for-agenda
15597 org-todo-keyword-alist-for-agenda
15598 org-tag-alist-for-agenda
15599 org--matcher-tags-todo-only)
15601 (cond
15602 ((eq match t) (setq matcher t))
15603 ((eq match nil) (setq matcher t))
15604 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15606 (save-excursion
15607 (save-restriction
15608 (cond ((eq scope 'tree)
15609 (org-back-to-heading t)
15610 (org-narrow-to-subtree)
15611 (setq scope nil))
15612 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15613 (org-region-active-p))
15614 ;; If needed, set start-level to a string like "2"
15615 (when start-level
15616 (save-excursion
15617 (goto-char (region-beginning))
15618 (unless (org-at-heading-p) (outline-next-heading))
15619 (setq start-level (org-current-level))))
15620 (narrow-to-region (region-beginning)
15621 (save-excursion
15622 (goto-char (region-end))
15623 (unless (and (bolp) (org-at-heading-p))
15624 (outline-next-heading))
15625 (point)))
15626 (setq scope nil)))
15628 (if (not scope)
15629 (progn
15630 (org-agenda-prepare-buffers
15631 (and buffer-file-name (list buffer-file-name)))
15632 (setq res
15633 (org-scan-tags
15634 func matcher org--matcher-tags-todo-only start-level)))
15635 ;; Get the right scope
15636 (cond
15637 ((and scope (listp scope) (symbolp (car scope)))
15638 (setq scope (eval scope)))
15639 ((eq scope 'agenda)
15640 (setq scope (org-agenda-files t)))
15641 ((eq scope 'agenda-with-archives)
15642 (setq scope (org-agenda-files t))
15643 (setq scope (org-add-archive-files scope)))
15644 ((eq scope 'file)
15645 (setq scope (and buffer-file-name (list buffer-file-name))))
15646 ((eq scope 'file-with-archives)
15647 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15648 (org-agenda-prepare-buffers scope)
15649 (dolist (file scope)
15650 (with-current-buffer (org-find-base-buffer-visiting file)
15651 (save-excursion
15652 (save-restriction
15653 (widen)
15654 (goto-char (point-min))
15655 (setq res
15656 (append
15658 (org-scan-tags
15659 func matcher org--matcher-tags-todo-only))))))))))
15660 res)))
15662 ;;; Properties API
15664 (defconst org-special-properties
15665 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15666 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15667 "The special properties valid in Org mode.
15668 These are properties that are not defined in the property drawer,
15669 but in some other way.")
15671 (defconst org-default-properties
15672 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15673 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15674 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15675 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15676 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15677 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15678 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15679 "Some properties that are used by Org mode for various purposes.
15680 Being in this list makes sure that they are offered for completion.")
15682 (defun org--valid-property-p (property)
15683 "Non nil when string PROPERTY is a valid property name."
15684 (not
15685 (or (equal property "")
15686 (string-match-p "\\s-" property))))
15688 (defun org--update-property-plist (key val props)
15689 "Associate KEY to VAL in alist PROPS.
15690 Modifications are made by side-effect. Return new alist."
15691 (let* ((appending (string= (substring key -1) "+"))
15692 (key (if appending (substring key 0 -1) key))
15693 (old (assoc-string key props t)))
15694 (if (not old) (cons (cons key val) props)
15695 (setcdr old (if appending (concat (cdr old) " " val) val))
15696 props)))
15698 (defun org-get-property-block (&optional beg force)
15699 "Return the (beg . end) range of the body of the property drawer.
15700 BEG is the beginning of the current subtree, or of the part
15701 before the first headline. If it is not given, it will be found.
15702 If the drawer does not exist, create it if FORCE is non-nil, or
15703 return nil."
15704 (org-with-wide-buffer
15705 (when beg (goto-char beg))
15706 (unless (org-before-first-heading-p)
15707 (let ((beg (cond (beg)
15708 ((or (not (featurep 'org-inlinetask))
15709 (org-inlinetask-in-task-p))
15710 (org-back-to-heading t))
15711 (t (org-with-limited-levels (org-back-to-heading t))))))
15712 (forward-line)
15713 (when (looking-at-p org-planning-line-re) (forward-line))
15714 (cond ((looking-at org-property-drawer-re)
15715 (forward-line)
15716 (cons (point) (progn (goto-char (match-end 0))
15717 (line-beginning-position))))
15718 (force
15719 (goto-char beg)
15720 (org-insert-property-drawer)
15721 (let ((pos (save-excursion (search-forward ":END:")
15722 (line-beginning-position))))
15723 (cons pos pos))))))))
15725 (defun org-at-property-p ()
15726 "Non-nil when point is inside a property drawer.
15727 See `org-property-re' for match data, if applicable."
15728 (save-excursion
15729 (beginning-of-line)
15730 (and (looking-at org-property-re)
15731 (let ((property-drawer (save-match-data (org-get-property-block))))
15732 (and property-drawer
15733 (>= (point) (car property-drawer))
15734 (< (point) (cdr property-drawer)))))))
15736 (defun org-property-action ()
15737 "Do an action on properties."
15738 (interactive)
15739 (unless (org-at-property-p) (user-error "Not at a property"))
15740 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15741 (let ((c (read-char-exclusive)))
15742 (cl-case c
15743 (?s (call-interactively #'org-set-property))
15744 (?d (call-interactively #'org-delete-property))
15745 (?D (call-interactively #'org-delete-property-globally))
15746 (?c (call-interactively #'org-compute-property-at-point))
15747 (otherwise (user-error "No such property action %c" c)))))
15749 (defun org-inc-effort ()
15750 "Increment the value of the effort property in the current entry."
15751 (interactive)
15752 (org-set-effort nil t))
15754 (defvar org-clock-effort) ; Defined in org-clock.el.
15755 (defvar org-clock-current-task) ; Defined in org-clock.el.
15756 (defun org-set-effort (&optional value increment)
15757 "Set the effort property of the current entry.
15758 With numerical prefix arg, use the nth allowed value, 0 stands for the
15759 10th allowed value.
15761 When INCREMENT is non-nil, set the property to the next allowed value."
15762 (interactive "P")
15763 (when (equal value 0) (setq value 10))
15764 (let* ((completion-ignore-case t)
15765 (prop org-effort-property)
15766 (cur (org-entry-get nil prop))
15767 (allowed (org-property-get-allowed-values nil prop 'table))
15768 (existing (mapcar 'list (org-property-values prop)))
15769 (heading (nth 4 (org-heading-components)))
15771 (val (cond
15772 ((stringp value) value)
15773 ((and allowed (integerp value))
15774 (or (car (nth (1- value) allowed))
15775 (car (org-last allowed))))
15776 ((and allowed increment)
15777 (or (cl-caadr (member (list cur) allowed))
15778 (user-error "Allowed effort values are not set")))
15779 (allowed
15780 (message "Select 1-9,0, [RET%s]: %s"
15781 (if cur (concat "=" cur) "")
15782 (mapconcat 'car allowed " "))
15783 (setq rpl (read-char-exclusive))
15784 (if (equal rpl ?\r)
15786 (setq rpl (- rpl ?0))
15787 (when (equal rpl 0) (setq rpl 10))
15788 (if (and (> rpl 0) (<= rpl (length allowed)))
15789 (car (nth (1- rpl) allowed))
15790 (org-completing-read "Effort: " allowed nil))))
15792 (org-completing-read
15793 (concat "Effort" (and cur (string-match "\\S-" cur)
15794 (concat " [" cur "]"))
15795 ": ")
15796 existing nil nil "" nil cur)))))
15797 (unless (equal (org-entry-get nil prop) val)
15798 (org-entry-put nil prop val))
15799 (org-refresh-property
15800 '((effort . identity)
15801 (effort-minutes . org-duration-string-to-minutes))
15802 val)
15803 (when (equal heading (bound-and-true-p org-clock-current-task))
15804 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15805 (org-clock-update-mode-line))
15806 (message "%s is now %s" prop val)))
15808 (defun org-entry-properties (&optional pom which)
15809 "Get all properties of the current entry.
15811 When POM is a buffer position, get all properties from the entry
15812 there instead.
15814 This includes the TODO keyword, the tags, time strings for
15815 deadline, scheduled, and clocking, and any additional properties
15816 defined in the entry.
15818 If WHICH is nil or `all', get all properties. If WHICH is
15819 `special' or `standard', only get that subclass. If WHICH is
15820 a string, only get that property.
15822 Return value is an alist. Keys are properties, as upcased
15823 strings."
15824 (org-with-point-at pom
15825 (when (and (derived-mode-p 'org-mode)
15826 (ignore-errors (org-back-to-heading t)))
15827 (catch 'exit
15828 (let* ((beg (point))
15829 (specific (and (stringp which) (upcase which)))
15830 (which (cond ((not specific) which)
15831 ((member specific org-special-properties) 'special)
15832 (t 'standard)))
15833 props)
15834 ;; Get the special properties, like TODO and TAGS.
15835 (when (memq which '(nil all special))
15836 (when (or (not specific) (string= specific "CLOCKSUM"))
15837 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15838 (when clocksum
15839 (push (cons "CLOCKSUM"
15840 (org-minutes-to-clocksum-string clocksum))
15841 props)))
15842 (when specific (throw 'exit props)))
15843 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15844 (let ((clocksumt (get-text-property (point)
15845 :org-clock-minutes-today)))
15846 (when clocksumt
15847 (push (cons "CLOCKSUM_T"
15848 (org-minutes-to-clocksum-string clocksumt))
15849 props)))
15850 (when specific (throw 'exit props)))
15851 (when (or (not specific) (string= specific "ITEM"))
15852 (when (looking-at org-complex-heading-regexp)
15853 (push (cons "ITEM"
15854 (let ((title (match-string-no-properties 4)))
15855 (if (org-string-nw-p title)
15856 (org-remove-tabs title)
15857 "")))
15858 props))
15859 (when specific (throw 'exit props)))
15860 (when (or (not specific) (string= specific "TODO"))
15861 (let ((case-fold-search nil))
15862 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15863 (push (cons "TODO" (match-string-no-properties 2)) props)))
15864 (when specific (throw 'exit props)))
15865 (when (or (not specific) (string= specific "PRIORITY"))
15866 (push (cons "PRIORITY"
15867 (if (looking-at org-priority-regexp)
15868 (match-string-no-properties 2)
15869 (char-to-string org-default-priority)))
15870 props)
15871 (when specific (throw 'exit props)))
15872 (when (or (not specific) (string= specific "FILE"))
15873 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15874 props)
15875 (when specific (throw 'exit props)))
15876 (when (or (not specific) (string= specific "TAGS"))
15877 (let ((value (org-string-nw-p (org-get-tags-string))))
15878 (when value (push (cons "TAGS" value) props)))
15879 (when specific (throw 'exit props)))
15880 (when (or (not specific) (string= specific "ALLTAGS"))
15881 (let ((value (org-get-tags-at)))
15882 (when value
15883 (push (cons "ALLTAGS"
15884 (format ":%s:" (mapconcat #'identity value ":")))
15885 props)))
15886 (when specific (throw 'exit props)))
15887 (when (or (not specific) (string= specific "BLOCKED"))
15888 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15889 (when specific (throw 'exit props)))
15890 (when (or (not specific)
15891 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15892 (forward-line)
15893 (when (looking-at-p org-planning-line-re)
15894 (end-of-line)
15895 (let ((bol (line-beginning-position))
15896 ;; Backward compatibility: time keywords used to
15897 ;; be configurable (before 8.3). Make sure we
15898 ;; get the correct keyword.
15899 (key-assoc `(("CLOSED" . ,org-closed-string)
15900 ("DEADLINE" . ,org-deadline-string)
15901 ("SCHEDULED" . ,org-scheduled-string))))
15902 (dolist (pair (if specific (list (assoc specific key-assoc))
15903 key-assoc))
15904 (save-excursion
15905 (when (search-backward (cdr pair) bol t)
15906 (goto-char (match-end 0))
15907 (skip-chars-forward " \t")
15908 (and (looking-at org-ts-regexp-both)
15909 (push (cons (car pair)
15910 (match-string-no-properties 0))
15911 props)))))))
15912 (when specific (throw 'exit props)))
15913 (when (or (not specific)
15914 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15915 (let ((find-ts
15916 (lambda (end ts)
15917 ;; Fix next time-stamp before END. TS is the
15918 ;; list of time-stamps found so far.
15919 (let ((ts ts)
15920 (regexp (cond
15921 ((string= specific "TIMESTAMP")
15922 org-ts-regexp)
15923 ((string= specific "TIMESTAMP_IA")
15924 org-ts-regexp-inactive)
15925 ((assoc "TIMESTAMP_IA" ts)
15926 org-ts-regexp)
15927 ((assoc "TIMESTAMP" ts)
15928 org-ts-regexp-inactive)
15929 (t org-ts-regexp-both))))
15930 (catch 'next
15931 (while (re-search-forward regexp end t)
15932 (backward-char)
15933 (let ((object (org-element-context)))
15934 ;; Accept to match timestamps in node
15935 ;; properties, too.
15936 (when (memq (org-element-type object)
15937 '(node-property timestamp))
15938 (let ((type
15939 (org-element-property :type object)))
15940 (cond
15941 ((and (memq type '(active active-range))
15942 (not (equal specific "TIMESTAMP_IA")))
15943 (unless (assoc "TIMESTAMP" ts)
15944 (push (cons "TIMESTAMP"
15945 (org-element-property
15946 :raw-value object))
15948 (when specific (throw 'exit ts))))
15949 ((and (memq type '(inactive inactive-range))
15950 (not (string= specific "TIMESTAMP")))
15951 (unless (assoc "TIMESTAMP_IA" ts)
15952 (push (cons "TIMESTAMP_IA"
15953 (org-element-property
15954 :raw-value object))
15956 (when specific (throw 'exit ts))))))
15957 ;; Both timestamp types are found,
15958 ;; move to next part.
15959 (when (= (length ts) 2) (throw 'next ts)))))
15960 ts)))))
15961 (goto-char beg)
15962 ;; First look for timestamps within headline.
15963 (let ((ts (funcall find-ts (line-end-position) nil)))
15964 (if (= (length ts) 2) (setq props (nconc ts props))
15965 (forward-line)
15966 ;; Then find timestamps in the section, skipping
15967 ;; planning line.
15968 (when (looking-at-p org-planning-line-re)
15969 (forward-line))
15970 (let ((end (save-excursion (outline-next-heading))))
15971 (setq props (nconc (funcall find-ts end ts) props))))))))
15972 ;; Get the standard properties, like :PROP:.
15973 (when (memq which '(nil all standard))
15974 ;; If we are looking after a specific property, delegate
15975 ;; to `org-entry-get', which is faster. However, make an
15976 ;; exception for "CATEGORY", since it can be also set
15977 ;; through keywords (i.e. #+CATEGORY).
15978 (if (and specific (not (equal specific "CATEGORY")))
15979 (let ((value (org-entry-get beg specific nil t)))
15980 (throw 'exit (and value (list (cons specific value)))))
15981 (let ((range (org-get-property-block beg)))
15982 (when range
15983 (let ((end (cdr range)) seen-base)
15984 (goto-char (car range))
15985 ;; Unlike to `org--update-property-plist', we
15986 ;; handle the case where base values is found
15987 ;; after its extension. We also forbid standard
15988 ;; properties to be named as special properties.
15989 (while (re-search-forward org-property-re end t)
15990 (let* ((key (upcase (match-string-no-properties 2)))
15991 (extendp (string-match-p "\\+\\'" key))
15992 (key-base (if extendp (substring key 0 -1) key))
15993 (value (match-string-no-properties 3)))
15994 (cond
15995 ((member-ignore-case key-base org-special-properties))
15996 (extendp
15997 (setq props
15998 (org--update-property-plist key value props)))
15999 ((member key seen-base))
16000 (t (push key seen-base)
16001 (let ((p (assoc-string key props t)))
16002 (if p (setcdr p (concat value " " (cdr p)))
16003 (push (cons key value) props))))))))))))
16004 (unless (assoc "CATEGORY" props)
16005 (push (cons "CATEGORY" (org-get-category beg)) props)
16006 (when (string= specific "CATEGORY") (throw 'exit props)))
16007 ;; Return value.
16008 props)))))
16010 (defun org-property--local-values (property literal-nil)
16011 "Return value for PROPERTY in current entry.
16012 Value is a list whose car is the base value for PROPERTY and cdr
16013 a list of accumulated values. Return nil if neither is found in
16014 the entry. Also return nil when PROPERTY is set to \"nil\",
16015 unless LITERAL-NIL is non-nil."
16016 (let ((range (org-get-property-block)))
16017 (when range
16018 (goto-char (car range))
16019 (let* ((case-fold-search t)
16020 (end (cdr range))
16021 (value
16022 ;; Base value.
16023 (save-excursion
16024 (let ((v (and (re-search-forward
16025 (org-re-property property nil t) end t)
16026 (match-string-no-properties 3))))
16027 (list (if literal-nil v (org-not-nil v)))))))
16028 ;; Find additional values.
16029 (let* ((property+ (org-re-property (concat property "+") nil t)))
16030 (while (re-search-forward property+ end t)
16031 (push (match-string-no-properties 3) value)))
16032 ;; Return final values.
16033 (and (not (equal value '(nil))) (nreverse value))))))
16035 (defun org-entry-get (pom property &optional inherit literal-nil)
16036 "Get value of PROPERTY for entry or content at point-or-marker POM.
16038 If INHERIT is non-nil and the entry does not have the property,
16039 then also check higher levels of the hierarchy. If INHERIT is
16040 the symbol `selective', use inheritance only if the setting in
16041 `org-use-property-inheritance' selects PROPERTY for inheritance.
16043 If the property is present but empty, the return value is the
16044 empty string. If the property is not present at all, nil is
16045 returned. In any other case, return the value as a string.
16046 Search is case-insensitive.
16048 If LITERAL-NIL is set, return the string value \"nil\" as
16049 a string, do not interpret it as the list atom nil. This is used
16050 for inheritance when a \"nil\" value can supersede a non-nil
16051 value higher up the hierarchy."
16052 (org-with-point-at pom
16053 (cond
16054 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
16055 ;; We need a special property. Use `org-entry-properties' to
16056 ;; retrieve it, but specify the wanted property.
16057 (cdr (assoc-string property (org-entry-properties nil property))))
16058 ((and inherit
16059 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
16060 (org-entry-get-with-inheritance property literal-nil))
16062 (let* ((local (org-property--local-values property literal-nil))
16063 (value (and local (mapconcat #'identity (delq nil local) " "))))
16064 (if literal-nil value (org-not-nil value)))))))
16066 (defun org-property-or-variable-value (var &optional inherit)
16067 "Check if there is a property fixing the value of VAR.
16068 If yes, return this value. If not, return the current value of the variable."
16069 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16070 (if (and prop (stringp prop) (string-match "\\S-" prop))
16071 (read prop)
16072 (symbol-value var))))
16074 (defun org-entry-delete (pom property)
16075 "Delete PROPERTY from entry at point-or-marker POM.
16076 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16077 non-nil when a property was removed."
16078 (unless (member property org-special-properties)
16079 (org-with-point-at pom
16080 (let ((range (org-get-property-block)))
16081 (when range
16082 (let* ((begin (car range))
16083 (origin (cdr range))
16084 (end (copy-marker origin))
16085 (re (org-re-property
16086 (concat (regexp-quote property) "\\+?") t t)))
16087 (goto-char begin)
16088 (while (re-search-forward re end t)
16089 (delete-region (match-beginning 0) (line-beginning-position 2)))
16090 ;; If drawer is empty, remove it altogether.
16091 (when (= begin end)
16092 (delete-region (line-beginning-position 0)
16093 (line-beginning-position 2)))
16094 ;; Return non-nil if some property was removed.
16095 (prog1 (/= end origin) (set-marker end nil))))))))
16097 ;; Multi-values properties are properties that contain multiple values
16098 ;; These values are assumed to be single words, separated by whitespace.
16099 (defun org-entry-add-to-multivalued-property (pom property value)
16100 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16101 (let* ((old (org-entry-get pom property))
16102 (values (and old (org-split-string old "[ \t]"))))
16103 (setq value (org-entry-protect-space value))
16104 (unless (member value values)
16105 (setq values (append values (list value)))
16106 (org-entry-put pom property
16107 (mapconcat 'identity values " ")))))
16109 (defun org-entry-remove-from-multivalued-property (pom property value)
16110 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16111 (let* ((old (org-entry-get pom property))
16112 (values (and old (org-split-string old "[ \t]"))))
16113 (setq value (org-entry-protect-space value))
16114 (when (member value values)
16115 (setq values (delete value values))
16116 (org-entry-put pom property
16117 (mapconcat 'identity values " ")))))
16119 (defun org-entry-member-in-multivalued-property (pom property value)
16120 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16121 (let* ((old (org-entry-get pom property))
16122 (values (and old (org-split-string old "[ \t]"))))
16123 (setq value (org-entry-protect-space value))
16124 (member value values)))
16126 (defun org-entry-get-multivalued-property (pom property)
16127 "Return a list of values in a multivalued property."
16128 (let* ((value (org-entry-get pom property))
16129 (values (and value (org-split-string value "[ \t]"))))
16130 (mapcar 'org-entry-restore-space values)))
16132 (defun org-entry-put-multivalued-property (pom property &rest values)
16133 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16134 VALUES should be a list of strings. Spaces will be protected."
16135 (org-entry-put pom property
16136 (mapconcat 'org-entry-protect-space values " "))
16137 (let* ((value (org-entry-get pom property))
16138 (values (and value (org-split-string value "[ \t]"))))
16139 (mapcar 'org-entry-restore-space values)))
16141 (defun org-entry-protect-space (s)
16142 "Protect spaces and newline in string S."
16143 (while (string-match " " s)
16144 (setq s (replace-match "%20" t t s)))
16145 (while (string-match "\n" s)
16146 (setq s (replace-match "%0A" t t s)))
16149 (defun org-entry-restore-space (s)
16150 "Restore spaces and newline in string S."
16151 (while (string-match "%20" s)
16152 (setq s (replace-match " " t t s)))
16153 (while (string-match "%0A" s)
16154 (setq s (replace-match "\n" t t s)))
16157 (defvar org-entry-property-inherited-from (make-marker)
16158 "Marker pointing to the entry from where a property was inherited.
16159 Each call to `org-entry-get-with-inheritance' will set this marker to the
16160 location of the entry where the inheritance search matched. If there was
16161 no match, the marker will point nowhere.
16162 Note that also `org-entry-get' calls this function, if the INHERIT flag
16163 is set.")
16165 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16166 "Get PROPERTY of entry or content at point, search higher levels if needed.
16167 The search will stop at the first ancestor which has the property defined.
16168 If the value found is \"nil\", return nil to show that the property
16169 should be considered as undefined (this is the meaning of nil here).
16170 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16171 (move-marker org-entry-property-inherited-from nil)
16172 (org-with-wide-buffer
16173 (let (value)
16174 (catch 'exit
16175 (while t
16176 (let ((v (org-property--local-values property literal-nil)))
16177 (when v
16178 (setq value
16179 (concat (mapconcat #'identity (delq nil v) " ")
16180 (and value " ")
16181 value)))
16182 (cond
16183 ((car v)
16184 (org-back-to-heading t)
16185 (move-marker org-entry-property-inherited-from (point))
16186 (throw 'exit nil))
16187 ((org-up-heading-safe))
16189 (let ((global
16190 (cdr (or (assoc-string property org-file-properties t)
16191 (assoc-string property org-global-properties t)
16192 (assoc-string property org-global-properties-fixed t)))))
16193 (cond ((not global))
16194 (value (setq value (concat global " " value)))
16195 (t (setq value global))))
16196 (throw 'exit nil))))))
16197 (if literal-nil value (org-not-nil value)))))
16199 (defvar org-property-changed-functions nil
16200 "Hook called when the value of a property has changed.
16201 Each hook function should accept two arguments, the name of the property
16202 and the new value.")
16204 (defun org-entry-put (pom property value)
16205 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16207 If the value is nil, it is converted to the empty string. If it
16208 is not a string, an error is raised. Also raise an error on
16209 invalid property names.
16211 PROPERTY can be any regular property (see
16212 `org-special-properties'). It can also be \"TODO\",
16213 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16215 For the last two properties, VALUE may have any of the special
16216 values \"earlier\" and \"later\". The function then increases or
16217 decreases scheduled or deadline date by one day."
16218 (cond ((null value) (setq value ""))
16219 ((not (stringp value)) (error "Properties values should be strings"))
16220 ((not (org--valid-property-p property))
16221 (user-error "Invalid property name: \"%s\"" property)))
16222 (org-with-point-at pom
16223 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16224 (org-back-to-heading t)
16225 (org-with-limited-levels (org-back-to-heading t)))
16226 (let ((beg (point)))
16227 (cond
16228 ((equal property "TODO")
16229 (cond ((not (org-string-nw-p value)) (setq value 'none))
16230 ((not (member value org-todo-keywords-1))
16231 (user-error "\"%s\" is not a valid TODO state" value)))
16232 (org-todo value)
16233 (org-set-tags nil 'align))
16234 ((equal property "PRIORITY")
16235 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16236 (org-set-tags nil 'align))
16237 ((equal property "SCHEDULED")
16238 (forward-line)
16239 (if (and (looking-at-p org-planning-line-re)
16240 (re-search-forward
16241 org-scheduled-time-regexp (line-end-position) t))
16242 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16243 ((string= value "later") (org-timestamp-change 1 'day))
16244 ((string= value "") (org-schedule '(4)))
16245 (t (org-schedule nil value)))
16246 (if (member value '("earlier" "later" ""))
16247 (call-interactively #'org-schedule)
16248 (org-schedule nil value))))
16249 ((equal property "DEADLINE")
16250 (forward-line)
16251 (if (and (looking-at-p org-planning-line-re)
16252 (re-search-forward
16253 org-deadline-time-regexp (line-end-position) t))
16254 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16255 ((string= value "later") (org-timestamp-change 1 'day))
16256 ((string= value "") (org-deadline '(4)))
16257 (t (org-deadline nil value)))
16258 (if (member value '("earlier" "later" ""))
16259 (call-interactively #'org-deadline)
16260 (org-deadline nil value))))
16261 ((member property org-special-properties)
16262 (error "The %s property cannot be set with `org-entry-put'" property))
16264 (let* ((range (org-get-property-block beg 'force))
16265 (end (cdr range))
16266 (case-fold-search t))
16267 (goto-char (car range))
16268 (if (re-search-forward (org-re-property property nil t) end t)
16269 (progn (delete-region (match-beginning 0) (match-end 0))
16270 (goto-char (match-beginning 0)))
16271 (goto-char end)
16272 (insert "\n")
16273 (backward-char))
16274 (insert ":" property ":")
16275 (when value (insert " " value))
16276 (org-indent-line)))))
16277 (run-hook-with-args 'org-property-changed-functions property value)))
16279 (defun org-buffer-property-keys
16280 (&optional specials defaults columns ignore-malformed)
16281 "Get all property keys in the current buffer.
16283 When SPECIALS is non-nil, also list the special properties that
16284 reflect things like tags and TODO state.
16286 When DEFAULTS is non-nil, also include properties that has
16287 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16288 DESCRIPTION, LOCATION, and LOGGING and others.
16290 When COLUMNS in non-nil, also include property names given in
16291 COLUMN formats in the current buffer.
16293 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16294 automatically performed, such drawers will be silently ignored."
16295 (let ((case-fold-search t)
16296 (props (append
16297 (and specials org-special-properties)
16298 (and defaults (cons org-effort-property org-default-properties))
16299 nil)))
16300 (org-with-wide-buffer
16301 (goto-char (point-min))
16302 (while (re-search-forward org-property-start-re nil t)
16303 (let ((range (org-get-property-block)))
16304 (catch 'skip
16305 (unless range
16306 (when (and (not ignore-malformed)
16307 (not (org-before-first-heading-p))
16308 (y-or-n-p (format "Malformed drawer at %d, repair?"
16309 (line-beginning-position))))
16310 (org-get-property-block nil t))
16311 (throw 'skip nil))
16312 (goto-char (car range))
16313 (let ((begin (car range))
16314 (end (cdr range)))
16315 ;; Make sure that found property block is not located
16316 ;; before current point, as it would generate an infloop.
16317 ;; It can happen, for example, in the following
16318 ;; situation:
16320 ;; * Headline
16321 ;; :PROPERTIES:
16322 ;; ...
16323 ;; :END:
16324 ;; *************** Inlinetask
16325 ;; #+BEGIN_EXAMPLE
16326 ;; :PROPERTIES:
16327 ;; #+END_EXAMPLE
16329 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16330 (while (< (point) end)
16331 (let ((p (progn (looking-at org-property-re)
16332 (match-string-no-properties 2))))
16333 ;; Only add true property name, not extension symbol.
16334 (push (if (not (string-match-p "\\+\\'" p)) p
16335 (substring p 0 -1))
16336 props))
16337 (forward-line))))
16338 (outline-next-heading)))
16339 (when columns
16340 (goto-char (point-min))
16341 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16342 (let ((element (org-element-at-point)))
16343 (when (memq (org-element-type element) '(keyword node-property))
16344 (let ((value (org-element-property :value element))
16345 (start 0))
16346 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16347 (setq start (match-end 0))
16348 (let ((p (match-string-no-properties 1 value)))
16349 (unless (member-ignore-case p org-special-properties)
16350 (push p props))))))))))
16351 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16353 (defun org-property-values (key)
16354 "List all non-nil values of property KEY in current buffer."
16355 (org-with-wide-buffer
16356 (goto-char (point-min))
16357 (let ((case-fold-search t)
16358 (re (org-re-property key))
16359 values)
16360 (while (re-search-forward re nil t)
16361 (push (org-entry-get (point) key) values))
16362 (delete-dups values))))
16364 (defun org-insert-property-drawer ()
16365 "Insert a property drawer into the current entry."
16366 (org-with-wide-buffer
16367 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16368 (org-back-to-heading t)
16369 (org-with-limited-levels (org-back-to-heading t)))
16370 (forward-line)
16371 (when (looking-at-p org-planning-line-re) (forward-line))
16372 (unless (looking-at-p org-property-drawer-re)
16373 ;; Make sure we start editing a line from current entry, not from
16374 ;; next one. It prevents extending text properties or overlays
16375 ;; belonging to the latter.
16376 (when (bolp) (backward-char))
16377 (let ((begin (1+ (point)))
16378 (inhibit-read-only t))
16379 (insert "\n:PROPERTIES:\n:END:")
16380 (when (eobp) (insert "\n"))
16381 (org-indent-region begin (point))))))
16383 (defun org-insert-drawer (&optional arg drawer)
16384 "Insert a drawer at point.
16386 When optional argument ARG is non-nil, insert a property drawer.
16388 Optional argument DRAWER, when non-nil, is a string representing
16389 drawer's name. Otherwise, the user is prompted for a name.
16391 If a region is active, insert the drawer around that region
16392 instead.
16394 Point is left between drawer's boundaries."
16395 (interactive "P")
16396 (let* ((drawer (if arg "PROPERTIES"
16397 (or drawer (read-from-minibuffer "Drawer: ")))))
16398 (cond
16399 ;; With C-u, fall back on `org-insert-property-drawer'
16400 (arg (org-insert-property-drawer))
16401 ;; Check validity of suggested drawer's name.
16402 ((not (string-match-p org-drawer-regexp (format ":%s:" drawer)))
16403 (user-error "Invalid drawer name"))
16404 ;; With an active region, insert a drawer at point.
16405 ((not (org-region-active-p))
16406 (progn
16407 (unless (bolp) (insert "\n"))
16408 (insert (format ":%s:\n\n:END:\n" drawer))
16409 (forward-line -2)))
16410 ;; Otherwise, insert the drawer at point
16412 (let ((rbeg (region-beginning))
16413 (rend (copy-marker (region-end))))
16414 (unwind-protect
16415 (progn
16416 (goto-char rbeg)
16417 (beginning-of-line)
16418 (when (save-excursion
16419 (re-search-forward org-outline-regexp-bol rend t))
16420 (user-error "Drawers cannot contain headlines"))
16421 ;; Position point at the beginning of the first
16422 ;; non-blank line in region. Insert drawer's opening
16423 ;; there, then indent it.
16424 (org-skip-whitespace)
16425 (beginning-of-line)
16426 (insert ":" drawer ":\n")
16427 (forward-line -1)
16428 (indent-for-tab-command)
16429 ;; Move point to the beginning of the first blank line
16430 ;; after the last non-blank line in region. Insert
16431 ;; drawer's closing, then indent it.
16432 (goto-char rend)
16433 (skip-chars-backward " \r\t\n")
16434 (insert "\n:END:")
16435 (deactivate-mark t)
16436 (indent-for-tab-command)
16437 (unless (eolp) (insert "\n")))
16438 ;; Clear marker, whatever the outcome of insertion is.
16439 (set-marker rend nil)))))))
16441 (defvar org-property-set-functions-alist nil
16442 "Property set function alist.
16443 Each entry should have the following format:
16445 (PROPERTY . READ-FUNCTION)
16447 The read function will be called with the same argument as
16448 `org-completing-read'.")
16450 (defun org-set-property-function (property)
16451 "Get the function that should be used to set PROPERTY.
16452 This is computed according to `org-property-set-functions-alist'."
16453 (or (cdr (assoc property org-property-set-functions-alist))
16454 'org-completing-read))
16456 (defun org-read-property-value (property)
16457 "Read PROPERTY value from user."
16458 (let* ((completion-ignore-case t)
16459 (allowed (org-property-get-allowed-values nil property 'table))
16460 (cur (org-entry-get nil property))
16461 (prompt (concat property " value"
16462 (if (and cur (string-match "\\S-" cur))
16463 (concat " [" cur "]") "") ": "))
16464 (set-function (org-set-property-function property))
16465 (val (if allowed
16466 (funcall set-function prompt allowed nil
16467 (not (get-text-property 0 'org-unrestricted
16468 (caar allowed))))
16469 (funcall set-function prompt
16470 (mapcar 'list (org-property-values property))
16471 nil nil "" nil cur))))
16472 (org-trim val)))
16474 (defvar org-last-set-property nil)
16475 (defvar org-last-set-property-value nil)
16476 (defun org-read-property-name ()
16477 "Read a property name."
16478 (let ((completion-ignore-case t)
16479 (default-prop (or (and (org-at-property-p)
16480 (match-string-no-properties 2))
16481 org-last-set-property)))
16482 (org-completing-read
16483 (concat "Property"
16484 (if default-prop (concat " [" default-prop "]") "")
16485 ": ")
16486 (mapcar #'list (org-buffer-property-keys nil t t))
16487 nil nil nil nil default-prop)))
16489 (defun org-set-property-and-value (use-last)
16490 "Allow to set [PROPERTY]: [value] direction from prompt.
16491 When use-default, don't even ask, just use the last
16492 \"[PROPERTY]: [value]\" string from the history."
16493 (interactive "P")
16494 (let* ((completion-ignore-case t)
16495 (pv (or (and use-last org-last-set-property-value)
16496 (org-completing-read
16497 "Enter a \"[Property]: [value]\" pair: "
16498 nil nil nil nil nil
16499 org-last-set-property-value)))
16500 prop val)
16501 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16502 (setq prop (match-string 1 pv)
16503 val (match-string 2 pv))
16504 (org-set-property prop val))))
16506 (defun org-set-property (property value)
16507 "In the current entry, set PROPERTY to VALUE.
16509 When called interactively, this will prompt for a property name, offering
16510 completion on existing and default properties. And then it will prompt
16511 for a value, offering completion either on allowed values (via an inherited
16512 xxx_ALL property) or on existing values in other instances of this property
16513 in the current file.
16515 Throw an error when trying to set a property with an invalid name."
16516 (interactive (list nil nil))
16517 (let ((property (or property (org-read-property-name))))
16518 ;; `org-entry-put' also makes the following check, but this one
16519 ;; avoids polluting `org-last-set-property' and
16520 ;; `org-last-set-property-value' needlessly.
16521 (unless (org--valid-property-p property)
16522 (user-error "Invalid property name: \"%s\"" property))
16523 (let ((value (or value (org-read-property-value property)))
16524 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16525 (setq org-last-set-property property)
16526 (setq org-last-set-property-value (concat property ": " value))
16527 ;; Possibly postprocess the inserted value:
16528 (when fn (setq value (funcall fn value)))
16529 (unless (equal (org-entry-get nil property) value)
16530 (org-entry-put nil property value)))))
16532 (defun org-find-property (property &optional value)
16533 "Find first entry in buffer that sets PROPERTY.
16535 When optional argument VALUE is non-nil, only consider an entry
16536 if it contains PROPERTY set to this value. If PROPERTY should be
16537 explicitly set to nil, use string \"nil\" for VALUE.
16539 Return position where the entry begins, or nil if there is no
16540 such entry. If narrowing is in effect, only search the visible
16541 part of the buffer."
16542 (save-excursion
16543 (goto-char (point-min))
16544 (let ((case-fold-search t)
16545 (re (org-re-property property nil (not value) value)))
16546 (catch 'exit
16547 (while (re-search-forward re nil t)
16548 (when (if value (org-at-property-p)
16549 (org-entry-get (point) property nil t))
16550 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16552 (defun org-delete-property (property)
16553 "In the current entry, delete PROPERTY."
16554 (interactive
16555 (let* ((completion-ignore-case t)
16556 (cat (org-entry-get (point) "CATEGORY"))
16557 (props0 (org-entry-properties nil 'standard))
16558 (props (if cat props0
16559 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16560 (prop (if (< 1 (length props))
16561 (completing-read "Property: " props nil t)
16562 (caar props))))
16563 (list prop)))
16564 (if (not property)
16565 (message "No property to delete in this entry")
16566 (org-entry-delete nil property)
16567 (message "Property \"%s\" deleted" property)))
16569 (defun org-delete-property-globally (property)
16570 "Remove PROPERTY globally, from all entries.
16571 This function ignores narrowing, if any."
16572 (interactive
16573 (let* ((completion-ignore-case t)
16574 (prop (completing-read
16575 "Globally remove property: "
16576 (mapcar #'list (org-buffer-property-keys)))))
16577 (list prop)))
16578 (org-with-wide-buffer
16579 (goto-char (point-min))
16580 (let ((count 0)
16581 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16582 (while (re-search-forward re nil t)
16583 (when (org-entry-delete (point) property) (cl-incf count)))
16584 (message "Property \"%s\" removed from %d entries" property count))))
16586 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16588 (defun org-compute-property-at-point ()
16589 "Compute the property at point.
16590 This looks for an enclosing column format, extracts the operator and
16591 then applies it to the property in the column format's scope."
16592 (interactive)
16593 (unless (org-at-property-p)
16594 (user-error "Not at a property"))
16595 (let ((prop (match-string-no-properties 2)))
16596 (org-columns-get-format-and-top-level)
16597 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16598 (user-error "No operator defined for property %s" prop))
16599 (org-columns-compute prop)))
16601 (defvar org-property-allowed-value-functions nil
16602 "Hook for functions supplying allowed values for a specific property.
16603 The functions must take a single argument, the name of the property, and
16604 return a flat list of allowed values. If \":ETC\" is one of
16605 the values, this means that these values are intended as defaults for
16606 completion, but that other values should be allowed too.
16607 The functions must return nil if they are not responsible for this
16608 property.")
16610 (defun org-property-get-allowed-values (pom property &optional table)
16611 "Get allowed values for the property PROPERTY.
16612 When TABLE is non-nil, return an alist that can directly be used for
16613 completion."
16614 (let (vals)
16615 (cond
16616 ((equal property "TODO")
16617 (setq vals (org-with-point-at pom
16618 (append org-todo-keywords-1 '("")))))
16619 ((equal property "PRIORITY")
16620 (let ((n org-lowest-priority))
16621 (while (>= n org-highest-priority)
16622 (push (char-to-string n) vals)
16623 (setq n (1- n)))))
16624 ((equal property "CATEGORY"))
16625 ((member property org-special-properties))
16626 ((setq vals (run-hook-with-args-until-success
16627 'org-property-allowed-value-functions property)))
16629 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16630 (when (and vals (string-match "\\S-" vals))
16631 (setq vals (car (read-from-string (concat "(" vals ")"))))
16632 (setq vals (mapcar (lambda (x)
16633 (cond ((stringp x) x)
16634 ((numberp x) (number-to-string x))
16635 ((symbolp x) (symbol-name x))
16636 (t "???")))
16637 vals)))))
16638 (when (member ":ETC" vals)
16639 (setq vals (remove ":ETC" vals))
16640 (org-add-props (car vals) '(org-unrestricted t)))
16641 (if table (mapcar 'list vals) vals)))
16643 (defun org-property-previous-allowed-value (&optional _previous)
16644 "Switch to the next allowed value for this property."
16645 (interactive)
16646 (org-property-next-allowed-value t))
16648 (defun org-property-next-allowed-value (&optional previous)
16649 "Switch to the next allowed value for this property."
16650 (interactive)
16651 (unless (org-at-property-p)
16652 (user-error "Not at a property"))
16653 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16654 (key (match-string 2))
16655 (value (match-string 3))
16656 (allowed (or (org-property-get-allowed-values (point) key)
16657 (and (member value '("[ ]" "[-]" "[X]"))
16658 '("[ ]" "[X]"))))
16659 (heading (save-match-data (nth 4 (org-heading-components))))
16660 nval)
16661 (unless allowed
16662 (user-error "Allowed values for this property have not been defined"))
16663 (when previous (setq allowed (reverse allowed)))
16664 (when (member value allowed)
16665 (setq nval (car (cdr (member value allowed)))))
16666 (setq nval (or nval (car allowed)))
16667 (when (equal nval value)
16668 (user-error "Only one allowed value for this property"))
16669 (org-at-property-p)
16670 (replace-match (concat " :" key ": " nval) t t)
16671 (org-indent-line)
16672 (beginning-of-line 1)
16673 (skip-chars-forward " \t")
16674 (when (equal prop org-effort-property)
16675 (org-refresh-property
16676 '((effort . identity)
16677 (effort-minutes . org-duration-string-to-minutes))
16678 nval)
16679 (when (string= org-clock-current-task heading)
16680 (setq org-clock-effort nval)
16681 (org-clock-update-mode-line)))
16682 (run-hook-with-args 'org-property-changed-functions key nval)))
16684 (defun org-find-olp (path &optional this-buffer)
16685 "Return a marker pointing to the entry at outline path OLP.
16686 If anything goes wrong, throw an error.
16687 You can wrap this call to catch the error like this:
16689 \(condition-case msg
16690 \(org-mobile-locate-entry (match-string 4))
16691 \(error (nth 1 msg)))
16693 The return value will then be either a string with the error message,
16694 or a marker if everything is OK.
16696 If THIS-BUFFER is set, the outline path does not contain a file,
16697 only headings."
16698 (let* ((file (if this-buffer buffer-file-name (pop path)))
16699 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16700 (level 1)
16701 (lmin 1)
16702 (lmax 1)
16703 end found flevel)
16704 (unless buffer (error "File not found :%s" file))
16705 (with-current-buffer buffer
16706 (org-with-wide-buffer
16707 (goto-char (point-min))
16708 (dolist (heading path)
16709 (let ((re (format org-complex-heading-regexp-format
16710 (regexp-quote heading)))
16711 (cnt 0))
16712 (while (re-search-forward re end t)
16713 (setq level (- (match-end 1) (match-beginning 1)))
16714 (when (and (>= level lmin) (<= level lmax))
16715 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16716 (when (= cnt 0)
16717 (error "Heading not found on level %d: %s" lmax heading))
16718 (when (> cnt 1)
16719 (error "Heading not unique on level %d: %s" lmax heading))
16720 (goto-char found)
16721 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16722 (setq end (save-excursion (org-end-of-subtree t t)))))
16723 (when (org-at-heading-p)
16724 (point-marker))))))
16726 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16727 "Find node HEADING in BUFFER.
16728 Return a marker to the heading if it was found, or nil if not.
16729 If POS-ONLY is set, return just the position instead of a marker.
16731 The heading text must match exact, but it may have a TODO keyword,
16732 a priority cookie and tags in the standard locations."
16733 (with-current-buffer (or buffer (current-buffer))
16734 (save-excursion
16735 (save-restriction
16736 (widen)
16737 (goto-char (point-min))
16738 (let (case-fold-search)
16739 (when (re-search-forward
16740 (format org-complex-heading-regexp-format
16741 (regexp-quote heading)) nil t)
16742 (if pos-only
16743 (match-beginning 0)
16744 (move-marker (make-marker) (match-beginning 0)))))))))
16746 (defun org-find-exact-heading-in-directory (heading &optional dir)
16747 "Find Org node headline HEADING in all .org files in directory DIR.
16748 When the target headline is found, return a marker to this location."
16749 (let ((files (directory-files (or dir default-directory)
16750 t "\\`[^.#].*\\.org\\'"))
16751 visiting m buffer)
16752 (catch 'found
16753 (dolist (file files)
16754 (message "trying %s" file)
16755 (setq visiting (org-find-base-buffer-visiting file))
16756 (setq buffer (or visiting (find-file-noselect file)))
16757 (setq m (org-find-exact-headline-in-buffer
16758 heading buffer))
16759 (when (and (not m) (not visiting)) (kill-buffer buffer))
16760 (and m (throw 'found m))))))
16762 (defun org-find-entry-with-id (ident)
16763 "Locate the entry that contains the ID property with exact value IDENT.
16764 IDENT can be a string, a symbol or a number, this function will search for
16765 the string representation of it.
16766 Return the position where this entry starts, or nil if there is no such entry."
16767 (interactive "sID: ")
16768 (let ((id (cond
16769 ((stringp ident) ident)
16770 ((symbolp ident) (symbol-name ident))
16771 ((numberp ident) (number-to-string ident))
16772 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16773 (org-with-wide-buffer (org-find-property "ID" id))))
16775 ;;;; Timestamps
16777 (defvar org-last-changed-timestamp nil)
16778 (defvar org-last-inserted-timestamp nil
16779 "The last time stamp inserted with `org-insert-time-stamp'.")
16780 (defvar org-ts-what) ; dynamically scoped parameter
16782 (defun org-time-stamp (arg &optional inactive)
16783 "Prompt for a date/time and insert a time stamp.
16785 If the user specifies a time like HH:MM or if this command is
16786 called with at least one prefix argument, the time stamp contains
16787 the date and the time. Otherwise, only the date is included.
16789 All parts of a date not specified by the user are filled in from
16790 the timestamp at point, if any, or the current date/time
16791 otherwise.
16793 If there is already a timestamp at the cursor, it is replaced.
16795 With two universal prefix arguments, insert an active timestamp
16796 with the current time without prompting the user.
16798 When called from lisp, the timestamp is inactive if INACTIVE is
16799 non-nil."
16800 (interactive "P")
16801 (let* ((ts (cond
16802 ((org-at-date-range-p t)
16803 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16804 ((org-at-timestamp-p t) (match-string 0))))
16805 ;; Default time is either the timestamp at point or today.
16806 ;; When entering a range, only the range start is considered.
16807 (default-time (if (not ts) (current-time)
16808 (apply #'encode-time (org-parse-time-string ts))))
16809 (default-input (and ts (org-get-compact-tod ts)))
16810 (repeater (and ts
16811 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16812 (match-string 0 ts)))
16813 org-time-was-given
16814 org-end-time-was-given
16815 (time
16816 (and (if (equal arg '(16)) (current-time)
16817 ;; Preserve `this-command' and `last-command'.
16818 (let ((this-command this-command)
16819 (last-command last-command))
16820 (org-read-date
16821 arg 'totime nil nil default-time default-input
16822 inactive))))))
16823 (cond
16824 ((and ts
16825 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16826 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16827 (insert "--")
16828 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16830 ;; Make sure we're on a timestamp. When in the middle of a date
16831 ;; range, move arbitrarily to range end.
16832 (unless (org-at-timestamp-p t)
16833 (skip-chars-forward "-")
16834 (org-at-timestamp-p t))
16835 (replace-match "")
16836 (setq org-last-changed-timestamp
16837 (org-insert-time-stamp
16838 time (or org-time-was-given arg)
16839 inactive nil nil (list org-end-time-was-given)))
16840 (when repeater
16841 (backward-char)
16842 (insert " " repeater)
16843 (setq org-last-changed-timestamp
16844 (concat (substring org-last-inserted-timestamp 0 -1)
16845 " " repeater ">")))
16846 (message "Timestamp updated"))
16847 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16848 (t (org-insert-time-stamp
16849 time (or org-time-was-given arg) inactive nil nil
16850 (list org-end-time-was-given))))))
16852 ;; FIXME: can we use this for something else, like computing time differences?
16853 (defun org-get-compact-tod (s)
16854 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16855 (let* ((t1 (match-string 1 s))
16856 (h1 (string-to-number (match-string 2 s)))
16857 (m1 (string-to-number (match-string 3 s)))
16858 (t2 (and (match-end 4) (match-string 5 s)))
16859 (h2 (and t2 (string-to-number (match-string 6 s))))
16860 (m2 (and t2 (string-to-number (match-string 7 s))))
16861 dh dm)
16862 (if (not t2)
16864 (setq dh (- h2 h1) dm (- m2 m1))
16865 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16866 (concat t1 "+" (number-to-string dh)
16867 (and (/= 0 dm) (format ":%02d" dm)))))))
16869 (defun org-time-stamp-inactive (&optional arg)
16870 "Insert an inactive time stamp.
16871 An inactive time stamp is enclosed in square brackets instead of angle
16872 brackets. It is inactive in the sense that it does not trigger agenda entries,
16873 does not link to the calendar and cannot be changed with the S-cursor keys.
16874 So these are more for recording a certain time/date."
16875 (interactive "P")
16876 (org-time-stamp arg 'inactive))
16878 (defvar org-date-ovl (make-overlay 1 1))
16879 (overlay-put org-date-ovl 'face 'org-date-selected)
16880 (delete-overlay org-date-ovl)
16882 (defvar org-ans1) ; dynamically scoped parameter
16883 (defvar org-ans2) ; dynamically scoped parameter
16885 (defvar org-plain-time-of-day-regexp) ; defined below
16887 (defvar org-overriding-default-time nil) ; dynamically scoped
16888 (defvar org-read-date-overlay nil)
16889 (defvar org-dcst nil) ; dynamically scoped
16890 (defvar org-read-date-history nil)
16891 (defvar org-read-date-final-answer nil)
16892 (defvar org-read-date-analyze-futurep nil)
16893 (defvar org-read-date-analyze-forced-year nil)
16894 (defvar org-read-date-inactive)
16896 (defvar org-read-date-minibuffer-local-map
16897 (let* ((map (make-sparse-keymap)))
16898 (set-keymap-parent map minibuffer-local-map)
16899 (org-defkey map (kbd ".")
16900 (lambda () (interactive)
16901 ;; Are we at the beginning of the prompt?
16902 (if (looking-back "^[^:]+: "
16903 (let ((inhibit-field-text-motion t))
16904 (line-beginning-position)))
16905 (org-eval-in-calendar '(calendar-goto-today))
16906 (insert "."))))
16907 (org-defkey map (kbd "C-.")
16908 (lambda () (interactive)
16909 (org-eval-in-calendar '(calendar-goto-today))))
16910 (org-defkey map [(meta shift left)]
16911 (lambda () (interactive)
16912 (org-eval-in-calendar '(calendar-backward-month 1))))
16913 (org-defkey map [(meta shift right)]
16914 (lambda () (interactive)
16915 (org-eval-in-calendar '(calendar-forward-month 1))))
16916 (org-defkey map [(meta shift up)]
16917 (lambda () (interactive)
16918 (org-eval-in-calendar '(calendar-backward-year 1))))
16919 (org-defkey map [(meta shift down)]
16920 (lambda () (interactive)
16921 (org-eval-in-calendar '(calendar-forward-year 1))))
16922 (org-defkey map [?\e (shift left)]
16923 (lambda () (interactive)
16924 (org-eval-in-calendar '(calendar-backward-month 1))))
16925 (org-defkey map [?\e (shift right)]
16926 (lambda () (interactive)
16927 (org-eval-in-calendar '(calendar-forward-month 1))))
16928 (org-defkey map [?\e (shift up)]
16929 (lambda () (interactive)
16930 (org-eval-in-calendar '(calendar-backward-year 1))))
16931 (org-defkey map [?\e (shift down)]
16932 (lambda () (interactive)
16933 (org-eval-in-calendar '(calendar-forward-year 1))))
16934 (org-defkey map [(shift up)]
16935 (lambda () (interactive)
16936 (org-eval-in-calendar '(calendar-backward-week 1))))
16937 (org-defkey map [(shift down)]
16938 (lambda () (interactive)
16939 (org-eval-in-calendar '(calendar-forward-week 1))))
16940 (org-defkey map [(shift left)]
16941 (lambda () (interactive)
16942 (org-eval-in-calendar '(calendar-backward-day 1))))
16943 (org-defkey map [(shift right)]
16944 (lambda () (interactive)
16945 (org-eval-in-calendar '(calendar-forward-day 1))))
16946 (org-defkey map "!"
16947 (lambda () (interactive)
16948 (org-eval-in-calendar '(diary-view-entries))
16949 (message "")))
16950 (org-defkey map ">"
16951 (lambda () (interactive)
16952 (org-eval-in-calendar '(calendar-scroll-left 1))))
16953 (org-defkey map "<"
16954 (lambda () (interactive)
16955 (org-eval-in-calendar '(calendar-scroll-right 1))))
16956 (org-defkey map "\C-v"
16957 (lambda () (interactive)
16958 (org-eval-in-calendar
16959 '(calendar-scroll-left-three-months 1))))
16960 (org-defkey map "\M-v"
16961 (lambda () (interactive)
16962 (org-eval-in-calendar
16963 '(calendar-scroll-right-three-months 1))))
16964 map)
16965 "Keymap for minibuffer commands when using `org-read-date'.")
16967 (defvar org-def)
16968 (defvar org-defdecode)
16969 (defvar org-with-time)
16971 (defvar calendar-setup) ; Dynamically scoped.
16972 (defun org-read-date (&optional with-time to-time from-string prompt
16973 default-time default-input inactive)
16974 "Read a date, possibly a time, and make things smooth for the user.
16975 The prompt will suggest to enter an ISO date, but you can also enter anything
16976 which will at least partially be understood by `parse-time-string'.
16977 Unrecognized parts of the date will default to the current day, month, year,
16978 hour and minute. If this command is called to replace a timestamp at point,
16979 or to enter the second timestamp of a range, the default time is taken
16980 from the existing stamp. Furthermore, the command prefers the future,
16981 so if you are giving a date where the year is not given, and the day-month
16982 combination is already past in the current year, it will assume you
16983 mean next year. For details, see the manual. A few examples:
16985 3-2-5 --> 2003-02-05
16986 feb 15 --> currentyear-02-15
16987 2/15 --> currentyear-02-15
16988 sep 12 9 --> 2009-09-12
16989 12:45 --> today 12:45
16990 22 sept 0:34 --> currentyear-09-22 0:34
16991 12 --> currentyear-currentmonth-12
16992 Fri --> nearest Friday after today
16993 -Tue --> last Tuesday
16994 etc.
16996 Furthermore you can specify a relative date by giving, as the *first* thing
16997 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16998 change in days weeks, months, years.
16999 With a single plus or minus, the date is relative to today. With a double
17000 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
17001 +4d --> four days from today
17002 +4 --> same as above
17003 +2w --> two weeks from today
17004 ++5 --> five days from default date
17006 The function understands only English month and weekday abbreviations.
17008 While prompting, a calendar is popped up - you can also select the
17009 date with the mouse (button 1). The calendar shows a period of three
17010 months. To scroll it to other months, use the keys `>' and `<'.
17011 If you don't like the calendar, turn it off with
17012 (setq org-read-date-popup-calendar nil)
17014 With optional argument TO-TIME, the date will immediately be converted
17015 to an internal time.
17016 With an optional argument WITH-TIME, the prompt will suggest to
17017 also insert a time. Note that when WITH-TIME is not set, you can
17018 still enter a time, and this function will inform the calling routine
17019 about this change. The calling routine may then choose to change the
17020 format used to insert the time stamp into the buffer to include the time.
17021 With optional argument FROM-STRING, read from this string instead from
17022 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
17023 the time/date that is used for everything that is not specified by the
17024 user."
17025 (require 'parse-time)
17026 (let* ((org-with-time with-time)
17027 (org-time-stamp-rounding-minutes
17028 (if (equal org-with-time '(16))
17029 '(0 0)
17030 org-time-stamp-rounding-minutes))
17031 (org-dcst org-display-custom-times)
17032 (ct (org-current-time))
17033 (org-def (or org-overriding-default-time default-time ct))
17034 (org-defdecode (decode-time org-def))
17035 (cur-frame (selected-frame))
17036 (mouse-autoselect-window nil) ; Don't let the mouse jump
17037 (calendar-setup
17038 (and (eq calendar-setup 'calendar-only) 'calendar-only))
17039 (calendar-move-hook nil)
17040 (calendar-view-diary-initially-flag nil)
17041 (calendar-view-holidays-initially-flag nil)
17042 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
17043 ;; Rationalize `org-def' and `org-defdecode', if required.
17044 (when (< (nth 2 org-defdecode) org-extend-today-until)
17045 (setf (nth 2 org-defdecode) -1)
17046 (setf (nth 1 org-defdecode) 59)
17047 (setq org-def (apply #'encode-time org-defdecode))
17048 (setq org-defdecode (decode-time org-def)))
17049 (let* ((timestr (format-time-string
17050 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
17051 org-def))
17052 (prompt (concat (if prompt (concat prompt " ") "")
17053 (format "Date+time [%s]: " timestr))))
17054 (cond
17055 (from-string (setq ans from-string))
17056 (org-read-date-popup-calendar
17057 (save-excursion
17058 (save-window-excursion
17059 (calendar)
17060 (when (eq calendar-setup 'calendar-only)
17061 (setq cal-frame
17062 (window-frame (get-buffer-window "*Calendar*" 'visible)))
17063 (select-frame cal-frame))
17064 (org-eval-in-calendar '(setq cursor-type nil) t)
17065 (unwind-protect
17066 (progn
17067 (calendar-forward-day (- (time-to-days org-def)
17068 (calendar-absolute-from-gregorian
17069 (calendar-current-date))))
17070 (org-eval-in-calendar nil t)
17071 (let* ((old-map (current-local-map))
17072 (map (copy-keymap calendar-mode-map))
17073 (minibuffer-local-map
17074 (copy-keymap org-read-date-minibuffer-local-map)))
17075 (org-defkey map (kbd "RET") 'org-calendar-select)
17076 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17077 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17078 (unwind-protect
17079 (progn
17080 (use-local-map map)
17081 (setq org-read-date-inactive inactive)
17082 (add-hook 'post-command-hook 'org-read-date-display)
17083 (setq org-ans0
17084 (read-string prompt
17085 default-input
17086 'org-read-date-history
17087 nil))
17088 ;; org-ans0: from prompt
17089 ;; org-ans1: from mouse click
17090 ;; org-ans2: from calendar motion
17091 (setq ans
17092 (concat org-ans0 " " (or org-ans1 org-ans2))))
17093 (remove-hook 'post-command-hook 'org-read-date-display)
17094 (use-local-map old-map)
17095 (when org-read-date-overlay
17096 (delete-overlay org-read-date-overlay)
17097 (setq org-read-date-overlay nil)))))
17098 (bury-buffer "*Calendar*")
17099 (when cal-frame
17100 (delete-frame cal-frame)
17101 (select-frame-set-input-focus cur-frame))))))
17103 (t ; Naked prompt only
17104 (unwind-protect
17105 (setq ans (read-string prompt default-input
17106 'org-read-date-history timestr))
17107 (when org-read-date-overlay
17108 (delete-overlay org-read-date-overlay)
17109 (setq org-read-date-overlay nil))))))
17111 (setq final (org-read-date-analyze ans org-def org-defdecode))
17113 (when org-read-date-analyze-forced-year
17114 (message "Year was forced into %s"
17115 (if org-read-date-force-compatible-dates
17116 "compatible range (1970-2037)"
17117 "range representable on this machine"))
17118 (ding))
17120 ;; One round trip to get rid of 34th of August and stuff like that....
17121 (setq final (decode-time (apply 'encode-time final)))
17123 (setq org-read-date-final-answer ans)
17125 (if to-time
17126 (apply 'encode-time final)
17127 (if (and (boundp 'org-time-was-given) org-time-was-given)
17128 (format "%04d-%02d-%02d %02d:%02d"
17129 (nth 5 final) (nth 4 final) (nth 3 final)
17130 (nth 2 final) (nth 1 final))
17131 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17133 (defun org-read-date-display ()
17134 "Display the current date prompt interpretation in the minibuffer."
17135 (when org-read-date-display-live
17136 (when org-read-date-overlay
17137 (delete-overlay org-read-date-overlay))
17138 (when (minibufferp (current-buffer))
17139 (save-excursion
17140 (end-of-line 1)
17141 (while (not (equal (buffer-substring
17142 (max (point-min) (- (point) 4)) (point))
17143 " "))
17144 (insert " ")))
17145 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17146 " " (or org-ans1 org-ans2)))
17147 (org-end-time-was-given nil)
17148 (f (org-read-date-analyze ans org-def org-defdecode))
17149 (fmts (if org-dcst
17150 org-time-stamp-custom-formats
17151 org-time-stamp-formats))
17152 (fmt (if (or org-with-time
17153 (and (boundp 'org-time-was-given) org-time-was-given))
17154 (cdr fmts)
17155 (car fmts)))
17156 (txt (format-time-string fmt (apply 'encode-time f)))
17157 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17158 (txt (concat "=> " txt)))
17159 (when (and org-end-time-was-given
17160 (string-match org-plain-time-of-day-regexp txt))
17161 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17162 org-end-time-was-given
17163 (substring txt (match-end 0)))))
17164 (when org-read-date-analyze-futurep
17165 (setq txt (concat txt " (=>F)")))
17166 (setq org-read-date-overlay
17167 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17168 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17170 (defun org-read-date-analyze (ans def defdecode)
17171 "Analyze the combined answer of the date prompt."
17172 ;; FIXME: cleanup and comment
17173 ;; Pass `current-time' result to `decode-time' (instead of calling
17174 ;; without arguments) so that only `current-time' has to be
17175 ;; overriden in tests.
17176 (let ((org-def def)
17177 (org-defdecode defdecode)
17178 (nowdecode (decode-time (current-time)))
17179 delta deltan deltaw deltadef year month day
17180 hour minute second wday pm h2 m2 tl wday1
17181 iso-year iso-weekday iso-week iso-date futurep kill-year)
17182 (setq org-read-date-analyze-futurep nil
17183 org-read-date-analyze-forced-year nil)
17184 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17185 (setq ans "+0"))
17187 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17188 (setq ans (replace-match "" t t ans)
17189 deltan (car delta)
17190 deltaw (nth 1 delta)
17191 deltadef (nth 2 delta)))
17193 ;; Check if there is an iso week date in there. If yes, store the
17194 ;; info and postpone interpreting it until the rest of the parsing
17195 ;; is done.
17196 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17197 (setq iso-year (when (match-end 1)
17198 (org-small-year-to-year
17199 (string-to-number (match-string 1 ans))))
17200 iso-weekday (when (match-end 3)
17201 (string-to-number (match-string 3 ans)))
17202 iso-week (string-to-number (match-string 2 ans)))
17203 (setq ans (replace-match "" t t ans)))
17205 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17206 (when (string-match
17207 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17208 (setq year (if (match-end 2)
17209 (string-to-number (match-string 2 ans))
17210 (progn (setq kill-year t)
17211 (string-to-number (format-time-string "%Y"))))
17212 month (string-to-number (match-string 3 ans))
17213 day (string-to-number (match-string 4 ans)))
17214 (setq year (org-small-year-to-year year))
17215 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17216 t nil ans)))
17218 ;; Help matching dotted european dates
17219 (when (string-match
17220 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17221 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17222 (setq kill-year t)
17223 (string-to-number (format-time-string "%Y")))
17224 day (string-to-number (match-string 1 ans))
17225 month (string-to-number (match-string 2 ans))
17226 ans (replace-match (format "%04d-%02d-%02d" year month day)
17227 t nil ans)))
17229 ;; Help matching american dates, like 5/30 or 5/30/7
17230 (when (string-match
17231 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17232 (setq year (if (match-end 4)
17233 (string-to-number (match-string 4 ans))
17234 (progn (setq kill-year t)
17235 (string-to-number (format-time-string "%Y"))))
17236 month (string-to-number (match-string 1 ans))
17237 day (string-to-number (match-string 2 ans)))
17238 (setq year (org-small-year-to-year year))
17239 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17240 t nil ans)))
17241 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17242 ;; If there is a time with am/pm, and *no* time without it, we convert
17243 ;; so that matching will be successful.
17244 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17245 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17246 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17247 (setq hour (string-to-number (match-string 1 ans))
17248 minute (if (match-end 3)
17249 (string-to-number (match-string 3 ans))
17251 pm (equal ?p
17252 (string-to-char (downcase (match-string 4 ans)))))
17253 (if (and (= hour 12) (not pm))
17254 (setq hour 0)
17255 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17256 (setq ans (replace-match (format "%02d:%02d" hour minute)
17257 t t ans))))
17259 ;; Check if a time range is given as a duration
17260 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17261 (setq hour (string-to-number (match-string 1 ans))
17262 h2 (+ hour (string-to-number (match-string 3 ans)))
17263 minute (string-to-number (match-string 2 ans))
17264 m2 (+ minute (if (match-end 5) (string-to-number
17265 (match-string 5 ans))0)))
17266 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17267 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17268 t t ans)))
17270 ;; Check if there is a time range
17271 (when (boundp 'org-end-time-was-given)
17272 (setq org-time-was-given nil)
17273 (when (and (string-match org-plain-time-of-day-regexp ans)
17274 (match-end 8))
17275 (setq org-end-time-was-given (match-string 8 ans))
17276 (setq ans (concat (substring ans 0 (match-beginning 7))
17277 (substring ans (match-end 7))))))
17279 (setq tl (parse-time-string ans)
17280 day (or (nth 3 tl) (nth 3 org-defdecode))
17281 month
17282 (cond ((nth 4 tl))
17283 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17284 ;; Day was specified. Make sure DAY+MONTH
17285 ;; combination happens in the future.
17286 ((nth 3 tl)
17287 (setq futurep t)
17288 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17289 (nth 4 nowdecode)))
17290 (t (nth 4 org-defdecode)))
17291 year
17292 (cond ((and (not kill-year) (nth 5 tl)))
17293 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17294 ;; Month was guessed in the future and is at least
17295 ;; equal to NOWDECODE's. Fix year accordingly.
17296 (futurep
17297 (if (or (> month (nth 4 nowdecode))
17298 (>= day (nth 3 nowdecode)))
17299 (nth 5 nowdecode)
17300 (1+ (nth 5 nowdecode))))
17301 ;; Month was specified. Make sure MONTH+YEAR
17302 ;; combination happens in the future.
17303 ((nth 4 tl)
17304 (setq futurep t)
17305 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17306 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17307 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17308 (t (nth 5 nowdecode))))
17309 (t (nth 5 org-defdecode)))
17310 hour (or (nth 2 tl) (nth 2 org-defdecode))
17311 minute (or (nth 1 tl) (nth 1 org-defdecode))
17312 second (or (nth 0 tl) 0)
17313 wday (nth 6 tl))
17315 (when (and (eq org-read-date-prefer-future 'time)
17316 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17317 (equal day (nth 3 nowdecode))
17318 (equal month (nth 4 nowdecode))
17319 (equal year (nth 5 nowdecode))
17320 (nth 2 tl)
17321 (or (< (nth 2 tl) (nth 2 nowdecode))
17322 (and (= (nth 2 tl) (nth 2 nowdecode))
17323 (nth 1 tl)
17324 (< (nth 1 tl) (nth 1 nowdecode)))))
17325 (setq day (1+ day)
17326 futurep t))
17328 ;; Special date definitions below
17329 (cond
17330 (iso-week
17331 ;; There was an iso week
17332 (require 'cal-iso)
17333 (setq futurep nil)
17334 (setq year (or iso-year year)
17335 day (or iso-weekday wday 1)
17336 wday nil ; to make sure that the trigger below does not match
17337 iso-date (calendar-gregorian-from-absolute
17338 (calendar-iso-to-absolute
17339 (list iso-week day year))))
17340 ; FIXME: Should we also push ISO weeks into the future?
17341 ; (when (and org-read-date-prefer-future
17342 ; (not iso-year)
17343 ; (< (calendar-absolute-from-gregorian iso-date)
17344 ; (time-to-days (current-time))))
17345 ; (setq year (1+ year)
17346 ; iso-date (calendar-gregorian-from-absolute
17347 ; (calendar-iso-to-absolute
17348 ; (list iso-week day year)))))
17349 (setq month (car iso-date)
17350 year (nth 2 iso-date)
17351 day (nth 1 iso-date)))
17352 (deltan
17353 (setq futurep nil)
17354 (unless deltadef
17355 ;; Pass `current-time' result to `decode-time' (instead of
17356 ;; calling without arguments) so that only `current-time' has
17357 ;; to be overriden in tests.
17358 (let ((now (decode-time (current-time))))
17359 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17360 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17361 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17362 ((equal deltaw "m") (setq month (+ month deltan)))
17363 ((equal deltaw "y") (setq year (+ year deltan)))))
17364 ((and wday (not (nth 3 tl)))
17365 ;; Weekday was given, but no day, so pick that day in the week
17366 ;; on or after the derived date.
17367 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17368 (unless (equal wday wday1)
17369 (setq day (+ day (% (- wday wday1 -7) 7))))))
17370 (when (and (boundp 'org-time-was-given)
17371 (nth 2 tl))
17372 (setq org-time-was-given t))
17373 (when (< year 100) (setq year (+ 2000 year)))
17374 ;; Check of the date is representable
17375 (if org-read-date-force-compatible-dates
17376 (progn
17377 (when (< year 1970)
17378 (setq year 1970 org-read-date-analyze-forced-year t))
17379 (when (> year 2037)
17380 (setq year 2037 org-read-date-analyze-forced-year t)))
17381 (condition-case nil
17382 (ignore (encode-time second minute hour day month year))
17383 (error
17384 (setq year (nth 5 org-defdecode))
17385 (setq org-read-date-analyze-forced-year t))))
17386 (setq org-read-date-analyze-futurep futurep)
17387 (list second minute hour day month year)))
17389 (defvar parse-time-weekdays)
17390 (defun org-read-date-get-relative (s today default)
17391 "Check string S for special relative date string.
17392 TODAY and DEFAULT are internal times, for today and for a default.
17393 Return shift list (N what def-flag)
17394 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17395 N is the number of WHATs to shift.
17396 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17397 the DEFAULT date rather than TODAY."
17398 (require 'parse-time)
17399 (when (and
17400 (string-match
17401 (concat
17402 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17403 "\\([0-9]+\\)?"
17404 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17405 "\\([ \t]\\|$\\)") s)
17406 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17407 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17408 (string-to-char (substring (match-string 1 s) -1))
17409 ?+))
17410 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17411 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17412 (what (if (match-end 3) (match-string 3 s) "d"))
17413 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17414 (date (if rel default today))
17415 (wday (nth 6 (decode-time date)))
17416 delta)
17417 (if wday1
17418 (progn
17419 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17420 (when (= delta 0) (setq delta 7))
17421 (when (= dir ?-)
17422 (setq delta (- delta 7))
17423 (when (= delta 0) (setq delta -7)))
17424 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17425 (list delta "d" rel))
17426 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17428 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17429 "Turn a user-specified date into the internal representation.
17430 The internal representation needed by the calendar is (month day year).
17431 This is a wrapper to handle the brain-dead convention in calendar that
17432 user function argument order change dependent on argument order."
17433 (pcase calendar-date-style
17434 (`american (list arg1 arg2 arg3))
17435 (`european (list arg2 arg1 arg3))
17436 (`iso (list arg2 arg3 arg1))))
17438 (defun org-eval-in-calendar (form &optional keepdate)
17439 "Eval FORM in the calendar window and return to current window.
17440 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17441 (let ((sf (selected-frame))
17442 (sw (selected-window)))
17443 (select-window (get-buffer-window "*Calendar*" t))
17444 (eval form)
17445 (when (and (not keepdate) (calendar-cursor-to-date))
17446 (let* ((date (calendar-cursor-to-date))
17447 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17448 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17449 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17450 (select-window sw)
17451 (select-frame-set-input-focus sf)))
17453 (defun org-calendar-select ()
17454 "Return to `org-read-date' with the date currently selected.
17455 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17456 (interactive)
17457 (when (calendar-cursor-to-date)
17458 (let* ((date (calendar-cursor-to-date))
17459 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17460 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17461 (when (active-minibuffer-window) (exit-minibuffer))))
17463 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17464 "Insert a date stamp for the date given by the internal TIME.
17465 See `format-time-string' for the format of TIME.
17466 WITH-HM means use the stamp format that includes the time of the day.
17467 INACTIVE means use square brackets instead of angular ones, so that the
17468 stamp will not contribute to the agenda.
17469 PRE and POST are optional strings to be inserted before and after the
17470 stamp.
17471 The command returns the inserted time stamp."
17472 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17473 stamp)
17474 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17475 (insert-before-markers (or pre ""))
17476 (when (listp extra)
17477 (setq extra (car extra))
17478 (if (and (stringp extra)
17479 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17480 (setq extra (format "-%02d:%02d"
17481 (string-to-number (match-string 1 extra))
17482 (string-to-number (match-string 2 extra))))
17483 (setq extra nil)))
17484 (when extra
17485 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17486 (insert-before-markers (setq stamp (format-time-string fmt time)))
17487 (insert-before-markers (or post ""))
17488 (setq org-last-inserted-timestamp stamp)))
17490 (defun org-toggle-time-stamp-overlays ()
17491 "Toggle the use of custom time stamp formats."
17492 (interactive)
17493 (setq org-display-custom-times (not org-display-custom-times))
17494 (unless org-display-custom-times
17495 (let ((p (point-min)) (bmp (buffer-modified-p)))
17496 (while (setq p (next-single-property-change p 'display))
17497 (when (and (get-text-property p 'display)
17498 (eq (get-text-property p 'face) 'org-date))
17499 (remove-text-properties
17500 p (setq p (next-single-property-change p 'display))
17501 '(display t))))
17502 (set-buffer-modified-p bmp)))
17503 (org-restart-font-lock)
17504 (setq org-table-may-need-update t)
17505 (if org-display-custom-times
17506 (message "Time stamps are overlaid with custom format")
17507 (message "Time stamp overlays removed")))
17509 (defun org-display-custom-time (beg end)
17510 "Overlay modified time stamp format over timestamp between BEG and END."
17511 (let* ((ts (buffer-substring beg end))
17512 t1 w1 with-hm tf time str w2 (off 0))
17513 (save-match-data
17514 (setq t1 (org-parse-time-string ts t))
17515 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17516 (setq off (- (match-end 0) (match-beginning 0)))))
17517 (setq end (- end off))
17518 (setq w1 (- end beg)
17519 with-hm (and (nth 1 t1) (nth 2 t1))
17520 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17521 time (org-fix-decoded-time t1)
17522 str (org-add-props
17523 (format-time-string
17524 (substring tf 1 -1) (apply 'encode-time time))
17525 nil 'mouse-face 'highlight)
17526 w2 (length str))
17527 (unless (= w2 w1)
17528 (add-text-properties (1+ beg) (+ 2 beg)
17529 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17530 (put-text-property beg end 'display str)))
17532 (defun org-fix-decoded-time (time)
17533 "Set 0 instead of nil for the first 6 elements of time.
17534 Don't touch the rest."
17535 (let ((n 0))
17536 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17538 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17539 "Difference between TIMESTAMP-STRING and now in days.
17540 If SECONDS is non-nil, return the difference in seconds."
17541 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17542 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17543 (funcall fdiff (current-time)))))
17545 (defun org-deadline-close-p (timestamp-string &optional ndays)
17546 "Is the time in TIMESTAMP-STRING close to the current date?"
17547 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17548 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17549 (not (org-entry-is-done-p))))
17551 (defun org-get-wdays (ts &optional delay zero-delay)
17552 "Get the deadline lead time appropriate for timestring TS.
17553 When DELAY is non-nil, get the delay time for scheduled items
17554 instead of the deadline lead time. When ZERO-DELAY is non-nil
17555 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17556 don't try to find the delay cookie in the scheduled timestamp."
17557 (let ((tv (if delay org-scheduled-delay-days
17558 org-deadline-warning-days)))
17559 (cond
17560 ((or (and delay (< tv 0))
17561 (and delay zero-delay (<= tv 0))
17562 (and (not delay) (<= tv 0)))
17563 ;; Enforce this value no matter what
17564 (- tv))
17565 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17566 ;; lead time is specified.
17567 (floor (* (string-to-number (match-string 1 ts))
17568 (cdr (assoc (match-string 2 ts)
17569 '(("d" . 1) ("w" . 7)
17570 ("m" . 30.4) ("y" . 365.25)
17571 ("h" . 0.041667)))))))
17572 ;; go for the default.
17573 (t tv))))
17575 (defun org-calendar-select-mouse (ev)
17576 "Return to `org-read-date' with the date currently selected.
17577 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17578 (interactive "e")
17579 (mouse-set-point ev)
17580 (when (calendar-cursor-to-date)
17581 (let* ((date (calendar-cursor-to-date))
17582 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17583 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17584 (when (active-minibuffer-window) (exit-minibuffer))))
17586 (defun org-check-deadlines (ndays)
17587 "Check if there are any deadlines due or past due.
17588 A deadline is considered due if it happens within `org-deadline-warning-days'
17589 days from today's date. If the deadline appears in an entry marked DONE,
17590 it is not shown. The prefix arg NDAYS can be used to test that many
17591 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17592 (interactive "P")
17593 (let* ((org-warn-days
17594 (cond
17595 ((equal ndays '(4)) 100000)
17596 (ndays (prefix-numeric-value ndays))
17597 (t (abs org-deadline-warning-days))))
17598 (case-fold-search nil)
17599 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17600 (callback
17601 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17602 (message "%d deadlines past-due or due within %d days"
17603 (org-occur regexp nil callback)
17604 org-warn-days)))
17606 (defsubst org-re-timestamp (type)
17607 "Return a regexp for timestamp TYPE.
17608 Allowed values for TYPE are:
17610 all: all timestamps
17611 active: only active timestamps (<...>)
17612 inactive: only inactive timestamps ([...])
17613 scheduled: only scheduled timestamps
17614 deadline: only deadline timestamps
17615 closed: only closed time-stamps
17617 When TYPE is nil, fall back on returning a regexp that matches
17618 both scheduled and deadline timestamps."
17619 (cl-case type
17620 (all org-ts-regexp-both)
17621 (active org-ts-regexp)
17622 (inactive org-ts-regexp-inactive)
17623 (scheduled org-scheduled-time-regexp)
17624 (deadline org-deadline-time-regexp)
17625 (closed org-closed-time-regexp)
17626 (otherwise
17627 (concat "\\<"
17628 (regexp-opt (list org-deadline-string org-scheduled-string))
17629 " *<\\([^>]+\\)>"))))
17631 (defun org-check-before-date (d)
17632 "Check if there are deadlines or scheduled entries before date D."
17633 (interactive (list (org-read-date)))
17634 (let* ((case-fold-search nil)
17635 (regexp (org-re-timestamp org-ts-type))
17636 (ts-type org-ts-type)
17637 (callback
17638 (lambda ()
17639 (let ((match (match-string 1)))
17640 (and (if (memq ts-type '(active inactive all))
17641 (eq (org-element-type (save-excursion
17642 (backward-char)
17643 (org-element-context)))
17644 'timestamp)
17645 (org-at-planning-p))
17646 (time-less-p
17647 (org-time-string-to-time match)
17648 (org-time-string-to-time d)))))))
17649 (message "%d entries before %s"
17650 (org-occur regexp nil callback)
17651 d)))
17653 (defun org-check-after-date (d)
17654 "Check if there are deadlines or scheduled entries after date D."
17655 (interactive (list (org-read-date)))
17656 (let* ((case-fold-search nil)
17657 (regexp (org-re-timestamp org-ts-type))
17658 (ts-type org-ts-type)
17659 (callback
17660 (lambda ()
17661 (let ((match (match-string 1)))
17662 (and (if (memq ts-type '(active inactive all))
17663 (eq (org-element-type (save-excursion
17664 (backward-char)
17665 (org-element-context)))
17666 'timestamp)
17667 (org-at-planning-p))
17668 (not (time-less-p
17669 (org-time-string-to-time match)
17670 (org-time-string-to-time d))))))))
17671 (message "%d entries after %s"
17672 (org-occur regexp nil callback)
17673 d)))
17675 (defun org-check-dates-range (start-date end-date)
17676 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17677 (interactive (list (org-read-date nil nil nil "Range starts")
17678 (org-read-date nil nil nil "Range end")))
17679 (let ((case-fold-search nil)
17680 (regexp (org-re-timestamp org-ts-type))
17681 (callback
17682 (let ((type org-ts-type))
17683 (lambda ()
17684 (let ((match (match-string 1)))
17685 (and
17686 (if (memq type '(active inactive all))
17687 (eq (org-element-type (save-excursion
17688 (backward-char)
17689 (org-element-context)))
17690 'timestamp)
17691 (org-at-planning-p))
17692 (not (time-less-p
17693 (org-time-string-to-time match)
17694 (org-time-string-to-time start-date)))
17695 (time-less-p
17696 (org-time-string-to-time match)
17697 (org-time-string-to-time end-date))))))))
17698 (message "%d entries between %s and %s"
17699 (org-occur regexp nil callback) start-date end-date)))
17701 (defun org-evaluate-time-range (&optional to-buffer)
17702 "Evaluate a time range by computing the difference between start and end.
17703 Normally the result is just printed in the echo area, but with prefix arg
17704 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17705 If the time range is actually in a table, the result is inserted into the
17706 next column.
17707 For time difference computation, a year is assumed to be exactly 365
17708 days in order to avoid rounding problems."
17709 (interactive "P")
17711 (org-clock-update-time-maybe)
17712 (save-excursion
17713 (unless (org-at-date-range-p t)
17714 (goto-char (point-at-bol))
17715 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17716 (unless (org-at-date-range-p t)
17717 (user-error "Not at a time-stamp range, and none found in current line")))
17718 (let* ((ts1 (match-string 1))
17719 (ts2 (match-string 2))
17720 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17721 (match-end (match-end 0))
17722 (time1 (org-time-string-to-time ts1))
17723 (time2 (org-time-string-to-time ts2))
17724 (t1 (float-time time1))
17725 (t2 (float-time time2))
17726 (diff (abs (- t2 t1)))
17727 (negative (< (- t2 t1) 0))
17728 ;; (ys (floor (* 365 24 60 60)))
17729 (ds (* 24 60 60))
17730 (hs (* 60 60))
17731 (fy "%dy %dd %02d:%02d")
17732 (fy1 "%dy %dd")
17733 (fd "%dd %02d:%02d")
17734 (fd1 "%dd")
17735 (fh "%02d:%02d")
17736 y d h m align)
17737 (if havetime
17738 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17740 d (floor (/ diff ds)) diff (mod diff ds)
17741 h (floor (/ diff hs)) diff (mod diff hs)
17742 m (floor (/ diff 60)))
17743 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17745 d (floor (+ (/ diff ds) 0.5))
17746 h 0 m 0))
17747 (if (not to-buffer)
17748 (message "%s" (org-make-tdiff-string y d h m))
17749 (if (org-at-table-p)
17750 (progn
17751 (goto-char match-end)
17752 (setq align t)
17753 (and (looking-at " *|") (goto-char (match-end 0))))
17754 (goto-char match-end))
17755 (when (looking-at
17756 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17757 (replace-match ""))
17758 (when negative (insert " -"))
17759 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17760 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17761 (insert " " (format fh h m))))
17762 (when align (org-table-align))
17763 (message "Time difference inserted")))))
17765 (defun org-make-tdiff-string (y d h m)
17766 (let ((fmt "")
17767 (l nil))
17768 (when (> y 0)
17769 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17770 (push y l))
17771 (when (> d 0)
17772 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17773 (push d l))
17774 (when (> h 0)
17775 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17776 (push h l))
17777 (when (> m 0)
17778 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17779 (push m l))
17780 (apply 'format fmt (nreverse l))))
17782 (defun org-time-string-to-time (s &optional buffer pos)
17783 "Convert a timestamp string into internal time."
17784 (condition-case errdata
17785 (apply 'encode-time (org-parse-time-string s))
17786 (error (error "Bad timestamp `%s'%s\nError was: %s"
17787 s (if (not (and buffer pos))
17789 (format-message " at %d in buffer `%s'" pos buffer))
17790 (cdr errdata)))))
17792 (defun org-time-string-to-seconds (s)
17793 "Convert a timestamp string to a number of seconds."
17794 (float-time (org-time-string-to-time s)))
17796 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17798 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17799 "Convert time stamp S to an absolute day number.
17801 If DAYNR in non-nil, and there is a specifier for a cyclic time
17802 stamp, get the closest date to DAYNR. If PREFER is
17803 `past' (respectively `future') return a date past (respectively
17804 after) or equal to DAYNR.
17806 POS is the location of time stamp S, as a buffer position in
17807 BUFFER.
17809 Diary sexp timestamps are matched against DAYNR, when non-nil.
17810 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17811 signalled."
17812 (cond
17813 ((string-match "\\`%%\\((.*)\\)" s)
17814 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17815 ;; only able to match individual dates. If it fails, raise an
17816 ;; error.
17817 (if (and daynr
17818 (org-diary-sexp-entry
17819 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17820 daynr
17821 (signal 'org-diary-sexp-no-match (list s))))
17822 ((and daynr show-all) (org-closest-date s daynr prefer))
17823 (t (time-to-days
17824 (condition-case errdata
17825 (apply #'encode-time (org-parse-time-string s))
17826 (error (error "Bad timestamp `%s'%s\nError was: %s"
17828 (if (not (and buffer pos)) ""
17829 (format-message " at %d in buffer `%s'" pos buffer))
17830 (cdr errdata))))))))
17832 (defun org-days-to-iso-week (days)
17833 "Return the iso week number."
17834 (require 'cal-iso)
17835 (car (calendar-iso-from-absolute days)))
17837 (defun org-small-year-to-year (year)
17838 "Convert 2-digit years into 4-digit years.
17839 YEAR is expanded into one of the 30 next years, if possible, or
17840 into a past one. Any year larger than 99 is returned unchanged."
17841 (if (>= year 100) year
17842 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17843 (century (/ current 100))
17844 (offset (- year (% current 100))))
17845 (cond ((> offset 30) (+ (* (1- century) 100) year))
17846 ((> offset -70) (+ (* century 100) year))
17847 (t (+ (* (1+ century) 100) year))))))
17849 (defun org-time-from-absolute (d)
17850 "Return the time corresponding to date D.
17851 D may be an absolute day number, or a calendar-type list (month day year)."
17852 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17853 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17855 (defvar org-agenda-current-date)
17856 (defun org-calendar-holiday ()
17857 "List of holidays, for Diary display in Org mode."
17858 (require 'holidays)
17859 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17860 (and hl (mapconcat #'identity hl "; "))))
17862 (defun org-diary-sexp-entry (sexp entry d)
17863 "Process a SEXP diary ENTRY for date D."
17864 (require 'diary-lib)
17865 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17866 ;; dynamically.
17867 (let* ((sexp `(let ((entry ,entry)
17868 (date ',d))
17869 ,(car (read-from-string sexp))))
17870 (result (if calendar-debug-sexp (eval sexp)
17871 (condition-case nil
17872 (eval sexp)
17873 (error
17874 (beep)
17875 (message "Bad sexp at line %d in %s: %s"
17876 (org-current-line)
17877 (buffer-file-name) sexp)
17878 (sleep-for 2))))))
17879 (cond ((stringp result) (split-string result "; "))
17880 ((and (consp result)
17881 (not (consp (cdr result)))
17882 (stringp (cdr result))) (cdr result))
17883 ((and (consp result)
17884 (stringp (car result))) result)
17885 (result entry))))
17887 (defun org-diary-to-ical-string (frombuf)
17888 "Get iCalendar entries from diary entries in buffer FROMBUF.
17889 This uses the icalendar.el library."
17890 (let* ((tmpdir temporary-file-directory)
17891 (tmpfile (make-temp-name
17892 (expand-file-name "orgics" tmpdir)))
17893 buf rtn b e)
17894 (with-current-buffer frombuf
17895 (icalendar-export-region (point-min) (point-max) tmpfile)
17896 (setq buf (find-buffer-visiting tmpfile))
17897 (set-buffer buf)
17898 (goto-char (point-min))
17899 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17900 (setq b (match-beginning 0)))
17901 (goto-char (point-max))
17902 (when (re-search-backward "^END:VEVENT" nil t)
17903 (setq e (match-end 0)))
17904 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17905 (kill-buffer buf)
17906 (delete-file tmpfile)
17907 rtn))
17909 (defun org-closest-date (start current prefer)
17910 "Return closest date to CURRENT starting from START.
17912 CURRENT and START are both time stamps.
17914 When PREFER is `past', return a date that is either CURRENT or
17915 past. When PREFER is `future', return a date that is either
17916 CURRENT or future.
17918 Only time stamps with a repeater are modified. Any other time
17919 stamp stay unchanged. In any case, return value is an absolute
17920 day number."
17921 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17922 ;; No repeater. Do not shift time stamp.
17923 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17924 (let ((value (string-to-number (match-string 1 start)))
17925 (type (match-string 2 start)))
17926 (if (= 0 value)
17927 ;; Repeater with a 0-value is considered as void.
17928 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17929 (let* ((base (org-date-to-gregorian start))
17930 (target (org-date-to-gregorian current))
17931 (sday (calendar-absolute-from-gregorian base))
17932 (cday (calendar-absolute-from-gregorian target))
17933 n1 n2)
17934 ;; If START is already past CURRENT, just return START.
17935 (if (<= cday sday) sday
17936 ;; Compute closest date before (N1) and closest date past
17937 ;; (N2) CURRENT.
17938 (pcase type
17939 ("h"
17940 (let ((missing-hours
17941 (mod (+ (- (* 24 (- cday sday))
17942 (nth 2 (org-parse-time-string start)))
17943 org-extend-today-until)
17944 value)))
17945 (setf n1 (if (= missing-hours 0) cday
17946 (- cday (1+ (/ missing-hours 24)))))
17947 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17948 ((or "d" "w")
17949 (let ((value (if (equal type "w") (* 7 value) value)))
17950 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17951 (setf n2 (+ n1 value))))
17952 ("m"
17953 (let* ((add-months
17954 (lambda (d n)
17955 ;; Add N months to gregorian date D, i.e.,
17956 ;; a list (MONTH DAY YEAR). Return a valid
17957 ;; gregorian date.
17958 (let ((m (+ (nth 0 d) n)))
17959 (list (mod m 12)
17960 (nth 1 d)
17961 (+ (/ m 12) (nth 2 d))))))
17962 (months ; Complete months to TARGET.
17963 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17964 (- (nth 0 target) (nth 0 base))
17965 ;; If START's day is greater than
17966 ;; TARGET's, remove incomplete month.
17967 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17968 value)
17969 value))
17970 (before (funcall add-months base months)))
17971 (setf n1 (calendar-absolute-from-gregorian before))
17972 (setf n2
17973 (calendar-absolute-from-gregorian
17974 (funcall add-months before value)))))
17976 (let* ((d (nth 1 base))
17977 (m (nth 0 base))
17978 (y (nth 2 base))
17979 (years ; Complete years to TARGET.
17980 (* (/ (- (nth 2 target)
17982 ;; If START's month and day are
17983 ;; greater than TARGET's, remove
17984 ;; incomplete year.
17985 (if (or (> (nth 0 target) m)
17986 (and (= (nth 0 target) m)
17987 (> (nth 1 target) d)))
17990 value)
17991 value))
17992 (before (list m d (+ y years))))
17993 (setf n1 (calendar-absolute-from-gregorian before))
17994 (setf n2 (calendar-absolute-from-gregorian
17995 (list m d (+ (nth 2 before) value)))))))
17996 ;; Handle PREFER parameter, if any.
17997 (cond
17998 ((eq prefer 'past) (if (= cday n2) n2 n1))
17999 ((eq prefer 'future) (if (= cday n1) n1 n2))
18000 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
18002 (defun org-date-to-gregorian (d)
18003 "Turn any specification of date D into a Gregorian date for the calendar."
18004 (cond ((integerp d) (calendar-gregorian-from-absolute d))
18005 ((and (listp d) (= (length d) 3)) d)
18006 ((stringp d)
18007 (let ((d (org-parse-time-string d)))
18008 (list (nth 4 d) (nth 3 d) (nth 5 d))))
18009 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
18011 (defun org-parse-time-string (s &optional nodefault)
18012 "Parse the standard Org-mode time string.
18013 This should be a lot faster than the normal `parse-time-string'.
18014 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
18015 hour and minute fields will be nil if not given."
18016 (cond ((string-match org-ts-regexp0 s)
18017 (list 0
18018 (when (or (match-beginning 8) (not nodefault))
18019 (string-to-number (or (match-string 8 s) "0")))
18020 (when (or (match-beginning 7) (not nodefault))
18021 (string-to-number (or (match-string 7 s) "0")))
18022 (string-to-number (match-string 4 s))
18023 (string-to-number (match-string 3 s))
18024 (string-to-number (match-string 2 s))
18025 nil nil nil))
18026 ((string-match "^<[^>]+>$" s)
18027 (decode-time (seconds-to-time (org-matcher-time s))))
18028 (t (error "Not a standard Org-mode time string: %s" s))))
18030 (defun org-timestamp-up (&optional arg)
18031 "Increase the date item at the cursor by one.
18032 If the cursor is on the year, change the year. If it is on the month,
18033 the day or the time, change that.
18034 With prefix ARG, change by that many units."
18035 (interactive "p")
18036 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
18038 (defun org-timestamp-down (&optional arg)
18039 "Decrease the date item at the cursor by one.
18040 If the cursor is on the year, change the year. If it is on the month,
18041 the day or the time, change that.
18042 With prefix ARG, change by that many units."
18043 (interactive "p")
18044 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
18046 (defun org-timestamp-up-day (&optional arg)
18047 "Increase the date in the time stamp by one day.
18048 With prefix ARG, change that many days."
18049 (interactive "p")
18050 (if (and (not (org-at-timestamp-p t))
18051 (org-at-heading-p))
18052 (org-todo 'up)
18053 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
18055 (defun org-timestamp-down-day (&optional arg)
18056 "Decrease the date in the time stamp by one day.
18057 With prefix ARG, change that many days."
18058 (interactive "p")
18059 (if (and (not (org-at-timestamp-p t))
18060 (org-at-heading-p))
18061 (org-todo 'down)
18062 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18064 (defun org-at-timestamp-p (&optional inactive-ok)
18065 "Non-nil if point is inside a timestamp.
18067 When optional argument INACTIVE-OK is non-nil, also consider
18068 inactive timestamps.
18070 When this function returns a non-nil value, match data is set
18071 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18072 INACTIVE-OK."
18073 (interactive)
18074 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18075 (pos (point))
18076 (ans (or (looking-at tsr)
18077 (save-excursion
18078 (skip-chars-backward "^[<\n\r\t")
18079 (when (> (point) (point-min)) (backward-char 1))
18080 (and (looking-at tsr)
18081 (> (- (match-end 0) pos) -1))))))
18082 (and ans
18083 (boundp 'org-ts-what)
18084 (setq org-ts-what
18085 (cond
18086 ((= pos (match-beginning 0)) 'bracket)
18087 ;; Point is considered to be "on the bracket" whether
18088 ;; it's really on it or right after it.
18089 ((= pos (1- (match-end 0))) 'bracket)
18090 ((= pos (match-end 0)) 'after)
18091 ((org-pos-in-match-range pos 2) 'year)
18092 ((org-pos-in-match-range pos 3) 'month)
18093 ((org-pos-in-match-range pos 7) 'hour)
18094 ((org-pos-in-match-range pos 8) 'minute)
18095 ((or (org-pos-in-match-range pos 4)
18096 (org-pos-in-match-range pos 5)) 'day)
18097 ((and (> pos (or (match-end 8) (match-end 5)))
18098 (< pos (match-end 0)))
18099 (- pos (or (match-end 8) (match-end 5))))
18100 (t 'day))))
18101 ans))
18103 (defun org-toggle-timestamp-type ()
18104 "Toggle the type (<active> or [inactive]) of a time stamp."
18105 (interactive)
18106 (when (org-at-timestamp-p t)
18107 (let ((beg (match-beginning 0)) (end (match-end 0))
18108 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18109 (save-excursion
18110 (goto-char beg)
18111 (while (re-search-forward "[][<>]" end t)
18112 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18113 t t)))
18114 (message "Timestamp is now %sactive"
18115 (if (equal (char-after beg) ?<) "" "in")))))
18117 (defun org-at-clock-log-p nil
18118 "Is the cursor on the clock log line?"
18119 (save-excursion
18120 (move-beginning-of-line 1)
18121 (looking-at org-clock-line-re)))
18123 (defvar org-clock-history) ; defined in org-clock.el
18124 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18125 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18126 "Change the date in the time stamp at point.
18127 The date will be changed by N times WHAT. WHAT can be `day', `month',
18128 `year', `minute', `second'. If WHAT is not given, the cursor position
18129 in the timestamp determines what will be changed.
18130 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18131 (let ((origin (point)) origin-cat
18132 with-hm inactive
18133 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18134 org-ts-what
18135 extra rem
18136 ts time time0 fixnext clrgx)
18137 (unless (org-at-timestamp-p t)
18138 (user-error "Not at a timestamp"))
18139 (if (and (not what) (eq org-ts-what 'bracket))
18140 (org-toggle-timestamp-type)
18141 ;; Point isn't on brackets. Remember the part of the time-stamp
18142 ;; the point was in. Indeed, size of time-stamps may change,
18143 ;; but point must be kept in the same category nonetheless.
18144 (setq origin-cat org-ts-what)
18145 (when (and (not what) (not (eq org-ts-what 'day))
18146 org-display-custom-times
18147 (get-text-property (point) 'display)
18148 (not (get-text-property (1- (point)) 'display)))
18149 (setq org-ts-what 'day))
18150 (setq org-ts-what (or what org-ts-what)
18151 inactive (= (char-after (match-beginning 0)) ?\[)
18152 ts (match-string 0))
18153 (replace-match "")
18154 (when (string-match
18155 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18157 (setq extra (match-string 1 ts))
18158 (when suppress-tmp-delay
18159 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18160 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18161 (setq with-hm t))
18162 (setq time0 (org-parse-time-string ts))
18163 (when (and updown
18164 (eq org-ts-what 'minute)
18165 (not current-prefix-arg))
18166 ;; This looks like s-up and s-down. Change by one rounding step.
18167 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18168 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18169 (setcar (cdr time0) (+ (nth 1 time0)
18170 (if (> n 0) (- rem) (- dm rem))))))
18171 (setq time
18172 (apply #'encode-time
18173 (or (car time0) 0)
18174 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18175 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18176 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18177 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18178 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18179 (nthcdr 6 time0)))
18180 (when (and (member org-ts-what '(hour minute))
18181 extra
18182 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18183 (setq extra (org-modify-ts-extra
18184 extra
18185 (if (eq org-ts-what 'hour) 2 5)
18186 n dm)))
18187 (when (integerp org-ts-what)
18188 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18189 (when (eq what 'calendar)
18190 (let ((cal-date (org-get-date-from-calendar)))
18191 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18192 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18193 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18194 (setcar time0 (or (car time0) 0))
18195 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18196 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18197 (setq time (apply 'encode-time time0))))
18198 ;; Insert the new time-stamp, and ensure point stays in the same
18199 ;; category as before (i.e. not after the last position in that
18200 ;; category).
18201 (let ((pos (point)))
18202 ;; Stay before inserted string. `save-excursion' is of no use.
18203 (setq org-last-changed-timestamp
18204 (org-insert-time-stamp time with-hm inactive nil nil extra))
18205 (goto-char pos))
18206 (save-match-data
18207 (looking-at org-ts-regexp3)
18208 (goto-char (cond
18209 ;; `day' category ends before `hour' if any, or at
18210 ;; the end of the day name.
18211 ((eq origin-cat 'day)
18212 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18213 ((eq origin-cat 'hour) (min (match-end 7) origin))
18214 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18215 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18216 ;; `year' and `month' have both fixed size: point
18217 ;; couldn't have moved into another part.
18218 (t origin))))
18219 ;; Update clock if on a CLOCK line.
18220 (org-clock-update-time-maybe)
18221 ;; Maybe adjust the closest clock in `org-clock-history'
18222 (when org-clock-adjust-closest
18223 (if (not (and (org-at-clock-log-p)
18224 (< 1 (length (delq nil (mapcar 'marker-position
18225 org-clock-history))))))
18226 (message "No clock to adjust")
18227 (cond ((save-excursion ; fix previous clock?
18228 (re-search-backward org-ts-regexp0 nil t)
18229 (looking-back (concat org-clock-string " \\[")
18230 (line-beginning-position)))
18231 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18232 ((save-excursion ; fix next clock?
18233 (re-search-backward org-ts-regexp0 nil t)
18234 (looking-at (concat org-ts-regexp0 "\\] =>")))
18235 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18236 (save-window-excursion
18237 ;; Find closest clock to point, adjust the previous/next one in history
18238 (let* ((p (save-excursion (org-back-to-heading t)))
18239 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18240 (clfixnth
18241 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18242 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18243 (if (not clfixpos)
18244 (message "No clock to adjust")
18245 (save-excursion
18246 (org-goto-marker-or-bmk clfixpos)
18247 (org-show-subtree)
18248 (when (re-search-forward clrgx nil t)
18249 (goto-char (match-beginning 1))
18250 (let (org-clock-adjust-closest)
18251 (org-timestamp-change n org-ts-what updown))
18252 (message "Clock adjusted in %s for heading: %s"
18253 (file-name-nondirectory (buffer-file-name))
18254 (org-get-heading t t)))))))))
18255 ;; Try to recenter the calendar window, if any.
18256 (when (and org-calendar-follow-timestamp-change
18257 (get-buffer-window "*Calendar*" t)
18258 (memq org-ts-what '(day month year)))
18259 (org-recenter-calendar (time-to-days time))))))
18261 (defun org-modify-ts-extra (s pos n dm)
18262 "Change the different parts of the lead-time and repeat fields in timestamp."
18263 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18264 ng h m new rem)
18265 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18266 (cond
18267 ((or (org-pos-in-match-range pos 2)
18268 (org-pos-in-match-range pos 3))
18269 (setq m (string-to-number (match-string 3 s))
18270 h (string-to-number (match-string 2 s)))
18271 (if (org-pos-in-match-range pos 2)
18272 (setq h (+ h n))
18273 (setq n (* dm (with-no-warnings (signum n))))
18274 (unless (= 0 (setq rem (% m dm)))
18275 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18276 (setq m (+ m n)))
18277 (when (< m 0) (setq m (+ m 60) h (1- h)))
18278 (when (> m 59) (setq m (- m 60) h (1+ h)))
18279 (setq h (mod h 24))
18280 (setq ng 1 new (format "-%02d:%02d" h m)))
18281 ((org-pos-in-match-range pos 6)
18282 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18283 ((org-pos-in-match-range pos 5)
18284 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18286 ((org-pos-in-match-range pos 9)
18287 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18288 ((org-pos-in-match-range pos 8)
18289 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18291 (when ng
18292 (setq s (concat
18293 (substring s 0 (match-beginning ng))
18295 (substring s (match-end ng))))))
18298 (defun org-recenter-calendar (d)
18299 "If the calendar is visible, recenter it to date D."
18300 (let ((cwin (get-buffer-window "*Calendar*" t)))
18301 (when cwin
18302 (let ((calendar-move-hook nil))
18303 (with-selected-window cwin
18304 (calendar-goto-date
18305 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18307 (defun org-goto-calendar (&optional arg)
18308 "Go to the Emacs calendar at the current date.
18309 If there is a time stamp in the current line, go to that date.
18310 A prefix ARG can be used to force the current date."
18311 (interactive "P")
18312 (let ((tsr org-ts-regexp) diff
18313 (calendar-move-hook nil)
18314 (calendar-view-holidays-initially-flag nil)
18315 (calendar-view-diary-initially-flag nil))
18316 (when (or (org-at-timestamp-p)
18317 (save-excursion
18318 (beginning-of-line 1)
18319 (looking-at (concat ".*" tsr))))
18320 (let ((d1 (time-to-days (current-time)))
18321 (d2 (time-to-days
18322 (org-time-string-to-time (match-string 1)))))
18323 (setq diff (- d2 d1))))
18324 (calendar)
18325 (calendar-goto-today)
18326 (when (and diff (not arg)) (calendar-forward-day diff))))
18328 (defun org-get-date-from-calendar ()
18329 "Return a list (month day year) of date at point in calendar."
18330 (with-current-buffer "*Calendar*"
18331 (save-match-data
18332 (calendar-cursor-to-date))))
18334 (defun org-date-from-calendar ()
18335 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18336 If there is already a time stamp at the cursor position, update it."
18337 (interactive)
18338 (if (org-at-timestamp-p t)
18339 (org-timestamp-change 0 'calendar)
18340 (let ((cal-date (org-get-date-from-calendar)))
18341 (org-insert-time-stamp
18342 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18344 (defcustom org-effort-durations
18345 `(("min" . 1)
18346 ("h" . 60)
18347 ("d" . ,(* 60 8))
18348 ("w" . ,(* 60 8 5))
18349 ("m" . ,(* 60 8 5 4))
18350 ("y" . ,(* 60 8 5 40)))
18351 "Conversion factor to minutes for an effort modifier.
18353 Each entry has the form (MODIFIER . MINUTES).
18355 In an effort string, a number followed by MODIFIER is multiplied
18356 by the specified number of MINUTES to obtain an effort in
18357 minutes.
18359 For example, if the value of this variable is ((\"hours\" . 60)), then an
18360 effort string \"2hours\" is equivalent to 120 minutes."
18361 :group 'org-agenda
18362 :version "25.1"
18363 :package-version '(Org . "8.3")
18364 :type '(alist :key-type (string :tag "Modifier")
18365 :value-type (number :tag "Minutes")))
18367 (defun org-minutes-to-clocksum-string (m)
18368 "Format number of minutes as a clocksum string.
18369 The format is determined by `org-time-clocksum-format',
18370 `org-time-clocksum-use-fractional' and
18371 `org-time-clocksum-fractional-format' and
18372 `org-time-clocksum-use-effort-durations'."
18373 (let ((clocksum "")
18374 (m (round m)) ; Don't allow fractions of minutes
18375 h d w mo y fmt n)
18376 (setq h (if org-time-clocksum-use-effort-durations
18377 (cdr (assoc "h" org-effort-durations)) 60)
18378 d (if org-time-clocksum-use-effort-durations
18379 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18380 w (if org-time-clocksum-use-effort-durations
18381 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18382 mo (if org-time-clocksum-use-effort-durations
18383 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18384 y (if org-time-clocksum-use-effort-durations
18385 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18386 ;; fractional format
18387 (if org-time-clocksum-use-fractional
18388 (cond
18389 ;; single format string
18390 ((stringp org-time-clocksum-fractional-format)
18391 (format org-time-clocksum-fractional-format (/ m (float h))))
18392 ;; choice of fractional formats for different time units
18393 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18394 (> (/ (truncate m) (* y d h)) 0))
18395 (format fmt (/ m (* y d (float h)))))
18396 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18397 (> (/ (truncate m) (* mo d h)) 0))
18398 (format fmt (/ m (* mo d (float h)))))
18399 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18400 (> (/ (truncate m) (* w d h)) 0))
18401 (format fmt (/ m (* w d (float h)))))
18402 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18403 (> (/ (truncate m) (* d h)) 0))
18404 (format fmt (/ m (* d (float h)))))
18405 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18406 (> (/ (truncate m) h) 0))
18407 (format fmt (/ m (float h))))
18408 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18409 (format fmt m))
18410 ;; fall back to smallest time unit with a format
18411 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18412 (format fmt (/ m (float h))))
18413 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18414 (format fmt (/ m (* d (float h)))))
18415 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18416 (format fmt (/ m (* w d (float h)))))
18417 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18418 (format fmt (/ m (* mo d (float h)))))
18419 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18420 (format fmt (/ m (* y d (float h))))))
18421 ;; standard (non-fractional) format, with single format string
18422 (if (stringp org-time-clocksum-format)
18423 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18424 ;; separate formats components
18425 (and (setq fmt (plist-get org-time-clocksum-format :years))
18426 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18427 (plist-get org-time-clocksum-format :require-years))
18428 (setq clocksum (concat clocksum (format fmt n))
18429 m (- m (* n y d h))))
18430 (and (setq fmt (plist-get org-time-clocksum-format :months))
18431 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18432 (plist-get org-time-clocksum-format :require-months))
18433 (setq clocksum (concat clocksum (format fmt n))
18434 m (- m (* n mo d h))))
18435 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18436 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18437 (plist-get org-time-clocksum-format :require-weeks))
18438 (setq clocksum (concat clocksum (format fmt n))
18439 m (- m (* n w d h))))
18440 (and (setq fmt (plist-get org-time-clocksum-format :days))
18441 (or (> (setq n (/ (truncate m) (* d h))) 0)
18442 (plist-get org-time-clocksum-format :require-days))
18443 (setq clocksum (concat clocksum (format fmt n))
18444 m (- m (* n d h))))
18445 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18446 (or (> (setq n (/ (truncate m) h)) 0)
18447 (plist-get org-time-clocksum-format :require-hours))
18448 (setq clocksum (concat clocksum (format fmt n))
18449 m (- m (* n h))))
18450 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18451 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18452 (setq clocksum (concat clocksum (format fmt m))))
18453 ;; return formatted time duration
18454 clocksum))))
18456 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18457 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18458 "Org mode version 8.0")
18460 (defun org-hours-to-clocksum-string (n)
18461 (org-minutes-to-clocksum-string (* n 60)))
18463 (defun org-hh:mm-string-to-minutes (s)
18464 "Convert a string H:MM to a number of minutes.
18465 If the string is just a number, interpret it as minutes.
18466 In fact, the first hh:mm or number in the string will be taken,
18467 there can be extra stuff in the string.
18468 If no number is found, the return value is 0."
18469 (cond
18470 ((integerp s) s)
18471 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18472 (+ (* (string-to-number (match-string 1 s)) 60)
18473 (string-to-number (match-string 2 s))))
18474 ((string-match "\\([0-9]+\\)" s)
18475 (string-to-number (match-string 1 s)))
18476 (t 0)))
18478 (defcustom org-image-actual-width t
18479 "Should we use the actual width of images when inlining them?
18481 When set to t, always use the image width.
18483 When set to a number, use imagemagick (when available) to set
18484 the image's width to this value.
18486 When set to a number in a list, try to get the width from any
18487 #+ATTR.* keyword if it matches a width specification like
18489 #+ATTR_HTML: :width 300px
18491 and fall back on that number if none is found.
18493 When set to nil, try to get the width from an #+ATTR.* keyword
18494 and fall back on the original width if none is found.
18496 This requires Emacs >= 24.1, build with imagemagick support."
18497 :group 'org-appearance
18498 :version "24.4"
18499 :package-version '(Org . "8.0")
18500 :type '(choice
18501 (const :tag "Use the image width" t)
18502 (integer :tag "Use a number of pixels")
18503 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18504 (const :tag "Use #+ATTR* or don't resize" nil)))
18506 (defcustom org-agenda-inhibit-startup nil
18507 "Inhibit startup when preparing agenda buffers.
18508 When this variable is t, the initialization of the Org agenda
18509 buffers is inhibited: e.g. the visibility state is not set, the
18510 tables are not re-aligned, etc."
18511 :type 'boolean
18512 :version "24.3"
18513 :group 'org-agenda)
18515 (defcustom org-agenda-ignore-properties nil
18516 "Avoid updating text properties when building the agenda.
18517 Properties are used to prepare buffers for effort estimates,
18518 appointments, statistics and subtree-local categories.
18519 If you don't use these in the agenda, you can add them to this
18520 list and agenda building will be a bit faster.
18521 The value is a list, with zero or more of the symbols `effort', `appt',
18522 `stats' or `category'."
18523 :type '(set :greedy t
18524 (const effort)
18525 (const appt)
18526 (const stats)
18527 (const category))
18528 :version "25.1"
18529 :package-version '(Org . "8.3")
18530 :group 'org-agenda)
18532 (defun org-duration-string-to-minutes (s &optional output-to-string)
18533 "Convert a duration string S to minutes.
18535 A bare number is interpreted as minutes, modifiers can be set by
18536 customizing `org-effort-durations' (which see).
18538 Entries containing a colon are interpreted as H:MM by
18539 `org-hh:mm-string-to-minutes'."
18540 (let ((result 0)
18541 (re (concat "\\([0-9.]+\\) *\\("
18542 (regexp-opt (mapcar 'car org-effort-durations))
18543 "\\)")))
18544 (while (string-match re s)
18545 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18546 (string-to-number (match-string 1 s))))
18547 (setq s (replace-match "" nil t s)))
18548 (setq result (floor result))
18549 (cl-incf result (org-hh:mm-string-to-minutes s))
18550 (if output-to-string (number-to-string result) result)))
18552 ;;;; Files
18554 (defun org-save-all-org-buffers ()
18555 "Save all Org-mode buffers without user confirmation."
18556 (interactive)
18557 (message "Saving all Org-mode buffers...")
18558 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18559 (when (featurep 'org-id) (org-id-locations-save))
18560 (message "Saving all Org-mode buffers... done"))
18562 (defun org-revert-all-org-buffers ()
18563 "Revert all Org-mode buffers.
18564 Prompt for confirmation when there are unsaved changes.
18565 Be sure you know what you are doing before letting this function
18566 overwrite your changes.
18568 This function is useful in a setup where one tracks org files
18569 with a version control system, to revert on one machine after pulling
18570 changes from another. I believe the procedure must be like this:
18572 1. M-x org-save-all-org-buffers
18573 2. Pull changes from the other machine, resolve conflicts
18574 3. M-x org-revert-all-org-buffers"
18575 (interactive)
18576 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18577 (user-error "Abort"))
18578 (save-excursion
18579 (save-window-excursion
18580 (dolist (b (buffer-list))
18581 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18582 (with-current-buffer b buffer-file-name))
18583 (pop-to-buffer-same-window b)
18584 (revert-buffer t 'no-confirm)))
18585 (when (and (featurep 'org-id) org-id-track-globally)
18586 (org-id-locations-load)))))
18588 ;;;; Agenda files
18590 ;;;###autoload
18591 (defun org-switchb (&optional arg)
18592 "Switch between Org buffers.
18594 With \\[universal-argument] prefix, restrict available buffers to files.
18596 With \\[universal-argument] \\[universal-argument] \
18597 prefix, restrict available buffers to agenda files."
18598 (interactive "P")
18599 (let ((blist (org-buffer-list
18600 (cond ((equal arg '(4)) 'files)
18601 ((equal arg '(16)) 'agenda)))))
18602 (pop-to-buffer-same-window
18603 (completing-read "Org buffer: "
18604 (mapcar #'list (mapcar #'buffer-name blist))
18605 nil t))))
18607 (defun org-buffer-list (&optional predicate exclude-tmp)
18608 "Return a list of Org buffers.
18609 PREDICATE can be `export', `files' or `agenda'.
18611 export restrict the list to Export buffers.
18612 files restrict the list to buffers visiting Org files.
18613 agenda restrict the list to buffers visiting agenda files.
18615 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18616 (let* ((bfn nil)
18617 (agenda-files (and (eq predicate 'agenda)
18618 (mapcar 'file-truename (org-agenda-files t))))
18619 (filter
18620 (cond
18621 ((eq predicate 'files)
18622 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18623 ((eq predicate 'export)
18624 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18625 ((eq predicate 'agenda)
18626 (lambda (b)
18627 (with-current-buffer b
18628 (and (derived-mode-p 'org-mode)
18629 (setq bfn (buffer-file-name b))
18630 (member (file-truename bfn) agenda-files)))))
18631 (t (lambda (b) (with-current-buffer b
18632 (or (derived-mode-p 'org-mode)
18633 (string-match "\\*Org .*Export"
18634 (buffer-name b)))))))))
18635 (delq nil
18636 (mapcar
18637 (lambda(b)
18638 (if (and (funcall filter b)
18639 (or (not exclude-tmp)
18640 (not (string-match "tmp" (buffer-name b)))))
18642 nil))
18643 (buffer-list)))))
18645 (defun org-agenda-files (&optional unrestricted archives)
18646 "Get the list of agenda files.
18647 Optional UNRESTRICTED means return the full list even if a restriction
18648 is currently in place.
18649 When ARCHIVES is t, include all archive files that are really being
18650 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18651 `org-agenda-archives-mode' is t."
18652 (let ((files
18653 (cond
18654 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18655 ((stringp org-agenda-files) (org-read-agenda-file-list))
18656 ((listp org-agenda-files) org-agenda-files)
18657 (t (error "Invalid value of `org-agenda-files'")))))
18658 (setq files (apply 'append
18659 (mapcar (lambda (f)
18660 (if (file-directory-p f)
18661 (directory-files
18662 f t org-agenda-file-regexp)
18663 (list f)))
18664 files)))
18665 (when org-agenda-skip-unavailable-files
18666 (setq files (delq nil
18667 (mapcar (function
18668 (lambda (file)
18669 (and (file-readable-p file) file)))
18670 files))))
18671 (when (or (eq archives t)
18672 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18673 (setq files (org-add-archive-files files)))
18674 files))
18676 (defun org-agenda-file-p (&optional file)
18677 "Return non-nil, if FILE is an agenda file.
18678 If FILE is omitted, use the file associated with the current
18679 buffer."
18680 (let ((fname (or file (buffer-file-name))))
18681 (and fname
18682 (member (file-truename fname)
18683 (mapcar #'file-truename (org-agenda-files t))))))
18685 (defun org-edit-agenda-file-list ()
18686 "Edit the list of agenda files.
18687 Depending on setup, this either uses customize to edit the variable
18688 `org-agenda-files', or it visits the file that is holding the list. In the
18689 latter case, the buffer is set up in a way that saving it automatically kills
18690 the buffer and restores the previous window configuration."
18691 (interactive)
18692 (if (stringp org-agenda-files)
18693 (let ((cw (current-window-configuration)))
18694 (find-file org-agenda-files)
18695 (setq-local org-window-configuration cw)
18696 (add-hook 'after-save-hook
18697 (lambda ()
18698 (set-window-configuration
18699 (prog1 org-window-configuration
18700 (kill-buffer (current-buffer))))
18701 (org-install-agenda-files-menu)
18702 (message "New agenda file list installed"))
18703 nil 'local)
18704 (message "%s" (substitute-command-keys
18705 "Edit list and finish with \\[save-buffer]")))
18706 (customize-variable 'org-agenda-files)))
18708 (defun org-store-new-agenda-file-list (list)
18709 "Set new value for the agenda file list and save it correctly."
18710 (if (stringp org-agenda-files)
18711 (let ((fe (org-read-agenda-file-list t)) b u)
18712 (while (setq b (find-buffer-visiting org-agenda-files))
18713 (kill-buffer b))
18714 (with-temp-file org-agenda-files
18715 (insert
18716 (mapconcat
18717 (lambda (f) ;; Keep un-expanded entries.
18718 (if (setq u (assoc f fe))
18719 (cdr u)
18721 list "\n")
18722 "\n")))
18723 (let ((org-mode-hook nil) (org-inhibit-startup t)
18724 (org-insert-mode-line-in-empty-file nil))
18725 (setq org-agenda-files list)
18726 (customize-save-variable 'org-agenda-files org-agenda-files))))
18728 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18729 "Read the list of agenda files from a file.
18730 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18731 filenames, used by `org-store-new-agenda-file-list' to write back
18732 un-expanded file names."
18733 (when (file-directory-p org-agenda-files)
18734 (error "`org-agenda-files' cannot be a single directory"))
18735 (when (stringp org-agenda-files)
18736 (with-temp-buffer
18737 (insert-file-contents org-agenda-files)
18738 (mapcar
18739 (lambda (f)
18740 (let ((e (expand-file-name (substitute-in-file-name f)
18741 org-directory)))
18742 (if pair-with-expansion
18743 (cons e f)
18744 e)))
18745 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18747 ;;;###autoload
18748 (defun org-cycle-agenda-files ()
18749 "Cycle through the files in `org-agenda-files'.
18750 If the current buffer visits an agenda file, find the next one in the list.
18751 If the current buffer does not, find the first agenda file."
18752 (interactive)
18753 (let* ((fs (or (org-agenda-files t)
18754 (user-error "No agenda files")))
18755 (files (copy-sequence fs))
18756 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18757 file)
18758 (when tcf
18759 (while (and (setq file (pop files))
18760 (not (equal (file-truename file) tcf)))))
18761 (find-file (car (or files fs)))
18762 (when (buffer-base-buffer) (pop-to-buffer-same-window (buffer-base-buffer)))))
18764 (defun org-agenda-file-to-front (&optional to-end)
18765 "Move/add the current file to the top of the agenda file list.
18766 If the file is not present in the list, it is added to the front. If it is
18767 present, it is moved there. With optional argument TO-END, add/move to the
18768 end of the list."
18769 (interactive "P")
18770 (let ((org-agenda-skip-unavailable-files nil)
18771 (file-alist (mapcar (lambda (x)
18772 (cons (file-truename x) x))
18773 (org-agenda-files t)))
18774 (ctf (file-truename
18775 (or buffer-file-name
18776 (user-error "Please save the current buffer to a file"))))
18777 x had)
18778 (setq x (assoc ctf file-alist) had x)
18780 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18781 (if to-end
18782 (setq file-alist (append (delq x file-alist) (list x)))
18783 (setq file-alist (cons x (delq x file-alist))))
18784 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18785 (org-install-agenda-files-menu)
18786 (message "File %s to %s of agenda file list"
18787 (if had "moved" "added") (if to-end "end" "front"))))
18789 (defun org-remove-file (&optional file)
18790 "Remove current file from the list of files in variable `org-agenda-files'.
18791 These are the files which are being checked for agenda entries.
18792 Optional argument FILE means use this file instead of the current."
18793 (interactive)
18794 (let* ((org-agenda-skip-unavailable-files nil)
18795 (file (or file buffer-file-name
18796 (user-error "Current buffer does not visit a file")))
18797 (true-file (file-truename file))
18798 (afile (abbreviate-file-name file))
18799 (files (delq nil (mapcar
18800 (lambda (x)
18801 (unless (equal true-file
18802 (file-truename x))
18804 (org-agenda-files t)))))
18805 (if (not (= (length files) (length (org-agenda-files t))))
18806 (progn
18807 (org-store-new-agenda-file-list files)
18808 (org-install-agenda-files-menu)
18809 (message "Removed from Org Agenda list: %s" afile))
18810 (message "File was not in list: %s (not removed)" afile))))
18812 (defun org-file-menu-entry (file)
18813 (vector file (list 'find-file file) t))
18815 (defun org-check-agenda-file (file)
18816 "Make sure FILE exists. If not, ask user what to do."
18817 (unless (file-exists-p file)
18818 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18819 (abbreviate-file-name file))
18820 (let ((r (downcase (read-char-exclusive))))
18821 (cond
18822 ((equal r ?r)
18823 (org-remove-file file)
18824 (throw 'nextfile t))
18825 (t (user-error "Abort"))))))
18827 (defun org-get-agenda-file-buffer (file)
18828 "Get an agenda buffer visiting FILE.
18829 If the buffer needs to be created, add it to the list of buffers
18830 which might be released later."
18831 (let ((buf (org-find-base-buffer-visiting file)))
18832 (if buf
18833 buf ; just return it
18834 ;; Make a new buffer and remember it
18835 (setq buf (find-file-noselect file))
18836 (when buf (push buf org-agenda-new-buffers))
18837 buf)))
18839 (defun org-release-buffers (blist)
18840 "Release all buffers in list, asking the user for confirmation when needed.
18841 When a buffer is unmodified, it is just killed. When modified, it is saved
18842 \(if the user agrees) and then killed."
18843 (let (file)
18844 (dolist (buf blist)
18845 (setq file (buffer-file-name buf))
18846 (when (and (buffer-modified-p buf)
18847 file
18848 (y-or-n-p (format "Save file %s? " file)))
18849 (with-current-buffer buf (save-buffer)))
18850 (kill-buffer buf))))
18852 (defun org-agenda-prepare-buffers (files)
18853 "Create buffers for all agenda files, protect archived trees and comments."
18854 (interactive)
18855 (let ((pa '(:org-archived t))
18856 (pc '(:org-comment t))
18857 (pall '(:org-archived t :org-comment t))
18858 (inhibit-read-only t)
18859 (org-inhibit-startup org-agenda-inhibit-startup)
18860 (rea (concat ":" org-archive-tag ":"))
18861 re pos)
18862 (setq org-tag-alist-for-agenda nil
18863 org-tag-groups-alist-for-agenda nil)
18864 (save-excursion
18865 (save-restriction
18866 (dolist (file files)
18867 (catch 'nextfile
18868 (if (bufferp file)
18869 (set-buffer file)
18870 (org-check-agenda-file file)
18871 (set-buffer (org-get-agenda-file-buffer file)))
18872 (widen)
18873 (org-set-regexps-and-options 'tags-only)
18874 (setq pos (point))
18875 (or (memq 'category org-agenda-ignore-properties)
18876 (org-refresh-category-properties))
18877 (or (memq 'stats org-agenda-ignore-properties)
18878 (org-refresh-stats-properties))
18879 (or (memq 'effort org-agenda-ignore-properties)
18880 (org-refresh-effort-properties))
18881 (or (memq 'appt org-agenda-ignore-properties)
18882 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18883 (setq org-todo-keywords-for-agenda
18884 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18885 (setq org-done-keywords-for-agenda
18886 (append org-done-keywords-for-agenda org-done-keywords))
18887 (setq org-todo-keyword-alist-for-agenda
18888 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18889 (setq org-tag-alist-for-agenda
18890 (org-uniquify
18891 (append org-tag-alist-for-agenda
18892 org-current-tag-alist)))
18893 ;; Merge current file's tag groups into global
18894 ;; `org-tag-groups-alist-for-agenda'.
18895 (when org-group-tags
18896 (dolist (alist org-tag-groups-alist)
18897 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18898 (if old
18899 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18900 (push alist org-tag-groups-alist-for-agenda)))))
18901 (org-with-silent-modifications
18902 (save-excursion
18903 (remove-text-properties (point-min) (point-max) pall)
18904 (when org-agenda-skip-archived-trees
18905 (goto-char (point-min))
18906 (while (re-search-forward rea nil t)
18907 (when (org-at-heading-p t)
18908 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18909 (goto-char (point-min))
18910 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18911 (while (re-search-forward re nil t)
18912 (when (save-match-data (org-in-commented-heading-p t))
18913 (add-text-properties
18914 (match-beginning 0) (org-end-of-subtree t) pc)))))
18915 (goto-char pos)))))
18916 (setq org-todo-keywords-for-agenda
18917 (org-uniquify org-todo-keywords-for-agenda))
18918 (setq org-todo-keyword-alist-for-agenda
18919 (org-uniquify org-todo-keyword-alist-for-agenda))))
18922 ;;;; CDLaTeX minor mode
18924 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18925 "Keymap for the minor `org-cdlatex-mode'.")
18927 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18928 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18929 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18930 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18931 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18933 (defvar org-cdlatex-texmathp-advice-is-done nil
18934 "Flag remembering if we have applied the advice to texmathp already.")
18936 (define-minor-mode org-cdlatex-mode
18937 "Toggle the minor `org-cdlatex-mode'.
18938 This mode supports entering LaTeX environment and math in LaTeX fragments
18939 in Org-mode.
18940 \\{org-cdlatex-mode-map}"
18941 nil " OCDL" nil
18942 (when org-cdlatex-mode
18943 (require 'cdlatex)
18944 (run-hooks 'cdlatex-mode-hook)
18945 (cdlatex-compute-tables))
18946 (unless org-cdlatex-texmathp-advice-is-done
18947 (setq org-cdlatex-texmathp-advice-is-done t)
18948 (defadvice texmathp (around org-math-always-on activate)
18949 "Always return t in org-mode buffers.
18950 This is because we want to insert math symbols without dollars even outside
18951 the LaTeX math segments. If Orgmode thinks that point is actually inside
18952 an embedded LaTeX fragment, let texmathp do its job.
18953 \\[org-cdlatex-mode-map]"
18954 (interactive)
18955 (let (p)
18956 (cond
18957 ((not (derived-mode-p 'org-mode)) ad-do-it)
18958 ((eq this-command 'cdlatex-math-symbol)
18959 (setq ad-return-value t
18960 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18962 (let ((p (org-inside-LaTeX-fragment-p)))
18963 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18964 (setq ad-return-value t
18965 texmathp-why '("Org-mode embedded math" . 0))
18966 (when p ad-do-it)))))))))
18968 (defun turn-on-org-cdlatex ()
18969 "Unconditionally turn on `org-cdlatex-mode'."
18970 (org-cdlatex-mode 1))
18972 (defun org-try-cdlatex-tab ()
18973 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18974 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18975 - inside a LaTeX fragment, or
18976 - after the first word in a line, where an abbreviation expansion could
18977 insert a LaTeX environment."
18978 (when org-cdlatex-mode
18979 (cond
18980 ;; Before any word on the line: No expansion possible.
18981 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18982 ;; Just after first word on the line: Expand it. Make sure it
18983 ;; cannot happen on headlines, though.
18984 ((save-excursion
18985 (skip-chars-backward "a-zA-Z0-9*")
18986 (skip-chars-backward " \t")
18987 (and (bolp) (not (org-at-heading-p))))
18988 (cdlatex-tab) t)
18989 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18991 (defun org-cdlatex-underscore-caret (&optional _arg)
18992 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18993 Revert to the normal definition outside of these fragments."
18994 (interactive "P")
18995 (if (org-inside-LaTeX-fragment-p)
18996 (call-interactively 'cdlatex-sub-superscript)
18997 (let (org-cdlatex-mode)
18998 (call-interactively (key-binding (vector last-input-event))))))
19000 (defun org-cdlatex-math-modify (&optional _arg)
19001 "Execute `cdlatex-math-modify' in LaTeX fragments.
19002 Revert to the normal definition outside of these fragments."
19003 (interactive "P")
19004 (if (org-inside-LaTeX-fragment-p)
19005 (call-interactively 'cdlatex-math-modify)
19006 (let (org-cdlatex-mode)
19007 (call-interactively (key-binding (vector last-input-event))))))
19009 (defun org-cdlatex-environment-indent (&optional environment item)
19010 "Execute `cdlatex-environment' and indent the inserted environment.
19012 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
19014 The inserted environment is indented to current indentation
19015 unless point is at the beginning of the line, in which the
19016 environment remains unintended."
19017 (interactive)
19018 ;; cdlatex-environment always return nil. Therefore, capture output
19019 ;; first and determine if an environment was selected.
19020 (let* ((beg (point-marker))
19021 (end (copy-marker (point) t))
19022 (inserted (progn
19023 (ignore-errors (cdlatex-environment environment item))
19024 (< beg end)))
19025 ;; Figure out how many lines to move forward after the
19026 ;; environment has been inserted.
19027 (lines (when inserted
19028 (save-excursion
19029 (- (cl-loop while (< beg (point))
19030 with x = 0
19031 do (forward-line -1)
19032 (cl-incf x)
19033 finally return x)
19034 (if (progn (goto-char beg)
19035 (and (progn (skip-chars-forward " \t") (eolp))
19036 (progn (skip-chars-backward " \t") (bolp))))
19037 1 0)))))
19038 (env (org-trim (delete-and-extract-region beg end))))
19039 (when inserted
19040 ;; Get indentation of next line unless at column 0.
19041 (let ((ind (if (bolp) 0
19042 (save-excursion
19043 (org-return-indent)
19044 (prog1 (org-get-indentation)
19045 (when (progn (skip-chars-forward " \t") (eolp))
19046 (delete-region beg (point)))))))
19047 (bol (progn (skip-chars-backward " \t") (bolp))))
19048 ;; Insert a newline before environment unless at column zero
19049 ;; to "escape" the current line. Insert a newline if
19050 ;; something is one the same line as \end{ENVIRONMENT}.
19051 (insert
19052 (concat (unless bol "\n") env
19053 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
19054 (unless (zerop ind)
19055 (save-excursion
19056 (goto-char beg)
19057 (while (< (point) end)
19058 (unless (eolp) (indent-line-to ind))
19059 (forward-line))))
19060 (goto-char beg)
19061 (forward-line lines)
19062 (indent-line-to ind)))
19063 (set-marker beg nil)
19064 (set-marker end nil)))
19067 ;;;; LaTeX fragments
19069 (defun org-inside-LaTeX-fragment-p ()
19070 "Test if point is inside a LaTeX fragment.
19071 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19072 sequence appearing also before point.
19073 Even though the matchers for math are configurable, this function assumes
19074 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19075 delimiters are skipped when they have been removed by customization.
19076 The return value is nil, or a cons cell with the delimiter and the
19077 position of this delimiter.
19079 This function does a reasonably good job, but can locally be fooled by
19080 for example currency specifications. For example it will assume being in
19081 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19082 fragments that are properly closed, but during editing, we have to live
19083 with the uncertainty caused by missing closing delimiters. This function
19084 looks only before point, not after."
19085 (catch 'exit
19086 (let ((pos (point))
19087 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19088 (lim (progn
19089 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19090 (point)))
19091 dd-on str (start 0) m re)
19092 (goto-char pos)
19093 (when dodollar
19094 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19095 re (nth 1 (assoc "$" org-latex-regexps)))
19096 (while (string-match re str start)
19097 (cond
19098 ((= (match-end 0) (length str))
19099 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19100 ((= (match-end 0) (- (length str) 5))
19101 (throw 'exit nil))
19102 (t (setq start (match-end 0))))))
19103 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19104 (goto-char pos)
19105 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19106 (and (match-beginning 2) (throw 'exit nil))
19107 ;; count $$
19108 (while (re-search-backward "\\$\\$" lim t)
19109 (setq dd-on (not dd-on)))
19110 (goto-char pos)
19111 (when dd-on (cons "$$" m))))))
19113 (defun org-inside-latex-macro-p ()
19114 "Is point inside a LaTeX macro or its arguments?"
19115 (save-match-data
19116 (org-in-regexp
19117 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19119 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19120 "Build an overlay between BEG and END using IMAGE file.
19121 Argument IMAGETYPE is the extension of the displayed image,
19122 as a string. It defaults to \"png\"."
19123 (let ((ov (make-overlay beg end))
19124 (imagetype (or (intern imagetype) 'png)))
19125 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19126 (overlay-put ov 'evaporate t)
19127 (overlay-put ov
19128 'modification-hooks
19129 (list (lambda (o _flag _beg _end &optional _l)
19130 (delete-overlay o))))
19131 (overlay-put ov
19132 'display
19133 (list 'image :type imagetype :file image :ascent 'center))))
19135 (defun org--list-latex-overlays (&optional beg end)
19136 "List all Org LaTeX overlays in current buffer.
19137 Limit to overlays between BEG and END when those are provided."
19138 (cl-remove-if-not
19139 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19140 (overlays-in (or beg (point-min)) (or end (point-max)))))
19142 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19143 "Remove all overlays with LaTeX fragment images in current buffer.
19144 When optional arguments BEG and END are non-nil, remove all
19145 overlays between them instead. Return a non-nil value when some
19146 overlays were removed, nil otherwise."
19147 (let ((overlays (org--list-latex-overlays beg end)))
19148 (mapc #'delete-overlay overlays)
19149 overlays))
19151 (defun org-toggle-latex-fragment (&optional arg)
19152 "Preview the LaTeX fragment at point, or all locally or globally.
19154 If the cursor is on a LaTeX fragment, create the image and overlay
19155 it over the source code, if there is none. Remove it otherwise.
19156 If there is no fragment at point, display all fragments in the
19157 current section.
19159 With prefix ARG, preview or clear image for all fragments in the
19160 current subtree or in the whole buffer when used before the first
19161 headline. With a double prefix ARG \\[universal-argument] \
19162 \\[universal-argument] preview or clear images
19163 for all fragments in the buffer."
19164 (interactive "P")
19165 (when (display-graphic-p)
19166 (catch 'exit
19167 (save-excursion
19168 (let (beg end msg)
19169 (cond
19170 ((or (equal arg '(16))
19171 (and (equal arg '(4))
19172 (org-with-limited-levels (org-before-first-heading-p))))
19173 (if (org-remove-latex-fragment-image-overlays)
19174 (progn (message "LaTeX fragments images removed from buffer")
19175 (throw 'exit nil))
19176 (setq msg "Creating images for buffer...")))
19177 ((equal arg '(4))
19178 (org-with-limited-levels (org-back-to-heading t))
19179 (setq beg (point))
19180 (setq end (progn (org-end-of-subtree t) (point)))
19181 (if (org-remove-latex-fragment-image-overlays beg end)
19182 (progn
19183 (message "LaTeX fragment images removed from subtree")
19184 (throw 'exit nil))
19185 (setq msg "Creating images for subtree...")))
19186 ((let ((datum (org-element-context)))
19187 (when (memq (org-element-type datum)
19188 '(latex-environment latex-fragment))
19189 (setq beg (org-element-property :begin datum))
19190 (setq end (org-element-property :end datum))
19191 (if (org-remove-latex-fragment-image-overlays beg end)
19192 (progn (message "LaTeX fragment image removed")
19193 (throw 'exit nil))
19194 (setq msg "Creating image...")))))
19196 (org-with-limited-levels
19197 (setq beg (if (org-at-heading-p) (line-beginning-position)
19198 (outline-previous-heading)
19199 (point)))
19200 (setq end (progn (outline-next-heading) (point)))
19201 (if (org-remove-latex-fragment-image-overlays beg end)
19202 (progn
19203 (message "LaTeX fragment images removed from section")
19204 (throw 'exit nil))
19205 (setq msg "Creating images for section...")))))
19206 (let ((file (buffer-file-name (buffer-base-buffer))))
19207 (org-format-latex
19208 (concat org-preview-latex-image-directory "org-ltximg")
19209 beg end
19210 ;; Emacs cannot overlay images from remote hosts. Create
19211 ;; it in `temporary-file-directory' instead.
19212 (if (or (not file) (file-remote-p file))
19213 temporary-file-directory
19214 default-directory)
19215 'overlays msg 'forbuffer org-preview-latex-default-process))
19216 (message (concat msg "done")))))))
19218 (defun org-format-latex
19219 (prefix &optional beg end dir overlays msg forbuffer processing-type)
19220 "Replace LaTeX fragments with links to an image.
19222 The function takes care of creating the replacement image.
19224 Only consider fragments between BEG and END when those are
19225 provided.
19227 When optional argument OVERLAYS is non-nil, display the image on
19228 top of the fragment instead of replacing it.
19230 PROCESSING-TYPE is the conversion method to use, as a symbol.
19232 Some of the options can be changed using the variable
19233 `org-format-latex-options', which see."
19234 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19235 (unless (eq processing-type 'verbatim)
19236 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19237 (cnt 0)
19238 checkdir-flag)
19239 (goto-char (or beg (point-min)))
19240 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19241 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19242 (overlay-recenter (or end (point-max))))
19243 (while (re-search-forward math-regexp end t)
19244 (unless (and overlays
19245 (eq (get-char-property (point) 'org-overlay-type)
19246 'org-latex-overlay))
19247 (let* ((context (org-element-context))
19248 (type (org-element-type context)))
19249 (when (memq type '(latex-environment latex-fragment))
19250 (let ((block-type (eq type 'latex-environment))
19251 (value (org-element-property :value context))
19252 (beg (org-element-property :begin context))
19253 (end (save-excursion
19254 (goto-char (org-element-property :end context))
19255 (skip-chars-backward " \r\t\n")
19256 (point))))
19257 (cond
19258 ((eq processing-type 'mathjax)
19259 ;; Prepare for MathJax processing.
19260 (if (not (string-match "\\`\\$\\$?" value))
19261 (goto-char end)
19262 (delete-region beg end)
19263 (if (string= (match-string 0 value) "$$")
19264 (insert "\\[" (substring value 2 -2) "\\]")
19265 (insert "\\(" (substring value 1 -1) "\\)"))))
19266 ((assq processing-type org-preview-latex-process-alist)
19267 ;; Process to an image.
19268 (cl-incf cnt)
19269 (goto-char beg)
19270 (let* ((processing-info
19271 (cdr (assq processing-type org-preview-latex-process-alist)))
19272 (face (face-at-point))
19273 ;; Get the colors from the face at point.
19275 (let ((color (plist-get org-format-latex-options
19276 :foreground)))
19277 (if (and forbuffer (eq color 'auto))
19278 (face-attribute face :foreground nil 'default)
19279 color)))
19281 (let ((color (plist-get org-format-latex-options
19282 :background)))
19283 (if (and forbuffer (eq color 'auto))
19284 (face-attribute face :background nil 'default)
19285 color)))
19286 (hash (sha1 (prin1-to-string
19287 (list org-format-latex-header
19288 org-latex-default-packages-alist
19289 org-latex-packages-alist
19290 org-format-latex-options
19291 forbuffer value fg bg))))
19292 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19293 (absprefix (expand-file-name prefix dir))
19294 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19295 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19296 (sep (and block-type "\n\n"))
19297 (link (concat sep "[[file:" linkfile "]]" sep))
19298 (options
19299 (org-combine-plists
19300 org-format-latex-options
19301 `(:foreground ,fg :background ,bg))))
19302 (when msg (message msg cnt))
19303 (unless checkdir-flag ; Ensure the directory exists.
19304 (setq checkdir-flag t)
19305 (let ((todir (file-name-directory absprefix)))
19306 (unless (file-directory-p todir)
19307 (make-directory todir t))))
19308 (unless (file-exists-p movefile)
19309 (org-create-formula-image
19310 value movefile options forbuffer processing-type))
19311 (if overlays
19312 (progn
19313 (dolist (o (overlays-in beg end))
19314 (when (eq (overlay-get o 'org-overlay-type)
19315 'org-latex-overlay)
19316 (delete-overlay o)))
19317 (org--format-latex-make-overlay beg end movefile imagetype)
19318 (goto-char end))
19319 (delete-region beg end)
19320 (insert
19321 (org-add-props link
19322 (list 'org-latex-src
19323 (replace-regexp-in-string "\"" "" value)
19324 'org-latex-src-embed-type
19325 (if block-type 'paragraph 'character)))))))
19326 ((eq processing-type 'mathml)
19327 ;; Process to MathML.
19328 (unless (org-format-latex-mathml-available-p)
19329 (user-error "LaTeX to MathML converter not configured"))
19330 (cl-incf cnt)
19331 (when msg (message msg cnt))
19332 (goto-char beg)
19333 (delete-region beg end)
19334 (insert (org-format-latex-as-mathml
19335 value block-type prefix dir)))
19337 (error "Unknown conversion process %s for LaTeX fragments"
19338 processing-type)))))))))))
19340 (defun org-create-math-formula (latex-frag &optional mathml-file)
19341 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19342 Use `org-latex-to-mathml-convert-command'. If the conversion is
19343 sucessful, return the portion between \"<math...> </math>\"
19344 elements otherwise return nil. When MATHML-FILE is specified,
19345 write the results in to that file. When invoked as an
19346 interactive command, prompt for LATEX-FRAG, with initial value
19347 set to the current active region and echo the results for user
19348 inspection."
19349 (interactive (list (let ((frag (when (org-region-active-p)
19350 (buffer-substring-no-properties
19351 (region-beginning) (region-end)))))
19352 (read-string "LaTeX Fragment: " frag nil frag))))
19353 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19354 (let* ((tmp-in-file
19355 (let ((file (file-relative-name
19356 (make-temp-name (expand-file-name "ltxmathml-in")))))
19357 (write-region latex-frag nil file)
19358 file))
19359 (tmp-out-file (file-relative-name
19360 (make-temp-name (expand-file-name "ltxmathml-out"))))
19361 (cmd (format-spec
19362 org-latex-to-mathml-convert-command
19363 `((?j . ,(and org-latex-to-mathml-jar-file
19364 (shell-quote-argument
19365 (expand-file-name
19366 org-latex-to-mathml-jar-file))))
19367 (?I . ,(shell-quote-argument tmp-in-file))
19368 (?i . ,latex-frag)
19369 (?o . ,(shell-quote-argument tmp-out-file)))))
19370 mathml shell-command-output)
19371 (when (called-interactively-p 'any)
19372 (unless (org-format-latex-mathml-available-p)
19373 (user-error "LaTeX to MathML converter not configured")))
19374 (message "Running %s" cmd)
19375 (setq shell-command-output (shell-command-to-string cmd))
19376 (setq mathml
19377 (when (file-readable-p tmp-out-file)
19378 (with-current-buffer (find-file-noselect tmp-out-file t)
19379 (goto-char (point-min))
19380 (when (re-search-forward
19381 (concat
19382 (regexp-quote
19383 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19384 "[^>]*?>"
19385 "\\(.\\|\n\\)*"
19386 "</math>")
19387 nil t)
19388 (prog1 (match-string 0) (kill-buffer))))))
19389 (cond
19390 (mathml
19391 (setq mathml
19392 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19393 (when mathml-file
19394 (write-region mathml nil mathml-file))
19395 (when (called-interactively-p 'any)
19396 (message mathml)))
19397 ((message "LaTeX to MathML conversion failed")
19398 (message shell-command-output)))
19399 (delete-file tmp-in-file)
19400 (when (file-exists-p tmp-out-file)
19401 (delete-file tmp-out-file))
19402 mathml))
19404 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19405 prefix &optional dir)
19406 "Use `org-create-math-formula' but check local cache first."
19407 (let* ((absprefix (expand-file-name prefix dir))
19408 (print-length nil) (print-level nil)
19409 (formula-id (concat
19410 "formula-"
19411 (sha1
19412 (prin1-to-string
19413 (list latex-frag
19414 org-latex-to-mathml-convert-command)))))
19415 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19416 (formula-cache-dir (file-name-directory formula-cache)))
19418 (unless (file-directory-p formula-cache-dir)
19419 (make-directory formula-cache-dir t))
19421 (unless (file-exists-p formula-cache)
19422 (org-create-math-formula latex-frag formula-cache))
19424 (if (file-exists-p formula-cache)
19425 ;; Successful conversion. Return the link to MathML file.
19426 (org-add-props
19427 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19428 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19429 'org-latex-src-embed-type (if latex-frag-type
19430 'paragraph 'character)))
19431 ;; Failed conversion. Return the LaTeX fragment verbatim
19432 latex-frag)))
19434 (declare-function org-export-get-backend "ox" (name))
19435 (declare-function org-export--get-global-options "ox" (&optional backend))
19436 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19437 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19438 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19439 (defun org-create-formula--latex-header ()
19440 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19441 (let ((info (org-combine-plists (org-export--get-global-options
19442 (org-export-get-backend 'latex))
19443 (org-export--get-inbuffer-options
19444 (org-export-get-backend 'latex)))))
19445 (org-latex-guess-babel-language
19446 (org-latex-guess-inputenc
19447 (org-splice-latex-header
19448 org-format-latex-header
19449 org-latex-default-packages-alist
19450 org-latex-packages-alist t
19451 (plist-get info :latex-header)))
19452 info)))
19454 (defun org--get-display-dpi ()
19455 "Get the DPI of the display.
19457 Assumes that the display has the same pixel width in the
19458 horizontal and vertical directions."
19459 (if (display-graphic-p)
19460 (round (/ (display-pixel-height)
19461 (/ (display-mm-height) 25.4)))
19462 (error "Attempt to calculate the dpi of a non-graphic display")))
19464 (defun org-create-formula-image
19465 (string tofile options buffer &optional processing-type)
19466 "Create an image from LaTeX source using external processes.
19468 The LaTeX STRING is saved to a temporary LaTeX file, then
19469 converted to an image file by process PROCESSING-TYPE defined in
19470 `org-preview-latex-process-alist'. A nil value defaults to
19471 `org-preview-latex-default-process'.
19473 The generated image file is eventually moved to TOFILE.
19475 The OPTIONS argument controls the size, foreground color and
19476 background color of the generated image.
19478 When BUFFER non-nil, this function is used for LaTeX previewing.
19479 Otherwise, it is used to deal with LaTeX snippets showed in
19480 a HTML file."
19481 (let* ((processing-type (or processing-type
19482 org-preview-latex-default-process))
19483 (processing-info
19484 (cdr (assq processing-type org-preview-latex-process-alist)))
19485 (programs (plist-get processing-info :programs))
19486 (error-message (or (plist-get processing-info :message) ""))
19487 (use-xcolor (plist-get processing-info :use-xcolor))
19488 (image-input-type (plist-get processing-info :image-input-type))
19489 (image-output-type (plist-get processing-info :image-output-type))
19490 (post-clean (or (plist-get processing-info :post-clean)
19491 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19492 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19493 (latex-header (or (plist-get processing-info :latex-header)
19494 (org-create-formula--latex-header)))
19495 (latex-compiler (plist-get processing-info :latex-compiler))
19496 (image-converter (plist-get processing-info :image-converter))
19497 (tmpdir temporary-file-directory)
19498 (texfilebase (make-temp-name
19499 (expand-file-name "orgtex" tmpdir)))
19500 (texfile (concat texfilebase ".tex"))
19501 (font-height (face-attribute 'default :height nil))
19502 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19503 '(1.0 . 1.0)))
19504 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19505 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19506 (dpi (* scale (floor (if buffer font-height 140.0))))
19507 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19508 "Black"))
19509 (bg (or (plist-get options (if buffer :background :html-background))
19510 "Transparent"))
19511 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19512 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19513 (dolist (program programs)
19514 (org-check-external-command program error-message))
19515 (if use-xcolor
19516 (progn (if (eq fg 'default)
19517 (setq fg (org-latex-color :foreground))
19518 (setq fg (org-latex-color-format fg)))
19519 (if (eq bg 'default)
19520 (setq bg (org-latex-color :background))
19521 (setq bg (org-latex-color-format
19522 (if (string= bg "Transparent") "white" bg))))
19523 (with-temp-file texfile
19524 (insert latex-header)
19525 (insert "\n\\begin{document}\n"
19526 "\\definecolor{fg}{rgb}{" fg "}\n"
19527 "\\definecolor{bg}{rgb}{" bg "}\n"
19528 "\n\\pagecolor{bg}\n"
19529 "\n{\\color{fg}\n"
19530 string
19531 "\n}\n"
19532 "\n\\end{document}\n")))
19533 (if (eq fg 'default)
19534 (setq fg (org-dvipng-color :foreground))
19535 (unless (string= fg "Transparent")
19536 (setq fg (org-dvipng-color-format fg))))
19537 (if (eq bg 'default)
19538 (setq bg (org-dvipng-color :background))
19539 (unless (string= bg "Transparent")
19540 (setq bg (org-dvipng-color-format bg))))
19541 (with-temp-file texfile
19542 (insert latex-header)
19543 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19545 (let* ((err-msg (format "Please adjust '%s' part of \
19546 `org-preview-latex-process-alist'."
19547 processing-type))
19548 (image-input-file
19549 (org-compile-file
19550 texfile latex-compiler image-input-type err-msg log-buf))
19551 (image-output-file
19552 (org-compile-file
19553 image-input-file image-converter image-output-type err-msg log-buf
19554 `((?F . ,(shell-quote-argument fg))
19555 (?B . ,(shell-quote-argument bg))
19556 (?D . ,(shell-quote-argument (format "%s" dpi)))
19557 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19558 (copy-file image-output-file tofile 'replace)
19559 (dolist (e post-clean)
19560 (when (file-exists-p (concat texfilebase e))
19561 (delete-file (concat texfilebase e))))
19562 image-output-file)))
19564 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19565 "Fill a LaTeX header template TPL.
19566 In the template, the following place holders will be recognized:
19568 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19569 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19570 [PACKAGES] \\usepackage statements for PKG
19571 [NO-PACKAGES] do not include PKG
19572 [EXTRA] the string EXTRA
19573 [NO-EXTRA] do not include EXTRA
19575 For backward compatibility, if both the positive and the negative place
19576 holder is missing, the positive one (without the \"NO-\") will be
19577 assumed to be present at the end of the template.
19578 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19579 EXTRA is a string.
19580 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19581 (let (rpl (end ""))
19582 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19583 (setq rpl (if (or (match-end 1) (not def-pkg))
19584 "" (org-latex-packages-to-string def-pkg snippets-p t))
19585 tpl (replace-match rpl t t tpl))
19586 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19588 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19589 (setq rpl (if (or (match-end 1) (not pkg))
19590 "" (org-latex-packages-to-string pkg snippets-p t))
19591 tpl (replace-match rpl t t tpl))
19592 (when pkg (setq end
19593 (concat end "\n"
19594 (org-latex-packages-to-string pkg snippets-p)))))
19596 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19597 (setq rpl (if (or (match-end 1) (not extra))
19598 "" (concat extra "\n"))
19599 tpl (replace-match rpl t t tpl))
19600 (when (and extra (string-match "\\S-" extra))
19601 (setq end (concat end "\n" extra))))
19603 (if (string-match "\\S-" end)
19604 (concat tpl "\n" end)
19605 tpl)))
19607 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19608 "Turn an alist of packages into a string with the \\usepackage macros."
19609 (setq pkg (mapconcat (lambda(p)
19610 (cond
19611 ((stringp p) p)
19612 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19613 (format "%% Package %s omitted" (cadr p)))
19614 ((equal "" (car p))
19615 (format "\\usepackage{%s}" (cadr p)))
19617 (format "\\usepackage[%s]{%s}"
19618 (car p) (cadr p)))))
19620 "\n"))
19621 (if newline (concat pkg "\n") pkg))
19623 (defun org-dvipng-color (attr)
19624 "Return a RGB color specification for dvipng."
19625 (apply #'format "rgb %s %s %s"
19626 (mapcar #'org-normalize-color
19627 (color-values (face-attribute 'default attr nil)))))
19629 (defun org-dvipng-color-format (color-name)
19630 "Convert COLOR-NAME to a RGB color value for dvipng."
19631 (apply 'format "rgb %s %s %s"
19632 (mapcar 'org-normalize-color
19633 (color-values color-name))))
19635 (defun org-latex-color (attr)
19636 "Return a RGB color for the LaTeX color package."
19637 (apply #'format "%s,%s,%s"
19638 (mapcar #'org-normalize-color
19639 (color-values (face-attribute 'default attr nil)))))
19641 (defun org-latex-color-format (color-name)
19642 "Convert COLOR-NAME to a RGB color value."
19643 (apply 'format "%s,%s,%s"
19644 (mapcar 'org-normalize-color
19645 (color-values color-name))))
19647 (defun org-normalize-color (value)
19648 "Return string to be used as color value for an RGB component."
19649 (format "%g" (/ value 65535.0)))
19653 ;; Image display
19655 (defvar-local org-inline-image-overlays nil)
19657 (defun org-toggle-inline-images (&optional include-linked)
19658 "Toggle the display of inline images.
19659 INCLUDE-LINKED is passed to `org-display-inline-images'."
19660 (interactive "P")
19661 (if org-inline-image-overlays
19662 (progn
19663 (org-remove-inline-images)
19664 (when (called-interactively-p 'interactive)
19665 (message "Inline image display turned off")))
19666 (org-display-inline-images include-linked)
19667 (when (called-interactively-p 'interactive)
19668 (message (if org-inline-image-overlays
19669 (format "%d images displayed inline"
19670 (length org-inline-image-overlays))
19671 "No images to display inline")))))
19673 (defun org-redisplay-inline-images ()
19674 "Refresh the display of inline images."
19675 (interactive)
19676 (if (not org-inline-image-overlays)
19677 (org-toggle-inline-images)
19678 (org-toggle-inline-images)
19679 (org-toggle-inline-images)))
19681 (defun org-display-inline-images (&optional include-linked refresh beg end)
19682 "Display inline images.
19684 An inline image is a link which follows either of these
19685 conventions:
19687 1. Its path is a file with an extension matching return value
19688 from `image-file-name-regexp' and it has no contents.
19690 2. Its description consists in a single link of the previous
19691 type.
19693 When optional argument INCLUDE-LINKED is non-nil, also links with
19694 a text description part will be inlined. This can be nice for
19695 a quick look at those images, but it does not reflect what
19696 exported files will look like.
19698 When optional argument REFRESH is non-nil, refresh existing
19699 images between BEG and END. This will create new image displays
19700 only if necessary. BEG and END default to the buffer
19701 boundaries."
19702 (interactive "P")
19703 (when (display-graphic-p)
19704 (unless refresh
19705 (org-remove-inline-images)
19706 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19707 (org-with-wide-buffer
19708 (goto-char (or beg (point-min)))
19709 (let ((case-fold-search t)
19710 (file-extension-re (image-file-name-regexp)))
19711 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19712 (let ((link (save-match-data (org-element-context))))
19713 ;; Check if we're at an inline image.
19714 (when (and (equal (org-element-property :type link) "file")
19715 (or include-linked
19716 (not (org-element-property :contents-begin link)))
19717 (let ((parent (org-element-property :parent link)))
19718 (or (not (eq (org-element-type parent) 'link))
19719 (not (cdr (org-element-contents parent)))))
19720 (string-match-p file-extension-re
19721 (org-element-property :path link)))
19722 (let ((file (expand-file-name
19723 (org-link-unescape
19724 (org-element-property :path link)))))
19725 (when (file-exists-p file)
19726 (let ((width
19727 ;; Apply `org-image-actual-width' specifications.
19728 (cond
19729 ((not (image-type-available-p 'imagemagick)) nil)
19730 ((eq org-image-actual-width t) nil)
19731 ((listp org-image-actual-width)
19733 ;; First try to find a width among
19734 ;; attributes associated to the paragraph
19735 ;; containing link.
19736 (let ((paragraph
19737 (let ((e link))
19738 (while (and (setq e (org-element-property
19739 :parent e))
19740 (not (eq (org-element-type e)
19741 'paragraph))))
19742 e)))
19743 (when paragraph
19744 (save-excursion
19745 (goto-char (org-element-property :begin paragraph))
19746 (when
19747 (re-search-forward
19748 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19749 (org-element-property
19750 :post-affiliated paragraph)
19752 (string-to-number (match-string 1))))))
19753 ;; Otherwise, fall-back to provided number.
19754 (car org-image-actual-width)))
19755 ((numberp org-image-actual-width)
19756 org-image-actual-width)))
19757 (old (get-char-property-and-overlay
19758 (org-element-property :begin link)
19759 'org-image-overlay)))
19760 (if (and (car-safe old) refresh)
19761 (image-refresh (overlay-get (cdr old) 'display))
19762 (let ((image (create-image file
19763 (and width 'imagemagick)
19765 :width width)))
19766 (when image
19767 (let* ((link
19768 ;; If inline image is the description
19769 ;; of another link, be sure to
19770 ;; consider the latter as the one to
19771 ;; apply the overlay on.
19772 (let ((parent
19773 (org-element-property :parent link)))
19774 (if (eq (org-element-type parent) 'link)
19775 parent
19776 link)))
19777 (ov (make-overlay
19778 (org-element-property :begin link)
19779 (progn
19780 (goto-char
19781 (org-element-property :end link))
19782 (skip-chars-backward " \t")
19783 (point)))))
19784 (overlay-put ov 'display image)
19785 (overlay-put ov 'face 'default)
19786 (overlay-put ov 'org-image-overlay t)
19787 (overlay-put
19788 ov 'modification-hooks
19789 (list 'org-display-inline-remove-overlay))
19790 (push ov org-inline-image-overlays)))))))))))))))
19792 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19793 "Remove inline-display overlay if a corresponding region is modified."
19794 (let ((inhibit-modification-hooks t))
19795 (when (and ov after)
19796 (delete ov org-inline-image-overlays)
19797 (delete-overlay ov))))
19799 (defun org-remove-inline-images ()
19800 "Remove inline display of images."
19801 (interactive)
19802 (mapc #'delete-overlay org-inline-image-overlays)
19803 (setq org-inline-image-overlays nil))
19805 ;;;; Key bindings
19807 ;; Outline functions from `outline-mode-prefix-map'
19808 ;; that can be remapped in Org:
19809 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19810 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19811 (define-key org-mode-map [remap outline-forward-same-level]
19812 'org-forward-heading-same-level)
19813 (define-key org-mode-map [remap outline-backward-same-level]
19814 'org-backward-heading-same-level)
19815 (define-key org-mode-map [remap outline-show-branches]
19816 'org-kill-note-or-show-branches)
19817 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19818 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19819 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19820 (define-key org-mode-map [remap outline-next-visible-heading]
19821 'org-next-visible-heading)
19822 (define-key org-mode-map [remap outline-previous-visible-heading]
19823 'org-previous-visible-heading)
19824 (define-key org-mode-map [remap show-children] 'org-show-children)
19826 ;; Outline functions from `outline-mode-prefix-map' that can not
19827 ;; be remapped in Org:
19829 ;; - the column "key binding" shows whether the Outline function is still
19830 ;; available in Org mode on the same key that it has been bound to in
19831 ;; Outline mode:
19832 ;; - "overridden": key used for a different functionality in Org mode
19833 ;; - else: key still bound to the same Outline function in Org mode
19835 ;; | Outline function | key binding | Org replacement |
19836 ;; |------------------------------------+-------------+--------------------------|
19837 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19838 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19839 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19840 ;; | `show-entry' | overridden | no replacement |
19841 ;; | `show-branches' | `C-c C-k' | still same function |
19842 ;; | `show-subtree' | overridden | visibility cycling |
19843 ;; | `show-all' | overridden | no replacement |
19844 ;; | `hide-subtree' | overridden | visibility cycling |
19845 ;; | `hide-body' | overridden | no replacement |
19846 ;; | `hide-entry' | overridden | visibility cycling |
19847 ;; | `hide-leaves' | overridden | no replacement |
19848 ;; | `hide-sublevels' | overridden | no replacement |
19849 ;; | `hide-other' | overridden | no replacement |
19851 ;; Make `C-c C-x' a prefix key
19852 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19854 ;; TAB key with modifiers
19855 (org-defkey org-mode-map "\C-i" 'org-cycle)
19856 (org-defkey org-mode-map [(tab)] 'org-cycle)
19857 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19858 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19859 ;; The following line is necessary under Suse GNU/Linux
19860 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19861 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19862 (define-key org-mode-map [backtab] 'org-shifttab)
19864 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19865 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19866 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19868 ;; Cursor keys with modifiers
19869 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19870 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19871 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19872 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19874 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19875 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19876 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19877 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19878 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19879 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19881 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19882 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19883 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19884 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19886 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19887 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19888 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19889 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19891 ;; Babel keys
19892 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19893 (dolist (pair org-babel-key-bindings)
19894 (define-key org-babel-map (car pair) (cdr pair)))
19896 ;;; Extra keys for tty access.
19897 ;; We only set them when really needed because otherwise the
19898 ;; menus don't show the simple keys
19900 (when (or org-use-extra-keys (not window-system))
19901 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19902 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19903 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19904 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19905 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19906 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19907 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19908 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19909 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19910 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19911 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19912 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19913 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19914 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19915 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19916 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19917 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19918 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19919 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19920 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19921 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19922 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19923 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19924 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19925 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19926 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19927 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19928 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19930 ;; All the other keys
19932 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19933 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19934 (if (boundp 'narrow-map)
19935 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19936 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19937 (if (boundp 'narrow-map)
19938 (org-defkey narrow-map "b" 'org-narrow-to-block)
19939 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19940 (if (boundp 'narrow-map)
19941 (org-defkey narrow-map "e" 'org-narrow-to-element)
19942 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19943 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19944 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19945 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19946 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19947 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19948 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19949 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19950 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19951 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19952 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19953 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19954 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19955 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19956 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19957 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19958 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19959 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19960 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19961 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19962 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19963 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19964 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19965 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19966 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19967 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19968 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19969 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19970 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19971 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19972 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19973 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19974 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19975 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19976 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19977 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19978 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19979 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19980 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19981 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19982 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19983 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19984 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19985 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19986 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19987 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19988 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19989 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19990 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19991 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19992 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19993 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19994 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19995 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19996 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19997 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19998 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19999 (org-defkey org-mode-map "\C-c^" 'org-sort)
20000 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
20001 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
20002 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
20003 (org-defkey org-mode-map [remap open-line] 'org-open-line)
20004 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
20005 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
20006 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
20007 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
20008 (org-defkey org-mode-map "\C-m" 'org-return)
20009 (org-defkey org-mode-map "\C-j" 'org-return-indent)
20010 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
20011 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
20012 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
20013 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
20014 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
20015 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
20016 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
20017 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
20018 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
20019 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
20020 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
20021 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
20022 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
20023 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
20024 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
20025 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
20026 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
20027 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
20028 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
20029 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
20030 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
20031 (org-defkey org-mode-map "\M-h" 'org-mark-element)
20032 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
20033 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
20035 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
20036 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
20037 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
20039 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
20040 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
20041 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
20042 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
20043 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
20044 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
20045 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
20046 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
20047 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
20048 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
20049 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20050 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20051 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20052 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20053 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20054 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20055 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20056 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20057 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20058 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20059 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20060 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20062 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20063 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20064 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20065 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20066 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20068 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20070 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20072 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20073 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20075 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20078 (defconst org-speed-commands-default
20080 ("Outline Navigation")
20081 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20082 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20083 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20084 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20085 ("F" . org-next-block)
20086 ("B" . org-previous-block)
20087 ("u" . (org-speed-move-safe 'outline-up-heading))
20088 ("j" . org-goto)
20089 ("g" . (org-refile t))
20090 ("Outline Visibility")
20091 ("c" . org-cycle)
20092 ("C" . org-shifttab)
20093 (" " . org-display-outline-path)
20094 ("s" . org-narrow-to-subtree)
20095 ("=" . org-columns)
20096 ("Outline Structure Editing")
20097 ("U" . org-metaup)
20098 ("D" . org-metadown)
20099 ("r" . org-metaright)
20100 ("l" . org-metaleft)
20101 ("R" . org-shiftmetaright)
20102 ("L" . org-shiftmetaleft)
20103 ("i" . (progn (forward-char 1) (call-interactively
20104 'org-insert-heading-respect-content)))
20105 ("^" . org-sort)
20106 ("w" . org-refile)
20107 ("a" . org-archive-subtree-default-with-confirmation)
20108 ("@" . org-mark-subtree)
20109 ("#" . org-toggle-comment)
20110 ("Clock Commands")
20111 ("I" . org-clock-in)
20112 ("O" . org-clock-out)
20113 ("Meta Data Editing")
20114 ("t" . org-todo)
20115 ("," . (org-priority))
20116 ("0" . (org-priority ?\ ))
20117 ("1" . (org-priority ?A))
20118 ("2" . (org-priority ?B))
20119 ("3" . (org-priority ?C))
20120 (":" . org-set-tags-command)
20121 ("e" . org-set-effort)
20122 ("E" . org-inc-effort)
20123 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20124 (org-entry-put (point) "APPT_WARNTIME" m)))
20125 ("Agenda Views etc")
20126 ("v" . org-agenda)
20127 ("/" . org-sparse-tree)
20128 ("Misc")
20129 ("o" . org-open-at-point)
20130 ("?" . org-speed-command-help)
20131 ("<" . (org-agenda-set-restriction-lock 'subtree))
20132 (">" . (org-agenda-remove-restriction-lock))
20134 "The default speed commands.")
20136 (defun org-print-speed-command (e)
20137 (if (> (length (car e)) 1)
20138 (progn
20139 (princ "\n")
20140 (princ (car e))
20141 (princ "\n")
20142 (princ (make-string (length (car e)) ?-))
20143 (princ "\n"))
20144 (princ (car e))
20145 (princ " ")
20146 (if (symbolp (cdr e))
20147 (princ (symbol-name (cdr e)))
20148 (prin1 (cdr e)))
20149 (princ "\n")))
20151 (defun org-speed-command-help ()
20152 "Show the available speed commands."
20153 (interactive)
20154 (if (not org-use-speed-commands)
20155 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20156 (with-output-to-temp-buffer "*Help*"
20157 (princ "User-defined Speed commands\n===========================\n")
20158 (mapc #'org-print-speed-command org-speed-commands-user)
20159 (princ "\n")
20160 (princ "Built-in Speed commands\n=======================\n")
20161 (mapc #'org-print-speed-command org-speed-commands-default))
20162 (with-current-buffer "*Help*"
20163 (setq truncate-lines t))))
20165 (defun org-speed-move-safe (cmd)
20166 "Execute CMD, but make sure that the cursor always ends up in a headline.
20167 If not, return to the original position and throw an error."
20168 (interactive)
20169 (let ((pos (point)))
20170 (call-interactively cmd)
20171 (unless (and (bolp) (org-at-heading-p))
20172 (goto-char pos)
20173 (error "Boundary reached while executing %s" cmd))))
20175 (defvar org-self-insert-command-undo-counter 0)
20177 (defvar org-table-auto-blank-field) ; defined in org-table.el
20178 (defvar org-speed-command nil)
20180 (defun org-speed-command-activate (keys)
20181 "Hook for activating single-letter speed commands.
20182 `org-speed-commands-default' specifies a minimal command set.
20183 Use `org-speed-commands-user' for further customization."
20184 (when (or (and (bolp) (looking-at org-outline-regexp))
20185 (and (functionp org-use-speed-commands)
20186 (funcall org-use-speed-commands)))
20187 (cdr (assoc keys (append org-speed-commands-user
20188 org-speed-commands-default)))))
20190 (defun org-babel-speed-command-activate (keys)
20191 "Hook for activating single-letter code block commands."
20192 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20193 (cdr (assoc keys org-babel-key-bindings))))
20195 (defcustom org-speed-command-hook
20196 '(org-speed-command-default-hook org-babel-speed-command-hook)
20197 "Hook for activating speed commands at strategic locations.
20198 Hook functions are called in sequence until a valid handler is
20199 found.
20201 Each hook takes a single argument, a user-pressed command key
20202 which is also a `self-insert-command' from the global map.
20204 Within the hook, examine the cursor position and the command key
20205 and return nil or a valid handler as appropriate. Handler could
20206 be one of an interactive command, a function, or a form.
20208 Set `org-use-speed-commands' to non-nil value to enable this
20209 hook. The default setting is `org-speed-command-activate'."
20210 :group 'org-structure
20211 :version "24.1"
20212 :type 'hook)
20214 (defun org-self-insert-command (N)
20215 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20216 If the cursor is in a table looking at whitespace, the whitespace is
20217 overwritten, and the table is not marked as requiring realignment."
20218 (interactive "p")
20219 (org-check-before-invisible-edit 'insert)
20220 (cond
20221 ((and org-use-speed-commands
20222 (let ((kv (this-command-keys-vector)))
20223 (setq org-speed-command
20224 (run-hook-with-args-until-success
20225 'org-speed-command-hook
20226 (make-string 1 (aref kv (1- (length kv))))))))
20227 (cond
20228 ((commandp org-speed-command)
20229 (setq this-command org-speed-command)
20230 (call-interactively org-speed-command))
20231 ((functionp org-speed-command)
20232 (funcall org-speed-command))
20233 ((and org-speed-command (listp org-speed-command))
20234 (eval org-speed-command))
20235 (t (let (org-use-speed-commands)
20236 (call-interactively 'org-self-insert-command)))))
20237 ((and
20238 (org-at-table-p)
20239 (progn
20240 ;; Check if we blank the field, and if that triggers align.
20241 (and (featurep 'org-table) org-table-auto-blank-field
20242 (memq last-command
20243 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20244 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20245 ;; Got extra space, this field does not determine
20246 ;; column width.
20247 (let (org-table-may-need-update) (org-table-blank-field))
20248 ;; No extra space, this field may determine column
20249 ;; width.
20250 (org-table-blank-field)))
20252 (eq N 1)
20253 (looking-at "[^|\n]* \\( \\)|"))
20254 ;; There is room for insertion without re-aligning the table.
20255 (delete-region (match-beginning 1) (match-end 1))
20256 (self-insert-command N))
20258 (setq org-table-may-need-update t)
20259 (self-insert-command N)
20260 (org-fix-tags-on-the-fly)
20261 (when org-self-insert-cluster-for-undo
20262 (if (not (eq last-command 'org-self-insert-command))
20263 (setq org-self-insert-command-undo-counter 1)
20264 (if (>= org-self-insert-command-undo-counter 20)
20265 (setq org-self-insert-command-undo-counter 1)
20266 (and (> org-self-insert-command-undo-counter 0)
20267 buffer-undo-list (listp buffer-undo-list)
20268 (not (cadr buffer-undo-list)) ; remove nil entry
20269 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20270 (setq org-self-insert-command-undo-counter
20271 (1+ org-self-insert-command-undo-counter))))))))
20273 (defun org-check-before-invisible-edit (kind)
20274 "Check is editing if kind KIND would be dangerous with invisible text around.
20275 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20276 ;; First, try to get out of here as quickly as possible, to reduce overhead
20277 (when (and org-catch-invisible-edits
20278 (or (not (boundp 'visible-mode)) (not visible-mode))
20279 (or (get-char-property (point) 'invisible)
20280 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20281 ;; OK, we need to take a closer look
20282 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20283 (invisible-before-point (unless (bobp) (get-char-property
20284 (1- (point)) 'invisible)))
20285 (border-and-ok-direction
20287 ;; Check if we are acting predictably before invisible text
20288 (and invisible-at-point (not invisible-before-point)
20289 (memq kind '(insert delete-backward)))
20290 ;; Check if we are acting predictably after invisible text
20291 ;; This works not well, and I have turned it off. It seems
20292 ;; better to always show and stop after invisible text.
20293 ;; (and (not invisible-at-point) invisible-before-point
20294 ;; (memq kind '(insert delete)))
20296 (when (or (memq invisible-at-point '(outline org-hide-block t))
20297 (memq invisible-before-point '(outline org-hide-block t)))
20298 (when (eq org-catch-invisible-edits 'error)
20299 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20300 (if (and org-custom-properties-overlays
20301 (y-or-n-p "Display invisible properties in this buffer? "))
20302 (org-toggle-custom-properties-visibility)
20303 ;; Make the area visible
20304 (save-excursion
20305 (when invisible-before-point
20306 (goto-char (previous-single-char-property-change
20307 (point) 'invisible)))
20308 (outline-show-subtree))
20309 (cond
20310 ((eq org-catch-invisible-edits 'show)
20311 ;; That's it, we do the edit after showing
20312 (message
20313 "Unfolding invisible region around point before editing")
20314 (sit-for 1))
20315 ((and (eq org-catch-invisible-edits 'smart)
20316 border-and-ok-direction)
20317 (message "Unfolding invisible region around point before editing"))
20319 ;; Don't do the edit, make the user repeat it in full visibility
20320 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20322 (defun org-fix-tags-on-the-fly ()
20323 (when (and (equal (char-after (point-at-bol)) ?*)
20324 (org-at-heading-p))
20325 (org-align-tags-here org-tags-column)))
20327 (defun org-delete-backward-char (N)
20328 "Like `delete-backward-char', insert whitespace at field end in tables.
20329 When deleting backwards, in tables this function will insert whitespace in
20330 front of the next \"|\" separator, to keep the table aligned. The table will
20331 still be marked for re-alignment if the field did fill the entire column,
20332 because, in this case the deletion might narrow the column."
20333 (interactive "p")
20334 (save-match-data
20335 (org-check-before-invisible-edit 'delete-backward)
20336 (if (and (org-at-table-p)
20337 (eq N 1)
20338 (string-match "|" (buffer-substring (point-at-bol) (point)))
20339 (looking-at ".*?|"))
20340 (let ((pos (point))
20341 (noalign (looking-at "[^|\n\r]* |"))
20342 (c org-table-may-need-update))
20343 (backward-delete-char N)
20344 (unless overwrite-mode
20345 (skip-chars-forward "^|")
20346 (insert " ")
20347 (goto-char (1- pos)))
20348 ;; noalign: if there were two spaces at the end, this field
20349 ;; does not determine the width of the column.
20350 (when noalign (setq org-table-may-need-update c)))
20351 (backward-delete-char N)
20352 (org-fix-tags-on-the-fly))))
20354 (defun org-delete-char (N)
20355 "Like `delete-char', but insert whitespace at field end in tables.
20356 When deleting characters, in tables this function will insert whitespace in
20357 front of the next \"|\" separator, to keep the table aligned. The table will
20358 still be marked for re-alignment if the field did fill the entire column,
20359 because, in this case the deletion might narrow the column."
20360 (interactive "p")
20361 (save-match-data
20362 (org-check-before-invisible-edit 'delete)
20363 (if (and (org-at-table-p)
20364 (not (bolp))
20365 (not (= (char-after) ?|))
20366 (eq N 1))
20367 (if (looking-at ".*?|")
20368 (let ((pos (point))
20369 (noalign (looking-at "[^|\n\r]* |"))
20370 (c org-table-may-need-update))
20371 (replace-match
20372 (concat (substring (match-string 0) 1 -1) " |") nil t)
20373 (goto-char pos)
20374 ;; noalign: if there were two spaces at the end, this field
20375 ;; does not determine the width of the column.
20376 (when noalign (setq org-table-may-need-update c)))
20377 (delete-char N))
20378 (delete-char N)
20379 (org-fix-tags-on-the-fly))))
20381 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20382 (put 'org-self-insert-command 'delete-selection
20383 (lambda ()
20384 (not (run-hook-with-args-until-success
20385 'self-insert-uses-region-functions))))
20386 (put 'orgtbl-self-insert-command 'delete-selection
20387 (lambda ()
20388 (not (run-hook-with-args-until-success
20389 'self-insert-uses-region-functions))))
20390 (put 'org-delete-char 'delete-selection 'supersede)
20391 (put 'org-delete-backward-char 'delete-selection 'supersede)
20392 (put 'org-yank 'delete-selection 'yank)
20394 ;; Make `flyspell-mode' delay after some commands
20395 (put 'org-self-insert-command 'flyspell-delayed t)
20396 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20397 (put 'org-delete-char 'flyspell-delayed t)
20398 (put 'org-delete-backward-char 'flyspell-delayed t)
20400 ;; Make pabbrev-mode expand after org-mode commands
20401 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20402 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20404 (defun org-remap (map &rest commands)
20405 "In MAP, remap the functions given in COMMANDS.
20406 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20407 (let (new old)
20408 (while commands
20409 (setq old (pop commands) new (pop commands))
20410 (if (fboundp 'command-remapping)
20411 (org-defkey map (vector 'remap old) new)
20412 (substitute-key-definition old new map global-map)))))
20414 (defun org-transpose-words ()
20415 "Transpose words for Org.
20416 This uses the `org-mode-transpose-word-syntax-table' syntax
20417 table, which interprets characters in `org-emphasis-alist' as
20418 word constituents."
20419 (interactive)
20420 (with-syntax-table org-mode-transpose-word-syntax-table
20421 (call-interactively 'transpose-words)))
20422 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20424 (when (eq org-enable-table-editor 'optimized)
20425 ;; If the user wants maximum table support, we need to hijack
20426 ;; some standard editing functions
20427 (org-remap org-mode-map
20428 'self-insert-command 'org-self-insert-command
20429 'delete-char 'org-delete-char
20430 'delete-backward-char 'org-delete-backward-char)
20431 (org-defkey org-mode-map "|" 'org-force-self-insert))
20433 (defvar org-ctrl-c-ctrl-c-hook nil
20434 "Hook for functions attaching themselves to `C-c C-c'.
20436 This can be used to add additional functionality to the C-c C-c
20437 key which executes context-dependent commands. This hook is run
20438 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20439 run after the last test.
20441 Each function will be called with no arguments. The function
20442 must check if the context is appropriate for it to act. If yes,
20443 it should do its thing and then return a non-nil value. If the
20444 context is wrong, just do nothing and return nil.")
20446 (defvar org-ctrl-c-ctrl-c-final-hook nil
20447 "Hook for functions attaching themselves to `C-c C-c'.
20449 This can be used to add additional functionality to the C-c C-c
20450 key which executes context-dependent commands. This hook is run
20451 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20452 before the first test.
20454 Each function will be called with no arguments. The function
20455 must check if the context is appropriate for it to act. If yes,
20456 it should do its thing and then return a non-nil value. If the
20457 context is wrong, just do nothing and return nil.")
20459 (defvar org-tab-first-hook nil
20460 "Hook for functions to attach themselves to TAB.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.
20462 This hook runs as the first action when TAB is pressed, even before
20463 `org-cycle' messes around with the `outline-regexp' to cater for
20464 inline tasks and plain list item folding.
20465 If any function in this hook returns t, any other actions that
20466 would have been caused by TAB (such as table field motion or visibility
20467 cycling) will not occur.")
20469 (defvar org-tab-after-check-for-table-hook nil
20470 "Hook for functions to attach themselves to TAB.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.
20472 This hook runs after it has been established that the cursor is not in a
20473 table, but before checking if the cursor is in a headline or if global cycling
20474 should be done.
20475 If any function in this hook returns t, not other actions like visibility
20476 cycling will be done.")
20478 (defvar org-tab-after-check-for-cycling-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 it has been established that not table field motion and
20482 not visibility should be done because of current context. This is probably
20483 the place where a package like yasnippets can hook in.")
20485 (defvar org-tab-before-tab-emulation-hook nil
20486 "Hook for functions to attach themselves to TAB.
20487 See `org-ctrl-c-ctrl-c-hook' for more information.
20488 This hook runs after every other options for TAB have been exhausted, but
20489 before indentation and \t insertion takes place.")
20491 (defvar org-metaleft-hook nil
20492 "Hook for functions attaching themselves to `M-left'.
20493 See `org-ctrl-c-ctrl-c-hook' for more information.")
20494 (defvar org-metaright-hook nil
20495 "Hook for functions attaching themselves to `M-right'.
20496 See `org-ctrl-c-ctrl-c-hook' for more information.")
20497 (defvar org-metaup-hook nil
20498 "Hook for functions attaching themselves to `M-up'.
20499 See `org-ctrl-c-ctrl-c-hook' for more information.")
20500 (defvar org-metadown-hook nil
20501 "Hook for functions attaching themselves to `M-down'.
20502 See `org-ctrl-c-ctrl-c-hook' for more information.")
20503 (defvar org-shiftmetaleft-hook nil
20504 "Hook for functions attaching themselves to `M-S-left'.
20505 See `org-ctrl-c-ctrl-c-hook' for more information.")
20506 (defvar org-shiftmetaright-hook nil
20507 "Hook for functions attaching themselves to `M-S-right'.
20508 See `org-ctrl-c-ctrl-c-hook' for more information.")
20509 (defvar org-shiftmetaup-hook nil
20510 "Hook for functions attaching themselves to `M-S-up'.
20511 See `org-ctrl-c-ctrl-c-hook' for more information.")
20512 (defvar org-shiftmetadown-hook nil
20513 "Hook for functions attaching themselves to `M-S-down'.
20514 See `org-ctrl-c-ctrl-c-hook' for more information.")
20515 (defvar org-metareturn-hook nil
20516 "Hook for functions attaching themselves to `M-RET'.
20517 See `org-ctrl-c-ctrl-c-hook' for more information.")
20518 (defvar org-shiftup-hook nil
20519 "Hook for functions attaching themselves to `S-up'.
20520 See `org-ctrl-c-ctrl-c-hook' for more information.")
20521 (defvar org-shiftup-final-hook nil
20522 "Hook for functions attaching themselves to `S-up'.
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-shiftdown-hook nil
20526 "Hook for functions attaching themselves to `S-down'.
20527 See `org-ctrl-c-ctrl-c-hook' for more information.")
20528 (defvar org-shiftdown-final-hook nil
20529 "Hook for functions attaching themselves to `S-down'.
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-shiftleft-hook nil
20533 "Hook for functions attaching themselves to `S-left'.
20534 See `org-ctrl-c-ctrl-c-hook' for more information.")
20535 (defvar org-shiftleft-final-hook nil
20536 "Hook for functions attaching themselves to `S-left'.
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.")
20539 (defvar org-shiftright-hook nil
20540 "Hook for functions attaching themselves to `S-right'.
20541 See `org-ctrl-c-ctrl-c-hook' for more information.")
20542 (defvar org-shiftright-final-hook nil
20543 "Hook for functions attaching themselves to `S-right'.
20544 This one runs after all other options except shift-select have been excluded.
20545 See `org-ctrl-c-ctrl-c-hook' for more information.")
20547 (defun org-modifier-cursor-error ()
20548 "Throw an error, a modified cursor command was applied in wrong context."
20549 (user-error "This command is active in special context like tables, headlines or items"))
20551 (defun org-shiftselect-error ()
20552 "Throw an error because Shift-Cursor command was applied in wrong context."
20553 (if (and (boundp 'shift-select-mode) shift-select-mode)
20554 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20555 (user-error "This command works only in special context like headlines or timestamps")))
20557 (defun org-call-for-shift-select (cmd)
20558 (let ((this-command-keys-shift-translated t))
20559 (call-interactively cmd)))
20561 (defun org-shifttab (&optional arg)
20562 "Global visibility cycling or move to previous table field.
20563 Call `org-table-previous-field' within a table.
20564 When ARG is nil, cycle globally through visibility states.
20565 When ARG is a numeric prefix, show contents of this level."
20566 (interactive "P")
20567 (cond
20568 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20569 ((integerp arg)
20570 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20571 (message "Content view to level: %d" arg)
20572 (org-content (prefix-numeric-value arg2))
20573 (org-cycle-show-empty-lines t)
20574 (setq org-cycle-global-status 'overview)))
20575 (t (call-interactively 'org-global-cycle))))
20577 (defun org-shiftmetaleft ()
20578 "Promote subtree or delete table column.
20579 Calls `org-promote-subtree', `org-outdent-item-tree', or
20580 `org-table-delete-column', depending on context. See the
20581 individual commands for more information."
20582 (interactive)
20583 (cond
20584 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20585 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20586 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20587 ((if (not (org-region-active-p)) (org-at-item-p)
20588 (save-excursion (goto-char (region-beginning))
20589 (org-at-item-p)))
20590 (call-interactively 'org-outdent-item-tree))
20591 (t (org-modifier-cursor-error))))
20593 (defun org-shiftmetaright ()
20594 "Demote subtree or insert table column.
20595 Calls `org-demote-subtree', `org-indent-item-tree', or
20596 `org-table-insert-column', depending on context. See the
20597 individual commands for more information."
20598 (interactive)
20599 (cond
20600 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20601 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20602 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20603 ((if (not (org-region-active-p)) (org-at-item-p)
20604 (save-excursion (goto-char (region-beginning))
20605 (org-at-item-p)))
20606 (call-interactively 'org-indent-item-tree))
20607 (t (org-modifier-cursor-error))))
20609 (defun org-shiftmetaup (&optional _arg)
20610 "Drag the line at point up.
20611 In a table, kill the current row.
20612 On a clock timestamp, update the value of the timestamp like `S-<up>'
20613 but also adjust the previous clocked item in the clock history.
20614 Everywhere else, drag the line at point up."
20615 (interactive "P")
20616 (cond
20617 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20618 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20619 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20620 (call-interactively 'org-timestamp-up)))
20621 (t (call-interactively 'org-drag-line-backward))))
20623 (defun org-shiftmetadown (&optional _arg)
20624 "Drag the line at point down.
20625 In a table, insert an empty row at the current line.
20626 On a clock timestamp, update the value of the timestamp like `S-<down>'
20627 but also adjust the previous clocked item in the clock history.
20628 Everywhere else, drag the line at point down."
20629 (interactive "P")
20630 (cond
20631 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20632 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20633 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20634 (call-interactively 'org-timestamp-down)))
20635 (t (call-interactively 'org-drag-line-forward))))
20637 (defsubst org-hidden-tree-error ()
20638 (user-error
20639 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20641 (defun org-metaleft (&optional _arg)
20642 "Promote heading, list item at point or move table column left.
20644 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20645 depending on context. With no specific context, calls the Emacs
20646 default `backward-word'. See the individual commands for more
20647 information.
20649 This function runs the hook `org-metaleft-hook' as a first step,
20650 and returns at first non-nil value."
20651 (interactive "P")
20652 (cond
20653 ((run-hook-with-args-until-success 'org-metaleft-hook))
20654 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20655 ((org-with-limited-levels
20656 (or (org-at-heading-p)
20657 (and (org-region-active-p)
20658 (save-excursion
20659 (goto-char (region-beginning))
20660 (org-at-heading-p)))))
20661 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20662 (call-interactively 'org-do-promote))
20663 ;; At an inline task.
20664 ((org-at-heading-p)
20665 (call-interactively 'org-inlinetask-promote))
20666 ((or (org-at-item-p)
20667 (and (org-region-active-p)
20668 (save-excursion
20669 (goto-char (region-beginning))
20670 (org-at-item-p))))
20671 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20672 (call-interactively 'org-outdent-item))
20673 (t (call-interactively 'backward-word))))
20675 (defun org-metaright (&optional _arg)
20676 "Demote heading, list item at point or move table column right.
20678 In front of a drawer or a block keyword, indent it correctly.
20680 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20681 `org-indnet-drawer' or `org-indent-block' depending on context.
20682 With no specific context, calls the Emacs default `forward-word'.
20683 See the individual commands for more information.
20685 This function runs the hook `org-metaright-hook' as a first step,
20686 and returns at first non-nil value."
20687 (interactive "P")
20688 (cond
20689 ((run-hook-with-args-until-success 'org-metaright-hook))
20690 ((org-at-table-p) (call-interactively 'org-table-move-column))
20691 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20692 ((org-at-block-p) (call-interactively 'org-indent-block))
20693 ((org-with-limited-levels
20694 (or (org-at-heading-p)
20695 (and (org-region-active-p)
20696 (save-excursion
20697 (goto-char (region-beginning))
20698 (org-at-heading-p)))))
20699 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20700 (call-interactively 'org-do-demote))
20701 ;; At an inline task.
20702 ((org-at-heading-p)
20703 (call-interactively 'org-inlinetask-demote))
20704 ((or (org-at-item-p)
20705 (and (org-region-active-p)
20706 (save-excursion
20707 (goto-char (region-beginning))
20708 (org-at-item-p))))
20709 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20710 (call-interactively 'org-indent-item))
20711 (t (call-interactively 'forward-word))))
20713 (defun org-check-for-hidden (what)
20714 "Check if there are hidden headlines/items in the current visual line.
20715 WHAT can be either `headlines' or `items'. If the current line is
20716 an outline or item heading and it has a folded subtree below it,
20717 this function returns t, nil otherwise."
20718 (let ((re (cond
20719 ((eq what 'headlines) org-outline-regexp-bol)
20720 ((eq what 'items) (org-item-beginning-re))
20721 (t (error "This should not happen"))))
20722 beg end)
20723 (save-excursion
20724 (catch 'exit
20725 (unless (org-region-active-p)
20726 (setq beg (point-at-bol))
20727 (beginning-of-line 2)
20728 (while (and (not (eobp)) ;; this is like `next-line'
20729 (get-char-property (1- (point)) 'invisible))
20730 (beginning-of-line 2))
20731 (setq end (point))
20732 (goto-char beg)
20733 (goto-char (point-at-eol))
20734 (setq end (max end (point)))
20735 (while (re-search-forward re end t)
20736 (when (get-char-property (match-beginning 0) 'invisible)
20737 (throw 'exit t))))
20738 nil))))
20740 (defun org-metaup (&optional _arg)
20741 "Move subtree up or move table row up.
20742 Calls `org-move-subtree-up' or `org-table-move-row' or
20743 `org-move-item-up', depending on context. See the individual commands
20744 for more information."
20745 (interactive "P")
20746 (cond
20747 ((run-hook-with-args-until-success 'org-metaup-hook))
20748 ((org-region-active-p)
20749 (let* ((a (min (region-beginning) (region-end)))
20750 (b (1- (max (region-beginning) (region-end))))
20751 (c (save-excursion (goto-char a)
20752 (move-beginning-of-line 0)))
20753 (d (save-excursion (goto-char a)
20754 (move-end-of-line 0) (point))))
20755 (transpose-regions a b c d)
20756 (goto-char c)))
20757 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20758 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20759 ((org-at-item-p) (call-interactively 'org-move-item-up))
20760 (t (org-drag-element-backward))))
20762 (defun org-metadown (&optional _arg)
20763 "Move subtree down or move table row down.
20764 Calls `org-move-subtree-down' or `org-table-move-row' or
20765 `org-move-item-down', depending on context. See the individual
20766 commands for more information."
20767 (interactive "P")
20768 (cond
20769 ((run-hook-with-args-until-success 'org-metadown-hook))
20770 ((org-region-active-p)
20771 (let* ((a (min (region-beginning) (region-end)))
20772 (b (max (region-beginning) (region-end)))
20773 (c (save-excursion (goto-char b)
20774 (move-beginning-of-line 1)))
20775 (d (save-excursion (goto-char b)
20776 (move-end-of-line 1) (1+ (point)))))
20777 (transpose-regions a b c d)
20778 (goto-char d)))
20779 ((org-at-table-p) (call-interactively 'org-table-move-row))
20780 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20781 ((org-at-item-p) (call-interactively 'org-move-item-down))
20782 (t (org-drag-element-forward))))
20784 (defun org-shiftup (&optional arg)
20785 "Increase item in timestamp or increase priority of current headline.
20786 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20787 depending on context. See the individual commands for more information."
20788 (interactive "P")
20789 (cond
20790 ((run-hook-with-args-until-success 'org-shiftup-hook))
20791 ((and org-support-shift-select (org-region-active-p))
20792 (org-call-for-shift-select 'previous-line))
20793 ((org-at-timestamp-p t)
20794 (call-interactively (if org-edit-timestamp-down-means-later
20795 'org-timestamp-down 'org-timestamp-up)))
20796 ((and (not (eq org-support-shift-select 'always))
20797 org-enable-priority-commands
20798 (org-at-heading-p))
20799 (call-interactively 'org-priority-up))
20800 ((and (not org-support-shift-select) (org-at-item-p))
20801 (call-interactively 'org-previous-item))
20802 ((org-clocktable-try-shift 'up arg))
20803 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20804 (org-support-shift-select
20805 (org-call-for-shift-select 'previous-line))
20806 (t (org-shiftselect-error))))
20808 (defun org-shiftdown (&optional arg)
20809 "Decrease item in timestamp or decrease priority of current headline.
20810 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20811 depending on context. See the individual commands for more information."
20812 (interactive "P")
20813 (cond
20814 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20815 ((and org-support-shift-select (org-region-active-p))
20816 (org-call-for-shift-select 'next-line))
20817 ((org-at-timestamp-p t)
20818 (call-interactively (if org-edit-timestamp-down-means-later
20819 'org-timestamp-up 'org-timestamp-down)))
20820 ((and (not (eq org-support-shift-select 'always))
20821 org-enable-priority-commands
20822 (org-at-heading-p))
20823 (call-interactively 'org-priority-down))
20824 ((and (not org-support-shift-select) (org-at-item-p))
20825 (call-interactively 'org-next-item))
20826 ((org-clocktable-try-shift 'down arg))
20827 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20828 (org-support-shift-select
20829 (org-call-for-shift-select 'next-line))
20830 (t (org-shiftselect-error))))
20832 (defun org-shiftright (&optional arg)
20833 "Cycle the thing at point or in the current line, depending on context.
20834 Depending on context, this does one of the following:
20836 - switch a timestamp at point one day into the future
20837 - on a headline, switch to the next TODO keyword.
20838 - on an item, switch entire list to the next bullet type
20839 - on a property line, switch to the next allowed value
20840 - on a clocktable definition line, move time block into the future"
20841 (interactive "P")
20842 (cond
20843 ((run-hook-with-args-until-success 'org-shiftright-hook))
20844 ((and org-support-shift-select (org-region-active-p))
20845 (org-call-for-shift-select 'forward-char))
20846 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20847 ((and (not (eq org-support-shift-select 'always))
20848 (org-at-heading-p))
20849 (let ((org-inhibit-logging
20850 (not org-treat-S-cursor-todo-selection-as-state-change))
20851 (org-inhibit-blocking
20852 (not org-treat-S-cursor-todo-selection-as-state-change)))
20853 (org-call-with-arg 'org-todo 'right)))
20854 ((or (and org-support-shift-select
20855 (not (eq org-support-shift-select 'always))
20856 (org-at-item-bullet-p))
20857 (and (not org-support-shift-select) (org-at-item-p)))
20858 (org-call-with-arg 'org-cycle-list-bullet nil))
20859 ((and (not (eq org-support-shift-select 'always))
20860 (org-at-property-p))
20861 (call-interactively 'org-property-next-allowed-value))
20862 ((org-clocktable-try-shift 'right arg))
20863 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20864 (org-support-shift-select
20865 (org-call-for-shift-select 'forward-char))
20866 (t (org-shiftselect-error))))
20868 (defun org-shiftleft (&optional arg)
20869 "Cycle the thing at point or in the current line, depending on context.
20870 Depending on context, this does one of the following:
20872 - switch a timestamp at point one day into the past
20873 - on a headline, switch to the previous TODO keyword.
20874 - on an item, switch entire list to the previous bullet type
20875 - on a property line, switch to the previous allowed value
20876 - on a clocktable definition line, move time block into the past"
20877 (interactive "P")
20878 (cond
20879 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20880 ((and org-support-shift-select (org-region-active-p))
20881 (org-call-for-shift-select 'backward-char))
20882 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20883 ((and (not (eq org-support-shift-select 'always))
20884 (org-at-heading-p))
20885 (let ((org-inhibit-logging
20886 (not org-treat-S-cursor-todo-selection-as-state-change))
20887 (org-inhibit-blocking
20888 (not org-treat-S-cursor-todo-selection-as-state-change)))
20889 (org-call-with-arg 'org-todo 'left)))
20890 ((or (and org-support-shift-select
20891 (not (eq org-support-shift-select 'always))
20892 (org-at-item-bullet-p))
20893 (and (not org-support-shift-select) (org-at-item-p)))
20894 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20895 ((and (not (eq org-support-shift-select 'always))
20896 (org-at-property-p))
20897 (call-interactively 'org-property-previous-allowed-value))
20898 ((org-clocktable-try-shift 'left arg))
20899 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20900 (org-support-shift-select
20901 (org-call-for-shift-select 'backward-char))
20902 (t (org-shiftselect-error))))
20904 (defun org-shiftcontrolright ()
20905 "Switch to next TODO set."
20906 (interactive)
20907 (cond
20908 ((and org-support-shift-select (org-region-active-p))
20909 (org-call-for-shift-select 'forward-word))
20910 ((and (not (eq org-support-shift-select 'always))
20911 (org-at-heading-p))
20912 (org-call-with-arg 'org-todo 'nextset))
20913 (org-support-shift-select
20914 (org-call-for-shift-select 'forward-word))
20915 (t (org-shiftselect-error))))
20917 (defun org-shiftcontrolleft ()
20918 "Switch to previous TODO set."
20919 (interactive)
20920 (cond
20921 ((and org-support-shift-select (org-region-active-p))
20922 (org-call-for-shift-select 'backward-word))
20923 ((and (not (eq org-support-shift-select 'always))
20924 (org-at-heading-p))
20925 (org-call-with-arg 'org-todo 'previousset))
20926 (org-support-shift-select
20927 (org-call-for-shift-select 'backward-word))
20928 (t (org-shiftselect-error))))
20930 (defun org-shiftcontrolup (&optional n)
20931 "Change timestamps synchronously up in CLOCK log lines.
20932 Optional argument N tells to change by that many units."
20933 (interactive "P")
20934 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20935 (let (org-support-shift-select)
20936 (org-clock-timestamps-up n))
20937 (user-error "Not at a clock log")))
20939 (defun org-shiftcontroldown (&optional n)
20940 "Change timestamps synchronously down in CLOCK log lines.
20941 Optional argument N tells to change by that many units."
20942 (interactive "P")
20943 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20944 (let (org-support-shift-select)
20945 (org-clock-timestamps-down n))
20946 (user-error "Not at a clock log")))
20948 (defun org-increase-number-at-point (&optional inc)
20949 "Increment the number at point.
20950 With an optional prefix numeric argument INC, increment using
20951 this numeric value."
20952 (interactive "p")
20953 (if (not (number-at-point))
20954 (user-error "Not on a number")
20955 (unless inc (setq inc 1))
20956 (let ((pos (point))
20957 (beg (skip-chars-backward "-+^/*0-9eE."))
20958 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20959 (setq nap (buffer-substring-no-properties
20960 (+ pos beg) (+ pos beg end)))
20961 (delete-region (+ pos beg) (+ pos beg end))
20962 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20963 (when (org-at-table-p)
20964 (org-table-align)
20965 (org-table-end-of-field 1))))
20967 (defun org-decrease-number-at-point (&optional inc)
20968 "Decrement the number at point.
20969 With an optional prefix numeric argument INC, decrement using
20970 this numeric value."
20971 (interactive "p")
20972 (org-increase-number-at-point (- (or inc 1))))
20974 (defun org-ctrl-c-ret ()
20975 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20976 (interactive)
20977 (cond
20978 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20979 (t (call-interactively 'org-insert-heading))))
20981 (defun org-find-visible ()
20982 (let ((s (point)))
20983 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20984 (get-char-property s 'invisible)))
20986 (defun org-find-invisible ()
20987 (let ((s (point)))
20988 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20989 (not (get-char-property s 'invisible))))
20992 (defun org-copy-visible (beg end)
20993 "Copy the visible parts of the region."
20994 (interactive "r")
20995 (let (snippets s)
20996 (save-excursion
20997 (save-restriction
20998 (narrow-to-region beg end)
20999 (setq s (goto-char (point-min)))
21000 (while (not (= (point) (point-max)))
21001 (goto-char (org-find-invisible))
21002 (push (buffer-substring s (point)) snippets)
21003 (setq s (goto-char (org-find-visible))))))
21004 (kill-new (apply 'concat (nreverse snippets)))))
21006 (defun org-copy-special ()
21007 "Copy region in table or copy current subtree.
21008 Calls `org-table-copy' or `org-copy-subtree', depending on context.
21009 See the individual commands for more information."
21010 (interactive)
21011 (call-interactively
21012 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
21014 (defun org-cut-special ()
21015 "Cut region in table or cut current subtree.
21016 Calls `org-table-copy' or `org-cut-subtree', depending on context.
21017 See the individual commands for more information."
21018 (interactive)
21019 (call-interactively
21020 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
21022 (defun org-paste-special (arg)
21023 "Paste rectangular region into table, or past subtree relative to level.
21024 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
21025 See the individual commands for more information."
21026 (interactive "P")
21027 (if (org-at-table-p)
21028 (org-table-paste-rectangle)
21029 (org-paste-subtree arg)))
21031 (defsubst org-in-fixed-width-region-p ()
21032 "Is point in a fixed-width region?"
21033 (save-match-data
21034 (eq 'fixed-width (org-element-type (org-element-at-point)))))
21036 (defun org-edit-special (&optional arg)
21037 "Call a special editor for the element at point.
21038 When at a table, call the formula editor with `org-table-edit-formulas'.
21039 When in a source code block, call `org-edit-src-code'.
21040 When in a fixed-width region, call `org-edit-fixed-width-region'.
21041 When in an export block, call `org-edit-export-block'.
21042 When at an #+INCLUDE keyword, visit the included file.
21043 When at a footnote reference, call `org-edit-footnote-reference'
21044 On a link, call `ffap' to visit the link at point.
21045 Otherwise, return a user error."
21046 (interactive "P")
21047 (let ((element (org-element-at-point)))
21048 (cl-assert (not buffer-read-only) nil
21049 "Buffer is read-only: %s" (buffer-name))
21050 (pcase (org-element-type element)
21051 (`src-block
21052 (if (not arg) (org-edit-src-code)
21053 (let* ((info (org-babel-get-src-block-info))
21054 (lang (nth 0 info))
21055 (params (nth 2 info))
21056 (session (cdr (assq :session params))))
21057 (if (not session) (org-edit-src-code)
21058 ;; At a src-block with a session and function called with
21059 ;; an ARG: switch to the buffer related to the inferior
21060 ;; process.
21061 (switch-to-buffer
21062 (funcall (intern (concat "org-babel-prep-session:" lang))
21063 session params))))))
21064 (`keyword
21065 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21066 (org-open-link-from-string
21067 (format "[[%s]]"
21068 (expand-file-name
21069 (let ((value (org-element-property :value element)))
21070 (cond ((not (org-string-nw-p value))
21071 (user-error "No file to edit"))
21072 ((string-match "\\`\"\\(.*?\\)\"" value)
21073 (match-string 1 value))
21074 ((string-match "\\`[^ \t\"]\\S-*" value)
21075 (match-string 0 value))
21076 (t (user-error "No valid file specified")))))))
21077 (user-error "No special environment to edit here")))
21078 (`table
21079 (if (eq (org-element-property :type element) 'table.el)
21080 (org-edit-table.el)
21081 (call-interactively 'org-table-edit-formulas)))
21082 ;; Only Org tables contain `table-row' type elements.
21083 (`table-row (call-interactively 'org-table-edit-formulas))
21084 (`example-block (org-edit-src-code))
21085 (`export-block (org-edit-export-block))
21086 (`fixed-width (org-edit-fixed-width-region))
21088 ;; No notable element at point. Though, we may be at a link or
21089 ;; a footnote reference, which are objects. Thus, scan deeper.
21090 (let ((context (org-element-context element)))
21091 (pcase (org-element-type context)
21092 (`footnote-reference (org-edit-footnote-reference))
21093 (`inline-src-block (org-edit-inline-src-code))
21094 (`link (call-interactively #'ffap))
21095 (_ (user-error "No special environment to edit here"))))))))
21097 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21098 (defun org-ctrl-c-ctrl-c (&optional arg)
21099 "Set tags in headline, or update according to changed information at point.
21101 This command does many different things, depending on context:
21103 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21104 this is what we do.
21106 - If the cursor is on a statistics cookie, update it.
21108 - If the cursor is in a headline, prompt for tags and insert them
21109 into the current line, aligned to `org-tags-column'. When called
21110 with prefix arg, realign all tags in the current buffer.
21112 - If the cursor is in one of the special #+KEYWORD lines, this
21113 triggers scanning the buffer for these lines and updating the
21114 information.
21116 - If the cursor is inside a table, realign the table. This command
21117 works even if the automatic table editor has been turned off.
21119 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21120 the entire table.
21122 - If the cursor is at a footnote reference or definition, jump to
21123 the corresponding definition or references, respectively.
21125 - If the cursor is a the beginning of a dynamic block, update it.
21127 - If the current buffer is a capture buffer, close note and file it.
21129 - If the cursor is on a <<<target>>>, update radio targets and
21130 corresponding links in this buffer.
21132 - If the cursor is on a numbered item in a plain list, renumber the
21133 ordered list.
21135 - If the cursor is on a checkbox, toggle it.
21137 - If the cursor is on a code block, evaluate it. The variable
21138 `org-confirm-babel-evaluate' can be used to control prompting
21139 before code block evaluation, by default every code block
21140 evaluation requires confirmation. Code block evaluation can be
21141 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21142 (interactive "P")
21143 (cond
21144 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21145 org-occur-highlights)
21146 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21147 (org-remove-occur-highlights)
21148 (message "Temporary highlights/overlays removed from current buffer"))
21149 ((and (local-variable-p 'org-finish-function (current-buffer))
21150 (fboundp org-finish-function))
21151 (funcall org-finish-function))
21152 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21154 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21155 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21156 (user-error "C-c C-c can do nothing useful at this location"))
21157 (let* ((context (org-element-context))
21158 (type (org-element-type context)))
21159 (cl-case type
21160 ;; When at a link, act according to the parent instead.
21161 (link (setq context (org-element-property :parent context))
21162 (setq type (org-element-type context)))
21163 ;; Unsupported object types: refer to the first supported
21164 ;; element or object containing it.
21165 ((bold code entity export-snippet inline-babel-call inline-src-block
21166 italic latex-fragment line-break macro strike-through subscript
21167 superscript underline verbatim)
21168 (setq context
21169 (org-element-lineage
21170 context '(radio-target paragraph verse-block table-cell)))))
21171 ;; For convenience: at the first line of a paragraph on the
21172 ;; same line as an item, apply function on that item instead.
21173 (when (eq type 'paragraph)
21174 (let ((parent (org-element-property :parent context)))
21175 (when (and (eq (org-element-type parent) 'item)
21176 (= (line-beginning-position)
21177 (org-element-property :begin parent)))
21178 (setq context parent type 'item))))
21179 ;; Act according to type of element or object at point.
21180 (cl-case type
21181 (clock (org-clock-update-time-maybe))
21182 (dynamic-block
21183 (save-excursion
21184 (goto-char (org-element-property :post-affiliated context))
21185 (org-update-dblock)))
21186 (footnote-definition
21187 (goto-char (org-element-property :post-affiliated context))
21188 (call-interactively 'org-footnote-action))
21189 (footnote-reference (call-interactively 'org-footnote-action))
21190 ((headline inlinetask)
21191 (save-excursion (goto-char (org-element-property :begin context))
21192 (call-interactively 'org-set-tags)))
21193 (item
21194 ;; At an item: a double C-u set checkbox to "[-]"
21195 ;; unconditionally, whereas a single one will toggle its
21196 ;; presence. Without a universal argument, if the item
21197 ;; has a checkbox, toggle it. Otherwise repair the list.
21198 (let* ((box (org-element-property :checkbox context))
21199 (struct (org-element-property :structure context))
21200 (old-struct (copy-tree struct))
21201 (parents (org-list-parents-alist struct))
21202 (prevs (org-list-prevs-alist struct))
21203 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21204 (org-list-set-checkbox
21205 (org-element-property :begin context) struct
21206 (cond ((equal arg '(16)) "[-]")
21207 ((and (not box) (equal arg '(4))) "[ ]")
21208 ((or (not box) (equal arg '(4))) nil)
21209 ((eq box 'on) "[ ]")
21210 (t "[X]")))
21211 ;; Mimic `org-list-write-struct' but with grabbing
21212 ;; a return value from `org-list-struct-fix-box'.
21213 (org-list-struct-fix-ind struct parents 2)
21214 (org-list-struct-fix-item-end struct)
21215 (org-list-struct-fix-bul struct prevs)
21216 (org-list-struct-fix-ind struct parents)
21217 (let ((block-item
21218 (org-list-struct-fix-box struct parents prevs orderedp)))
21219 (if (and box (equal struct old-struct))
21220 (if (equal arg '(16))
21221 (message "Checkboxes already reset")
21222 (user-error "Cannot toggle this checkbox: %s"
21223 (if (eq box 'on)
21224 "all subitems checked"
21225 "unchecked subitems")))
21226 (org-list-struct-apply-struct struct old-struct)
21227 (org-update-checkbox-count-maybe))
21228 (when block-item
21229 (message "Checkboxes were removed due to empty box at line %d"
21230 (org-current-line block-item))))))
21231 (keyword
21232 (let ((org-inhibit-startup-visibility-stuff t)
21233 (org-startup-align-all-tables nil))
21234 (when (boundp 'org-table-coordinate-overlays)
21235 (mapc #'delete-overlay org-table-coordinate-overlays)
21236 (setq org-table-coordinate-overlays nil))
21237 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21238 (message "Local setup has been refreshed"))
21239 (plain-list
21240 ;; At a plain list, with a double C-u argument, set
21241 ;; checkboxes of each item to "[-]", whereas a single one
21242 ;; will toggle their presence according to the state of the
21243 ;; first item in the list. Without an argument, repair the
21244 ;; list.
21245 (let* ((begin (org-element-property :contents-begin context))
21246 (beginm (move-marker (make-marker) begin))
21247 (struct (org-element-property :structure context))
21248 (old-struct (copy-tree struct))
21249 (first-box (save-excursion
21250 (goto-char begin)
21251 (looking-at org-list-full-item-re)
21252 (match-string-no-properties 3)))
21253 (new-box (cond ((equal arg '(16)) "[-]")
21254 ((equal arg '(4)) (unless first-box "[ ]"))
21255 ((equal first-box "[X]") "[ ]")
21256 (t "[X]"))))
21257 (cond
21258 (arg
21259 (dolist (pos
21260 (org-list-get-all-items
21261 begin struct (org-list-prevs-alist struct)))
21262 (org-list-set-checkbox pos struct new-box)))
21263 ((and first-box (eq (point) begin))
21264 ;; For convenience, when point is at bol on the first
21265 ;; item of the list and no argument is provided, simply
21266 ;; toggle checkbox of that item, if any.
21267 (org-list-set-checkbox begin struct new-box)))
21268 (org-list-write-struct
21269 struct (org-list-parents-alist struct) old-struct)
21270 (org-update-checkbox-count-maybe)
21271 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21272 ((property-drawer node-property)
21273 (call-interactively 'org-property-action))
21274 ((radio-target target)
21275 (call-interactively 'org-update-radio-target-regexp))
21276 (statistics-cookie
21277 (call-interactively 'org-update-statistics-cookies))
21278 ((table table-cell table-row)
21279 ;; At a table, recalculate every field and align it. Also
21280 ;; send the table if necessary. If the table has
21281 ;; a `table.el' type, just give up. At a table row or
21282 ;; cell, maybe recalculate line but always align table.
21283 (if (eq (org-element-property :type context) 'table.el)
21284 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21285 Use \\[org-edit-special] to edit table.el tables"))
21286 (let ((org-enable-table-editor t))
21287 (if (or (eq type 'table)
21288 ;; Check if point is at a TBLFM line.
21289 (and (eq type 'table-row)
21290 (= (point) (org-element-property :end context))))
21291 (save-excursion
21292 (if (org-at-TBLFM-p)
21293 (progn (require 'org-table)
21294 (org-table-calc-current-TBLFM))
21295 (goto-char (org-element-property :contents-begin context))
21296 (org-call-with-arg 'org-table-recalculate (or arg t))
21297 (orgtbl-send-table 'maybe)))
21298 (org-table-maybe-eval-formula)
21299 (cond (arg (call-interactively 'org-table-recalculate))
21300 ((org-table-maybe-recalculate-line))
21301 (t (org-table-align)))))))
21302 (timestamp (org-timestamp-change 0 'day))
21303 (otherwise
21304 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21305 (user-error
21306 "C-c C-c can do nothing useful at this location")))))))))
21308 (defun org-mode-restart ()
21309 (interactive)
21310 (let ((indent-status (bound-and-true-p org-indent-mode)))
21311 (funcall major-mode)
21312 (hack-local-variables)
21313 (when (and indent-status (not (bound-and-true-p org-indent-mode)))
21314 (org-indent-mode -1)))
21315 (message "%s restarted" major-mode))
21317 (defun org-kill-note-or-show-branches ()
21318 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21319 (interactive)
21320 (if (not org-finish-function)
21321 (progn
21322 (outline-hide-subtree)
21323 (call-interactively 'outline-show-branches))
21324 (let ((org-note-abort t))
21325 (funcall org-finish-function))))
21327 (defun org-delete-indentation (&optional ARG)
21328 "Join current line to previous and fix whitespace at join.
21330 If previous line is a headline add to headline title. Otherwise
21331 the function calls `delete-indentation'.
21333 With argument, join this line to following line."
21334 (interactive "*P")
21335 (if (save-excursion
21336 (if ARG (beginning-of-line)
21337 (forward-line -1))
21338 (looking-at org-complex-heading-regexp))
21339 ;; At headline.
21340 (let ((tags-column (when (match-beginning 5)
21341 (save-excursion (goto-char (match-beginning 5))
21342 (current-column))))
21343 (string (concat " " (progn (when ARG (forward-line 1))
21344 (org-trim (delete-and-extract-region
21345 (line-beginning-position)
21346 (line-end-position)))))))
21347 (unless (bobp) (delete-region (point) (1- (point))))
21348 (goto-char (or (match-end 4)
21349 (match-beginning 5)
21350 (match-end 0)))
21351 (skip-chars-backward " \t")
21352 (save-excursion (insert string))
21353 ;; Adjust alignment of tags.
21354 (when tags-column
21355 (org-align-tags-here (if org-auto-align-tags
21356 org-tags-column
21357 tags-column))))
21358 (delete-indentation ARG)))
21360 (defun org-open-line (n)
21361 "Insert a new row in tables, call `open-line' elsewhere.
21362 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21363 (interactive "*p")
21364 (cond
21365 ((not org-special-ctrl-o)
21366 (open-line n))
21367 ((org-at-table-p)
21368 (org-table-insert-row))
21370 (open-line n))))
21372 (defun org-return (&optional indent)
21373 "Goto next table row or insert a newline.
21375 Calls `org-table-next-row' or `newline', depending on context.
21377 When optional INDENT argument is non-nil, call
21378 `newline-and-indent' instead of `newline'.
21380 When `org-return-follows-link' is non-nil and point is on
21381 a timestamp or a link, call `org-open-at-point'. However, it
21382 will not happen if point is in a table or on a \"dead\"
21383 object (e.g., within a comment). In these case, you need to use
21384 `org-open-at-point' directly."
21385 (interactive)
21386 (let ((context (if org-return-follows-link (org-element-context)
21387 (org-element-at-point))))
21388 (cond
21389 ;; In a table, call `org-table-next-row'.
21390 ((or (and (eq (org-element-type context) 'table)
21391 (>= (point) (org-element-property :contents-begin context))
21392 (< (point) (org-element-property :contents-end context)))
21393 (org-element-lineage context '(table-row table-cell) t))
21394 (org-table-justify-field-maybe)
21395 (call-interactively #'org-table-next-row))
21396 ;; On a link or a timestamp, call `org-open-at-point' if
21397 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21398 ;; locations, e.g., in a comment, as `org-open-at-point'.
21399 ((and org-return-follows-link
21400 (or (org-in-regexp org-ts-regexp-both nil t)
21401 (org-in-regexp org-tsr-regexp-both nil t)
21402 (org-in-regexp org-any-link-re nil t)))
21403 (call-interactively #'org-open-at-point))
21404 ;; Insert newline in heading, but preserve tags.
21405 ((and (not (bolp))
21406 (save-excursion (beginning-of-line)
21407 (looking-at org-complex-heading-regexp)))
21408 ;; At headline. Split line. However, if point is on keyword,
21409 ;; priority cookie or tags, do not break any of them: add
21410 ;; a newline after the headline instead.
21411 (let ((tags-column (and (match-beginning 5)
21412 (save-excursion (goto-char (match-beginning 5))
21413 (current-column))))
21414 (string
21415 (when (and (match-end 4)
21416 (>= (point)
21417 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21418 (<= (point) (match-end 4)))
21419 (delete-and-extract-region (point) (match-end 4)))))
21420 (when (and tags-column string) ; Adjust tag alignment.
21421 (org-align-tags-here
21422 (if org-auto-align-tags org-tags-column tags-column)))
21423 (end-of-line)
21424 (org-show-entry)
21425 (if indent (newline-and-indent) (newline))
21426 (when string (save-excursion (insert (org-trim string))))))
21427 ;; In a list, make sure indenting keeps trailing text within.
21428 ((and indent
21429 (not (eolp))
21430 (org-element-lineage context '(item)))
21431 (let ((trailing-data
21432 (delete-and-extract-region (point) (line-end-position))))
21433 (newline-and-indent)
21434 (save-excursion (insert trailing-data))))
21435 (t (if indent (newline-and-indent) (newline))))))
21437 (defun org-return-indent ()
21438 "Goto next table row or insert a newline and indent.
21439 Calls `org-table-next-row' or `newline-and-indent', depending on
21440 context. See the individual commands for more information."
21441 (interactive)
21442 (org-return t))
21444 (defun org-ctrl-c-star ()
21445 "Compute table, or change heading status of lines.
21446 Calls `org-table-recalculate' or `org-toggle-heading',
21447 depending on context."
21448 (interactive)
21449 (cond
21450 ((org-at-table-p)
21451 (call-interactively 'org-table-recalculate))
21453 ;; Convert all lines in region to list items
21454 (call-interactively 'org-toggle-heading))))
21456 (defun org-ctrl-c-minus ()
21457 "Insert separator line in table or modify bullet status of line.
21458 Also turns a plain line or a region of lines into list items.
21459 Calls `org-table-insert-hline', `org-toggle-item', or
21460 `org-cycle-list-bullet', depending on context."
21461 (interactive)
21462 (cond
21463 ((org-at-table-p)
21464 (call-interactively 'org-table-insert-hline))
21465 ((org-region-active-p)
21466 (call-interactively 'org-toggle-item))
21467 ((org-in-item-p)
21468 (call-interactively 'org-cycle-list-bullet))
21470 (call-interactively 'org-toggle-item))))
21472 (defun org-toggle-heading (&optional nstars)
21473 "Convert headings to normal text, or items or text to headings.
21474 If there is no active region, only convert the current line.
21476 With a \\[universal-argument] prefix, convert the whole list at
21477 point into heading.
21479 In a region:
21481 - If the first non blank line is a headline, remove the stars
21482 from all headlines in the region.
21484 - If it is a normal line, turn each and every normal line (i.e.,
21485 not an heading or an item) in the region into headings. If you
21486 want to convert only the first line of this region, use one
21487 universal prefix argument.
21489 - If it is a plain list item, turn all plain list items into headings.
21491 When converting a line into a heading, the number of stars is chosen
21492 such that the lines become children of the current entry. However,
21493 when a numeric prefix argument is given, its value determines the
21494 number of stars to add."
21495 (interactive "P")
21496 (let ((skip-blanks
21497 (function
21498 ;; Return beginning of first non-blank line, starting from
21499 ;; line at POS.
21500 (lambda (pos)
21501 (save-excursion
21502 (goto-char pos)
21503 (while (org-at-comment-p) (forward-line))
21504 (skip-chars-forward " \r\t\n")
21505 (point-at-bol)))))
21506 beg end toggled)
21507 ;; Determine boundaries of changes. If a universal prefix has
21508 ;; been given, put the list in a region. If region ends at a bol,
21509 ;; do not consider the last line to be in the region.
21511 (when (and current-prefix-arg (org-at-item-p))
21512 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21513 (org-mark-element))
21515 (if (org-region-active-p)
21516 (setq beg (funcall skip-blanks (region-beginning))
21517 end (copy-marker (save-excursion
21518 (goto-char (region-end))
21519 (if (bolp) (point) (point-at-eol)))))
21520 (setq beg (funcall skip-blanks (point-at-bol))
21521 end (copy-marker (point-at-eol))))
21522 ;; Ensure inline tasks don't count as headings.
21523 (org-with-limited-levels
21524 (save-excursion
21525 (goto-char beg)
21526 (cond
21527 ;; Case 1. Started at an heading: de-star headings.
21528 ((org-at-heading-p)
21529 (while (< (point) end)
21530 (when (org-at-heading-p t)
21531 (looking-at org-outline-regexp) (replace-match "")
21532 (setq toggled t))
21533 (forward-line)))
21534 ;; Case 2. Started at an item: change items into headlines.
21535 ;; One star will be added by `org-list-to-subtree'.
21536 ((org-at-item-p)
21537 (while (< (point) end)
21538 (when (org-at-item-p)
21539 ;; Pay attention to cases when region ends before list.
21540 (let* ((struct (org-list-struct))
21541 (list-end
21542 (min (org-list-get-bottom-point struct) (1+ end))))
21543 (save-restriction
21544 (narrow-to-region (point) list-end)
21545 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21546 (setq toggled t))
21547 (forward-line)))
21548 ;; Case 3. Started at normal text: make every line an heading,
21549 ;; skipping headlines and items.
21550 (t (let* ((stars
21551 (make-string
21552 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21553 (add-stars
21554 (cond (nstars "") ; stars from prefix only
21555 ((equal stars "") "*") ; before first heading
21556 (org-odd-levels-only "**") ; inside heading, odd
21557 (t "*"))) ; inside heading, oddeven
21558 (rpl (concat stars add-stars " "))
21559 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21560 (while (< (point) (if (equal nstars '(4)) lend end))
21561 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21562 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21563 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21564 (forward-line)))))))
21565 (unless toggled (message "Cannot toggle heading from here"))))
21567 (defun org-meta-return (&optional _arg)
21568 "Insert a new heading or wrap a region in a table.
21569 Calls `org-insert-heading' or `org-table-wrap-region', depending
21570 on context. See the individual commands for more information."
21571 (interactive)
21572 (org-check-before-invisible-edit 'insert)
21573 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21574 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21575 #'org-insert-heading))))
21577 ;;; Menu entries
21579 (defsubst org-in-subtree-not-table-p ()
21580 "Are we in a subtree and not in a table?"
21581 (and (not (org-before-first-heading-p))
21582 (not (org-at-table-p))))
21584 ;; Define the Org-mode menus
21585 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21586 '("Tbl"
21587 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21588 ["Next Field" org-cycle (org-at-table-p)]
21589 ["Previous Field" org-shifttab (org-at-table-p)]
21590 ["Next Row" org-return (org-at-table-p)]
21591 "--"
21592 ["Blank Field" org-table-blank-field (org-at-table-p)]
21593 ["Edit Field" org-table-edit-field (org-at-table-p)]
21594 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21595 "--"
21596 ("Column"
21597 ["Move Column Left" org-metaleft (org-at-table-p)]
21598 ["Move Column Right" org-metaright (org-at-table-p)]
21599 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21600 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21601 ("Row"
21602 ["Move Row Up" org-metaup (org-at-table-p)]
21603 ["Move Row Down" org-metadown (org-at-table-p)]
21604 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21605 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21606 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21607 "--"
21608 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21609 ("Rectangle"
21610 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21611 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21612 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21613 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21614 "--"
21615 ("Calculate"
21616 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21617 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21618 ["Edit Formulas" org-edit-special (org-at-table-p)]
21619 "--"
21620 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21621 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21622 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21623 "--"
21624 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21625 "--"
21626 ["Sum Column/Rectangle" org-table-sum
21627 (or (org-at-table-p) (org-region-active-p))]
21628 ["Which Column?" org-table-current-column (org-at-table-p)])
21629 ["Debug Formulas"
21630 org-table-toggle-formula-debugger
21631 :style toggle :selected (bound-and-true-p org-table-formula-debug)]
21632 ["Show Col/Row Numbers"
21633 org-table-toggle-coordinate-overlays
21634 :style toggle
21635 :selected (bound-and-true-p org-table-overlay-coordinates)]
21636 "--"
21637 ["Create" org-table-create (and (not (org-at-table-p))
21638 org-enable-table-editor)]
21639 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21640 ["Import from File" org-table-import (not (org-at-table-p))]
21641 ["Export to File" org-table-export (org-at-table-p)]
21642 "--"
21643 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21644 "--"
21645 ("Plot"
21646 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21647 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21649 (easy-menu-define org-org-menu org-mode-map "Org menu"
21650 '("Org"
21651 ("Show/Hide"
21652 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21653 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21654 ["Sparse Tree..." org-sparse-tree t]
21655 ["Reveal Context" org-reveal t]
21656 ["Show All" outline-show-all t]
21657 "--"
21658 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21659 "--"
21660 ["New Heading" org-insert-heading t]
21661 ("Navigate Headings"
21662 ["Up" outline-up-heading t]
21663 ["Next" outline-next-visible-heading t]
21664 ["Previous" outline-previous-visible-heading t]
21665 ["Next Same Level" outline-forward-same-level t]
21666 ["Previous Same Level" outline-backward-same-level t]
21667 "--"
21668 ["Jump" org-goto t])
21669 ("Edit Structure"
21670 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21671 "--"
21672 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21673 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21674 "--"
21675 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21676 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21677 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21678 "--"
21679 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21680 "--"
21681 ["Copy visible text" org-copy-visible t]
21682 "--"
21683 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21684 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21685 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21686 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21687 "--"
21688 ["Sort Region/Children" org-sort t]
21689 "--"
21690 ["Convert to odd levels" org-convert-to-odd-levels t]
21691 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21692 ("Editing"
21693 ["Emphasis..." org-emphasize t]
21694 ["Edit Source Example" org-edit-special t]
21695 "--"
21696 ["Footnote new/jump" org-footnote-action t]
21697 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21698 ("Archive"
21699 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21700 "--"
21701 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21702 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21703 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21705 "--"
21706 ("Hyperlinks"
21707 ["Store Link (Global)" org-store-link t]
21708 ["Find existing link to here" org-occur-link-in-agenda-files t]
21709 ["Insert Link" org-insert-link t]
21710 ["Follow Link" org-open-at-point t]
21711 "--"
21712 ["Next link" org-next-link t]
21713 ["Previous link" org-previous-link t]
21714 "--"
21715 ["Descriptive Links"
21716 org-toggle-link-display
21717 :style radio
21718 :selected org-descriptive-links
21720 ["Literal Links"
21721 org-toggle-link-display
21722 :style radio
21723 :selected (not org-descriptive-links)])
21724 "--"
21725 ("TODO Lists"
21726 ["TODO/DONE/-" org-todo t]
21727 ("Select keyword"
21728 ["Next keyword" org-shiftright (org-at-heading-p)]
21729 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21730 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21731 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21732 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21733 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21734 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21735 "--"
21736 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21737 :selected org-enforce-todo-dependencies :style toggle :active t]
21738 "Settings for tree at point"
21739 ["Do Children sequentially" org-toggle-ordered-property :style radio
21740 :selected (org-entry-get nil "ORDERED")
21741 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21742 ["Do Children parallel" org-toggle-ordered-property :style radio
21743 :selected (not (org-entry-get nil "ORDERED"))
21744 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21745 "--"
21746 ["Set Priority" org-priority t]
21747 ["Priority Up" org-shiftup t]
21748 ["Priority Down" org-shiftdown t]
21749 "--"
21750 ["Get news from all feeds" org-feed-update-all t]
21751 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21752 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21753 ("TAGS and Properties"
21754 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21755 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21756 "--"
21757 ["Set property" org-set-property (not (org-before-first-heading-p))]
21758 ["Column view of properties" org-columns t]
21759 ["Insert Column View DBlock" org-columns-insert-dblock t])
21760 ("Dates and Scheduling"
21761 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21762 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21763 ("Change Date"
21764 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21765 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21766 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21767 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21768 ["Compute Time Range" org-evaluate-time-range t]
21769 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21770 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21771 "--"
21772 ["Custom time format" org-toggle-time-stamp-overlays
21773 :style radio :selected org-display-custom-times]
21774 "--"
21775 ["Goto Calendar" org-goto-calendar t]
21776 ["Date from Calendar" org-date-from-calendar t]
21777 "--"
21778 ["Start/Restart Timer" org-timer-start t]
21779 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21780 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21781 ["Insert Timer String" org-timer t]
21782 ["Insert Timer Item" org-timer-item t])
21783 ("Logging work"
21784 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21785 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21786 ["Clock out" org-clock-out t]
21787 ["Clock cancel" org-clock-cancel t]
21788 "--"
21789 ["Mark as default task" org-clock-mark-default-task t]
21790 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21791 ["Goto running clock" org-clock-goto t]
21792 "--"
21793 ["Display times" org-clock-display t]
21794 ["Create clock table" org-clock-report t]
21795 "--"
21796 ["Record DONE time"
21797 (progn (setq org-log-done (not org-log-done))
21798 (message "Switching to %s will %s record a timestamp"
21799 (car org-done-keywords)
21800 (if org-log-done "automatically" "not")))
21801 :style toggle :selected org-log-done])
21802 "--"
21803 ["Agenda Command..." org-agenda t]
21804 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21805 ("File List for Agenda")
21806 ("Special views current file"
21807 ["TODO Tree" org-show-todo-tree t]
21808 ["Check Deadlines" org-check-deadlines t]
21809 ["Timeline" org-timeline t]
21810 ["Tags/Property tree" org-match-sparse-tree t])
21811 "--"
21812 ["Export/Publish..." org-export-dispatch t]
21813 ("LaTeX"
21814 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21815 :selected org-cdlatex-mode]
21816 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21817 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21818 ["Modify math symbol" org-cdlatex-math-modify
21819 (org-inside-LaTeX-fragment-p)]
21820 ["Insert citation" org-reftex-citation t])
21821 "--"
21822 ("MobileOrg"
21823 ["Push Files and Views" org-mobile-push t]
21824 ["Get Captured and Flagged" org-mobile-pull t]
21825 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21826 "--"
21827 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21828 "--"
21829 ("Documentation"
21830 ["Show Version" org-version t]
21831 ["Info Documentation" org-info t])
21832 ("Customize"
21833 ["Browse Org Group" org-customize t]
21834 "--"
21835 ["Expand This Menu" org-create-customize-menu
21836 (fboundp 'customize-menu-create)])
21837 ["Send bug report" org-submit-bug-report t]
21838 "--"
21839 ("Refresh/Reload"
21840 ["Refresh setup current buffer" org-mode-restart t]
21841 ["Reload Org (after update)" org-reload t]
21842 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21845 (defun org-info (&optional node)
21846 "Read documentation for Org-mode in the info system.
21847 With optional NODE, go directly to that node."
21848 (interactive)
21849 (info (format "(org)%s" (or node ""))))
21851 ;;;###autoload
21852 (defun org-submit-bug-report ()
21853 "Submit a bug report on Org-mode via mail.
21855 Don't hesitate to report any problems or inaccurate documentation.
21857 If you don't have setup sending mail from (X)Emacs, please copy the
21858 output buffer into your mail program, as it gives us important
21859 information about your Org-mode version and configuration."
21860 (interactive)
21861 (require 'reporter)
21862 (defvar reporter-prompt-for-summary-p)
21863 (org-load-modules-maybe)
21864 (org-require-autoloaded-modules)
21865 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21866 (reporter-submit-bug-report
21867 "emacs-orgmode@gnu.org"
21868 (org-version nil 'full)
21869 (let (list)
21870 (save-window-excursion
21871 (pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21872 (delete-other-windows)
21873 (erase-buffer)
21874 (insert "You are about to submit a bug report to the Org-mode mailing list.
21876 We would like to add your full Org-mode and Outline configuration to the
21877 bug report. This greatly simplifies the work of the maintainer and
21878 other experts on the mailing list.
21880 HOWEVER, some variables you have customized may contain private
21881 information. The names of customers, colleagues, or friends, might
21882 appear in the form of file names, tags, todo states, or search strings.
21883 If you answer yes to the prompt, you might want to check and remove
21884 such private information before sending the email.")
21885 (add-text-properties (point-min) (point-max) '(face org-warning))
21886 (when (yes-or-no-p "Include your Org-mode configuration ")
21887 (mapatoms
21888 (lambda (v)
21889 (and (boundp v)
21890 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21891 (or (and (symbol-value v)
21892 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21893 (and
21894 (get v 'custom-type) (get v 'standard-value)
21895 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21896 (push v list)))))
21897 (kill-buffer (get-buffer "*Warn about privacy*"))
21898 list))
21899 nil nil
21900 "Remember to cover the basics, that is, what you expected to happen and
21901 what in fact did happen. You don't know how to make a good report? See
21903 http://orgmode.org/manual/Feedback.html#Feedback
21905 Your bug report will be posted to the Org-mode mailing list.
21906 ------------------------------------------------------------------------")
21907 (save-excursion
21908 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21909 (replace-match "\\1Bug: \\3 [\\2]")))))
21912 (defun org-install-agenda-files-menu ()
21913 (let ((bl (buffer-list)))
21914 (save-excursion
21915 (while bl
21916 (set-buffer (pop bl))
21917 (when (derived-mode-p 'org-mode) (setq bl nil)))
21918 (when (derived-mode-p 'org-mode)
21919 (easy-menu-change
21920 '("Org") "File List for Agenda"
21921 (append
21922 (list
21923 ["Edit File List" (org-edit-agenda-file-list) t]
21924 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21925 ["Remove Current File from List" org-remove-file t]
21926 ["Cycle through agenda files" org-cycle-agenda-files t]
21927 ["Occur in all agenda files" org-occur-in-agenda-files t]
21928 "--")
21929 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21931 ;;;; Documentation
21933 (defun org-require-autoloaded-modules ()
21934 (interactive)
21935 (mapc #'require
21936 '(org-agenda org-archive org-attach org-clock org-colview org-id
21937 org-table org-timer)))
21939 ;;;###autoload
21940 (defun org-reload (&optional uncompiled)
21941 "Reload all org lisp files.
21942 With prefix arg UNCOMPILED, load the uncompiled versions."
21943 (interactive "P")
21944 (require 'loadhist)
21945 (let* ((org-dir (org-find-library-dir "org"))
21946 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21947 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21948 (remove-re (format "\\`%s\\'"
21949 (regexp-opt '("org" "org-loaddefs" "org-version"))))
21950 (feats (delete-dups
21951 (mapcar 'file-name-sans-extension
21952 (mapcar 'file-name-nondirectory
21953 (delq nil
21954 (mapcar 'feature-file
21955 features))))))
21956 (lfeat (append
21957 (sort
21958 (setq feats
21959 (delq nil (mapcar
21960 (lambda (f)
21961 (if (and (string-match feature-re f)
21962 (not (string-match remove-re f)))
21963 f nil))
21964 feats)))
21965 'string-lessp)
21966 (list "org-version" "org")))
21967 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
21968 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
21969 load-uncore load-misses)
21970 (setq load-misses
21971 (delq 't
21972 (mapcar (lambda (f)
21973 (or (org-load-noerror-mustsuffix (concat org-dir f))
21974 (and (string= org-dir contrib-dir)
21975 (org-load-noerror-mustsuffix (concat contrib-dir f)))
21976 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
21977 (add-to-list 'load-uncore f 'append)
21980 lfeat)))
21981 (when load-uncore
21982 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
21983 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
21984 (if load-misses
21985 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
21986 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
21987 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
21989 ;;;###autoload
21990 (defun org-customize ()
21991 "Call the customize function with org as argument."
21992 (interactive)
21993 (org-load-modules-maybe)
21994 (org-require-autoloaded-modules)
21995 (customize-browse 'org))
21997 (defun org-create-customize-menu ()
21998 "Create a full customization menu for Org-mode, insert it into the menu."
21999 (interactive)
22000 (org-load-modules-maybe)
22001 (org-require-autoloaded-modules)
22002 (if (fboundp 'customize-menu-create)
22003 (progn
22004 (easy-menu-change
22005 '("Org") "Customize"
22006 `(["Browse Org group" org-customize t]
22007 "--"
22008 ,(customize-menu-create 'org)
22009 ["Set" Custom-set t]
22010 ["Save" Custom-save t]
22011 ["Reset to Current" Custom-reset-current t]
22012 ["Reset to Saved" Custom-reset-saved t]
22013 ["Reset to Standard Settings" Custom-reset-standard t]))
22014 (message "\"Org\"-menu now contains full customization menu"))
22015 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22017 ;;;; Miscellaneous stuff
22019 ;;; Generally useful functions
22021 (defun org-get-at-eol (property n)
22022 "Get text property PROPERTY at the end of line less N characters."
22023 (get-text-property (- (point-at-eol) n) property))
22025 (defun org-find-text-property-in-string (prop s)
22026 "Return the first non-nil value of property PROP in string S."
22027 (or (get-text-property 0 prop s)
22028 (get-text-property (or (next-single-property-change 0 prop s) 0)
22029 prop s)))
22031 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22032 "Display the given MESSAGE as a warning."
22033 (if (fboundp 'display-warning)
22034 (display-warning 'org message :warning)
22035 (let ((buf (get-buffer-create "*Org warnings*")))
22036 (with-current-buffer buf
22037 (goto-char (point-max))
22038 (insert "Warning (Org): " message)
22039 (unless (bolp)
22040 (newline)))
22041 (display-buffer buf)
22042 (sit-for 0))))
22044 (defun org-eval (form)
22045 "Eval FORM and return result."
22046 (condition-case error
22047 (eval form)
22048 (error (format "%%![Error: %s]" error))))
22050 (defun org-in-clocktable-p ()
22051 "Check if the cursor is in a clocktable."
22052 (let ((pos (point)) start)
22053 (save-excursion
22054 (end-of-line 1)
22055 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22056 (setq start (match-beginning 0))
22057 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22058 (>= (match-end 0) pos)
22059 start))))
22061 (defun org-in-verbatim-emphasis ()
22062 (save-match-data
22063 (and (org-in-regexp org-emph-re 2)
22064 (>= (point) (match-beginning 3))
22065 (<= (point) (match-end 4))
22066 (member (match-string 3) '("=" "~")))))
22068 (defun org-overlay-display (ovl text &optional face evap)
22069 "Make overlay OVL display TEXT with face FACE."
22070 (overlay-put ovl 'display text)
22071 (if face (overlay-put ovl 'face face))
22072 (if evap (overlay-put ovl 'evaporate t)))
22074 (defun org-overlay-before-string (ovl text &optional face evap)
22075 "Make overlay OVL display TEXT with face FACE."
22076 (if face (org-add-props text nil 'face face))
22077 (overlay-put ovl 'before-string text)
22078 (if evap (overlay-put ovl 'evaporate t)))
22080 (defun org-find-overlays (prop &optional pos delete)
22081 "Find all overlays specifying PROP at POS or point.
22082 If DELETE is non-nil, delete all those overlays."
22083 (let (found)
22084 (dolist (ov (overlays-at (or pos (point))) found)
22085 (cond ((not (overlay-get ov prop)))
22086 (delete (delete-overlay ov))
22087 (t (push ov found))))))
22089 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22090 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22091 (if (and marker (marker-buffer marker)
22092 (buffer-live-p (marker-buffer marker)))
22093 (progn
22094 (pop-to-buffer-same-window (marker-buffer marker))
22095 (when (or (> marker (point-max)) (< marker (point-min)))
22096 (widen))
22097 (goto-char marker)
22098 (org-show-context 'org-goto))
22099 (if bookmark
22100 (bookmark-jump bookmark)
22101 (error "Cannot find location"))))
22103 (defun org-quote-csv-field (s)
22104 "Quote field for inclusion in CSV material."
22105 (if (string-match "[\",]" s)
22106 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22109 (defun org-force-self-insert (N)
22110 "Needed to enforce self-insert under remapping."
22111 (interactive "p")
22112 (self-insert-command N))
22114 (defun org-string-width (s)
22115 "Compute width of string, ignoring invisible characters.
22116 This ignores character with invisibility property `org-link', and also
22117 characters with property `org-cwidth', because these will become invisible
22118 upon the next fontification round."
22119 (let (b l)
22120 (when (or (eq t buffer-invisibility-spec)
22121 (assq 'org-link buffer-invisibility-spec))
22122 (while (setq b (text-property-any 0 (length s)
22123 'invisible 'org-link s))
22124 (setq s (concat (substring s 0 b)
22125 (substring s (or (next-single-property-change
22126 b 'invisible s)
22127 (length s)))))))
22128 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22129 (setq s (concat (substring s 0 b)
22130 (substring s (or (next-single-property-change
22131 b 'org-cwidth s)
22132 (length s))))))
22133 (setq l (string-width s) b -1)
22134 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22135 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22138 (defun org-shorten-string (s maxlength)
22139 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22140 If the string is shorter or has length MAXLENGTH, just return the
22141 original string. If it is longer, the functions finds a space in the
22142 string, breaks this string off at that locations and adds three dots
22143 as ellipsis. Including the ellipsis, the string will not be longer
22144 than MAXLENGTH. If finding a good breaking point in the string does
22145 not work, the string is just chopped off in the middle of a word
22146 if necessary."
22147 (if (<= (length s) maxlength)
22149 (let* ((n (max (- maxlength 4) 1))
22150 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22151 (if (string-match re s)
22152 (concat (match-string 1 s) "...")
22153 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22155 (defun org-get-indentation (&optional line)
22156 "Get the indentation of the current line, interpreting tabs.
22157 When LINE is given, assume it represents a line and compute its indentation."
22158 (if line
22159 (when (string-match "^ *" (org-remove-tabs line))
22160 (match-end 0))
22161 (save-excursion
22162 (beginning-of-line 1)
22163 (skip-chars-forward " \t")
22164 (current-column))))
22166 (defun org-get-string-indentation (s)
22167 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22168 (let ((n -1) (i 0) (w tab-width) c)
22169 (catch 'exit
22170 (while (< (setq n (1+ n)) (length s))
22171 (setq c (aref s n))
22172 (cond ((= c ?\ ) (setq i (1+ i)))
22173 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22174 (t (throw 'exit t)))))
22177 (defun org-remove-tabs (s &optional width)
22178 "Replace tabulators in S with spaces.
22179 Assumes that s is a single line, starting in column 0."
22180 (setq width (or width tab-width))
22181 (while (string-match "\t" s)
22182 (setq s (replace-match
22183 (make-string
22184 (- (* width (/ (+ (match-beginning 0) width) width))
22185 (match-beginning 0)) ?\ )
22186 t t s)))
22189 (defun org-fix-indentation (line ind)
22190 "Fix indentation in LINE.
22191 IND is a cons cell with target and minimum indentation.
22192 If the current indentation in LINE is smaller than the minimum,
22193 leave it alone. If it is larger than ind, set it to the target."
22194 (let* ((l (org-remove-tabs line))
22195 (i (org-get-indentation l))
22196 (i1 (car ind)) (i2 (cdr ind)))
22197 (when (>= i i2) (setq l (substring line i2)))
22198 (if (> i1 0)
22199 (concat (make-string i1 ?\ ) l)
22200 l)))
22202 (defun org-remove-indentation (code &optional n)
22203 "Remove maximum common indentation in string CODE and return it.
22204 N may optionally be the number of columns to remove. Return CODE
22205 as-is if removal failed."
22206 (with-temp-buffer
22207 (insert code)
22208 (if (org-do-remove-indentation n) (buffer-string) code)))
22210 (defun org-do-remove-indentation (&optional n)
22211 "Remove the maximum common indentation from the buffer.
22212 When optional argument N is a positive integer, remove exactly
22213 that much characters from indentation, if possible. Return nil
22214 if it fails."
22215 (catch :exit
22216 (goto-char (point-min))
22217 ;; Find maximum common indentation, if not specified.
22218 (let ((n (or n
22219 (let ((min-ind (point-max)))
22220 (save-excursion
22221 (while (re-search-forward "^[ \t]*\\S-" nil t)
22222 (let ((ind (1- (current-column))))
22223 (if (zerop ind) (throw :exit nil)
22224 (setq min-ind (min min-ind ind))))))
22225 min-ind))))
22226 (if (zerop n) (throw :exit nil)
22227 ;; Remove exactly N indentation, but give up if not possible.
22228 (while (not (eobp))
22229 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22230 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22231 ((< ind n) (throw :exit nil))
22232 (t (indent-line-to (- ind n))))
22233 (forward-line)))
22234 ;; Signal success.
22235 t))))
22237 (defun org-fill-template (template alist)
22238 "Find each %key of ALIST in TEMPLATE and replace it."
22239 (let ((case-fold-search nil))
22240 (dolist (entry (sort (copy-sequence alist)
22241 (lambda (a b) (< (length (car a)) (length (car b))))))
22242 (setq template
22243 (replace-regexp-in-string
22244 (concat "%" (regexp-quote (car entry)))
22245 (or (cdr entry) "") template t t)))
22246 template))
22248 (defun org-base-buffer (buffer)
22249 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22250 (if (not buffer)
22251 buffer
22252 (or (buffer-base-buffer buffer)
22253 buffer)))
22255 (defun org-wrap (string &optional width lines)
22256 "Wrap string to either a number of lines, or a width in characters.
22257 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22258 that costs. If there is a word longer than WIDTH, the text is actually
22259 wrapped to the length of that word.
22260 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22261 many lines, whatever width that takes.
22262 The return value is a list of lines, without newlines at the end."
22263 (let* ((words (org-split-string string "[ \t\n]+"))
22264 (maxword (apply 'max (mapcar 'org-string-width words)))
22265 w ll)
22266 (cond (width
22267 (org-do-wrap words (max maxword width)))
22268 (lines
22269 (setq w maxword)
22270 (setq ll (org-do-wrap words maxword))
22271 (if (<= (length ll) lines)
22273 (setq ll words)
22274 (while (> (length ll) lines)
22275 (setq w (1+ w))
22276 (setq ll (org-do-wrap words w)))
22277 ll))
22278 (t (error "Cannot wrap this")))))
22280 (defun org-do-wrap (words width)
22281 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22282 (let (lines line)
22283 (while words
22284 (setq line (pop words))
22285 (while (and words (< (+ (length line) (length (car words))) width))
22286 (setq line (concat line " " (pop words))))
22287 (setq lines (push line lines)))
22288 (nreverse lines)))
22290 (defun org-split-string (string &optional separators)
22291 "Splits STRING into substrings at SEPARATORS.
22292 SEPARATORS is a regular expression.
22293 No empty strings are returned if there are matches at the beginning
22294 and end of string."
22295 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22296 (let ((start 0) notfirst list)
22297 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22298 (if (and notfirst
22299 (= start (match-beginning 0))
22300 (< start (length string)))
22301 (1+ start) start))
22302 (< (match-beginning 0) (length string)))
22303 (setq notfirst t)
22304 (or (eq (match-beginning 0) 0)
22305 (and (eq (match-beginning 0) (match-end 0))
22306 (eq (match-beginning 0) start))
22307 (push (substring string start (match-beginning 0)) list))
22308 (setq start (match-end 0)))
22309 (or (eq start (length string))
22310 (push (substring string start) list))
22311 (nreverse list)))
22313 (defun org-quote-vert (s)
22314 "Replace \"|\" with \"\\vert\"."
22315 (while (string-match "|" s)
22316 (setq s (replace-match "\\vert" t t s)))
22319 (defun org-uuidgen-p (s)
22320 "Is S an ID created by UUIDGEN?"
22321 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22323 (defun org-in-src-block-p (&optional inside)
22324 "Whether point is in a code source block.
22325 When INSIDE is non-nil, don't consider we are within a src block
22326 when point is at #+BEGIN_SRC or #+END_SRC."
22327 (let ((case-fold-search t))
22328 (or (and (eq (get-char-property (point) 'src-block) t))
22329 (and (not inside)
22330 (save-match-data
22331 (save-excursion
22332 (beginning-of-line)
22333 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22335 (defun org-context ()
22336 "Return a list of contexts of the current cursor position.
22337 If several contexts apply, all are returned.
22338 Each context entry is a list with a symbol naming the context, and
22339 two positions indicating start and end of the context. Possible
22340 contexts are:
22342 :headline anywhere in a headline
22343 :headline-stars on the leading stars in a headline
22344 :todo-keyword on a TODO keyword (including DONE) in a headline
22345 :tags on the TAGS in a headline
22346 :priority on the priority cookie in a headline
22347 :item on the first line of a plain list item
22348 :item-bullet on the bullet/number of a plain list item
22349 :checkbox on the checkbox in a plain list item
22350 :table in an org-mode table
22351 :table-special on a special filed in a table
22352 :table-table in a table.el table
22353 :clocktable in a clocktable
22354 :src-block in a source block
22355 :link on a hyperlink
22356 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22357 :target on a <<target>>
22358 :radio-target on a <<<radio-target>>>
22359 :latex-fragment on a LaTeX fragment
22360 :latex-preview on a LaTeX fragment with overlaid preview image
22362 This function expects the position to be visible because it uses font-lock
22363 faces as a help to recognize the following contexts: :table-special, :link,
22364 and :keyword."
22365 (let* ((f (get-text-property (point) 'face))
22366 (faces (if (listp f) f (list f)))
22367 (case-fold-search t)
22368 (p (point)) clist o)
22369 ;; First the large context
22370 (cond
22371 ((org-at-heading-p t)
22372 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22373 (when (progn
22374 (beginning-of-line 1)
22375 (looking-at org-todo-line-tags-regexp))
22376 (push (org-point-in-group p 1 :headline-stars) clist)
22377 (push (org-point-in-group p 2 :todo-keyword) clist)
22378 (push (org-point-in-group p 4 :tags) clist))
22379 (goto-char p)
22380 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22381 (when (looking-at "\\[#[A-Z0-9]\\]")
22382 (push (org-point-in-group p 0 :priority) clist)))
22384 ((org-at-item-p)
22385 (push (org-point-in-group p 2 :item-bullet) clist)
22386 (push (list :item (point-at-bol)
22387 (save-excursion (org-end-of-item) (point)))
22388 clist)
22389 (and (org-at-item-checkbox-p)
22390 (push (org-point-in-group p 0 :checkbox) clist)))
22392 ((org-at-table-p)
22393 (push (list :table (org-table-begin) (org-table-end)) clist)
22394 (when (memq 'org-formula faces)
22395 (push (list :table-special
22396 (previous-single-property-change p 'face)
22397 (next-single-property-change p 'face)) clist)))
22398 ((org-at-table-p 'any)
22399 (push (list :table-table) clist)))
22400 (goto-char p)
22402 (let ((case-fold-search t))
22403 ;; New the "medium" contexts: clocktables, source blocks
22404 (cond ((org-in-clocktable-p)
22405 (push (list :clocktable
22406 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22407 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22408 (match-beginning 1))
22409 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22410 (match-end 0))) clist))
22411 ((org-in-src-block-p)
22412 (push (list :src-block
22413 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22414 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22415 (match-beginning 1))
22416 (and (search-forward "#+END_SRC" nil t)
22417 (match-beginning 0))) clist))))
22418 (goto-char p)
22420 ;; Now the small context
22421 (cond
22422 ((org-at-timestamp-p)
22423 (push (org-point-in-group p 0 :timestamp) clist))
22424 ((memq 'org-link faces)
22425 (push (list :link
22426 (previous-single-property-change p 'face)
22427 (next-single-property-change p 'face)) clist))
22428 ((memq 'org-special-keyword faces)
22429 (push (list :keyword
22430 (previous-single-property-change p 'face)
22431 (next-single-property-change p 'face)) clist))
22432 ((org-at-target-p)
22433 (push (org-point-in-group p 0 :target) clist)
22434 (goto-char (1- (match-beginning 0)))
22435 (when (looking-at org-radio-target-regexp)
22436 (push (org-point-in-group p 0 :radio-target) clist))
22437 (goto-char p))
22438 ((setq o (cl-some
22439 (lambda (o)
22440 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22442 (overlays-at (point))))
22443 (push (list :latex-fragment
22444 (overlay-start o) (overlay-end o)) clist)
22445 (push (list :latex-preview
22446 (overlay-start o) (overlay-end o)) clist))
22447 ((org-inside-LaTeX-fragment-p)
22448 ;; FIXME: positions wrong.
22449 (push (list :latex-fragment (point) (point)) clist)))
22451 (setq clist (nreverse (delq nil clist)))
22452 clist))
22454 (defun org-in-regexp (regexp &optional nlines visually)
22455 "Check if point is inside a match of REGEXP.
22457 Normally only the current line is checked, but you can include
22458 NLINES extra lines around point into the search. If VISUALLY is
22459 set, require that the cursor is not after the match but really
22460 on, so that the block visually is on the match.
22462 Return nil or a cons cell (BEG . END) where BEG and END are,
22463 respectively, the positions at the beginning and the end of the
22464 match."
22465 (catch :exit
22466 (let ((pos (point))
22467 (eol (line-end-position (if nlines (1+ nlines) 1))))
22468 (save-excursion
22469 (beginning-of-line (- 1 (or nlines 0)))
22470 (while (and (re-search-forward regexp eol t)
22471 (<= (match-beginning 0) pos))
22472 (let ((end (match-end 0)))
22473 (when (or (> end pos) (and (= end pos) (not visually)))
22474 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22476 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22477 "Non-nil when point is between matches of START-RE and END-RE.
22479 Also return a non-nil value when point is on one of the matches.
22481 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22482 buffer positions. Default values are the positions of headlines
22483 surrounding the point.
22485 The functions returns a cons cell whose car (resp. cdr) is the
22486 position before START-RE (resp. after END-RE)."
22487 (save-match-data
22488 (let ((pos (point))
22489 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22490 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22491 beg end)
22492 (save-excursion
22493 ;; Point is on a block when on START-RE or if START-RE can be
22494 ;; found before it...
22495 (and (or (org-in-regexp start-re)
22496 (re-search-backward start-re limit-up t))
22497 (setq beg (match-beginning 0))
22498 ;; ... and END-RE after it...
22499 (goto-char (match-end 0))
22500 (re-search-forward end-re limit-down t)
22501 (> (setq end (match-end 0)) pos)
22502 ;; ... without another START-RE in-between.
22503 (goto-char (match-beginning 0))
22504 (not (re-search-backward start-re (1+ beg) t))
22505 ;; Return value.
22506 (cons beg end))))))
22508 (defun org-in-block-p (names)
22509 "Non-nil when point belongs to a block whose name belongs to NAMES.
22511 NAMES is a list of strings containing names of blocks.
22513 Return first block name matched, or nil. Beware that in case of
22514 nested blocks, the returned name may not belong to the closest
22515 block from point."
22516 (save-match-data
22517 (catch 'exit
22518 (let ((case-fold-search t)
22519 (lim-up (save-excursion (outline-previous-heading)))
22520 (lim-down (save-excursion (outline-next-heading))))
22521 (dolist (name names)
22522 (let ((n (regexp-quote name)))
22523 (when (org-between-regexps-p
22524 (concat "^[ \t]*#\\+begin_" n)
22525 (concat "^[ \t]*#\\+end_" n)
22526 lim-up lim-down)
22527 (throw 'exit n)))))
22528 nil)))
22530 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22531 "Call `multi-occur' with buffers for all agenda files."
22532 (interactive "sOrg-files matching: ")
22533 (let* ((files (org-agenda-files))
22534 (tnames (mapcar #'file-truename files))
22535 (extra org-agenda-text-search-extra-files))
22536 (when (eq (car extra) 'agenda-archives)
22537 (setq extra (cdr extra))
22538 (setq files (org-add-archive-files files)))
22539 (dolist (f extra)
22540 (unless (member (file-truename f) tnames)
22541 (unless (member f files) (setq files (append files (list f))))
22542 (setq tnames (append tnames (list (file-truename f))))))
22543 (multi-occur
22544 (mapcar (lambda (x)
22545 (with-current-buffer
22546 ;; FIXME: Why not just (find-file-noselect x)?
22547 ;; Is it to avoid the "revert buffer" prompt?
22548 (or (get-file-buffer x) (find-file-noselect x))
22549 (widen)
22550 (current-buffer)))
22551 files)
22552 regexp)))
22554 (add-hook 'occur-mode-find-occurrence-hook
22555 (lambda () (when (derived-mode-p 'org-mode) (org-reveal))))
22557 (defun org-occur-link-in-agenda-files ()
22558 "Create a link and search for it in the agendas.
22559 The link is not stored in `org-stored-links', it is just created
22560 for the search purpose."
22561 (interactive)
22562 (let ((link (condition-case nil
22563 (org-store-link nil)
22564 (error "Unable to create a link to here"))))
22565 (org-occur-in-agenda-files (regexp-quote link))))
22567 (defun org-reverse-string (string)
22568 "Return the reverse of STRING."
22569 (apply 'string (reverse (string-to-list string))))
22571 ;; defsubst org-uniquify must be defined before first use
22573 (defun org-uniquify-alist (alist)
22574 "Merge elements of ALIST with the same key.
22576 For example, in this alist:
22578 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22579 => \\='((a 1 3) (b 2))
22581 merge (a 1) and (a 3) into (a 1 3).
22583 The function returns the new ALIST."
22584 (let (rtn)
22585 (dolist (e alist rtn)
22586 (let (n)
22587 (if (not (assoc (car e) rtn))
22588 (push e rtn)
22589 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22590 (setq rtn (assq-delete-all (car e) rtn))
22591 (push n rtn))))))
22593 (defun org-delete-all (elts list)
22594 "Remove all elements in ELTS from LIST.
22595 Comparison is done with `equal'. It is a destructive operation
22596 that may remove elements by altering the list structure."
22597 (while elts
22598 (setq list (delete (pop elts) list)))
22599 list)
22601 (defun org-back-over-empty-lines ()
22602 "Move backwards over whitespace, to the beginning of the first empty line.
22603 Returns the number of empty lines passed."
22604 (let ((pos (point)))
22605 (if (cdr (assoc 'heading org-blank-before-new-entry))
22606 (skip-chars-backward " \t\n\r")
22607 (unless (eobp)
22608 (forward-line -1)))
22609 (beginning-of-line 2)
22610 (goto-char (min (point) pos))
22611 (count-lines (point) pos)))
22613 (defun org-skip-whitespace ()
22614 (skip-chars-forward " \t\n\r"))
22616 (defun org-point-in-group (point group &optional context)
22617 "Check if POINT is in match-group GROUP.
22618 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22619 match. If the match group does not exist or point is not inside it,
22620 return nil."
22621 (and (match-beginning group)
22622 (>= point (match-beginning group))
22623 (<= point (match-end group))
22624 (if context
22625 (list context (match-beginning group) (match-end group))
22626 t)))
22628 (defun org-switch-to-buffer-other-window (&rest args)
22629 "Switch to buffer in a second window on the current frame.
22630 In particular, do not allow pop-up frames.
22631 Returns the newly created buffer."
22632 (org-no-popups
22633 (apply 'switch-to-buffer-other-window args)))
22635 (defun org-combine-plists (&rest plists)
22636 "Create a single property list from all plists in PLISTS.
22637 The process starts by copying the first list, and then setting properties
22638 from the other lists. Settings in the last list are the most significant
22639 ones and overrule settings in the other lists."
22640 (let ((rtn (copy-sequence (pop plists)))
22641 p v ls)
22642 (while plists
22643 (setq ls (pop plists))
22644 (while ls
22645 (setq p (pop ls) v (pop ls))
22646 (setq rtn (plist-put rtn p v))))
22647 rtn))
22649 (defun org-replace-escapes (string table)
22650 "Replace %-escapes in STRING with values in TABLE.
22651 TABLE is an association list with keys like \"%a\" and string values.
22652 The sequences in STRING may contain normal field width and padding information,
22653 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22654 so values can contain further %-escapes if they are define later in TABLE."
22655 (let ((tbl (copy-alist table))
22656 (case-fold-search nil)
22657 (pchg 0)
22658 re rpl)
22659 (dolist (e tbl)
22660 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22661 (when (and (cdr e) (string-match re (cdr e)))
22662 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22663 (safe "SREF"))
22664 (add-text-properties 0 3 (list 'sref sref) safe)
22665 (setcdr e (replace-match safe t t (cdr e)))))
22666 (while (string-match re string)
22667 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22668 (cdr e)))
22669 (setq string (replace-match rpl t t string))))
22670 (while (setq pchg (next-property-change pchg string))
22671 (let ((sref (get-text-property pchg 'sref string)))
22672 (when (and sref (string-match "SREF" string pchg))
22673 (setq string (replace-match sref t t string)))))
22674 string))
22676 (defun org-sublist (list start end)
22677 "Return a section of LIST, from START to END.
22679 Counting starts at 1."
22680 (cl-subseq list (1- start) end))
22681 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22683 (defun org-find-base-buffer-visiting (file)
22684 "Like `find-buffer-visiting' but always return the base buffer and
22685 not an indirect buffer."
22686 (let ((buf (or (get-file-buffer file)
22687 (find-buffer-visiting file))))
22688 (if buf
22689 (or (buffer-base-buffer buf) buf)
22690 nil)))
22692 ;;; TODO: Only called once, from ox-odt which should probably use
22693 ;;; org-export-inline-image-p or something.
22694 (defun org-file-image-p (file)
22695 "Return non-nil if FILE is an image."
22696 (save-match-data
22697 (string-match (image-file-name-regexp) file)))
22699 (defun org-get-cursor-date (&optional with-time)
22700 "Return the date at cursor in as a time.
22701 This works in the calendar and in the agenda, anywhere else it just
22702 returns the current time.
22703 If WITH-TIME is non-nil, returns the time of the event at point (in
22704 the agenda) or the current time of the day."
22705 (let (date day defd tp hod mod)
22706 (when with-time
22707 (setq tp (get-text-property (point) 'time))
22708 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22709 (setq hod (string-to-number (match-string 1 tp))
22710 mod (string-to-number (match-string 2 tp))))
22711 (or tp (let ((now (decode-time)))
22712 (setq hod (nth 2 now)
22713 mod (nth 1 now)))))
22714 (cond
22715 ((eq major-mode 'calendar-mode)
22716 (setq date (calendar-cursor-to-date)
22717 defd (encode-time 0 (or mod 0) (or hod 0)
22718 (nth 1 date) (nth 0 date) (nth 2 date))))
22719 ((eq major-mode 'org-agenda-mode)
22720 (setq day (get-text-property (point) 'day))
22721 (when day
22722 (setq date (calendar-gregorian-from-absolute day)
22723 defd (encode-time 0 (or mod 0) (or hod 0)
22724 (nth 1 date) (nth 0 date) (nth 2 date))))))
22725 (or defd (current-time))))
22727 (defun org-mark-subtree (&optional up)
22728 "Mark the current subtree.
22729 This puts point at the start of the current subtree, and mark at
22730 the end. If a numeric prefix UP is given, move up into the
22731 hierarchy of headlines by UP levels before marking the subtree."
22732 (interactive "P")
22733 (org-with-limited-levels
22734 (cond ((org-at-heading-p) (beginning-of-line))
22735 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22736 (t (outline-previous-visible-heading 1))))
22737 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22738 (if (called-interactively-p 'any)
22739 (call-interactively 'org-mark-element)
22740 (org-mark-element)))
22742 (defun org-file-newer-than-p (file time)
22743 "Non-nil if FILE is newer than TIME.
22744 FILE is a filename, as a string, TIME is a list of integers, as
22745 returned by, e.g., `current-time'."
22746 (and (file-exists-p file)
22747 ;; Only compare times up to whole seconds as some file-systems
22748 ;; (e.g. HFS+) do not retain any finer granularity. As
22749 ;; a consequence, make sure we return non-nil when the two
22750 ;; times are equal.
22751 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22752 (cl-subseq time 0 2)))))
22754 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22755 "Compile a SOURCE file using PROCESS.
22757 PROCESS is either a function or a list of shell commands, as
22758 strings. EXT is a file extension, without the leading dot, as
22759 a string. It is used to check if the process actually succeeded.
22761 PROCESS must create a file with the same base name and directory
22762 as SOURCE, but ending with EXT. The function then returns its
22763 filename. Otherwise, it raises an error. The error message can
22764 then be refined by providing string ERR-MSG, which is appended to
22765 the standard message.
22767 If PROCESS is a function, it is called with a single argument:
22768 the SOURCE file.
22770 If it is a list of commands, each of them is called using
22771 `shell-command'. By default, in each command, %b, %f, %F and %o
22772 are replaced with, respectively, SOURCE base name, name, full
22773 name and directory. It is possible, however, to use more
22774 place-holders by specifying them in optional argument SPEC, as an
22775 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22777 When PROCESS is a list of commands, optional argument LOG-BUF can
22778 be set to a buffer or a buffer name. `shell-command' then uses
22779 it for output.
22781 `default-directory' is set to SOURCE directory during the whole
22782 process."
22783 (let* ((source-name (file-name-nondirectory source))
22784 (base-name (file-name-sans-extension source-name))
22785 (full-name (file-truename source))
22786 (out-dir (file-name-directory source))
22787 (time (current-time))
22788 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22789 (save-window-excursion
22790 (let ((default-directory (file-name-directory full-name)))
22791 (pcase process
22792 ((pred functionp) (funcall process (shell-quote-argument source)))
22793 ((pred consp)
22794 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22795 (spec (append spec
22796 `((?b . ,(shell-quote-argument base-name))
22797 (?f . ,(shell-quote-argument source-name))
22798 (?F . ,(shell-quote-argument full-name))
22799 (?o . ,(shell-quote-argument out-dir))))))
22800 (dolist (command process)
22801 (shell-command (format-spec command spec) log-buf))))
22802 (_ (error "No valid command to process %S%s" source err-msg)))))
22803 ;; Check for process failure.
22804 (let ((output (concat out-dir base-name "." ext)))
22805 (unless (org-file-newer-than-p output time)
22806 (error (format "File %S wasn't produced%s" output err-msg)))
22807 output)))
22809 ;;; Indentation
22811 (defun org--get-expected-indentation (element contentsp)
22812 "Expected indentation column for current line, according to ELEMENT.
22813 ELEMENT is an element containing point. CONTENTSP is non-nil
22814 when indentation is to be computed according to contents of
22815 ELEMENT."
22816 (let ((type (org-element-type element))
22817 (start (org-element-property :begin element))
22818 (post-affiliated (org-element-property :post-affiliated element)))
22819 (org-with-wide-buffer
22820 (cond
22821 (contentsp
22822 (cl-case type
22823 ((diary-sexp footnote-definition) 0)
22824 ((headline inlinetask nil)
22825 (if (not org-adapt-indentation) 0
22826 (let ((level (org-current-level)))
22827 (if level (1+ level) 0))))
22828 ((item plain-list) (org-list-item-body-column post-affiliated))
22830 (goto-char start)
22831 (org-get-indentation))))
22832 ((memq type '(headline inlinetask nil))
22833 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22834 (org--get-expected-indentation element t)
22836 ((memq type '(diary-sexp footnote-definition)) 0)
22837 ;; First paragraph of a footnote definition or an item.
22838 ;; Indent like parent.
22839 ((< (line-beginning-position) start)
22840 (org--get-expected-indentation
22841 (org-element-property :parent element) t))
22842 ;; At first line: indent according to previous sibling, if any,
22843 ;; ignoring footnote definitions and inline tasks, or parent's
22844 ;; contents.
22845 ((= (line-beginning-position) start)
22846 (catch 'exit
22847 (while t
22848 (if (= (point-min) start) (throw 'exit 0)
22849 (goto-char (1- start))
22850 (let* ((previous (org-element-at-point))
22851 (parent previous))
22852 (while (and parent (<= (org-element-property :end parent) start))
22853 (setq previous parent
22854 parent (org-element-property :parent parent)))
22855 (cond
22856 ((not previous) (throw 'exit 0))
22857 ((> (org-element-property :end previous) start)
22858 (throw 'exit (org--get-expected-indentation previous t)))
22859 ((memq (org-element-type previous)
22860 '(footnote-definition inlinetask))
22861 (setq start (org-element-property :begin previous)))
22862 (t (goto-char (org-element-property :begin previous))
22863 (throw 'exit
22864 (if (bolp) (org-get-indentation)
22865 ;; At first paragraph in an item or
22866 ;; a footnote definition.
22867 (org--get-expected-indentation
22868 (org-element-property :parent previous) t))))))))))
22869 ;; Otherwise, move to the first non-blank line above.
22871 (beginning-of-line)
22872 (let ((pos (point)))
22873 (skip-chars-backward " \r\t\n")
22874 (cond
22875 ;; Two blank lines end a footnote definition or a plain
22876 ;; list. When we indent an empty line after them, the
22877 ;; containing list or footnote definition is over, so it
22878 ;; qualifies as a previous sibling. Therefore, we indent
22879 ;; like its first line.
22880 ((and (memq type '(footnote-definition plain-list))
22881 (> (count-lines (point) pos) 2))
22882 (goto-char start)
22883 (org-get-indentation))
22884 ;; Line above is the first one of a paragraph at the
22885 ;; beginning of an item or a footnote definition. Indent
22886 ;; like parent.
22887 ((< (line-beginning-position) start)
22888 (org--get-expected-indentation
22889 (org-element-property :parent element) t))
22890 ;; Line above is the beginning of an element, i.e., point
22891 ;; was originally on the blank lines between element's start
22892 ;; and contents.
22893 ((= (line-beginning-position) post-affiliated)
22894 (org--get-expected-indentation element t))
22895 ;; POS is after contents in a greater element. Indent like
22896 ;; the beginning of the element.
22898 ;; As a special case, if point is at the end of a footnote
22899 ;; definition or an item, indent like the very last element
22900 ;; within. If that last element is an item, indent like its
22901 ;; contents.
22902 ((and (not (eq type 'paragraph))
22903 (let ((cend (org-element-property :contents-end element)))
22904 (and cend (<= cend pos))))
22905 (if (memq type '(footnote-definition item plain-list))
22906 (let ((last (org-element-at-point)))
22907 (org--get-expected-indentation
22908 last (eq (org-element-type last) 'item)))
22909 (goto-char start)
22910 (org-get-indentation)))
22911 ;; In any other case, indent like the current line.
22912 (t (org-get-indentation)))))))))
22914 (defun org--align-node-property ()
22915 "Align node property at point.
22916 Alignment is done according to `org-property-format', which see."
22917 (when (save-excursion
22918 (beginning-of-line)
22919 (looking-at org-property-re))
22920 (replace-match
22921 (concat (match-string 4)
22922 (org-trim
22923 (format org-property-format (match-string 1) (match-string 3))))
22924 t t)))
22926 (defun org-indent-line ()
22927 "Indent line depending on context.
22929 Indentation is done according to the following rules:
22931 - Footnote definitions, diary sexps, headlines and inline tasks
22932 have to start at column 0.
22934 - On the very first line of an element, consider, in order, the
22935 next rules until one matches:
22937 1. If there's a sibling element before, ignoring footnote
22938 definitions and inline tasks, indent like its first line.
22940 2. If element has a parent, indent like its contents. More
22941 precisely, if parent is an item, indent after the
22942 description part, if any, or the bullet (see
22943 `org-list-description-max-indent'). Else, indent like
22944 parent's first line.
22946 3. Otherwise, indent relatively to current level, if
22947 `org-adapt-indentation' is non-nil, or to left margin.
22949 - On a blank line at the end of an element, indent according to
22950 the type of the element. More precisely
22952 1. If element is a plain list, an item, or a footnote
22953 definition, indent like the very last element within.
22955 2. If element is a paragraph, indent like its last non blank
22956 line.
22958 3. Otherwise, indent like its very first line.
22960 - In the code part of a source block, use language major mode
22961 to indent current line if `org-src-tab-acts-natively' is
22962 non-nil. If it is nil, do nothing.
22964 - Otherwise, indent like the first non-blank line above.
22966 The function doesn't indent an item as it could break the whole
22967 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22968 \\[org-shiftmetaright].
22970 Also align node properties according to `org-property-format'."
22971 (interactive)
22972 (cond
22973 (orgstruct-is-++
22974 (let ((indent-line-function
22975 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22976 (indent-according-to-mode)))
22977 ((org-at-heading-p) 'noindent)
22979 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22980 (type (org-element-type element)))
22981 (cond ((and (memq type '(plain-list item))
22982 (= (line-beginning-position)
22983 (org-element-property :post-affiliated element)))
22984 'noindent)
22985 ((and (eq type 'src-block)
22986 org-src-tab-acts-natively
22987 (> (line-beginning-position)
22988 (org-element-property :post-affiliated element))
22989 (< (line-beginning-position)
22990 (org-with-wide-buffer
22991 (goto-char (org-element-property :end element))
22992 (skip-chars-backward " \r\t\n")
22993 (line-beginning-position))))
22994 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22996 (let ((column (org--get-expected-indentation element nil)))
22997 ;; Preserve current column.
22998 (if (<= (current-column) (current-indentation))
22999 (indent-line-to column)
23000 (save-excursion (indent-line-to column))))
23001 ;; Align node property. Also preserve current column.
23002 (when (eq type 'node-property)
23003 (let ((column (current-column)))
23004 (org--align-node-property)
23005 (org-move-to-column column)))))))))
23007 (defun org-indent-region (start end)
23008 "Indent each non-blank line in the region.
23009 Called from a program, START and END specify the region to
23010 indent. The function will not indent contents of example blocks,
23011 verse blocks and export blocks as leading white spaces are
23012 assumed to be significant there."
23013 (interactive "r")
23014 (save-excursion
23015 (goto-char start)
23016 (skip-chars-forward " \r\t\n")
23017 (unless (eobp) (beginning-of-line))
23018 (let ((indent-to
23019 (lambda (ind pos)
23020 ;; Set IND as indentation for all lines between point and
23021 ;; POS. Blank lines are ignored. Leave point after POS
23022 ;; once done.
23023 (let ((limit (copy-marker pos)))
23024 (while (< (point) limit)
23025 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23026 (forward-line))
23027 (set-marker limit nil))))
23028 (end (copy-marker end)))
23029 (while (< (point) end)
23030 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23031 (let* ((element (org-element-at-point))
23032 (type (org-element-type element))
23033 (element-end (copy-marker (org-element-property :end element)))
23034 (ind (org--get-expected-indentation element nil)))
23035 (cond
23036 ((or (memq type '(paragraph table table-row))
23037 (not (or (org-element-property :contents-begin element)
23038 (memq type
23039 '(example-block export-block src-block)))))
23040 ;; Elements here are indented as a single block. Also
23041 ;; align node properties.
23042 (when (eq type 'node-property)
23043 (org--align-node-property)
23044 (beginning-of-line))
23045 (funcall indent-to ind (min element-end end)))
23047 ;; Elements in this category consist of three parts:
23048 ;; before the contents, the contents, and after the
23049 ;; contents. The contents are treated specially,
23050 ;; according to the element type, or not indented at
23051 ;; all. Other parts are indented as a single block.
23052 (let* ((post (copy-marker
23053 (org-element-property :post-affiliated element)))
23054 (cbeg
23055 (copy-marker
23056 (cond
23057 ((not (org-element-property :contents-begin element))
23058 ;; Fake contents for source blocks.
23059 (org-with-wide-buffer
23060 (goto-char post)
23061 (forward-line)
23062 (point)))
23063 ((memq type '(footnote-definition item plain-list))
23064 ;; Contents in these elements could start on
23065 ;; the same line as the beginning of the
23066 ;; element. Make sure we start indenting
23067 ;; from the second line.
23068 (org-with-wide-buffer
23069 (goto-char post)
23070 (end-of-line)
23071 (skip-chars-forward " \r\t\n")
23072 (if (eobp) (point) (line-beginning-position))))
23073 (t (org-element-property :contents-begin element)))))
23074 (cend (copy-marker
23075 (or (org-element-property :contents-end element)
23076 ;; Fake contents for source blocks.
23077 (org-with-wide-buffer
23078 (goto-char element-end)
23079 (skip-chars-backward " \r\t\n")
23080 (line-beginning-position)))
23081 t)))
23082 ;; Do not change items indentation individually as it
23083 ;; might break the list as a whole. On the other
23084 ;; hand, when at a plain list, indent it as a whole.
23085 (cond ((eq type 'plain-list)
23086 (let ((offset (- ind (org-get-indentation))))
23087 (unless (zerop offset)
23088 (indent-rigidly (org-element-property :begin element)
23089 (org-element-property :end element)
23090 offset))
23091 (goto-char cbeg)))
23092 ((eq type 'item) (goto-char cbeg))
23093 (t (funcall indent-to ind (min cbeg end))))
23094 (when (< (point) end)
23095 (cl-case type
23096 ((example-block export-block verse-block))
23097 (src-block
23098 ;; In a source block, indent source code
23099 ;; according to language major mode, but only if
23100 ;; `org-src-tab-acts-natively' is non-nil.
23101 (when (and (< (point) end) org-src-tab-acts-natively)
23102 (ignore-errors
23103 (org-babel-do-in-edit-buffer
23104 (indent-region (point-min) (point-max))))))
23105 (t (org-indent-region (point) (min cend end))))
23106 (goto-char (min cend end))
23107 (when (< (point) end)
23108 (funcall indent-to ind (min element-end end))))
23109 (set-marker post nil)
23110 (set-marker cbeg nil)
23111 (set-marker cend nil))))
23112 (set-marker element-end nil))))
23113 (set-marker end nil))))
23115 (defun org-indent-drawer ()
23116 "Indent the drawer at point."
23117 (interactive)
23118 (unless (save-excursion
23119 (beginning-of-line)
23120 (looking-at-p org-drawer-regexp))
23121 (user-error "Not at a drawer"))
23122 (let ((element (org-element-at-point)))
23123 (unless (memq (org-element-type element) '(drawer property-drawer))
23124 (user-error "Not at a drawer"))
23125 (org-with-wide-buffer
23126 (org-indent-region (org-element-property :begin element)
23127 (org-element-property :end element))))
23128 (message "Drawer at point indented"))
23130 (defun org-indent-block ()
23131 "Indent the block at point."
23132 (interactive)
23133 (unless (save-excursion
23134 (beginning-of-line)
23135 (let ((case-fold-search t))
23136 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23137 (user-error "Not at a block"))
23138 (let ((element (org-element-at-point)))
23139 (unless (memq (org-element-type element)
23140 '(comment-block center-block dynamic-block example-block
23141 export-block quote-block special-block
23142 src-block verse-block))
23143 (user-error "Not at a block"))
23144 (org-with-wide-buffer
23145 (org-indent-region (org-element-property :begin element)
23146 (org-element-property :end element))))
23147 (message "Block at point indented"))
23150 ;;; Filling
23152 ;; We use our own fill-paragraph and auto-fill functions.
23154 ;; `org-fill-paragraph' relies on adaptive filling and context
23155 ;; checking. Appropriate `fill-prefix' is computed with
23156 ;; `org-adaptive-fill-function'.
23158 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23159 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23160 ;; `org-adaptive-fill-function' value. Internally,
23161 ;; `org-comment-line-break-function' breaks the line.
23163 ;; `org-setup-filling' installs filling and auto-filling related
23164 ;; variables during `org-mode' initialization.
23166 (defvar org-element-paragraph-separate) ; org-element.el
23167 (defun org-setup-filling ()
23168 (require 'org-element)
23169 ;; Prevent auto-fill from inserting unwanted new items.
23170 (when (boundp 'fill-nobreak-predicate)
23171 (setq-local
23172 fill-nobreak-predicate
23173 (org-uniquify
23174 (append fill-nobreak-predicate
23175 '(org-fill-line-break-nobreak-p
23176 org-fill-paragraph-with-timestamp-nobreak-p)))))
23177 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23178 (setq-local paragraph-start paragraph-ending)
23179 (setq-local paragraph-separate paragraph-ending))
23180 (setq-local fill-paragraph-function 'org-fill-paragraph)
23181 (setq-local auto-fill-inhibit-regexp nil)
23182 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23183 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23184 (setq-local comment-line-break-function 'org-comment-line-break-function))
23186 (defun org-fill-line-break-nobreak-p ()
23187 "Non-nil when a new line at point would create an Org line break."
23188 (save-excursion
23189 (skip-chars-backward "[ \t]")
23190 (skip-chars-backward "\\\\")
23191 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23193 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23194 "Non-nil when a new line at point would split a timestamp."
23195 (and (org-at-timestamp-p t)
23196 (not (looking-at org-ts-regexp-both))))
23198 (declare-function message-in-body-p "message" ())
23199 (defvar orgtbl-line-start-regexp) ; From org-table.el
23200 (defun org-adaptive-fill-function ()
23201 "Compute a fill prefix for the current line.
23202 Return fill prefix, as a string, or nil if current line isn't
23203 meant to be filled. For convenience, if `adaptive-fill-regexp'
23204 matches in paragraphs or comments, use it."
23205 (catch 'exit
23206 (when (derived-mode-p 'message-mode)
23207 (save-excursion
23208 (beginning-of-line)
23209 (cond ((not (message-in-body-p)) (throw 'exit nil))
23210 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23211 ((looking-at message-cite-prefix-regexp)
23212 (throw 'exit (match-string-no-properties 0)))
23213 ((looking-at org-outline-regexp)
23214 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23215 (org-with-wide-buffer
23216 (unless (org-at-heading-p)
23217 (let* ((p (line-beginning-position))
23218 (element (save-excursion
23219 (beginning-of-line)
23220 (org-element-at-point)))
23221 (type (org-element-type element))
23222 (post-affiliated (org-element-property :post-affiliated element)))
23223 (unless (< p post-affiliated)
23224 (cl-case type
23225 (comment
23226 (save-excursion
23227 (beginning-of-line)
23228 (looking-at "[ \t]*")
23229 (concat (match-string 0) "# ")))
23230 (footnote-definition "")
23231 ((item plain-list)
23232 (make-string (org-list-item-body-column post-affiliated) ?\s))
23233 (paragraph
23234 ;; Fill prefix is usually the same as the current line,
23235 ;; unless the paragraph is at the beginning of an item.
23236 (let ((parent (org-element-property :parent element)))
23237 (save-excursion
23238 (beginning-of-line)
23239 (cond ((eq (org-element-type parent) 'item)
23240 (make-string (org-list-item-body-column
23241 (org-element-property :begin parent))
23242 ?\s))
23243 ((and adaptive-fill-regexp
23244 ;; Locally disable
23245 ;; `adaptive-fill-function' to let
23246 ;; `fill-context-prefix' handle
23247 ;; `adaptive-fill-regexp' variable.
23248 (let (adaptive-fill-function)
23249 (fill-context-prefix
23250 post-affiliated
23251 (org-element-property :end element)))))
23252 ((looking-at "[ \t]+") (match-string 0))
23253 (t "")))))
23254 (comment-block
23255 ;; Only fill contents if P is within block boundaries.
23256 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23257 (forward-line)
23258 (point)))
23259 (cend (save-excursion
23260 (goto-char (org-element-property :end element))
23261 (skip-chars-backward " \r\t\n")
23262 (line-beginning-position))))
23263 (when (and (>= p cbeg) (< p cend))
23264 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23265 (match-string 0)
23266 "")))))))))))
23268 (declare-function message-goto-body "message" ())
23269 (defvar message-cite-prefix-regexp) ; From message.el
23270 (defun org-fill-paragraph (&optional justify)
23271 "Fill element at point, when applicable.
23273 This function only applies to comment blocks, comments, example
23274 blocks and paragraphs. Also, as a special case, re-align table
23275 when point is at one.
23277 If JUSTIFY is non-nil (interactively, with prefix argument),
23278 justify as well. If `sentence-end-double-space' is non-nil, then
23279 period followed by one space does not end a sentence, so don't
23280 break a line there. The variable `fill-column' controls the
23281 width for filling.
23283 For convenience, when point is at a plain list, an item or
23284 a footnote definition, try to fill the first paragraph within."
23285 (interactive)
23286 (if (and (derived-mode-p 'message-mode)
23287 (or (not (message-in-body-p))
23288 (save-excursion (move-beginning-of-line 1)
23289 (looking-at message-cite-prefix-regexp))))
23290 ;; First ensure filling is correct in message-mode.
23291 (let ((fill-paragraph-function
23292 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23293 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23294 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23295 (paragraph-separate
23296 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23297 (fill-paragraph nil))
23298 (with-syntax-table org-mode-transpose-word-syntax-table
23299 ;; Move to end of line in order to get the first paragraph
23300 ;; within a plain list or a footnote definition.
23301 (let ((element (save-excursion
23302 (end-of-line)
23303 (or (ignore-errors (org-element-at-point))
23304 (user-error "An element cannot be parsed line %d"
23305 (line-number-at-pos (point)))))))
23306 ;; First check if point is in a blank line at the beginning of
23307 ;; the buffer. In that case, ignore filling.
23308 (cl-case (org-element-type element)
23309 ;; Use major mode filling function is src blocks.
23310 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23311 ;; Align Org tables, leave table.el tables as-is.
23312 (table-row (org-table-align) t)
23313 (table
23314 (when (eq (org-element-property :type element) 'org)
23315 (save-excursion
23316 (goto-char (org-element-property :post-affiliated element))
23317 (org-table-align)))
23319 (paragraph
23320 ;; Paragraphs may contain `line-break' type objects.
23321 (let ((beg (max (point-min)
23322 (org-element-property :contents-begin element)))
23323 (end (min (point-max)
23324 (org-element-property :contents-end element))))
23325 ;; Do nothing if point is at an affiliated keyword.
23326 (if (< (line-end-position) beg) t
23327 (when (derived-mode-p 'message-mode)
23328 ;; In `message-mode', do not fill following citation
23329 ;; in current paragraph nor text before message body.
23330 (let ((body-start (save-excursion (message-goto-body))))
23331 (when body-start (setq beg (max body-start beg))))
23332 (when (save-excursion
23333 (re-search-forward
23334 (concat "^" message-cite-prefix-regexp) end t))
23335 (setq end (match-beginning 0))))
23336 ;; Fill paragraph, taking line breaks into account.
23337 (save-excursion
23338 (goto-char beg)
23339 (let ((cuts (list beg)))
23340 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23341 (when (eq 'line-break
23342 (org-element-type
23343 (save-excursion (backward-char)
23344 (org-element-context))))
23345 (push (point) cuts)))
23346 (dolist (c (delq end cuts))
23347 (fill-region-as-paragraph c end justify)
23348 (setq end c))))
23349 t)))
23350 ;; Contents of `comment-block' type elements should be
23351 ;; filled as plain text, but only if point is within block
23352 ;; markers.
23353 (comment-block
23354 (let* ((case-fold-search t)
23355 (beg (save-excursion
23356 (goto-char (org-element-property :begin element))
23357 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23358 (forward-line)
23359 (point)))
23360 (end (save-excursion
23361 (goto-char (org-element-property :end element))
23362 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23363 (line-beginning-position))))
23364 (if (or (< (point) beg) (> (point) end)) t
23365 (fill-region-as-paragraph
23366 (save-excursion (end-of-line)
23367 (re-search-backward "^[ \t]*$" beg 'move)
23368 (line-beginning-position))
23369 (save-excursion (beginning-of-line)
23370 (re-search-forward "^[ \t]*$" end 'move)
23371 (line-beginning-position))
23372 justify))))
23373 ;; Fill comments.
23374 (comment
23375 (let ((begin (org-element-property :post-affiliated element))
23376 (end (org-element-property :end element)))
23377 (when (and (>= (point) begin) (<= (point) end))
23378 (let ((begin (save-excursion
23379 (end-of-line)
23380 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23381 (progn (forward-line) (point))
23382 begin)))
23383 (end (save-excursion
23384 (end-of-line)
23385 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23386 (1- (line-beginning-position))
23387 (skip-chars-backward " \r\t\n")
23388 (line-end-position)))))
23389 ;; Do not fill comments when at a blank line.
23390 (when (> end begin)
23391 (let ((fill-prefix
23392 (save-excursion
23393 (beginning-of-line)
23394 (looking-at "[ \t]*#")
23395 (let ((comment-prefix (match-string 0)))
23396 (goto-char (match-end 0))
23397 (if (looking-at adaptive-fill-regexp)
23398 (concat comment-prefix (match-string 0))
23399 (concat comment-prefix " "))))))
23400 (save-excursion
23401 (fill-region-as-paragraph begin end justify))))))
23403 ;; Ignore every other element.
23404 (otherwise t))))))
23406 (defun org-auto-fill-function ()
23407 "Auto-fill function."
23408 ;; Check if auto-filling is meaningful.
23409 (let ((fc (current-fill-column)))
23410 (when (and fc (> (current-column) fc))
23411 (let* ((fill-prefix (org-adaptive-fill-function))
23412 ;; Enforce empty fill prefix, if required. Otherwise, it
23413 ;; will be computed again.
23414 (adaptive-fill-mode (not (equal fill-prefix ""))))
23415 (when fill-prefix (do-auto-fill))))))
23417 (defun org-comment-line-break-function (&optional soft)
23418 "Break line at point and indent, continuing comment if within one.
23419 The inserted newline is marked hard if variable
23420 `use-hard-newlines' is true, unless optional argument SOFT is
23421 non-nil."
23422 (if soft (insert-and-inherit ?\n) (newline 1))
23423 (save-excursion (forward-char -1) (delete-horizontal-space))
23424 (delete-horizontal-space)
23425 (indent-to-left-margin)
23426 (insert-before-markers-and-inherit fill-prefix))
23429 ;;; Fixed Width Areas
23431 (defun org-toggle-fixed-width ()
23432 "Toggle fixed-width markup.
23434 Add or remove fixed-width markup on current line, whenever it
23435 makes sense. Return an error otherwise.
23437 If a region is active and if it contains only fixed-width areas
23438 or blank lines, remove all fixed-width markup in it. If the
23439 region contains anything else, convert all non-fixed-width lines
23440 to fixed-width ones.
23442 Blank lines at the end of the region are ignored unless the
23443 region only contains such lines."
23444 (interactive)
23445 (if (not (org-region-active-p))
23446 ;; No region:
23448 ;; Remove fixed width marker only in a fixed-with element.
23450 ;; Add fixed width maker in paragraphs, in blank lines after
23451 ;; elements or at the beginning of a headline or an inlinetask,
23452 ;; and before any one-line elements (e.g., a clock).
23453 (progn
23454 (beginning-of-line)
23455 (let* ((element (org-element-at-point))
23456 (type (org-element-type element)))
23457 (cond
23458 ((and (eq type 'fixed-width)
23459 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23460 (replace-match
23461 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23462 ((and (memq type '(babel-call clock comment diary-sexp headline
23463 horizontal-rule keyword paragraph
23464 planning))
23465 (<= (org-element-property :post-affiliated element) (point)))
23466 (skip-chars-forward " \t")
23467 (insert ": "))
23468 ((and (looking-at-p "[ \t]*$")
23469 (or (eq type 'inlinetask)
23470 (save-excursion
23471 (skip-chars-forward " \r\t\n")
23472 (<= (org-element-property :end element) (point)))))
23473 (delete-region (point) (line-end-position))
23474 (org-indent-line)
23475 (insert ": "))
23476 (t (user-error "Cannot insert a fixed-width line here")))))
23477 ;; Region active.
23478 (let* ((begin (save-excursion
23479 (goto-char (region-beginning))
23480 (line-beginning-position)))
23481 (end (copy-marker
23482 (save-excursion
23483 (goto-char (region-end))
23484 (unless (eolp) (beginning-of-line))
23485 (if (save-excursion (re-search-backward "\\S-" begin t))
23486 (progn (skip-chars-backward " \r\t\n") (point))
23487 (point)))))
23488 (all-fixed-width-p
23489 (catch 'not-all-p
23490 (save-excursion
23491 (goto-char begin)
23492 (skip-chars-forward " \r\t\n")
23493 (when (eobp) (throw 'not-all-p nil))
23494 (while (< (point) end)
23495 (let ((element (org-element-at-point)))
23496 (if (eq (org-element-type element) 'fixed-width)
23497 (goto-char (org-element-property :end element))
23498 (throw 'not-all-p nil))))
23499 t))))
23500 (if all-fixed-width-p
23501 (save-excursion
23502 (goto-char begin)
23503 (while (< (point) end)
23504 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23505 (replace-match
23506 "" nil nil nil
23507 (if (= (line-end-position) (match-end 0)) 0 1)))
23508 (forward-line)))
23509 (let ((min-ind (point-max)))
23510 ;; Find minimum indentation across all lines.
23511 (save-excursion
23512 (goto-char begin)
23513 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23514 (setq min-ind 0)
23515 (catch 'zerop
23516 (while (< (point) end)
23517 (unless (looking-at-p "[ \t]*$")
23518 (let ((ind (org-get-indentation)))
23519 (setq min-ind (min min-ind ind))
23520 (when (zerop ind) (throw 'zerop t))))
23521 (forward-line)))))
23522 ;; Loop over all lines and add fixed-width markup everywhere
23523 ;; but in fixed-width lines.
23524 (save-excursion
23525 (goto-char begin)
23526 (while (< (point) end)
23527 (cond
23528 ((org-at-heading-p)
23529 (insert ": ")
23530 (forward-line)
23531 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23532 (insert ":")
23533 (forward-line)))
23534 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23535 (let* ((element (org-element-at-point))
23536 (element-end (org-element-property :end element)))
23537 (if (eq (org-element-type element) 'fixed-width)
23538 (progn (goto-char element-end)
23539 (skip-chars-backward " \r\t\n")
23540 (forward-line))
23541 (let ((limit (min end element-end)))
23542 (while (< (point) limit)
23543 (org-move-to-column min-ind t)
23544 (insert ": ")
23545 (forward-line))))))
23547 (org-move-to-column min-ind t)
23548 (insert ": ")
23549 (forward-line)))))))
23550 (set-marker end nil))))
23553 ;;; Comments
23555 ;; Org comments syntax is quite complex. It requires the entire line
23556 ;; to be just a comment. Also, even with the right syntax at the
23557 ;; beginning of line, some some elements (i.e. verse-block or
23558 ;; example-block) don't accept comments. Usual Emacs comment commands
23559 ;; cannot cope with those requirements. Therefore, Org replaces them.
23561 ;; Org still relies on `comment-dwim', but cannot trust
23562 ;; `comment-only-p'. So, `comment-region-function' and
23563 ;; `uncomment-region-function' both point
23564 ;; to`org-comment-or-uncomment-region'. Eventually,
23565 ;; `org-insert-comment' takes care of insertion of comments at the
23566 ;; beginning of line.
23568 ;; `org-setup-comments-handling' install comments related variables
23569 ;; during `org-mode' initialization.
23571 (defun org-setup-comments-handling ()
23572 (interactive)
23573 (setq-local comment-use-syntax nil)
23574 (setq-local comment-start "# ")
23575 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23576 (setq-local comment-insert-comment-function 'org-insert-comment)
23577 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23578 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23580 (defun org-insert-comment ()
23581 "Insert an empty comment above current line.
23582 If the line is empty, insert comment at its beginning. When
23583 point is within a source block, comment according to the related
23584 major mode."
23585 (if (let ((element (org-element-at-point)))
23586 (and (eq (org-element-type element) 'src-block)
23587 (< (save-excursion
23588 (goto-char (org-element-property :post-affiliated element))
23589 (line-end-position))
23590 (point))
23591 (> (save-excursion
23592 (goto-char (org-element-property :end element))
23593 (skip-chars-backward " \r\t\n")
23594 (line-beginning-position))
23595 (point))))
23596 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23597 (beginning-of-line)
23598 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23599 (open-line 1))
23600 (org-indent-line)
23601 (insert "# ")))
23603 (defvar comment-empty-lines) ; From newcomment.el.
23604 (defun org-comment-or-uncomment-region (beg end &rest _)
23605 "Comment or uncomment each non-blank line in the region.
23606 Uncomment each non-blank line between BEG and END if it only
23607 contains commented lines. Otherwise, comment them. If region is
23608 strictly within a source block, use appropriate comment syntax."
23609 (if (let ((element (org-element-at-point)))
23610 (and (eq (org-element-type element) 'src-block)
23611 (< (save-excursion
23612 (goto-char (org-element-property :post-affiliated element))
23613 (line-end-position))
23614 beg)
23615 (>= (save-excursion
23616 (goto-char (org-element-property :end element))
23617 (skip-chars-backward " \r\t\n")
23618 (line-beginning-position))
23619 end)))
23620 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23621 (save-restriction
23622 ;; Restrict region
23623 (narrow-to-region (save-excursion (goto-char beg)
23624 (skip-chars-forward " \r\t\n" end)
23625 (line-beginning-position))
23626 (save-excursion (goto-char end)
23627 (skip-chars-backward " \r\t\n" beg)
23628 (line-end-position)))
23629 (let ((uncommentp
23630 ;; UNCOMMENTP is non-nil when every non blank line between
23631 ;; BEG and END is a comment.
23632 (save-excursion
23633 (goto-char (point-min))
23634 (while (and (not (eobp))
23635 (let ((element (org-element-at-point)))
23636 (and (eq (org-element-type element) 'comment)
23637 (goto-char (min (point-max)
23638 (org-element-property
23639 :end element)))))))
23640 (eobp))))
23641 (if uncommentp
23642 ;; Only blank lines and comments in region: uncomment it.
23643 (save-excursion
23644 (goto-char (point-min))
23645 (while (not (eobp))
23646 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23647 (replace-match "" nil nil nil 1))
23648 (forward-line)))
23649 ;; Comment each line in region.
23650 (let ((min-indent (point-max)))
23651 ;; First find the minimum indentation across all lines.
23652 (save-excursion
23653 (goto-char (point-min))
23654 (while (and (not (eobp)) (not (zerop min-indent)))
23655 (unless (looking-at "[ \t]*$")
23656 (setq min-indent (min min-indent (current-indentation))))
23657 (forward-line)))
23658 ;; Then loop over all lines.
23659 (save-excursion
23660 (goto-char (point-min))
23661 (while (not (eobp))
23662 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23663 ;; Don't get fooled by invisible text (e.g. link path)
23664 ;; when moving to column MIN-INDENT.
23665 (let ((buffer-invisibility-spec nil))
23666 (org-move-to-column min-indent t))
23667 (insert comment-start))
23668 (forward-line)))))))))
23670 (defun org-comment-dwim (_arg)
23671 "Call `comment-dwim' within a source edit buffer if needed."
23672 (interactive "*P")
23673 (if (org-in-src-block-p)
23674 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23675 (call-interactively 'comment-dwim)))
23678 ;;; Timestamps API
23680 ;; This section contains tools to operate on timestamp objects, as
23681 ;; returned by, e.g. `org-element-context'.
23683 (defun org-timestamp--to-internal-time (timestamp &optional end)
23684 "Encode TIMESTAMP object into Emacs internal time.
23685 Use end of date range or time range when END is non-nil."
23686 (apply #'encode-time
23687 (cons 0
23688 (mapcar
23689 (lambda (prop) (or (org-element-property prop timestamp) 0))
23690 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23691 '(:minute-start :hour-start :day-start :month-start
23692 :year-start))))))
23694 (defun org-timestamp-has-time-p (timestamp)
23695 "Non-nil when TIMESTAMP has a time specified."
23696 (org-element-property :hour-start timestamp))
23698 (defun org-timestamp-format (timestamp format &optional end utc)
23699 "Format a TIMESTAMP object into a string.
23701 FORMAT is a format specifier to be passed to
23702 `format-time-string'.
23704 When optional argument END is non-nil, use end of date-range or
23705 time-range, if possible.
23707 When optional argument UTC is non-nil, time will be expressed as
23708 Universal Time."
23709 (format-time-string
23710 format (org-timestamp--to-internal-time timestamp end)
23711 (and utc t)))
23713 (defun org-timestamp-split-range (timestamp &optional end)
23714 "Extract a TIMESTAMP object from a date or time range.
23716 END, when non-nil, means extract the end of the range.
23717 Otherwise, extract its start.
23719 Return a new timestamp object."
23720 (let ((type (org-element-property :type timestamp)))
23721 (if (memq type '(active inactive diary)) timestamp
23722 (let ((split-ts (org-element-copy timestamp)))
23723 ;; Set new type.
23724 (org-element-put-property
23725 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23726 ;; Copy start properties over end properties if END is
23727 ;; non-nil. Otherwise, copy end properties over `start' ones.
23728 (let ((p-alist '((:minute-start . :minute-end)
23729 (:hour-start . :hour-end)
23730 (:day-start . :day-end)
23731 (:month-start . :month-end)
23732 (:year-start . :year-end))))
23733 (dolist (p-cell p-alist)
23734 (org-element-put-property
23735 split-ts
23736 (funcall (if end #'car #'cdr) p-cell)
23737 (org-element-property
23738 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23739 ;; Eventually refresh `:raw-value'.
23740 (org-element-put-property split-ts :raw-value nil)
23741 (org-element-put-property
23742 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23744 (defun org-timestamp-translate (timestamp &optional boundary)
23745 "Translate TIMESTAMP object to custom format.
23747 Format string is defined in `org-time-stamp-custom-formats',
23748 which see.
23750 When optional argument BOUNDARY is non-nil, it is either the
23751 symbol `start' or `end'. In this case, only translate the
23752 starting or ending part of TIMESTAMP if it is a date or time
23753 range. Otherwise, translate both parts.
23755 Return timestamp as-is if `org-display-custom-times' is nil or if
23756 it has a `diary' type."
23757 (let ((type (org-element-property :type timestamp)))
23758 (if (or (not org-display-custom-times) (eq type 'diary))
23759 (org-element-interpret-data timestamp)
23760 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23761 org-time-stamp-custom-formats)))
23762 (if (and (not boundary) (memq type '(active-range inactive-range)))
23763 (concat (org-timestamp-format timestamp fmt)
23764 "--"
23765 (org-timestamp-format timestamp fmt t))
23766 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23770 ;;; Other stuff.
23772 (defvar reftex-docstruct-symbol)
23773 (defvar reftex-cite-format)
23774 (defvar org--rds)
23776 (defun org-reftex-citation ()
23777 "Use reftex-citation to insert a citation into the buffer.
23778 This looks for a line like
23780 #+BIBLIOGRAPHY: foo plain option:-d
23782 and derives from it that foo.bib is the bibliography file relevant
23783 for this document. It then installs the necessary environment for RefTeX
23784 to work in this buffer and calls `reftex-citation' to insert a citation
23785 into the buffer.
23787 Export of such citations to both LaTeX and HTML is handled by the contributed
23788 package ox-bibtex by Taru Karttunen."
23789 (interactive)
23790 (let ((reftex-docstruct-symbol 'org--rds)
23791 (reftex-cite-format "\\cite{%l}")
23792 org--rds bib)
23793 (save-excursion
23794 (save-restriction
23795 (widen)
23796 (let ((case-fold-search t)
23797 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23798 (if (not (save-excursion
23799 (or (re-search-forward re nil t)
23800 (re-search-backward re nil t))))
23801 (user-error "No bibliography defined in file")
23802 (setq bib (concat (match-string 1) ".bib")
23803 org--rds (list (list 'bib bib)))))))
23804 (call-interactively 'reftex-citation)))
23806 ;;;; Functions extending outline functionality
23808 (defun org-beginning-of-line (&optional arg)
23809 "Go to the beginning of the current line. If that is invisible, continue
23810 to a visible line beginning. This makes the function of C-a more intuitive.
23811 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23812 first attempt, and only move to after the tags when the cursor is already
23813 beyond the end of the headline."
23814 (interactive "P")
23815 (let ((pos (point))
23816 (special (if (consp org-special-ctrl-a/e)
23817 (car org-special-ctrl-a/e)
23818 org-special-ctrl-a/e))
23819 deactivate-mark refpos)
23820 (call-interactively (if (bound-and-true-p visual-line-mode)
23821 #'beginning-of-visual-line
23822 #'move-beginning-of-line))
23823 (cond
23824 ((or arg (not special)))
23825 ((and (looking-at org-complex-heading-regexp)
23826 (eq (char-after (match-end 1)) ?\s))
23827 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23828 (point-at-eol)))
23829 (goto-char
23830 (if (eq special t)
23831 (cond ((> pos refpos) refpos)
23832 ((= pos (point)) refpos)
23833 (t (point)))
23834 (cond ((> pos (point)) (point))
23835 ((not (eq last-command this-command)) (point))
23836 (t refpos)))))
23837 ((org-at-item-p)
23838 ;; Being at an item and not looking at an the item means point
23839 ;; was previously moved to beginning of a visual line, which
23840 ;; doesn't contain the item. Therefore, do nothing special,
23841 ;; just stay here.
23842 (when (looking-at org-list-full-item-re)
23843 ;; Set special position at first white space character after
23844 ;; bullet, and check-box, if any.
23845 (let ((after-bullet
23846 (let ((box (match-end 3)))
23847 (if (not box) (match-end 1)
23848 (let ((after (char-after box)))
23849 (if (and after (= after ? )) (1+ box) box))))))
23850 ;; Special case: Move point to special position when
23851 ;; currently after it or at beginning of line.
23852 (if (eq special t)
23853 (when (or (> pos after-bullet) (= (point) pos))
23854 (goto-char after-bullet))
23855 ;; Reversed case: Move point to special position when
23856 ;; point was already at beginning of line and command is
23857 ;; repeated.
23858 (when (and (= (point) pos) (eq last-command this-command))
23859 (goto-char after-bullet))))))))
23860 (setq disable-point-adjustment
23861 (or (not (invisible-p (point)))
23862 (not (invisible-p (max (point-min) (1- (point))))))))
23864 (defun org-end-of-line (&optional arg)
23865 "Go to the end of the line.
23866 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23867 tags on the first attempt, and only move to after the tags when
23868 the cursor is already beyond the end of the headline."
23869 (interactive "P")
23870 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23871 org-special-ctrl-a/e))
23872 (move-fun (cond ((bound-and-true-p visual-line-mode)
23873 'end-of-visual-line)
23874 ((fboundp 'move-end-of-line) 'move-end-of-line)
23875 (t 'end-of-line)))
23876 deactivate-mark)
23877 (if (or (not special) arg) (call-interactively move-fun)
23878 (let* ((element (save-excursion (beginning-of-line)
23879 (org-element-at-point)))
23880 (type (org-element-type element)))
23881 (cond
23882 ((memq type '(headline inlinetask))
23883 (let ((pos (point)))
23884 (beginning-of-line 1)
23885 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
23886 (if (eq special t)
23887 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23888 (goto-char (match-beginning 1))
23889 (goto-char (match-end 0)))
23890 (if (or (< pos (match-end 0))
23891 (not (eq this-command last-command)))
23892 (goto-char (match-end 0))
23893 (goto-char (match-beginning 1))))
23894 (call-interactively move-fun))))
23895 ((outline-invisible-p (line-end-position))
23896 ;; If element is hidden, `move-end-of-line' would put point
23897 ;; after it. Use `end-of-line' to stay on current line.
23898 (call-interactively 'end-of-line))
23899 (t (call-interactively move-fun))))))
23900 (setq disable-point-adjustment
23901 (or (not (invisible-p (point)))
23902 (not (invisible-p (max (point-min) (1- (point))))))))
23904 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23905 (define-key org-mode-map "\C-e" 'org-end-of-line)
23907 (defun org-backward-sentence (&optional _arg)
23908 "Go to beginning of sentence, or beginning of table field.
23909 This will call `backward-sentence' or `org-table-beginning-of-field',
23910 depending on context."
23911 (interactive)
23912 (let* ((element (org-element-at-point))
23913 (contents-begin (org-element-property :contents-begin element))
23914 (table (org-element-lineage element '(table) t)))
23915 (if (and table
23916 (> (point) contents-begin)
23917 (<= (point) (org-element-property :contents-end table)))
23918 (call-interactively #'org-table-beginning-of-field)
23919 (save-restriction
23920 (when (and contents-begin
23921 (< (point-min) contents-begin)
23922 (> (point) contents-begin))
23923 (narrow-to-region contents-begin
23924 (org-element-property :contents-end element)))
23925 (call-interactively #'backward-sentence)))))
23927 (defun org-forward-sentence (&optional _arg)
23928 "Go to end of sentence, or end of table field.
23929 This will call `forward-sentence' or `org-table-end-of-field',
23930 depending on context."
23931 (interactive)
23932 (let* ((element (org-element-at-point))
23933 (contents-end (org-element-property :contents-end element))
23934 (table (org-element-lineage element '(table) t)))
23935 (if (and table
23936 (>= (point) (org-element-property :contents-begin table))
23937 (< (point) contents-end))
23938 (call-interactively #'org-table-end-of-field)
23939 (save-restriction
23940 (when (and contents-end
23941 (> (point-max) contents-end)
23942 ;; Skip blank lines between elements.
23943 (< (org-element-property :end element)
23944 (save-excursion (goto-char contents-end)
23945 (skip-chars-forward " \r\t\n"))))
23946 (narrow-to-region (org-element-property :contents-begin element)
23947 contents-end))
23948 (call-interactively #'forward-sentence)))))
23950 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23951 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23953 (defun org-kill-line (&optional _arg)
23954 "Kill line, to tags or end of line."
23955 (interactive)
23956 (cond
23957 ((or (not org-special-ctrl-k)
23958 (bolp)
23959 (not (org-at-heading-p)))
23960 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23961 org-ctrl-k-protect-subtree
23962 (or (eq org-ctrl-k-protect-subtree 'error)
23963 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23964 (user-error "C-k aborted as it would kill a hidden subtree"))
23965 (call-interactively
23966 (if (bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23967 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
23968 (kill-region (point) (match-beginning 1))
23969 (org-set-tags nil t))
23970 (t (kill-region (point) (point-at-eol)))))
23972 (define-key org-mode-map "\C-k" 'org-kill-line)
23974 (defun org-yank (&optional arg)
23975 "Yank. If the kill is a subtree, treat it specially.
23976 This command will look at the current kill and check if is a single
23977 subtree, or a series of subtrees[1]. If it passes the test, and if the
23978 cursor is at the beginning of a line or after the stars of a currently
23979 empty headline, then the yank is handled specially. How exactly depends
23980 on the value of the following variables.
23982 `org-yank-folded-subtrees'
23983 By default, this variable is non-nil, which results in subtree(s)
23984 being folded after insertion, but only if doing so would now
23985 swallow text after the yanked text.
23987 `org-yank-adjusted-subtrees'
23988 When non-nil (the default value is nil), the subtree will be
23989 promoted or demoted in order to fit into the local outline tree
23990 structure, which means that the level will be adjusted so that it
23991 becomes the smaller one of the two *visible* surrounding headings.
23993 Any prefix to this command will cause `yank' to be called directly with
23994 no special treatment. In particular, a simple \\[universal-argument] prefix \
23995 will just
23996 plainly yank the text as it is.
23998 \[1] The test checks if the first non-white line is a heading
23999 and if there are no other headings with fewer stars."
24000 (interactive "P")
24001 (org-yank-generic 'yank arg))
24003 (defun org-yank-generic (command arg)
24004 "Perform some yank-like command.
24006 This function implements the behavior described in the `org-yank'
24007 documentation. However, it has been generalized to work for any
24008 interactive command with similar behavior."
24010 ;; pretend to be command COMMAND
24011 (setq this-command command)
24013 (if arg
24014 (call-interactively command)
24016 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24017 (and (org-kill-is-subtree-p)
24018 (or (bolp)
24019 (and (looking-at "[ \t]*$")
24020 (string-match
24021 "\\`\\*+\\'"
24022 (buffer-substring (point-at-bol) (point)))))))
24023 swallowp)
24024 (cond
24025 ((and subtreep org-yank-folded-subtrees)
24026 (let ((beg (point))
24027 end)
24028 (if (and subtreep org-yank-adjusted-subtrees)
24029 (org-paste-subtree nil nil 'for-yank)
24030 (call-interactively command))
24032 (setq end (point))
24033 (goto-char beg)
24034 (when (and (bolp) subtreep
24035 (not (setq swallowp
24036 (org-yank-folding-would-swallow-text beg end))))
24037 (org-with-limited-levels
24038 (or (looking-at org-outline-regexp)
24039 (re-search-forward org-outline-regexp-bol end t))
24040 (while (and (< (point) end) (looking-at org-outline-regexp))
24041 (outline-hide-subtree)
24042 (org-cycle-show-empty-lines 'folded)
24043 (condition-case nil
24044 (outline-forward-same-level 1)
24045 (error (goto-char end))))))
24046 (when swallowp
24047 (message
24048 "Inserted text not folded because that would swallow text"))
24050 (goto-char end)
24051 (skip-chars-forward " \t\n\r")
24052 (beginning-of-line 1)
24053 (push-mark beg 'nomsg)))
24054 ((and subtreep org-yank-adjusted-subtrees)
24055 (let ((beg (point-at-bol)))
24056 (org-paste-subtree nil nil 'for-yank)
24057 (push-mark beg 'nomsg)))
24059 (call-interactively command))))))
24061 (defun org-yank-folding-would-swallow-text (beg end)
24062 "Would hide-subtree at BEG swallow any text after END?"
24063 (let (level)
24064 (org-with-limited-levels
24065 (save-excursion
24066 (goto-char beg)
24067 (when (or (looking-at org-outline-regexp)
24068 (re-search-forward org-outline-regexp-bol end t))
24069 (setq level (org-outline-level)))
24070 (goto-char end)
24071 (skip-chars-forward " \t\r\n\v\f")
24072 (not (or (eobp)
24073 (and (bolp) (looking-at-p org-outline-regexp)
24074 (<= (org-outline-level) level))))))))
24076 (define-key org-mode-map "\C-y" 'org-yank)
24078 (defun org-truely-invisible-p ()
24079 "Check if point is at a character currently not visible.
24080 This version does not only check the character property, but also
24081 `visible-mode'."
24082 ;; Early versions of noutline don't have `outline-invisible-p'.
24083 (unless (bound-and-true-p visible-mode)
24084 (outline-invisible-p)))
24086 (defun org-invisible-p2 ()
24087 "Check if point is at a character currently not visible."
24088 (save-excursion
24089 (when (and (eolp) (not (bobp))) (backward-char 1))
24090 ;; Early versions of noutline don't have `outline-invisible-p'.
24091 (outline-invisible-p)))
24093 (defun org-back-to-heading (&optional invisible-ok)
24094 "Call `outline-back-to-heading', but provide a better error message."
24095 (condition-case nil
24096 (outline-back-to-heading invisible-ok)
24097 (error (error "Before first headline at position %d in buffer %s"
24098 (point) (current-buffer)))))
24100 (defun org-before-first-heading-p ()
24101 "Before first heading?"
24102 (save-excursion
24103 (end-of-line)
24104 (null (re-search-backward org-outline-regexp-bol nil t))))
24106 (defun org-at-heading-p (&optional ignored)
24107 (outline-on-heading-p t))
24109 (defun org-in-commented-heading-p (&optional no-inheritance)
24110 "Non-nil if point is under a commented heading.
24111 This function also checks ancestors of the current headline,
24112 unless optional argument NO-INHERITANCE is non-nil."
24113 (cond
24114 ((org-before-first-heading-p) nil)
24115 ((let ((headline (nth 4 (org-heading-components))))
24116 (and headline
24117 (let ((case-fold-search nil))
24118 (string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24119 headline)))))
24120 (no-inheritance nil)
24122 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24124 (defun org-at-comment-p nil
24125 "Is cursor in a commented line?"
24126 (save-excursion
24127 (save-match-data
24128 (beginning-of-line)
24129 (looking-at "^[ \t]*# "))))
24131 (defun org-at-drawer-p nil
24132 "Is cursor at a drawer keyword?"
24133 (save-excursion
24134 (move-beginning-of-line 1)
24135 (looking-at org-drawer-regexp)))
24137 (defun org-at-block-p nil
24138 "Is cursor at a block keyword?"
24139 (save-excursion
24140 (move-beginning-of-line 1)
24141 (looking-at org-block-regexp)))
24143 (defun org-point-at-end-of-empty-headline ()
24144 "If point is at the end of an empty headline, return t, else nil.
24145 If the heading only contains a TODO keyword, it is still still considered
24146 empty."
24147 (and (looking-at "[ \t]*$")
24148 (when org-todo-line-regexp
24149 (save-excursion
24150 (beginning-of-line 1)
24151 (let ((case-fold-search nil))
24152 (looking-at org-todo-line-regexp)
24153 (string= (match-string 3) ""))))))
24155 (defun org-at-heading-or-item-p ()
24156 (or (org-at-heading-p) (org-at-item-p)))
24158 (defun org-at-target-p ()
24159 (or (org-in-regexp org-radio-target-regexp)
24160 (org-in-regexp org-target-regexp)))
24161 ;; Compatibility alias with Org versions < 7.8.03
24162 (defalias 'org-on-target-p 'org-at-target-p)
24164 (defun org-up-heading-all (arg)
24165 "Move to the heading line of which the present line is a subheading.
24166 This function considers both visible and invisible heading lines.
24167 With argument, move up ARG levels."
24168 (outline-up-heading arg t))
24170 (defun org-up-heading-safe ()
24171 "Move to the heading line of which the present line is a subheading.
24172 This version will not throw an error. It will return the level of the
24173 headline found, or nil if no higher level is found.
24175 Also, this function will be a lot faster than `outline-up-heading',
24176 because it relies on stars being the outline starters. This can really
24177 make a significant difference in outlines with very many siblings."
24178 (when (ignore-errors (org-back-to-heading t))
24179 (let ((level-up (1- (funcall outline-level))))
24180 (and (> level-up 0)
24181 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24182 (funcall outline-level)))))
24184 (defun org-first-sibling-p ()
24185 "Is this heading the first child of its parents?"
24186 (interactive)
24187 (let ((re org-outline-regexp-bol)
24188 level l)
24189 (unless (org-at-heading-p t)
24190 (user-error "Not at a heading"))
24191 (setq level (funcall outline-level))
24192 (save-excursion
24193 (if (not (re-search-backward re nil t))
24195 (setq l (funcall outline-level))
24196 (< l level)))))
24198 (defun org-goto-sibling (&optional previous)
24199 "Goto the next sibling, even if it is invisible.
24200 When PREVIOUS is set, go to the previous sibling instead. Returns t
24201 when a sibling was found. When none is found, return nil and don't
24202 move point."
24203 (let ((fun (if previous 're-search-backward 're-search-forward))
24204 (pos (point))
24205 (re org-outline-regexp-bol)
24206 level l)
24207 (when (ignore-errors (org-back-to-heading t))
24208 (setq level (funcall outline-level))
24209 (catch 'exit
24210 (or previous (forward-char 1))
24211 (while (funcall fun re nil t)
24212 (setq l (funcall outline-level))
24213 (when (< l level) (goto-char pos) (throw 'exit nil))
24214 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24215 (goto-char pos)
24216 nil))))
24218 (defun org-show-siblings ()
24219 "Show all siblings of the current headline."
24220 (save-excursion
24221 (while (org-goto-sibling) (org-flag-heading nil)))
24222 (save-excursion
24223 (while (org-goto-sibling 'previous)
24224 (org-flag-heading nil))))
24226 (defun org-goto-first-child ()
24227 "Goto the first child, even if it is invisible.
24228 Return t when a child was found. Otherwise don't move point and
24229 return nil."
24230 (let (level (pos (point)) (re org-outline-regexp-bol))
24231 (when (ignore-errors (org-back-to-heading t))
24232 (setq level (outline-level))
24233 (forward-char 1)
24234 (if (and (re-search-forward re nil t) (> (outline-level) level))
24235 (progn (goto-char (match-beginning 0)) t)
24236 (goto-char pos) nil))))
24238 (defun org-show-hidden-entry ()
24239 "Show an entry where even the heading is hidden."
24240 (save-excursion
24241 (org-show-entry)))
24243 (defun org-flag-heading (flag &optional entry)
24244 "Flag the current heading. FLAG non-nil means make invisible.
24245 When ENTRY is non-nil, show the entire entry."
24246 (save-excursion
24247 (org-back-to-heading t)
24248 ;; Check if we should show the entire entry
24249 (if entry
24250 (progn
24251 (org-show-entry)
24252 (save-excursion
24253 (and (outline-next-heading)
24254 (org-flag-heading nil))))
24255 (outline-flag-region (max (point-min) (1- (point)))
24256 (save-excursion (outline-end-of-heading) (point))
24257 flag))))
24259 (defun org-get-next-sibling ()
24260 "Move to next heading of the same level, and return point.
24261 If there is no such heading, return nil.
24262 This is like outline-next-sibling, but invisible headings are ok."
24263 (let ((level (funcall outline-level)))
24264 (outline-next-heading)
24265 (while (and (not (eobp)) (> (funcall outline-level) level))
24266 (outline-next-heading))
24267 (unless (or (eobp) (< (funcall outline-level) level))
24268 (point))))
24270 (defun org-get-last-sibling ()
24271 "Move to previous heading of the same level, and return point.
24272 If there is no such heading, return nil."
24273 (let ((opoint (point))
24274 (level (funcall outline-level)))
24275 (outline-previous-heading)
24276 (when (and (/= (point) opoint) (outline-on-heading-p t))
24277 (while (and (> (funcall outline-level) level)
24278 (not (bobp)))
24279 (outline-previous-heading))
24280 (unless (< (funcall outline-level) level)
24281 (point)))))
24283 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24284 "Goto to the end of a subtree."
24285 ;; This contains an exact copy of the original function, but it uses
24286 ;; `org-back-to-heading', to make it work also in invisible
24287 ;; trees. And is uses an invisible-ok argument.
24288 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24289 ;; Furthermore, when used inside Org, finding the end of a large subtree
24290 ;; with many children and grandchildren etc, this can be much faster
24291 ;; than the outline version.
24292 (org-back-to-heading invisible-ok)
24293 (let ((first t)
24294 (level (funcall outline-level)))
24295 (if (and (derived-mode-p 'org-mode) (< level 1000))
24296 ;; A true heading (not a plain list item), in Org-mode
24297 ;; This means we can easily find the end by looking
24298 ;; only for the right number of stars. Using a regexp to do
24299 ;; this is so much faster than using a Lisp loop.
24300 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24301 (forward-char 1)
24302 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24303 ;; something else, do it the slow way
24304 (while (and (not (eobp))
24305 (or first (> (funcall outline-level) level)))
24306 (setq first nil)
24307 (outline-next-heading)))
24308 (unless to-heading
24309 (when (memq (preceding-char) '(?\n ?\^M))
24310 ;; Go to end of line before heading
24311 (forward-char -1)
24312 (when (memq (preceding-char) '(?\n ?\^M))
24313 ;; leave blank line before heading
24314 (forward-char -1)))))
24315 (point))
24317 (defun org-end-of-meta-data (&optional full)
24318 "Skip planning line and properties drawer in current entry.
24319 When optional argument FULL is non-nil, also skip empty lines,
24320 clocking lines and regular drawers at the beginning of the
24321 entry."
24322 (org-back-to-heading t)
24323 (forward-line)
24324 (when (looking-at-p org-planning-line-re) (forward-line))
24325 (when (looking-at org-property-drawer-re)
24326 (goto-char (match-end 0))
24327 (forward-line))
24328 (when (and full (not (org-at-heading-p)))
24329 (catch 'exit
24330 (let ((end (save-excursion (outline-next-heading) (point)))
24331 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24332 (while (not (eobp))
24333 (cond ((looking-at-p org-drawer-regexp)
24334 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24335 (forward-line)
24336 (throw 'exit t)))
24337 ((looking-at-p re) (forward-line))
24338 (t (throw 'exit t))))))))
24340 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24341 "Move forward to the ARG'th subheading at same level as this one.
24342 Stop at the first and last subheadings of a superior heading.
24343 Normally this only looks at visible headings, but when INVISIBLE-OK is
24344 non-nil it will also look at invisible ones."
24345 (interactive "p")
24346 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24347 (if (and arg (< arg 0))
24348 (goto-char (point-min))
24349 (outline-next-heading))
24350 (org-at-heading-p)
24351 (let ((level (- (match-end 0) (match-beginning 0) 1))
24352 (f (if (and arg (< arg 0))
24353 're-search-backward
24354 're-search-forward))
24355 (count (if arg (abs arg) 1))
24356 (result (point)))
24357 (while (and (prog1 (> count 0)
24358 (forward-char (if (and arg (< arg 0)) -1 1)))
24359 (funcall f org-outline-regexp-bol nil 'move))
24360 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24361 (cond ((< l level) (setq count 0))
24362 ((and (= l level)
24363 (or invisible-ok
24364 (progn
24365 (goto-char (line-beginning-position))
24366 (not (outline-invisible-p)))))
24367 (setq count (1- count))
24368 (when (eq l level)
24369 (setq result (point)))))))
24370 (goto-char result))
24371 (beginning-of-line 1)))
24373 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24374 "Move backward to the ARG'th subheading at same level as this one.
24375 Stop at the first and last subheadings of a superior heading."
24376 (interactive "p")
24377 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24379 (defun org-next-visible-heading (arg)
24380 "Move to the next visible heading.
24382 This function wraps `outline-next-visible-heading' with
24383 `org-with-limited-levels' in order to skip over inline tasks and
24384 respect customization of `org-odd-levels-only'."
24385 (interactive "p")
24386 (org-with-limited-levels
24387 (outline-next-visible-heading arg)))
24389 (defun org-previous-visible-heading (arg)
24390 "Move to the previous visible heading.
24392 This function wraps `outline-previous-visible-heading' with
24393 `org-with-limited-levels' in order to skip over inline tasks and
24394 respect customization of `org-odd-levels-only'."
24395 (interactive "p")
24396 (org-with-limited-levels
24397 (outline-previous-visible-heading arg)))
24399 (defun org-next-block (arg &optional backward block-regexp)
24400 "Jump to the next block.
24402 With a prefix argument ARG, jump forward ARG many blocks.
24404 When BACKWARD is non-nil, jump to the previous block.
24406 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24407 Match data is set according to this regexp when the function
24408 returns.
24410 Return point at beginning of the opening line of found block.
24411 Throw an error if no block is found."
24412 (interactive "p")
24413 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24414 (case-fold-search t)
24415 (search-fn (if backward #'re-search-backward #'re-search-forward))
24416 (count (or arg 1))
24417 (origin (point))
24418 last-element)
24419 (if backward (beginning-of-line) (end-of-line))
24420 (while (and (> count 0) (funcall search-fn re nil t))
24421 (let ((element (save-excursion
24422 (goto-char (match-beginning 0))
24423 (save-match-data (org-element-at-point)))))
24424 (when (and (memq (org-element-type element)
24425 '(center-block comment-block dynamic-block
24426 example-block export-block quote-block
24427 special-block src-block verse-block))
24428 (<= (match-beginning 0)
24429 (org-element-property :post-affiliated element)))
24430 (setq last-element element)
24431 (cl-decf count))))
24432 (if (= count 0)
24433 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24434 (save-match-data (org-show-context)))
24435 (goto-char origin)
24436 (user-error "No %s code blocks" (if backward "previous" "further")))))
24438 (defun org-previous-block (arg &optional block-regexp)
24439 "Jump to the previous block.
24440 With a prefix argument ARG, jump backward ARG many source blocks.
24441 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24442 (interactive "p")
24443 (org-next-block arg t block-regexp))
24445 (defun org-forward-paragraph ()
24446 "Move forward to beginning of next paragraph or equivalent.
24448 The function moves point to the beginning of the next visible
24449 structural element, which can be a paragraph, a table, a list
24450 item, etc. It also provides some special moves for convenience:
24452 - On an affiliated keyword, jump to the beginning of the
24453 relative element.
24454 - On an item or a footnote definition, move to the second
24455 element inside, if any.
24456 - On a table or a property drawer, jump after it.
24457 - On a verse or source block, stop after blank lines."
24458 (interactive)
24459 (when (eobp) (user-error "Cannot move further down"))
24460 (let* ((deactivate-mark nil)
24461 (element (org-element-at-point))
24462 (type (org-element-type element))
24463 (post-affiliated (org-element-property :post-affiliated element))
24464 (contents-begin (org-element-property :contents-begin element))
24465 (contents-end (org-element-property :contents-end element))
24466 (end (let ((end (org-element-property :end element)) (parent element))
24467 (while (and (setq parent (org-element-property :parent parent))
24468 (= (org-element-property :contents-end parent) end))
24469 (setq end (org-element-property :end parent)))
24470 end)))
24471 (cond ((not element)
24472 (skip-chars-forward " \r\t\n")
24473 (or (eobp) (beginning-of-line)))
24474 ;; On affiliated keywords, move to element's beginning.
24475 ((< (point) post-affiliated)
24476 (goto-char post-affiliated))
24477 ;; At a table row, move to the end of the table. Similarly,
24478 ;; at a node property, move to the end of the property
24479 ;; drawer.
24480 ((memq type '(node-property table-row))
24481 (goto-char (org-element-property
24482 :end (org-element-property :parent element))))
24483 ((memq type '(property-drawer table)) (goto-char end))
24484 ;; Consider blank lines as separators in verse and source
24485 ;; blocks to ease editing.
24486 ((memq type '(src-block verse-block))
24487 (when (eq type 'src-block)
24488 (setq contents-end
24489 (save-excursion (goto-char end)
24490 (skip-chars-backward " \r\t\n")
24491 (line-beginning-position))))
24492 (beginning-of-line)
24493 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24494 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24495 (goto-char end)
24496 (skip-chars-forward " \r\t\n")
24497 (if (= (point) contents-end) (goto-char end)
24498 (beginning-of-line))))
24499 ;; With no contents, just skip element.
24500 ((not contents-begin) (goto-char end))
24501 ;; If contents are invisible, skip the element altogether.
24502 ((outline-invisible-p (line-end-position))
24503 (cl-case type
24504 (headline
24505 (org-with-limited-levels (outline-next-visible-heading 1)))
24506 ;; At a plain list, make sure we move to the next item
24507 ;; instead of skipping the whole list.
24508 (plain-list (forward-char)
24509 (org-forward-paragraph))
24510 (otherwise (goto-char end))))
24511 ((>= (point) contents-end) (goto-char end))
24512 ((>= (point) contents-begin)
24513 ;; This can only happen on paragraphs and plain lists.
24514 (cl-case type
24515 (paragraph (goto-char end))
24516 ;; At a plain list, try to move to second element in
24517 ;; first item, if possible.
24518 (plain-list (end-of-line)
24519 (org-forward-paragraph))))
24520 ;; When contents start on the middle of a line (e.g. in
24521 ;; items and footnote definitions), try to reach first
24522 ;; element starting after current line.
24523 ((> (line-end-position) contents-begin)
24524 (end-of-line)
24525 (org-forward-paragraph))
24526 (t (goto-char contents-begin)))))
24528 (defun org-backward-paragraph ()
24529 "Move backward to start of previous paragraph or equivalent.
24531 The function moves point to the beginning of the current
24532 structural element, which can be a paragraph, a table, a list
24533 item, etc., or to the beginning of the previous visible one if
24534 point is already there. It also provides some special moves for
24535 convenience:
24537 - On an affiliated keyword, jump to the first one.
24538 - On a table or a property drawer, move to its beginning.
24539 - On a verse or source block, stop before blank lines."
24540 (interactive)
24541 (when (bobp) (user-error "Cannot move further up"))
24542 (let* ((deactivate-mark nil)
24543 (element (org-element-at-point))
24544 (type (org-element-type element))
24545 (contents-begin (org-element-property :contents-begin element))
24546 (contents-end (org-element-property :contents-end element))
24547 (post-affiliated (org-element-property :post-affiliated element))
24548 (begin (org-element-property :begin element)))
24549 (cond
24550 ((not element) (goto-char (point-min)))
24551 ((= (point) begin)
24552 (backward-char)
24553 (org-backward-paragraph))
24554 ((<= (point) post-affiliated) (goto-char begin))
24555 ((memq type '(node-property table-row))
24556 (goto-char (org-element-property
24557 :post-affiliated (org-element-property :parent element))))
24558 ((memq type '(property-drawer table)) (goto-char begin))
24559 ((memq type '(src-block verse-block))
24560 (when (eq type 'src-block)
24561 (setq contents-begin
24562 (save-excursion (goto-char begin) (forward-line) (point))))
24563 (if (= (point) contents-begin) (goto-char post-affiliated)
24564 ;; Inside a verse block, see blank lines as paragraph
24565 ;; separators.
24566 (let ((origin (point)))
24567 (skip-chars-backward " \r\t\n" contents-begin)
24568 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24569 (skip-chars-forward " \r\t\n" origin)
24570 (if (= (point) origin) (goto-char contents-begin)
24571 (beginning-of-line))))))
24572 ((not contents-begin) (goto-char (or post-affiliated begin)))
24573 ((eq type 'paragraph)
24574 (goto-char contents-begin)
24575 ;; When at first paragraph in an item or a footnote definition,
24576 ;; move directly to beginning of line.
24577 (let ((parent-contents
24578 (org-element-property
24579 :contents-begin (org-element-property :parent element))))
24580 (when (and parent-contents (= parent-contents contents-begin))
24581 (beginning-of-line))))
24582 ;; At the end of a greater element, move to the beginning of the
24583 ;; last element within.
24584 ((>= (point) contents-end)
24585 (goto-char (1- contents-end))
24586 (org-backward-paragraph))
24587 (t (goto-char (or post-affiliated begin))))
24588 ;; Ensure we never leave point invisible.
24589 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24591 (defun org-forward-element ()
24592 "Move forward by one element.
24593 Move to the next element at the same level, when possible."
24594 (interactive)
24595 (cond ((eobp) (user-error "Cannot move further down"))
24596 ((org-with-limited-levels (org-at-heading-p))
24597 (let ((origin (point)))
24598 (goto-char (org-end-of-subtree nil t))
24599 (unless (org-with-limited-levels (org-at-heading-p))
24600 (goto-char origin)
24601 (user-error "Cannot move further down"))))
24603 (let* ((elem (org-element-at-point))
24604 (end (org-element-property :end elem))
24605 (parent (org-element-property :parent elem)))
24606 (cond ((and parent (= (org-element-property :contents-end parent) end))
24607 (goto-char (org-element-property :end parent)))
24608 ((integer-or-marker-p end) (goto-char end))
24609 (t (message "No element at point")))))))
24611 (defun org-backward-element ()
24612 "Move backward by one element.
24613 Move to the previous element at the same level, when possible."
24614 (interactive)
24615 (cond ((bobp) (user-error "Cannot move further up"))
24616 ((org-with-limited-levels (org-at-heading-p))
24617 ;; At a headline, move to the previous one, if any, or stay
24618 ;; here.
24619 (let ((origin (point)))
24620 (org-with-limited-levels (org-backward-heading-same-level 1))
24621 ;; When current headline has no sibling above, move to its
24622 ;; parent.
24623 (when (= (point) origin)
24624 (or (org-with-limited-levels (org-up-heading-safe))
24625 (progn (goto-char origin)
24626 (user-error "Cannot move further up"))))))
24628 (let* ((elem (org-element-at-point))
24629 (beg (org-element-property :begin elem)))
24630 (cond
24631 ;; Move to beginning of current element if point isn't
24632 ;; there already.
24633 ((null beg) (message "No element at point"))
24634 ((/= (point) beg) (goto-char beg))
24635 (t (goto-char beg)
24636 (skip-chars-backward " \r\t\n")
24637 (unless (bobp)
24638 (let ((prev (org-element-at-point)))
24639 (goto-char (org-element-property :begin prev))
24640 (while (and (setq prev (org-element-property :parent prev))
24641 (<= (org-element-property :end prev) beg))
24642 (goto-char (org-element-property :begin prev)))))))))))
24644 (defun org-up-element ()
24645 "Move to upper element."
24646 (interactive)
24647 (if (org-with-limited-levels (org-at-heading-p))
24648 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24649 (let* ((elem (org-element-at-point))
24650 (parent (org-element-property :parent elem)))
24651 (if parent (goto-char (org-element-property :begin parent))
24652 (if (org-with-limited-levels (org-before-first-heading-p))
24653 (user-error "No surrounding element")
24654 (org-with-limited-levels (org-back-to-heading)))))))
24656 (defvar org-element-greater-elements)
24657 (defun org-down-element ()
24658 "Move to inner element."
24659 (interactive)
24660 (let ((element (org-element-at-point)))
24661 (cond
24662 ((memq (org-element-type element) '(plain-list table))
24663 (goto-char (org-element-property :contents-begin element))
24664 (forward-char))
24665 ((memq (org-element-type element) org-element-greater-elements)
24666 ;; If contents are hidden, first disclose them.
24667 (when (outline-invisible-p (line-end-position)) (org-cycle))
24668 (goto-char (or (org-element-property :contents-begin element)
24669 (user-error "No content for this element"))))
24670 (t (user-error "No inner element")))))
24672 (defun org-drag-element-backward ()
24673 "Move backward element at point."
24674 (interactive)
24675 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24676 (let* ((elem (org-element-at-point))
24677 (prev-elem
24678 (save-excursion
24679 (goto-char (org-element-property :begin elem))
24680 (skip-chars-backward " \r\t\n")
24681 (unless (bobp)
24682 (let* ((beg (org-element-property :begin elem))
24683 (prev (org-element-at-point))
24684 (up prev))
24685 (while (and (setq up (org-element-property :parent up))
24686 (<= (org-element-property :end up) beg))
24687 (setq prev up))
24688 prev)))))
24689 ;; Error out if no previous element or previous element is
24690 ;; a parent of the current one.
24691 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24692 (user-error "Cannot drag element backward")
24693 (let ((pos (point)))
24694 (org-element-swap-A-B prev-elem elem)
24695 (goto-char (+ (org-element-property :begin prev-elem)
24696 (- pos (org-element-property :begin elem)))))))))
24698 (defun org-drag-element-forward ()
24699 "Move forward element at point."
24700 (interactive)
24701 (let* ((pos (point))
24702 (elem (org-element-at-point)))
24703 (when (= (point-max) (org-element-property :end elem))
24704 (user-error "Cannot drag element forward"))
24705 (goto-char (org-element-property :end elem))
24706 (let ((next-elem (org-element-at-point)))
24707 (when (or (org-element-nested-p elem next-elem)
24708 (and (eq (org-element-type next-elem) 'headline)
24709 (not (eq (org-element-type elem) 'headline))))
24710 (goto-char pos)
24711 (user-error "Cannot drag element forward"))
24712 ;; Compute new position of point: it's shifted by NEXT-ELEM
24713 ;; body's length (without final blanks) and by the length of
24714 ;; blanks between ELEM and NEXT-ELEM.
24715 (let ((size-next (- (save-excursion
24716 (goto-char (org-element-property :end next-elem))
24717 (skip-chars-backward " \r\t\n")
24718 (forward-line)
24719 ;; Small correction if buffer doesn't end
24720 ;; with a newline character.
24721 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24722 (org-element-property :begin next-elem)))
24723 (size-blank (- (org-element-property :end elem)
24724 (save-excursion
24725 (goto-char (org-element-property :end elem))
24726 (skip-chars-backward " \r\t\n")
24727 (forward-line)
24728 (point)))))
24729 (org-element-swap-A-B elem next-elem)
24730 (goto-char (+ pos size-next size-blank))))))
24732 (defun org-drag-line-forward (arg)
24733 "Drag the line at point ARG lines forward."
24734 (interactive "p")
24735 (dotimes (_ (abs arg))
24736 (let ((c (current-column)))
24737 (if (< 0 arg)
24738 (progn
24739 (beginning-of-line 2)
24740 (transpose-lines 1)
24741 (beginning-of-line 0))
24742 (transpose-lines 1)
24743 (beginning-of-line -1))
24744 (org-move-to-column c))))
24746 (defun org-drag-line-backward (arg)
24747 "Drag the line at point ARG lines backward."
24748 (interactive "p")
24749 (org-drag-line-forward (- arg)))
24751 (defun org-mark-element ()
24752 "Put point at beginning of this element, mark at end.
24754 Interactively, if this command is repeated or (in Transient Mark
24755 mode) if the mark is active, it marks the next element after the
24756 ones already marked."
24757 (interactive)
24758 (let (deactivate-mark)
24759 (if (and (called-interactively-p 'any)
24760 (or (and (eq last-command this-command) (mark t))
24761 (and transient-mark-mode mark-active)))
24762 (set-mark
24763 (save-excursion
24764 (goto-char (mark))
24765 (goto-char (org-element-property :end (org-element-at-point)))))
24766 (let ((element (org-element-at-point)))
24767 (end-of-line)
24768 (push-mark (org-element-property :end element) t t)
24769 (goto-char (org-element-property :begin element))))))
24771 (defun org-narrow-to-element ()
24772 "Narrow buffer to current element."
24773 (interactive)
24774 (let ((elem (org-element-at-point)))
24775 (cond
24776 ((eq (car elem) 'headline)
24777 (narrow-to-region
24778 (org-element-property :begin elem)
24779 (org-element-property :end elem)))
24780 ((memq (car elem) org-element-greater-elements)
24781 (narrow-to-region
24782 (org-element-property :contents-begin elem)
24783 (org-element-property :contents-end elem)))
24785 (narrow-to-region
24786 (org-element-property :begin elem)
24787 (org-element-property :end elem))))))
24789 (defun org-transpose-element ()
24790 "Transpose current and previous elements, keeping blank lines between.
24791 Point is moved after both elements."
24792 (interactive)
24793 (org-skip-whitespace)
24794 (let ((end (org-element-property :end (org-element-at-point))))
24795 (org-drag-element-backward)
24796 (goto-char end)))
24798 (defun org-unindent-buffer ()
24799 "Un-indent the visible part of the buffer.
24800 Relative indentation (between items, inside blocks, etc.) isn't
24801 modified."
24802 (interactive)
24803 (unless (eq major-mode 'org-mode)
24804 (user-error "Cannot un-indent a buffer not in Org mode"))
24805 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24806 (unindent-tree
24807 (lambda (contents)
24808 (dolist (element (reverse contents))
24809 (if (memq (org-element-type element) '(headline section))
24810 (funcall unindent-tree (org-element-contents element))
24811 (save-excursion
24812 (save-restriction
24813 (narrow-to-region
24814 (org-element-property :begin element)
24815 (org-element-property :end element))
24816 (org-do-remove-indentation))))))))
24817 (funcall unindent-tree (org-element-contents parse-tree))))
24819 (defun org-show-children (&optional level)
24820 "Show all direct subheadings of this heading.
24821 Prefix arg LEVEL is how many levels below the current level
24822 should be shown. Default is enough to cause the following
24823 heading to appear."
24824 (interactive "p")
24825 ;; If `orgstruct-mode' is active, use the slower version.
24826 (if orgstruct-mode (call-interactively #'outline-show-children)
24827 (save-excursion
24828 (org-back-to-heading t)
24829 (let* ((current-level (funcall outline-level))
24830 (max-level (org-get-valid-level
24831 current-level
24832 (if level (prefix-numeric-value level) 1)))
24833 (end (save-excursion (org-end-of-subtree t t)))
24834 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24835 (past-first-child nil)
24836 ;; Make sure to skip inlinetasks.
24837 (re (format regexp-fmt
24838 current-level
24839 (cond
24840 ((not (featurep 'org-inlinetask)) "")
24841 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24843 (t (1- org-inlinetask-min-level))))))
24844 ;; Display parent heading.
24845 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24846 (forward-line)
24847 ;; Display children. First child may be deeper than expected
24848 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24849 ;; MAX-LEVEL accordingly.
24850 (while (re-search-forward re end t)
24851 (unless past-first-child
24852 (setq re (format regexp-fmt
24853 current-level
24854 (max (funcall outline-level) max-level)))
24855 (setq past-first-child t))
24856 (outline-flag-region
24857 (line-end-position 0) (line-end-position) nil))))))
24859 (defun org-show-subtree ()
24860 "Show everything after this heading at deeper levels."
24861 (interactive)
24862 (outline-flag-region
24863 (point)
24864 (save-excursion
24865 (org-end-of-subtree t t))
24866 nil))
24868 (defun org-show-entry ()
24869 "Show the body directly following this heading.
24870 Show the heading too, if it is currently invisible."
24871 (interactive)
24872 (save-excursion
24873 (ignore-errors
24874 (org-back-to-heading t)
24875 (outline-flag-region
24876 (max (point-min) (1- (point)))
24877 (save-excursion
24878 (if (re-search-forward
24879 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24880 (match-beginning 1)
24881 (point-max)))
24882 nil)
24883 (org-cycle-hide-drawers 'children))))
24885 (defun org-make-options-regexp (kwds &optional extra)
24886 "Make a regular expression for keyword lines.
24887 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24888 when non-nil, is a regexp matching keywords names."
24889 (concat "^[ \t]*#\\+\\("
24890 (regexp-opt kwds)
24891 (and extra (concat (and kwds "\\|") extra))
24892 "\\):[ \t]*\\(.*\\)"))
24894 ;;;; Integration with and fixes for other packages
24896 ;;; Imenu support
24898 (defvar-local org-imenu-markers nil
24899 "All markers currently used by Imenu.")
24901 (defun org-imenu-new-marker (&optional pos)
24902 "Return a new marker for use by Imenu, and remember the marker."
24903 (let ((m (make-marker)))
24904 (move-marker m (or pos (point)))
24905 (push m org-imenu-markers)
24908 (defun org-imenu-get-tree ()
24909 "Produce the index for Imenu."
24910 (dolist (x org-imenu-markers) (move-marker x nil))
24911 (setq org-imenu-markers nil)
24912 (let* ((case-fold-search nil)
24913 (n org-imenu-depth)
24914 (re (concat "^" (org-get-limited-outline-regexp)))
24915 (subs (make-vector (1+ n) nil))
24916 (last-level 0)
24917 m level head0 head)
24918 (save-excursion
24919 (save-restriction
24920 (widen)
24921 (goto-char (point-max))
24922 (while (re-search-backward re nil t)
24923 (setq level (org-reduced-level (funcall outline-level)))
24924 (when (and (<= level n)
24925 (looking-at org-complex-heading-regexp)
24926 (setq head0 (match-string-no-properties 4)))
24927 (setq head (org-link-display-format head0)
24928 m (org-imenu-new-marker))
24929 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24930 (if (>= level last-level)
24931 (push (cons head m) (aref subs level))
24932 (push (cons head (aref subs (1+ level))) (aref subs level))
24933 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24934 (setq last-level level)))))
24935 (aref subs 1)))
24937 (eval-after-load "imenu"
24938 '(progn
24939 (add-hook 'imenu-after-jump-hook
24940 (lambda ()
24941 (when (derived-mode-p 'org-mode)
24942 (org-show-context 'org-goto))))))
24944 (defun org-link-display-format (s)
24945 "Replace links in string S with their description.
24946 If there is no description, use the link target."
24947 (save-match-data
24948 (replace-regexp-in-string
24949 org-bracket-link-analytic-regexp
24950 (lambda (m)
24951 (if (match-end 5) (match-string 5 m)
24952 (concat (match-string 1 m) (match-string 3 m))))
24953 s nil t)))
24955 (defun org-toggle-link-display ()
24956 "Toggle the literal or descriptive display of links."
24957 (interactive)
24958 (if org-descriptive-links
24959 (progn (org-remove-from-invisibility-spec '(org-link))
24960 (org-restart-font-lock)
24961 (setq org-descriptive-links nil))
24962 (progn (add-to-invisibility-spec '(org-link))
24963 (org-restart-font-lock)
24964 (setq org-descriptive-links t))))
24966 ;; Speedbar support
24968 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24969 "Overlay marking the agenda restriction line in speedbar.")
24970 (overlay-put org-speedbar-restriction-lock-overlay
24971 'face 'org-agenda-restriction-lock)
24972 (overlay-put org-speedbar-restriction-lock-overlay
24973 'help-echo "Agendas are currently limited to this item.")
24974 (delete-overlay org-speedbar-restriction-lock-overlay)
24976 (defun org-speedbar-set-agenda-restriction ()
24977 "Restrict future agenda commands to the location at point in speedbar.
24978 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24979 (interactive)
24980 (require 'org-agenda)
24981 (let (p m tp np dir txt)
24982 (cond
24983 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24984 'org-imenu t))
24985 (setq m (get-text-property p 'org-imenu-marker))
24986 (with-current-buffer (marker-buffer m)
24987 (goto-char m)
24988 (org-agenda-set-restriction-lock 'subtree)))
24989 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24990 'speedbar-function 'speedbar-find-file))
24991 (setq tp (previous-single-property-change
24992 (1+ p) 'speedbar-function)
24993 np (next-single-property-change
24994 tp 'speedbar-function)
24995 dir (speedbar-line-directory)
24996 txt (buffer-substring-no-properties (or tp (point-min))
24997 (or np (point-max))))
24998 (with-current-buffer (find-file-noselect
24999 (let ((default-directory dir))
25000 (expand-file-name txt)))
25001 (unless (derived-mode-p 'org-mode)
25002 (user-error "Cannot restrict to non-Org-mode file"))
25003 (org-agenda-set-restriction-lock 'file)))
25004 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25005 (move-overlay org-speedbar-restriction-lock-overlay
25006 (point-at-bol) (point-at-eol))
25007 (setq current-prefix-arg nil)
25008 (org-agenda-maybe-redo)))
25010 (defvar speedbar-file-key-map)
25011 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25012 (eval-after-load "speedbar"
25013 '(progn
25014 (speedbar-add-supported-extension ".org")
25015 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25016 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25017 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25018 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25019 (add-hook 'speedbar-visiting-tag-hook
25020 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25022 ;;; Fixes and Hacks for problems with other packages
25024 (defun org--flyspell-object-check-p (element)
25025 "Non-nil when Flyspell can check object at point.
25026 ELEMENT is the element at point."
25027 (let ((object (save-excursion
25028 (when (looking-at-p "\\>") (backward-char))
25029 (org-element-context element))))
25030 (cl-case (org-element-type object)
25031 ;; Prevent checks in links due to keybinding conflict with
25032 ;; Flyspell.
25033 ((code entity export-snippet inline-babel-call
25034 inline-src-block line-break latex-fragment link macro
25035 statistics-cookie target timestamp verbatim)
25036 nil)
25037 (footnote-reference
25038 ;; Only in inline footnotes, within the definition.
25039 (and (eq (org-element-property :type object) 'inline)
25040 (< (save-excursion
25041 (goto-char (org-element-property :begin object))
25042 (search-forward ":" nil t 2))
25043 (point))))
25044 (otherwise t))))
25046 (defun org-mode-flyspell-verify ()
25047 "Function used for `flyspell-generic-check-word-predicate'."
25048 (if (org-at-heading-p)
25049 ;; At a headline or an inlinetask, check title only. This is
25050 ;; faster than relying on `org-element-at-point'.
25051 (and (save-excursion (beginning-of-line)
25052 (and (let ((case-fold-search t))
25053 (not (looking-at "\\*+ END[ \t]*$")))
25054 (looking-at org-complex-heading-regexp)))
25055 (match-beginning 4)
25056 (>= (point) (match-beginning 4))
25057 (or (not (match-beginning 5))
25058 (< (point) (match-beginning 5))))
25059 (let* ((element (org-element-at-point))
25060 (post-affiliated (org-element-property :post-affiliated element)))
25061 (cond
25062 ;; Ignore checks in all affiliated keywords but captions.
25063 ((< (point) post-affiliated)
25064 (and (save-excursion
25065 (beginning-of-line)
25066 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25067 (> (point) (match-end 0))
25068 (org--flyspell-object-check-p element)))
25069 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25070 ((let ((log (org-log-into-drawer)))
25071 (and log
25072 (let ((drawer (org-element-lineage element '(drawer))))
25073 (and drawer
25074 (eq (compare-strings
25075 log nil nil
25076 (org-element-property :drawer-name drawer) nil nil t)
25077 t)))))
25078 nil)
25080 (cl-case (org-element-type element)
25081 ((comment quote-section) t)
25082 (comment-block
25083 ;; Allow checks between block markers, not on them.
25084 (and (> (line-beginning-position) post-affiliated)
25085 (save-excursion
25086 (end-of-line)
25087 (skip-chars-forward " \r\t\n")
25088 (< (point) (org-element-property :end element)))))
25089 ;; Arbitrary list of keywords where checks are meaningful.
25090 ;; Make sure point is on the value part of the element.
25091 (keyword
25092 (and (member (org-element-property :key element)
25093 '("DESCRIPTION" "TITLE"))
25094 (save-excursion
25095 (search-backward ":" (line-beginning-position) t))))
25096 ;; Check is globally allowed in paragraphs verse blocks and
25097 ;; table rows (after affiliated keywords) but some objects
25098 ;; must not be affected.
25099 ((paragraph table-row verse-block)
25100 (let ((cbeg (org-element-property :contents-begin element))
25101 (cend (org-element-property :contents-end element)))
25102 (and cbeg (>= (point) cbeg) (< (point) cend)
25103 (org--flyspell-object-check-p element))))))))))
25104 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25106 (defun org-remove-flyspell-overlays-in (beg end)
25107 "Remove flyspell overlays in region."
25108 (and (bound-and-true-p flyspell-mode)
25109 (fboundp 'flyspell-delete-region-overlays)
25110 (flyspell-delete-region-overlays beg end)))
25112 (defvar flyspell-delayed-commands)
25113 (eval-after-load "flyspell"
25114 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25116 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25117 (eval-after-load "bookmark"
25118 '(if (boundp 'bookmark-after-jump-hook)
25119 ;; We can use the hook
25120 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25121 ;; Hook not available, use advice
25122 (defadvice bookmark-jump (after org-make-visible activate)
25123 "Make the position visible."
25124 (org-bookmark-jump-unhide))))
25126 ;; Make sure saveplace shows the location if it was hidden
25127 (eval-after-load "saveplace"
25128 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25129 "Make the position visible."
25130 (org-bookmark-jump-unhide)))
25132 ;; Make sure ecb shows the location if it was hidden
25133 (eval-after-load "ecb"
25134 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25135 "Make hierarchy visible when jumping into location from ECB tree buffer."
25136 (when (derived-mode-p 'org-mode)
25137 (org-show-context))))
25139 (defun org-bookmark-jump-unhide ()
25140 "Unhide the current position, to show the bookmark location."
25141 (and (derived-mode-p 'org-mode)
25142 (or (outline-invisible-p)
25143 (save-excursion (goto-char (max (point-min) (1- (point))))
25144 (outline-invisible-p)))
25145 (org-show-context 'bookmark-jump)))
25147 (defun org-mark-jump-unhide ()
25148 "Make the point visible with `org-show-context' after jumping to the mark."
25149 (when (and (derived-mode-p 'org-mode)
25150 (outline-invisible-p))
25151 (org-show-context 'mark-goto)))
25153 (eval-after-load "simple"
25154 '(defadvice pop-to-mark-command (after org-make-visible activate)
25155 "Make the point visible with `org-show-context'."
25156 (org-mark-jump-unhide)))
25158 (eval-after-load "simple"
25159 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25160 "Make the point visible with `org-show-context'."
25161 (org-mark-jump-unhide)))
25163 (eval-after-load "simple"
25164 '(defadvice pop-global-mark (after org-make-visible activate)
25165 "Make the point visible with `org-show-context'."
25166 (org-mark-jump-unhide)))
25168 ;; Make session.el ignore our circular variable
25169 (defvar session-globals-exclude)
25170 (eval-after-load "session"
25171 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25173 ;;;; Finish up
25175 (provide 'org)
25177 (run-hooks 'org-load-hook)
25179 ;;; org.el ends here