Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob680086df27f8ef5f50b303551e0fb222fb4a44ab
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 etc/ directory of Emacs 22.
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-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-edit-field "org-table" (arg))
160 (declare-function org-table-end "org-table" (&optional table-type))
161 (declare-function org-table-end-of-field "org-table" (&optional n))
162 (declare-function org-table-insert-row "org-table" (&optional arg))
163 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
164 (declare-function org-table-maybe-eval-formula "org-table" ())
165 (declare-function org-table-maybe-recalculate-line "org-table" ())
166 (declare-function org-table-next-row "org-table" ())
167 (declare-function org-table-paste-rectangle "org-table" ())
168 (declare-function org-table-wrap-region "org-table" (arg))
169 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
170 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
171 (declare-function orgtbl-mode "org-table" (&optional arg))
173 (defsubst org-uniquify (list)
174 "Non-destructively remove duplicate elements from LIST."
175 (let ((res (copy-sequence list))) (delete-dups res)))
177 (defsubst org-get-at-bol (property)
178 "Get text property PROPERTY at the beginning of line."
179 (get-text-property (point-at-bol) property))
181 (defsubst org-trim (s)
182 "Remove whitespace at the beginning and the end of string S."
183 (replace-regexp-in-string
184 "\\`[ \t\n\r]+" ""
185 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
187 ;; load languages based on value of `org-babel-load-languages'
188 (defvar org-babel-load-languages)
190 ;;;###autoload
191 (defun org-babel-do-load-languages (sym value)
192 "Load the languages defined in `org-babel-load-languages'."
193 (set-default sym value)
194 (dolist (pair org-babel-load-languages)
195 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
196 (if active
197 (require (intern (concat "ob-" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-execute:" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-expand-body:" lang)))))))
203 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
204 ;;;###autoload
205 (defun org-babel-load-file (file &optional compile)
206 "Load Emacs Lisp source code blocks in the Org-mode FILE.
207 This function exports the source code using `org-babel-tangle'
208 and then loads the resulting file using `load-file'. With prefix
209 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
210 file to byte-code before it is loaded."
211 (interactive "fFile to load: \nP")
212 (let* ((age (lambda (file)
213 (float-time
214 (time-subtract (current-time)
215 (nth 5 (or (file-attributes (file-truename file))
216 (file-attributes file)))))))
217 (base-name (file-name-sans-extension file))
218 (exported-file (concat base-name ".el")))
219 ;; tangle if the org-mode file is newer than the elisp file
220 (unless (and (file-exists-p exported-file)
221 (> (funcall age file) (funcall age exported-file)))
222 ;; Tangle-file traversal returns reversed list of tangled files
223 ;; and we want to evaluate the first target.
224 (setq exported-file
225 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
226 (message "%s %s"
227 (if compile
228 (progn (byte-compile-file exported-file 'load)
229 "Compiled and loaded")
230 (progn (load-file exported-file) "Loaded"))
231 exported-file)))
233 (defcustom org-babel-load-languages '((emacs-lisp . t))
234 "Languages which can be evaluated in Org-mode buffers.
235 This list can be used to load support for any of the languages
236 below, note that each language will depend on a different set of
237 system executables and/or Emacs modes. When a language is
238 \"loaded\", then code blocks in that language can be evaluated
239 with `org-babel-execute-src-block' bound by default to C-c
240 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
241 be set to remove code block evaluation from the C-c C-c
242 keybinding. By default only Emacs Lisp (which has no
243 requirements) is loaded."
244 :group 'org-babel
245 :set 'org-babel-do-load-languages
246 :version "24.1"
247 :type '(alist :tag "Babel Languages"
248 :key-type
249 (choice
250 (const :tag "Awk" awk)
251 (const :tag "C" C)
252 (const :tag "R" R)
253 (const :tag "Asymptote" asymptote)
254 (const :tag "Calc" calc)
255 (const :tag "Clojure" clojure)
256 (const :tag "CSS" css)
257 (const :tag "Ditaa" ditaa)
258 (const :tag "Dot" dot)
259 (const :tag "Emacs Lisp" emacs-lisp)
260 (const :tag "Forth" forth)
261 (const :tag "Fortran" fortran)
262 (const :tag "Gnuplot" gnuplot)
263 (const :tag "Haskell" haskell)
264 (const :tag "IO" io)
265 (const :tag "J" J)
266 (const :tag "Java" java)
267 (const :tag "Javascript" js)
268 (const :tag "LaTeX" latex)
269 (const :tag "Ledger" ledger)
270 (const :tag "Lilypond" lilypond)
271 (const :tag "Lisp" lisp)
272 (const :tag "Makefile" makefile)
273 (const :tag "Maxima" maxima)
274 (const :tag "Matlab" matlab)
275 (const :tag "Mscgen" mscgen)
276 (const :tag "Ocaml" ocaml)
277 (const :tag "Octave" octave)
278 (const :tag "Org" org)
279 (const :tag "Perl" perl)
280 (const :tag "Pico Lisp" picolisp)
281 (const :tag "PlantUML" plantuml)
282 (const :tag "Python" python)
283 (const :tag "Ruby" ruby)
284 (const :tag "Sass" sass)
285 (const :tag "Scala" scala)
286 (const :tag "Scheme" scheme)
287 (const :tag "Screen" screen)
288 (const :tag "Shell Script" shell)
289 (const :tag "Shen" shen)
290 (const :tag "Sql" sql)
291 (const :tag "Sqlite" sqlite)
292 (const :tag "Stan" stan)
293 (const :tag "ebnf2ps" ebnf2ps))
294 :value-type (boolean :tag "Activate" :value t)))
296 ;;;; Customization variables
297 (defcustom org-clone-delete-id nil
298 "Remove ID property of clones of a subtree.
299 When non-nil, clones of a subtree don't inherit the ID property.
300 Otherwise they inherit the ID property with a new unique
301 identifier."
302 :type 'boolean
303 :version "24.1"
304 :group 'org-id)
306 ;;; Version
307 (org-check-version)
309 ;;;###autoload
310 (defun org-version (&optional here full message)
311 "Show the org-mode version.
312 Interactively, or when MESSAGE is non-nil, show it in echo area.
313 With prefix argument, or when HERE is non-nil, insert it at point.
314 In non-interactive uses, a reduced version string is output unless
315 FULL is given."
316 (interactive (list current-prefix-arg t (not current-prefix-arg)))
317 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
318 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
319 (load-suffixes (list ".el"))
320 (org-install-dir
321 (ignore-errors (org-find-library-dir "org-loaddefs"))))
322 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
323 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
324 (let* ((load-suffixes save-load-suffixes)
325 (release (org-release))
326 (git-version (org-git-version))
327 (version (format "Org-mode version %s (%s @ %s)"
328 release
329 git-version
330 (if org-install-dir
331 (if (string= org-dir org-install-dir)
332 org-install-dir
333 (concat "mixed installation! "
334 org-install-dir
335 " and "
336 org-dir))
337 "org-loaddefs.el can not be found!")))
338 (version1 (if full version release)))
339 (when here (insert version1))
340 (when message (message "%s" version1))
341 version1)))
343 (defconst org-version (org-version))
346 ;;; Syntax Constants
348 ;;;; Block
350 (defconst org-block-regexp
351 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
352 "Regular expression for hiding blocks.")
354 (defconst org-dblock-start-re
355 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
356 "Matches the start line of a dynamic block, with parameters.")
358 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
359 "Matches the end of a dynamic block.")
361 ;;;; Clock and Planning
363 (defconst org-clock-string "CLOCK:"
364 "String used as prefix for timestamps clocking work hours on an item.")
366 (defvar org-closed-string "CLOSED:"
367 "String used as the prefix for timestamps logging closing a TODO entry.")
369 (defvar org-deadline-string "DEADLINE:"
370 "String to mark deadline entries.
371 A deadline is this string, followed by a time stamp. Should be a word,
372 terminated by a colon. You can insert a schedule keyword and
373 a timestamp with \\[org-deadline].")
375 (defvar org-scheduled-string "SCHEDULED:"
376 "String to mark scheduled TODO entries.
377 A schedule is this string, followed by a time stamp. Should be a word,
378 terminated by a colon. You can insert a schedule keyword and
379 a timestamp with \\[org-schedule].")
381 (defconst org-ds-keyword-length
382 (+ 2
383 (apply #'max
384 (mapcar #'length
385 (list org-deadline-string org-scheduled-string
386 org-clock-string org-closed-string))))
387 "Maximum length of the DEADLINE and SCHEDULED keywords.")
389 (defconst org-planning-line-re
390 (concat "^[ \t]*"
391 (regexp-opt
392 (list org-closed-string org-deadline-string org-scheduled-string)
394 "Matches a line with planning info.
395 Matched keyword is in group 1.")
397 (defconst org-clock-line-re
398 (concat "^[ \t]*" org-clock-string)
399 "Matches a line with clock info.")
401 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
402 "Matches the DEADLINE keyword.")
404 (defconst org-deadline-time-regexp
405 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
406 "Matches the DEADLINE keyword together with a time stamp.")
408 (defconst org-deadline-time-hour-regexp
409 (concat "\\<" org-deadline-string
410 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
411 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
413 (defconst org-deadline-line-regexp
414 (concat "\\<\\(" org-deadline-string "\\).*")
415 "Matches the DEADLINE keyword and the rest of the line.")
417 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
418 "Matches the SCHEDULED keyword.")
420 (defconst org-scheduled-time-regexp
421 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
422 "Matches the SCHEDULED keyword together with a time stamp.")
424 (defconst org-scheduled-time-hour-regexp
425 (concat "\\<" org-scheduled-string
426 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
427 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
429 (defconst org-closed-time-regexp
430 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
431 "Matches the CLOSED keyword together with a time stamp.")
433 (defconst org-keyword-time-regexp
434 (concat "\\<"
435 (regexp-opt
436 (list org-scheduled-string org-deadline-string org-closed-string
437 org-clock-string)
439 " *[[<]\\([^]>]+\\)[]>]")
440 "Matches any of the 4 keywords, together with the time stamp.")
442 (defconst org-keyword-time-not-clock-regexp
443 (concat
444 "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string) t)
447 " *[[<]\\([^]>]+\\)[]>]")
448 "Matches any of the 3 keywords, together with the time stamp.")
450 (defconst org-maybe-keyword-time-regexp
451 (concat "\\(\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string
454 org-clock-string)
456 "\\)?"
457 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
458 "\\|"
459 "<%%([^\r\n>]*>\\)")
460 "Matches a timestamp, possibly preceded by a keyword.")
462 (defconst org-all-time-keywords
463 (mapcar (lambda (w) (substring w 0 -1))
464 (list org-scheduled-string org-deadline-string
465 org-clock-string org-closed-string))
466 "List of time keywords.")
468 ;;;; Drawer
470 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
471 "Matches first or last line of a hidden block.
472 Group 1 contains drawer's name or \"END\".")
474 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
475 "Regular expression matching the first line of a property drawer.")
477 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
478 "Regular expression matching the last line of a property drawer.")
480 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
481 "Regular expression matching the first line of a clock drawer.")
483 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a clock drawer.")
486 (defconst org-property-drawer-re
487 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
488 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
489 "[ \t]*:END:[ \t]*$")
490 "Matches an entire property drawer.")
492 (defconst org-clock-drawer-re
493 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
494 org-clock-drawer-end-re "\\)\n?")
495 "Matches an entire clock drawer.")
497 ;;;; Headline
499 (defconst org-heading-keyword-regexp-format
500 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
501 "Printf format for a regexp matching a headline with some keyword.
502 This regexp will match the headline of any node which has the
503 exact keyword that is put into the format. The keyword isn't in
504 any group by default, but the stars and the body are.")
506 (defconst org-heading-keyword-maybe-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline, possibly with some keyword.
509 This regexp can match any headline with the specified keyword, or
510 without a keyword. The keyword isn't in any group by default,
511 but the stars and the body are.")
513 (defconst org-archive-tag "ARCHIVE"
514 "The tag that marks a subtree as archived.
515 An archived subtree does not open during visibility cycling, and does
516 not contribute to the agenda listings.")
518 (defconst org-comment-string "COMMENT"
519 "Entries starting with this keyword will never be exported.
520 An entry can be toggled between COMMENT and normal with
521 \\[org-toggle-comment].")
524 ;;;; LaTeX Environments and Fragments
526 (defconst org-latex-regexps
527 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
528 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
529 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
530 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
531 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
532 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
533 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
534 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
535 "Regular expressions for matching embedded LaTeX.")
537 ;;;; Node Property
539 (defconst org-effort-property "Effort"
540 "The property that is being used to keep track of effort estimates.
541 Effort estimates given in this property need to have the format H:MM.")
543 ;;;; Table
545 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
546 "Detect an org-type or table-type table.")
548 (defconst org-table-line-regexp "^[ \t]*|"
549 "Detect an org-type table line.")
551 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
552 "Detect an org-type table line.")
554 (defconst org-table-hline-regexp "^[ \t]*|-"
555 "Detect an org-type table hline.")
557 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
558 "Detect a table-type table hline.")
560 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
561 "Detect the first line outside a table when searching from within it.
562 This works for both table types.")
564 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
565 "Detect a #+TBLFM line.")
567 ;;;; Timestamp
569 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
570 "Regular expression for fast time stamp matching.")
572 (defconst org-ts-regexp-inactive
573 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
574 "Regular expression for fast inactive time stamp matching.")
576 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
577 "Regular expression for fast time stamp matching.")
579 (defconst org-ts-regexp0
580 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
581 "Regular expression matching time strings for analysis.
582 This one does not require the space after the date, so it can be used
583 on a string that terminates immediately after the date.")
585 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
586 "Regular expression matching time strings for analysis.")
588 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
589 "Regular expression matching time stamps, with groups.")
591 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
592 "Regular expression matching time stamps (also [..]), with groups.")
594 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
595 "Regular expression matching a time stamp range.")
597 (defconst org-tr-regexp-both
598 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
599 "Regular expression matching a time stamp range.")
601 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
602 org-ts-regexp "\\)?")
603 "Regular expression matching a time stamp or time stamp range.")
605 (defconst org-tsr-regexp-both
606 (concat org-ts-regexp-both "\\(--?-?"
607 org-ts-regexp-both "\\)?")
608 "Regular expression matching a time stamp or time stamp range.
609 The time stamps may be either active or inactive.")
611 (defconst org-repeat-re
612 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
613 "Regular expression for specifying repeated events.
614 After a match, group 1 contains the repeat expression.")
616 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
617 "Formats for `format-time-string' which are used for time stamps.")
620 ;;; The custom variables
622 (defgroup org nil
623 "Outline-based notes management and organizer."
624 :tag "Org"
625 :group 'outlines
626 :group 'calendar)
628 (defcustom org-mode-hook nil
629 "Mode hook for Org-mode, run after the mode was turned on."
630 :group 'org
631 :type 'hook)
633 (defcustom org-load-hook nil
634 "Hook that is run after org.el has been loaded."
635 :group 'org
636 :type 'hook)
638 (defcustom org-log-buffer-setup-hook nil
639 "Hook that is run after an Org log buffer is created."
640 :group 'org
641 :version "24.1"
642 :type 'hook)
644 (defvar org-modules) ; defined below
645 (defvar org-modules-loaded nil
646 "Have the modules been loaded already?")
648 (defun org-load-modules-maybe (&optional force)
649 "Load all extensions listed in `org-modules'."
650 (when (or force (not org-modules-loaded))
651 (dolist (ext org-modules)
652 (condition-case nil (require ext)
653 (error (message "Problems while trying to load feature `%s'" ext))))
654 (setq org-modules-loaded t)))
656 (defun org-set-modules (var value)
657 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
658 (set var value)
659 (when (featurep 'org)
660 (org-load-modules-maybe 'force)
661 (org-element-cache-reset 'all)))
663 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
664 "Modules that should always be loaded together with org.el.
666 If a description starts with <C>, the file is not part of Emacs
667 and loading it will require that you have downloaded and properly
668 installed the Org mode distribution.
670 You can also use this system to load external packages (i.e. neither Org
671 core modules, nor modules from the CONTRIB directory). Just add symbols
672 to the end of the list. If the package is called org-xyz.el, then you need
673 to add the symbol `xyz', and the package must have a call to:
675 (provide \\='org-xyz)
677 For export specific modules, see also `org-export-backends'."
678 :group 'org
679 :set 'org-set-modules
680 :version "24.4"
681 :package-version '(Org . "8.0")
682 :type
683 '(set :greedy t
684 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
685 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
686 (const :tag " crypt: Encryption of subtrees" org-crypt)
687 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
688 (const :tag " docview: Links to doc-view buffers" org-docview)
689 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
690 (const :tag " habit: Track your consistency with habits" org-habit)
691 (const :tag " id: Global IDs for identifying entries" org-id)
692 (const :tag " info: Links to Info nodes" org-info)
693 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
694 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
695 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
696 (const :tag " mouse: Additional mouse support" org-mouse)
697 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
698 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
699 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
701 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
702 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
703 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
704 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
705 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
706 (const :tag "C collector: Collect properties into tables" org-collector)
707 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
708 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
709 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
710 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
711 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
712 (const :tag "C eval: Include command output as text" org-eval)
713 (const :tag "C eww: Store link to url of eww" org-eww)
714 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
715 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
716 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
717 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
718 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
719 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
720 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
721 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
722 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
723 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
724 (const :tag "C mew: Links to Mew folders/messages" org-mew)
725 (const :tag "C mtags: Support for muse-like tags" org-mtags)
726 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
727 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
728 (const :tag "C registry: A registry for Org-mode links" org-registry)
729 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
730 (const :tag "C secretary: Team management with org-mode" org-secretary)
731 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
732 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
733 (const :tag "C track: Keep up with Org-mode development" org-track)
734 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
735 (const :tag "C vm: Links to VM folders/messages" org-vm)
736 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
737 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
738 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
740 (defvar org-export-registered-backends) ; From ox.el.
741 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
742 (declare-function org-export-backend-name "ox" (backend) t)
743 (defcustom org-export-backends '(ascii html icalendar latex odt)
744 "List of export back-ends that should be always available.
746 If a description starts with <C>, the file is not part of Emacs
747 and loading it will require that you have downloaded and properly
748 installed the Org mode distribution.
750 Unlike to `org-modules', libraries in this list will not be
751 loaded along with Org, but only once the export framework is
752 needed.
754 This variable needs to be set before org.el is loaded. If you
755 need to make a change while Emacs is running, use the customize
756 interface or run the following code, where VAL stands for the new
757 value of the variable, after updating it:
759 (progn
760 (setq org-export-registered-backends
761 (cl-remove-if-not
762 (lambda (backend)
763 (let ((name (org-export-backend-name backend)))
764 (or (memq name val)
765 (catch \\='parentp
766 (dolist (b val)
767 (and (org-export-derived-backend-p b name)
768 (throw \\='parentp t)))))))
769 org-export-registered-backends))
770 (let ((new-list (mapcar #\\='org-export-backend-name
771 org-export-registered-backends)))
772 (dolist (backend val)
773 (cond
774 ((not (load (format \"ox-%s\" backend) t t))
775 (message \"Problems while trying to load export back-end \\=`%s\\='\"
776 backend))
777 ((not (memq backend new-list)) (push backend new-list))))
778 (set-default \\='org-export-backends new-list)))
780 Adding a back-end to this list will also pull the back-end it
781 depends on, if any."
782 :group 'org
783 :group 'org-export
784 :version "25.1"
785 :package-version '(Org . "9.0")
786 :initialize 'custom-initialize-set
787 :set (lambda (var val)
788 (if (not (featurep 'ox)) (set-default var val)
789 ;; Any back-end not required anymore (not present in VAL and not
790 ;; a parent of any back-end in the new value) is removed from the
791 ;; list of registered back-ends.
792 (setq org-export-registered-backends
793 (cl-remove-if-not
794 (lambda (backend)
795 (let ((name (org-export-backend-name backend)))
796 (or (memq name val)
797 (catch 'parentp
798 (dolist (b val)
799 (and (org-export-derived-backend-p b name)
800 (throw 'parentp t)))))))
801 org-export-registered-backends))
802 ;; Now build NEW-LIST of both new back-ends and required
803 ;; parents.
804 (let ((new-list (mapcar #'org-export-backend-name
805 org-export-registered-backends)))
806 (dolist (backend val)
807 (cond
808 ((not (load (format "ox-%s" backend) t t))
809 (message "Problems while trying to load export back-end `%s'"
810 backend))
811 ((not (memq backend new-list)) (push backend new-list))))
812 ;; Set VAR to that list with fixed dependencies.
813 (set-default var new-list))))
814 :type '(set :greedy t
815 (const :tag " ascii Export buffer to ASCII format" ascii)
816 (const :tag " beamer Export buffer to Beamer presentation" beamer)
817 (const :tag " html Export buffer to HTML format" html)
818 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
819 (const :tag " latex Export buffer to LaTeX format" latex)
820 (const :tag " man Export buffer to MAN format" man)
821 (const :tag " md Export buffer to Markdown format" md)
822 (const :tag " odt Export buffer to ODT format" odt)
823 (const :tag " org Export buffer to Org format" org)
824 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
825 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
826 (const :tag "C deck Export buffer to deck.js presentations" deck)
827 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
828 (const :tag "C groff Export buffer to Groff format" groff)
829 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
830 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
831 (const :tag "C s5 Export buffer to s5 presentations" s5)
832 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
834 (eval-after-load 'ox
835 '(dolist (backend org-export-backends)
836 (condition-case nil (require (intern (format "ox-%s" backend)))
837 (error (message "Problems while trying to load export back-end `%s'"
838 backend)))))
840 (defcustom org-support-shift-select nil
841 "Non-nil means make shift-cursor commands select text when possible.
842 \\<org-mode-map>\
844 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
845 start selecting a region, or enlarge regions started in this way.
846 In Org-mode, in special contexts, these same keys are used for
847 other purposes, important enough to compete with shift selection.
848 Org tries to balance these needs by supporting `shift-select-mode'
849 outside these special contexts, under control of this variable.
851 The default of this variable is nil, to avoid confusing behavior. Shifted
852 cursor keys will then execute Org commands in the following contexts:
853 - on a headline, changing TODO state (left/right) and priority (up/down)
854 - on a time stamp, changing the time
855 - in a plain list item, changing the bullet type
856 - in a property definition line, switching between allowed values
857 - in the BEGIN line of a clock table (changing the time block).
858 Outside these contexts, the commands will throw an error.
860 When this variable is t and the cursor is not in a special
861 context, Org-mode will support shift-selection for making and
862 enlarging regions. To make this more effective, the bullet
863 cycling will no longer happen anywhere in an item line, but only
864 if the cursor is exactly on the bullet.
866 If you set this variable to the symbol `always', then the keys
867 will not be special in headlines, property lines, and item lines,
868 to make shift selection work there as well. If this is what you
869 want, you can use the following alternative commands:
870 `\\[org-todo]' and `\\[org-priority]' \
871 to change TODO state and priority,
872 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
873 can be used to switch TODO sets,
874 `\\[org-ctrl-c-minus]' to cycle item bullet types,
875 and properties can be edited by hand or in column view.
877 However, when the cursor is on a timestamp, shift-cursor commands
878 will still edit the time stamp - this is just too good to give up."
879 :group 'org
880 :type '(choice
881 (const :tag "Never" nil)
882 (const :tag "When outside special context" t)
883 (const :tag "Everywhere except timestamps" always)))
885 (defcustom org-loop-over-headlines-in-active-region nil
886 "Shall some commands act upon headlines in the active region?
888 When set to t, some commands will be performed in all headlines
889 within the active region.
891 When set to `start-level', some commands will be performed in all
892 headlines within the active region, provided that these headlines
893 are of the same level than the first one.
895 When set to a string, those commands will be performed on the
896 matching headlines within the active region. Such string must be
897 a tags/property/todo match as it is used in the agenda tags view.
899 The list of commands is: `org-schedule', `org-deadline',
900 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
901 `org-archive-to-archive-sibling'. The archiving commands skip
902 already archived entries."
903 :type '(choice (const :tag "Don't loop" nil)
904 (const :tag "All headlines in active region" t)
905 (const :tag "In active region, headlines at the same level than the first one" start-level)
906 (string :tag "Tags/Property/Todo matcher"))
907 :version "24.1"
908 :group 'org-todo
909 :group 'org-archive)
911 (defgroup org-startup nil
912 "Options concerning startup of Org-mode."
913 :tag "Org Startup"
914 :group 'org)
916 (defcustom org-startup-folded t
917 "Non-nil means entering Org-mode will switch to OVERVIEW.
918 This can also be configured on a per-file basis by adding one of
919 the following lines anywhere in the buffer:
921 #+STARTUP: fold (or `overview', this is equivalent)
922 #+STARTUP: nofold (or `showall', this is equivalent)
923 #+STARTUP: content
924 #+STARTUP: showeverything
926 By default, this option is ignored when Org opens agenda files
927 for the first time. If you want the agenda to honor the startup
928 option, set `org-agenda-inhibit-startup' to nil."
929 :group 'org-startup
930 :type '(choice
931 (const :tag "nofold: show all" nil)
932 (const :tag "fold: overview" t)
933 (const :tag "content: all headlines" content)
934 (const :tag "show everything, even drawers" showeverything)))
936 (defcustom org-startup-truncated t
937 "Non-nil means entering Org-mode will set `truncate-lines'.
938 This is useful since some lines containing links can be very long and
939 uninteresting. Also tables look terrible when wrapped."
940 :group 'org-startup
941 :type 'boolean)
943 (defcustom org-startup-indented nil
944 "Non-nil means turn on `org-indent-mode' on startup.
945 This can also be configured on a per-file basis by adding one of
946 the following lines anywhere in the buffer:
948 #+STARTUP: indent
949 #+STARTUP: noindent"
950 :group 'org-structure
951 :type '(choice
952 (const :tag "Not" nil)
953 (const :tag "Globally (slow on startup in large files)" t)))
955 (defcustom org-use-sub-superscripts t
956 "Non-nil means interpret \"_\" and \"^\" for display.
958 If you want to control how Org exports those characters, see
959 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
960 used to be an alias for `org-export-with-sub-superscripts' in
961 Org <8.0, it is not anymore.
963 When this option is turned on, you can use TeX-like syntax for
964 sub- and superscripts within the buffer. Several characters after
965 \"_\" or \"^\" will be considered as a single item - so grouping
966 with {} is normally not needed. For example, the following things
967 will be parsed as single sub- or superscripts:
969 10^24 or 10^tau several digits will be considered 1 item.
970 10^-12 or 10^-tau a leading sign with digits or a word
971 x^2-y^3 will be read as x^2 - y^3, because items are
972 terminated by almost any nonword/nondigit char.
973 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
975 Still, ambiguity is possible. So when in doubt, use {} to enclose
976 the sub/superscript. If you set this variable to the symbol `{}',
977 the braces are *required* in order to trigger interpretations as
978 sub/superscript. This can be helpful in documents that need \"_\"
979 frequently in plain text."
980 :group 'org-startup
981 :version "24.4"
982 :package-version '(Org . "8.0")
983 :type '(choice
984 (const :tag "Always interpret" t)
985 (const :tag "Only with braces" {})
986 (const :tag "Never interpret" nil)))
988 (defcustom org-startup-with-beamer-mode nil
989 "Non-nil means turn on `org-beamer-mode' on startup.
990 This can also be configured on a per-file basis by adding one of
991 the following lines anywhere in the buffer:
993 #+STARTUP: beamer"
994 :group 'org-startup
995 :version "24.1"
996 :type 'boolean)
998 (defcustom org-startup-align-all-tables nil
999 "Non-nil means align all tables when visiting a file.
1000 This is useful when the column width in tables is forced with <N> cookies
1001 in table fields. Such tables will look correct only after the first re-align.
1002 This can also be configured on a per-file basis by adding one of
1003 the following lines anywhere in the buffer:
1004 #+STARTUP: align
1005 #+STARTUP: noalign"
1006 :group 'org-startup
1007 :type 'boolean)
1009 (defcustom org-startup-with-inline-images nil
1010 "Non-nil means show inline images when loading a new Org file.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1013 #+STARTUP: inlineimages
1014 #+STARTUP: noinlineimages"
1015 :group 'org-startup
1016 :version "24.1"
1017 :type 'boolean)
1019 (defcustom org-startup-with-latex-preview nil
1020 "Non-nil means preview LaTeX fragments when loading a new Org file.
1022 This can also be configured on a per-file basis by adding one of
1023 the following lines anywhere in the buffer:
1024 #+STARTUP: latexpreview
1025 #+STARTUP: nolatexpreview"
1026 :group 'org-startup
1027 :version "24.4"
1028 :package-version '(Org . "8.0")
1029 :type 'boolean)
1031 (defcustom org-insert-mode-line-in-empty-file nil
1032 "Non-nil means insert the first line setting Org-mode in empty files.
1033 When the function `org-mode' is called interactively in an empty file, this
1034 normally means that the file name does not automatically trigger Org-mode.
1035 To ensure that the file will always be in Org-mode in the future, a
1036 line enforcing Org-mode will be inserted into the buffer, if this option
1037 has been set."
1038 :group 'org-startup
1039 :type 'boolean)
1041 (defcustom org-replace-disputed-keys nil
1042 "Non-nil means use alternative key bindings for some keys.
1043 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1044 These keys are also used by other packages like shift-selection-mode'
1045 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1046 If you want to use Org-mode together with one of these other modes,
1047 or more generally if you would like to move some Org-mode commands to
1048 other keys, set this variable and configure the keys with the variable
1049 `org-disputed-keys'.
1051 This option is only relevant at load-time of Org-mode, and must be set
1052 *before* org.el is loaded. Changing it requires a restart of Emacs to
1053 become effective."
1054 :group 'org-startup
1055 :type 'boolean)
1057 (defcustom org-use-extra-keys nil
1058 "Non-nil means use extra key sequence definitions for certain commands.
1059 This happens automatically if `window-system' is nil. This
1060 variable lets you do the same manually. You must set it before
1061 loading org.
1063 Example: on Carbon Emacs 22 running graphically, with an external
1064 keyboard on a Powerbook, the default way of setting M-left might
1065 not work for either Alt or ESC. Setting this variable will make
1066 it work for ESC."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1072 (defcustom org-disputed-keys
1073 '(([(shift up)] . [(meta p)])
1074 ([(shift down)] . [(meta n)])
1075 ([(shift left)] . [(meta -)])
1076 ([(shift right)] . [(meta +)])
1077 ([(control shift right)] . [(meta shift +)])
1078 ([(control shift left)] . [(meta shift -)]))
1079 "Keys for which Org-mode and other modes compete.
1080 This is an alist, cars are the default keys, second element specifies
1081 the alternative to use when `org-replace-disputed-keys' is t.
1083 Keys can be specified in any syntax supported by `define-key'.
1084 The value of this option takes effect only at Org-mode's startup,
1085 therefore you'll have to restart Emacs to apply it after changing."
1086 :group 'org-startup
1087 :type 'alist)
1089 (defun org-key (key)
1090 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1091 Or return the original if not disputed."
1092 (when org-replace-disputed-keys
1093 (let* ((nkey (key-description key))
1094 (x (org-find-if (lambda (x)
1095 (equal (key-description (car x)) nkey))
1096 org-disputed-keys)))
1097 (setq key (if x (cdr x) key))))
1098 key)
1100 (defun org-find-if (predicate seq)
1101 (catch 'exit
1102 (while seq
1103 (if (funcall predicate (car seq))
1104 (throw 'exit (car seq))
1105 (pop seq)))))
1107 (defun org-defkey (keymap key def)
1108 "Define a key, possibly translated, as returned by `org-key'."
1109 (define-key keymap (org-key key) def))
1111 (defcustom org-ellipsis nil
1112 "The ellipsis to use in the Org-mode outline.
1113 When nil, just use the standard three dots.
1114 When a string, use that string instead.
1115 When a face, use the standard 3 dots, but with the specified face.
1116 The change affects only Org-mode (which will then use its own display table).
1117 Changing this requires executing \\[org-mode] in a buffer to become
1118 effective."
1119 :group 'org-startup
1120 :type '(choice (const :tag "Default" nil)
1121 (face :tag "Face" :value org-warning)
1122 (string :tag "String" :value "...#")))
1124 (defvar org-display-table nil
1125 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1127 (defgroup org-keywords nil
1128 "Keywords in Org-mode."
1129 :tag "Org Keywords"
1130 :group 'org)
1132 (defcustom org-closed-keep-when-no-todo nil
1133 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1134 :group 'org-todo
1135 :group 'org-keywords
1136 :version "24.4"
1137 :package-version '(Org . "8.0")
1138 :type 'boolean)
1140 (defgroup org-structure nil
1141 "Options concerning the general structure of Org-mode files."
1142 :tag "Org Structure"
1143 :group 'org)
1145 (defgroup org-reveal-location nil
1146 "Options about how to make context of a location visible."
1147 :tag "Org Reveal Location"
1148 :group 'org-structure)
1150 (defcustom org-show-context-detail '((agenda . local)
1151 (bookmark-jump . lineage)
1152 (isearch . lineage)
1153 (default . ancestors))
1154 "Alist between context and visibility span when revealing a location.
1156 \\<org-mode-map>Some actions may move point into invisible
1157 locations. As a consequence, Org always expose a neighborhood
1158 around point. How much is shown depends on the initial action,
1159 or context. Valid contexts are
1161 agenda when exposing an entry from the agenda
1162 org-goto when using the command `org-goto' (\\[org-goto])
1163 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1164 tags-tree when constructing a sparse tree based on tags matches
1165 link-search when exposing search matches associated with a link
1166 mark-goto when exposing the jump goal of a mark
1167 bookmark-jump when exposing a bookmark location
1168 isearch when exiting from an incremental search
1169 default default for all contexts not set explicitly
1171 Allowed visibility spans are
1173 minimal show current headline; if point is not on headline,
1174 also show entry
1176 local show current headline, entry and next headline
1178 ancestors show current headline and its direct ancestors; if
1179 point is not on headline, also show entry
1181 lineage show current headline, its direct ancestors and all
1182 their children; if point is not on headline, also show
1183 entry and first child
1185 tree show current headline, its direct ancestors and all
1186 their children; if point is not on headline, also show
1187 entry and all children
1189 canonical show current headline, its direct ancestors along with
1190 their entries and children; if point is not located on
1191 the headline, also show current entry and all children
1193 As special cases, a nil or t value means show all contexts in
1194 `minimal' or `canonical' view, respectively.
1196 Some views can make displayed information very compact, but also
1197 make it harder to edit the location of the match. In such
1198 a case, use the command `org-reveal' (\\[org-reveal]) to show
1199 more context."
1200 :group 'org-reveal-location
1201 :version "25.2"
1202 :package-version '(Org . "9.0")
1203 :type '(choice
1204 (const :tag "Canonical" t)
1205 (const :tag "Minimal" nil)
1206 (repeat :greedy t :tag "Individual contexts"
1207 (cons
1208 (choice :tag "Context"
1209 (const agenda)
1210 (const org-goto)
1211 (const occur-tree)
1212 (const tags-tree)
1213 (const link-search)
1214 (const mark-goto)
1215 (const bookmark-jump)
1216 (const isearch)
1217 (const default))
1218 (choice :tag "Detail level"
1219 (const minimal)
1220 (const local)
1221 (const ancestors)
1222 (const lineage)
1223 (const tree)
1224 (const canonical))))))
1226 (defcustom org-indirect-buffer-display 'other-window
1227 "How should indirect tree buffers be displayed?
1228 This applies to indirect buffers created with the commands
1229 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1230 Valid values are:
1231 current-window Display in the current window
1232 other-window Just display in another window.
1233 dedicated-frame Create one new frame, and re-use it each time.
1234 new-frame Make a new frame each time. Note that in this case
1235 previously-made indirect buffers are kept, and you need to
1236 kill these buffers yourself."
1237 :group 'org-structure
1238 :group 'org-agenda-windows
1239 :type '(choice
1240 (const :tag "In current window" current-window)
1241 (const :tag "In current frame, other window" other-window)
1242 (const :tag "Each time a new frame" new-frame)
1243 (const :tag "One dedicated frame" dedicated-frame)))
1245 (defcustom org-use-speed-commands nil
1246 "Non-nil means activate single letter commands at beginning of a headline.
1247 This may also be a function to test for appropriate locations where speed
1248 commands should be active.
1250 For example, to activate speed commands when the point is on any
1251 star at the beginning of the headline, you can do this:
1253 (setq org-use-speed-commands
1254 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1255 :group 'org-structure
1256 :type '(choice
1257 (const :tag "Never" nil)
1258 (const :tag "At beginning of headline stars" t)
1259 (function)))
1261 (defcustom org-speed-commands-user nil
1262 "Alist of additional speed commands.
1263 This list will be checked before `org-speed-commands-default'
1264 when the variable `org-use-speed-commands' is non-nil
1265 and when the cursor is at the beginning of a headline.
1266 The car if each entry is a string with a single letter, which must
1267 be assigned to `self-insert-command' in the global map.
1268 The cdr is either a command to be called interactively, a function
1269 to be called, or a form to be evaluated.
1270 An entry that is just a list with a single string will be interpreted
1271 as a descriptive headline that will be added when listing the speed
1272 commands in the Help buffer using the `?' speed command."
1273 :group 'org-structure
1274 :type '(repeat :value ("k" . ignore)
1275 (choice :value ("k" . ignore)
1276 (list :tag "Descriptive Headline" (string :tag "Headline"))
1277 (cons :tag "Letter and Command"
1278 (string :tag "Command letter")
1279 (choice
1280 (function)
1281 (sexp))))))
1283 (defcustom org-bookmark-names-plist
1284 '(:last-capture "org-capture-last-stored"
1285 :last-refile "org-refile-last-stored"
1286 :last-capture-marker "org-capture-last-stored-marker")
1287 "Names for bookmarks automatically set by some Org commands.
1288 This can provide strings as names for a number of bookmarks Org sets
1289 automatically. The following keys are currently implemented:
1290 :last-capture
1291 :last-capture-marker
1292 :last-refile
1293 When a key does not show up in the property list, the corresponding bookmark
1294 is not set."
1295 :group 'org-structure
1296 :type 'plist)
1298 (defgroup org-cycle nil
1299 "Options concerning visibility cycling in Org-mode."
1300 :tag "Org Cycle"
1301 :group 'org-structure)
1303 (defcustom org-cycle-skip-children-state-if-no-children t
1304 "Non-nil means skip CHILDREN state in entries that don't have any."
1305 :group 'org-cycle
1306 :type 'boolean)
1308 (defcustom org-cycle-max-level nil
1309 "Maximum level which should still be subject to visibility cycling.
1310 Levels higher than this will, for cycling, be treated as text, not a headline.
1311 When `org-odd-levels-only' is set, a value of N in this variable actually
1312 means 2N-1 stars as the limiting headline.
1313 When nil, cycle all levels.
1314 Note that the limiting level of cycling is also influenced by
1315 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1316 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1317 than its value."
1318 :group 'org-cycle
1319 :type '(choice
1320 (const :tag "No limit" nil)
1321 (integer :tag "Maximum level")))
1323 (defcustom org-hide-block-startup nil
1324 "Non-nil means entering Org-mode will fold all blocks.
1325 This can also be set in on a per-file basis with
1327 #+STARTUP: hideblocks
1328 #+STARTUP: showblocks"
1329 :group 'org-startup
1330 :group 'org-cycle
1331 :type 'boolean)
1333 (defcustom org-cycle-global-at-bob nil
1334 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1335 This makes it possible to do global cycling without having to use S-TAB or
1336 \\[universal-argument] TAB. For this special case to work, the first line
1337 of the buffer must not be a headline -- it may be empty or some other text.
1338 When used in this way, `org-cycle-hook' is disabled temporarily to make
1339 sure the cursor stays at the beginning of the buffer. When this option is
1340 nil, don't do anything special at the beginning of the buffer."
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-level-after-item/entry-creation t
1345 "Non-nil means cycle entry level or item indentation in new empty entries.
1347 When the cursor is at the end of an empty headline, i.e., with only stars
1348 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1349 and then all possible ancestor states, before returning to the original state.
1350 This makes data entry extremely fast: M-RET to create a new headline,
1351 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1353 When the cursor is at the end of an empty plain list item, one TAB will
1354 make it a subitem, two or more tabs will back up to make this an item
1355 higher up in the item hierarchy."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-emulate-tab t
1360 "Where should `org-cycle' emulate TAB.
1361 nil Never
1362 white Only in completely white lines
1363 whitestart Only at the beginning of lines, before the first non-white char
1364 t Everywhere except in headlines
1365 exc-hl-bol Everywhere except at the start of a headline
1366 If TAB is used in a place where it does not emulate TAB, the current subtree
1367 visibility is cycled."
1368 :group 'org-cycle
1369 :type '(choice (const :tag "Never" nil)
1370 (const :tag "Only in completely white lines" white)
1371 (const :tag "Before first char in a line" whitestart)
1372 (const :tag "Everywhere except in headlines" t)
1373 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1375 (defcustom org-cycle-separator-lines 2
1376 "Number of empty lines needed to keep an empty line between collapsed trees.
1377 If you leave an empty line between the end of a subtree and the following
1378 headline, this empty line is hidden when the subtree is folded.
1379 Org-mode will leave (exactly) one empty line visible if the number of
1380 empty lines is equal or larger to the number given in this variable.
1381 So the default 2 means at least 2 empty lines after the end of a subtree
1382 are needed to produce free space between a collapsed subtree and the
1383 following headline.
1385 If the number is negative, and the number of empty lines is at least -N,
1386 all empty lines are shown.
1388 Special case: when 0, never leave empty lines in collapsed view."
1389 :group 'org-cycle
1390 :type 'integer)
1391 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1393 (defcustom org-pre-cycle-hook nil
1394 "Hook that is run before visibility cycling is happening.
1395 The function(s) in this hook must accept a single argument which indicates
1396 the new state that will be set right after running this hook. The
1397 argument is a symbol. Before a global state change, it can have the values
1398 `overview', `content', or `all'. Before a local state change, it can have
1399 the values `folded', `children', or `subtree'."
1400 :group 'org-cycle
1401 :type 'hook)
1403 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1404 org-cycle-hide-drawers
1405 org-cycle-show-empty-lines
1406 org-optimize-window-after-visibility-change)
1407 "Hook that is run after `org-cycle' has changed the buffer visibility.
1408 The function(s) in this hook must accept a single argument which indicates
1409 the new state that was set by the most recent `org-cycle' command. The
1410 argument is a symbol. After a global state change, it can have the values
1411 `overview', `contents', or `all'. After a local state change, it can have
1412 the values `folded', `children', or `subtree'."
1413 :group 'org-cycle
1414 :type 'hook
1415 :version "25.1"
1416 :package-version '(Org . "8.3"))
1418 (defgroup org-edit-structure nil
1419 "Options concerning structure editing in Org-mode."
1420 :tag "Org Edit Structure"
1421 :group 'org-structure)
1423 (defcustom org-odd-levels-only nil
1424 "Non-nil means skip even levels and only use odd levels for the outline.
1425 This has the effect that two stars are being added/taken away in
1426 promotion/demotion commands. It also influences how levels are
1427 handled by the exporters.
1428 Changing it requires restart of `font-lock-mode' to become effective
1429 for fontification also in regions already fontified.
1430 You may also set this on a per-file basis by adding one of the following
1431 lines to the buffer:
1433 #+STARTUP: odd
1434 #+STARTUP: oddeven"
1435 :group 'org-edit-structure
1436 :group 'org-appearance
1437 :type 'boolean)
1439 (defcustom org-adapt-indentation t
1440 "Non-nil means adapt indentation to outline node level.
1442 When this variable is set, Org assumes that you write outlines by
1443 indenting text in each node to align with the headline (after the
1444 stars). The following issues are influenced by this variable:
1446 - The indentation is increased by one space in a demotion
1447 command, and decreased by one in a promotion command. However,
1448 in the latter case, if shifting some line in the entry body
1449 would alter document structure (e.g., insert a new headline),
1450 indentation is not changed at all.
1452 - Property drawers and planning information is inserted indented
1453 when this variable is set. When nil, they will not be indented.
1455 - TAB indents a line relative to current level. The lines below
1456 a headline will be indented when this variable is set.
1458 Note that this is all about true indentation, by adding and
1459 removing space characters. See also `org-indent.el' which does
1460 level-dependent indentation in a virtual way, i.e. at display
1461 time in Emacs."
1462 :group 'org-edit-structure
1463 :type 'boolean)
1465 (defcustom org-special-ctrl-a/e nil
1466 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1468 When t, `C-a' will bring back the cursor to the beginning of the
1469 headline text, i.e. after the stars and after a possible TODO
1470 keyword. In an item, this will be the position after bullet and
1471 check-box, if any. When the cursor is already at that position,
1472 another `C-a' will bring it to the beginning of the line.
1474 `C-e' will jump to the end of the headline, ignoring the presence
1475 of tags in the headline. A second `C-e' will then jump to the
1476 true end of the line, after any tags. This also means that, when
1477 this variable is non-nil, `C-e' also will never jump beyond the
1478 end of the heading of a folded section, i.e. not after the
1479 ellipses.
1481 When set to the symbol `reversed', the first `C-a' or `C-e' works
1482 normally, going to the true line boundary first. Only a directly
1483 following, identical keypress will bring the cursor to the
1484 special positions.
1486 This may also be a cons cell where the behavior for `C-a' and
1487 `C-e' is set separately."
1488 :group 'org-edit-structure
1489 :type '(choice
1490 (const :tag "off" nil)
1491 (const :tag "on: after stars/bullet and before tags first" t)
1492 (const :tag "reversed: true line boundary first" reversed)
1493 (cons :tag "Set C-a and C-e separately"
1494 (choice :tag "Special C-a"
1495 (const :tag "off" nil)
1496 (const :tag "on: after stars/bullet first" t)
1497 (const :tag "reversed: before stars/bullet first" reversed))
1498 (choice :tag "Special C-e"
1499 (const :tag "off" nil)
1500 (const :tag "on: before tags first" t)
1501 (const :tag "reversed: after tags first" reversed)))))
1502 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1504 (defcustom org-special-ctrl-k nil
1505 "Non-nil means `C-k' will behave specially in headlines.
1506 When nil, `C-k' will call the default `kill-line' command.
1507 When t, the following will happen while the cursor is in the headline:
1509 - When the cursor is at the beginning of a headline, kill the entire
1510 line and possible the folded subtree below the line.
1511 - When in the middle of the headline text, kill the headline up to the tags.
1512 - When after the headline text, kill the tags."
1513 :group 'org-edit-structure
1514 :type 'boolean)
1516 (defcustom org-ctrl-k-protect-subtree nil
1517 "Non-nil means, do not delete a hidden subtree with C-k.
1518 When set to the symbol `error', simply throw an error when C-k is
1519 used to kill (part-of) a headline that has hidden text behind it.
1520 Any other non-nil value will result in a query to the user, if it is
1521 OK to kill that hidden subtree. When nil, kill without remorse."
1522 :group 'org-edit-structure
1523 :version "24.1"
1524 :type '(choice
1525 (const :tag "Do not protect hidden subtrees" nil)
1526 (const :tag "Protect hidden subtrees with a security query" t)
1527 (const :tag "Never kill a hidden subtree with C-k" error)))
1529 (defcustom org-special-ctrl-o t
1530 "Non-nil means, make `C-o' insert a row in tables."
1531 :group 'org-edit-structure
1532 :type 'boolean)
1534 (defcustom org-catch-invisible-edits nil
1535 "Check if in invisible region before inserting or deleting a character.
1536 Valid values are:
1538 nil Do not check, so just do invisible edits.
1539 error Throw an error and do nothing.
1540 show Make point visible, and do the requested edit.
1541 show-and-error Make point visible, then throw an error and abort the edit.
1542 smart Make point visible, and do insertion/deletion if it is
1543 adjacent to visible text and the change feels predictable.
1544 Never delete a previously invisible character or add in the
1545 middle or right after an invisible region. Basically, this
1546 allows insertion and backward-delete right before ellipses.
1547 FIXME: maybe in this case we should not even show?"
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not check" nil)
1552 (const :tag "Throw error when trying to edit" error)
1553 (const :tag "Unhide, but do not do the edit" show-and-error)
1554 (const :tag "Show invisible part and do the edit" show)
1555 (const :tag "Be smart and do the right thing" smart)))
1557 (defcustom org-yank-folded-subtrees t
1558 "Non-nil means when yanking subtrees, fold them.
1559 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1560 it starts with a heading and all other headings in it are either children
1561 or siblings, then fold all the subtrees. However, do this only if no
1562 text after the yank would be swallowed into a folded tree by this action."
1563 :group 'org-edit-structure
1564 :type 'boolean)
1566 (defcustom org-yank-adjusted-subtrees nil
1567 "Non-nil means when yanking subtrees, adjust the level.
1568 With this setting, `org-paste-subtree' is used to insert the subtree, see
1569 this function for details."
1570 :group 'org-edit-structure
1571 :type 'boolean)
1573 (defcustom org-M-RET-may-split-line '((default . t))
1574 "Non-nil means M-RET will split the line at the cursor position.
1575 When nil, it will go to the end of the line before making a
1576 new line.
1577 You may also set this option in a different way for different
1578 contexts. Valid contexts are:
1580 headline when creating a new headline
1581 item when creating a new item
1582 table in a table field
1583 default the value to be used for all contexts not explicitly
1584 customized"
1585 :group 'org-structure
1586 :group 'org-table
1587 :type '(choice
1588 (const :tag "Always" t)
1589 (const :tag "Never" nil)
1590 (repeat :greedy t :tag "Individual contexts"
1591 (cons
1592 (choice :tag "Context"
1593 (const headline)
1594 (const item)
1595 (const table)
1596 (const default))
1597 (boolean)))))
1600 (defcustom org-insert-heading-respect-content nil
1601 "Non-nil means insert new headings after the current subtree.
1602 When nil, the new heading is created directly after the current line.
1603 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1604 this variable on for the duration of the command."
1605 :group 'org-structure
1606 :type 'boolean)
1608 (defcustom org-blank-before-new-entry '((heading . auto)
1609 (plain-list-item . auto))
1610 "Should `org-insert-heading' leave a blank line before new heading/item?
1611 The value is an alist, with `heading' and `plain-list-item' as CAR,
1612 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1613 which case Org will look at the surrounding headings/items and try to
1614 make an intelligent decision whether to insert a blank line or not."
1615 :group 'org-edit-structure
1616 :type '(list
1617 (cons (const heading)
1618 (choice (const :tag "Never" nil)
1619 (const :tag "Always" t)
1620 (const :tag "Auto" auto)))
1621 (cons (const plain-list-item)
1622 (choice (const :tag "Never" nil)
1623 (const :tag "Always" t)
1624 (const :tag "Auto" auto)))))
1626 (defcustom org-insert-heading-hook nil
1627 "Hook being run after inserting a new heading."
1628 :group 'org-edit-structure
1629 :type 'hook)
1631 (defcustom org-enable-fixed-width-editor t
1632 "Non-nil means lines starting with \":\" are treated as fixed-width.
1633 This currently only means they are never auto-wrapped.
1634 When nil, such lines will be treated like ordinary lines."
1635 :group 'org-edit-structure
1636 :type 'boolean)
1638 (defcustom org-goto-auto-isearch t
1639 "Non-nil means typing characters in `org-goto' starts incremental search.
1640 When nil, you can use these keybindings to navigate the buffer:
1642 q Quit the org-goto interface
1643 n Go to the next visible heading
1644 p Go to the previous visible heading
1645 f Go one heading forward on same level
1646 b Go one heading backward on same level
1647 u Go one heading up"
1648 :group 'org-edit-structure
1649 :type 'boolean)
1651 (defgroup org-sparse-trees nil
1652 "Options concerning sparse trees in Org-mode."
1653 :tag "Org Sparse Trees"
1654 :group 'org-structure)
1656 (defcustom org-highlight-sparse-tree-matches t
1657 "Non-nil means highlight all matches that define a sparse tree.
1658 The highlights will automatically disappear the next time the buffer is
1659 changed by an edit command."
1660 :group 'org-sparse-trees
1661 :type 'boolean)
1663 (defcustom org-remove-highlights-with-change t
1664 "Non-nil means any change to the buffer will remove temporary highlights.
1665 \\<org-mode-map>\
1666 Such highlights are created by `org-occur' and `org-clock-display'.
1667 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1668 to get rid of the highlights.
1669 The highlights created by `org-toggle-latex-fragment' always need
1670 `\\[org-toggle-latex-fragment]' to be removed."
1671 :group 'org-sparse-trees
1672 :group 'org-time
1673 :type 'boolean)
1675 (defcustom org-occur-case-fold-search t
1676 "Non-nil means `org-occur' should be case-insensitive.
1677 If set to `smart' the search will be case-insensitive only if it
1678 doesn't specify any upper case character."
1679 :group 'org-sparse-trees
1680 :version "25.1"
1681 :type '(choice
1682 (const :tag "Case-sensitive" nil)
1683 (const :tag "Case-insensitive" t)
1684 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1686 (defcustom org-occur-hook '(org-first-headline-recenter)
1687 "Hook that is run after `org-occur' has constructed a sparse tree.
1688 This can be used to recenter the window to show as much of the structure
1689 as possible."
1690 :group 'org-sparse-trees
1691 :type 'hook)
1693 (defgroup org-imenu-and-speedbar nil
1694 "Options concerning imenu and speedbar in Org-mode."
1695 :tag "Org Imenu and Speedbar"
1696 :group 'org-structure)
1698 (defcustom org-imenu-depth 2
1699 "The maximum level for Imenu access to Org-mode headlines.
1700 This also applied for speedbar access."
1701 :group 'org-imenu-and-speedbar
1702 :type 'integer)
1704 (defgroup org-table nil
1705 "Options concerning tables in Org-mode."
1706 :tag "Org Table"
1707 :group 'org)
1709 (defcustom org-enable-table-editor 'optimized
1710 "Non-nil means lines starting with \"|\" are handled by the table editor.
1711 When nil, such lines will be treated like ordinary lines.
1713 When equal to the symbol `optimized', the table editor will be optimized to
1714 do the following:
1715 - Automatic overwrite mode in front of whitespace in table fields.
1716 This makes the structure of the table stay in tact as long as the edited
1717 field does not exceed the column width.
1718 - Minimize the number of realigns. Normally, the table is aligned each time
1719 TAB or RET are pressed to move to another field. With optimization this
1720 happens only if changes to a field might have changed the column width.
1721 Optimization requires replacing the functions `self-insert-command',
1722 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1723 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1724 very good at guessing when a re-align will be necessary, but you can always
1725 force one with \\[org-ctrl-c-ctrl-c].
1727 If you would like to use the optimized version in Org-mode, but the
1728 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1730 This variable can be used to turn on and off the table editor during a session,
1731 but in order to toggle optimization, a restart is required.
1733 See also the variable `org-table-auto-blank-field'."
1734 :group 'org-table
1735 :type '(choice
1736 (const :tag "off" nil)
1737 (const :tag "on" t)
1738 (const :tag "on, optimized" optimized)))
1740 (defcustom org-self-insert-cluster-for-undo nil
1741 "Non-nil means cluster self-insert commands for undo when possible.
1742 If this is set, then, like in the Emacs command loop, 20 consecutive
1743 characters will be undone together.
1744 This is configurable, because there is some impact on typing performance."
1745 :group 'org-table
1746 :type 'boolean)
1748 (defcustom org-table-tab-recognizes-table.el t
1749 "Non-nil means TAB will automatically notice a table.el table.
1750 When it sees such a table, it moves point into it and - if necessary -
1751 calls `table-recognize-table'."
1752 :group 'org-table-editing
1753 :type 'boolean)
1755 (defgroup org-link nil
1756 "Options concerning links in Org-mode."
1757 :tag "Org Link"
1758 :group 'org)
1760 (defvar-local org-link-abbrev-alist-local nil
1761 "Buffer-local version of `org-link-abbrev-alist', which see.
1762 The value of this is taken from the #+LINK lines.")
1764 (defcustom org-link-abbrev-alist nil
1765 "Alist of link abbreviations.
1766 The car of each element is a string, to be replaced at the start of a link.
1767 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1768 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1770 [[linkkey:tag][description]]
1772 The `linkkey' must be a word word, starting with a letter, followed
1773 by letters, numbers, `-' or `_'.
1775 If REPLACE is a string, the tag will simply be appended to create the link.
1776 If the string contains \"%s\", the tag will be inserted there. If the string
1777 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1778 at that point (see the function `url-hexify-string'). If the string contains
1779 the specifier \"%(my-function)\", then the custom function `my-function' will
1780 be invoked: this function takes the tag as its only argument and must return
1781 a string.
1783 REPLACE may also be a function that will be called with the tag as the
1784 only argument to create the link, which should be returned as a string.
1786 See the manual for examples."
1787 :group 'org-link
1788 :type '(repeat
1789 (cons
1790 (string :tag "Protocol")
1791 (choice
1792 (string :tag "Format")
1793 (function)))))
1795 (defcustom org-descriptive-links t
1796 "Non-nil means Org will display descriptive links.
1797 E.g. [[http://orgmode.org][Org website]] will be displayed as
1798 \"Org Website\", hiding the link itself and just displaying its
1799 description. When set to nil, Org will display the full links
1800 literally.
1802 You can interactively set the value of this variable by calling
1803 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1804 :group 'org-link
1805 :type 'boolean)
1807 (defcustom org-link-file-path-type 'adaptive
1808 "How the path name in file links should be stored.
1809 Valid values are:
1811 relative Relative to the current directory, i.e. the directory of the file
1812 into which the link is being inserted.
1813 absolute Absolute path, if possible with ~ for home directory.
1814 noabbrev Absolute path, no abbreviation of home directory.
1815 adaptive Use relative path for files in the current directory and sub-
1816 directories of it. For other files, use an absolute path."
1817 :group 'org-link
1818 :type '(choice
1819 (const relative)
1820 (const absolute)
1821 (const noabbrev)
1822 (const adaptive)))
1824 (defvaralias 'org-activate-links 'org-highlight-links)
1825 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1826 "Types of links that should be highlighted in Org-mode files.
1828 This is a list of symbols, each one of them leading to the
1829 highlighting of a certain link type.
1831 You can still open links that are not highlighted.
1833 In principle, it does not hurt to turn on highlighting for all
1834 link types. There may be a small gain when turning off unused
1835 link types. The types are:
1837 bracket The recommended [[link][description]] or [[link]] links with hiding.
1838 angle Links in angular brackets that may contain whitespace like
1839 <bbdb:Carsten Dominik>.
1840 plain Plain links in normal text, no whitespace, like http://google.com.
1841 radio Text that is matched by a radio target, see manual for details.
1842 tag Tag settings in a headline (link to tag search).
1843 date Time stamps (link to calendar).
1844 footnote Footnote labels.
1846 If you set this variable during an Emacs session, use `org-mode-restart'
1847 in the Org buffer so that the change takes effect."
1848 :group 'org-link
1849 :group 'org-appearance
1850 :type '(set :greedy t
1851 (const :tag "Double bracket links" bracket)
1852 (const :tag "Angular bracket links" angle)
1853 (const :tag "Plain text links" plain)
1854 (const :tag "Radio target matches" radio)
1855 (const :tag "Tags" tag)
1856 (const :tag "Timestamps" date)
1857 (const :tag "Footnotes" footnote)))
1859 (defcustom org-make-link-description-function nil
1860 "Function to use for generating link descriptions from links.
1861 When nil, the link location will be used. This function must take
1862 two parameters: the first one is the link, the second one is the
1863 description generated by `org-insert-link'. The function should
1864 return the description to use."
1865 :group 'org-link
1866 :type '(choice (const nil) (function)))
1868 (defgroup org-link-store nil
1869 "Options concerning storing links in Org-mode."
1870 :tag "Org Store Link"
1871 :group 'org-link)
1873 (defcustom org-url-hexify-p t
1874 "When non-nil, hexify URL when creating a link."
1875 :type 'boolean
1876 :version "24.3"
1877 :group 'org-link-store)
1879 (defcustom org-email-link-description-format "Email %c: %.30s"
1880 "Format of the description part of a link to an email or usenet message.
1881 The following %-escapes will be replaced by corresponding information:
1883 %F full \"From\" field
1884 %f name, taken from \"From\" field, address if no name
1885 %T full \"To\" field
1886 %t first name in \"To\" field, address if no name
1887 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1888 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1889 %s subject
1890 %d date
1891 %m message-id.
1893 You may use normal field width specification between the % and the letter.
1894 This is for example useful to limit the length of the subject.
1896 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1897 :group 'org-link-store
1898 :type 'string)
1900 (defcustom org-from-is-user-regexp
1901 (let (r1 r2)
1902 (when (and user-mail-address (not (string= user-mail-address "")))
1903 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1904 (when (and user-full-name (not (string= user-full-name "")))
1905 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1906 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1907 "Regexp matched against the \"From:\" header of an email or usenet message.
1908 It should match if the message is from the user him/herself."
1909 :group 'org-link-store
1910 :type 'regexp)
1912 (defcustom org-context-in-file-links t
1913 "Non-nil means file links from `org-store-link' contain context.
1914 A search string will be added to the file name with :: as separator and
1915 used to find the context when the link is activated by the command
1916 `org-open-at-point'. When this option is t, the entire active region
1917 will be placed in the search string of the file link. If set to a
1918 positive integer, only the first n lines of context will be stored.
1920 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1921 negates this setting for the duration of the command."
1922 :group 'org-link-store
1923 :type '(choice boolean integer))
1925 (defcustom org-keep-stored-link-after-insertion nil
1926 "Non-nil means keep link in list for entire session.
1928 The command `org-store-link' adds a link pointing to the current
1929 location to an internal list. These links accumulate during a session.
1930 The command `org-insert-link' can be used to insert links into any
1931 Org-mode file (offering completion for all stored links). When this
1932 option is nil, every link which has been inserted once using \\[org-insert-link]
1933 will be removed from the list, to make completing the unused links
1934 more efficient."
1935 :group 'org-link-store
1936 :type 'boolean)
1938 (defgroup org-link-follow nil
1939 "Options concerning following links in Org-mode."
1940 :tag "Org Follow Link"
1941 :group 'org-link)
1943 (defcustom org-link-translation-function nil
1944 "Function to translate links with different syntax to Org syntax.
1945 This can be used to translate links created for example by the Planner
1946 or emacs-wiki packages to Org syntax.
1947 The function must accept two parameters, a TYPE containing the link
1948 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1949 which is everything after the link protocol. It should return a cons
1950 with possibly modified values of type and path.
1951 Org contains a function for this, so if you set this variable to
1952 `org-translate-link-from-planner', you should be able follow many
1953 links created by planner."
1954 :group 'org-link-follow
1955 :type '(choice (const nil) (function)))
1957 (defcustom org-follow-link-hook nil
1958 "Hook that is run after a link has been followed."
1959 :group 'org-link-follow
1960 :type 'hook)
1962 (defcustom org-tab-follows-link nil
1963 "Non-nil means on links TAB will follow the link.
1964 Needs to be set before org.el is loaded.
1965 This really should not be used, it does not make sense, and the
1966 implementation is bad."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-return-follows-link nil
1971 "Non-nil means on links RET will follow the link.
1972 In tables, the special behavior of RET has precedence."
1973 :group 'org-link-follow
1974 :type 'boolean)
1976 (defcustom org-mouse-1-follows-link
1977 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1978 "Non-nil means mouse-1 on a link will follow the link.
1979 A longer mouse click will still set point. Needs to be set
1980 before org.el is loaded."
1981 :group 'org-link-follow
1982 :version "24.4"
1983 :package-version '(Org . "8.3")
1984 :type '(choice
1985 (const :tag "A double click follows the link" double)
1986 (const :tag "Unconditionally follow the link with mouse-1" t)
1987 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1989 (defcustom org-mark-ring-length 4
1990 "Number of different positions to be recorded in the ring.
1991 Changing this requires a restart of Emacs to work correctly."
1992 :group 'org-link-follow
1993 :type 'integer)
1995 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1996 "Non-nil means internal links in Org files must exactly match a headline.
1997 When nil, the link search tries to match a phrase with all words
1998 in the search text."
1999 :group 'org-link-follow
2000 :version "24.1"
2001 :type '(choice
2002 (const :tag "Use fuzzy text search" nil)
2003 (const :tag "Match only exact headline" t)
2004 (const :tag "Match exact headline or query to create it"
2005 query-to-create)))
2007 (defcustom org-link-frame-setup
2008 '((vm . vm-visit-folder-other-frame)
2009 (vm-imap . vm-visit-imap-folder-other-frame)
2010 (gnus . org-gnus-no-new-news)
2011 (file . find-file-other-window)
2012 (wl . wl-other-frame))
2013 "Setup the frame configuration for following links.
2014 When following a link with Emacs, it may often be useful to display
2015 this link in another window or frame. This variable can be used to
2016 set this up for the different types of links.
2017 For VM, use any of
2018 `vm-visit-folder'
2019 `vm-visit-folder-other-window'
2020 `vm-visit-folder-other-frame'
2021 For Gnus, use any of
2022 `gnus'
2023 `gnus-other-frame'
2024 `org-gnus-no-new-news'
2025 For FILE, use any of
2026 `find-file'
2027 `find-file-other-window'
2028 `find-file-other-frame'
2029 For Wanderlust use any of
2030 `wl'
2031 `wl-other-frame'
2032 For the calendar, use the variable `calendar-setup'.
2033 For BBDB, it is currently only possible to display the matches in
2034 another window."
2035 :group 'org-link-follow
2036 :type '(list
2037 (cons (const vm)
2038 (choice
2039 (const vm-visit-folder)
2040 (const vm-visit-folder-other-window)
2041 (const vm-visit-folder-other-frame)))
2042 (cons (const vm-imap)
2043 (choice
2044 (const vm-visit-imap-folder)
2045 (const vm-visit-imap-folder-other-window)
2046 (const vm-visit-imap-folder-other-frame)))
2047 (cons (const gnus)
2048 (choice
2049 (const gnus)
2050 (const gnus-other-frame)
2051 (const org-gnus-no-new-news)))
2052 (cons (const file)
2053 (choice
2054 (const find-file)
2055 (const find-file-other-window)
2056 (const find-file-other-frame)))
2057 (cons (const wl)
2058 (choice
2059 (const wl)
2060 (const wl-other-frame)))))
2062 (defcustom org-display-internal-link-with-indirect-buffer nil
2063 "Non-nil means use indirect buffer to display infile links.
2064 Activating internal links (from one location in a file to another location
2065 in the same file) normally just jumps to the location. When the link is
2066 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2067 is displayed in
2068 another window. When this option is set, the other window actually displays
2069 an indirect buffer clone of the current buffer, to avoid any visibility
2070 changes to the current buffer."
2071 :group 'org-link-follow
2072 :type 'boolean)
2074 (defcustom org-open-non-existing-files nil
2075 "Non-nil means `org-open-file' will open non-existing files.
2076 When nil, an error will be generated.
2077 This variable applies only to external applications because they
2078 might choke on non-existing files. If the link is to a file that
2079 will be opened in Emacs, the variable is ignored."
2080 :group 'org-link-follow
2081 :type 'boolean)
2083 (defcustom org-open-directory-means-index-dot-org nil
2084 "Non-nil means a link to a directory really means to index.org.
2085 When nil, following a directory link will run dired or open a finder/explorer
2086 window on that directory."
2087 :group 'org-link-follow
2088 :type 'boolean)
2090 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2091 "Non-nil means ask for confirmation before executing shell links.
2092 Shell links can be dangerous: just think about a link
2094 [[shell:rm -rf ~/*][Google Search]]
2096 This link would show up in your Org-mode document as \"Google Search\",
2097 but really it would remove your entire home directory.
2098 Therefore we advise against setting this variable to nil.
2099 Just change it to `y-or-n-p' if you want to confirm with a
2100 single keystroke rather than having to type \"yes\"."
2101 :group 'org-link-follow
2102 :type '(choice
2103 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2104 (const :tag "with y-or-n (faster)" y-or-n-p)
2105 (const :tag "no confirmation (dangerous)" nil)))
2106 (put 'org-confirm-shell-link-function
2107 'safe-local-variable
2108 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2110 (defcustom org-confirm-shell-link-not-regexp ""
2111 "A regexp to skip confirmation for shell links."
2112 :group 'org-link-follow
2113 :version "24.1"
2114 :type 'regexp)
2116 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2117 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2118 Elisp links can be dangerous: just think about a link
2120 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2122 This link would show up in your Org-mode document as \"Google Search\",
2123 but really it would remove your entire home directory.
2124 Therefore we advise against setting this variable to nil.
2125 Just change it to `y-or-n-p' if you want to confirm with a
2126 single keystroke rather than having to type \"yes\"."
2127 :group 'org-link-follow
2128 :type '(choice
2129 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2130 (const :tag "with y-or-n (faster)" y-or-n-p)
2131 (const :tag "no confirmation (dangerous)" nil)))
2132 (put 'org-confirm-shell-link-function
2133 'safe-local-variable
2134 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2136 (defcustom org-confirm-elisp-link-not-regexp ""
2137 "A regexp to skip confirmation for Elisp links."
2138 :group 'org-link-follow
2139 :version "24.1"
2140 :type 'regexp)
2142 (defconst org-file-apps-defaults-gnu
2143 '((remote . emacs)
2144 (system . mailcap)
2145 (t . mailcap))
2146 "Default file applications on a UNIX or GNU/Linux system.
2147 See `org-file-apps'.")
2149 (defconst org-file-apps-defaults-macosx
2150 '((remote . emacs)
2151 (system . "open %s")
2152 ("ps.gz" . "gv %s")
2153 ("eps.gz" . "gv %s")
2154 ("dvi" . "xdvi %s")
2155 ("fig" . "xfig %s")
2156 (t . "open %s"))
2157 "Default file applications on a MacOS X system.
2158 The system \"open\" is known as a default, but we use X11 applications
2159 for some files for which the OS does not have a good default.
2160 See `org-file-apps'.")
2162 (defconst org-file-apps-defaults-windowsnt
2163 (list '(remote . emacs)
2164 (cons 'system (lambda (file _path)
2165 (with-no-warnings (w32-shell-execute "open" file))))
2166 (cons t (lambda (file _path)
2167 (with-no-warnings (w32-shell-execute "open" file)))))
2168 "Default file applications on a Windows NT system.
2169 The system \"open\" is used for most files.
2170 See `org-file-apps'.")
2172 (defcustom org-file-apps
2173 '((auto-mode . emacs)
2174 ("\\.mm\\'" . default)
2175 ("\\.x?html?\\'" . default)
2176 ("\\.pdf\\'" . default))
2177 "External applications for opening `file:path' items in a document.
2178 \\<org-mode-map>\
2179 Org mode uses system defaults for different file types, but
2180 you can use this variable to set the application for a given file
2181 extension. The entries in this list are cons cells where the car identifies
2182 files and the cdr the corresponding command. Possible values for the
2183 file identifier are
2184 \"string\" A string as a file identifier can be interpreted in different
2185 ways, depending on its contents:
2187 - Alphanumeric characters only:
2188 Match links with this file extension.
2189 Example: (\"pdf\" . \"evince %s\")
2190 to open PDFs with evince.
2192 - Regular expression: Match links where the
2193 filename matches the regexp. If you want to
2194 use groups here, use shy groups.
2196 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2197 \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2198 to open *.html and *.xhtml with firefox.
2200 - Regular expression which contains (non-shy) groups:
2201 Match links where the whole link, including \"::\", and
2202 anything after that, matches the regexp.
2203 In a custom command string, %1, %2, etc. are replaced with
2204 the parts of the link that were matched by the groups.
2205 For backwards compatibility, if a command string is given
2206 that does not use any of the group matches, this case is
2207 handled identically to the second one (i.e. match against
2208 file name only).
2209 In a custom function, you can access the group matches with
2210 \(match-string n link).
2212 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2213 to open [[file:document.pdf::5]] with evince at page 5.
2215 `directory' Matches a directory
2216 `remote' Matches a remote file, accessible through tramp or efs.
2217 Remote files most likely should be visited through Emacs
2218 because external applications cannot handle such paths.
2219 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2220 so all files Emacs knows how to handle. Using this with
2221 command `emacs' will open most files in Emacs. Beware that this
2222 will also open html files inside Emacs, unless you add
2223 \(\"html\" . default) to the list as well.
2224 `system' The system command to open files, like `open' on Windows
2225 and Mac OS X, and mailcap under GNU/Linux. This is the command
2226 that will be selected if you call \\[org-open-at-point] with a double
2227 \\[universal-argument] \\[universal-argument] prefix.
2228 t Default for files not matched by any of the other options.
2230 Possible values for the command are:
2231 `emacs' The file will be visited by the current Emacs process.
2232 `default' Use the default application for this file type, which is the
2233 association for t in the list, most likely in the system-specific
2234 part. This can be used to overrule an unwanted setting in the
2235 system-specific variable.
2236 `system' Use the system command for opening files, like \"open\".
2237 This command is specified by the entry whose car is `system'.
2238 Most likely, the system-specific version of this variable
2239 does define this command, but you can overrule/replace it
2240 here.
2241 `mailcap' Use command specified in the mailcaps.
2242 string A command to be executed by a shell; %s will be replaced
2243 by the path to the file.
2245 function A Lisp function, which will be called with two arguments:
2246 the file path and the original link string, without the
2247 \"file:\" prefix.
2249 For more examples, see the system specific constants
2250 `org-file-apps-defaults-macosx'
2251 `org-file-apps-defaults-windowsnt'
2252 `org-file-apps-defaults-gnu'."
2253 :group 'org-link-follow
2254 :type '(repeat
2255 (cons (choice :value ""
2256 (string :tag "Extension")
2257 (const :tag "System command to open files" system)
2258 (const :tag "Default for unrecognized files" t)
2259 (const :tag "Remote file" remote)
2260 (const :tag "Links to a directory" directory)
2261 (const :tag "Any files that have Emacs modes"
2262 auto-mode))
2263 (choice :value ""
2264 (const :tag "Visit with Emacs" emacs)
2265 (const :tag "Use default" default)
2266 (const :tag "Use the system command" system)
2267 (string :tag "Command")
2268 (function :tag "Function")))))
2270 (defcustom org-doi-server-url "http://dx.doi.org/"
2271 "The URL of the DOI server."
2272 :type 'string
2273 :version "24.3"
2274 :group 'org-link-follow)
2276 (defgroup org-refile nil
2277 "Options concerning refiling entries in Org-mode."
2278 :tag "Org Refile"
2279 :group 'org)
2281 (defcustom org-directory "~/org"
2282 "Directory with Org files.
2283 This is just a default location to look for Org files. There is no need
2284 at all to put your files into this directory. It is used in the
2285 following situations:
2287 1. When a capture template specifies a target file that is not an
2288 absolute path. The path will then be interpreted relative to
2289 `org-directory'
2290 2. When the value of variable `org-agenda-files' is a single file, any
2291 relative paths in this file will be taken as relative to
2292 `org-directory'."
2293 :group 'org-refile
2294 :group 'org-capture
2295 :type 'directory)
2297 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2298 "Default target for storing notes.
2299 Used as a fall back file for org-capture.el, for templates that
2300 do not specify a target file."
2301 :group 'org-refile
2302 :group 'org-capture
2303 :type 'file)
2305 (defcustom org-goto-interface 'outline
2306 "The default interface to be used for `org-goto'.
2307 Allowed values are:
2308 outline The interface shows an outline of the relevant file
2309 and the correct heading is found by moving through
2310 the outline or by searching with incremental search.
2311 outline-path-completion Headlines in the current buffer are offered via
2312 completion. This is the interface also used by
2313 the refile command."
2314 :group 'org-refile
2315 :type '(choice
2316 (const :tag "Outline" outline)
2317 (const :tag "Outline-path-completion" outline-path-completion)))
2319 (defcustom org-goto-max-level 5
2320 "Maximum target level when running `org-goto' with refile interface."
2321 :group 'org-refile
2322 :type 'integer)
2324 (defcustom org-reverse-note-order nil
2325 "Non-nil means store new notes at the beginning of a file or entry.
2326 When nil, new notes will be filed to the end of a file or entry.
2327 This can also be a list with cons cells of regular expressions that
2328 are matched against file names, and values."
2329 :group 'org-capture
2330 :group 'org-refile
2331 :type '(choice
2332 (const :tag "Reverse always" t)
2333 (const :tag "Reverse never" nil)
2334 (repeat :tag "By file name regexp"
2335 (cons regexp boolean))))
2337 (defcustom org-log-refile nil
2338 "Information to record when a task is refiled.
2340 Possible values are:
2342 nil Don't add anything
2343 time Add a time stamp to the task
2344 note Prompt for a note and add it with template `org-log-note-headings'
2346 This option can also be set with on a per-file-basis with
2348 #+STARTUP: nologrefile
2349 #+STARTUP: logrefile
2350 #+STARTUP: lognoterefile
2352 You can have local logging settings for a subtree by setting the LOGGING
2353 property to one or more of these keywords.
2355 When bulk-refiling from the agenda, the value `note' is forbidden and
2356 will temporarily be changed to `time'."
2357 :group 'org-refile
2358 :group 'org-progress
2359 :version "24.1"
2360 :type '(choice
2361 (const :tag "No logging" nil)
2362 (const :tag "Record timestamp" time)
2363 (const :tag "Record timestamp with note." note)))
2365 (defcustom org-refile-targets nil
2366 "Targets for refiling entries with \\[org-refile].
2367 This is a list of cons cells. Each cell contains:
2368 - a specification of the files to be considered, either a list of files,
2369 or a symbol whose function or variable value will be used to retrieve
2370 a file name or a list of file names. If you use `org-agenda-files' for
2371 that, all agenda files will be scanned for targets. Nil means consider
2372 headings in the current buffer.
2373 - A specification of how to find candidate refile targets. This may be
2374 any of:
2375 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2376 This tag has to be present in all target headlines, inheritance will
2377 not be considered.
2378 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2379 todo keyword.
2380 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2381 headlines that are refiling targets.
2382 - a cons cell (:level . N). Any headline of level N is considered a target.
2383 Note that, when `org-odd-levels-only' is set, level corresponds to
2384 order in hierarchy, not to the number of stars.
2385 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2386 Note that, when `org-odd-levels-only' is set, level corresponds to
2387 order in hierarchy, not to the number of stars.
2389 Each element of this list generates a set of possible targets.
2390 The union of these sets is presented (with completion) to
2391 the user by `org-refile'.
2393 You can set the variable `org-refile-target-verify-function' to a function
2394 to verify each headline found by the simple criteria above.
2396 When this variable is nil, all top-level headlines in the current buffer
2397 are used, equivalent to the value `((nil . (:level . 1))'."
2398 :group 'org-refile
2399 :type '(repeat
2400 (cons
2401 (choice :value org-agenda-files
2402 (const :tag "All agenda files" org-agenda-files)
2403 (const :tag "Current buffer" nil)
2404 (function) (variable) (file))
2405 (choice :tag "Identify target headline by"
2406 (cons :tag "Specific tag" (const :value :tag) (string))
2407 (cons :tag "TODO keyword" (const :value :todo) (string))
2408 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2409 (cons :tag "Level number" (const :value :level) (integer))
2410 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2412 (defcustom org-refile-target-verify-function nil
2413 "Function to verify if the headline at point should be a refile target.
2414 The function will be called without arguments, with point at the
2415 beginning of the headline. It should return t and leave point
2416 where it is if the headline is a valid target for refiling.
2418 If the target should not be selected, the function must return nil.
2419 In addition to this, it may move point to a place from where the search
2420 should be continued. For example, the function may decide that the entire
2421 subtree of the current entry should be excluded and move point to the end
2422 of the subtree."
2423 :group 'org-refile
2424 :type '(choice
2425 (const nil)
2426 (function)))
2428 (defcustom org-refile-use-cache nil
2429 "Non-nil means cache refile targets to speed up the process.
2430 \\<org-mode-map>\
2431 The cache for a particular file will be updated automatically when
2432 the buffer has been killed, or when any of the marker used for flagging
2433 refile targets no longer points at a live buffer.
2434 If you have added new entries to a buffer that might themselves be targets,
2435 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2436 if you find that easier, \
2437 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2438 \\[org-refile]'."
2439 :group 'org-refile
2440 :version "24.1"
2441 :type 'boolean)
2443 (defcustom org-refile-use-outline-path nil
2444 "Non-nil means provide refile targets as paths.
2445 So a level 3 headline will be available as level1/level2/level3.
2447 When the value is `file', also include the file name (without directory)
2448 into the path. In this case, you can also stop the completion after
2449 the file name, to get entries inserted as top level in the file.
2451 When `full-file-path', include the full file path."
2452 :group 'org-refile
2453 :type '(choice
2454 (const :tag "Not" nil)
2455 (const :tag "Yes" t)
2456 (const :tag "Start with file name" file)
2457 (const :tag "Start with full file path" full-file-path)))
2459 (defcustom org-outline-path-complete-in-steps t
2460 "Non-nil means complete the outline path in hierarchical steps.
2461 When Org-mode uses the refile interface to select an outline path
2462 \(see variable `org-refile-use-outline-path'), the completion of
2463 the path can be done in a single go, or it can be done in steps down
2464 the headline hierarchy. Going in steps is probably the best if you
2465 do not use a special completion package like `ido' or `icicles'.
2466 However, when using these packages, going in one step can be very
2467 fast, while still showing the whole path to the entry."
2468 :group 'org-refile
2469 :type 'boolean)
2471 (defcustom org-refile-allow-creating-parent-nodes nil
2472 "Non-nil means allow the creation of new nodes as refile targets.
2473 New nodes are then created by adding \"/new node name\" to the completion
2474 of an existing node. When the value of this variable is `confirm',
2475 new node creation must be confirmed by the user (recommended).
2476 When nil, the completion must match an existing entry.
2478 Note that, if the new heading is not seen by the criteria
2479 listed in `org-refile-targets', multiple instances of the same
2480 heading would be created by trying again to file under the new
2481 heading."
2482 :group 'org-refile
2483 :type '(choice
2484 (const :tag "Never" nil)
2485 (const :tag "Always" t)
2486 (const :tag "Prompt for confirmation" confirm)))
2488 (defcustom org-refile-active-region-within-subtree nil
2489 "Non-nil means also refile active region within a subtree.
2491 By default `org-refile' doesn't allow refiling regions if they
2492 don't contain a set of subtrees, but it might be convenient to
2493 do so sometimes: in that case, the first line of the region is
2494 converted to a headline before refiling."
2495 :group 'org-refile
2496 :version "24.1"
2497 :type 'boolean)
2499 (defgroup org-todo nil
2500 "Options concerning TODO items in Org-mode."
2501 :tag "Org TODO"
2502 :group 'org)
2504 (defgroup org-progress nil
2505 "Options concerning Progress logging in Org-mode."
2506 :tag "Org Progress"
2507 :group 'org-time)
2509 (defvar org-todo-interpretation-widgets
2510 '((:tag "Sequence (cycling hits every state)" sequence)
2511 (:tag "Type (cycling directly to DONE)" type))
2512 "The available interpretation symbols for customizing `org-todo-keywords'.
2513 Interested libraries should add to this list.")
2515 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2516 "List of TODO entry keyword sequences and their interpretation.
2517 \\<org-mode-map>This is a list of sequences.
2519 Each sequence starts with a symbol, either `sequence' or `type',
2520 indicating if the keywords should be interpreted as a sequence of
2521 action steps, or as different types of TODO items. The first
2522 keywords are states requiring action - these states will select a headline
2523 for inclusion into the global TODO list Org-mode produces. If one of
2524 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2525 signify that no further action is necessary. If \"|\" is not found,
2526 the last keyword is treated as the only DONE state of the sequence.
2528 The command \\[org-todo] cycles an entry through these states, and one
2529 additional state where no keyword is present. For details about this
2530 cycling, see the manual.
2532 TODO keywords and interpretation can also be set on a per-file basis with
2533 the special #+SEQ_TODO and #+TYP_TODO lines.
2535 Each keyword can optionally specify a character for fast state selection
2536 \(in combination with the variable `org-use-fast-todo-selection')
2537 and specifiers for state change logging, using the same syntax that
2538 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2539 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2540 indicates to record a time stamp each time this state is selected.
2542 Each keyword may also specify if a timestamp or a note should be
2543 recorded when entering or leaving the state, by adding additional
2544 characters in the parenthesis after the keyword. This looks like this:
2545 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2546 record only the time of the state change. With X and Y being either
2547 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2548 Y when leaving the state if and only if the *target* state does not
2549 define X. You may omit any of the fast-selection key or X or /Y,
2550 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2552 For backward compatibility, this variable may also be just a list
2553 of keywords. In this case the interpretation (sequence or type) will be
2554 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2555 :group 'org-todo
2556 :group 'org-keywords
2557 :type '(choice
2558 (repeat :tag "Old syntax, just keywords"
2559 (string :tag "Keyword"))
2560 (repeat :tag "New syntax"
2561 (cons
2562 (choice
2563 :tag "Interpretation"
2564 ;;Quick and dirty way to see
2565 ;;`org-todo-interpretations'. This takes the
2566 ;;place of item arguments
2567 :convert-widget
2568 (lambda (widget)
2569 (widget-put widget
2570 :args (mapcar
2571 (lambda (x)
2572 (widget-convert
2573 (cons 'const x)))
2574 org-todo-interpretation-widgets))
2575 widget))
2576 (repeat
2577 (string :tag "Keyword"))))))
2579 (defvar-local org-todo-keywords-1 nil
2580 "All TODO and DONE keywords active in a buffer.")
2581 (defvar org-todo-keywords-for-agenda nil)
2582 (defvar org-done-keywords-for-agenda nil)
2583 (defvar org-todo-keyword-alist-for-agenda nil)
2584 (defvar org-tag-alist-for-agenda nil
2585 "Alist of all tags from all agenda files.")
2586 (defvar org-tag-groups-alist-for-agenda nil
2587 "Alist of all groups tags from all current agenda files.")
2588 (defvar-local org-tag-groups-alist nil)
2589 (defvar org-agenda-contributing-files nil)
2590 (defvar-local org-current-tag-alist nil
2591 "Alist of all tag groups in current buffer.
2592 This variable takes into consideration `org-tag-alist',
2593 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2594 (defvar-local org-not-done-keywords nil)
2595 (defvar-local org-done-keywords nil)
2596 (defvar-local org-todo-heads nil)
2597 (defvar-local org-todo-sets nil)
2598 (defvar-local org-todo-log-states nil)
2599 (defvar-local org-todo-kwd-alist nil)
2600 (defvar-local org-todo-key-alist nil)
2601 (defvar-local org-todo-key-trigger nil)
2603 (defcustom org-todo-interpretation 'sequence
2604 "Controls how TODO keywords are interpreted.
2605 This variable is in principle obsolete and is only used for
2606 backward compatibility, if the interpretation of todo keywords is
2607 not given already in `org-todo-keywords'. See that variable for
2608 more information."
2609 :group 'org-todo
2610 :group 'org-keywords
2611 :type '(choice (const sequence)
2612 (const type)))
2614 (defcustom org-use-fast-todo-selection t
2615 "\\<org-mode-map>\
2616 Non-nil means use the fast todo selection scheme with \\[org-todo].
2617 This variable describes if and under what circumstances the cycling
2618 mechanism for TODO keywords will be replaced by a single-key, direct
2619 selection scheme.
2621 When nil, fast selection is never used.
2623 When the symbol `prefix', it will be used when `org-todo' is called
2624 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2625 in an Org-mode buffer, and
2626 `\\[universal-argument] t' in an agenda buffer.
2628 When t, fast selection is used by default. In this case, the prefix
2629 argument forces cycling instead.
2631 In all cases, the special interface is only used if access keys have
2632 actually been assigned by the user, i.e. if keywords in the configuration
2633 are followed by a letter in parenthesis, like TODO(t)."
2634 :group 'org-todo
2635 :type '(choice
2636 (const :tag "Never" nil)
2637 (const :tag "By default" t)
2638 (const :tag "Only with C-u C-c C-t" prefix)))
2640 (defcustom org-provide-todo-statistics t
2641 "Non-nil means update todo statistics after insert and toggle.
2642 ALL-HEADLINES means update todo statistics by including headlines
2643 with no TODO keyword as well, counting them as not done.
2644 A list of TODO keywords means the same, but skip keywords that are
2645 not in this list.
2646 When set to a list of two lists, the first list contains keywords
2647 to consider as TODO keywords, the second list contains keywords
2648 to consider as DONE keywords.
2650 When this is set, todo statistics is updated in the parent of the
2651 current entry each time a todo state is changed."
2652 :group 'org-todo
2653 :type '(choice
2654 (const :tag "Yes, only for TODO entries" t)
2655 (const :tag "Yes, including all entries" all-headlines)
2656 (repeat :tag "Yes, for TODOs in this list"
2657 (string :tag "TODO keyword"))
2658 (list :tag "Yes, for TODOs and DONEs in these lists"
2659 (repeat (string :tag "TODO keyword"))
2660 (repeat (string :tag "DONE keyword")))
2661 (other :tag "No TODO statistics" nil)))
2663 (defcustom org-hierarchical-todo-statistics t
2664 "Non-nil means TODO statistics covers just direct children.
2665 When nil, all entries in the subtree are considered.
2666 This has only an effect if `org-provide-todo-statistics' is set.
2667 To set this to nil for only a single subtree, use a COOKIE_DATA
2668 property and include the word \"recursive\" into the value."
2669 :group 'org-todo
2670 :type 'boolean)
2672 (defcustom org-after-todo-state-change-hook nil
2673 "Hook which is run after the state of a TODO item was changed.
2674 The new state (a string with a TODO keyword, or nil) is available in the
2675 Lisp variable `org-state'."
2676 :group 'org-todo
2677 :type 'hook)
2679 (defvar org-blocker-hook nil
2680 "Hook for functions that are allowed to block a state change.
2682 Functions in this hook should not modify the buffer.
2683 Each function gets as its single argument a property list,
2684 see `org-trigger-hook' for more information about this list.
2686 If any of the functions in this hook returns nil, the state change
2687 is blocked.")
2689 (defvar org-trigger-hook nil
2690 "Hook for functions that are triggered by a state change.
2692 Each function gets as its single argument a property list with at
2693 least the following elements:
2695 (:type type-of-change :position pos-at-entry-start
2696 :from old-state :to new-state)
2698 Depending on the type, more properties may be present.
2700 This mechanism is currently implemented for:
2702 TODO state changes
2703 ------------------
2704 :type todo-state-change
2705 :from previous state (keyword as a string), or nil, or a symbol
2706 `todo' or `done', to indicate the general type of state.
2707 :to new state, like in :from")
2709 (defcustom org-enforce-todo-dependencies nil
2710 "Non-nil means undone TODO entries will block switching the parent to DONE.
2711 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2712 be blocked if any prior sibling is not yet done.
2713 Finally, if the parent is blocked because of ordered siblings of its own,
2714 the child will also be blocked."
2715 :set (lambda (var val)
2716 (set var val)
2717 (if val
2718 (add-hook 'org-blocker-hook
2719 'org-block-todo-from-children-or-siblings-or-parent)
2720 (remove-hook 'org-blocker-hook
2721 'org-block-todo-from-children-or-siblings-or-parent)))
2722 :group 'org-todo
2723 :type 'boolean)
2725 (defcustom org-enforce-todo-checkbox-dependencies nil
2726 "Non-nil means unchecked boxes will block switching the parent to DONE.
2727 When this is nil, checkboxes have no influence on switching TODO states.
2728 When non-nil, you first need to check off all check boxes before the TODO
2729 entry can be switched to DONE.
2730 This variable needs to be set before org.el is loaded, and you need to
2731 restart Emacs after a change to make the change effective. The only way
2732 to change is while Emacs is running is through the customize interface."
2733 :set (lambda (var val)
2734 (set var val)
2735 (if val
2736 (add-hook 'org-blocker-hook
2737 'org-block-todo-from-checkboxes)
2738 (remove-hook 'org-blocker-hook
2739 'org-block-todo-from-checkboxes)))
2740 :group 'org-todo
2741 :type 'boolean)
2743 (defcustom org-treat-insert-todo-heading-as-state-change nil
2744 "Non-nil means inserting a TODO heading is treated as state change.
2745 So when the command \\[org-insert-todo-heading] is used, state change
2746 logging will apply if appropriate. When nil, the new TODO item will
2747 be inserted directly, and no logging will take place."
2748 :group 'org-todo
2749 :type 'boolean)
2751 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2752 "Non-nil means switching TODO states with S-cursor counts as state change.
2753 This is the default behavior. However, setting this to nil allows a
2754 convenient way to select a TODO state and bypass any logging associated
2755 with that."
2756 :group 'org-todo
2757 :type 'boolean)
2759 (defcustom org-todo-state-tags-triggers nil
2760 "Tag changes that should be triggered by TODO state changes.
2761 This is a list. Each entry is
2763 (state-change (tag . flag) .......)
2765 State-change can be a string with a state, and empty string to indicate the
2766 state that has no TODO keyword, or it can be one of the symbols `todo'
2767 or `done', meaning any not-done or done state, respectively."
2768 :group 'org-todo
2769 :group 'org-tags
2770 :type '(repeat
2771 (cons (choice :tag "When changing to"
2772 (const :tag "Not-done state" todo)
2773 (const :tag "Done state" done)
2774 (string :tag "State"))
2775 (repeat
2776 (cons :tag "Tag action"
2777 (string :tag "Tag")
2778 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2780 (defcustom org-log-done nil
2781 "Information to record when a task moves to the DONE state.
2783 Possible values are:
2785 nil Don't add anything, just change the keyword
2786 time Add a time stamp to the task
2787 note Prompt for a note and add it with template `org-log-note-headings'
2789 This option can also be set with on a per-file-basis with
2791 #+STARTUP: nologdone
2792 #+STARTUP: logdone
2793 #+STARTUP: lognotedone
2795 You can have local logging settings for a subtree by setting the LOGGING
2796 property to one or more of these keywords."
2797 :group 'org-todo
2798 :group 'org-progress
2799 :type '(choice
2800 (const :tag "No logging" nil)
2801 (const :tag "Record CLOSED timestamp" time)
2802 (const :tag "Record CLOSED timestamp with note." note)))
2804 ;; Normalize old uses of org-log-done.
2805 (cond
2806 ((eq org-log-done t) (setq org-log-done 'time))
2807 ((and (listp org-log-done) (memq 'done org-log-done))
2808 (setq org-log-done 'note)))
2810 (defcustom org-log-reschedule nil
2811 "Information to record when the scheduling date of a tasks is modified.
2813 Possible values are:
2815 nil Don't add anything, just change the date
2816 time Add a time stamp to the task
2817 note Prompt for a note and add it with template `org-log-note-headings'
2819 This option can also be set with on a per-file-basis with
2821 #+STARTUP: nologreschedule
2822 #+STARTUP: logreschedule
2823 #+STARTUP: lognotereschedule"
2824 :group 'org-todo
2825 :group 'org-progress
2826 :type '(choice
2827 (const :tag "No logging" nil)
2828 (const :tag "Record timestamp" time)
2829 (const :tag "Record timestamp with note." note)))
2831 (defcustom org-log-redeadline nil
2832 "Information to record when the deadline date of a tasks is modified.
2834 Possible values are:
2836 nil Don't add anything, just change the date
2837 time Add a time stamp to the task
2838 note Prompt for a note and add it with template `org-log-note-headings'
2840 This option can also be set with on a per-file-basis with
2842 #+STARTUP: nologredeadline
2843 #+STARTUP: logredeadline
2844 #+STARTUP: lognoteredeadline
2846 You can have local logging settings for a subtree by setting the LOGGING
2847 property to one or more of these keywords."
2848 :group 'org-todo
2849 :group 'org-progress
2850 :type '(choice
2851 (const :tag "No logging" nil)
2852 (const :tag "Record timestamp" time)
2853 (const :tag "Record timestamp with note." note)))
2855 (defcustom org-log-note-clock-out nil
2856 "Non-nil means record a note when clocking out of an item.
2857 This can also be configured on a per-file basis by adding one of
2858 the following lines anywhere in the buffer:
2860 #+STARTUP: lognoteclock-out
2861 #+STARTUP: nolognoteclock-out"
2862 :group 'org-todo
2863 :group 'org-progress
2864 :type 'boolean)
2866 (defcustom org-log-done-with-time t
2867 "Non-nil means the CLOSED time stamp will contain date and time.
2868 When nil, only the date will be recorded."
2869 :group 'org-progress
2870 :type 'boolean)
2872 (defcustom org-log-note-headings
2873 '((done . "CLOSING NOTE %t")
2874 (state . "State %-12s from %-12S %t")
2875 (note . "Note taken on %t")
2876 (reschedule . "Rescheduled from %S on %t")
2877 (delschedule . "Not scheduled, was %S on %t")
2878 (redeadline . "New deadline from %S on %t")
2879 (deldeadline . "Removed deadline, was %S on %t")
2880 (refile . "Refiled on %t")
2881 (clock-out . ""))
2882 "Headings for notes added to entries.
2884 The value is an alist, with the car being a symbol indicating the
2885 note context, and the cdr is the heading to be used. The heading
2886 may also be the empty string. The following placeholders can be
2887 used:
2889 %t a time stamp.
2890 %T an active time stamp instead the default inactive one
2891 %d a short-format time stamp.
2892 %D an active short-format time stamp.
2893 %s the new TODO state or time stamp (inactive), in double quotes.
2894 %S the old TODO state or time stamp (inactive), in double quotes.
2895 %u the user name.
2896 %U full user name.
2898 In fact, it is not a good idea to change the `state' entry,
2899 because Agenda Log mode depends on the format of these entries."
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type '(list :greedy t
2903 (cons (const :tag "Heading when closing an item" done) string)
2904 (cons (const :tag
2905 "Heading when changing todo state (todo sequence only)"
2906 state) string)
2907 (cons (const :tag "Heading when just taking a note" note) string)
2908 (cons (const :tag "Heading when rescheduling" reschedule) string)
2909 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2910 (cons (const :tag "Heading when changing deadline" redeadline) string)
2911 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2912 (cons (const :tag "Heading when refiling" refile) string)
2913 (cons (const :tag "Heading when clocking out" clock-out) string)))
2915 (unless (assq 'note org-log-note-headings)
2916 (push '(note . "%t") org-log-note-headings))
2918 (defcustom org-log-into-drawer nil
2919 "Non-nil means insert state change notes and time stamps into a drawer.
2920 When nil, state changes notes will be inserted after the headline and
2921 any scheduling and clock lines, but not inside a drawer.
2923 The value of this variable should be the name of the drawer to use.
2924 LOGBOOK is proposed as the default drawer for this purpose, you can
2925 also set this to a string to define the drawer of your choice.
2927 A value of t is also allowed, representing \"LOGBOOK\".
2929 A value of t or nil can also be set with on a per-file-basis with
2931 #+STARTUP: logdrawer
2932 #+STARTUP: nologdrawer
2934 If this variable is set, `org-log-state-notes-insert-after-drawers'
2935 will be ignored.
2937 You can set the property LOG_INTO_DRAWER to overrule this setting for
2938 a subtree.
2940 Do not check directly this variable in a Lisp program. Call
2941 function `org-log-into-drawer' instead."
2942 :group 'org-todo
2943 :group 'org-progress
2944 :type '(choice
2945 (const :tag "Not into a drawer" nil)
2946 (const :tag "LOGBOOK" t)
2947 (string :tag "Other")))
2949 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2951 (defun org-log-into-drawer ()
2952 "Name of the log drawer, as a string, or nil.
2953 This is the value of `org-log-into-drawer'. However, if the
2954 current entry has or inherits a LOG_INTO_DRAWER property, it will
2955 be used instead of the default value."
2956 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2957 (cond ((equal p "nil") nil)
2958 ((equal p "t") "LOGBOOK")
2959 ((stringp p) p)
2960 (p "LOGBOOK")
2961 ((stringp org-log-into-drawer) org-log-into-drawer)
2962 (org-log-into-drawer "LOGBOOK"))))
2964 (defcustom org-log-state-notes-insert-after-drawers nil
2965 "Non-nil means insert state change notes after any drawers in entry.
2966 Only the drawers that *immediately* follow the headline and the
2967 deadline/scheduled line are skipped.
2968 When nil, insert notes right after the heading and perhaps the line
2969 with deadline/scheduling if present.
2971 This variable will have no effect if `org-log-into-drawer' is
2972 set."
2973 :group 'org-todo
2974 :group 'org-progress
2975 :type 'boolean)
2977 (defcustom org-log-states-order-reversed t
2978 "Non-nil means the latest state note will be directly after heading.
2979 When nil, the state change notes will be ordered according to time.
2981 This option can also be set with on a per-file-basis with
2983 #+STARTUP: logstatesreversed
2984 #+STARTUP: nologstatesreversed"
2985 :group 'org-todo
2986 :group 'org-progress
2987 :type 'boolean)
2989 (defcustom org-todo-repeat-to-state nil
2990 "The TODO state to which a repeater should return the repeating task.
2991 By default this is the first task in a TODO sequence, or the previous state
2992 in a TODO_TYP set. But you can specify another task here.
2993 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2994 :group 'org-todo
2995 :version "24.1"
2996 :type '(choice (const :tag "Head of sequence" nil)
2997 (string :tag "Specific state")))
2999 (defcustom org-log-repeat 'time
3000 "Non-nil means record moving through the DONE state when triggering repeat.
3001 An auto-repeating task is immediately switched back to TODO when
3002 marked DONE. If you are not logging state changes (by adding \"@\"
3003 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3004 record a closing note, there will be no record of the task moving
3005 through DONE. This variable forces taking a note anyway.
3007 nil Don't force a record
3008 time Record a time stamp
3009 note Prompt for a note and add it with template `org-log-note-headings'
3011 This option can also be set with on a per-file-basis with
3013 #+STARTUP: nologrepeat
3014 #+STARTUP: logrepeat
3015 #+STARTUP: lognoterepeat
3017 You can have local logging settings for a subtree by setting the LOGGING
3018 property to one or more of these keywords."
3019 :group 'org-todo
3020 :group 'org-progress
3021 :type '(choice
3022 (const :tag "Don't force a record" nil)
3023 (const :tag "Force recording the DONE state" time)
3024 (const :tag "Force recording a note with the DONE state" note)))
3027 (defgroup org-priorities nil
3028 "Priorities in Org-mode."
3029 :tag "Org Priorities"
3030 :group 'org-todo)
3032 (defcustom org-enable-priority-commands t
3033 "Non-nil means priority commands are active.
3034 When nil, these commands will be disabled, so that you never accidentally
3035 set a priority."
3036 :group 'org-priorities
3037 :type 'boolean)
3039 (defcustom org-highest-priority ?A
3040 "The highest priority of TODO items. A character like ?A, ?B etc.
3041 Must have a smaller ASCII number than `org-lowest-priority'."
3042 :group 'org-priorities
3043 :type 'character)
3045 (defcustom org-lowest-priority ?C
3046 "The lowest priority of TODO items. A character like ?A, ?B etc.
3047 Must have a larger ASCII number than `org-highest-priority'."
3048 :group 'org-priorities
3049 :type 'character)
3051 (defcustom org-default-priority ?B
3052 "The default priority of TODO items.
3053 This is the priority an item gets if no explicit priority is given.
3054 When starting to cycle on an empty priority the first step in the cycle
3055 depends on `org-priority-start-cycle-with-default'. The resulting first
3056 step priority must not exceed the range from `org-highest-priority' to
3057 `org-lowest-priority' which means that `org-default-priority' has to be
3058 in this range exclusive or inclusive the range boundaries. Else the
3059 first step refuses to set the default and the second will fall back
3060 to (depending on the command used) the highest or lowest priority."
3061 :group 'org-priorities
3062 :type 'character)
3064 (defcustom org-priority-start-cycle-with-default t
3065 "Non-nil means start with default priority when starting to cycle.
3066 When this is nil, the first step in the cycle will be (depending on the
3067 command used) one higher or lower than the default priority.
3068 See also `org-default-priority'."
3069 :group 'org-priorities
3070 :type 'boolean)
3072 (defcustom org-get-priority-function nil
3073 "Function to extract the priority from a string.
3074 The string is normally the headline. If this is nil Org computes the
3075 priority from the priority cookie like [#A] in the headline. It returns
3076 an integer, increasing by 1000 for each priority level.
3077 The user can set a different function here, which should take a string
3078 as an argument and return the numeric priority."
3079 :group 'org-priorities
3080 :version "24.1"
3081 :type '(choice
3082 (const nil)
3083 (function)))
3085 (defgroup org-time nil
3086 "Options concerning time stamps and deadlines in Org-mode."
3087 :tag "Org Time"
3088 :group 'org)
3090 (defcustom org-time-stamp-rounding-minutes '(0 5)
3091 "Number of minutes to round time stamps to.
3092 \\<org-mode-map>\
3093 These are two values, the first applies when first creating a time stamp.
3094 The second applies when changing it with the commands `S-up' and `S-down'.
3095 When changing the time stamp, this means that it will change in steps
3096 of N minutes, as given by the second value.
3098 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3099 numbers should be factors of 60, so for example 5, 10, 15.
3101 When this is larger than 1, you can still force an exact time stamp by using
3102 a double prefix argument to a time stamp command like \
3103 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3104 and by using a prefix arg to `S-up/down' to specify the exact number
3105 of minutes to shift."
3106 :group 'org-time
3107 :get (lambda (var) ; Make sure both elements are there
3108 (if (integerp (default-value var))
3109 (list (default-value var) 5)
3110 (default-value var)))
3111 :type '(list
3112 (integer :tag "when inserting times")
3113 (integer :tag "when modifying times")))
3115 ;; Normalize old customizations of this variable.
3116 (when (integerp org-time-stamp-rounding-minutes)
3117 (setq org-time-stamp-rounding-minutes
3118 (list org-time-stamp-rounding-minutes
3119 org-time-stamp-rounding-minutes)))
3121 (defcustom org-display-custom-times nil
3122 "Non-nil means overlay custom formats over all time stamps.
3123 The formats are defined through the variable `org-time-stamp-custom-formats'.
3124 To turn this on on a per-file basis, insert anywhere in the file:
3125 #+STARTUP: customtime"
3126 :group 'org-time
3127 :set 'set-default
3128 :type 'sexp)
3129 (make-variable-buffer-local 'org-display-custom-times)
3131 (defcustom org-time-stamp-custom-formats
3132 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3133 "Custom formats for time stamps. See `format-time-string' for the syntax.
3134 These are overlaid over the default ISO format if the variable
3135 `org-display-custom-times' is set. Time like %H:%M should be at the
3136 end of the second format. The custom formats are also honored by export
3137 commands, if custom time display is turned on at the time of export."
3138 :group 'org-time
3139 :type 'sexp)
3141 (defun org-time-stamp-format (&optional long inactive)
3142 "Get the right format for a time string."
3143 (let ((f (if long (cdr org-time-stamp-formats)
3144 (car org-time-stamp-formats))))
3145 (if inactive
3146 (concat "[" (substring f 1 -1) "]")
3147 f)))
3149 (defcustom org-time-clocksum-format
3150 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3151 "The format string used when creating CLOCKSUM lines.
3152 This is also used when Org mode generates a time duration.
3154 The value can be a single format string containing two
3155 %-sequences, which will be filled with the number of hours and
3156 minutes in that order.
3158 Alternatively, the value can be a plist associating any of the
3159 keys :years, :months, :weeks, :days, :hours or :minutes with
3160 format strings. The time duration is formatted using only the
3161 time components that are needed and concatenating the results.
3162 If a time unit in absent, it falls back to the next smallest
3163 unit.
3165 The keys :require-years, :require-months, :require-days,
3166 :require-weeks, :require-hours, :require-minutes are also
3167 meaningful. A non-nil value for these keys indicates that the
3168 corresponding time component should always be included, even if
3169 its value is 0.
3172 For example,
3174 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3175 :require-minutes t)
3177 means durations longer than a day will be expressed in days,
3178 hours and minutes, and durations less than a day will always be
3179 expressed in hours and minutes (even for durations less than an
3180 hour).
3182 The value
3184 (:days \"%dd\" :minutes \"%dm\")
3186 means durations longer than a day will be expressed in days and
3187 minutes, and durations less than a day will be expressed entirely
3188 in minutes (even for durations longer than an hour)."
3189 :group 'org-time
3190 :group 'org-clock
3191 :version "24.4"
3192 :package-version '(Org . "8.0")
3193 :type '(choice (string :tag "Format string")
3194 (set :tag "Plist"
3195 (group :inline t (const :tag "Years" :years)
3196 (string :tag "Format string"))
3197 (group :inline t
3198 (const :tag "Always show years" :require-years)
3199 (const t))
3200 (group :inline t (const :tag "Months" :months)
3201 (string :tag "Format string"))
3202 (group :inline t
3203 (const :tag "Always show months" :require-months)
3204 (const t))
3205 (group :inline t (const :tag "Weeks" :weeks)
3206 (string :tag "Format string"))
3207 (group :inline t
3208 (const :tag "Always show weeks" :require-weeks)
3209 (const t))
3210 (group :inline t (const :tag "Days" :days)
3211 (string :tag "Format string"))
3212 (group :inline t
3213 (const :tag "Always show days" :require-days)
3214 (const t))
3215 (group :inline t (const :tag "Hours" :hours)
3216 (string :tag "Format string"))
3217 (group :inline t
3218 (const :tag "Always show hours" :require-hours)
3219 (const t))
3220 (group :inline t (const :tag "Minutes" :minutes)
3221 (string :tag "Format string"))
3222 (group :inline t
3223 (const :tag "Always show minutes" :require-minutes)
3224 (const t)))))
3226 (defcustom org-time-clocksum-use-fractional nil
3227 "When non-nil, \\[org-clock-display] uses fractional times.
3228 See `org-time-clocksum-format' for more on time clock formats."
3229 :group 'org-time
3230 :group 'org-clock
3231 :version "24.3"
3232 :type 'boolean)
3234 (defcustom org-time-clocksum-use-effort-durations nil
3235 "When non-nil, \\[org-clock-display] uses effort durations.
3236 E.g. by default, one day is considered to be a 8 hours effort,
3237 so a task that has been clocked for 16 hours will be displayed
3238 as during 2 days in the clock display or in the clocktable.
3240 See `org-effort-durations' on how to set effort durations
3241 and `org-time-clocksum-format' for more on time clock formats."
3242 :group 'org-time
3243 :group 'org-clock
3244 :version "24.4"
3245 :package-version '(Org . "8.0")
3246 :type 'boolean)
3248 (defcustom org-time-clocksum-fractional-format "%.2f"
3249 "The format string used when creating CLOCKSUM lines,
3250 or when Org mode generates a time duration, if
3251 `org-time-clocksum-use-fractional' is enabled.
3253 The value can be a single format string containing one
3254 %-sequence, which will be filled with the number of hours as
3255 a float.
3257 Alternatively, the value can be a plist associating any of the
3258 keys :years, :months, :weeks, :days, :hours or :minutes with
3259 a format string. The time duration is formatted using the
3260 largest time unit which gives a non-zero integer part. If all
3261 specified formats have zero integer part, the smallest time unit
3262 is used."
3263 :group 'org-time
3264 :type '(choice (string :tag "Format string")
3265 (set (group :inline t (const :tag "Years" :years)
3266 (string :tag "Format string"))
3267 (group :inline t (const :tag "Months" :months)
3268 (string :tag "Format string"))
3269 (group :inline t (const :tag "Weeks" :weeks)
3270 (string :tag "Format string"))
3271 (group :inline t (const :tag "Days" :days)
3272 (string :tag "Format string"))
3273 (group :inline t (const :tag "Hours" :hours)
3274 (string :tag "Format string"))
3275 (group :inline t (const :tag "Minutes" :minutes)
3276 (string :tag "Format string")))))
3278 (defcustom org-deadline-warning-days 14
3279 "Number of days before expiration during which a deadline becomes active.
3280 This variable governs the display in sparse trees and in the agenda.
3281 When 0 or negative, it means use this number (the absolute value of it)
3282 even if a deadline has a different individual lead time specified.
3284 Custom commands can set this variable in the options section."
3285 :group 'org-time
3286 :group 'org-agenda-daily/weekly
3287 :type 'integer)
3289 (defcustom org-scheduled-delay-days 0
3290 "Number of days before a scheduled item becomes active.
3291 This variable governs the display in sparse trees and in the agenda.
3292 The default value (i.e. 0) means: don't delay scheduled item.
3293 When negative, it means use this number (the absolute value of it)
3294 even if a scheduled item has a different individual delay time
3295 specified.
3297 Custom commands can set this variable in the options section."
3298 :group 'org-time
3299 :group 'org-agenda-daily/weekly
3300 :version "24.4"
3301 :package-version '(Org . "8.0")
3302 :type 'integer)
3304 (defcustom org-read-date-prefer-future t
3305 "Non-nil means assume future for incomplete date input from user.
3306 This affects the following situations:
3307 1. The user gives a month but not a year.
3308 For example, if it is April and you enter \"feb 2\", this will be read
3309 as Feb 2, *next* year. \"May 5\", however, will be this year.
3310 2. The user gives a day, but no month.
3311 For example, if today is the 15th, and you enter \"3\", Org-mode will
3312 read this as the third of *next* month. However, if you enter \"17\",
3313 it will be considered as *this* month.
3315 If you set this variable to the symbol `time', then also the following
3316 will work:
3318 3. If the user gives a time.
3319 If the time is before now, it will be interpreted as tomorrow.
3321 Currently none of this works for ISO week specifications.
3323 When this option is nil, the current day, month and year will always be
3324 used as defaults.
3326 See also `org-agenda-jump-prefer-future'."
3327 :group 'org-time
3328 :type '(choice
3329 (const :tag "Never" nil)
3330 (const :tag "Check month and day" t)
3331 (const :tag "Check month, day, and time" time)))
3333 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3334 "Should the agenda jump command prefer the future for incomplete dates?
3335 The default is to do the same as configured in `org-read-date-prefer-future'.
3336 But you can also set a deviating value here.
3337 This may t or nil, or the symbol `org-read-date-prefer-future'."
3338 :group 'org-agenda
3339 :group 'org-time
3340 :version "24.1"
3341 :type '(choice
3342 (const :tag "Use org-read-date-prefer-future"
3343 org-read-date-prefer-future)
3344 (const :tag "Never" nil)
3345 (const :tag "Always" t)))
3347 (defcustom org-read-date-force-compatible-dates t
3348 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3350 Depending on the system Emacs is running on, certain dates cannot
3351 be represented with the type used internally to represent time.
3352 Dates between 1970-1-1 and 2038-1-1 can always be represented
3353 correctly. Some systems allow for earlier dates, some for later,
3354 some for both. One way to find out it to insert any date into an
3355 Org buffer, putting the cursor on the year and hitting S-up and
3356 S-down to test the range.
3358 When this variable is set to t, the date/time prompt will not let
3359 you specify dates outside the 1970-2037 range, so it is certain that
3360 these dates will work in whatever version of Emacs you are
3361 running, and also that you can move a file from one Emacs implementation
3362 to another. WHenever Org is forcing the year for you, it will display
3363 a message and beep.
3365 When this variable is nil, Org will check if the date is
3366 representable in the specific Emacs implementation you are using.
3367 If not, it will force a year, usually the current year, and beep
3368 to remind you. Currently this setting is not recommended because
3369 the likelihood that you will open your Org files in an Emacs that
3370 has limited date range is not negligible.
3372 A workaround for this problem is to use diary sexp dates for time
3373 stamps outside of this range."
3374 :group 'org-time
3375 :version "24.1"
3376 :type 'boolean)
3378 (defcustom org-read-date-display-live t
3379 "Non-nil means display current interpretation of date prompt live.
3380 This display will be in an overlay, in the minibuffer."
3381 :group 'org-time
3382 :type 'boolean)
3384 (defcustom org-read-date-popup-calendar t
3385 "Non-nil means pop up a calendar when prompting for a date.
3386 In the calendar, the date can be selected with mouse-1. However, the
3387 minibuffer will also be active, and you can simply enter the date as well.
3388 When nil, only the minibuffer will be available."
3389 :group 'org-time
3390 :type 'boolean)
3391 (org-defvaralias 'org-popup-calendar-for-date-prompt
3392 'org-read-date-popup-calendar)
3394 (make-obsolete-variable
3395 'org-read-date-minibuffer-setup-hook
3396 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3397 (defcustom org-read-date-minibuffer-setup-hook nil
3398 "Hook to be used to set up keys for the date/time interface.
3399 Add key definitions to `minibuffer-local-map', which will be a
3400 temporary copy.
3402 WARNING: This option is obsolete, you should use
3403 `org-read-date-minibuffer-local-map' to set up keys."
3404 :group 'org-time
3405 :type 'hook)
3407 (defcustom org-extend-today-until 0
3408 "The hour when your day really ends. Must be an integer.
3409 This has influence for the following applications:
3410 - When switching the agenda to \"today\". It it is still earlier than
3411 the time given here, the day recognized as TODAY is actually yesterday.
3412 - When a date is read from the user and it is still before the time given
3413 here, the current date and time will be assumed to be yesterday, 23:59.
3414 Also, timestamps inserted in capture templates follow this rule.
3416 IMPORTANT: This is a feature whose implementation is and likely will
3417 remain incomplete. Really, it is only here because past midnight seems to
3418 be the favorite working time of John Wiegley :-)"
3419 :group 'org-time
3420 :type 'integer)
3422 (defcustom org-use-effective-time nil
3423 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3424 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3425 \"effective time\" of any timestamps between midnight and 8am will be
3426 23:59 of the previous day."
3427 :group 'org-time
3428 :version "24.1"
3429 :type 'boolean)
3431 (defcustom org-use-last-clock-out-time-as-effective-time nil
3432 "When non-nil, use the last clock out time for `org-todo'.
3433 Note that this option has precedence over the combined use of
3434 `org-use-effective-time' and `org-extend-today-until'."
3435 :group 'org-time
3436 :version "24.4"
3437 :package-version '(Org . "8.0")
3438 :type 'boolean)
3440 (defcustom org-edit-timestamp-down-means-later nil
3441 "Non-nil means S-down will increase the time in a time stamp.
3442 When nil, S-up will increase."
3443 :group 'org-time
3444 :type 'boolean)
3446 (defcustom org-calendar-follow-timestamp-change t
3447 "Non-nil means make the calendar window follow timestamp changes.
3448 When a timestamp is modified and the calendar window is visible, it will be
3449 moved to the new date."
3450 :group 'org-time
3451 :type 'boolean)
3453 (defgroup org-tags nil
3454 "Options concerning tags in Org-mode."
3455 :tag "Org Tags"
3456 :group 'org)
3458 (defcustom org-tag-alist nil
3459 "Default tags available in Org files.
3461 The value of this variable is an alist. Associations either:
3463 (TAG)
3464 (TAG . SELECT)
3465 (SPECIAL)
3467 where TAG is a tag as a string, SELECT is a character, used to
3468 select that tag through the fast tag selection interface, and
3469 SPECIAL is one of the following keywords: `:startgroup',
3470 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3471 `:newline'. These keywords are used to define a hierarchy of
3472 tags. See manual for details.
3474 When this variable is nil, Org mode bases tag input on what is
3475 already in the buffer. The value can be overridden locally by
3476 using a TAGS keyword, e.g.,
3478 #+TAGS: tag1 tag2
3480 See also `org-tag-persistent-alist' to sidestep this behavior."
3481 :group 'org-tags
3482 :type '(repeat
3483 (choice
3484 (cons (string :tag "Tag name")
3485 (character :tag "Access char"))
3486 (const :tag "Start radio group" (:startgroup))
3487 (const :tag "Start tag group, non distinct" (:startgrouptag))
3488 (const :tag "Group tags delimiter" (:grouptags))
3489 (const :tag "End radio group" (:endgroup))
3490 (const :tag "End tag group, non distinct" (:endgrouptag))
3491 (const :tag "New line" (:newline)))))
3493 (defcustom org-tag-persistent-alist nil
3494 "Tags always available in Org files.
3496 The value of this variable is an alist. Associations either:
3498 (TAG)
3499 (TAG . SELECT)
3500 (SPECIAL)
3502 where TAG is a tag as a string, SELECT is a character, used to
3503 select that tag through the fast tag selection interface, and
3504 SPECIAL is one of the following keywords: `:startgroup',
3505 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3506 `:newline'. These keywords are used to define a hierarchy of
3507 tags. See manual for details.
3509 Unlike to `org-tag-alist', tags defined in this variable do not
3510 depend on a local TAGS keyword. Instead, to disable these tags
3511 on a per-file basis, insert anywhere in the file:
3513 #+STARTUP: noptag"
3514 :group 'org-tags
3515 :type '(repeat
3516 (choice
3517 (cons (string :tag "Tag name")
3518 (character :tag "Access char"))
3519 (const :tag "Start radio group" (:startgroup))
3520 (const :tag "Start tag group, non distinct" (:startgrouptag))
3521 (const :tag "Group tags delimiter" (:grouptags))
3522 (const :tag "End radio group" (:endgroup))
3523 (const :tag "End tag group, non distinct" (:endgrouptag))
3524 (const :tag "New line" (:newline)))))
3526 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3527 "If non-nil, always offer completion for all tags of all agenda files.
3528 Instead of customizing this variable directly, you might want to
3529 set it locally for capture buffers, because there no list of
3530 tags in that file can be created dynamically (there are none).
3532 (add-hook \\='org-capture-mode-hook
3533 (lambda ()
3534 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3535 :group 'org-tags
3536 :version "24.1"
3537 :type 'boolean)
3539 (defvar org-file-tags nil
3540 "List of tags that can be inherited by all entries in the file.
3541 The tags will be inherited if the variable `org-use-tag-inheritance'
3542 says they should be.
3543 This variable is populated from #+FILETAGS lines.")
3545 (defcustom org-use-fast-tag-selection 'auto
3546 "Non-nil means use fast tag selection scheme.
3547 This is a special interface to select and deselect tags with single keys.
3548 When nil, fast selection is never used.
3549 When the symbol `auto', fast selection is used if and only if selection
3550 characters for tags have been configured, either through the variable
3551 `org-tag-alist' or through a #+TAGS line in the buffer.
3552 When t, fast selection is always used and selection keys are assigned
3553 automatically if necessary."
3554 :group 'org-tags
3555 :type '(choice
3556 (const :tag "Always" t)
3557 (const :tag "Never" nil)
3558 (const :tag "When selection characters are configured" auto)))
3560 (defcustom org-fast-tag-selection-single-key nil
3561 "Non-nil means fast tag selection exits after first change.
3562 When nil, you have to press RET to exit it.
3563 During fast tag selection, you can toggle this flag with `C-c'.
3564 This variable can also have the value `expert'. In this case, the window
3565 displaying the tags menu is not even shown, until you press C-c again."
3566 :group 'org-tags
3567 :type '(choice
3568 (const :tag "No" nil)
3569 (const :tag "Yes" t)
3570 (const :tag "Expert" expert)))
3572 (defvar org-fast-tag-selection-include-todo nil
3573 "Non-nil means fast tags selection interface will also offer TODO states.
3574 This is an undocumented feature, you should not rely on it.")
3576 (defcustom org-tags-column -77
3577 "The column to which tags should be indented in a headline.
3578 If this number is positive, it specifies the column. If it is negative,
3579 it means that the tags should be flushright to that column. For example,
3580 -80 works well for a normal 80 character screen.
3581 When 0, place tags directly after headline text, with only one space in
3582 between."
3583 :group 'org-tags
3584 :type 'integer)
3586 (defcustom org-auto-align-tags t
3587 "Non-nil keeps tags aligned when modifying headlines.
3588 Some operations (i.e. demoting) change the length of a headline and
3589 therefore shift the tags around. With this option turned on, after
3590 each such operation the tags are again aligned to `org-tags-column'."
3591 :group 'org-tags
3592 :type 'boolean)
3594 (defcustom org-use-tag-inheritance t
3595 "Non-nil means tags in levels apply also for sublevels.
3596 When nil, only the tags directly given in a specific line apply there.
3597 This may also be a list of tags that should be inherited, or a regexp that
3598 matches tags that should be inherited. Additional control is possible
3599 with the variable `org-tags-exclude-from-inheritance' which gives an
3600 explicit list of tags to be excluded from inheritance, even if the value of
3601 `org-use-tag-inheritance' would select it for inheritance.
3603 If this option is t, a match early-on in a tree can lead to a large
3604 number of matches in the subtree when constructing the agenda or creating
3605 a sparse tree. If you only want to see the first match in a tree during
3606 a search, check out the variable `org-tags-match-list-sublevels'."
3607 :group 'org-tags
3608 :type '(choice
3609 (const :tag "Not" nil)
3610 (const :tag "Always" t)
3611 (repeat :tag "Specific tags" (string :tag "Tag"))
3612 (regexp :tag "Tags matched by regexp")))
3614 (defcustom org-tags-exclude-from-inheritance nil
3615 "List of tags that should never be inherited.
3616 This is a way to exclude a few tags from inheritance. For way to do
3617 the opposite, to actively allow inheritance for selected tags,
3618 see the variable `org-use-tag-inheritance'."
3619 :group 'org-tags
3620 :type '(repeat (string :tag "Tag")))
3622 (defun org-tag-inherit-p (tag)
3623 "Check if TAG is one that should be inherited."
3624 (cond
3625 ((member tag org-tags-exclude-from-inheritance) nil)
3626 ((eq org-use-tag-inheritance t) t)
3627 ((not org-use-tag-inheritance) nil)
3628 ((stringp org-use-tag-inheritance)
3629 (string-match org-use-tag-inheritance tag))
3630 ((listp org-use-tag-inheritance)
3631 (member tag org-use-tag-inheritance))
3632 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3634 (defcustom org-tags-match-list-sublevels t
3635 "Non-nil means list also sublevels of headlines matching a search.
3636 This variable applies to tags/property searches, and also to stuck
3637 projects because this search is based on a tags match as well.
3639 When set to the symbol `indented', sublevels are indented with
3640 leading dots.
3642 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3643 the sublevels of a headline matching a tag search often also match
3644 the same search. Listing all of them can create very long lists.
3645 Setting this variable to nil causes subtrees of a match to be skipped.
3647 This variable is semi-obsolete and probably should always be true. It
3648 is better to limit inheritance to certain tags using the variables
3649 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3650 :group 'org-tags
3651 :type '(choice
3652 (const :tag "No, don't list them" nil)
3653 (const :tag "Yes, do list them" t)
3654 (const :tag "List them, indented with leading dots" indented)))
3656 (defcustom org-tags-sort-function nil
3657 "When set, tags are sorted using this function as a comparator."
3658 :group 'org-tags
3659 :type '(choice
3660 (const :tag "No sorting" nil)
3661 (const :tag "Alphabetical" string<)
3662 (const :tag "Reverse alphabetical" string>)
3663 (function :tag "Custom function" nil)))
3665 (defvar org-tags-history nil
3666 "History of minibuffer reads for tags.")
3667 (defvar org-last-tags-completion-table nil
3668 "The last used completion table for tags.")
3669 (defvar org-after-tags-change-hook nil
3670 "Hook that is run after the tags in a line have changed.")
3672 (defgroup org-properties nil
3673 "Options concerning properties in Org-mode."
3674 :tag "Org Properties"
3675 :group 'org)
3677 (defcustom org-property-format "%-10s %s"
3678 "How property key/value pairs should be formatted by `indent-line'.
3679 When `indent-line' hits a property definition, it will format the line
3680 according to this format, mainly to make sure that the values are
3681 lined-up with respect to each other."
3682 :group 'org-properties
3683 :type 'string)
3685 (defcustom org-properties-postprocess-alist nil
3686 "Alist of properties and functions to adjust inserted values.
3687 Elements of this alist must be of the form
3689 ([string] [function])
3691 where [string] must be a property name and [function] must be a
3692 lambda expression: this lambda expression must take one argument,
3693 the value to adjust, and return the new value as a string.
3695 For example, this element will allow the property \"Remaining\"
3696 to be updated wrt the relation between the \"Effort\" property
3697 and the clock summary:
3699 ((\"Remaining\" (lambda(value)
3700 (let ((clocksum (org-clock-sum-current-item))
3701 (effort (org-duration-string-to-minutes
3702 (org-entry-get (point) \"Effort\"))))
3703 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3704 :group 'org-properties
3705 :version "24.1"
3706 :type '(alist :key-type (string :tag "Property")
3707 :value-type (function :tag "Function")))
3709 (defcustom org-use-property-inheritance nil
3710 "Non-nil means properties apply also for sublevels.
3712 This setting is chiefly used during property searches. Turning it on can
3713 cause significant overhead when doing a search, which is why it is not
3714 on by default.
3716 When nil, only the properties directly given in the current entry count.
3717 When t, every property is inherited. The value may also be a list of
3718 properties that should have inheritance, or a regular expression matching
3719 properties that should be inherited.
3721 However, note that some special properties use inheritance under special
3722 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3723 and the properties ending in \"_ALL\" when they are used as descriptor
3724 for valid values of a property.
3726 Note for programmers:
3727 When querying an entry with `org-entry-get', you can control if inheritance
3728 should be used. By default, `org-entry-get' looks only at the local
3729 properties. You can request inheritance by setting the inherit argument
3730 to t (to force inheritance) or to `selective' (to respect the setting
3731 in this variable)."
3732 :group 'org-properties
3733 :type '(choice
3734 (const :tag "Not" nil)
3735 (const :tag "Always" t)
3736 (repeat :tag "Specific properties" (string :tag "Property"))
3737 (regexp :tag "Properties matched by regexp")))
3739 (defun org-property-inherit-p (property)
3740 "Check if PROPERTY is one that should be inherited."
3741 (cond
3742 ((eq org-use-property-inheritance t) t)
3743 ((not org-use-property-inheritance) nil)
3744 ((stringp org-use-property-inheritance)
3745 (string-match org-use-property-inheritance property))
3746 ((listp org-use-property-inheritance)
3747 (member property org-use-property-inheritance))
3748 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3750 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3751 "The default column format, if no other format has been defined.
3752 This variable can be set on the per-file basis by inserting a line
3754 #+COLUMNS: %25ITEM ....."
3755 :group 'org-properties
3756 :type 'string)
3758 (defcustom org-columns-ellipses ".."
3759 "The ellipses to be used when a field in column view is truncated.
3760 When this is the empty string, as many characters as possible are shown,
3761 but then there will be no visual indication that the field has been truncated.
3762 When this is a string of length N, the last N characters of a truncated
3763 field are replaced by this string. If the column is narrower than the
3764 ellipses string, only part of the ellipses string will be shown."
3765 :group 'org-properties
3766 :type 'string)
3768 (defconst org-global-properties-fixed
3769 '(("VISIBILITY_ALL" . "folded children content all")
3770 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3771 "List of property/value pairs that can be inherited by any entry.
3773 These are fixed values, for the preset properties. The user variable
3774 that can be used to add to this list is `org-global-properties'.
3776 The entries in this list are cons cells where the car is a property
3777 name and cdr is a string with the value. If the value represents
3778 multiple items like an \"_ALL\" property, separate the items by
3779 spaces.")
3781 (defcustom org-global-properties nil
3782 "List of property/value pairs that can be inherited by any entry.
3784 This list will be combined with the constant `org-global-properties-fixed'.
3786 The entries in this list are cons cells where the car is a property
3787 name and cdr is a string with the value.
3789 You can set buffer-local values for the same purpose in the variable
3790 `org-file-properties' this by adding lines like
3792 #+PROPERTY: NAME VALUE"
3793 :group 'org-properties
3794 :type '(repeat
3795 (cons (string :tag "Property")
3796 (string :tag "Value"))))
3798 (defvar-local org-file-properties nil
3799 "List of property/value pairs that can be inherited by any entry.
3800 Valid for the current buffer.
3801 This variable is populated from #+PROPERTY lines.")
3803 (defgroup org-agenda nil
3804 "Options concerning agenda views in Org-mode."
3805 :tag "Org Agenda"
3806 :group 'org)
3808 (defvar-local org-category nil
3809 "Variable used by org files to set a category for agenda display.
3810 Such files should use a file variable to set it, for example
3812 # -*- mode: org; org-category: \"ELisp\"
3814 or contain a special line
3816 #+CATEGORY: ELisp
3818 If the file does not specify a category, then file's base name
3819 is used instead.")
3820 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3822 (defcustom org-agenda-files nil
3823 "The files to be used for agenda display.
3824 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3825 \\[org-remove-file]. You can also use customize to edit the list.
3827 If an entry is a directory, all files in that directory that are matched by
3828 `org-agenda-file-regexp' will be part of the file list.
3830 If the value of the variable is not a list but a single file name, then
3831 the list of agenda files is actually stored and maintained in that file, one
3832 agenda file per line. In this file paths can be given relative to
3833 `org-directory'. Tilde expansion and environment variable substitution
3834 are also made."
3835 :group 'org-agenda
3836 :type '(choice
3837 (repeat :tag "List of files and directories" file)
3838 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3840 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3841 "Regular expression to match files for `org-agenda-files'.
3842 If any element in the list in that variable contains a directory instead
3843 of a normal file, all files in that directory that are matched by this
3844 regular expression will be included."
3845 :group 'org-agenda
3846 :type 'regexp)
3848 (defcustom org-agenda-text-search-extra-files nil
3849 "List of extra files to be searched by text search commands.
3850 These files will be searched in addition to the agenda files by the
3851 commands `org-search-view' (`\\[org-agenda] s') \
3852 and `org-occur-in-agenda-files'.
3853 Note that these files will only be searched for text search commands,
3854 not for the other agenda views like todo lists, tag searches or the weekly
3855 agenda. This variable is intended to list notes and possibly archive files
3856 that should also be searched by these two commands.
3857 In fact, if the first element in the list is the symbol `agenda-archives',
3858 then all archive files of all agenda files will be added to the search
3859 scope."
3860 :group 'org-agenda
3861 :type '(set :greedy t
3862 (const :tag "Agenda Archives" agenda-archives)
3863 (repeat :inline t (file))))
3865 (org-defvaralias 'org-agenda-multi-occur-extra-files
3866 'org-agenda-text-search-extra-files)
3868 (defcustom org-agenda-skip-unavailable-files nil
3869 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3870 A nil value means to remove them, after a query, from the list."
3871 :group 'org-agenda
3872 :type 'boolean)
3874 (defcustom org-calendar-to-agenda-key [?c]
3875 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3876 The command `org-calendar-goto-agenda' will be bound to this key. The
3877 default is the character `c' because then `c' can be used to switch back and
3878 forth between agenda and calendar."
3879 :group 'org-agenda
3880 :type 'sexp)
3882 (defcustom org-calendar-insert-diary-entry-key [?i]
3883 "The key to be installed in `calendar-mode-map' for adding diary entries.
3884 This option is irrelevant until `org-agenda-diary-file' has been configured
3885 to point to an Org-mode file. When that is the case, the command
3886 `org-agenda-diary-entry' will be bound to the key given here, by default
3887 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3888 if you want to continue doing this, you need to change this to a different
3889 key."
3890 :group 'org-agenda
3891 :type 'sexp)
3893 (defcustom org-agenda-diary-file 'diary-file
3894 "File to which to add new entries with the `i' key in agenda and calendar.
3895 When this is the symbol `diary-file', the functionality in the Emacs
3896 calendar will be used to add entries to the `diary-file'. But when this
3897 points to a file, `org-agenda-diary-entry' will be used instead."
3898 :group 'org-agenda
3899 :type '(choice
3900 (const :tag "The standard Emacs diary file" diary-file)
3901 (file :tag "Special Org file diary entries")))
3903 (eval-after-load "calendar"
3904 '(progn
3905 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3906 'org-calendar-goto-agenda)
3907 (add-hook 'calendar-mode-hook
3908 (lambda ()
3909 (unless (eq org-agenda-diary-file 'diary-file)
3910 (define-key calendar-mode-map
3911 org-calendar-insert-diary-entry-key
3912 'org-agenda-diary-entry))))))
3914 (defgroup org-latex nil
3915 "Options for embedding LaTeX code into Org-mode."
3916 :tag "Org LaTeX"
3917 :group 'org)
3919 (defcustom org-format-latex-options
3920 '(:foreground default :background default :scale 1.0
3921 :html-foreground "Black" :html-background "Transparent"
3922 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3923 "Options for creating images from LaTeX fragments.
3924 This is a property list with the following properties:
3925 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3926 `default' means use the foreground of the default face.
3927 `auto' means use the foreground from the text face.
3928 :background the background color, or \"Transparent\".
3929 `default' means use the background of the default face.
3930 `auto' means use the background from the text face.
3931 :scale a scaling factor for the size of the images, to get more pixels
3932 :html-foreground, :html-background, :html-scale
3933 the same numbers for HTML export.
3934 :matchers a list indicating which matchers should be used to
3935 find LaTeX fragments. Valid members of this list are:
3936 \"begin\" find environments
3937 \"$1\" find single characters surrounded by $.$
3938 \"$\" find math expressions surrounded by $...$
3939 \"$$\" find math expressions surrounded by $$....$$
3940 \"\\(\" find math expressions surrounded by \\(...\\)
3941 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3942 :group 'org-latex
3943 :type 'plist)
3945 (defcustom org-format-latex-signal-error t
3946 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3947 When nil, just push out a message."
3948 :group 'org-latex
3949 :version "24.1"
3950 :type 'boolean)
3952 (defcustom org-latex-to-mathml-jar-file nil
3953 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3954 Use this to specify additional executable file say a jar file.
3956 When using MathToWeb as the converter, specify the full-path to
3957 your mathtoweb.jar file."
3958 :group 'org-latex
3959 :version "24.1"
3960 :type '(choice
3961 (const :tag "None" nil)
3962 (file :tag "JAR file" :must-match t)))
3964 (defcustom org-latex-to-mathml-convert-command nil
3965 "Command to convert LaTeX fragments to MathML.
3966 Replace format-specifiers in the command as noted below and use
3967 `shell-command' to convert LaTeX to MathML.
3968 %j: Executable file in fully expanded form as specified by
3969 `org-latex-to-mathml-jar-file'.
3970 %I: Input LaTeX file in fully expanded form.
3971 %i: The latex fragment to be converted.
3972 %o: Output MathML file.
3974 This command is used by `org-create-math-formula'.
3976 When using MathToWeb as the converter, set this option to
3977 \"java -jar %j -unicode -force -df %o %I\".
3979 When using LaTeXML set this option to
3980 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3981 :group 'org-latex
3982 :version "24.1"
3983 :type '(choice
3984 (const :tag "None" nil)
3985 (string :tag "\nShell command")))
3987 (define-obsolete-variable-alias
3988 'org-latex-create-formula-image-program
3989 'org-preview-latex-default-process "25.1")
3991 (defcustom org-preview-latex-default-process 'dvipng
3992 "The default process to convert LaTeX fragments to image files.
3993 All available processes and theirs documents can be found in
3994 `org-preview-latex-process-alist', which see."
3995 :group 'org-latex
3996 :version "25.2"
3997 :package-version '(Org . "9.0")
3998 :type 'symbol)
4000 (defcustom org-preview-latex-process-alist
4001 '((dvipng
4002 :programs ("latex" "dvipng" "gs")
4003 :description "dvi > png"
4004 :message "you need to install the programs: latex, dvipng and ghostscript."
4005 :image-input-type "dvi"
4006 :image-output-type "png"
4007 :image-size-adjust (1.0 . 1.0)
4008 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4009 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4010 (dvisvgm
4011 :programs ("latex" "dvisvgm" "gs")
4012 :description "dvi > svg"
4013 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4014 :use-xcolor t
4015 :image-input-type "dvi"
4016 :image-output-type "svg"
4017 :image-size-adjust (1.7 . 1.5)
4018 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4019 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4020 (imagemagick
4021 :programs ("latex" "convert" "gs")
4022 :description "pdf > png"
4023 :message
4024 "you need to install the programs: latex, imagemagick and ghostscript."
4025 :use-xcolor t
4026 :image-input-type "pdf"
4027 :image-output-type "png"
4028 :image-size-adjust (1.0 . 1.0)
4029 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4030 :image-converter
4031 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4032 "Definitions of external processes for LaTeX previewing.
4033 Org mode can use some external commands to generate TeX snippet's images for
4034 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4035 `org-create-formula-image' how to call them.
4037 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4038 PROPERTIES accepts the following attributes:
4040 :programs list of strings, required programs.
4041 :description string, describe the process.
4042 :message string, message it when required programs cannot be found.
4043 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4044 :image-output-type string, output file type of image converter (e.g., \"png\").
4045 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4046 deal with background and foreground color of image.
4047 Otherwise, dvipng style background and foregroud color
4048 format are generated. You may then refer to them in
4049 command options with \"%F\" and \"%B\".
4050 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4051 image size showed in buffer and the cdr element is for
4052 HTML file. This option is only useful for process
4053 developers, users should use variable
4054 `org-format-latex-options' instead.
4055 :post-clean list of strings, files matched are to be cleaned up once
4056 the image is generated. When nil, the files with \".dvi\",
4057 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4058 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4059 be cleaned up.
4060 :latex-header list of strings, the LaTeX header of the snippet file.
4061 When nil, the fallback value is used instead, which is
4062 controlled by `org-format-latex-header',
4063 `org-latex-default-packages-alist' and
4064 `org-latex-packages-alist', which see.
4065 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4066 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4067 replaced with values defined below.
4068 :image-converter list of image converter commands strings. Each of them is
4069 given to the shell and supports any of the following
4070 place-holders defined below.
4072 Place-holders used by `:image-converter' and `:latex-compiler':
4074 %f input file name.
4075 %b base name of input file.
4076 %o base directory of input file.
4078 Place-holders only used by `:image-converter':
4080 %F foreground of image
4081 %B background of image
4082 %D dpi, which is used to adjust image size by some processing commands.
4083 %S the image size scale ratio, which is used to adjust image size by some
4084 processing commands."
4085 :group 'org-latex
4086 :version "25.2"
4087 :package-version '(Org . "9.0")
4088 :type '(alist :tag "LaTeX to image backends"
4089 :value-type (plist)))
4091 (define-obsolete-variable-alias
4092 'org-latex-preview-ltxpng-directory
4093 'org-preview-latex-image-directory "25.1")
4095 (defcustom org-preview-latex-image-directory "ltximg/"
4096 "Path to store latex preview images.
4097 A relative path here creates many directories relative to the
4098 processed org files paths. An absolute path puts all preview
4099 images at the same place."
4100 :group 'org-latex
4101 :version "25.1"
4102 :package-version '(Org . "9.0")
4103 :type 'string)
4105 (defun org-format-latex-mathml-available-p ()
4106 "Return t if `org-latex-to-mathml-convert-command' is usable."
4107 (save-match-data
4108 (when (and (boundp 'org-latex-to-mathml-convert-command)
4109 org-latex-to-mathml-convert-command)
4110 (let ((executable (car (split-string
4111 org-latex-to-mathml-convert-command))))
4112 (when (executable-find executable)
4113 (if (string-match
4114 "%j" org-latex-to-mathml-convert-command)
4115 (file-readable-p org-latex-to-mathml-jar-file)
4116 t))))))
4118 (defcustom org-format-latex-header "\\documentclass{article}
4119 \\usepackage[usenames]{color}
4120 \[PACKAGES]
4121 \[DEFAULT-PACKAGES]
4122 \\pagestyle{empty} % do not remove
4123 % The settings below are copied from fullpage.sty
4124 \\setlength{\\textwidth}{\\paperwidth}
4125 \\addtolength{\\textwidth}{-3cm}
4126 \\setlength{\\oddsidemargin}{1.5cm}
4127 \\addtolength{\\oddsidemargin}{-2.54cm}
4128 \\setlength{\\evensidemargin}{\\oddsidemargin}
4129 \\setlength{\\textheight}{\\paperheight}
4130 \\addtolength{\\textheight}{-\\headheight}
4131 \\addtolength{\\textheight}{-\\headsep}
4132 \\addtolength{\\textheight}{-\\footskip}
4133 \\addtolength{\\textheight}{-3cm}
4134 \\setlength{\\topmargin}{1.5cm}
4135 \\addtolength{\\topmargin}{-2.54cm}"
4136 "The document header used for processing LaTeX fragments.
4137 It is imperative that this header make sure that no page number
4138 appears on the page. The package defined in the variables
4139 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4140 will either replace the placeholder \"[PACKAGES]\" in this
4141 header, or they will be appended."
4142 :group 'org-latex
4143 :type 'string)
4145 (defun org-set-packages-alist (var val)
4146 "Set the packages alist and make sure it has 3 elements per entry."
4147 (set var (mapcar (lambda (x)
4148 (if (and (consp x) (= (length x) 2))
4149 (list (car x) (nth 1 x) t)
4151 val)))
4153 (defun org-get-packages-alist (var)
4154 "Get the packages alist and make sure it has 3 elements per entry."
4155 (mapcar (lambda (x)
4156 (if (and (consp x) (= (length x) 2))
4157 (list (car x) (nth 1 x) t)
4159 (default-value var)))
4161 (defcustom org-latex-default-packages-alist
4162 '(("AUTO" "inputenc" t ("pdflatex"))
4163 ("T1" "fontenc" t ("pdflatex"))
4164 ("" "graphicx" t)
4165 ("" "grffile" t)
4166 ("" "longtable" nil)
4167 ("" "wrapfig" nil)
4168 ("" "rotating" nil)
4169 ("normalem" "ulem" t)
4170 ("" "amsmath" t)
4171 ("" "textcomp" t)
4172 ("" "amssymb" t)
4173 ("" "capt-of" nil)
4174 ("" "hyperref" nil))
4175 "Alist of default packages to be inserted in the header.
4177 Change this only if one of the packages here causes an
4178 incompatibility with another package you are using.
4180 The packages in this list are needed by one part or another of
4181 Org mode to function properly:
4183 - inputenc, fontenc: for basic font and character selection
4184 - graphicx: for including images
4185 - grffile: allow periods and spaces in graphics file names
4186 - longtable: For multipage tables
4187 - wrapfig: for figure placement
4188 - rotating: for sideways figures and tables
4189 - ulem: for underline and strike-through
4190 - amsmath: for subscript and superscript and math environments
4191 - textcomp, amssymb: for various symbols used
4192 for interpreting the entities in `org-entities'. You can skip
4193 some of these packages if you don't use any of their symbols.
4194 - capt-of: for captions outside of floats
4195 - hyperref: for cross references
4197 Therefore you should not modify this variable unless you know
4198 what you are doing. The one reason to change it anyway is that
4199 you might be loading some other package that conflicts with one
4200 of the default packages. Each element is either a cell or
4201 a string.
4203 A cell is of the format
4205 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4207 If SNIPPET-FLAG is non-nil, the package also needs to be included
4208 when compiling LaTeX snippets into images for inclusion into
4209 non-LaTeX output. COMPILERS is a list of compilers that should
4210 include the package, see `org-latex-compiler'. If the document
4211 compiler is not in the list, and the list is non-nil, the package
4212 will not be inserted in the final document.
4214 A string will be inserted as-is in the header of the document."
4215 :group 'org-latex
4216 :group 'org-export-latex
4217 :set 'org-set-packages-alist
4218 :get 'org-get-packages-alist
4219 :version "25.1"
4220 :package-version '(Org . "8.3")
4221 :type '(repeat
4222 (choice
4223 (list :tag "options/package pair"
4224 (string :tag "options")
4225 (string :tag "package")
4226 (boolean :tag "Snippet"))
4227 (string :tag "A line of LaTeX"))))
4229 (defcustom org-latex-packages-alist nil
4230 "Alist of packages to be inserted in every LaTeX header.
4232 These will be inserted after `org-latex-default-packages-alist'.
4233 Each element is either a cell or a string.
4235 A cell is of the format:
4237 (\"options\" \"package\" SNIPPET-FLAG)
4239 SNIPPET-FLAG, when non-nil, indicates that this package is also
4240 needed when turning LaTeX snippets into images for inclusion into
4241 non-LaTeX output.
4243 A string will be inserted as-is in the header of the document.
4245 Make sure that you only list packages here which:
4247 - you want in every file;
4248 - do not conflict with the setup in `org-format-latex-header';
4249 - do not conflict with the default packages in
4250 `org-latex-default-packages-alist'."
4251 :group 'org-latex
4252 :group 'org-export-latex
4253 :set 'org-set-packages-alist
4254 :get 'org-get-packages-alist
4255 :type '(repeat
4256 (choice
4257 (list :tag "options/package pair"
4258 (string :tag "options")
4259 (string :tag "package")
4260 (boolean :tag "Snippet"))
4261 (string :tag "A line of LaTeX"))))
4263 (defgroup org-appearance nil
4264 "Settings for Org-mode appearance."
4265 :tag "Org Appearance"
4266 :group 'org)
4268 (defcustom org-level-color-stars-only nil
4269 "Non-nil means fontify only the stars in each headline.
4270 When nil, the entire headline is fontified.
4271 Changing it requires restart of `font-lock-mode' to become effective
4272 also in regions already fontified."
4273 :group 'org-appearance
4274 :type 'boolean)
4276 (defcustom org-hide-leading-stars nil
4277 "Non-nil means hide the first N-1 stars in a headline.
4278 This works by using the face `org-hide' for these stars. This
4279 face is white for a light background, and black for a dark
4280 background. You may have to customize the face `org-hide' to
4281 make this work.
4282 Changing it requires restart of `font-lock-mode' to become effective
4283 also in regions already fontified.
4284 You may also set this on a per-file basis by adding one of the following
4285 lines to the buffer:
4287 #+STARTUP: hidestars
4288 #+STARTUP: showstars"
4289 :group 'org-appearance
4290 :type 'boolean)
4292 (defcustom org-hidden-keywords nil
4293 "List of symbols corresponding to keywords to be hidden the org buffer.
4294 For example, a value \\='(title) for this list will make the document's title
4295 appear in the buffer without the initial #+TITLE: keyword."
4296 :group 'org-appearance
4297 :version "24.1"
4298 :type '(set (const :tag "#+AUTHOR" author)
4299 (const :tag "#+DATE" date)
4300 (const :tag "#+EMAIL" email)
4301 (const :tag "#+TITLE" title)))
4303 (defcustom org-custom-properties nil
4304 "List of properties (as strings) with a special meaning.
4305 The default use of these custom properties is to let the user
4306 hide them with `org-toggle-custom-properties-visibility'."
4307 :group 'org-properties
4308 :group 'org-appearance
4309 :version "24.3"
4310 :type '(repeat (string :tag "Property Name")))
4312 (defcustom org-fontify-done-headline nil
4313 "Non-nil means change the face of a headline if it is marked DONE.
4314 Normally, only the TODO/DONE keyword indicates the state of a headline.
4315 When this is non-nil, the headline after the keyword is set to the
4316 `org-headline-done' as an additional indication."
4317 :group 'org-appearance
4318 :type 'boolean)
4320 (defcustom org-fontify-emphasized-text t
4321 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4322 Changing this variable requires a restart of Emacs to take effect."
4323 :group 'org-appearance
4324 :type 'boolean)
4326 (defcustom org-fontify-whole-heading-line nil
4327 "Non-nil means fontify the whole line for headings.
4328 This is useful when setting a background color for the
4329 org-level-* faces."
4330 :group 'org-appearance
4331 :type 'boolean)
4333 (defcustom org-highlight-latex-and-related nil
4334 "Non-nil means highlight LaTeX related syntax in the buffer.
4335 When non nil, the value should be a list containing any of the
4336 following symbols:
4337 `latex' Highlight LaTeX snippets and environments.
4338 `script' Highlight subscript and superscript.
4339 `entities' Highlight entities."
4340 :group 'org-appearance
4341 :version "24.4"
4342 :package-version '(Org . "8.0")
4343 :type '(choice
4344 (const :tag "No highlighting" nil)
4345 (set :greedy t :tag "Highlight"
4346 (const :tag "LaTeX snippets and environments" latex)
4347 (const :tag "Subscript and superscript" script)
4348 (const :tag "Entities" entities))))
4350 (defcustom org-hide-emphasis-markers nil
4351 "Non-nil mean font-lock should hide the emphasis marker characters."
4352 :group 'org-appearance
4353 :type 'boolean)
4355 (defcustom org-hide-macro-markers nil
4356 "Non-nil mean font-lock should hide the brackets marking macro calls."
4357 :group 'org-appearance
4358 :type 'boolean)
4360 (defcustom org-pretty-entities nil
4361 "Non-nil means show entities as UTF8 characters.
4362 When nil, the \\name form remains in the buffer."
4363 :group 'org-appearance
4364 :version "24.1"
4365 :type 'boolean)
4367 (defcustom org-pretty-entities-include-sub-superscripts t
4368 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4369 :group 'org-appearance
4370 :version "24.1"
4371 :type 'boolean)
4373 (defvar org-emph-re nil
4374 "Regular expression for matching emphasis.
4375 After a match, the match groups contain these elements:
4376 0 The match of the full regular expression, including the characters
4377 before and after the proper match
4378 1 The character before the proper match, or empty at beginning of line
4379 2 The proper match, including the leading and trailing markers
4380 3 The leading marker like * or /, indicating the type of highlighting
4381 4 The text between the emphasis markers, not including the markers
4382 5 The character after the match, empty at the end of a line")
4383 (defvar org-verbatim-re nil
4384 "Regular expression for matching verbatim text.")
4385 (defvar org-emphasis-regexp-components) ; defined just below
4386 (defvar org-emphasis-alist) ; defined just below
4387 (defun org-set-emph-re (var val)
4388 "Set variable and compute the emphasis regular expression."
4389 (set var val)
4390 (when (and (boundp 'org-emphasis-alist)
4391 (boundp 'org-emphasis-regexp-components)
4392 org-emphasis-alist org-emphasis-regexp-components)
4393 (let* ((e org-emphasis-regexp-components)
4394 (pre (car e))
4395 (post (nth 1 e))
4396 (border (nth 2 e))
4397 (body (nth 3 e))
4398 (nl (nth 4 e))
4399 (body1 (concat body "*?"))
4400 (markers (mapconcat 'car org-emphasis-alist ""))
4401 (vmarkers (mapconcat
4402 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4403 org-emphasis-alist "")))
4404 ;; make sure special characters appear at the right position in the class
4405 (if (string-match "\\^" markers)
4406 (setq markers (concat (replace-match "" t t markers) "^")))
4407 (if (string-match "-" markers)
4408 (setq markers (concat (replace-match "" t t markers) "-")))
4409 (if (string-match "\\^" vmarkers)
4410 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4411 (if (string-match "-" vmarkers)
4412 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4413 (if (> nl 0)
4414 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4415 (int-to-string nl) "\\}")))
4416 ;; Make the regexp
4417 (setq org-emph-re
4418 (concat "\\([" pre "]\\|^\\)"
4419 "\\("
4420 "\\([" markers "]\\)"
4421 "\\("
4422 "[^" border "]\\|"
4423 "[^" border "]"
4424 body1
4425 "[^" border "]"
4426 "\\)"
4427 "\\3\\)"
4428 "\\([" post "]\\|$\\)"))
4429 (setq org-verbatim-re
4430 (concat "\\([" pre "]\\|^\\)"
4431 "\\("
4432 "\\([" vmarkers "]\\)"
4433 "\\("
4434 "[^" border "]\\|"
4435 "[^" border "]"
4436 body1
4437 "[^" border "]"
4438 "\\)"
4439 "\\3\\)"
4440 "\\([" post "]\\|$\\)")))))
4442 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4443 ;; set this option proved cumbersome. See this message/thread:
4444 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4445 (defvar org-emphasis-regexp-components
4446 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4447 "Components used to build the regular expression for emphasis.
4448 This is a list with five entries. Terminology: In an emphasis string
4449 like \" *strong word* \", we call the initial space PREMATCH, the final
4450 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4451 and \"trong wor\" is the body. The different components in this variable
4452 specify what is allowed/forbidden in each part:
4454 pre Chars allowed as prematch. Beginning of line will be allowed too.
4455 post Chars allowed as postmatch. End of line will be allowed too.
4456 border The chars *forbidden* as border characters.
4457 body-regexp A regexp like \".\" to match a body character. Don't use
4458 non-shy groups here, and don't allow newline here.
4459 newline The maximum number of newlines allowed in an emphasis exp.
4461 You need to reload Org or to restart Emacs after customizing this.")
4463 (defcustom org-emphasis-alist
4464 '(("*" bold)
4465 ("/" italic)
4466 ("_" underline)
4467 ("=" org-verbatim verbatim)
4468 ("~" org-code verbatim)
4469 ("+" (:strike-through t)))
4470 "Alist of characters and faces to emphasize text.
4471 Text starting and ending with a special character will be emphasized,
4472 for example *bold*, _underlined_ and /italic/. This variable sets the
4473 marker characters and the face to be used by font-lock for highlighting
4474 in Org-mode Emacs buffers.
4476 You need to reload Org or to restart Emacs after customizing this."
4477 :group 'org-appearance
4478 :set 'org-set-emph-re
4479 :version "24.4"
4480 :package-version '(Org . "8.0")
4481 :type '(repeat
4482 (list
4483 (string :tag "Marker character")
4484 (choice
4485 (face :tag "Font-lock-face")
4486 (plist :tag "Face property list"))
4487 (option (const verbatim)))))
4489 (defvar org-protecting-blocks '("src" "example" "export")
4490 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4491 This is needed for font-lock setup.")
4493 ;;; Functions and variables from their packages
4494 ;; Declared here to avoid compiler warnings
4495 (defvar mark-active)
4497 ;; Various packages
4498 (declare-function calc-eval "calc" (str &optional separator &rest args))
4499 (declare-function calendar-forward-day "cal-move" (arg))
4500 (declare-function calendar-goto-date "cal-move" (date))
4501 (declare-function calendar-goto-today "cal-move" ())
4502 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4503 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4504 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4505 (declare-function cdlatex-tab "ext:cdlatex" ())
4506 (declare-function dired-get-filename
4507 "dired"
4508 (&optional localp no-error-if-not-filep))
4509 (declare-function iswitchb-read-buffer
4510 "iswitchb"
4511 (prompt &optional
4512 default require-match _predicate start matches-set))
4513 (declare-function org-agenda-change-all-lines
4514 "org-agenda"
4515 (newhead hdmarker &optional fixface just-this))
4516 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4517 "org-agenda"
4518 (&optional end))
4519 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4520 (declare-function org-agenda-format-item
4521 "org-agenda"
4522 (extra txt &optional level category tags dotime
4523 remove-re habitp))
4524 (declare-function org-agenda-maybe-redo "org-agenda" ())
4525 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4526 (declare-function org-agenda-save-markers-for-cut-and-paste
4527 "org-agenda"
4528 (beg end))
4529 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4530 (declare-function org-agenda-skip "org-agenda" ())
4531 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4532 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4533 (declare-function org-indent-mode "org-indent" (&optional arg))
4534 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4535 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4536 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4537 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4538 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4539 (declare-function parse-time-string "parse-time" (string))
4540 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4541 (declare-function table--at-cell-p
4542 "table"
4543 (position &optional object at-column))
4545 (defvar align-mode-rules-list)
4546 (defvar calc-embedded-close-formula)
4547 (defvar calc-embedded-open-formula)
4548 (defvar calc-embedded-open-mode)
4549 (defvar font-lock-unfontify-region-function)
4550 (defvar iswitchb-temp-buflist)
4551 (defvar org-agenda-tags-todo-honor-ignore-options)
4552 (defvar remember-data-file)
4553 (defvar texmathp-why)
4555 ;;;###autoload
4556 (defun turn-on-orgtbl ()
4557 "Unconditionally turn on `orgtbl-mode'."
4558 (require 'org-table)
4559 (orgtbl-mode 1))
4561 (defun org-at-table-p (&optional table-type)
4562 "Non-nil if the cursor is inside an Org table.
4563 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4564 If `org-enable-table-editor' is nil, return nil unconditionally."
4565 (and
4566 org-enable-table-editor
4567 (save-excursion
4568 (beginning-of-line)
4569 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4570 (or (not (derived-mode-p 'org-mode))
4571 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4572 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4573 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4575 (defun org-at-table.el-p ()
4576 "Non-nil when point is at a table.el table."
4577 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4578 (let ((element (org-element-at-point)))
4579 (and (eq (org-element-type element) 'table)
4580 (eq (org-element-property :type element) 'table.el)))))
4582 (defun org-table-recognize-table.el ()
4583 "If there is a table.el table nearby, recognize it and move into it."
4584 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4585 (beginning-of-line)
4586 (unless (or (looking-at org-table-dataline-regexp)
4587 (not (looking-at org-table1-hline-regexp)))
4588 (forward-line)
4589 (when (looking-at org-table-any-border-regexp)
4590 (forward-line -2)))
4591 (if (re-search-forward "|" (org-table-end t) t)
4592 (progn
4593 (require 'table)
4594 (if (table--at-cell-p (point)) t
4595 (message "recognizing table.el table...")
4596 (table-recognize-table)
4597 (message "recognizing table.el table...done")))
4598 (error "This should not happen"))))
4599 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4600 (make-obsolete 'org-table-recognize-table.el
4601 "please notify the org mailing list if you use this function."
4602 "Org 9.0")
4604 (defun org-at-table-hline-p ()
4605 "Non-nil when point is inside a hline in a table.
4606 Assume point is already in a table. If `org-enable-table-editor'
4607 is nil, return nil unconditionally."
4608 (and org-enable-table-editor
4609 (save-excursion
4610 (beginning-of-line)
4611 (looking-at org-table-hline-regexp))))
4613 (defun org-table-map-tables (function &optional quietly)
4614 "Apply FUNCTION to the start of all tables in the buffer."
4615 (save-excursion
4616 (save-restriction
4617 (widen)
4618 (goto-char (point-min))
4619 (while (re-search-forward org-table-any-line-regexp nil t)
4620 (unless quietly
4621 (message "Mapping tables: %d%%"
4622 (floor (* 100.0 (point)) (buffer-size))))
4623 (beginning-of-line 1)
4624 (when (and (looking-at org-table-line-regexp)
4625 ;; Exclude tables in src/example/verbatim/clocktable blocks
4626 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4627 (save-excursion (funcall function))
4628 (or (looking-at org-table-line-regexp)
4629 (forward-char 1)))
4630 (re-search-forward org-table-any-border-regexp nil 1))))
4631 (unless quietly (message "Mapping tables: done")))
4633 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4634 (declare-function org-clock-update-mode-line "org-clock" ())
4635 (declare-function org-resolve-clocks "org-clock"
4636 (&optional also-non-dangling-p prompt last-valid))
4638 (defun org-at-TBLFM-p (&optional pos)
4639 "Non-nil when point (or POS) is in #+TBLFM line."
4640 (save-excursion
4641 (goto-char (or pos (point)))
4642 (beginning-of-line)
4643 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4644 (eq (org-element-type (org-element-at-point)) 'table))))
4646 (defvar org-clock-start-time)
4647 (defvar org-clock-marker (make-marker)
4648 "Marker recording the last clock-in.")
4649 (defvar org-clock-hd-marker (make-marker)
4650 "Marker recording the last clock-in, but the headline position.")
4651 (defvar org-clock-heading ""
4652 "The heading of the current clock entry.")
4653 (defun org-clock-is-active ()
4654 "Return the buffer where the clock is currently running.
4655 Return nil if no clock is running."
4656 (marker-buffer org-clock-marker))
4658 (defun org-check-running-clock ()
4659 "Check if the current buffer contains the running clock.
4660 If yes, offer to stop it and to save the buffer with the changes."
4661 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4662 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4663 (buffer-name))))
4664 (org-clock-out)
4665 (when (y-or-n-p "Save changed buffer?")
4666 (save-buffer))))
4668 (defun org-clocktable-try-shift (dir n)
4669 "Check if this line starts a clock table, if yes, shift the time block."
4670 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4671 (org-clocktable-shift dir n)))
4673 ;;;###autoload
4674 (defun org-clock-persistence-insinuate ()
4675 "Set up hooks for clock persistence."
4676 (require 'org-clock)
4677 (add-hook 'org-mode-hook 'org-clock-load)
4678 (add-hook 'kill-emacs-hook 'org-clock-save))
4680 (defgroup org-archive nil
4681 "Options concerning archiving in Org-mode."
4682 :tag "Org Archive"
4683 :group 'org-structure)
4685 (defcustom org-archive-location "%s_archive::"
4686 "The location where subtrees should be archived.
4688 The value of this variable is a string, consisting of two parts,
4689 separated by a double-colon. The first part is a filename and
4690 the second part is a headline.
4692 When the filename is omitted, archiving happens in the same file.
4693 %s in the filename will be replaced by the current file
4694 name (without the directory part). Archiving to a different file
4695 is useful to keep archived entries from contributing to the
4696 Org-mode Agenda.
4698 The archived entries will be filed as subtrees of the specified
4699 headline. When the headline is omitted, the subtrees are simply
4700 filed away at the end of the file, as top-level entries. Also in
4701 the heading you can use %s to represent the file name, this can be
4702 useful when using the same archive for a number of different files.
4704 Here are a few examples:
4705 \"%s_archive::\"
4706 If the current file is Projects.org, archive in file
4707 Projects.org_archive, as top-level trees. This is the default.
4709 \"::* Archived Tasks\"
4710 Archive in the current file, under the top-level headline
4711 \"* Archived Tasks\".
4713 \"~/org/archive.org::\"
4714 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4716 \"~/org/archive.org::* From %s\"
4717 Archive in file ~/org/archive.org (absolute path), under headlines
4718 \"From FILENAME\" where file name is the current file name.
4720 \"~/org/datetree.org::datetree/* Finished Tasks\"
4721 The \"datetree/\" string is special, signifying to archive
4722 items to the datetree. Items are placed in either the CLOSED
4723 date of the item, or the current date if there is no CLOSED date.
4724 The heading will be a subentry to the current date. There doesn't
4725 need to be a heading, but there always needs to be a slash after
4726 datetree. For example, to store archived items directly in the
4727 datetree, use \"~/org/datetree.org::datetree/\".
4729 \"basement::** Finished Tasks\"
4730 Archive in file ./basement (relative path), as level 3 trees
4731 below the level 2 heading \"** Finished Tasks\".
4733 You may set this option on a per-file basis by adding to the buffer a
4734 line like
4736 #+ARCHIVE: basement::** Finished Tasks
4738 You may also define it locally for a subtree by setting an ARCHIVE property
4739 in the entry. If such a property is found in an entry, or anywhere up
4740 the hierarchy, it will be used."
4741 :group 'org-archive
4742 :type 'string)
4744 (defcustom org-agenda-skip-archived-trees t
4745 "Non-nil means the agenda will skip any items located in archived trees.
4746 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4747 variable is no longer recommended, you should leave it at the value t.
4748 Instead, use the key `v' to cycle the archives-mode in the agenda."
4749 :group 'org-archive
4750 :group 'org-agenda-skip
4751 :type 'boolean)
4753 (defcustom org-columns-skip-archived-trees t
4754 "Non-nil means ignore archived trees when creating column view."
4755 :group 'org-archive
4756 :group 'org-properties
4757 :type 'boolean)
4759 (defcustom org-cycle-open-archived-trees nil
4760 "Non-nil means `org-cycle' will open archived trees.
4761 An archived tree is a tree marked with the tag ARCHIVE.
4762 When nil, archived trees will stay folded. You can still open them with
4763 normal outline commands like `show-all', but not with the cycling commands."
4764 :group 'org-archive
4765 :group 'org-cycle
4766 :type 'boolean)
4768 (defcustom org-sparse-tree-open-archived-trees nil
4769 "Non-nil means sparse tree construction shows matches in archived trees.
4770 When nil, matches in these trees are highlighted, but the trees are kept in
4771 collapsed state."
4772 :group 'org-archive
4773 :group 'org-sparse-trees
4774 :type 'boolean)
4776 (defcustom org-sparse-tree-default-date-type nil
4777 "The default date type when building a sparse tree.
4778 When this is nil, a date is a scheduled or a deadline timestamp.
4779 Otherwise, these types are allowed:
4781 all: all timestamps
4782 active: only active timestamps (<...>)
4783 inactive: only inactive timestamps ([...])
4784 scheduled: only scheduled timestamps
4785 deadline: only deadline timestamps"
4786 :type '(choice (const :tag "Scheduled or deadline" nil)
4787 (const :tag "All timestamps" all)
4788 (const :tag "Only active timestamps" active)
4789 (const :tag "Only inactive timestamps" inactive)
4790 (const :tag "Only scheduled timestamps" scheduled)
4791 (const :tag "Only deadline timestamps" deadline)
4792 (const :tag "Only closed timestamps" closed))
4793 :version "25.1"
4794 :package-version '(Org . "8.3")
4795 :group 'org-sparse-trees)
4797 (defun org-cycle-hide-archived-subtrees (state)
4798 "Re-hide all archived subtrees after a visibility state change."
4799 (when (and (not org-cycle-open-archived-trees)
4800 (not (memq state '(overview folded))))
4801 (save-excursion
4802 (let* ((globalp (memq state '(contents all)))
4803 (beg (if globalp (point-min) (point)))
4804 (end (if globalp (point-max) (org-end-of-subtree t))))
4805 (org-hide-archived-subtrees beg end)
4806 (goto-char beg)
4807 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4808 (message "%s" (substitute-command-keys
4809 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4811 (defun org-force-cycle-archived ()
4812 "Cycle subtree even if it is archived."
4813 (interactive)
4814 (setq this-command 'org-cycle)
4815 (let ((org-cycle-open-archived-trees t))
4816 (call-interactively 'org-cycle)))
4818 (defun org-hide-archived-subtrees (beg end)
4819 "Re-hide all archived subtrees after a visibility state change."
4820 (org-with-wide-buffer
4821 (let ((case-fold-search nil)
4822 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4823 (goto-char beg)
4824 ;; Include headline point is currently on.
4825 (beginning-of-line)
4826 (while (and (< (point) end) (re-search-forward re end t))
4827 (when (member org-archive-tag (org-get-tags))
4828 (org-flag-subtree t)
4829 (org-end-of-subtree t))))))
4831 (declare-function outline-end-of-heading "outline" ())
4832 (declare-function outline-flag-region "outline" (from to flag))
4833 (defun org-flag-subtree (flag)
4834 (save-excursion
4835 (org-back-to-heading t)
4836 (outline-end-of-heading)
4837 (outline-flag-region (point)
4838 (progn (org-end-of-subtree t) (point))
4839 flag)))
4841 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4843 ;; Declare Column View Code
4845 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4846 (declare-function org-columns-compute "org-colview" (property))
4848 ;; Declare ID code
4850 (declare-function org-id-store-link "org-id")
4851 (declare-function org-id-locations-load "org-id")
4852 (declare-function org-id-locations-save "org-id")
4853 (defvar org-id-track-globally)
4855 ;;; Variables for pre-computed regular expressions, all buffer local
4857 (defvar-local org-todo-regexp nil
4858 "Matches any of the TODO state keywords.")
4859 (defvar-local org-not-done-regexp nil
4860 "Matches any of the TODO state keywords except the last one.")
4861 (defvar-local org-not-done-heading-regexp nil
4862 "Matches a TODO headline that is not done.")
4863 (defvar-local org-todo-line-regexp nil
4864 "Matches a headline and puts TODO state into group 2 if present.")
4865 (defvar-local org-complex-heading-regexp nil
4866 "Matches a headline and puts everything into groups:
4867 group 1: the stars
4868 group 2: The todo keyword, maybe
4869 group 3: Priority cookie
4870 group 4: True headline
4871 group 5: Tags")
4872 (defvar-local org-complex-heading-regexp-format nil
4873 "Printf format to make regexp to match an exact headline.
4874 This regexp will match the headline of any node which has the
4875 exact headline text that is put into the format, but may have any
4876 TODO state, priority and tags.")
4877 (defvar-local org-todo-line-tags-regexp nil
4878 "Matches a headline and puts TODO state into group 2 if present.
4879 Also put tags into group 4 if tags are present.")
4881 (defconst org-plain-time-of-day-regexp
4882 (concat
4883 "\\(\\<[012]?[0-9]"
4884 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4885 "\\(--?"
4886 "\\(\\<[012]?[0-9]"
4887 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4888 "\\)?")
4889 "Regular expression to match a plain time or time range.
4890 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4891 groups carry important information:
4892 0 the full match
4893 1 the first time, range or not
4894 8 the second time, if it is a range.")
4896 (defconst org-plain-time-extension-regexp
4897 (concat
4898 "\\(\\<[012]?[0-9]"
4899 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4900 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4901 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4902 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4903 groups carry important information:
4904 0 the full match
4905 7 hours of duration
4906 9 minutes of duration")
4908 (defconst org-stamp-time-of-day-regexp
4909 (concat
4910 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4911 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4912 "\\(--?"
4913 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4914 "Regular expression to match a timestamp time or time range.
4915 After a match, the following groups carry important information:
4916 0 the full match
4917 1 date plus weekday, for back referencing to make sure both times are on the same day
4918 2 the first time, range or not
4919 4 the second time, if it is a range.")
4921 (defconst org-startup-options
4922 '(("fold" org-startup-folded t)
4923 ("overview" org-startup-folded t)
4924 ("nofold" org-startup-folded nil)
4925 ("showall" org-startup-folded nil)
4926 ("showeverything" org-startup-folded showeverything)
4927 ("content" org-startup-folded content)
4928 ("indent" org-startup-indented t)
4929 ("noindent" org-startup-indented nil)
4930 ("hidestars" org-hide-leading-stars t)
4931 ("showstars" org-hide-leading-stars nil)
4932 ("odd" org-odd-levels-only t)
4933 ("oddeven" org-odd-levels-only nil)
4934 ("align" org-startup-align-all-tables t)
4935 ("noalign" org-startup-align-all-tables nil)
4936 ("inlineimages" org-startup-with-inline-images t)
4937 ("noinlineimages" org-startup-with-inline-images nil)
4938 ("latexpreview" org-startup-with-latex-preview t)
4939 ("nolatexpreview" org-startup-with-latex-preview nil)
4940 ("customtime" org-display-custom-times t)
4941 ("logdone" org-log-done time)
4942 ("lognotedone" org-log-done note)
4943 ("nologdone" org-log-done nil)
4944 ("lognoteclock-out" org-log-note-clock-out t)
4945 ("nolognoteclock-out" org-log-note-clock-out nil)
4946 ("logrepeat" org-log-repeat state)
4947 ("lognoterepeat" org-log-repeat note)
4948 ("logdrawer" org-log-into-drawer t)
4949 ("nologdrawer" org-log-into-drawer nil)
4950 ("logstatesreversed" org-log-states-order-reversed t)
4951 ("nologstatesreversed" org-log-states-order-reversed nil)
4952 ("nologrepeat" org-log-repeat nil)
4953 ("logreschedule" org-log-reschedule time)
4954 ("lognotereschedule" org-log-reschedule note)
4955 ("nologreschedule" org-log-reschedule nil)
4956 ("logredeadline" org-log-redeadline time)
4957 ("lognoteredeadline" org-log-redeadline note)
4958 ("nologredeadline" org-log-redeadline nil)
4959 ("logrefile" org-log-refile time)
4960 ("lognoterefile" org-log-refile note)
4961 ("nologrefile" org-log-refile nil)
4962 ("fninline" org-footnote-define-inline t)
4963 ("nofninline" org-footnote-define-inline nil)
4964 ("fnlocal" org-footnote-section nil)
4965 ("fnauto" org-footnote-auto-label t)
4966 ("fnprompt" org-footnote-auto-label nil)
4967 ("fnconfirm" org-footnote-auto-label confirm)
4968 ("fnplain" org-footnote-auto-label plain)
4969 ("fnadjust" org-footnote-auto-adjust t)
4970 ("nofnadjust" org-footnote-auto-adjust nil)
4971 ("constcgs" constants-unit-system cgs)
4972 ("constSI" constants-unit-system SI)
4973 ("noptag" org-tag-persistent-alist nil)
4974 ("hideblocks" org-hide-block-startup t)
4975 ("nohideblocks" org-hide-block-startup nil)
4976 ("beamer" org-startup-with-beamer-mode t)
4977 ("entitiespretty" org-pretty-entities t)
4978 ("entitiesplain" org-pretty-entities nil))
4979 "Variable associated with STARTUP options for org-mode.
4980 Each element is a list of three items: the startup options (as written
4981 in the #+STARTUP line), the corresponding variable, and the value to set
4982 this variable to if the option is found. An optional forth element PUSH
4983 means to push this value onto the list in the variable.")
4985 (defcustom org-group-tags t
4986 "When non-nil (the default), use group tags.
4987 This can be turned on/off through `org-toggle-tags-groups'."
4988 :group 'org-tags
4989 :group 'org-startup
4990 :type 'boolean)
4992 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4994 (defun org-toggle-tags-groups ()
4995 "Toggle support for group tags.
4996 Support for group tags is controlled by the option
4997 `org-group-tags', which is non-nil by default."
4998 (interactive)
4999 (setq org-group-tags (not org-group-tags))
5000 (cond ((and (derived-mode-p 'org-agenda-mode)
5001 org-group-tags)
5002 (org-agenda-redo))
5003 ((derived-mode-p 'org-mode)
5004 (let ((org-inhibit-startup t)) (org-mode))))
5005 (message "Groups tags support has been turned %s"
5006 (if org-group-tags "on" "off")))
5008 (defun org-set-regexps-and-options (&optional tags-only)
5009 "Precompute regular expressions used in the current buffer.
5010 When optional argument TAGS-ONLY is non-nil, only compute tags
5011 related expressions."
5012 (when (derived-mode-p 'org-mode)
5013 (let ((alist (org--setup-collect-keywords
5014 (org-make-options-regexp
5015 (append '("FILETAGS" "TAGS" "SETUPFILE")
5016 (and (not tags-only)
5017 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5018 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5019 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5020 ;; Startup options. Get this early since it does change
5021 ;; behavior for other options (e.g., tags).
5022 (let ((startup (cdr (assq 'startup alist))))
5023 (dolist (option startup)
5024 (let ((entry (assoc-string option org-startup-options t)))
5025 (when entry
5026 (let ((var (nth 1 entry))
5027 (val (nth 2 entry)))
5028 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5029 (unless (listp (symbol-value var))
5030 (set (make-local-variable var) nil))
5031 (add-to-list var val)))))))
5032 (setq-local org-file-tags
5033 (mapcar #'org-add-prop-inherited
5034 (cdr (assq 'filetags alist))))
5035 (setq org-current-tag-alist
5036 (append org-tag-persistent-alist
5037 (let ((tags (cdr (assq 'tags alist))))
5038 (if tags (org-tag-string-to-alist tags)
5039 org-tag-alist))))
5040 (setq org-tag-groups-alist
5041 (org-tag-alist-to-groups org-current-tag-alist))
5042 (unless tags-only
5043 ;; File properties.
5044 (setq-local org-file-properties (cdr (assq 'property alist)))
5045 ;; Archive location.
5046 (let ((archive (cdr (assq 'archive alist))))
5047 (when archive (setq-local org-archive-location archive)))
5048 ;; Category.
5049 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5050 (when cat
5051 (setq-local org-category (intern cat))
5052 (setq-local org-file-properties
5053 (org--update-property-plist
5054 "CATEGORY" cat org-file-properties))))
5055 ;; Columns.
5056 (let ((column (cdr (assq 'columns alist))))
5057 (when column (setq-local org-columns-default-format column)))
5058 ;; Constants.
5059 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5060 ;; Link abbreviations.
5061 (let ((links (cdr (assq 'link alist))))
5062 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5063 ;; Priorities.
5064 (let ((priorities (cdr (assq 'priorities alist))))
5065 (when priorities
5066 (setq-local org-highest-priority (nth 0 priorities))
5067 (setq-local org-lowest-priority (nth 1 priorities))
5068 (setq-local org-default-priority (nth 2 priorities))))
5069 ;; Scripts.
5070 (let ((scripts (assq 'scripts alist)))
5071 (when scripts
5072 (setq-local org-use-sub-superscripts (cdr scripts))))
5073 ;; TODO keywords.
5074 (setq-local org-todo-kwd-alist nil)
5075 (setq-local org-todo-key-alist nil)
5076 (setq-local org-todo-key-trigger nil)
5077 (setq-local org-todo-keywords-1 nil)
5078 (setq-local org-done-keywords nil)
5079 (setq-local org-todo-heads nil)
5080 (setq-local org-todo-sets nil)
5081 (setq-local org-todo-log-states nil)
5082 (let ((todo-sequences
5083 (or (nreverse (cdr (assq 'todo alist)))
5084 (let ((d (default-value 'org-todo-keywords)))
5085 (if (not (stringp (car d))) d
5086 ;; XXX: Backward compatibility code.
5087 (list (cons org-todo-interpretation d)))))))
5088 (dolist (sequence todo-sequences)
5089 (let* ((sequence (or (run-hook-with-args-until-success
5090 'org-todo-setup-filter-hook sequence)
5091 sequence))
5092 (sequence-type (car sequence))
5093 (keywords (cdr sequence))
5094 (sep (member "|" keywords))
5095 names alist)
5096 (dolist (k (remove "|" keywords))
5097 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5099 (error "Invalid TODO keyword %s" k))
5100 (let ((name (match-string 1 k))
5101 (key (match-string 2 k))
5102 (log (org-extract-log-state-settings k)))
5103 (push name names)
5104 (push (cons name (and key (string-to-char key))) alist)
5105 (when log (push log org-todo-log-states))))
5106 (let* ((names (nreverse names))
5107 (done (if sep (org-remove-keyword-keys (cdr sep))
5108 (last names)))
5109 (head (car names))
5110 (tail (list sequence-type head (car done) (org-last done))))
5111 (add-to-list 'org-todo-heads head 'append)
5112 (push names org-todo-sets)
5113 (setq org-done-keywords (append org-done-keywords done nil))
5114 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5115 (setq org-todo-key-alist
5116 (append org-todo-key-alist
5117 (and alist
5118 (append '((:startgroup))
5119 (nreverse alist)
5120 '((:endgroup))))))
5121 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5122 (setq org-todo-sets (nreverse org-todo-sets)
5123 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5124 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5125 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5126 ;; Compute the regular expressions and other local variables.
5127 ;; Using `org-outline-regexp-bol' would complicate them much,
5128 ;; because of the fixed white space at the end of that string.
5129 (unless org-done-keywords
5130 (setq org-done-keywords
5131 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5132 (setq org-not-done-keywords
5133 (org-delete-all org-done-keywords
5134 (copy-sequence org-todo-keywords-1))
5135 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5136 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5137 org-not-done-heading-regexp
5138 (format org-heading-keyword-regexp-format org-not-done-regexp)
5139 org-todo-line-regexp
5140 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5141 org-complex-heading-regexp
5142 (concat "^\\(\\*+\\)"
5143 "\\(?: +" org-todo-regexp "\\)?"
5144 "\\(?: +\\(\\[#.\\]\\)\\)?"
5145 "\\(?: +\\(.*?\\)\\)??"
5146 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5147 "[ \t]*$")
5148 org-complex-heading-regexp-format
5149 (concat "^\\(\\*+\\)"
5150 "\\(?: +" org-todo-regexp "\\)?"
5151 "\\(?: +\\(\\[#.\\]\\)\\)?"
5152 "\\(?: +"
5153 ;; Stats cookies can be stuck to body.
5154 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5155 "\\(%s\\)"
5156 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5157 "\\)"
5158 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5159 "[ \t]*$")
5160 org-todo-line-tags-regexp
5161 (concat "^\\(\\*+\\)"
5162 "\\(?: +" org-todo-regexp "\\)?"
5163 "\\(?: +\\(.*?\\)\\)??"
5164 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5165 "[ \t]*$"))
5166 (org-compute-latex-and-related-regexp)))))
5168 (defun org--setup-collect-keywords (regexp &optional files alist)
5169 "Return setup keywords values as an alist.
5171 REGEXP matches a subset of setup keywords. FILES is a list of
5172 file names already visited. It is used to avoid circular setup
5173 files. ALIST, when non-nil, is the alist computed so far.
5175 Return value contains the following keys: `archive', `category',
5176 `columns', `constants', `filetags', `link', `priorities',
5177 `property', `scripts', `startup', `tags' and `todo'."
5178 (org-with-wide-buffer
5179 (goto-char (point-min))
5180 (let ((case-fold-search t))
5181 (while (re-search-forward regexp nil t)
5182 (let ((element (org-element-at-point)))
5183 (when (eq (org-element-type element) 'keyword)
5184 (let ((key (org-element-property :key element))
5185 (value (org-element-property :value element)))
5186 (cond
5187 ((equal key "ARCHIVE")
5188 (when (org-string-nw-p value)
5189 (push (cons 'archive value) alist)))
5190 ((equal key "CATEGORY") (push (cons 'category value) alist))
5191 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5192 ((equal key "CONSTANTS")
5193 (let* ((constants (assq 'constants alist))
5194 (store (cdr constants)))
5195 (dolist (pair (org-split-string value))
5196 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5197 pair)
5198 (let* ((name (match-string 1 pair))
5199 (value (match-string 2 pair))
5200 (old (assoc name store)))
5201 (if old (setcdr old value)
5202 (push (cons name value) store)))))
5203 (if constants (setcdr constants store)
5204 (push (cons 'constants store) alist))))
5205 ((equal key "FILETAGS")
5206 (when (org-string-nw-p value)
5207 (let ((old (assq 'filetags alist))
5208 (new (apply #'nconc
5209 (mapcar (lambda (x) (org-split-string x ":"))
5210 (org-split-string value)))))
5211 (if old (setcdr old (append new (cdr old)))
5212 (push (cons 'filetags new) alist)))))
5213 ((equal key "LINK")
5214 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5215 (let ((links (assq 'link alist))
5216 (pair (cons (match-string-no-properties 1 value)
5217 (match-string-no-properties 2 value))))
5218 (if links (push pair (cdr links))
5219 (push (list 'link pair) alist)))))
5220 ((equal key "OPTIONS")
5221 (when (and (org-string-nw-p value)
5222 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5223 (push (cons 'scripts (read (match-string 1 value))) alist)))
5224 ((equal key "PRIORITIES")
5225 (push (cons 'priorities
5226 (let ((prio (org-split-string value)))
5227 (if (< (length prio) 3) '(?A ?C ?B)
5228 (mapcar #'string-to-char prio))))
5229 alist))
5230 ((equal key "PROPERTY")
5231 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5232 (let* ((property (assq 'property alist))
5233 (value (org--update-property-plist
5234 (match-string-no-properties 1 value)
5235 (match-string-no-properties 2 value)
5236 (cdr property))))
5237 (if property (setcdr property value)
5238 (push (cons 'property value) alist)))))
5239 ((equal key "STARTUP")
5240 (let ((startup (assq 'startup alist)))
5241 (if startup
5242 (setcdr startup
5243 (append (cdr startup) (org-split-string value)))
5244 (push (cons 'startup (org-split-string value)) alist))))
5245 ((equal key "TAGS")
5246 (let ((tag-cell (assq 'tags alist)))
5247 (if tag-cell
5248 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5249 (push (cons 'tags value) alist))))
5250 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5251 (let ((todo (assq 'todo alist))
5252 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5253 (org-split-string value))))
5254 (if todo (push value (cdr todo))
5255 (push (list 'todo value) alist))))
5256 ((equal key "SETUPFILE")
5257 (unless buffer-read-only ; Do not check in Gnus messages.
5258 (let ((f (and (org-string-nw-p value)
5259 (expand-file-name
5260 (org-remove-double-quotes value)))))
5261 (when (and f (file-readable-p f) (not (member f files)))
5262 (with-temp-buffer
5263 (setq default-directory (file-name-directory f))
5264 (insert-file-contents f)
5265 (setq alist
5266 ;; Fake Org mode to benefit from cache
5267 ;; without recurring needlessly.
5268 (let ((major-mode 'org-mode))
5269 (org--setup-collect-keywords
5270 regexp (cons f files) alist)))))))))))))))
5271 alist)
5273 (defun org-tag-string-to-alist (s)
5274 "Return tag alist associated to string S.
5275 S is a value for TAGS keyword or produced with
5276 `org-tag-alist-to-string'. Return value is an alist suitable for
5277 `org-tag-alist' or `org-tag-persistent-alist'."
5278 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5279 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5280 "\\|{.+?}\\)" ; regular expression
5281 "\\(?:(\\(.\\))\\)?\\'"))
5282 alist group-flag)
5283 (dolist (tokens lines (cdr (nreverse alist)))
5284 (push '(:newline) alist)
5285 (while tokens
5286 (let ((token (pop tokens)))
5287 (pcase token
5288 ("{"
5289 (push '(:startgroup) alist)
5290 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5291 ("}"
5292 (push '(:endgroup) alist)
5293 (setq group-flag nil))
5294 ("["
5295 (push '(:startgrouptag) alist)
5296 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5297 ("]"
5298 (push '(:endgrouptag) alist)
5299 (setq group-flag nil))
5300 (":"
5301 (push '(:grouptags) alist))
5302 ((guard (string-match tag-re token))
5303 (let ((tag (match-string 1 token))
5304 (key (and (match-beginning 2)
5305 (string-to-char (match-string 2 token)))))
5306 ;; Push all tags in groups, no matter if they already
5307 ;; appear somewhere else in the list.
5308 (when (or group-flag (not (assoc tag alist)))
5309 (push (cons tag key) alist))))))))))
5311 (defun org-tag-alist-to-string (alist &optional skip-key)
5312 "Return tag string associated to ALIST.
5314 ALIST is an alist, as defined in `org-tag-alist' or
5315 `org-tag-persistent-alist', or produced with
5316 `org-tag-string-to-alist'.
5318 Return value is a string suitable as a value for \"TAGS\"
5319 keyword.
5321 When optional argument SKIP-KEY is non-nil, skip selection keys
5322 next to tags."
5323 (mapconcat (lambda (token)
5324 (pcase token
5325 (`(:startgroup) "{")
5326 (`(:endgroup) "}")
5327 (`(:startgrouptag) "[")
5328 (`(:endgrouptag) "]")
5329 (`(:grouptags) ":")
5330 (`(:newline) "\\n")
5331 ((and
5332 (guard (not skip-key))
5333 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5334 (format "%s(%c)" tag key))
5335 (`(,(and tag (pred stringp)) . ,_) tag)
5336 (_ (user-error "Invalid tag token: %S" token))))
5337 alist
5338 " "))
5340 (defun org-tag-alist-to-groups (alist)
5341 "Return group alist from tag ALIST.
5342 ALIST is an alist, as defined in `org-tag-alist' or
5343 `org-tag-persistent-alist', or produced with
5344 `org-tag-string-to-alist'. Return value is an alist following
5345 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5346 a string, summarizing TAGS, as a list of strings."
5347 (let (groups group-status current-group)
5348 (dolist (token alist (nreverse groups))
5349 (pcase token
5350 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5351 (`(,(or :endgroup :endgrouptag))
5352 (when (eq group-status 'append)
5353 (push (nreverse current-group) groups))
5354 (setq group-status nil))
5355 (`(:grouptags) (setq group-status 'append))
5356 ((and `(,tag . ,_) (guard group-status))
5357 (if (eq group-status 'append) (push tag current-group)
5358 (setq current-group (list tag))))
5359 (_ nil)))))
5361 (defun org-file-contents (file &optional noerror)
5362 "Return the contents of FILE, as a string."
5363 (if (and file (file-readable-p file))
5364 (with-temp-buffer
5365 (insert-file-contents file)
5366 (buffer-string))
5367 (funcall (if noerror 'message 'error)
5368 "Cannot read file \"%s\"%s"
5369 file
5370 (let ((from (buffer-file-name (buffer-base-buffer))))
5371 (if from (concat " (referenced in file \"" from "\")") "")))))
5373 (defun org-extract-log-state-settings (x)
5374 "Extract the log state setting from a TODO keyword string.
5375 This will extract info from a string like \"WAIT(w@/!)\"."
5376 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5377 (let ((kw (match-string 1 x))
5378 (log1 (and (match-end 3) (match-string 3 x)))
5379 (log2 (and (match-end 4) (match-string 4 x))))
5380 (and (or log1 log2)
5381 (list kw
5382 (and log1 (if (equal log1 "!") 'time 'note))
5383 (and log2 (if (equal log2 "!") 'time 'note)))))))
5385 (defun org-remove-keyword-keys (list)
5386 "Remove a pair of parenthesis at the end of each string in LIST."
5387 (mapcar (lambda (x)
5388 (if (string-match "(.*)$" x)
5389 (substring x 0 (match-beginning 0))
5391 list))
5393 (defun org-assign-fast-keys (alist)
5394 "Assign fast keys to a keyword-key alist.
5395 Respect keys that are already there."
5396 (let (new e (alt ?0))
5397 (while (setq e (pop alist))
5398 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5399 (cdr e)) ;; Key already assigned.
5400 (push e new)
5401 (let ((clist (string-to-list (downcase (car e))))
5402 (used (append new alist)))
5403 (when (= (car clist) ?@)
5404 (pop clist))
5405 (while (and clist (rassoc (car clist) used))
5406 (pop clist))
5407 (unless clist
5408 (while (rassoc alt used)
5409 (cl-incf alt)))
5410 (push (cons (car e) (or (car clist) alt)) new))))
5411 (nreverse new)))
5413 ;;; Some variables used in various places
5415 (defvar org-window-configuration nil
5416 "Used in various places to store a window configuration.")
5417 (defvar org-selected-window nil
5418 "Used in various places to store a window configuration.")
5419 (defvar org-finish-function nil
5420 "Function to be called when `C-c C-c' is used.
5421 This is for getting out of special buffers like capture.")
5422 (defvar org-last-state)
5424 ;; Defined somewhere in this file, but used before definition.
5425 (defvar org-entities) ;; defined in org-entities.el
5426 (defvar org-struct-menu)
5427 (defvar org-org-menu)
5428 (defvar org-tbl-menu)
5430 ;;;; Define the Org-mode
5432 ;; We use a before-change function to check if a table might need
5433 ;; an update.
5434 (defvar org-table-may-need-update t
5435 "Indicates that a table might need an update.
5436 This variable is set by `org-before-change-function'.
5437 `org-table-align' sets it back to nil.")
5438 (defun org-before-change-function (_beg _end)
5439 "Every change indicates that a table might need an update."
5440 (setq org-table-may-need-update t))
5441 (defvar org-mode-map)
5442 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5443 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5444 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5445 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5446 (defvar org-table-buffer-is-an nil)
5448 (defvar bidi-paragraph-direction)
5449 (defvar buffer-face-mode-face)
5451 (require 'outline)
5452 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5453 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5455 ;; Other stuff we need.
5456 (require 'time-date)
5457 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5458 (require 'easymenu)
5459 (autoload 'easy-menu-add "easymenu")
5460 (require 'overlay)
5462 ;; (require 'org-macs) moved higher up in the file before it is first used
5463 (require 'org-entities)
5464 ;; (require 'org-compat) moved higher up in the file before it is first used
5465 (require 'org-faces)
5466 (require 'org-list)
5467 (require 'org-pcomplete)
5468 (require 'org-src)
5469 (require 'org-footnote)
5470 (require 'org-macro)
5472 ;; babel
5473 (require 'ob)
5475 ;;;###autoload
5476 (define-derived-mode org-mode outline-mode "Org"
5477 "Outline-based notes management and organizer, alias
5478 \"Carsten's outline-mode for keeping track of everything.\"
5480 Org-mode develops organizational tasks around a NOTES file which
5481 contains information about projects as plain text. Org-mode is
5482 implemented on top of outline-mode, which is ideal to keep the content
5483 of large files well structured. It supports ToDo items, deadlines and
5484 time stamps, which magically appear in the diary listing of the Emacs
5485 calendar. Tables are easily created with a built-in table editor.
5486 Plain text URL-like links connect to websites, emails (VM), Usenet
5487 messages (Gnus), BBDB entries, and any files related to the project.
5488 For printing and sharing of notes, an Org-mode file (or a part of it)
5489 can be exported as a structured ASCII or HTML file.
5491 The following commands are available:
5493 \\{org-mode-map}"
5495 ;; Get rid of Outline menus, they are not needed
5496 ;; Need to do this here because define-derived-mode sets up
5497 ;; the keymap so late. Still, it is a waste to call this each time
5498 ;; we switch another buffer into Org mode.
5499 (define-key org-mode-map [menu-bar headings] 'undefined)
5500 (define-key org-mode-map [menu-bar hide] 'undefined)
5501 (define-key org-mode-map [menu-bar show] 'undefined)
5503 (org-load-modules-maybe)
5504 (org-install-agenda-files-menu)
5505 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5506 (add-to-invisibility-spec '(org-cwidth))
5507 (add-to-invisibility-spec '(org-hide-block . t))
5508 (setq-local outline-regexp org-outline-regexp)
5509 (setq-local outline-level 'org-outline-level)
5510 (setq bidi-paragraph-direction 'left-to-right)
5511 (when (and org-ellipsis
5512 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5513 (fboundp 'make-glyph-code))
5514 (unless org-display-table
5515 (setq org-display-table (make-display-table)))
5516 (set-display-table-slot
5517 org-display-table 4
5518 (vconcat (mapcar
5519 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5520 org-ellipsis)))
5521 (if (stringp org-ellipsis) org-ellipsis "..."))))
5522 (setq buffer-display-table org-display-table))
5523 (org-set-regexps-and-options)
5524 (org-set-font-lock-defaults)
5525 (when (and org-tag-faces (not org-tags-special-faces-re))
5526 ;; tag faces set outside customize.... force initialization.
5527 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5528 ;; Calc embedded
5529 (setq-local calc-embedded-open-mode "# ")
5530 ;; Modify a few syntax entries
5531 (modify-syntax-entry ?@ "w")
5532 (modify-syntax-entry ?\" "\"")
5533 (modify-syntax-entry ?\\ "_")
5534 (modify-syntax-entry ?~ "_")
5535 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5536 ;; Activate before-change-function
5537 (setq-local org-table-may-need-update t)
5538 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5539 ;; Check for running clock before killing a buffer
5540 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5541 ;; Initialize macros templates.
5542 (org-macro-initialize-templates)
5543 ;; Initialize radio targets.
5544 (org-update-radio-target-regexp)
5545 ;; Indentation.
5546 (setq-local indent-line-function 'org-indent-line)
5547 (setq-local indent-region-function 'org-indent-region)
5548 ;; Filling and auto-filling.
5549 (org-setup-filling)
5550 ;; Comments.
5551 (org-setup-comments-handling)
5552 ;; Initialize cache.
5553 (org-element-cache-reset)
5554 ;; Beginning/end of defun
5555 (setq-local beginning-of-defun-function 'org-backward-element)
5556 (setq-local end-of-defun-function
5557 (lambda ()
5558 (if (not (org-at-heading-p))
5559 (org-forward-element)
5560 (org-forward-element)
5561 (forward-char -1))))
5562 ;; Next error for sparse trees
5563 (setq-local next-error-function 'org-occur-next-match)
5564 ;; Make sure dependence stuff works reliably, even for users who set it
5565 ;; too late :-(
5566 (if org-enforce-todo-dependencies
5567 (add-hook 'org-blocker-hook
5568 'org-block-todo-from-children-or-siblings-or-parent)
5569 (remove-hook 'org-blocker-hook
5570 'org-block-todo-from-children-or-siblings-or-parent))
5571 (if org-enforce-todo-checkbox-dependencies
5572 (add-hook 'org-blocker-hook
5573 'org-block-todo-from-checkboxes)
5574 (remove-hook 'org-blocker-hook
5575 'org-block-todo-from-checkboxes))
5577 ;; Align options lines
5578 (setq-local
5579 align-mode-rules-list
5580 '((org-in-buffer-settings
5581 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5582 (modes . '(org-mode)))))
5584 ;; Imenu
5585 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5587 ;; Make isearch reveal context
5588 (setq-local outline-isearch-open-invisible-function
5589 (lambda (&rest _) (org-show-context 'isearch)))
5591 ;; Setup the pcomplete hooks
5592 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5593 (setq-local pcomplete-command-name-function 'org-command-at-point)
5594 (setq-local pcomplete-default-completion-function 'ignore)
5595 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5596 (setq-local pcomplete-termination-string "")
5597 (setq-local buffer-face-mode-face 'org-default)
5599 ;; If empty file that did not turn on Org mode automatically, make
5600 ;; it to.
5601 (when (and org-insert-mode-line-in-empty-file
5602 (org-called-interactively-p 'any)
5603 (= (point-min) (point-max)))
5604 (insert "# -*- mode: org -*-\n\n"))
5605 (unless org-inhibit-startup
5606 (org-unmodified
5607 (when org-startup-with-beamer-mode (org-beamer-mode))
5608 (when org-startup-align-all-tables
5609 (org-table-map-tables #'org-table-align t))
5610 (when org-startup-with-inline-images (org-display-inline-images))
5611 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5612 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5613 (when org-startup-truncated (setq truncate-lines t))
5614 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5615 (org-refresh-effort-properties)))
5616 ;; Try to set `org-hide' face correctly.
5617 (let ((foreground (org-find-invisible-foreground)))
5618 (when foreground
5619 (set-face-foreground 'org-hide foreground))))
5621 ;; Update `customize-package-emacs-version-alist'
5622 (add-to-list 'customize-package-emacs-version-alist
5623 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5624 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5625 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5627 (defvar org-mode-transpose-word-syntax-table
5628 (let ((st (make-syntax-table text-mode-syntax-table)))
5629 (dolist (c org-emphasis-alist st)
5630 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5632 (when (fboundp 'abbrev-table-put)
5633 (abbrev-table-put org-mode-abbrev-table
5634 :parents (list text-mode-abbrev-table)))
5636 (defun org-find-invisible-foreground ()
5637 (let ((candidates (remove
5638 "unspecified-bg"
5639 (nconc
5640 (list (face-background 'default)
5641 (face-background 'org-default))
5642 (mapcar
5643 (lambda (alist)
5644 (when (boundp alist)
5645 (cdr (assoc 'background-color (symbol-value alist)))))
5646 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5647 (list (face-foreground 'org-hide))))))
5648 (car (remove nil candidates))))
5650 (defun org-current-time (&optional rounding-minutes past)
5651 "Current time, possibly rounded to ROUNDING-MINUTES.
5652 When ROUNDING-MINUTES is not an integer, fall back on the car of
5653 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5654 the rounding returns a past time."
5655 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5656 (car org-time-stamp-rounding-minutes)))
5657 (time (decode-time)) res)
5658 (if (< r 1)
5659 (current-time)
5660 (setq res
5661 (apply 'encode-time
5662 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5663 (nthcdr 2 time))))
5664 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5665 (seconds-to-time (- (float-time res) (* r 60)))
5666 res))))
5668 (defun org-today ()
5669 "Return today date, considering `org-extend-today-until'."
5670 (time-to-days
5671 (time-subtract (current-time)
5672 (list 0 (* 3600 org-extend-today-until) 0))))
5674 ;;;; Font-Lock stuff, including the activators
5676 (defvar org-mouse-map (make-sparse-keymap))
5677 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5678 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5679 (when org-mouse-1-follows-link
5680 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5681 (when org-tab-follows-link
5682 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5683 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5685 (require 'font-lock)
5687 (defconst org-non-link-chars "]\t\n\r<>")
5688 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5689 "file+sys" "news" "shell" "elisp" "doi" "message"
5690 "help"))
5691 (defvar org-link-types-re nil
5692 "Matches a link that has a url-like prefix like \"http:\"")
5693 (defvar org-link-re-with-space nil
5694 "Matches a link with spaces, optional angular brackets around it.")
5695 (defvar org-link-re-with-space2 nil
5696 "Matches a link with spaces, optional angular brackets around it.")
5697 (defvar org-link-re-with-space3 nil
5698 "Matches a link with spaces, only for internal part in bracket links.")
5699 (defvar org-angle-link-re nil
5700 "Matches link with angular brackets, spaces are allowed.")
5701 (defvar org-plain-link-re nil
5702 "Matches plain link, without spaces.")
5703 (defvar org-bracket-link-regexp nil
5704 "Matches a link in double brackets.")
5705 (defvar org-bracket-link-analytic-regexp nil
5706 "Regular expression used to analyze links.
5707 Here is what the match groups contain after a match:
5708 1: http:
5709 2: http
5710 3: path
5711 4: [desc]
5712 5: desc")
5713 (defvar org-bracket-link-analytic-regexp++ nil
5714 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5715 (defvar org-any-link-re nil
5716 "Regular expression matching any link.")
5718 (defconst org-match-sexp-depth 3
5719 "Number of stacked braces for sub/superscript matching.")
5721 (defun org-create-multibrace-regexp (left right n)
5722 "Create a regular expression which will match a balanced sexp.
5723 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5724 as single character strings.
5725 The regexp returned will match the entire expression including the
5726 delimiters. It will also define a single group which contains the
5727 match except for the outermost delimiters. The maximum depth of
5728 stacked delimiters is N. Escaping delimiters is not possible."
5729 (let* ((nothing (concat "[^" left right "]*?"))
5730 (or "\\|")
5731 (re nothing)
5732 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5733 (while (> n 1)
5734 (setq n (1- n)
5735 re (concat re or next)
5736 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5737 (concat left "\\(" re "\\)" right)))
5739 (defconst org-match-substring-regexp
5740 (concat
5741 "\\(\\S-\\)\\([_^]\\)\\("
5742 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5743 "\\|"
5744 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5745 "\\|"
5746 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5747 "The regular expression matching a sub- or superscript.")
5749 (defconst org-match-substring-with-braces-regexp
5750 (concat
5751 "\\(\\S-\\)\\([_^]\\)"
5752 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5753 "The regular expression matching a sub- or superscript, forcing braces.")
5755 (defun org-make-link-regexps ()
5756 "Update the link regular expressions.
5757 This should be called after the variable `org-link-types' has changed."
5758 (let ((types-re (regexp-opt org-link-types t)))
5759 (setq org-link-types-re
5760 (concat "\\`" types-re ":")
5761 org-link-re-with-space
5762 (concat "<?" types-re ":"
5763 "\\([^" org-non-link-chars " ]"
5764 "[^" org-non-link-chars "]*"
5765 "[^" org-non-link-chars " ]\\)>?")
5766 org-link-re-with-space2
5767 (concat "<?" types-re ":"
5768 "\\([^" org-non-link-chars " ]"
5769 "[^\t\n\r]*"
5770 "[^" org-non-link-chars " ]\\)>?")
5771 org-link-re-with-space3
5772 (concat "<?" types-re ":"
5773 "\\([^" org-non-link-chars " ]"
5774 "[^\t\n\r]*\\)")
5775 org-angle-link-re
5776 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5777 types-re)
5778 org-plain-link-re
5779 (concat
5780 "\\<" types-re ":"
5781 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5782 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5783 org-bracket-link-regexp
5784 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5785 org-bracket-link-analytic-regexp
5786 (concat
5787 "\\[\\["
5788 "\\(" types-re ":\\)?"
5789 "\\([^]]+\\)"
5790 "\\]"
5791 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5792 "\\]")
5793 org-bracket-link-analytic-regexp++
5794 (concat
5795 "\\[\\["
5796 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5797 "\\([^]]+\\)"
5798 "\\]"
5799 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5800 "\\]")
5801 org-any-link-re
5802 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5803 org-angle-link-re "\\)\\|\\("
5804 org-plain-link-re "\\)"))))
5806 (org-make-link-regexps)
5808 (defvar org-emph-face nil)
5810 (defun org-do-emphasis-faces (limit)
5811 "Run through the buffer and emphasize strings."
5812 (let (rtn a)
5813 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5814 (let* ((border (char-after (match-beginning 3)))
5815 (bre (regexp-quote (char-to-string border))))
5816 (when (and (not (= border (char-after (match-beginning 4))))
5817 (not (string-match-p (concat bre ".*" bre)
5818 (replace-regexp-in-string
5819 "\n" " "
5820 (substring (match-string 2) 1 -1)))))
5821 (setq rtn t)
5822 (setq a (assoc (match-string 3) org-emphasis-alist))
5823 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5824 'face
5825 (nth 1 a))
5826 (and (nth 2 a)
5827 (org-remove-flyspell-overlays-in
5828 (match-beginning 0) (match-end 0)))
5829 (add-text-properties (match-beginning 2) (match-end 2)
5830 '(font-lock-multiline t org-emphasis t))
5831 (when org-hide-emphasis-markers
5832 (add-text-properties (match-end 4) (match-beginning 5)
5833 '(invisible org-link))
5834 (add-text-properties (match-beginning 3) (match-end 3)
5835 '(invisible org-link)))))
5836 (goto-char (1+ (match-beginning 0))))
5837 rtn))
5839 (defun org-emphasize (&optional char)
5840 "Insert or change an emphasis, i.e. a font like bold or italic.
5841 If there is an active region, change that region to a new emphasis.
5842 If there is no region, just insert the marker characters and position
5843 the cursor between them.
5844 CHAR should be the marker character. If it is a space, it means to
5845 remove the emphasis of the selected region.
5846 If CHAR is not given (for example in an interactive call) it will be
5847 prompted for."
5848 (interactive)
5849 (let ((erc org-emphasis-regexp-components)
5850 (string "") beg end move s)
5851 (if (org-region-active-p)
5852 (setq beg (region-beginning)
5853 end (region-end)
5854 string (buffer-substring beg end))
5855 (setq move t))
5857 (unless char
5858 (message "Emphasis marker or tag: [%s]"
5859 (mapconcat #'car org-emphasis-alist ""))
5860 (setq char (read-char-exclusive)))
5861 (if (equal char ?\s)
5862 (setq s ""
5863 move nil)
5864 (unless (assoc (char-to-string char) org-emphasis-alist)
5865 (user-error "No such emphasis marker: \"%c\"" char))
5866 (setq s (char-to-string char)))
5867 (while (and (> (length string) 1)
5868 (equal (substring string 0 1) (substring string -1))
5869 (assoc (substring string 0 1) org-emphasis-alist))
5870 (setq string (substring string 1 -1)))
5871 (setq string (concat s string s))
5872 (when beg (delete-region beg end))
5873 (unless (or (bolp)
5874 (string-match (concat "[" (nth 0 erc) "\n]")
5875 (char-to-string (char-before (point)))))
5876 (insert " "))
5877 (unless (or (eobp)
5878 (string-match (concat "[" (nth 1 erc) "\n]")
5879 (char-to-string (char-after (point)))))
5880 (insert " ") (backward-char 1))
5881 (insert string)
5882 (and move (backward-char 1))))
5884 (defconst org-nonsticky-props
5885 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5887 (defsubst org-rear-nonsticky-at (pos)
5888 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5890 (defun org-activate-plain-links (limit)
5891 "Add link properties for plain links."
5892 (when (and (re-search-forward org-plain-link-re limit t)
5893 (not (org-in-src-block-p)))
5894 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5895 'face))
5896 (link (match-string-no-properties 0)))
5897 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5898 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5899 (add-text-properties (match-beginning 0) (match-end 0)
5900 (list 'mouse-face 'highlight
5901 'face 'org-link
5902 'htmlize-link `(:uri ,link)
5903 'keymap org-mouse-map))
5904 (org-rear-nonsticky-at (match-end 0))
5905 t))))
5907 (defun org-activate-code (limit)
5908 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5909 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5910 (remove-text-properties (match-beginning 0) (match-end 0)
5911 '(display t invisible t intangible t))
5914 (defcustom org-src-fontify-natively t
5915 "When non-nil, fontify code in code blocks."
5916 :type 'boolean
5917 :version "24.4"
5918 :package-version '(Org . "8.3")
5919 :group 'org-appearance
5920 :group 'org-babel)
5922 (defcustom org-allow-promoting-top-level-subtree nil
5923 "When non-nil, allow promoting a top level subtree.
5924 The leading star of the top level headline will be replaced
5925 by a #."
5926 :type 'boolean
5927 :version "24.1"
5928 :group 'org-appearance)
5930 (defun org-fontify-meta-lines-and-blocks (limit)
5931 (condition-case nil
5932 (org-fontify-meta-lines-and-blocks-1 limit)
5933 (error (message "org-mode fontification error in %S at %d"
5934 (current-buffer)
5935 (line-number-at-pos)))))
5937 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5938 "Fontify #+ lines and blocks."
5939 (let ((case-fold-search t))
5940 (when (re-search-forward
5941 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5942 limit t)
5943 (let ((beg (match-beginning 0))
5944 (block-start (match-end 0))
5945 (block-end nil)
5946 (lang (match-string 7))
5947 (beg1 (line-beginning-position 2))
5948 (dc1 (downcase (match-string 2)))
5949 (dc3 (downcase (match-string 3)))
5950 end end1 quoting block-type)
5951 (cond
5952 ((and (match-end 4) (equal dc3 "+begin"))
5953 ;; Truly a block
5954 (setq block-type (downcase (match-string 5))
5955 quoting (member block-type org-protecting-blocks))
5956 (when (re-search-forward
5957 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5958 nil t) ;; on purpose, we look further than LIMIT
5959 (setq end (min (point-max) (match-end 0))
5960 end1 (min (point-max) (1- (match-beginning 0))))
5961 (setq block-end (match-beginning 0))
5962 (when quoting
5963 (org-remove-flyspell-overlays-in beg1 end1)
5964 (remove-text-properties beg end
5965 '(display t invisible t intangible t)))
5966 (add-text-properties
5967 beg end '(font-lock-fontified t font-lock-multiline t))
5968 (add-text-properties beg beg1 '(face org-meta-line))
5969 (org-remove-flyspell-overlays-in beg beg1)
5970 (add-text-properties ; For end_src
5971 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5972 (org-remove-flyspell-overlays-in end1 end)
5973 (cond
5974 ((and lang (not (string= lang "")) org-src-fontify-natively)
5975 (org-src-font-lock-fontify-block lang block-start block-end)
5976 (add-text-properties beg1 block-end '(src-block t)))
5977 (quoting
5978 (add-text-properties beg1 (min (point-max) (1+ end1))
5979 '(face org-block))) ; end of source block
5980 ((not org-fontify-quote-and-verse-blocks))
5981 ((string= block-type "quote")
5982 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5983 ((string= block-type "verse")
5984 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5985 (add-text-properties beg beg1 '(face org-block-begin-line))
5986 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5987 '(face org-block-end-line))
5989 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5990 (org-remove-flyspell-overlays-in
5991 (match-beginning 0)
5992 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5993 (add-text-properties
5994 beg (match-end 3)
5995 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5996 '(font-lock-fontified t invisible t)
5997 '(font-lock-fontified t face org-document-info-keyword)))
5998 (add-text-properties
5999 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6000 (if (string-equal dc1 "+title:")
6001 '(font-lock-fontified t face org-document-title)
6002 '(font-lock-fontified t face org-document-info))))
6003 ((equal dc1 "+caption:")
6004 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6005 (remove-text-properties (match-beginning 0) (match-end 0)
6006 '(display t invisible t intangible t))
6007 (add-text-properties (match-beginning 1) (match-end 3)
6008 '(font-lock-fontified t face org-meta-line))
6009 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6010 '(font-lock-fontified t face org-block))
6012 ((member dc3 '(" " ""))
6013 (org-remove-flyspell-overlays-in beg (match-end 0))
6014 (add-text-properties
6015 beg (match-end 0)
6016 '(font-lock-fontified t face font-lock-comment-face)))
6017 (t ;; just any other in-buffer setting, but not indented
6018 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6019 (remove-text-properties (match-beginning 0) (match-end 0)
6020 '(display t invisible t intangible t))
6021 (add-text-properties beg (match-end 0)
6022 '(font-lock-fontified t face org-meta-line))
6023 t))))))
6025 (defun org-fontify-drawers (limit)
6026 "Fontify drawers."
6027 (when (re-search-forward org-drawer-regexp limit t)
6028 (add-text-properties
6029 (match-beginning 0) (match-end 0)
6030 '(font-lock-fontified t face org-special-keyword))
6031 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6034 (defun org-fontify-macros (limit)
6035 "Fontify macros."
6036 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6037 (add-text-properties
6038 (match-beginning 0) (match-end 0)
6039 '(font-lock-fontified t face org-macro))
6040 (when org-hide-macro-markers
6041 (add-text-properties (match-end 2) (match-beginning 2)
6042 '(invisible t))
6043 (add-text-properties (match-beginning 1) (match-end 1)
6044 '(invisible t)))
6045 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6048 (defun org-activate-angle-links (limit)
6049 "Add text properties for angle links."
6050 (when (and (re-search-forward org-angle-link-re limit t)
6051 (not (org-in-src-block-p)))
6052 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6053 (add-text-properties (match-beginning 0) (match-end 0)
6054 (list 'mouse-face 'highlight
6055 'keymap org-mouse-map
6056 'font-lock-multiline t))
6057 (org-rear-nonsticky-at (match-end 0))
6060 (defun org-activate-footnote-links (limit)
6061 "Add text properties for footnotes."
6062 (let ((fn (org-footnote-next-reference-or-definition limit)))
6063 (when fn
6064 (let* ((beg (nth 1 fn))
6065 (end (nth 2 fn))
6066 (label (car fn))
6067 (referencep (/= (line-beginning-position) beg)))
6068 (when (and referencep (nth 3 fn))
6069 (save-excursion
6070 (goto-char beg)
6071 (search-forward (or label "fn:"))
6072 (org-remove-flyspell-overlays-in beg (match-end 0))))
6073 (add-text-properties beg end
6074 (list 'mouse-face 'highlight
6075 'keymap org-mouse-map
6076 'help-echo
6077 (if referencep "Footnote reference"
6078 "Footnote definition")
6079 'font-lock-fontified t
6080 'font-lock-multiline t
6081 'face 'org-footnote))))))
6083 (defun org-activate-bracket-links (limit)
6084 "Add text properties for bracketed links."
6085 (when (and (re-search-forward org-bracket-link-regexp limit t)
6086 (not (org-in-src-block-p)))
6087 (let* ((hl (match-string-no-properties 1))
6088 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6089 (ip (org-maybe-intangible
6090 (list 'invisible 'org-link
6091 'keymap org-mouse-map 'mouse-face 'highlight
6092 'font-lock-multiline t 'help-echo help
6093 'htmlize-link `(:uri ,hl))))
6094 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6095 'font-lock-multiline t 'help-echo help
6096 'htmlize-link `(:uri ,hl))))
6097 ;; We need to remove the invisible property here. Table narrowing
6098 ;; may have made some of this invisible.
6099 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6100 (remove-text-properties (match-beginning 0) (match-end 0)
6101 '(invisible nil))
6102 (if (match-end 3)
6103 (progn
6104 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6105 (org-rear-nonsticky-at (match-beginning 3))
6106 (add-text-properties (match-beginning 3) (match-end 3) vp)
6107 (org-rear-nonsticky-at (match-end 3))
6108 (add-text-properties (match-end 3) (match-end 0) ip)
6109 (org-rear-nonsticky-at (match-end 0)))
6110 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6111 (org-rear-nonsticky-at (match-beginning 1))
6112 (add-text-properties (match-beginning 1) (match-end 1) vp)
6113 (org-rear-nonsticky-at (match-end 1))
6114 (add-text-properties (match-end 1) (match-end 0) ip)
6115 (org-rear-nonsticky-at (match-end 0)))
6116 t)))
6118 (defun org-activate-dates (limit)
6119 "Add text properties for dates."
6120 (when (and (re-search-forward org-tsr-regexp-both limit t)
6121 (not (equal (char-before (match-beginning 0)) 91)))
6122 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6123 (add-text-properties (match-beginning 0) (match-end 0)
6124 (list 'mouse-face 'highlight
6125 'keymap org-mouse-map))
6126 (org-rear-nonsticky-at (match-end 0))
6127 (when org-display-custom-times
6128 (if (match-end 3)
6129 (org-display-custom-time (match-beginning 3) (match-end 3))
6130 (org-display-custom-time (match-beginning 1) (match-end 1))))
6133 (defvar-local org-target-link-regexp nil
6134 "Regular expression matching radio targets in plain text.")
6136 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6137 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6138 border border border))
6139 "Regular expression matching a link target.")
6141 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6142 "Regular expression matching a radio target.")
6144 (defconst org-any-target-regexp
6145 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6146 "Regular expression matching any target.")
6148 (defun org-activate-target-links (limit)
6149 "Add text properties for target matches."
6150 (when org-target-link-regexp
6151 (let ((case-fold-search t))
6152 (when (re-search-forward org-target-link-regexp limit t)
6153 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6154 (add-text-properties (match-beginning 1) (match-end 1)
6155 (list 'mouse-face 'highlight
6156 'keymap org-mouse-map
6157 'help-echo "Radio target link"
6158 'org-linked-text t))
6159 (org-rear-nonsticky-at (match-end 1))
6160 t))))
6162 (defun org-update-radio-target-regexp ()
6163 "Find all radio targets in this file and update the regular expression.
6164 Also refresh fontification if needed."
6165 (interactive)
6166 (let ((old-regexp org-target-link-regexp)
6167 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6168 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6169 (targets
6170 (org-with-wide-buffer
6171 (goto-char (point-min))
6172 (let (rtn)
6173 (while (re-search-forward org-radio-target-regexp nil t)
6174 ;; Make sure point is really within the object.
6175 (backward-char)
6176 (let ((obj (org-element-context)))
6177 (when (eq (org-element-type obj) 'radio-target)
6178 (cl-pushnew (org-element-property :value obj) rtn
6179 :test #'equal))))
6180 rtn))))
6181 (setq org-target-link-regexp
6182 (and targets
6183 (concat before-re
6184 (mapconcat
6185 (lambda (x)
6186 (replace-regexp-in-string
6187 " +" "\\s-+" (regexp-quote x) t t))
6188 targets
6189 "\\|")
6190 after-re)))
6191 (unless (equal old-regexp org-target-link-regexp)
6192 ;; Clean-up cache.
6193 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6194 ((not org-target-link-regexp) old-regexp)
6196 (concat before-re
6197 (mapconcat
6198 (lambda (re)
6199 (substring re (length before-re)
6200 (- (length after-re))))
6201 (list old-regexp org-target-link-regexp)
6202 "\\|")
6203 after-re)))))
6204 (org-with-wide-buffer
6205 (goto-char (point-min))
6206 (while (re-search-forward regexp nil t)
6207 (org-element-cache-refresh (match-beginning 1)))))
6208 ;; Re fontify buffer.
6209 (when (memq 'radio org-highlight-links)
6210 (org-restart-font-lock)))))
6212 (defun org-hide-wide-columns (limit)
6213 (let (s e)
6214 (setq s (text-property-any (point) (or limit (point-max))
6215 'org-cwidth t))
6216 (when s
6217 (setq e (next-single-property-change s 'org-cwidth))
6218 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6219 (goto-char e)
6220 t)))
6222 (defvar org-latex-and-related-regexp nil
6223 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6225 (defun org-compute-latex-and-related-regexp ()
6226 "Compute regular expression for LaTeX, entities and sub/superscript.
6227 Result depends on variable `org-highlight-latex-and-related'."
6228 (setq-local
6229 org-latex-and-related-regexp
6230 (let* ((re-sub
6231 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6232 ((eq org-use-sub-superscripts '{})
6233 (list org-match-substring-with-braces-regexp))
6234 (org-use-sub-superscripts (list org-match-substring-regexp))))
6235 (re-latex
6236 (when (memq 'latex org-highlight-latex-and-related)
6237 (let ((matchers (plist-get org-format-latex-options :matchers)))
6238 (delq nil
6239 (mapcar (lambda (x)
6240 (and (member (car x) matchers) (nth 1 x)))
6241 org-latex-regexps)))))
6242 (re-entities
6243 (when (memq 'entities org-highlight-latex-and-related)
6244 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6245 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6247 (defun org-do-latex-and-related (limit)
6248 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6249 LIMIT bounds the search for syntax to highlight. Stop at first
6250 highlighted object, if any. Return t if some highlighting was
6251 done, nil otherwise."
6252 (when (org-string-nw-p org-latex-and-related-regexp)
6253 (catch 'found
6254 (while (re-search-forward org-latex-and-related-regexp limit t)
6255 (unless
6256 (cl-some
6257 (lambda (f)
6258 (memq f '(org-code org-verbatim underline org-special-keyword)))
6259 (save-excursion
6260 (goto-char (1+ (match-beginning 0)))
6261 (face-at-point nil t)))
6262 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6263 '(?_ ?^))
6265 0)))
6266 (font-lock-prepend-text-property
6267 (+ offset (match-beginning 0)) (match-end 0)
6268 'face 'org-latex-and-related)
6269 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6270 '(font-lock-multiline t)))
6271 (throw 'found t)))
6272 nil)))
6274 (defun org-restart-font-lock ()
6275 "Restart `font-lock-mode', to force refontification."
6276 (when (and (boundp 'font-lock-mode) font-lock-mode)
6277 (font-lock-mode -1)
6278 (font-lock-mode 1)))
6280 (defun org-activate-tags (limit)
6281 (when (re-search-forward
6282 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6283 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6284 (add-text-properties (match-beginning 1) (match-end 1)
6285 (list 'mouse-face 'highlight
6286 'keymap org-mouse-map))
6287 (org-rear-nonsticky-at (match-end 1))
6290 (defun org-outline-level ()
6291 "Compute the outline level of the heading at point.
6293 If this is called at a normal headline, the level is the number
6294 of stars. Use `org-reduced-level' to remove the effect of
6295 `org-odd-levels'. Unlike to `org-current-level', this function
6296 takes into consideration inlinetasks."
6297 (org-with-wide-buffer
6298 (end-of-line)
6299 (if (re-search-backward org-outline-regexp-bol nil t)
6300 (1- (- (match-end 0) (match-beginning 0)))
6301 0)))
6303 (defvar org-font-lock-keywords nil)
6305 (defsubst org-re-property (property &optional literal allow-null value)
6306 "Return a regexp matching a PROPERTY line.
6308 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6309 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6310 non-nil, match properties even without a value.
6312 Match group 3 is set to the value when it exists. If there is no
6313 value and ALLOW-NULL is non-nil, it is set to the empty string.
6315 With optional argument VALUE, match only property lines with
6316 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6317 unless LITERAL is non-nil."
6318 (concat
6319 "^\\(?4:[ \t]*\\)"
6320 (format "\\(?1::\\(?2:%s\\):\\)"
6321 (if literal property (regexp-quote property)))
6322 (cond (value
6323 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6324 (if literal value (regexp-quote value))))
6325 (allow-null
6326 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6328 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6330 (defconst org-property-re
6331 (org-re-property "\\S-+" 'literal t)
6332 "Regular expression matching a property line.
6333 There are four matching groups:
6334 1: :PROPKEY: including the leading and trailing colon,
6335 2: PROPKEY without the leading and trailing colon,
6336 3: PROPVAL without leading or trailing spaces,
6337 4: the indentation of the current line,
6338 5: trailing whitespace.")
6340 (defvar org-font-lock-hook nil
6341 "Functions to be called for special font lock stuff.")
6343 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6345 (defvar org-font-lock-set-keywords-hook nil
6346 "Functions that can manipulate `org-font-lock-extra-keywords'.
6347 This is called after `org-font-lock-extra-keywords' is defined, but before
6348 it is installed to be used by font lock. This can be useful if something
6349 needs to be inserted at a specific position in the font-lock sequence.")
6351 (defun org-font-lock-hook (limit)
6352 "Run `org-font-lock-hook' within LIMIT."
6353 (run-hook-with-args 'org-font-lock-hook limit))
6355 (defun org-set-font-lock-defaults ()
6356 "Set font lock defaults for the current buffer."
6357 (let* ((em org-fontify-emphasized-text)
6358 (lk org-highlight-links)
6359 (org-font-lock-extra-keywords
6360 (list
6361 ;; Call the hook
6362 '(org-font-lock-hook)
6363 ;; Headlines
6364 `(,(if org-fontify-whole-heading-line
6365 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6366 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6367 (1 (org-get-level-face 1))
6368 (2 (org-get-level-face 2))
6369 (3 (org-get-level-face 3)))
6370 ;; Table lines
6371 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6372 (1 'org-table t))
6373 ;; Table internals
6374 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6375 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6376 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6377 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6378 ;; Drawers
6379 '(org-fontify-drawers)
6380 ;; Properties
6381 (list org-property-re
6382 '(1 'org-special-keyword t)
6383 '(3 'org-property-value t))
6384 ;; Links
6385 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6386 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6387 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6388 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6389 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6390 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6391 (when (memq 'footnote lk) '(org-activate-footnote-links))
6392 ;; Targets.
6393 (list org-any-target-regexp '(0 'org-target t))
6394 ;; Diary sexps.
6395 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6396 ;; Macro
6397 '(org-fontify-macros)
6398 '(org-hide-wide-columns (0 nil append))
6399 ;; TODO keyword
6400 (list (format org-heading-keyword-regexp-format
6401 org-todo-regexp)
6402 '(2 (org-get-todo-face 2) t))
6403 ;; DONE
6404 (if org-fontify-done-headline
6405 (list (format org-heading-keyword-regexp-format
6406 (concat
6407 "\\(?:"
6408 (mapconcat 'regexp-quote org-done-keywords "\\|")
6409 "\\)"))
6410 '(2 'org-headline-done t))
6411 nil)
6412 ;; Priorities
6413 '(org-font-lock-add-priority-faces)
6414 ;; Tags
6415 '(org-font-lock-add-tag-faces)
6416 ;; Tags groups
6417 (when (and org-group-tags org-tag-groups-alist)
6418 (list (concat org-outline-regexp-bol ".+\\(:"
6419 (regexp-opt (mapcar 'car org-tag-groups-alist))
6420 ":\\).*$")
6421 '(1 'org-tag-group prepend)))
6422 ;; Special keywords
6423 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6424 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6425 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6426 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6427 ;; Emphasis
6428 (when em '(org-do-emphasis-faces))
6429 ;; Checkboxes
6430 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6431 1 'org-checkbox prepend)
6432 (when (cdr (assq 'checkbox org-list-automatic-rules))
6433 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6434 (0 (org-get-checkbox-statistics-face) t)))
6435 ;; Description list items
6436 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6437 1 'org-list-dt prepend)
6438 ;; ARCHIVEd headings
6439 (list (concat
6440 org-outline-regexp-bol
6441 "\\(.*:" org-archive-tag ":.*\\)")
6442 '(1 'org-archived prepend))
6443 ;; Specials
6444 '(org-do-latex-and-related)
6445 '(org-fontify-entities)
6446 '(org-raise-scripts)
6447 ;; Code
6448 '(org-activate-code (1 'org-code t))
6449 ;; COMMENT
6450 (list (format
6451 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6452 org-todo-regexp
6453 org-comment-string)
6454 '(9 'org-special-keyword t))
6455 ;; Blocks and meta lines
6456 '(org-fontify-meta-lines-and-blocks))))
6457 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6458 (run-hooks 'org-font-lock-set-keywords-hook)
6459 ;; Now set the full font-lock-keywords
6460 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6461 (setq-local font-lock-defaults
6462 '(org-font-lock-keywords t nil nil backward-paragraph))
6463 (kill-local-variable 'font-lock-keywords) nil))
6465 (defun org-toggle-pretty-entities ()
6466 "Toggle the composition display of entities as UTF8 characters."
6467 (interactive)
6468 (setq-local org-pretty-entities (not org-pretty-entities))
6469 (org-restart-font-lock)
6470 (if org-pretty-entities
6471 (message "Entities are now displayed as UTF8 characters")
6472 (save-restriction
6473 (widen)
6474 (decompose-region (point-min) (point-max))
6475 (message "Entities are now displayed as plain text"))))
6477 (defvar-local org-custom-properties-overlays nil
6478 "List of overlays used for custom properties.")
6480 (defun org-toggle-custom-properties-visibility ()
6481 "Display or hide properties in `org-custom-properties'."
6482 (interactive)
6483 (if org-custom-properties-overlays
6484 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6485 (setq org-custom-properties-overlays nil))
6486 (when org-custom-properties
6487 (org-with-wide-buffer
6488 (goto-char (point-min))
6489 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6490 (while (re-search-forward regexp nil t)
6491 (let ((end (cdr (save-match-data (org-get-property-block)))))
6492 (when (and end (< (point) end))
6493 ;; Hide first custom property in current drawer.
6494 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6495 (overlay-put o 'invisible t)
6496 (overlay-put o 'org-custom-property t)
6497 (push o org-custom-properties-overlays))
6498 ;; Hide additional custom properties in the same drawer.
6499 (while (re-search-forward regexp end t)
6500 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6501 (overlay-put o 'invisible t)
6502 (overlay-put o 'org-custom-property t)
6503 (push o org-custom-properties-overlays)))))
6504 ;; Each entry is limited to a single property drawer.
6505 (outline-next-heading)))))))
6507 (defun org-fontify-entities (limit)
6508 "Find an entity to fontify."
6509 (let (ee)
6510 (when org-pretty-entities
6511 (catch 'match
6512 ;; "\_ "-family is left out on purpose. Only the first one,
6513 ;; i.e., "\_ ", could be fontified anyway, and it would be
6514 ;; confusing when adding a second white space character.
6515 (while (re-search-forward
6516 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6517 limit t)
6518 (when (and (not (org-at-comment-p))
6519 (setq ee (org-entity-get (match-string 1)))
6520 (= (length (nth 6 ee)) 1))
6521 (let* ((end (if (equal (match-string 2) "{}")
6522 (match-end 2)
6523 (match-end 1))))
6524 (add-text-properties
6525 (match-beginning 0) end
6526 (list 'font-lock-fontified t))
6527 (compose-region (match-beginning 0) end
6528 (nth 6 ee) nil)
6529 (backward-char 1)
6530 (throw 'match t))))
6531 nil))))
6533 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6534 "Fontify string S like in Org-mode."
6535 (with-temp-buffer
6536 (insert s)
6537 (let ((org-odd-levels-only odd-levels))
6538 (org-mode)
6539 (org-font-lock-ensure)
6540 (buffer-string))))
6542 (defvar org-m nil)
6543 (defvar org-l nil)
6544 (defvar org-f nil)
6545 (defun org-get-level-face (n)
6546 "Get the right face for match N in font-lock matching of headlines."
6547 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6548 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6549 (if org-cycle-level-faces
6550 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6551 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6552 (cond
6553 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6554 ((eq n 2) org-f)
6555 (t (unless org-level-color-stars-only org-f))))
6557 (defun org-face-from-face-or-color (context inherit face-or-color)
6558 "Create a face list that inherits INHERIT, but sets the foreground color.
6559 When FACE-OR-COLOR is not a string, just return it."
6560 (if (stringp face-or-color)
6561 (list :inherit inherit
6562 (cdr (assoc context org-faces-easy-properties))
6563 face-or-color)
6564 face-or-color))
6566 (defun org-get-todo-face (kwd)
6567 "Get the right face for a TODO keyword KWD.
6568 If KWD is a number, get the corresponding match group."
6569 (when (numberp kwd) (setq kwd (match-string kwd)))
6570 (or (org-face-from-face-or-color
6571 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6572 (and (member kwd org-done-keywords) 'org-done)
6573 'org-todo))
6575 (defun org-get-priority-face (priority)
6576 "Get the right face for PRIORITY.
6577 PRIORITY is a character."
6578 (or (org-face-from-face-or-color
6579 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6580 'org-priority))
6582 (defun org-get-tag-face (tag)
6583 "Get the right face for TAG.
6584 If TAG is a number, get the corresponding match group."
6585 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6586 (or (org-face-from-face-or-color
6587 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6588 'org-tag)))
6590 (defun org-font-lock-add-priority-faces (limit)
6591 "Add the special priority faces."
6592 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6593 (add-text-properties
6594 (match-beginning 1) (match-end 1)
6595 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6596 'font-lock-fontified t))))
6598 (defun org-font-lock-add-tag-faces (limit)
6599 "Add the special tag faces."
6600 (when (and org-tag-faces org-tags-special-faces-re)
6601 (while (re-search-forward org-tags-special-faces-re limit t)
6602 (add-text-properties (match-beginning 1) (match-end 1)
6603 (list 'face (org-get-tag-face 1)
6604 'font-lock-fontified t))
6605 (backward-char 1))))
6607 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6608 "Remove fontification and activation overlays from links."
6609 (font-lock-default-unfontify-region beg end)
6610 (let* ((buffer-undo-list t)
6611 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6612 (inhibit-modification-hooks t)
6613 deactivate-mark buffer-file-name buffer-file-truename)
6614 (decompose-region beg end)
6615 (remove-text-properties beg end
6616 '(mouse-face t keymap t org-linked-text t
6617 invisible t intangible t
6618 org-emphasis t))
6619 (org-remove-font-lock-display-properties beg end)))
6621 (defconst org-script-display '(((raise -0.3) (height 0.7))
6622 ((raise 0.3) (height 0.7))
6623 ((raise -0.5))
6624 ((raise 0.5)))
6625 "Display properties for showing superscripts and subscripts.")
6627 (defun org-remove-font-lock-display-properties (beg end)
6628 "Remove specific display properties that have been added by font lock.
6629 The will remove the raise properties that are used to show superscripts
6630 and subscripts."
6631 (let (next prop)
6632 (while (< beg end)
6633 (setq next (next-single-property-change beg 'display nil end)
6634 prop (get-text-property beg 'display))
6635 (when (member prop org-script-display)
6636 (put-text-property beg next 'display nil))
6637 (setq beg next))))
6639 (defun org-raise-scripts (limit)
6640 "Add raise properties to sub/superscripts."
6641 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6642 (re-search-forward
6643 (if (eq org-use-sub-superscripts t)
6644 org-match-substring-regexp
6645 org-match-substring-with-braces-regexp)
6646 limit t))
6647 (let* ((pos (point)) table-p comment-p
6648 (mpos (match-beginning 3))
6649 (emph-p (get-text-property mpos 'org-emphasis))
6650 (link-p (get-text-property mpos 'mouse-face))
6651 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6652 (goto-char (point-at-bol))
6653 (setq table-p (looking-at-p org-table-dataline-regexp)
6654 comment-p (looking-at-p "^[ \t]*#[ +]"))
6655 (goto-char pos)
6656 ;; Handle a_b^c
6657 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6658 (unless (or comment-p emph-p link-p keyw-p)
6659 (put-text-property (match-beginning 3) (match-end 0)
6660 'display
6661 (if (equal (char-after (match-beginning 2)) ?^)
6662 (nth (if table-p 3 1) org-script-display)
6663 (nth (if table-p 2 0) org-script-display)))
6664 (add-text-properties (match-beginning 2) (match-end 2)
6665 (list 'invisible t
6666 'org-dwidth t 'org-dwidth-n 1))
6667 (if (and (eq (char-after (match-beginning 3)) ?{)
6668 (eq (char-before (match-end 3)) ?}))
6669 (progn
6670 (add-text-properties
6671 (match-beginning 3) (1+ (match-beginning 3))
6672 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6673 (add-text-properties
6674 (1- (match-end 3)) (match-end 3)
6675 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6676 t)))
6678 ;;;; Visibility cycling, including org-goto and indirect buffer
6680 ;;; Cycling
6682 (defvar-local org-cycle-global-status nil)
6683 (put 'org-cycle-global-status 'org-state t)
6684 (defvar-local org-cycle-subtree-status nil)
6685 (put 'org-cycle-subtree-status 'org-state t)
6687 (defvar org-inlinetask-min-level)
6689 (defun org-unlogged-message (&rest args)
6690 "Display a message, but avoid logging it in the *Messages* buffer."
6691 (let ((message-log-max nil))
6692 (apply 'message args)))
6694 ;;;###autoload
6695 (defun org-cycle (&optional arg)
6696 "TAB-action and visibility cycling for Org-mode.
6698 This is the command invoked in Org-mode by the TAB key. Its main purpose
6699 is outline visibility cycling, but it also invokes other actions
6700 in special contexts.
6702 - When this function is called with a prefix argument, rotate the entire
6703 buffer through 3 states (global cycling)
6704 1. OVERVIEW: Show only top-level headlines.
6705 2. CONTENTS: Show all headlines of all levels, but no body text.
6706 3. SHOW ALL: Show everything.
6707 With a double \\[universal-argument] prefix argument, \
6708 switch to the startup visibility,
6709 determined by the variable `org-startup-folded', and by any VISIBILITY
6710 properties in the buffer.
6711 With a triple \\[universal-argument] prefix argument, \
6712 show the entire buffer, including any drawers.
6714 - When inside a table, re-align the table and move to the next field.
6716 - When point is at the beginning of a headline, rotate the subtree started
6717 by this line through 3 different states (local cycling)
6718 1. FOLDED: Only the main headline is shown.
6719 2. CHILDREN: The main headline and the direct children are shown.
6720 From this state, you can move to one of the children
6721 and zoom in further.
6722 3. SUBTREE: Show the entire subtree, including body text.
6723 If there is no subtree, switch directly from CHILDREN to FOLDED.
6725 - When point is at the beginning of an empty headline and the variable
6726 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6727 of the headline by demoting and promoting it to likely levels. This
6728 speeds up creation document structure by pressing TAB once or several
6729 times right after creating a new headline.
6731 - When there is a numeric prefix, go up to a heading with level ARG, do
6732 a `show-subtree' and return to the previous cursor position. If ARG
6733 is negative, go up that many levels.
6735 - When point is not at the beginning of a headline, execute the global
6736 binding for TAB, which is re-indenting the line. See the option
6737 `org-cycle-emulate-tab' for details.
6739 - Special case: if point is at the beginning of the buffer and there is
6740 no headline in line 1, this function will act as if called with prefix arg
6741 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6742 But only if also the variable `org-cycle-global-at-bob' is t."
6743 (interactive "P")
6744 (org-load-modules-maybe)
6745 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6746 (and org-cycle-level-after-item/entry-creation
6747 (or (org-cycle-level)
6748 (org-cycle-item-indentation))))
6749 (let* ((limit-level
6750 (or org-cycle-max-level
6751 (and (boundp 'org-inlinetask-min-level)
6752 org-inlinetask-min-level
6753 (1- org-inlinetask-min-level))))
6754 (nstars (and limit-level
6755 (if org-odd-levels-only
6756 (and limit-level (1- (* limit-level 2)))
6757 limit-level)))
6758 (org-outline-regexp
6759 (if (not (derived-mode-p 'org-mode))
6760 outline-regexp
6761 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6762 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6763 (not (looking-at org-outline-regexp))))
6764 (org-cycle-hook
6765 (if bob-special
6766 (delq 'org-optimize-window-after-visibility-change
6767 (copy-sequence org-cycle-hook))
6768 org-cycle-hook))
6769 (pos (point)))
6771 (when (or bob-special (equal arg '(4)))
6772 ;; special case: use global cycling
6773 (setq arg t))
6775 (cond
6777 ((equal arg '(16))
6778 (setq last-command 'dummy)
6779 (org-set-startup-visibility)
6780 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6782 ((equal arg '(64))
6783 (outline-show-all)
6784 (org-unlogged-message "Entire buffer visible, including drawers"))
6786 ;; Try cdlatex TAB completion
6787 ((org-try-cdlatex-tab))
6789 ;; Table: enter it or move to the next field.
6790 ((org-at-table-p 'any)
6791 (if (org-at-table.el-p)
6792 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6793 Use \\[org-edit-special] to edit table.el tables"))
6794 (if arg (org-table-edit-field t)
6795 (org-table-justify-field-maybe)
6796 (call-interactively 'org-table-next-field))))
6798 ((run-hook-with-args-until-success
6799 'org-tab-after-check-for-table-hook))
6801 ;; Global cycling: delegate to `org-cycle-internal-global'.
6802 ((eq arg t) (org-cycle-internal-global))
6804 ;; Drawers: delegate to `org-flag-drawer'.
6805 ((save-excursion
6806 (beginning-of-line 1)
6807 (looking-at org-drawer-regexp))
6808 (org-flag-drawer ; toggle block visibility
6809 (not (get-char-property (match-end 0) 'invisible))))
6811 ;; Show-subtree, ARG levels up from here.
6812 ((integerp arg)
6813 (save-excursion
6814 (org-back-to-heading)
6815 (outline-up-heading (if (< arg 0) (- arg)
6816 (- (funcall outline-level) arg)))
6817 (org-show-subtree)))
6819 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6820 ((and (featurep 'org-inlinetask)
6821 (org-inlinetask-at-task-p)
6822 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6823 (org-inlinetask-toggle-visibility))
6825 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6826 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6827 (save-excursion (move-beginning-of-line 1)
6828 (looking-at org-outline-regexp)))
6829 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6830 (org-cycle-internal-local))
6832 ;; From there: TAB emulation and template completion.
6833 (buffer-read-only (org-back-to-heading))
6835 ((run-hook-with-args-until-success
6836 'org-tab-after-check-for-cycling-hook))
6838 ((org-try-structure-completion))
6840 ((run-hook-with-args-until-success
6841 'org-tab-before-tab-emulation-hook))
6843 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6844 (or (not (bolp))
6845 (not (looking-at org-outline-regexp))))
6846 (call-interactively (global-key-binding "\t")))
6848 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6849 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6850 (or (and (eq org-cycle-emulate-tab 'white)
6851 (= (match-end 0) (point-at-eol)))
6852 (and (eq org-cycle-emulate-tab 'whitestart)
6853 (>= (match-end 0) pos))))
6855 (eq org-cycle-emulate-tab t))
6856 (call-interactively (global-key-binding "\t")))
6858 (t (save-excursion
6859 (org-back-to-heading)
6860 (org-cycle)))))))
6862 (defun org-cycle-internal-global ()
6863 "Do the global cycling action."
6864 ;; Hack to avoid display of messages for .org attachments in Gnus
6865 (let ((ga (string-match "\\*fontification" (buffer-name))))
6866 (cond
6867 ((and (eq last-command this-command)
6868 (eq org-cycle-global-status 'overview))
6869 ;; We just created the overview - now do table of contents
6870 ;; This can be slow in very large buffers, so indicate action
6871 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6872 (unless ga (org-unlogged-message "CONTENTS..."))
6873 (org-content)
6874 (unless ga (org-unlogged-message "CONTENTS...done"))
6875 (setq org-cycle-global-status 'contents)
6876 (run-hook-with-args 'org-cycle-hook 'contents))
6878 ((and (eq last-command this-command)
6879 (eq org-cycle-global-status 'contents))
6880 ;; We just showed the table of contents - now show everything
6881 (run-hook-with-args 'org-pre-cycle-hook 'all)
6882 (outline-show-all)
6883 (unless ga (org-unlogged-message "SHOW ALL"))
6884 (setq org-cycle-global-status 'all)
6885 (run-hook-with-args 'org-cycle-hook 'all))
6888 ;; Default action: go to overview
6889 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6890 (org-overview)
6891 (unless ga (org-unlogged-message "OVERVIEW"))
6892 (setq org-cycle-global-status 'overview)
6893 (run-hook-with-args 'org-cycle-hook 'overview)))))
6895 (defvar org-called-with-limited-levels nil
6896 "Non-nil when `org-with-limited-levels' is currently active.")
6898 (defun org-cycle-internal-local ()
6899 "Do the local cycling action."
6900 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6901 ;; First, determine end of headline (EOH), end of subtree or item
6902 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6903 (save-excursion
6904 (if (org-at-item-p)
6905 (progn
6906 (beginning-of-line)
6907 (setq struct (org-list-struct))
6908 (setq eoh (point-at-eol))
6909 (setq eos (org-list-get-item-end-before-blank (point) struct))
6910 (setq has-children (org-list-has-child-p (point) struct)))
6911 (org-back-to-heading)
6912 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6913 (setq eos (save-excursion (org-end-of-subtree t t)
6914 (when (bolp) (backward-char)) (point)))
6915 (setq has-children
6916 (or (save-excursion
6917 (let ((level (funcall outline-level)))
6918 (outline-next-heading)
6919 (and (org-at-heading-p t)
6920 (> (funcall outline-level) level))))
6921 (save-excursion
6922 (org-list-search-forward (org-item-beginning-re) eos t)))))
6923 ;; Determine end invisible part of buffer (EOL)
6924 (beginning-of-line 2)
6925 (while (and (not (eobp)) ;This is like `next-line'.
6926 (get-char-property (1- (point)) 'invisible))
6927 (goto-char (next-single-char-property-change (point) 'invisible))
6928 (and (eolp) (beginning-of-line 2)))
6929 (setq eol (point)))
6930 ;; Find out what to do next and set `this-command'
6931 (cond
6932 ((= eos eoh)
6933 ;; Nothing is hidden behind this heading
6934 (unless (org-before-first-heading-p)
6935 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6936 (org-unlogged-message "EMPTY ENTRY")
6937 (setq org-cycle-subtree-status nil)
6938 (save-excursion
6939 (goto-char eos)
6940 (outline-next-heading)
6941 (when (outline-invisible-p) (org-flag-heading nil))))
6942 ((and (or (>= eol eos)
6943 (not (string-match "\\S-" (buffer-substring eol eos))))
6944 (or has-children
6945 (not (setq children-skipped
6946 org-cycle-skip-children-state-if-no-children))))
6947 ;; Entire subtree is hidden in one line: children view
6948 (unless (org-before-first-heading-p)
6949 (run-hook-with-args 'org-pre-cycle-hook 'children))
6950 (if (org-at-item-p)
6951 (org-list-set-item-visibility (point-at-bol) struct 'children)
6952 (org-show-entry)
6953 (org-with-limited-levels (org-show-children))
6954 ;; FIXME: This slows down the func way too much.
6955 ;; How keep drawers hidden in subtree anyway?
6956 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6957 ;; (org-cycle-hide-drawers 'subtree))
6959 ;; Fold every list in subtree to top-level items.
6960 (when (eq org-cycle-include-plain-lists 'integrate)
6961 (save-excursion
6962 (org-back-to-heading)
6963 (while (org-list-search-forward (org-item-beginning-re) eos t)
6964 (beginning-of-line 1)
6965 (let* ((struct (org-list-struct))
6966 (prevs (org-list-prevs-alist struct))
6967 (end (org-list-get-bottom-point struct)))
6968 (dolist (e (org-list-get-all-items (point) struct prevs))
6969 (org-list-set-item-visibility e struct 'folded))
6970 (goto-char (if (< end eos) end eos)))))))
6971 (org-unlogged-message "CHILDREN")
6972 (save-excursion
6973 (goto-char eos)
6974 (outline-next-heading)
6975 (when (outline-invisible-p) (org-flag-heading nil)))
6976 (setq org-cycle-subtree-status 'children)
6977 (unless (org-before-first-heading-p)
6978 (run-hook-with-args 'org-cycle-hook 'children)))
6979 ((or children-skipped
6980 (and (eq last-command this-command)
6981 (eq org-cycle-subtree-status 'children)))
6982 ;; We just showed the children, or no children are there,
6983 ;; now show everything.
6984 (unless (org-before-first-heading-p)
6985 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6986 (outline-flag-region eoh eos nil)
6987 (org-unlogged-message
6988 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6989 (setq org-cycle-subtree-status 'subtree)
6990 (unless (org-before-first-heading-p)
6991 (run-hook-with-args 'org-cycle-hook 'subtree)))
6993 ;; Default action: hide the subtree.
6994 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6995 (outline-flag-region eoh eos t)
6996 (org-unlogged-message "FOLDED")
6997 (setq org-cycle-subtree-status 'folded)
6998 (unless (org-before-first-heading-p)
6999 (run-hook-with-args 'org-cycle-hook 'folded))))))
7001 ;;;###autoload
7002 (defun org-global-cycle (&optional arg)
7003 "Cycle the global visibility. For details see `org-cycle'.
7004 With \\[universal-argument] prefix arg, switch to startup visibility.
7005 With a numeric prefix, show all headlines up to that level."
7006 (interactive "P")
7007 (let ((org-cycle-include-plain-lists
7008 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7009 (cond
7010 ((integerp arg)
7011 (outline-show-all)
7012 (outline-hide-sublevels arg)
7013 (setq org-cycle-global-status 'contents))
7014 ((equal arg '(4))
7015 (org-set-startup-visibility)
7016 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7018 (org-cycle '(4))))))
7020 (defun org-set-startup-visibility ()
7021 "Set the visibility required by startup options and properties."
7022 (cond
7023 ((eq org-startup-folded t)
7024 (org-overview))
7025 ((eq org-startup-folded 'content)
7026 (org-content))
7027 ((or (eq org-startup-folded 'showeverything)
7028 (eq org-startup-folded nil))
7029 (outline-show-all)))
7030 (unless (eq org-startup-folded 'showeverything)
7031 (when org-hide-block-startup (org-hide-block-all))
7032 (org-set-visibility-according-to-property 'no-cleanup)
7033 (org-cycle-hide-archived-subtrees 'all)
7034 (org-cycle-hide-drawers 'all)
7035 (org-cycle-show-empty-lines t)))
7037 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7038 "Switch subtree visibilities according to :VISIBILITY: property."
7039 (interactive)
7040 (org-with-wide-buffer
7041 (goto-char (point-min))
7042 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7043 (if (not (org-at-property-p)) (outline-next-heading)
7044 (let ((state (match-string 3)))
7045 (save-excursion
7046 (org-back-to-heading t)
7047 (outline-hide-subtree)
7048 (org-reveal)
7049 (cond
7050 ((equal state "folded")
7051 (outline-hide-subtree))
7052 ((equal state "children")
7053 (org-show-hidden-entry)
7054 (org-show-children))
7055 ((equal state "content")
7056 (save-excursion
7057 (save-restriction
7058 (org-narrow-to-subtree)
7059 (org-content))))
7060 ((member state '("all" "showall"))
7061 (outline-show-subtree)))))))
7062 (unless no-cleanup
7063 (org-cycle-hide-archived-subtrees 'all)
7064 (org-cycle-hide-drawers 'all)
7065 (org-cycle-show-empty-lines 'all))))
7067 ;; This function uses outline-regexp instead of the more fundamental
7068 ;; org-outline-regexp so that org-cycle-global works outside of Org
7069 ;; buffers, where outline-regexp is needed.
7070 (defun org-overview ()
7071 "Switch to overview mode, showing only top-level headlines.
7072 This shows all headlines with a level equal or greater than the level
7073 of the first headline in the buffer. This is important, because if the
7074 first headline is not level one, then (hide-sublevels 1) gives confusing
7075 results."
7076 (interactive)
7077 (save-excursion
7078 (let ((level
7079 (save-excursion
7080 (goto-char (point-min))
7081 (when (re-search-forward (concat "^" outline-regexp) nil t)
7082 (goto-char (match-beginning 0))
7083 (funcall outline-level)))))
7084 (and level (outline-hide-sublevels level)))))
7086 (defun org-content (&optional arg)
7087 "Show all headlines in the buffer, like a table of contents.
7088 With numerical argument N, show content up to level N."
7089 (interactive "P")
7090 (org-overview)
7091 (save-excursion
7092 ;; Visit all headings and show their offspring
7093 (and (integerp arg) (org-overview))
7094 (goto-char (point-max))
7095 (catch 'exit
7096 (while (and (progn (condition-case nil
7097 (outline-previous-visible-heading 1)
7098 (error (goto-char (point-min))))
7100 (looking-at org-outline-regexp))
7101 (if (integerp arg)
7102 (org-show-children (1- arg))
7103 (outline-show-branches))
7104 (when (bobp) (throw 'exit nil))))))
7106 (defun org-optimize-window-after-visibility-change (state)
7107 "Adjust the window after a change in outline visibility.
7108 This function is the default value of the hook `org-cycle-hook'."
7109 (when (get-buffer-window (current-buffer))
7110 (cond
7111 ((eq state 'content) nil)
7112 ((eq state 'all) nil)
7113 ((eq state 'folded) nil)
7114 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7115 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7117 (defun org-remove-empty-overlays-at (pos)
7118 "Remove outline overlays that do not contain non-white stuff."
7119 (dolist (o (overlays-at pos))
7120 (and (eq 'outline (overlay-get o 'invisible))
7121 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7122 (overlay-end o))))
7123 (delete-overlay o))))
7125 (defun org-clean-visibility-after-subtree-move ()
7126 "Fix visibility issues after moving a subtree."
7127 ;; First, find a reasonable region to look at:
7128 ;; Start two siblings above, end three below
7129 (let* ((beg (save-excursion
7130 (and (org-get-last-sibling)
7131 (org-get-last-sibling))
7132 (point)))
7133 (end (save-excursion
7134 (and (org-get-next-sibling)
7135 (org-get-next-sibling)
7136 (org-get-next-sibling))
7137 (if (org-at-heading-p)
7138 (point-at-eol)
7139 (point))))
7140 (level (looking-at "\\*+"))
7141 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7142 (save-excursion
7143 (save-restriction
7144 (narrow-to-region beg end)
7145 (when re
7146 ;; Properly fold already folded siblings
7147 (goto-char (point-min))
7148 (while (re-search-forward re nil t)
7149 (when (and (not (outline-invisible-p))
7150 (save-excursion
7151 (goto-char (point-at-eol)) (outline-invisible-p)))
7152 (outline-hide-entry))))
7153 (org-cycle-show-empty-lines 'overview)
7154 (org-cycle-hide-drawers 'overview)))))
7156 (defun org-cycle-show-empty-lines (state)
7157 "Show empty lines above all visible headlines.
7158 The region to be covered depends on STATE when called through
7159 `org-cycle-hook'. Lisp program can use t for STATE to get the
7160 entire buffer covered. Note that an empty line is only shown if there
7161 are at least `org-cycle-separator-lines' empty lines before the headline."
7162 (when (/= org-cycle-separator-lines 0)
7163 (save-excursion
7164 (let* ((n (abs org-cycle-separator-lines))
7165 (re (cond
7166 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7167 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7168 (t (let ((ns (number-to-string (- n 2))))
7169 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7170 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7171 beg end)
7172 (cond
7173 ((memq state '(overview contents t))
7174 (setq beg (point-min) end (point-max)))
7175 ((memq state '(children folded))
7176 (setq beg (point)
7177 end (progn (org-end-of-subtree t t)
7178 (line-beginning-position 2)))))
7179 (when beg
7180 (goto-char beg)
7181 (while (re-search-forward re end t)
7182 (unless (get-char-property (match-end 1) 'invisible)
7183 (let ((e (match-end 1))
7184 (b (if (>= org-cycle-separator-lines 0)
7185 (match-beginning 1)
7186 (save-excursion
7187 (goto-char (match-beginning 0))
7188 (skip-chars-backward " \t\n")
7189 (line-end-position)))))
7190 (outline-flag-region b e nil))))))))
7191 ;; Never hide empty lines at the end of the file.
7192 (save-excursion
7193 (goto-char (point-max))
7194 (outline-previous-heading)
7195 (outline-end-of-heading)
7196 (when (and (looking-at "[ \t\n]+")
7197 (= (match-end 0) (point-max)))
7198 (outline-flag-region (point) (match-end 0) nil))))
7200 (defun org-show-empty-lines-in-parent ()
7201 "Move to the parent and re-show empty lines before visible headlines."
7202 (save-excursion
7203 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7204 (org-cycle-show-empty-lines context))))
7206 (defun org-files-list ()
7207 "Return `org-agenda-files' list, plus all open org-mode files.
7208 This is useful for operations that need to scan all of a user's
7209 open and agenda-wise Org files."
7210 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7211 (dolist (buf (buffer-list))
7212 (with-current-buffer buf
7213 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7214 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7215 files))
7217 (defsubst org-entry-beginning-position ()
7218 "Return the beginning position of the current entry."
7219 (save-excursion (org-back-to-heading t) (point)))
7221 (defsubst org-entry-end-position ()
7222 "Return the end position of the current entry."
7223 (save-excursion (outline-next-heading) (point)))
7225 (defun org-cycle-hide-drawers (state &optional exceptions)
7226 "Re-hide all drawers after a visibility state change.
7227 When non-nil, optional argument EXCEPTIONS is a list of strings
7228 specifying which drawers should not be hidden."
7229 (when (and (derived-mode-p 'org-mode)
7230 (not (memq state '(overview folded contents))))
7231 (save-excursion
7232 (let* ((globalp (memq state '(contents all)))
7233 (beg (if globalp (point-min) (point)))
7234 (end (if globalp (point-max)
7235 (if (eq state 'children)
7236 (save-excursion (outline-next-heading) (point))
7237 (org-end-of-subtree t)))))
7238 (goto-char beg)
7239 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7240 (unless (member-ignore-case (match-string 1) exceptions)
7241 (let ((drawer (org-element-at-point)))
7242 (when (memq (org-element-type drawer) '(drawer property-drawer))
7243 (org-flag-drawer t drawer)
7244 ;; Make sure to skip drawer entirely or we might flag
7245 ;; it another time when matching its ending line with
7246 ;; `org-drawer-regexp'.
7247 (goto-char (org-element-property :end drawer))))))))))
7249 (defun org-flag-drawer (flag &optional element)
7250 "When FLAG is non-nil, hide the drawer we are at.
7251 Otherwise make it visible. When optional argument ELEMENT is
7252 a parsed drawer, as returned by `org-element-at-point', hide or
7253 show that drawer instead."
7254 (let ((drawer (or element
7255 (and (save-excursion
7256 (beginning-of-line)
7257 (looking-at-p org-drawer-regexp))
7258 (org-element-at-point)))))
7259 (when (memq (org-element-type drawer) '(drawer property-drawer))
7260 (let ((post (org-element-property :post-affiliated drawer)))
7261 (save-excursion
7262 (outline-flag-region
7263 (progn (goto-char post) (line-end-position))
7264 (progn (goto-char (org-element-property :end drawer))
7265 (skip-chars-backward " \r\t\n")
7266 (line-end-position))
7267 flag))
7268 ;; When the drawer is hidden away, make sure point lies in
7269 ;; a visible part of the buffer.
7270 (when (and flag (> (line-beginning-position) post))
7271 (goto-char post))))))
7273 (defun org-subtree-end-visible-p ()
7274 "Is the end of the current subtree visible?"
7275 (pos-visible-in-window-p
7276 (save-excursion (org-end-of-subtree t) (point))))
7278 (defun org-first-headline-recenter ()
7279 "Move cursor to the first headline and recenter the headline."
7280 (let ((window (get-buffer-window)))
7281 (when window
7282 (goto-char (point-min))
7283 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7284 (set-window-start window (line-beginning-position))))))
7286 ;;; Saving and restoring visibility
7288 (defun org-outline-overlay-data (&optional use-markers)
7289 "Return a list of the locations of all outline overlays.
7290 These are overlays with the `invisible' property value `outline'.
7291 The return value is a list of cons cells, with start and stop
7292 positions for each overlay.
7293 If USE-MARKERS is set, return the positions as markers."
7294 (let (beg end)
7295 (save-excursion
7296 (save-restriction
7297 (widen)
7298 (delq nil
7299 (mapcar (lambda (o)
7300 (when (eq (overlay-get o 'invisible) 'outline)
7301 (setq beg (overlay-start o)
7302 end (overlay-end o))
7303 (and beg end (> end beg)
7304 (if use-markers
7305 (cons (copy-marker beg)
7306 (copy-marker end t))
7307 (cons beg end)))))
7308 (overlays-in (point-min) (point-max))))))))
7310 (defun org-set-outline-overlay-data (data)
7311 "Create visibility overlays for all positions in DATA.
7312 DATA should have been made by `org-outline-overlay-data'."
7313 (org-with-wide-buffer
7314 (outline-show-all)
7315 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7317 ;;; Folding of blocks
7319 (defvar-local org-hide-block-overlays nil
7320 "Overlays hiding blocks.")
7322 (defun org-block-map (function &optional start end)
7323 "Call FUNCTION at the head of all source blocks in the current buffer.
7324 Optional arguments START and END can be used to limit the range."
7325 (let ((start (or start (point-min)))
7326 (end (or end (point-max))))
7327 (save-excursion
7328 (goto-char start)
7329 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7330 (save-excursion
7331 (save-match-data
7332 (goto-char (match-beginning 0))
7333 (funcall function)))))))
7335 (defun org-hide-block-toggle-all ()
7336 "Toggle the visibility of all blocks in the current buffer."
7337 (org-block-map 'org-hide-block-toggle))
7339 (defun org-hide-block-all ()
7340 "Fold all blocks in the current buffer."
7341 (interactive)
7342 (org-show-block-all)
7343 (org-block-map 'org-hide-block-toggle-maybe))
7345 (defun org-show-block-all ()
7346 "Unfold all blocks in the current buffer."
7347 (interactive)
7348 (mapc #'delete-overlay org-hide-block-overlays)
7349 (setq org-hide-block-overlays nil))
7351 (defun org-hide-block-toggle-maybe ()
7352 "Toggle visibility of block at point.
7353 Unlike to `org-hide-block-toggle', this function does not throw
7354 an error. Return a non-nil value when toggling is successful."
7355 (interactive)
7356 (ignore-errors (org-hide-block-toggle)))
7358 (defun org-hide-block-toggle (&optional force)
7359 "Toggle the visibility of the current block.
7360 When optional argument FORCE is `off', make block visible. If it
7361 is non-nil, hide it unconditionally. Throw an error when not at
7362 a block. Return a non-nil value when toggling is successful."
7363 (interactive)
7364 (let ((element (org-element-at-point)))
7365 (unless (memq (org-element-type element)
7366 '(center-block comment-block dynamic-block example-block
7367 export-block quote-block special-block
7368 src-block verse-block))
7369 (user-error "Not at a block"))
7370 (let* ((start (save-excursion
7371 (goto-char (org-element-property :post-affiliated element))
7372 (line-end-position)))
7373 (end (save-excursion
7374 (goto-char (org-element-property :end element))
7375 (skip-chars-backward " \r\t\n")
7376 (line-end-position)))
7377 (overlays (overlays-at start)))
7378 (cond
7379 ;; Do nothing when not before or at the block opening line or
7380 ;; at the block closing line.
7381 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7382 ((and (not (eq force 'off))
7383 (not (memq t (mapcar
7384 (lambda (o)
7385 (eq (overlay-get o 'invisible) 'org-hide-block))
7386 overlays))))
7387 (let ((ov (make-overlay start end)))
7388 (overlay-put ov 'invisible 'org-hide-block)
7389 ;; Make the block accessible to `isearch'.
7390 (overlay-put
7391 ov 'isearch-open-invisible
7392 (lambda (ov)
7393 (when (memq ov org-hide-block-overlays)
7394 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7395 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7396 (delete-overlay ov))))
7397 (push ov org-hide-block-overlays)
7398 ;; When the block is hidden away, make sure point is left in
7399 ;; a visible part of the buffer.
7400 (when (> (line-beginning-position) start)
7401 (goto-char start)
7402 (beginning-of-line))
7403 ;; Signal successful toggling.
7405 ((or (not force) (eq force 'off))
7406 (dolist (ov overlays t)
7407 (when (memq ov org-hide-block-overlays)
7408 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7409 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7410 (delete-overlay ov))))))))
7412 ;; org-tab-after-check-for-cycling-hook
7413 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7414 ;; Remove overlays when changing major mode
7415 (add-hook 'org-mode-hook
7416 (lambda () (add-hook 'change-major-mode-hook
7417 'org-show-block-all 'append 'local)))
7419 ;;; Org-goto
7421 (defvar org-goto-window-configuration nil)
7422 (defvar org-goto-marker nil)
7423 (defvar org-goto-map)
7424 (defun org-goto-map ()
7425 "Set the keymap `org-goto'."
7426 (setq org-goto-map
7427 (let ((map (make-sparse-keymap)))
7428 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7429 mouse-drag-region universal-argument org-occur)))
7430 (dolist (cmd cmds)
7431 (substitute-key-definition cmd cmd map global-map)))
7432 (suppress-keymap map)
7433 (org-defkey map "\C-m" 'org-goto-ret)
7434 (org-defkey map [(return)] 'org-goto-ret)
7435 (org-defkey map [(left)] 'org-goto-left)
7436 (org-defkey map [(right)] 'org-goto-right)
7437 (org-defkey map [(control ?g)] 'org-goto-quit)
7438 (org-defkey map "\C-i" 'org-cycle)
7439 (org-defkey map [(tab)] 'org-cycle)
7440 (org-defkey map [(down)] 'outline-next-visible-heading)
7441 (org-defkey map [(up)] 'outline-previous-visible-heading)
7442 (if org-goto-auto-isearch
7443 (if (fboundp 'define-key-after)
7444 (define-key-after map [t] 'org-goto-local-auto-isearch)
7445 nil)
7446 (org-defkey map "q" 'org-goto-quit)
7447 (org-defkey map "n" 'outline-next-visible-heading)
7448 (org-defkey map "p" 'outline-previous-visible-heading)
7449 (org-defkey map "f" 'outline-forward-same-level)
7450 (org-defkey map "b" 'outline-backward-same-level)
7451 (org-defkey map "u" 'outline-up-heading))
7452 (org-defkey map "/" 'org-occur)
7453 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7454 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7455 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7456 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7457 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7458 map)))
7460 (defconst org-goto-help
7461 "Browse buffer copy, to find location or copy text.%s
7462 RET=jump to location C-g=quit and return to previous location
7463 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7465 (defvar org-goto-start-pos) ; dynamically scoped parameter
7467 (defun org-goto (&optional alternative-interface)
7468 "Look up a different location in the current file, keeping current visibility.
7470 When you want look-up or go to a different location in a
7471 document, the fastest way is often to fold the entire buffer and
7472 then dive into the tree. This method has the disadvantage, that
7473 the previous location will be folded, which may not be what you
7474 want.
7476 This command works around this by showing a copy of the current
7477 buffer in an indirect buffer, in overview mode. You can dive
7478 into the tree in that copy, use org-occur and incremental search
7479 to find a location. When pressing RET or `Q', the command
7480 returns to the original buffer in which the visibility is still
7481 unchanged. After RET it will also jump to the location selected
7482 in the indirect buffer and expose the headline hierarchy above.
7484 With a prefix argument, use the alternative interface: e.g., if
7485 `org-goto-interface' is `outline' use `outline-path-completion'."
7486 (interactive "P")
7487 (org-goto-map)
7488 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7489 (org-refile-use-outline-path t)
7490 (org-refile-target-verify-function nil)
7491 (interface
7492 (if (not alternative-interface)
7493 org-goto-interface
7494 (if (eq org-goto-interface 'outline)
7495 'outline-path-completion
7496 'outline)))
7497 (org-goto-start-pos (point))
7498 (selected-point
7499 (if (eq interface 'outline)
7500 (car (org-get-location (current-buffer) org-goto-help))
7501 (let ((pa (org-refile-get-location "Goto")))
7502 (org-refile-check-position pa)
7503 (nth 3 pa)))))
7504 (if selected-point
7505 (progn
7506 (org-mark-ring-push org-goto-start-pos)
7507 (goto-char selected-point)
7508 (when (or (outline-invisible-p) (org-invisible-p2))
7509 (org-show-context 'org-goto)))
7510 (message "Quit"))))
7512 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7513 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7514 (defvar org-goto-local-auto-isearch-map) ; defined below
7516 (defun org-get-location (_buf help)
7517 "Let the user select a location in current buffer.
7518 This function uses a recursive edit. It returns the selected position
7519 or nil."
7520 (org-no-popups
7521 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7522 (isearch-hide-immediately nil)
7523 (isearch-search-fun-function
7524 (lambda () 'org-goto-local-search-headings))
7525 (org-goto-selected-point org-goto-exit-command))
7526 (save-excursion
7527 (save-window-excursion
7528 (delete-other-windows)
7529 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7530 (org-pop-to-buffer-same-window
7531 (condition-case nil
7532 (make-indirect-buffer (current-buffer) "*org-goto*")
7533 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7534 (with-output-to-temp-buffer "*Org Help*"
7535 (princ (format help (if org-goto-auto-isearch
7536 " Just type for auto-isearch."
7537 " n/p/f/b/u to navigate, q to quit."))))
7538 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7539 (setq buffer-read-only nil)
7540 (let ((org-startup-truncated t)
7541 (org-startup-folded nil)
7542 (org-startup-align-all-tables nil))
7543 (org-mode)
7544 (org-overview))
7545 (setq buffer-read-only t)
7546 (if (and (boundp 'org-goto-start-pos)
7547 (integer-or-marker-p org-goto-start-pos))
7548 (progn (goto-char org-goto-start-pos)
7549 (when (outline-invisible-p)
7550 (org-show-set-visibility 'lineage)))
7551 (goto-char (point-min)))
7552 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7553 (message "Select location and press RET")
7554 (use-local-map org-goto-map)
7555 (recursive-edit)))
7556 (kill-buffer "*org-goto*")
7557 (cons org-goto-selected-point org-goto-exit-command))))
7559 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7560 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7561 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7562 (if (fboundp 'isearch-other-control-char)
7563 (progn
7564 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7565 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7566 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7567 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7568 (define-key org-goto-local-auto-isearch-map [return] nil))
7570 (defun org-goto-local-search-headings (string bound noerror)
7571 "Search and make sure that any matches are in headlines."
7572 (catch 'return
7573 (while (if isearch-forward
7574 (search-forward string bound noerror)
7575 (search-backward string bound noerror))
7576 (when (save-match-data
7577 (and (save-excursion
7578 (beginning-of-line)
7579 (looking-at org-complex-heading-regexp))
7580 (or (not (match-beginning 5))
7581 (< (point) (match-beginning 5)))))
7582 (throw 'return (point))))))
7584 (defun org-goto-local-auto-isearch ()
7585 "Start isearch."
7586 (interactive)
7587 (goto-char (point-min))
7588 (let ((keys (this-command-keys)))
7589 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7590 (isearch-mode t)
7591 (isearch-process-search-char (string-to-char keys)))))
7593 (defun org-goto-ret (&optional _arg)
7594 "Finish `org-goto' by going to the new location."
7595 (interactive "P")
7596 (setq org-goto-selected-point (point))
7597 (setq org-goto-exit-command 'return)
7598 (throw 'exit nil))
7600 (defun org-goto-left ()
7601 "Finish `org-goto' by going to the new location."
7602 (interactive)
7603 (if (org-at-heading-p)
7604 (progn
7605 (beginning-of-line 1)
7606 (setq org-goto-selected-point (point)
7607 org-goto-exit-command 'left)
7608 (throw 'exit nil))
7609 (user-error "Not on a heading")))
7611 (defun org-goto-right ()
7612 "Finish `org-goto' by going to the new location."
7613 (interactive)
7614 (if (org-at-heading-p)
7615 (progn
7616 (setq org-goto-selected-point (point)
7617 org-goto-exit-command 'right)
7618 (throw 'exit nil))
7619 (user-error "Not on a heading")))
7621 (defun org-goto-quit ()
7622 "Finish `org-goto' without cursor motion."
7623 (interactive)
7624 (setq org-goto-selected-point nil)
7625 (setq org-goto-exit-command 'quit)
7626 (throw 'exit nil))
7628 ;;; Indirect buffer display of subtrees
7630 (defvar org-indirect-dedicated-frame nil
7631 "This is the frame being used for indirect tree display.")
7632 (defvar org-last-indirect-buffer nil)
7634 (defun org-tree-to-indirect-buffer (&optional arg)
7635 "Create indirect buffer and narrow it to current subtree.
7636 With a numerical prefix ARG, go up to this level and then take that tree.
7637 If ARG is negative, go up that many levels.
7639 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7640 indirect buffer previously made with this command, to avoid proliferation of
7641 indirect buffers. However, when you call the command with a \
7642 \\[universal-argument] prefix, or
7643 when `org-indirect-buffer-display' is `new-frame', the last buffer
7644 is kept so that you can work with several indirect buffers at the same time.
7645 If `org-indirect-buffer-display' is `dedicated-frame', the \
7646 \\[universal-argument] prefix also
7647 requests that a new frame be made for the new buffer, so that the dedicated
7648 frame is not changed."
7649 (interactive "P")
7650 (let ((cbuf (current-buffer))
7651 (cwin (selected-window))
7652 (pos (point))
7653 beg end level heading ibuf)
7654 (save-excursion
7655 (org-back-to-heading t)
7656 (when (numberp arg)
7657 (setq level (org-outline-level))
7658 (when (< arg 0) (setq arg (+ level arg)))
7659 (while (> (setq level (org-outline-level)) arg)
7660 (org-up-heading-safe)))
7661 (setq beg (point)
7662 heading (org-get-heading 'no-tags))
7663 (org-end-of-subtree t t)
7664 (when (org-at-heading-p) (backward-char 1))
7665 (setq end (point)))
7666 (when (and (buffer-live-p org-last-indirect-buffer)
7667 (not (eq org-indirect-buffer-display 'new-frame))
7668 (not arg))
7669 (kill-buffer org-last-indirect-buffer))
7670 (setq ibuf (org-get-indirect-buffer cbuf heading)
7671 org-last-indirect-buffer ibuf)
7672 (cond
7673 ((or (eq org-indirect-buffer-display 'new-frame)
7674 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7675 (select-frame (make-frame))
7676 (delete-other-windows)
7677 (org-pop-to-buffer-same-window ibuf)
7678 (org-set-frame-title heading))
7679 ((eq org-indirect-buffer-display 'dedicated-frame)
7680 (raise-frame
7681 (select-frame (or (and org-indirect-dedicated-frame
7682 (frame-live-p org-indirect-dedicated-frame)
7683 org-indirect-dedicated-frame)
7684 (setq org-indirect-dedicated-frame (make-frame)))))
7685 (delete-other-windows)
7686 (org-pop-to-buffer-same-window ibuf)
7687 (org-set-frame-title (concat "Indirect: " heading)))
7688 ((eq org-indirect-buffer-display 'current-window)
7689 (org-pop-to-buffer-same-window ibuf))
7690 ((eq org-indirect-buffer-display 'other-window)
7691 (pop-to-buffer ibuf))
7692 (t (error "Invalid value")))
7693 (narrow-to-region beg end)
7694 (outline-show-all)
7695 (goto-char pos)
7696 (run-hook-with-args 'org-cycle-hook 'all)
7697 (and (window-live-p cwin) (select-window cwin))))
7699 (defun org-get-indirect-buffer (&optional buffer heading)
7700 (setq buffer (or buffer (current-buffer)))
7701 (let ((n 1) (base (buffer-name buffer)) bname)
7702 (while (buffer-live-p
7703 (get-buffer
7704 (setq bname
7705 (concat base "-"
7706 (if heading (concat heading "-" (number-to-string n))
7707 (number-to-string n))))))
7708 (setq n (1+ n)))
7709 (condition-case nil
7710 (make-indirect-buffer buffer bname 'clone)
7711 (error (make-indirect-buffer buffer bname)))))
7713 (defun org-set-frame-title (title)
7714 "Set the title of the current frame to the string TITLE."
7715 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7717 ;;;; Structure editing
7719 ;;; Inserting headlines
7721 (defun org--line-empty-p (n)
7722 "Is the Nth next line empty?
7724 Counts the current line as N = 1 and the previous line as N = 0;
7725 see `beginning-of-line'."
7726 (save-excursion
7727 (and (not (bobp))
7728 (or (beginning-of-line n) t)
7729 (save-match-data
7730 (looking-at "[ \t]*$")))))
7732 (defun org-previous-line-empty-p ()
7733 "Is the previous line a blank line?
7734 When NEXT is non-nil, check the next line instead."
7735 (org--line-empty-p 0))
7737 (defun org-next-line-empty-p ()
7738 "Is the previous line a blank line?
7739 When NEXT is non-nil, check the next line instead."
7740 (org--line-empty-p 2))
7742 (defun org-insert-heading (&optional arg invisible-ok top)
7743 "Insert a new heading or an item with the same depth at point.
7745 If point is at the beginning of a heading or a list item, insert
7746 a new heading or a new item above the current one. If point is
7747 at the beginning of a normal line, turn the line into a heading.
7749 If point is in the middle of a headline or a list item, split the
7750 headline or the item and create a new headline/item with the text
7751 in the current line after point \(see `org-M-RET-may-split-line'
7752 on how to modify this behavior).
7754 With one universal prefix argument, set the user option
7755 `org-insert-heading-respect-content' to t for the duration of
7756 the command. This modifies the behavior described above in this
7757 ways: on list items and at the beginning of normal lines, force
7758 the insertion of a heading after the current subtree.
7760 With two universal prefix arguments, insert the heading at the
7761 end of the grandparent subtree. For example, if point is within
7762 a 2nd-level heading, then it will insert a 2nd-level heading at
7763 the end of the 1st-level parent heading.
7765 If point is at the beginning of a headline, insert a sibling
7766 before the current headline. If point is not at the beginning,
7767 split the line and create a new headline with the text in the
7768 current line after point \(see `org-M-RET-may-split-line' on how
7769 to modify this behavior).
7771 If point is at the beginning of a normal line, turn this line
7772 into a heading.
7774 When INVISIBLE-OK is set, stop at invisible headlines when going
7775 back. This is important for non-interactive uses of the
7776 command.
7778 When optional argument TOP is non-nil, insert a level 1 heading,
7779 unconditionally."
7780 (interactive "P")
7781 (when (org-called-interactively-p 'any) (org-reveal))
7782 (let ((itemp (and (not top) (org-in-item-p)))
7783 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7784 (respect-content (or org-insert-heading-respect-content
7785 (equal arg '(4))))
7786 (initial-content ""))
7788 (cond
7790 ((or (= (buffer-size) 0)
7791 (and (not (save-excursion
7792 (and (ignore-errors (org-back-to-heading invisible-ok))
7793 (org-at-heading-p))))
7794 (or arg (not itemp))))
7795 ;; At beginning of buffer or so high up that only a heading
7796 ;; makes sense.
7797 (cond ((and (bolp) (not respect-content)) (insert "* "))
7798 ((not respect-content)
7799 (unless may-split (end-of-line))
7800 (insert "\n* "))
7801 ((re-search-forward org-outline-regexp-bol nil t)
7802 (beginning-of-line)
7803 (insert "* \n")
7804 (backward-char))
7805 (t (goto-char (point-max))
7806 (insert "\n* ")))
7807 (run-hooks 'org-insert-heading-hook))
7809 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7812 ;; Maybe move at the end of the subtree
7813 (when (equal arg '(16))
7814 (org-up-heading-safe)
7815 (org-end-of-subtree t))
7816 ;; Insert a heading
7817 (save-restriction
7818 (widen)
7819 (let* ((level nil)
7820 (on-heading (org-at-heading-p))
7821 (empty-line-p (if on-heading
7822 (org-previous-line-empty-p)
7823 ;; We will decide later
7824 nil))
7825 ;; Get a level string to fall back on.
7826 (fix-level
7827 (if (org-before-first-heading-p) "*"
7828 (save-excursion
7829 (org-back-to-heading t)
7830 (when (org-previous-line-empty-p) (setq empty-line-p t))
7831 (looking-at org-outline-regexp)
7832 (make-string (1- (length (match-string 0))) ?*))))
7833 (stars
7834 (save-excursion
7835 (condition-case nil
7836 (if top "* "
7837 (org-back-to-heading invisible-ok)
7838 (when (and (not on-heading)
7839 (featurep 'org-inlinetask)
7840 (integerp org-inlinetask-min-level)
7841 (>= (length (match-string 0))
7842 org-inlinetask-min-level))
7843 ;; Find a heading level before the inline
7844 ;; task.
7845 (while (and (setq level (org-up-heading-safe))
7846 (>= level org-inlinetask-min-level)))
7847 (if (org-at-heading-p)
7848 (org-back-to-heading invisible-ok)
7849 (error "This should not happen")))
7850 (unless (and (save-excursion
7851 (save-match-data
7852 (org-backward-heading-same-level
7853 1 invisible-ok))
7854 (= (point) (match-beginning 0)))
7855 (not (org-next-line-empty-p)))
7856 (setq empty-line-p (or empty-line-p
7857 (org-previous-line-empty-p))))
7858 (match-string 0))
7859 (error (or fix-level "* ")))))
7860 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7861 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7863 ;; If we insert after content, move there and clean up
7864 ;; whitespace.
7865 (when (and respect-content
7866 (not (looking-at-p org-outline-regexp-bol)))
7867 (if (not (org-before-first-heading-p))
7868 (org-end-of-subtree nil t)
7869 (re-search-forward org-outline-regexp-bol)
7870 (beginning-of-line 0))
7871 (skip-chars-backward " \r\t\n")
7872 (and (not (looking-back "^\\*+" (line-beginning-position)))
7873 (looking-at "[ \t]+") (replace-match ""))
7874 (unless (eobp) (forward-char 1))
7875 (when (looking-at "^\\*")
7876 (unless (bobp) (backward-char 1))
7877 (insert "\n")))
7879 ;; If we are splitting, grab the text that should be moved
7880 ;; to the new headline.
7881 (when may-split
7882 (if (org-at-heading-p)
7883 ;; This is a heading: split intelligently (keeping
7884 ;; tags).
7885 (let ((pos (point)))
7886 (beginning-of-line)
7887 (unless (looking-at org-complex-heading-regexp)
7888 (error "This should not happen"))
7889 (when (and (match-beginning 4)
7890 (> pos (match-beginning 4))
7891 (< pos (match-end 4)))
7892 (setq initial-content (buffer-substring pos (match-end 4)))
7893 (goto-char pos)
7894 (delete-region (point) (match-end 4))
7895 (if (looking-at "[ \t]*$")
7896 (replace-match "")
7897 (insert (make-string (length initial-content) ?\s)))
7898 (setq initial-content (org-trim initial-content)))
7899 (goto-char pos))
7900 ;; A normal line.
7901 (setq initial-content
7902 (org-trim
7903 (delete-and-extract-region (point) (line-end-position))))))
7905 ;; If we are at the beginning of the line, insert before it.
7906 ;; Otherwise, after it.
7907 (cond
7908 ((and (bolp) (looking-at "[ \t]*$")))
7909 ((bolp) (save-excursion (insert "\n")))
7910 (t (end-of-line)
7911 (insert "\n")))
7913 ;; Insert the new heading
7914 (insert stars)
7915 (just-one-space)
7916 (insert initial-content)
7917 (unless (and blank (org-previous-line-empty-p))
7918 (org-N-empty-lines-before-current (if blank 1 0)))
7919 ;; Adjust visibility, which may be messed up if we removed
7920 ;; blank lines while previous entry was hidden.
7921 (let ((bol (line-beginning-position)))
7922 (dolist (o (overlays-at (1- bol)))
7923 (when (and (eq (overlay-get o 'invisible) 'outline)
7924 (eq (overlay-end o) bol))
7925 (move-overlay o (overlay-start o) (1- bol)))))
7926 (run-hooks 'org-insert-heading-hook)))))))
7928 (defun org-N-empty-lines-before-current (N)
7929 "Make the number of empty lines before current exactly N.
7930 So this will delete or add empty lines."
7931 (save-excursion
7932 (beginning-of-line)
7933 (let ((p (point)))
7934 (skip-chars-backward " \r\t\n")
7935 (unless (bolp) (forward-line))
7936 (delete-region (point) p))
7937 (when (> N 0) (insert (make-string N ?\n)))))
7939 (defun org-get-heading (&optional no-tags no-todo)
7940 "Return the heading of the current entry, without the stars.
7941 When NO-TAGS is non-nil, don't include tags.
7942 When NO-TODO is non-nil, don't include TODO keywords."
7943 (save-excursion
7944 (org-back-to-heading t)
7945 (cond
7946 ((and no-tags no-todo)
7947 (looking-at org-complex-heading-regexp)
7948 (match-string 4))
7949 (no-tags
7950 (looking-at (concat org-outline-regexp
7951 "\\(.*?\\)"
7952 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7953 (match-string 1))
7954 (no-todo
7955 (looking-at org-todo-line-regexp)
7956 (match-string 3))
7957 (t (looking-at org-heading-regexp)
7958 (match-string 2)))))
7960 (defvar orgstruct-mode) ; defined below
7962 (defun org-heading-components ()
7963 "Return the components of the current heading.
7964 This is a list with the following elements:
7965 - the level as an integer
7966 - the reduced level, different if `org-odd-levels-only' is set.
7967 - the TODO keyword, or nil
7968 - the priority character, like ?A, or nil if no priority is given
7969 - the headline text itself, or the tags string if no headline text
7970 - the tags string, or nil."
7971 (save-excursion
7972 (org-back-to-heading t)
7973 (when (let (case-fold-search)
7974 (looking-at
7975 (if orgstruct-mode
7976 org-heading-regexp
7977 org-complex-heading-regexp)))
7978 (if orgstruct-mode
7979 (list (length (match-string 1))
7980 (org-reduced-level (length (match-string 1)))
7983 (match-string 2)
7984 nil)
7985 (list (length (match-string 1))
7986 (org-reduced-level (length (match-string 1)))
7987 (match-string-no-properties 2)
7988 (and (match-end 3) (aref (match-string 3) 2))
7989 (match-string-no-properties 4)
7990 (match-string-no-properties 5))))))
7992 (defun org-get-entry ()
7993 "Get the entry text, after heading, entire subtree."
7994 (save-excursion
7995 (org-back-to-heading t)
7996 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7998 (defun org-edit-headline (&optional heading)
7999 "Edit the current headline.
8000 Set it to HEADING when provided."
8001 (interactive)
8002 (org-with-wide-buffer
8003 (org-back-to-heading t)
8004 (when (looking-at org-complex-heading-regexp)
8005 (let* ((old (match-string-no-properties 4))
8006 (new (save-match-data
8007 (org-trim (or heading (read-string "Edit: " old))))))
8008 (unless (equal old new)
8009 (if old (replace-match new t t nil 4)
8010 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8011 (insert " " new))
8012 (org-set-tags nil t)
8013 (when (looking-at "[ \t]*$") (replace-match "")))))))
8015 (defun org-insert-heading-after-current ()
8016 "Insert a new heading with same level as current, after current subtree."
8017 (interactive)
8018 (org-back-to-heading)
8019 (org-insert-heading)
8020 (org-move-subtree-down)
8021 (end-of-line 1))
8023 (defun org-insert-heading-respect-content (&optional invisible-ok)
8024 "Insert heading with `org-insert-heading-respect-content' set to t."
8025 (interactive)
8026 (org-insert-heading '(4) invisible-ok))
8028 (defun org-insert-todo-heading-respect-content (&optional force-state)
8029 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8030 (interactive)
8031 (org-insert-todo-heading force-state '(4)))
8033 (defun org-insert-todo-heading (arg &optional force-heading)
8034 "Insert a new heading with the same level and TODO state as current heading.
8035 If the heading has no TODO state, or if the state is DONE, use the first
8036 state (TODO by default). Also with one prefix arg, force first state. With
8037 two prefix args, force inserting at the end of the parent subtree."
8038 (interactive "P")
8039 (when (or force-heading (not (org-insert-item 'checkbox)))
8040 (org-insert-heading (or (and (equal arg '(16)) '(16))
8041 force-heading))
8042 (save-excursion
8043 (org-back-to-heading)
8044 (outline-previous-heading)
8045 (looking-at org-todo-line-regexp))
8046 (let*
8047 ((new-mark-x
8048 (if (or (equal arg '(4))
8049 (not (match-beginning 2))
8050 (member (match-string 2) org-done-keywords))
8051 (car org-todo-keywords-1)
8052 (match-string 2)))
8053 (new-mark
8055 (run-hook-with-args-until-success
8056 'org-todo-get-default-hook new-mark-x nil)
8057 new-mark-x)))
8058 (beginning-of-line 1)
8059 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8060 (if org-treat-insert-todo-heading-as-state-change
8061 (org-todo new-mark)
8062 (insert new-mark " "))))
8063 (when org-provide-todo-statistics
8064 (org-update-parent-todo-statistics))))
8066 (defun org-insert-subheading (arg)
8067 "Insert a new subheading and demote it.
8068 Works for outline headings and for plain lists alike."
8069 (interactive "P")
8070 (org-insert-heading arg)
8071 (cond
8072 ((org-at-heading-p) (org-do-demote))
8073 ((org-at-item-p) (org-indent-item))))
8075 (defun org-insert-todo-subheading (arg)
8076 "Insert a new subheading with TODO keyword or checkbox and demote it.
8077 Works for outline headings and for plain lists alike."
8078 (interactive "P")
8079 (org-insert-todo-heading arg)
8080 (cond
8081 ((org-at-heading-p) (org-do-demote))
8082 ((org-at-item-p) (org-indent-item))))
8084 ;;; Promotion and Demotion
8086 (defvar org-after-demote-entry-hook nil
8087 "Hook run after an entry has been demoted.
8088 The cursor will be at the beginning of the entry.
8089 When a subtree is being demoted, the hook will be called for each node.")
8091 (defvar org-after-promote-entry-hook nil
8092 "Hook run after an entry has been promoted.
8093 The cursor will be at the beginning of the entry.
8094 When a subtree is being promoted, the hook will be called for each node.")
8096 (defun org-promote-subtree ()
8097 "Promote the entire subtree.
8098 See also `org-promote'."
8099 (interactive)
8100 (save-excursion
8101 (org-with-limited-levels (org-map-tree 'org-promote)))
8102 (org-fix-position-after-promote))
8104 (defun org-demote-subtree ()
8105 "Demote the entire subtree.
8106 See `org-demote' and `org-promote'."
8107 (interactive)
8108 (save-excursion
8109 (org-with-limited-levels (org-map-tree 'org-demote)))
8110 (org-fix-position-after-promote))
8112 (defun org-do-promote ()
8113 "Promote the current heading higher up the tree.
8114 If the region is active in `transient-mark-mode', promote all
8115 headings in the region."
8116 (interactive)
8117 (save-excursion
8118 (if (org-region-active-p)
8119 (org-map-region 'org-promote (region-beginning) (region-end))
8120 (org-promote)))
8121 (org-fix-position-after-promote))
8123 (defun org-do-demote ()
8124 "Demote the current heading lower down the tree.
8125 If the region is active in `transient-mark-mode', demote all
8126 headings in the region."
8127 (interactive)
8128 (save-excursion
8129 (if (org-region-active-p)
8130 (org-map-region 'org-demote (region-beginning) (region-end))
8131 (org-demote)))
8132 (org-fix-position-after-promote))
8134 (defun org-fix-position-after-promote ()
8135 "Fix cursor position and indentation after demoting/promoting."
8136 (let ((pos (point)))
8137 (when (save-excursion
8138 (beginning-of-line 1)
8139 (looking-at org-todo-line-regexp)
8140 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8141 (cond ((eobp) (insert " "))
8142 ((eolp) (insert " "))
8143 ((equal (char-after) ?\ ) (forward-char 1))))))
8145 (defun org-current-level ()
8146 "Return the level of the current entry, or nil if before the first headline.
8147 The level is the number of stars at the beginning of the
8148 headline. Use `org-reduced-level' to remove the effect of
8149 `org-odd-levels'. Unlike to `org-outline-level', this function
8150 ignores inlinetasks."
8151 (let ((level (org-with-limited-levels (org-outline-level))))
8152 (and (> level 0) level)))
8154 (defun org-get-previous-line-level ()
8155 "Return the outline depth of the last headline before the current line.
8156 Returns 0 for the first headline in the buffer, and nil if before the
8157 first headline."
8158 (and (org-current-level)
8159 (or (and (/= (line-beginning-position) (point-min))
8160 (save-excursion (beginning-of-line 0) (org-current-level)))
8161 0)))
8163 (defun org-reduced-level (l)
8164 "Compute the effective level of a heading.
8165 This takes into account the setting of `org-odd-levels-only'."
8166 (cond
8167 ((zerop l) 0)
8168 (org-odd-levels-only (1+ (floor (/ l 2))))
8169 (t l)))
8171 (defun org-level-increment ()
8172 "Return the number of stars that will be added or removed at a
8173 time to headlines when structure editing, based on the value of
8174 `org-odd-levels-only'."
8175 (if org-odd-levels-only 2 1))
8177 (defun org-get-valid-level (level &optional change)
8178 "Rectify a level change under the influence of `org-odd-levels-only'
8179 LEVEL is a current level, CHANGE is by how much the level should be
8180 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8181 even level numbers will become the next higher odd number."
8182 (if org-odd-levels-only
8183 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8184 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8185 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8186 (max 1 (+ level (or change 0)))))
8187 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8189 (defun org-promote ()
8190 "Promote the current heading higher up the tree."
8191 (org-with-wide-buffer
8192 (org-back-to-heading t)
8193 (let* ((after-change-functions (remq 'flyspell-after-change-function
8194 after-change-functions))
8195 (level (save-match-data (funcall outline-level)))
8196 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8197 (diff (abs (- level (length up-head) -1))))
8198 (cond
8199 ((and (= level 1) org-allow-promoting-top-level-subtree)
8200 (replace-match "# " nil t))
8201 ((= level 1)
8202 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8203 (t (replace-match up-head nil t)))
8204 (unless (= level 1)
8205 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8206 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8207 (run-hooks 'org-after-promote-entry-hook))))
8209 (defun org-demote ()
8210 "Demote the current heading lower down the tree."
8211 (org-with-wide-buffer
8212 (org-back-to-heading t)
8213 (let* ((after-change-functions (remq 'flyspell-after-change-function
8214 after-change-functions))
8215 (level (save-match-data (funcall outline-level)))
8216 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8217 (diff (abs (- level (length down-head) -1))))
8218 (replace-match down-head nil t)
8219 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8220 (when org-adapt-indentation (org-fixup-indentation diff))
8221 (run-hooks 'org-after-demote-entry-hook))))
8223 (defun org-cycle-level ()
8224 "Cycle the level of an empty headline through possible states.
8225 This goes first to child, then to parent, level, then up the hierarchy.
8226 After top level, it switches back to sibling level."
8227 (interactive)
8228 (let ((org-adapt-indentation nil))
8229 (when (org-point-at-end-of-empty-headline)
8230 (setq this-command 'org-cycle-level) ; Only needed for caching
8231 (let ((cur-level (org-current-level))
8232 (prev-level (org-get-previous-line-level)))
8233 (cond
8234 ;; If first headline in file, promote to top-level.
8235 ((= prev-level 0)
8236 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8237 do (org-do-promote)))
8238 ;; If same level as prev, demote one.
8239 ((= prev-level cur-level)
8240 (org-do-demote))
8241 ;; If parent is top-level, promote to top level if not already.
8242 ((= prev-level 1)
8243 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8244 do (org-do-promote)))
8245 ;; If top-level, return to prev-level.
8246 ((= cur-level 1)
8247 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8248 do (org-do-demote)))
8249 ;; If less than prev-level, promote one.
8250 ((< cur-level prev-level)
8251 (org-do-promote))
8252 ;; If deeper than prev-level, promote until higher than
8253 ;; prev-level.
8254 ((> cur-level prev-level)
8255 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8256 do (org-do-promote))))
8257 t))))
8259 (defun org-map-tree (fun)
8260 "Call FUN for every heading underneath the current one."
8261 (org-back-to-heading)
8262 (let ((level (funcall outline-level)))
8263 (save-excursion
8264 (funcall fun)
8265 (while (and (progn
8266 (outline-next-heading)
8267 (> (funcall outline-level) level))
8268 (not (eobp)))
8269 (funcall fun)))))
8271 (defun org-map-region (fun beg end)
8272 "Call FUN for every heading between BEG and END."
8273 (let ((org-ignore-region t))
8274 (save-excursion
8275 (setq end (copy-marker end))
8276 (goto-char beg)
8277 (when (and (re-search-forward org-outline-regexp-bol nil t)
8278 (< (point) end))
8279 (funcall fun))
8280 (while (and (progn
8281 (outline-next-heading)
8282 (< (point) end))
8283 (not (eobp)))
8284 (funcall fun)))))
8286 (defun org-fixup-indentation (diff)
8287 "Change the indentation in the current entry by DIFF.
8289 DIFF is an integer. Indentation is done according to the
8290 following rules:
8292 - Planning information and property drawers are always indented
8293 according to the new level of the headline;
8295 - Footnote definitions and their contents are ignored;
8297 - Inlinetasks' boundaries are not shifted;
8299 - Empty lines are ignored;
8301 - Other lines' indentation are shifted by DIFF columns, unless
8302 it would introduce a structural change in the document, in
8303 which case no shifting is done at all.
8305 Assume point is at a heading or an inlinetask beginning."
8306 (org-with-wide-buffer
8307 (narrow-to-region (line-beginning-position)
8308 (save-excursion
8309 (if (org-with-limited-levels (org-at-heading-p))
8310 (org-with-limited-levels (outline-next-heading))
8311 (org-inlinetask-goto-end))
8312 (point)))
8313 (forward-line)
8314 ;; Indent properly planning info and property drawer.
8315 (when (looking-at-p org-planning-line-re)
8316 (org-indent-line)
8317 (forward-line))
8318 (when (looking-at org-property-drawer-re)
8319 (goto-char (match-end 0))
8320 (forward-line)
8321 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8322 (catch 'no-shift
8323 (when (zerop diff) (throw 'no-shift nil))
8324 ;; If DIFF is negative, first check if a shift is possible at all
8325 ;; (e.g., it doesn't break structure). This can only happen if
8326 ;; some contents are not properly indented.
8327 (let ((case-fold-search t))
8328 (when (< diff 0)
8329 (let ((diff (- diff))
8330 (forbidden-re (concat org-outline-regexp
8331 "\\|"
8332 (substring org-footnote-definition-re 1))))
8333 (save-excursion
8334 (while (not (eobp))
8335 (cond
8336 ((looking-at-p "[ \t]*$") (forward-line))
8337 ((and (looking-at-p org-footnote-definition-re)
8338 (let ((e (org-element-at-point)))
8339 (and (eq (org-element-type e) 'footnote-definition)
8340 (goto-char (org-element-property :end e))))))
8341 ((looking-at-p org-outline-regexp) (forward-line))
8342 ;; Give up if shifting would move before column 0 or
8343 ;; if it would introduce a headline or a footnote
8344 ;; definition.
8346 (skip-chars-forward " \t")
8347 (let ((ind (current-column)))
8348 (when (or (< ind diff)
8349 (and (= ind diff) (looking-at-p forbidden-re)))
8350 (throw 'no-shift nil)))
8351 ;; Ignore contents of example blocks and source
8352 ;; blocks if their indentation is meant to be
8353 ;; preserved. Jump to block's closing line.
8354 (beginning-of-line)
8355 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8356 (let ((e (org-element-at-point)))
8357 (and (memq (org-element-type e)
8358 '(example-block src-block))
8359 (or org-src-preserve-indentation
8360 (org-element-property :preserve-indent e))
8361 (goto-char (org-element-property :end e))
8362 (progn (skip-chars-backward " \r\t\n")
8363 (beginning-of-line)
8364 t))))
8365 (forward-line))))))))
8366 ;; Shift lines but footnote definitions, inlinetasks boundaries
8367 ;; by DIFF. Also skip contents of source or example blocks
8368 ;; when indentation is meant to be preserved.
8369 (while (not (eobp))
8370 (cond
8371 ((and (looking-at-p org-footnote-definition-re)
8372 (let ((e (org-element-at-point)))
8373 (and (eq (org-element-type e) 'footnote-definition)
8374 (goto-char (org-element-property :end e))))))
8375 ((looking-at-p org-outline-regexp) (forward-line))
8376 ((looking-at-p "[ \t]*$") (forward-line))
8378 (indent-line-to (+ (org-get-indentation) diff))
8379 (beginning-of-line)
8380 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8381 (let ((e (org-element-at-point)))
8382 (and (memq (org-element-type e)
8383 '(example-block src-block))
8384 (or org-src-preserve-indentation
8385 (org-element-property :preserve-indent e))
8386 (goto-char (org-element-property :end e))
8387 (progn (skip-chars-backward " \r\t\n")
8388 (beginning-of-line)
8389 t))))
8390 (forward-line)))))))))
8392 (defun org-convert-to-odd-levels ()
8393 "Convert an org-mode file with all levels allowed to one with odd levels.
8394 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8395 level 5 etc."
8396 (interactive)
8397 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8398 (let ((outline-level 'org-outline-level)
8399 (org-odd-levels-only nil) n)
8400 (save-excursion
8401 (goto-char (point-min))
8402 (while (re-search-forward "^\\*\\*+ " nil t)
8403 (setq n (- (length (match-string 0)) 2))
8404 (while (>= (setq n (1- n)) 0)
8405 (org-demote))
8406 (end-of-line 1))))))
8408 (defun org-convert-to-oddeven-levels ()
8409 "Convert an org-mode file with only odd levels to one with odd/even levels.
8410 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8411 file contains a section with an even level, conversion would
8412 destroy the structure of the file. An error is signaled in this
8413 case."
8414 (interactive)
8415 (goto-char (point-min))
8416 ;; First check if there are no even levels
8417 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8418 (org-show-set-visibility 'canonical)
8419 (error "Not all levels are odd in this file. Conversion not possible"))
8420 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8421 (let ((outline-regexp org-outline-regexp)
8422 (outline-level 'org-outline-level)
8423 (org-odd-levels-only nil) n)
8424 (save-excursion
8425 (goto-char (point-min))
8426 (while (re-search-forward "^\\*\\*+ " nil t)
8427 (setq n (/ (1- (length (match-string 0))) 2))
8428 (while (>= (setq n (1- n)) 0)
8429 (org-promote))
8430 (end-of-line 1))))))
8432 (defun org-tr-level (n)
8433 "Make N odd if required."
8434 (if org-odd-levels-only (1+ (/ n 2)) n))
8436 ;;; Vertical tree motion, cutting and pasting of subtrees
8438 (defun org-move-subtree-up (&optional arg)
8439 "Move the current subtree up past ARG headlines of the same level."
8440 (interactive "p")
8441 (org-move-subtree-down (- (prefix-numeric-value arg))))
8443 (defun org-move-subtree-down (&optional arg)
8444 "Move the current subtree down past ARG headlines of the same level."
8445 (interactive "p")
8446 (setq arg (prefix-numeric-value arg))
8447 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8448 'org-get-last-sibling))
8449 (ins-point (make-marker))
8450 (cnt (abs arg))
8451 (col (current-column))
8452 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8453 ;; Select the tree
8454 (org-back-to-heading)
8455 (setq beg0 (point))
8456 (save-excursion
8457 (setq ne-beg (org-back-over-empty-lines))
8458 (setq beg (point)))
8459 (save-match-data
8460 (save-excursion (outline-end-of-heading)
8461 (setq folded (outline-invisible-p)))
8462 (progn (org-end-of-subtree nil t)
8463 (unless (eobp) (backward-char))))
8464 (outline-next-heading)
8465 (setq ne-end (org-back-over-empty-lines))
8466 (setq end (point))
8467 (goto-char beg0)
8468 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8469 ;; include less whitespace
8470 (save-excursion
8471 (goto-char beg)
8472 (forward-line (- ne-beg ne-end))
8473 (setq beg (point))))
8474 ;; Find insertion point, with error handling
8475 (while (> cnt 0)
8476 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8477 (progn (goto-char beg0)
8478 (user-error "Cannot move past superior level or buffer limit")))
8479 (setq cnt (1- cnt)))
8480 (when (> arg 0)
8481 ;; Moving forward - still need to move over subtree
8482 (org-end-of-subtree t t)
8483 (save-excursion
8484 (org-back-over-empty-lines)
8485 (or (bolp) (newline))))
8486 (setq ne-ins (org-back-over-empty-lines))
8487 (move-marker ins-point (point))
8488 (setq txt (buffer-substring beg end))
8489 (org-save-markers-in-region beg end)
8490 (delete-region beg end)
8491 (org-remove-empty-overlays-at beg)
8492 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8493 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8494 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8495 (let ((bbb (point)))
8496 (insert-before-markers txt)
8497 (org-reinstall-markers-in-region bbb)
8498 (move-marker ins-point bbb))
8499 (or (bolp) (insert "\n"))
8500 (setq ins-end (point))
8501 (goto-char ins-point)
8502 (org-skip-whitespace)
8503 (when (and (< arg 0)
8504 (org-first-sibling-p)
8505 (> ne-ins ne-beg))
8506 ;; Move whitespace back to beginning
8507 (save-excursion
8508 (goto-char ins-end)
8509 (let ((kill-whole-line t))
8510 (kill-line (- ne-ins ne-beg)) (point)))
8511 (insert (make-string (- ne-ins ne-beg) ?\n)))
8512 (move-marker ins-point nil)
8513 (if folded
8514 (outline-hide-subtree)
8515 (org-show-entry)
8516 (org-show-children)
8517 (org-cycle-hide-drawers 'children))
8518 (org-clean-visibility-after-subtree-move)
8519 ;; move back to the initial column we were at
8520 (move-to-column col)))
8522 (defvar org-subtree-clip ""
8523 "Clipboard for cut and paste of subtrees.
8524 This is actually only a copy of the kill, because we use the normal kill
8525 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8527 (defvar org-subtree-clip-folded nil
8528 "Was the last copied subtree folded?
8529 This is used to fold the tree back after pasting.")
8531 (defun org-cut-subtree (&optional n)
8532 "Cut the current subtree into the clipboard.
8533 With prefix arg N, cut this many sequential subtrees.
8534 This is a short-hand for marking the subtree and then cutting it."
8535 (interactive "p")
8536 (org-copy-subtree n 'cut))
8538 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8539 "Copy the current subtree it in the clipboard.
8540 With prefix arg N, copy this many sequential subtrees.
8541 This is a short-hand for marking the subtree and then copying it.
8542 If CUT is non-nil, actually cut the subtree.
8543 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8544 of some markers in the region, even if CUT is non-nil. This is
8545 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8546 (interactive "p")
8547 (let (beg end folded (beg0 (point)))
8548 (if (org-called-interactively-p 'any)
8549 (org-back-to-heading nil) ; take what looks like a subtree
8550 (org-back-to-heading t)) ; take what is really there
8551 (setq beg (point))
8552 (skip-chars-forward " \t\r\n")
8553 (save-match-data
8554 (if nosubtrees
8555 (outline-next-heading)
8556 (save-excursion (outline-end-of-heading)
8557 (setq folded (outline-invisible-p)))
8558 (ignore-errors (org-forward-heading-same-level (1- n) t))
8559 (org-end-of-subtree t t)))
8560 ;; Include the end of an inlinetask
8561 (when (and (featurep 'org-inlinetask)
8562 (looking-at-p (concat (org-inlinetask-outline-regexp)
8563 "END[ \t]*$")))
8564 (end-of-line))
8565 (setq end (point))
8566 (goto-char beg0)
8567 (when (> end beg)
8568 (setq org-subtree-clip-folded folded)
8569 (when (or cut force-store-markers)
8570 (org-save-markers-in-region beg end))
8571 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8572 (setq org-subtree-clip (current-kill 0))
8573 (message "%s: Subtree(s) with %d characters"
8574 (if cut "Cut" "Copied")
8575 (length org-subtree-clip)))))
8577 (defun org-paste-subtree (&optional level tree for-yank remove)
8578 "Paste the clipboard as a subtree, with modification of headline level.
8579 The entire subtree is promoted or demoted in order to match a new headline
8580 level.
8582 If the cursor is at the beginning of a headline, the same level as
8583 that headline is used to paste the tree.
8585 If not, the new level is derived from the *visible* headings
8586 before and after the insertion point, and taken to be the inferior headline
8587 level of the two. So if the previous visible heading is level 3 and the
8588 next is level 4 (or vice versa), level 4 will be used for insertion.
8589 This makes sure that the subtree remains an independent subtree and does
8590 not swallow low level entries.
8592 You can also force a different level, either by using a numeric prefix
8593 argument, or by inserting the heading marker by hand. For example, if the
8594 cursor is after \"*****\", then the tree will be shifted to level 5.
8596 If optional TREE is given, use this text instead of the kill ring.
8598 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8599 move back over whitespace before inserting, and move point to the end of
8600 the inserted text when done.
8602 When REMOVE is non-nil, remove the subtree from the clipboard."
8603 (interactive "P")
8604 (setq tree (or tree (and kill-ring (current-kill 0))))
8605 (unless (org-kill-is-subtree-p tree)
8606 (user-error "%s"
8607 (substitute-command-keys
8608 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8609 (org-with-limited-levels
8610 (let* ((visp (not (outline-invisible-p)))
8611 (txt tree)
8612 (^re_ "\\(\\*+\\)[ \t]*")
8613 (old-level (if (string-match org-outline-regexp-bol txt)
8614 (- (match-end 0) (match-beginning 0) 1)
8615 -1))
8616 (force-level (cond (level (prefix-numeric-value level))
8617 ((and (looking-at "[ \t]*$")
8618 (string-match
8619 "^\\*+$" (buffer-substring
8620 (point-at-bol) (point))))
8621 (- (match-end 0) (match-beginning 0)))
8622 ((and (bolp)
8623 (looking-at org-outline-regexp))
8624 (- (match-end 0) (point) 1))))
8625 (previous-level (save-excursion
8626 (condition-case nil
8627 (progn
8628 (outline-previous-visible-heading 1)
8629 (if (looking-at ^re_)
8630 (- (match-end 0) (match-beginning 0) 1)
8632 (error 1))))
8633 (next-level (save-excursion
8634 (condition-case nil
8635 (progn
8636 (or (looking-at org-outline-regexp)
8637 (outline-next-visible-heading 1))
8638 (if (looking-at ^re_)
8639 (- (match-end 0) (match-beginning 0) 1)
8641 (error 1))))
8642 (new-level (or force-level (max previous-level next-level)))
8643 (shift (if (or (= old-level -1)
8644 (= new-level -1)
8645 (= old-level new-level))
8647 (- new-level old-level)))
8648 (delta (if (> shift 0) -1 1))
8649 (func (if (> shift 0) 'org-demote 'org-promote))
8650 (org-odd-levels-only nil)
8651 beg end newend)
8652 ;; Remove the forced level indicator
8653 (when force-level
8654 (delete-region (point-at-bol) (point)))
8655 ;; Paste
8656 (beginning-of-line (if (bolp) 1 2))
8657 (setq beg (point))
8658 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8659 (insert-before-markers txt)
8660 (unless (string-match "\n\\'" txt) (insert "\n"))
8661 (setq newend (point))
8662 (org-reinstall-markers-in-region beg)
8663 (setq end (point))
8664 (goto-char beg)
8665 (skip-chars-forward " \t\n\r")
8666 (setq beg (point))
8667 (when (and (outline-invisible-p) visp)
8668 (save-excursion (outline-show-heading)))
8669 ;; Shift if necessary
8670 (unless (= shift 0)
8671 (save-restriction
8672 (narrow-to-region beg end)
8673 (while (not (= shift 0))
8674 (org-map-region func (point-min) (point-max))
8675 (setq shift (+ delta shift)))
8676 (goto-char (point-min))
8677 (setq newend (point-max))))
8678 (when (or (org-called-interactively-p 'interactive) for-yank)
8679 (message "Clipboard pasted as level %d subtree" new-level))
8680 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8681 kill-ring
8682 (eq org-subtree-clip (current-kill 0))
8683 org-subtree-clip-folded)
8684 ;; The tree was folded before it was killed/copied
8685 (outline-hide-subtree))
8686 (and for-yank (goto-char newend))
8687 (and remove (setq kill-ring (cdr kill-ring))))))
8689 (defun org-kill-is-subtree-p (&optional txt)
8690 "Check if the current kill is an outline subtree, or a set of trees.
8691 Returns nil if kill does not start with a headline, or if the first
8692 headline level is not the largest headline level in the tree.
8693 So this will actually accept several entries of equal levels as well,
8694 which is OK for `org-paste-subtree'.
8695 If optional TXT is given, check this string instead of the current kill."
8696 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8697 (re (org-get-limited-outline-regexp))
8698 (^re (concat "^" re))
8699 (start-level (and kill
8700 (string-match
8701 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8702 kill)
8703 (- (match-end 2) (match-beginning 2) 1)))
8704 (start (1+ (or (match-beginning 2) -1))))
8705 (if (not start-level)
8706 (progn
8707 nil) ;; does not even start with a heading
8708 (catch 'exit
8709 (while (setq start (string-match ^re kill (1+ start)))
8710 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8711 (throw 'exit nil)))
8712 t))))
8714 (defvar org-markers-to-move nil
8715 "Markers that should be moved with a cut-and-paste operation.
8716 Those markers are stored together with their positions relative to
8717 the start of the region.")
8719 (defun org-save-markers-in-region (beg end)
8720 "Check markers in region.
8721 If these markers are between BEG and END, record their position relative
8722 to BEG, so that after moving the block of text, we can put the markers back
8723 into place.
8724 This function gets called just before an entry or tree gets cut from the
8725 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8726 called immediately, to move the markers with the entries."
8727 (setq org-markers-to-move nil)
8728 (when (featurep 'org-clock)
8729 (org-clock-save-markers-for-cut-and-paste beg end))
8730 (when (featurep 'org-agenda)
8731 (org-agenda-save-markers-for-cut-and-paste beg end)))
8733 (defun org-check-and-save-marker (marker beg end)
8734 "Check if MARKER is between BEG and END.
8735 If yes, remember the marker and the distance to BEG."
8736 (when (and (marker-buffer marker)
8737 (equal (marker-buffer marker) (current-buffer))
8738 (>= marker beg) (< marker end))
8739 (push (cons marker (- marker beg)) org-markers-to-move)))
8741 (defun org-reinstall-markers-in-region (beg)
8742 "Move all remembered markers to their position relative to BEG."
8743 (dolist (x org-markers-to-move)
8744 (move-marker (car x) (+ beg (cdr x))))
8745 (setq org-markers-to-move nil))
8747 (defun org-narrow-to-subtree ()
8748 "Narrow buffer to the current subtree."
8749 (interactive)
8750 (save-excursion
8751 (save-match-data
8752 (org-with-limited-levels
8753 (narrow-to-region
8754 (progn (org-back-to-heading t) (point))
8755 (progn (org-end-of-subtree t t)
8756 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8757 (point)))))))
8759 (defun org-narrow-to-block ()
8760 "Narrow buffer to the current block."
8761 (interactive)
8762 (let* ((case-fold-search t)
8763 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8764 "^[ \t]*#\\+end_.*")))
8765 (if blockp
8766 (narrow-to-region (car blockp) (cdr blockp))
8767 (user-error "Not in a block"))))
8769 (defun org-clone-subtree-with-time-shift (n &optional shift)
8770 "Clone the task (subtree) at point N times.
8771 The clones will be inserted as siblings.
8773 In interactive use, the user will be prompted for the number of
8774 clones to be produced. If the entry has a timestamp, the user
8775 will also be prompted for a time shift, which may be a repeater
8776 as used in time stamps, for example `+3d'. To disable this,
8777 you can call the function with a universal prefix argument.
8779 When a valid repeater is given and the entry contains any time
8780 stamps, the clones will become a sequence in time, with time
8781 stamps in the subtree shifted for each clone produced. If SHIFT
8782 is nil or the empty string, time stamps will be left alone. The
8783 ID property of the original subtree is removed.
8785 If the original subtree did contain time stamps with a repeater,
8786 the following will happen:
8787 - the repeater will be removed in each clone
8788 - an additional clone will be produced, with the current, unshifted
8789 date(s) in the entry.
8790 - the original entry will be placed *after* all the clones, with
8791 repeater intact.
8792 - the start days in the repeater in the original entry will be shifted
8793 to past the last clone.
8794 In this way you can spell out a number of instances of a repeating task,
8795 and still retain the repeater to cover future instances of the task.
8797 As described above, N+1 clones are produced when the original
8798 subtree has a repeater. Setting N to 0, then, can be used to
8799 remove the repeater from a subtree and create a shifted clone
8800 with the original repeater."
8801 (interactive "nNumber of clones to produce: ")
8802 (let ((shift
8803 (or shift
8804 (if (and (not (equal current-prefix-arg '(4)))
8805 (save-excursion
8806 (re-search-forward org-ts-regexp-both
8807 (save-excursion
8808 (org-end-of-subtree t)
8809 (point)) t)))
8810 (read-from-minibuffer
8811 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8812 ""))) ;; No time shift
8813 (n-no-remove -1)
8814 (drawer-re org-drawer-regexp)
8815 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8816 beg end template task idprop
8817 shift-n shift-what doshift nmin nmax)
8818 (unless (wholenump n)
8819 (user-error "Invalid number of replications %s" n))
8820 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8821 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8822 shift)))
8823 (user-error "Invalid shift specification %s" shift))
8824 (when doshift
8825 (setq shift-n (string-to-number (match-string 1 shift))
8826 shift-what (cdr (assoc (match-string 2 shift)
8827 '(("d" . day) ("w" . week)
8828 ("m" . month) ("y" . year))))))
8829 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8830 (setq nmin 1 nmax n)
8831 (org-back-to-heading t)
8832 (setq beg (point))
8833 (setq idprop (org-entry-get nil "ID"))
8834 (org-end-of-subtree t t)
8835 (or (bolp) (insert "\n"))
8836 (setq end (point))
8837 (setq template (buffer-substring beg end))
8838 (when (and doshift
8839 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8840 (delete-region beg end)
8841 (setq end beg)
8842 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8843 (goto-char end)
8844 (cl-loop for n from nmin to nmax do
8845 ;; prepare clone
8846 (with-temp-buffer
8847 (insert template)
8848 (org-mode)
8849 (goto-char (point-min))
8850 (org-show-subtree)
8851 (and idprop (if org-clone-delete-id
8852 (org-entry-delete nil "ID")
8853 (org-id-get-create t)))
8854 (unless (= n 0)
8855 (while (re-search-forward org-clock-re nil t)
8856 (kill-whole-line))
8857 (goto-char (point-min))
8858 (while (re-search-forward drawer-re nil t)
8859 (org-remove-empty-drawer-at (point))))
8860 (goto-char (point-min))
8861 (when doshift
8862 (while (re-search-forward org-ts-regexp-both nil t)
8863 (org-timestamp-change (* n shift-n) shift-what))
8864 (unless (= n n-no-remove)
8865 (goto-char (point-min))
8866 (while (re-search-forward org-ts-regexp nil t)
8867 (save-excursion
8868 (goto-char (match-beginning 0))
8869 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8870 (delete-region (match-beginning 1) (match-end 1)))))))
8871 (setq task (buffer-string)))
8872 (insert task))
8873 (goto-char beg)))
8875 ;;; Outline Sorting
8877 (defun org-sort (with-case)
8878 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8879 Optional argument WITH-CASE means sort case-sensitively."
8880 (interactive "P")
8881 (cond
8882 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8883 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8885 (org-call-with-arg 'org-sort-entries with-case))))
8887 (defun org-sort-remove-invisible (s)
8888 "Remove invisible links from string S."
8889 (remove-text-properties 0 (length s) org-rm-props s)
8890 (while (string-match org-bracket-link-regexp s)
8891 (setq s (replace-match (if (match-end 2)
8892 (match-string 3 s)
8893 (match-string 1 s))
8894 t t s)))
8895 (let ((st (format " %s " s)))
8896 (while (string-match org-emph-re st)
8897 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8898 (setq s (substring st 1 -1)))
8901 (defvar org-priority-regexp) ; defined later in the file
8903 (defvar org-after-sorting-entries-or-items-hook nil
8904 "Hook that is run after a bunch of entries or items have been sorted.
8905 When children are sorted, the cursor is in the parent line when this
8906 hook gets called. When a region or a plain list is sorted, the cursor
8907 will be in the first entry of the sorted region/list.")
8909 (defun org-sort-entries
8910 (&optional with-case sorting-type getkey-func compare-func property)
8911 "Sort entries on a certain level of an outline tree.
8912 If there is an active region, the entries in the region are sorted.
8913 Else, if the cursor is before the first entry, sort the top-level items.
8914 Else, the children of the entry at point are sorted.
8916 Sorting can be alphabetically, numerically, by date/time as given by
8917 a time stamp, by a property, by priority order, or by a custom function.
8919 The command prompts for the sorting type unless it has been given to the
8920 function through the SORTING-TYPE argument, which needs to be a character,
8921 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8922 the precise meaning of each character:
8924 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8925 c By creation time, which is assumed to be the first inactive time stamp
8926 at the beginning of a line.
8927 d By deadline date/time.
8928 k By clocking time.
8929 n Numerically, by converting the beginning of the entry/item to a number.
8930 o By order of TODO keywords.
8931 p By priority according to the cookie.
8932 r By the value of a property.
8933 s By scheduled date/time.
8934 t By date/time, either the first active time stamp in the entry, or, if
8935 none exist, by the first inactive one.
8937 Capital letters will reverse the sort order.
8939 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8940 called with point at the beginning of the record. It must return either
8941 a string or a number that should serve as the sorting key for that record.
8943 Comparing entries ignores case by default. However, with an optional argument
8944 WITH-CASE, the sorting considers case as well.
8946 Sorting is done against the visible part of the headlines, it ignores hidden
8947 links.
8949 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8950 (interactive "P")
8951 (let ((case-func (if with-case 'identity 'downcase))
8952 (cmstr
8953 ;; The clock marker is lost when using `sort-subr', let's
8954 ;; store the clocking string.
8955 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8956 (save-excursion
8957 (goto-char org-clock-marker)
8958 (buffer-substring-no-properties (line-beginning-position)
8959 (point)))))
8960 start beg end stars re re2
8961 txt what tmp)
8962 ;; Find beginning and end of region to sort
8963 (cond
8964 ((org-region-active-p)
8965 ;; we will sort the region
8966 (setq end (region-end)
8967 what "region")
8968 (goto-char (region-beginning))
8969 (unless (org-at-heading-p) (outline-next-heading))
8970 (setq start (point)))
8971 ((or (org-at-heading-p)
8972 (ignore-errors (progn (org-back-to-heading) t)))
8973 ;; we will sort the children of the current headline
8974 (org-back-to-heading)
8975 (setq start (point)
8976 end (progn (org-end-of-subtree t t)
8977 (or (bolp) (insert "\n"))
8978 (when (>= (org-back-over-empty-lines) 1)
8979 (forward-line 1))
8980 (point))
8981 what "children")
8982 (goto-char start)
8983 (outline-show-subtree)
8984 (outline-next-heading))
8986 ;; we will sort the top-level entries in this file
8987 (goto-char (point-min))
8988 (or (org-at-heading-p) (outline-next-heading))
8989 (setq start (point))
8990 (goto-char (point-max))
8991 (beginning-of-line 1)
8992 (when (looking-at ".*?\\S-")
8993 ;; File ends in a non-white line
8994 (end-of-line 1)
8995 (insert "\n"))
8996 (setq end (point-max))
8997 (setq what "top-level")
8998 (goto-char start)
8999 (outline-show-all)))
9001 (setq beg (point))
9002 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9004 (looking-at "\\(\\*+\\)")
9005 (setq stars (match-string 1)
9006 re (concat "^" (regexp-quote stars) " +")
9007 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9008 txt (buffer-substring beg end))
9009 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9010 (when (and (not (equal stars "*")) (string-match re2 txt))
9011 (user-error "Region to sort contains a level above the first entry"))
9013 (unless sorting-type
9014 (message
9015 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9016 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9017 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9018 what)
9019 (setq sorting-type (read-char-exclusive))
9021 (unless getkey-func
9022 (and (= (downcase sorting-type) ?f)
9023 (setq getkey-func
9024 (completing-read "Sort using function: "
9025 obarray 'fboundp t nil nil))
9026 (setq getkey-func (intern getkey-func))))
9028 (and (= (downcase sorting-type) ?r)
9029 (not property)
9030 (setq property
9031 (completing-read "Property: "
9032 (mapcar #'list (org-buffer-property-keys t))
9033 nil t))))
9035 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9036 (message "Sorting entries...")
9038 (save-restriction
9039 (narrow-to-region start end)
9040 (let ((dcst (downcase sorting-type))
9041 (case-fold-search nil)
9042 (now (current-time)))
9043 (sort-subr
9044 (/= dcst sorting-type)
9045 ;; This function moves to the beginning character of the "record" to
9046 ;; be sorted.
9047 (lambda nil
9048 (if (re-search-forward re nil t)
9049 (goto-char (match-beginning 0))
9050 (goto-char (point-max))))
9051 ;; This function moves to the last character of the "record" being
9052 ;; sorted.
9053 (lambda nil
9054 (save-match-data
9055 (condition-case nil
9056 (outline-forward-same-level 1)
9057 (error
9058 (goto-char (point-max))))))
9059 ;; This function returns the value that gets sorted against.
9060 (lambda nil
9061 (cond
9062 ((= dcst ?n)
9063 (if (looking-at org-complex-heading-regexp)
9064 (string-to-number (org-sort-remove-invisible (match-string 4)))
9065 nil))
9066 ((= dcst ?a)
9067 (if (looking-at org-complex-heading-regexp)
9068 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9069 nil))
9070 ((= dcst ?k)
9071 (or (get-text-property (point) :org-clock-minutes) 0))
9072 ((= dcst ?t)
9073 (let ((end (save-excursion (outline-next-heading) (point))))
9074 (if (or (re-search-forward org-ts-regexp end t)
9075 (re-search-forward org-ts-regexp-both end t))
9076 (org-time-string-to-seconds (match-string 0))
9077 (float-time now))))
9078 ((= dcst ?c)
9079 (let ((end (save-excursion (outline-next-heading) (point))))
9080 (if (re-search-forward
9081 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9082 end t)
9083 (org-time-string-to-seconds (match-string 0))
9084 (float-time now))))
9085 ((= dcst ?s)
9086 (let ((end (save-excursion (outline-next-heading) (point))))
9087 (if (re-search-forward org-scheduled-time-regexp end t)
9088 (org-time-string-to-seconds (match-string 1))
9089 (float-time now))))
9090 ((= dcst ?d)
9091 (let ((end (save-excursion (outline-next-heading) (point))))
9092 (if (re-search-forward org-deadline-time-regexp end t)
9093 (org-time-string-to-seconds (match-string 1))
9094 (float-time now))))
9095 ((= dcst ?p)
9096 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9097 (string-to-char (match-string 2))
9098 org-default-priority))
9099 ((= dcst ?r)
9100 (or (org-entry-get nil property) ""))
9101 ((= dcst ?o)
9102 (when (looking-at org-complex-heading-regexp)
9103 (let* ((m (match-string 2))
9104 (s (if (member m org-done-keywords) '- '+)))
9105 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9106 ((= dcst ?f)
9107 (if getkey-func
9108 (progn
9109 (setq tmp (funcall getkey-func))
9110 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9111 tmp)
9112 (error "Invalid key function `%s'" getkey-func)))
9113 (t (error "Invalid sorting type `%c'" sorting-type))))
9115 (cond
9116 ((= dcst ?a) 'string<)
9117 ((= dcst ?f) compare-func)
9118 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9119 (run-hooks 'org-after-sorting-entries-or-items-hook)
9120 ;; Reset the clock marker if needed
9121 (when cmstr
9122 (save-excursion
9123 (goto-char start)
9124 (search-forward cmstr nil t)
9125 (move-marker org-clock-marker (point))))
9126 (message "Sorting entries...done")))
9128 ;;; The orgstruct minor mode
9130 ;; Define a minor mode which can be used in other modes in order to
9131 ;; integrate the org-mode structure editing commands.
9133 ;; This is really a hack, because the org-mode structure commands use
9134 ;; keys which normally belong to the major mode. Here is how it
9135 ;; works: The minor mode defines all the keys necessary to operate the
9136 ;; structure commands, but wraps the commands into a function which
9137 ;; tests if the cursor is currently at a headline or a plain list
9138 ;; item. If that is the case, the structure command is used,
9139 ;; temporarily setting many Org-mode variables like regular
9140 ;; expressions for filling etc. However, when any of those keys is
9141 ;; used at a different location, function uses `key-binding' to look
9142 ;; up if the key has an associated command in another currently active
9143 ;; keymap (minor modes, major mode, global), and executes that
9144 ;; command. There might be problems if any of the keys is otherwise
9145 ;; used as a prefix key.
9147 (defcustom orgstruct-heading-prefix-regexp ""
9148 "Regexp that matches the custom prefix of Org headlines in
9149 orgstruct(++)-mode."
9150 :group 'org
9151 :version "24.4"
9152 :package-version '(Org . "8.3")
9153 :type 'regexp)
9154 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9156 (defcustom orgstruct-setup-hook nil
9157 "Hook run after orgstruct-mode-map is filled."
9158 :group 'org
9159 :version "24.4"
9160 :package-version '(Org . "8.0")
9161 :type 'hook)
9163 (defvar orgstruct-initialized nil)
9165 (defvar org-local-vars nil
9166 "List of local variables, for use by `orgstruct-mode'.")
9168 ;;;###autoload
9169 (define-minor-mode orgstruct-mode
9170 "Toggle the minor mode `orgstruct-mode'.
9171 This mode is for using Org-mode structure commands in other
9172 modes. The following keys behave as if Org-mode were active, if
9173 the cursor is on a headline, or on a plain list item (both as
9174 defined by Org-mode)."
9175 nil " OrgStruct" (make-sparse-keymap)
9176 (funcall (if orgstruct-mode
9177 'add-to-invisibility-spec
9178 'remove-from-invisibility-spec)
9179 '(outline . t))
9180 (when orgstruct-mode
9181 (org-load-modules-maybe)
9182 (unless orgstruct-initialized
9183 (orgstruct-setup)
9184 (setq orgstruct-initialized t))))
9186 ;;;###autoload
9187 (defun turn-on-orgstruct ()
9188 "Unconditionally turn on `orgstruct-mode'."
9189 (orgstruct-mode 1))
9191 (defvar-local orgstruct-is-++ nil
9192 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9193 (defvar-local org-fb-vars nil)
9194 (defun orgstruct++-mode (&optional arg)
9195 "Toggle `orgstruct-mode', the enhanced version of it.
9196 In addition to setting orgstruct-mode, this also exports all
9197 indentation and autofilling variables from org-mode into the
9198 buffer. It will also recognize item context in multiline items."
9199 (interactive "P")
9200 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9201 (if (< arg 1)
9202 (progn (orgstruct-mode -1)
9203 (dolist (v org-fb-vars)
9204 (set (make-local-variable (car v))
9205 (if (eq (car-safe (cadr v)) 'quote)
9206 (cl-cadadr v)
9207 (nth 1 v)))))
9208 (orgstruct-mode 1)
9209 (setq org-fb-vars nil)
9210 (unless org-local-vars
9211 (setq org-local-vars (org-get-local-variables)))
9212 (let (var val)
9213 (dolist (x org-local-vars)
9214 (when (string-match
9215 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9216 \\|fill-prefix\\|indent-\\)"
9217 (symbol-name (car x)))
9218 (setq var (car x) val (nth 1 x))
9219 (push (list var `(quote ,(eval var))) org-fb-vars)
9220 (set (make-local-variable var)
9221 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9222 (setq-local orgstruct-is-++ t))))
9224 ;;;###autoload
9225 (defun turn-on-orgstruct++ ()
9226 "Unconditionally turn on `orgstruct++-mode'."
9227 (orgstruct++-mode 1))
9229 (defun orgstruct-error ()
9230 "Error when there is no default binding for a structure key."
9231 (interactive)
9232 (funcall (if (fboundp 'user-error)
9233 'user-error
9234 'error)
9235 "This key has no function outside structure elements"))
9237 (defun orgstruct-setup ()
9238 "Setup orgstruct keymap."
9239 (dolist (cell '((org-demote . t)
9240 (org-metaleft . t)
9241 (org-metaright . t)
9242 (org-promote . t)
9243 (org-shiftmetaleft . t)
9244 (org-shiftmetaright . t)
9245 org-backward-element
9246 org-backward-heading-same-level
9247 org-ctrl-c-ret
9248 org-ctrl-c-minus
9249 org-ctrl-c-star
9250 org-cycle
9251 org-force-cycle-archived
9252 org-forward-heading-same-level
9253 org-insert-heading
9254 org-insert-heading-respect-content
9255 org-kill-note-or-show-branches
9256 org-mark-subtree
9257 org-meta-return
9258 org-metadown
9259 org-metaup
9260 org-narrow-to-subtree
9261 org-promote-subtree
9262 org-reveal
9263 org-shiftdown
9264 org-shiftleft
9265 org-shiftmetadown
9266 org-shiftmetaup
9267 org-shiftright
9268 org-shifttab
9269 org-shifttab
9270 org-shiftup
9271 org-show-children
9272 org-show-subtree
9273 org-sort
9274 org-up-element
9275 outline-demote
9276 outline-next-visible-heading
9277 outline-previous-visible-heading
9278 outline-promote
9279 outline-up-heading))
9280 (let ((f (or (car-safe cell) cell))
9281 (disable-when-heading-prefix (cdr-safe cell)))
9282 (when (fboundp f)
9283 (let ((new-bindings))
9284 (dolist (binding (nconc (where-is-internal f org-mode-map)
9285 (where-is-internal f outline-mode-map)))
9286 (push binding new-bindings)
9287 ;; TODO use local-function-key-map
9288 (dolist (rep '(("<tab>" . "TAB")
9289 ("<return>" . "RET")
9290 ("<escape>" . "ESC")
9291 ("<delete>" . "DEL")))
9292 (setq binding (read-kbd-macro
9293 (let ((case-fold-search))
9294 (replace-regexp-in-string
9295 (regexp-quote (cdr rep))
9296 (car rep)
9297 (key-description binding)))))
9298 (cl-pushnew binding new-bindings :test 'equal)))
9299 (dolist (binding new-bindings)
9300 (let ((key (lookup-key orgstruct-mode-map binding)))
9301 (when (or (not key) (numberp key))
9302 (ignore-errors
9303 (org-defkey orgstruct-mode-map
9304 binding
9305 (orgstruct-make-binding
9306 f binding disable-when-heading-prefix))))))))))
9307 (run-hooks 'orgstruct-setup-hook))
9309 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9310 "Create a function for binding in the structure minor mode.
9311 FUN is the command to call inside a table. KEY is the key that
9312 should be checked in for a command to execute outside of tables.
9313 Non-nil `disable-when-heading-prefix' means to disable the command
9314 if `orgstruct-heading-prefix-regexp' is not empty."
9315 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9316 (let ((nname name)
9317 (i 0))
9318 (while (fboundp (intern nname))
9319 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9320 (setq name (intern nname)))
9321 (eval
9322 (let ((bindings '((org-heading-regexp
9323 (concat "^"
9324 orgstruct-heading-prefix-regexp
9325 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9326 (org-outline-regexp
9327 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9328 (org-outline-regexp-bol
9329 (concat "^" org-outline-regexp))
9330 (outline-regexp org-outline-regexp)
9331 (outline-heading-end-regexp "\n")
9332 (outline-level 'org-outline-level)
9333 (outline-heading-alist))))
9334 `(defun ,name (arg)
9335 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9336 "Outside of structure, run the binding of `"
9337 (key-description key) "'."
9338 (when disable-when-heading-prefix
9339 (concat
9340 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9341 "back to the default binding due to limitations of Org's implementation of\n"
9342 "`" (symbol-name fun) "'.")))
9343 (interactive "p")
9344 (let* ((disable
9345 ,(and disable-when-heading-prefix
9346 '(not (string= orgstruct-heading-prefix-regexp ""))))
9347 (fallback
9348 (or disable
9349 (not
9350 (let* ,bindings
9351 (org-context-p 'headline 'item
9352 ,(when (memq fun
9353 '(org-insert-heading
9354 org-insert-heading-respect-content
9355 org-meta-return))
9356 '(when orgstruct-is-++
9357 'item-body))))))))
9358 (if fallback
9359 (let* ((orgstruct-mode)
9360 (binding
9361 (let ((key ,key))
9362 (catch 'exit
9363 (dolist
9364 (rep
9365 '(nil
9366 ("<\\([^>]*\\)tab>" . "\\1TAB")
9367 ("<\\([^>]*\\)return>" . "\\1RET")
9368 ("<\\([^>]*\\)escape>" . "\\1ESC")
9369 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9370 nil)
9371 (when rep
9372 (setq key (read-kbd-macro
9373 (let ((case-fold-search))
9374 (replace-regexp-in-string
9375 (car rep)
9376 (cdr rep)
9377 (key-description key))))))
9378 (when (key-binding key)
9379 (throw 'exit (key-binding key))))))))
9380 (if (keymapp binding)
9381 (org-set-transient-map binding)
9382 (let ((func (or binding
9383 (unless disable
9384 'orgstruct-error))))
9385 (when func
9386 (call-interactively func)))))
9387 (org-run-like-in-org-mode
9388 (lambda ()
9389 (interactive)
9390 (let* ,bindings
9391 (call-interactively ',fun)))))))))
9392 name))
9394 (defun org-contextualize-keys (alist contexts)
9395 "Return valid elements in ALIST depending on CONTEXTS.
9397 `org-agenda-custom-commands' or `org-capture-templates' are the
9398 values used for ALIST, and `org-agenda-custom-commands-contexts'
9399 or `org-capture-templates-contexts' are the associated contexts
9400 definitions."
9401 (let ((contexts
9402 ;; normalize contexts
9403 (mapcar
9404 (lambda(c) (cond ((listp (cadr c))
9405 (list (car c) (car c) (nth 1 c)))
9406 ((string= "" (cadr c))
9407 (list (car c) (car c) (nth 2 c)))
9408 (t c)))
9409 contexts))
9410 (a alist) r s)
9411 ;; loop over all commands or templates
9412 (dolist (c a)
9413 (let (vrules repl)
9414 (cond
9415 ((not (assoc (car c) contexts))
9416 (push c r))
9417 ((and (assoc (car c) contexts)
9418 (setq vrules (org-contextualize-validate-key
9419 (car c) contexts)))
9420 (mapc (lambda (vr)
9421 (unless (equal (car vr) (cadr vr))
9422 (setq repl vr)))
9423 vrules)
9424 (if (not repl) (push c r)
9425 (push (cadr repl) s)
9426 (push
9427 (cons (car c)
9428 (cdr (or (assoc (cadr repl) alist)
9429 (error "Undefined key `%s' as contextual replacement for `%s'"
9430 (cadr repl) (car c)))))
9431 r))))))
9432 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9433 (delq
9435 (delete-dups
9436 (mapcar (lambda (x)
9437 (let ((tpl (car x)))
9438 (unless (delq
9440 (mapcar (lambda (y)
9441 (equal y tpl))
9443 x)))
9444 (reverse r))))))
9446 (defun org-contextualize-validate-key (key contexts)
9447 "Check CONTEXTS for agenda or capture KEY."
9448 (let (res)
9449 (dolist (r contexts)
9450 (dolist (rr (car (last r)))
9451 (when
9452 (and (equal key (car r))
9453 (if (functionp rr) (funcall rr)
9454 (or (and (eq (car rr) 'in-file)
9455 (buffer-file-name)
9456 (string-match (cdr rr) (buffer-file-name)))
9457 (and (eq (car rr) 'in-mode)
9458 (string-match (cdr rr) (symbol-name major-mode)))
9459 (and (eq (car rr) 'in-buffer)
9460 (string-match (cdr rr) (buffer-name)))
9461 (when (and (eq (car rr) 'not-in-file)
9462 (buffer-file-name))
9463 (not (string-match (cdr rr) (buffer-file-name))))
9464 (when (eq (car rr) 'not-in-mode)
9465 (not (string-match (cdr rr) (symbol-name major-mode))))
9466 (when (eq (car rr) 'not-in-buffer)
9467 (not (string-match (cdr rr) (buffer-name)))))))
9468 (push r res))))
9469 (delete-dups (delq nil res))))
9471 (defun org-context-p (&rest contexts)
9472 "Check if local context is any of CONTEXTS.
9473 Possible values in the list of contexts are `table', `headline', and `item'."
9474 (let ((pos (point)))
9475 (goto-char (point-at-bol))
9476 (prog1 (or (and (memq 'table contexts)
9477 (looking-at "[ \t]*|"))
9478 (and (memq 'headline contexts)
9479 (looking-at org-outline-regexp))
9480 (and (memq 'item contexts)
9481 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9482 (and (memq 'item-body contexts)
9483 (org-in-item-p)))
9484 (goto-char pos))))
9486 (defconst org-unique-local-variables
9487 '(org-element--cache
9488 org-element--cache-objects
9489 org-element--cache-sync-keys
9490 org-element--cache-sync-requests
9491 org-element--cache-sync-timer)
9492 "List of local variables that cannot be transferred to another buffer.")
9494 (defun org-get-local-variables ()
9495 "Return a list of all local variables in an Org mode buffer."
9496 (delq nil
9497 (mapcar
9498 (lambda (x)
9499 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9500 (name (car binding)))
9501 (and (not (get name 'org-state))
9502 (not (memq name org-unique-local-variables))
9503 (string-match-p
9504 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9505 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9506 (symbol-name name))
9507 binding)))
9508 (with-temp-buffer
9509 (org-mode)
9510 (buffer-local-variables)))))
9512 (defun org-clone-local-variables (from-buffer &optional regexp)
9513 "Clone local variables from FROM-BUFFER.
9514 Optional argument REGEXP selects variables to clone."
9515 (dolist (pair (buffer-local-variables from-buffer))
9516 (let ((name (car pair)))
9517 (when (and (symbolp name)
9518 (not (memq name org-unique-local-variables))
9519 (or (null regexp) (string-match regexp (symbol-name name))))
9520 (set (make-local-variable name) (cdr pair))))))
9522 ;;;###autoload
9523 (defun org-run-like-in-org-mode (cmd)
9524 "Run a command, pretending that the current buffer is in Org-mode.
9525 This will temporarily bind local variables that are typically bound in
9526 Org-mode to the values they have in Org-mode, and then interactively
9527 call CMD."
9528 (org-load-modules-maybe)
9529 (unless org-local-vars
9530 (setq org-local-vars (org-get-local-variables)))
9531 (let (binds)
9532 (dolist (var org-local-vars)
9533 (when (or (not (boundp (car var)))
9534 (eq (symbol-value (car var))
9535 (default-value (car var))))
9536 (push (list (car var) `(quote ,(cadr var))) binds)))
9537 (eval `(let ,binds
9538 (call-interactively (quote ,cmd))))))
9540 (defun org-get-category (&optional pos force-refresh)
9541 "Get the category applying to position POS."
9542 (save-match-data
9543 (when force-refresh (org-refresh-category-properties))
9544 (let ((pos (or pos (point))))
9545 (or (get-text-property pos 'org-category)
9546 (progn (org-refresh-category-properties)
9547 (get-text-property pos 'org-category))))))
9549 ;;; Refresh properties
9551 (defun org-refresh-properties (dprop tprop)
9552 "Refresh buffer text properties.
9553 DPROP is the drawer property and TPROP is either the
9554 corresponding text property to set, or an alist with each element
9555 being a text property (as a symbol) and a function to apply to
9556 the value of the drawer property."
9557 (let ((case-fold-search t)
9558 (inhibit-read-only t))
9559 (org-with-silent-modifications
9560 (save-excursion
9561 (save-restriction
9562 (widen)
9563 (goto-char (point-min))
9564 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9565 (org-refresh-property tprop (match-string-no-properties 1))))))))
9567 (defun org-refresh-property (tprop p)
9568 "Refresh the buffer text property TPROP from the drawer property P.
9569 The refresh happens only for the current tree (not subtree)."
9570 (unless (org-before-first-heading-p)
9571 (save-excursion
9572 (org-back-to-heading t)
9573 (if (symbolp tprop)
9574 ;; TPROP is a text property symbol
9575 (put-text-property
9576 (point) (or (outline-next-heading) (point-max)) tprop p)
9577 ;; TPROP is an alist with (properties . function) elements
9578 (dolist (al tprop)
9579 (save-excursion
9580 (put-text-property
9581 (line-beginning-position) (or (outline-next-heading) (point-max))
9582 (car al)
9583 (funcall (cdr al) p))))))))
9585 (defun org-refresh-category-properties ()
9586 "Refresh category text properties in the buffer."
9587 (let ((case-fold-search t)
9588 (inhibit-read-only t)
9589 (default-category
9590 (cond ((null org-category)
9591 (if buffer-file-name
9592 (file-name-sans-extension
9593 (file-name-nondirectory buffer-file-name))
9594 "???"))
9595 ((symbolp org-category) (symbol-name org-category))
9596 (t org-category))))
9597 (org-with-silent-modifications
9598 (org-with-wide-buffer
9599 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9600 ;; This is the default category for the buffer. If none is
9601 ;; found, fall-back to `org-category' or buffer file name.
9602 (put-text-property
9603 (point-min) (point-max)
9604 'org-category
9605 (catch 'buffer-category
9606 (goto-char (point-max))
9607 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9608 (let ((element (org-element-at-point)))
9609 (when (eq (org-element-type element) 'keyword)
9610 (throw 'buffer-category
9611 (org-element-property :value element)))))
9612 default-category))
9613 ;; Set sub-tree specific categories.
9614 (goto-char (point-min))
9615 (let ((regexp (org-re-property "CATEGORY")))
9616 (while (re-search-forward regexp nil t)
9617 (let ((value (match-string-no-properties 3)))
9618 (when (org-at-property-p)
9619 (put-text-property
9620 (save-excursion (org-back-to-heading t) (point))
9621 (save-excursion (org-end-of-subtree t t) (point))
9622 'org-category
9623 value)))))))))
9625 (defun org-refresh-stats-properties ()
9626 "Refresh stats text properties in the buffer."
9627 (let (stats)
9628 (org-with-silent-modifications
9629 (save-excursion
9630 (save-restriction
9631 (widen)
9632 (goto-char (point-min))
9633 (while (re-search-forward
9634 (concat org-outline-regexp-bol ".*"
9635 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9636 nil t)
9637 (setq stats (cond ((equal (match-string 3) "0") 0)
9638 ((match-string 2)
9639 (/ (* (string-to-number (match-string 2)) 100)
9640 (string-to-number (match-string 3))))
9641 (t (string-to-number (match-string 1)))))
9642 (org-back-to-heading t)
9643 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9644 'org-stats stats)))))))
9646 (defun org-refresh-effort-properties ()
9647 "Refresh effort properties"
9648 (org-refresh-properties
9649 org-effort-property
9650 '((effort . identity)
9651 (effort-minutes . org-duration-string-to-minutes))))
9653 ;;;; Link Stuff
9655 ;;; Link abbreviations
9657 (defun org-link-expand-abbrev (link)
9658 "Apply replacements as defined in `org-link-abbrev-alist'."
9659 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9660 (let* ((key (match-string 1 link))
9661 (as (or (assoc key org-link-abbrev-alist-local)
9662 (assoc key org-link-abbrev-alist)))
9663 (tag (and (match-end 2) (match-string 3 link)))
9664 rpl)
9665 (if (not as)
9666 link
9667 (setq rpl (cdr as))
9668 (cond
9669 ((symbolp rpl) (funcall rpl tag))
9670 ((string-match "%(\\([^)]+\\))" rpl)
9671 (replace-match
9672 (save-match-data
9673 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9674 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9675 ((string-match "%h" rpl)
9676 (replace-match (url-hexify-string (or tag "")) t t rpl))
9677 (t (concat rpl tag)))))
9678 link))
9680 ;;; Storing and inserting links
9682 (defvar org-insert-link-history nil
9683 "Minibuffer history for links inserted with `org-insert-link'.")
9685 (defvar org-stored-links nil
9686 "Contains the links stored with `org-store-link'.")
9688 (defvar org-store-link-plist nil
9689 "Plist with info about the most recently link created with `org-store-link'.")
9691 (defvar org-link-protocols nil
9692 "Link protocols added to Org-mode using `org-add-link-type'.")
9694 (defvar org-store-link-functions nil
9695 "List of functions that are called to create and store a link.
9696 Each function will be called in turn until one returns a non-nil
9697 value. Each function should check if it is responsible for creating
9698 this link (for example by looking at the major mode).
9699 If not, it must exit and return nil.
9700 If yes, it should return a non-nil value after a calling
9701 `org-store-link-props' with a list of properties and values.
9702 Special properties are:
9704 :type The link prefix, like \"http\". This must be given.
9705 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9706 This is obligatory as well.
9707 :description Optional default description for the second pair
9708 of brackets in an Org-mode link. The user can still change
9709 this when inserting this link into an Org-mode buffer.
9711 In addition to these, any additional properties can be specified
9712 and then used in capture templates.")
9714 (defun org-add-link-type (type &optional follow export)
9715 "Add TYPE to the list of `org-link-types'.
9716 Re-compute all regular expressions depending on `org-link-types'
9718 FOLLOW and EXPORT are two functions.
9720 FOLLOW should take the link path as the single argument and do whatever
9721 is necessary to follow the link, for example find a file or display
9722 a mail message.
9724 EXPORT should format the link path for export to one of the export formats.
9725 It should be a function accepting three arguments:
9727 path the path of the link, the text after the prefix (like \"http:\")
9728 desc the description of the link, if any
9729 format the export format, a symbol like `html' or `latex' or `ascii'.
9731 The function may use the FORMAT information to return different values
9732 depending on the format. The return value will be put literally into
9733 the exported file. If the return value is nil, this means Org should
9734 do what it normally does with links which do not have EXPORT defined.
9736 Org mode has a built-in default for exporting links. If you are happy with
9737 this default, there is no need to define an export function for the link
9738 type. For a simple example of an export function, see `org-bbdb.el'."
9739 (add-to-list 'org-link-types type t)
9740 (org-make-link-regexps)
9741 (org-element-update-syntax)
9742 (if (assoc type org-link-protocols)
9743 (setcdr (assoc type org-link-protocols) (list follow export))
9744 (push (list type follow export) org-link-protocols)))
9746 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9747 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9749 ;;;###autoload
9750 (defun org-store-link (arg)
9751 "\\<org-mode-map>Store an org-link to the current location.
9752 This link is added to `org-stored-links' and can later be inserted
9753 into an Org buffer with \\[org-insert-link].
9755 For some link types, a prefix ARG is interpreted.
9756 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9757 For file links, ARG negates `org-context-in-file-links'.
9759 A double prefix ARG force skipping storing functions that are not
9760 part of Org's core.
9762 A triple prefix ARG force storing a link for each line in the
9763 active region."
9764 (interactive "P")
9765 (org-load-modules-maybe)
9766 (if (and (equal arg '(64)) (org-region-active-p))
9767 (save-excursion
9768 (let ((end (region-end)))
9769 (goto-char (region-beginning))
9770 (set-mark (point))
9771 (while (< (point-at-eol) end)
9772 (move-end-of-line 1) (activate-mark)
9773 (let (current-prefix-arg)
9774 (call-interactively 'org-store-link))
9775 (move-beginning-of-line 2)
9776 (set-mark (point)))))
9777 (org-with-limited-levels
9778 (setq org-store-link-plist nil)
9779 (let (link cpltxt desc description search
9780 txt custom-id agenda-link sfuns sfunsn)
9781 (cond
9783 ;; Store a link using an external link type
9784 ((and (not (equal arg '(16)))
9785 (setq sfuns
9786 (delq
9787 nil (mapcar (lambda (f)
9788 (let (fs) (if (funcall f) (push f fs))))
9789 org-store-link-functions))
9790 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9791 (or (and (cdr sfuns)
9792 (funcall (intern
9793 (completing-read
9794 "Which function for creating the link? "
9795 sfunsn nil t (car sfunsn)))))
9796 (funcall (caar sfuns)))
9797 (setq link (plist-get org-store-link-plist :link)
9798 desc (or (plist-get org-store-link-plist
9799 :description)
9800 link))))
9802 ;; Store a link from a source code buffer.
9803 ((org-src-edit-buffer-p)
9804 (cond
9805 ((save-excursion
9806 (beginning-of-line)
9807 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9808 "[ \t]*$")))
9809 (setq link (format "(%s)" (match-string-no-properties 1))))
9810 ((org-called-interactively-p 'any)
9811 (let (label)
9812 (while (or (not label)
9813 (org-with-wide-buffer
9814 (goto-char (point-min))
9815 (re-search-forward
9816 (regexp-quote (format org-coderef-label-format label))
9817 nil t)))
9818 (when label (message "Label exists already") (sit-for 2))
9819 (setq label (read-string "Code line label: " label)))
9820 (end-of-line)
9821 (setq link (format org-coderef-label-format label))
9822 (let ((gc (- 79 (length link))))
9823 (if (< (current-column) gc) (org-move-to-column gc t)
9824 (insert " ")))
9825 (insert link)
9826 (setq link (concat "(" label ")") desc nil)))
9827 (t (setq link nil))))
9829 ;; We are in the agenda, link to referenced location
9830 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9831 (let ((m (or (get-text-property (point) 'org-hd-marker)
9832 (get-text-property (point) 'org-marker))))
9833 (when m
9834 (org-with-point-at m
9835 (setq agenda-link
9836 (if (org-called-interactively-p 'any)
9837 (call-interactively 'org-store-link)
9838 (org-store-link nil)))))))
9840 ((eq major-mode 'calendar-mode)
9841 (let ((cd (calendar-cursor-to-date)))
9842 (setq link
9843 (format-time-string
9844 (car org-time-stamp-formats)
9845 (apply 'encode-time
9846 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9847 nil nil nil))))
9848 (org-store-link-props :type "calendar" :date cd)))
9850 ((eq major-mode 'help-mode)
9851 (setq link (concat "help:" (save-excursion
9852 (goto-char (point-min))
9853 (looking-at "^[^ ]+")
9854 (match-string 0))))
9855 (org-store-link-props :type "help"))
9857 ((eq major-mode 'w3-mode)
9858 (setq cpltxt (if (and (buffer-name)
9859 (not (string-match "Untitled" (buffer-name))))
9860 (buffer-name)
9861 (url-view-url t))
9862 link (url-view-url t))
9863 (org-store-link-props :type "w3" :url (url-view-url t)))
9865 ((eq major-mode 'image-mode)
9866 (setq cpltxt (concat "file:"
9867 (abbreviate-file-name buffer-file-name))
9868 link cpltxt)
9869 (org-store-link-props :type "image" :file buffer-file-name))
9871 ;; In dired, store a link to the file of the current line
9872 ((derived-mode-p 'dired-mode)
9873 (let ((file (dired-get-filename nil t)))
9874 (setq file (if file
9875 (abbreviate-file-name
9876 (expand-file-name (dired-get-filename nil t)))
9877 ;; otherwise, no file so use current directory.
9878 default-directory))
9879 (setq cpltxt (concat "file:" file)
9880 link cpltxt)))
9882 ((setq search (run-hook-with-args-until-success
9883 'org-create-file-search-functions))
9884 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9885 "::" search))
9886 (setq cpltxt (or description link)))
9888 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9889 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9890 (cond
9891 ;; Store a link using the target at point
9892 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9893 (setq cpltxt
9894 (concat "file:"
9895 (abbreviate-file-name
9896 (buffer-file-name (buffer-base-buffer)))
9897 "::" (match-string 1))
9898 link cpltxt))
9899 ((and (featurep 'org-id)
9900 (or (eq org-id-link-to-org-use-id t)
9901 (and (org-called-interactively-p 'any)
9902 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9903 (and (eq org-id-link-to-org-use-id
9904 'create-if-interactive-and-no-custom-id)
9905 (not custom-id))))
9906 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9907 ;; Store a link using the ID at point
9908 (setq link (condition-case nil
9909 (prog1 (org-id-store-link)
9910 (setq desc (or (plist-get org-store-link-plist
9911 :description)
9912 "")))
9913 (error
9914 ;; Probably before first headline, link only to file
9915 (concat "file:"
9916 (abbreviate-file-name
9917 (buffer-file-name (buffer-base-buffer))))))))
9919 ;; Just link to current headline
9920 (setq cpltxt (concat "file:"
9921 (abbreviate-file-name
9922 (buffer-file-name (buffer-base-buffer)))))
9923 ;; Add a context search string
9924 (when (org-xor org-context-in-file-links arg)
9925 (let* ((element (org-element-at-point))
9926 (name (org-element-property :name element)))
9927 (setq txt (cond
9928 ((org-at-heading-p) nil)
9929 (name)
9930 ((org-region-active-p)
9931 (buffer-substring (region-beginning) (region-end)))))
9932 (when (or (null txt) (string-match "\\S-" txt))
9933 (setq cpltxt
9934 (concat cpltxt "::"
9935 (condition-case nil
9936 (org-make-org-heading-search-string txt)
9937 (error "")))
9938 desc (or name
9939 (nth 4 (ignore-errors (org-heading-components)))
9940 "NONE")))))
9941 (when (string-match "::\\'" cpltxt)
9942 (setq cpltxt (substring cpltxt 0 -2)))
9943 (setq link cpltxt))))
9945 ((buffer-file-name (buffer-base-buffer))
9946 ;; Just link to this file here.
9947 (setq cpltxt (concat "file:"
9948 (abbreviate-file-name
9949 (buffer-file-name (buffer-base-buffer)))))
9950 ;; Add a context string.
9951 (when (org-xor org-context-in-file-links arg)
9952 (setq txt (if (org-region-active-p)
9953 (buffer-substring (region-beginning) (region-end))
9954 (buffer-substring (point-at-bol) (point-at-eol))))
9955 ;; Only use search option if there is some text.
9956 (when (string-match "\\S-" txt)
9957 (setq cpltxt
9958 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9959 desc "NONE")))
9960 (setq link cpltxt))
9962 ((org-called-interactively-p 'interactive)
9963 (user-error "No method for storing a link from this buffer"))
9965 (t (setq link nil)))
9967 ;; We're done setting link and desc, clean up
9968 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9969 (setq link (or link cpltxt)
9970 desc (or desc cpltxt))
9971 (cond ((not desc))
9972 ((equal desc "NONE") (setq desc nil))
9973 (t (setq desc
9974 (replace-regexp-in-string
9975 org-bracket-link-analytic-regexp
9976 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9977 desc))))
9978 ;; Return the link
9979 (if (not (and (or (org-called-interactively-p 'any)
9980 executing-kbd-macro)
9981 link))
9982 (or agenda-link (and link (org-make-link-string link desc)))
9983 (push (list link desc) org-stored-links)
9984 (message "Stored: %s" (or desc link))
9985 (when custom-id
9986 (setq link (concat "file:" (abbreviate-file-name
9987 (buffer-file-name)) "::#" custom-id))
9988 (push (list link desc) org-stored-links))
9989 (car org-stored-links))))))
9991 (defun org-store-link-props (&rest plist)
9992 "Store link properties, extract names, addresses and dates."
9993 (let ((x (plist-get plist :from)))
9994 (when x
9995 (let ((adr (mail-extract-address-components x)))
9996 (setq plist (plist-put plist :fromname (car adr)))
9997 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9998 (let ((x (plist-get plist :to)))
9999 (when x
10000 (let ((adr (mail-extract-address-components x)))
10001 (setq plist (plist-put plist :toname (car adr)))
10002 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10003 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10004 (when x
10005 (setq plist (plist-put plist :date-timestamp
10006 (format-time-string
10007 (org-time-stamp-format t) x)))
10008 (setq plist (plist-put plist :date-timestamp-inactive
10009 (format-time-string
10010 (org-time-stamp-format t t) x)))))
10011 (let ((from (plist-get plist :from))
10012 (to (plist-get plist :to)))
10013 (when (and from to org-from-is-user-regexp)
10014 (setq plist
10015 (plist-put plist :fromto
10016 (if (string-match org-from-is-user-regexp from)
10017 (concat "to %t")
10018 (concat "from %f"))))))
10019 (setq org-store-link-plist plist))
10021 (defun org-add-link-props (&rest plist)
10022 "Add these properties to the link property list."
10023 (let (key value)
10024 (while plist
10025 (setq key (pop plist) value (pop plist))
10026 (setq org-store-link-plist
10027 (plist-put org-store-link-plist key value)))))
10029 (defun org-email-link-description (&optional fmt)
10030 "Return the description part of an email link.
10031 This takes information from `org-store-link-plist' and formats it
10032 according to FMT (default from `org-email-link-description-format')."
10033 (setq fmt (or fmt org-email-link-description-format))
10034 (let* ((p org-store-link-plist)
10035 (to (plist-get p :toaddress))
10036 (from (plist-get p :fromaddress))
10037 (table
10038 (list
10039 (cons "%c" (plist-get p :fromto))
10040 (cons "%F" (plist-get p :from))
10041 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10042 (cons "%T" (plist-get p :to))
10043 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10044 (cons "%s" (plist-get p :subject))
10045 (cons "%d" (plist-get p :date))
10046 (cons "%m" (plist-get p :message-id)))))
10047 (when (string-match "%c" fmt)
10048 ;; Check if the user wrote this message
10049 (if (and org-from-is-user-regexp from to
10050 (save-match-data (string-match org-from-is-user-regexp from)))
10051 (setq fmt (replace-match "to %t" t t fmt))
10052 (setq fmt (replace-match "from %f" t t fmt))))
10053 (org-replace-escapes fmt table)))
10055 (defun org-make-org-heading-search-string (&optional string)
10056 "Make search string for the current headline or STRING."
10057 (let ((s (or string
10058 (and (derived-mode-p 'org-mode)
10059 (save-excursion
10060 (org-back-to-heading t)
10061 (org-element-property :raw-value (org-element-at-point))))))
10062 (lines org-context-in-file-links))
10063 (or string (setq s (concat "*" s))) ; Add * for headlines
10064 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10065 (when (and string (integerp lines) (> lines 0))
10066 (let ((slines (org-split-string s "\n")))
10067 (when (< lines (length slines))
10068 (setq s (mapconcat
10069 'identity
10070 (reverse (nthcdr (- (length slines) lines)
10071 (reverse slines))) "\n")))))
10072 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10074 (defun org-make-link-string (link &optional description)
10075 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10076 (unless (org-string-nw-p link) (error "Empty link"))
10077 (let ((uri (cond ((string-match org-link-types-re link)
10078 (concat (match-string 1 link)
10079 (org-link-escape (substring link (match-end 1)))))
10080 ;; For readability, url-encode internal links only
10081 ;; when absolutely needed (i.e, when they contain
10082 ;; square brackets). File links however, are
10083 ;; encoded since, e.g., spaces are significant.
10084 ((or (file-name-absolute-p link)
10085 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10086 (org-link-escape link))
10087 (t link)))
10088 (description
10089 (and (org-string-nw-p description)
10090 ;; Remove brackets from description, as they are fatal.
10091 (replace-regexp-in-string
10092 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10093 (org-trim description)))))
10094 (format "[[%s]%s]"
10096 (if description (format "[%s]" description) ""))))
10098 (defconst org-link-escape-chars
10099 ;;%20 %5B %5D %25
10100 '(?\s ?\[ ?\] ?%)
10101 "List of characters that should be escaped in a link when stored to Org.
10102 This is the list that is used for internal purposes.")
10104 (defconst org-link-escape-chars-browser
10105 ;;%20 %22
10106 '(?\s ?\")
10107 "List of characters to be escaped before handing over to the browser.
10108 If you consider using this constant then you probably want to use
10109 the function `org-link-escape-browser' instead. See there why
10110 this constant is a candidate to be removed once Org drops support
10111 for Emacs 24.1 and 24.2.")
10113 (defun org-link-escape (text &optional table merge)
10114 "Return percent escaped representation of TEXT.
10115 TEXT is a string with the text to escape.
10116 Optional argument TABLE is a list with characters that should be
10117 escaped. When nil, `org-link-escape-chars' is used.
10118 If optional argument MERGE is set, merge TABLE into
10119 `org-link-escape-chars'."
10120 (let ((characters-to-encode
10121 (cond ((null table) org-link-escape-chars)
10122 (merge (append org-link-escape-chars table))
10123 (t table))))
10124 (mapconcat
10125 (lambda (c)
10126 (if (or (memq c characters-to-encode)
10127 (and org-url-hexify-p (or (< c 32) (> c 126))))
10128 (mapconcat (lambda (e) (format "%%%.2X" e))
10129 (or (encode-coding-char c 'utf-8)
10130 (error "Unable to percent escape character: %c" c))
10132 (char-to-string c)))
10133 text "")))
10135 (defun org-link-escape-browser (text)
10136 "Escape some characters before handing over to the browser.
10137 This function is a candidate to be removed together with the
10138 constant `org-link-escape-chars-browser' once Org drops support
10139 for Emacs 24.1 and 24.2. All calls to this function will have to
10140 be replaced with `url-encode-url' which is available since Emacs
10141 24.3.1."
10142 ;; Example with the Org link
10143 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10144 ;; to open the browser with +subject:"Release 8.2" filled into the
10145 ;; query field: In this case the variable TEXT contains the
10146 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10147 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10148 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10149 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10150 (if (fboundp 'url-encode-url)
10151 (url-encode-url text)
10152 (if (org-string-match-p
10153 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10154 text)
10155 (org-link-escape text org-link-escape-chars-browser)
10156 text)))
10158 (defun org-link-unescape (str)
10159 "Unhex hexified Unicode parts in string STR.
10160 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10161 reciprocal of `org-link-escape', which see."
10162 (if (org-string-nw-p str)
10163 (replace-regexp-in-string
10164 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10165 str))
10167 (defun org-link-unescape-compound (hex)
10168 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10169 Note: this function also decodes single byte encodings like
10170 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10171 (save-match-data
10172 (let* ((bytes (cdr (split-string hex "%")))
10173 (ret "")
10174 (eat 0)
10175 (sum 0))
10176 (while bytes
10177 (let* ((val (string-to-number (pop bytes) 16))
10178 (shift-xor
10179 (if (= 0 eat)
10180 (cond
10181 ((>= val 252) (cons 6 252))
10182 ((>= val 248) (cons 5 248))
10183 ((>= val 240) (cons 4 240))
10184 ((>= val 224) (cons 3 224))
10185 ((>= val 192) (cons 2 192))
10186 (t (cons 0 0)))
10187 (cons 6 128))))
10188 (when (>= val 192) (setq eat (car shift-xor)))
10189 (setq val (logxor val (cdr shift-xor)))
10190 (setq sum (+ (lsh sum (car shift-xor)) val))
10191 (when (> eat 0) (setq eat (- eat 1)))
10192 (cond
10193 ((= 0 eat) ;multi byte
10194 (setq ret (concat ret (org-char-to-string sum)))
10195 (setq sum 0))
10196 ((not bytes) ; single byte(s)
10197 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10198 ret)))
10200 (defun org-link-unescape-single-byte-sequence (hex)
10201 "Unhexify hex-encoded single byte character sequences."
10202 (mapconcat (lambda (byte)
10203 (char-to-string (string-to-number byte 16)))
10204 (cdr (split-string hex "%")) ""))
10206 (defun org-xor (a b)
10207 "Exclusive or."
10208 (if a (not b) b))
10210 (defun org-fixup-message-id-for-http (s)
10211 "Replace special characters in a message id, so it can be used in an http query."
10212 (when (string-match "%" s)
10213 (setq s (mapconcat (lambda (c)
10214 (if (eq c ?%)
10215 "%25"
10216 (char-to-string c)))
10217 s "")))
10218 (while (string-match "<" s)
10219 (setq s (replace-match "%3C" t t s)))
10220 (while (string-match ">" s)
10221 (setq s (replace-match "%3E" t t s)))
10222 (while (string-match "@" s)
10223 (setq s (replace-match "%40" t t s)))
10226 (defun org-link-prettify (link)
10227 "Return a human-readable representation of LINK.
10228 The car of LINK must be a raw link.
10229 The cdr of LINK must be either a link description or nil."
10230 (let ((desc (or (cadr link) "<no description>")))
10231 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10232 "<" (car link) ">")))
10234 ;;;###autoload
10235 (defun org-insert-link-global ()
10236 "Insert a link like Org-mode does.
10237 This command can be called in any mode to insert a link in Org-mode syntax."
10238 (interactive)
10239 (org-load-modules-maybe)
10240 (org-run-like-in-org-mode 'org-insert-link))
10242 (defun org-insert-all-links (arg &optional pre post)
10243 "Insert all links in `org-stored-links'.
10244 When a universal prefix, do not delete the links from `org-stored-links'.
10245 When `ARG' is a number, insert the last N link(s).
10246 `PRE' and `POST' are optional arguments to define a string to
10247 prepend or to append."
10248 (interactive "P")
10249 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10250 (links (copy-sequence org-stored-links))
10251 (pr (or pre "- "))
10252 (po (or post "\n"))
10253 (cnt 1) l)
10254 (if (null org-stored-links)
10255 (message "No link to insert")
10256 (while (and (or (listp arg) (>= arg cnt))
10257 (setq l (if (listp arg)
10258 (pop links)
10259 (pop org-stored-links))))
10260 (setq cnt (1+ cnt))
10261 (insert pr)
10262 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10263 (insert po)))))
10265 (defun org-insert-last-stored-link (arg)
10266 "Insert the last link stored in `org-stored-links'."
10267 (interactive "p")
10268 (org-insert-all-links arg "" "\n"))
10270 (defun org-link-fontify-links-to-this-file ()
10271 "Fontify links to the current file in `org-stored-links'."
10272 (let ((f (buffer-file-name)) a b)
10273 (setq a (mapcar (lambda(l)
10274 (let ((ll (car l)))
10275 (when (and (string-match "^file:\\(.+\\)::" ll)
10276 (equal f (expand-file-name (match-string 1 ll))))
10277 ll)))
10278 org-stored-links))
10279 (when (featurep 'org-id)
10280 (setq b (mapcar (lambda(l)
10281 (let ((ll (car l)))
10282 (when (and (string-match "^id:\\(.+\\)$" ll)
10283 (equal f (expand-file-name
10284 (or (org-id-find-id-file
10285 (match-string 1 ll)) ""))))
10286 ll)))
10287 org-stored-links)))
10288 (mapcar (lambda(l)
10289 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10290 (delq nil (append a b)))))
10292 (defvar org--links-history nil)
10293 (defun org-insert-link (&optional complete-file link-location default-description)
10294 "Insert a link. At the prompt, enter the link.
10296 Completion can be used to insert any of the link protocol prefixes like
10297 http or ftp in use.
10299 The history can be used to select a link previously stored with
10300 `org-store-link'. When the empty string is entered (i.e. if you just
10301 press RET at the prompt), the link defaults to the most recently
10302 stored link. As SPC triggers completion in the minibuffer, you need to
10303 use M-SPC or C-q SPC to force the insertion of a space character.
10305 You will also be prompted for a description, and if one is given, it will
10306 be displayed in the buffer instead of the link.
10308 If there is already a link at point, this command will allow you to edit link
10309 and description parts.
10311 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10312 be selected using completion. The path to the file will be relative to the
10313 current directory if the file is in the current directory or a subdirectory.
10314 Otherwise, the link will be the absolute path as completed in the minibuffer
10315 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10316 option `org-link-file-path-type'.
10318 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10319 the current directory or below.
10321 With three \\[universal-argument] prefixes, negate the meaning of
10322 `org-keep-stored-link-after-insertion'.
10324 If `org-make-link-description-function' is non-nil, this function will be
10325 called with the link target, and the result will be the default
10326 link description.
10328 If the LINK-LOCATION parameter is non-nil, this value will be
10329 used as the link location instead of reading one interactively.
10331 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10332 be used as the default description."
10333 (interactive "P")
10334 (let* ((wcf (current-window-configuration))
10335 (origbuf (current-buffer))
10336 (region (when (org-region-active-p)
10337 (buffer-substring (region-beginning) (region-end))))
10338 (remove (and region (list (region-beginning) (region-end))))
10339 (desc region)
10340 (link link-location)
10341 (abbrevs org-link-abbrev-alist-local)
10342 entry all-prefixes auto-desc)
10343 (cond
10344 (link-location) ; specified by arg, just use it.
10345 ((org-in-regexp org-bracket-link-regexp 1)
10346 ;; We do have a link at point, and we are going to edit it.
10347 (setq remove (list (match-beginning 0) (match-end 0)))
10348 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10349 (setq link (read-string "Link: "
10350 (org-link-unescape
10351 (match-string-no-properties 1)))))
10352 ((or (org-in-regexp org-angle-link-re)
10353 (org-in-regexp org-plain-link-re))
10354 ;; Convert to bracket link
10355 (setq remove (list (match-beginning 0) (match-end 0))
10356 link (read-string "Link: "
10357 (org-remove-angle-brackets (match-string 0)))))
10358 ((member complete-file '((4) (16)))
10359 ;; Completing read for file names.
10360 (setq link (org-file-complete-link complete-file)))
10362 ;; Read link, with completion for stored links.
10363 (org-link-fontify-links-to-this-file)
10364 (org-switch-to-buffer-other-window "*Org Links*")
10365 (with-current-buffer "*Org Links*"
10366 (erase-buffer)
10367 (insert "Insert a link.
10368 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10369 (when org-stored-links
10370 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10371 (insert (mapconcat 'org-link-prettify
10372 (reverse org-stored-links) "\n")))
10373 (goto-char (point-min)))
10374 (let ((cw (selected-window)))
10375 (select-window (get-buffer-window "*Org Links*" 'visible))
10376 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10377 (unless (pos-visible-in-window-p (point-max))
10378 (org-fit-window-to-buffer))
10379 (and (window-live-p cw) (select-window cw)))
10380 (setq all-prefixes (append (mapcar 'car abbrevs)
10381 (mapcar 'car org-link-abbrev-alist)
10382 org-link-types))
10383 (unwind-protect
10384 ;; Fake a link history, containing the stored links.
10385 (let ((org--links-history
10386 (append (mapcar #'car org-stored-links)
10387 org-insert-link-history)))
10388 (setq link
10389 (org-completing-read
10390 "Link: "
10391 (append
10392 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10393 (mapcar #'car org-stored-links))
10394 nil nil nil
10395 'org--links-history
10396 (caar org-stored-links)))
10397 (unless (org-string-nw-p link) (user-error "No link selected"))
10398 (dolist (l org-stored-links)
10399 (when (equal link (cadr l))
10400 (setq link (car l))
10401 (setq auto-desc t)))
10402 (when (or (member link all-prefixes)
10403 (and (equal ":" (substring link -1))
10404 (member (substring link 0 -1) all-prefixes)
10405 (setq link (substring link 0 -1))))
10406 (setq link (with-current-buffer origbuf
10407 (org-link-try-special-completion link)))))
10408 (set-window-configuration wcf)
10409 (kill-buffer "*Org Links*"))
10410 (setq entry (assoc link org-stored-links))
10411 (or entry (push link org-insert-link-history))
10412 (setq desc (or desc (nth 1 entry)))))
10414 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10415 (not org-keep-stored-link-after-insertion))
10416 (setq org-stored-links (delq (assoc link org-stored-links)
10417 org-stored-links)))
10419 (when (and (string-match org-plain-link-re link)
10420 (not (string-match org-ts-regexp link)))
10421 ;; URL-like link, normalize the use of angular brackets.
10422 (setq link (org-remove-angle-brackets link)))
10424 ;; Check if we are linking to the current file with a search
10425 ;; option If yes, simplify the link by using only the search
10426 ;; option.
10427 (when (and buffer-file-name
10428 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10429 (let* ((path (match-string 1 link))
10430 (case-fold-search nil)
10431 (search (match-string 2 link)))
10432 (save-match-data
10433 (when (equal (file-truename buffer-file-name) (file-truename path))
10434 ;; We are linking to this same file, with a search option
10435 (setq link search)))))
10437 ;; Check if we can/should use a relative path. If yes, simplify the link
10438 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10439 (let* ((type (match-string 1 link))
10440 (path (match-string 2 link))
10441 (origpath path)
10442 (case-fold-search nil))
10443 (cond
10444 ((or (eq org-link-file-path-type 'absolute)
10445 (equal complete-file '(16)))
10446 (setq path (abbreviate-file-name (expand-file-name path))))
10447 ((eq org-link-file-path-type 'noabbrev)
10448 (setq path (expand-file-name path)))
10449 ((eq org-link-file-path-type 'relative)
10450 (setq path (file-relative-name path)))
10452 (save-match-data
10453 (if (string-match (concat "^" (regexp-quote
10454 (expand-file-name
10455 (file-name-as-directory
10456 default-directory))))
10457 (expand-file-name path))
10458 ;; We are linking a file with relative path name.
10459 (setq path (substring (expand-file-name path)
10460 (match-end 0)))
10461 (setq path (abbreviate-file-name (expand-file-name path)))))))
10462 (setq link (concat type path))
10463 (when (equal desc origpath)
10464 (setq desc path))))
10466 (if org-make-link-description-function
10467 (setq desc
10468 (or (condition-case nil
10469 (funcall org-make-link-description-function link desc)
10470 (error (progn (message "Can't get link description from `%s'"
10471 (symbol-name org-make-link-description-function))
10472 (sit-for 2) nil)))
10473 (read-string "Description: " default-description)))
10474 (if default-description (setq desc default-description)
10475 (setq desc (or (and auto-desc desc)
10476 (read-string "Description: " desc)))))
10478 (unless (string-match "\\S-" desc) (setq desc nil))
10479 (when remove (apply 'delete-region remove))
10480 (insert (org-make-link-string link desc))
10481 ;; Redisplay so as the new link has proper invisible characters.
10482 (sit-for 0)))
10484 (defun org-link-try-special-completion (type)
10485 "If there is completion support for link type TYPE, offer it."
10486 (let ((fun (intern (concat "org-" type "-complete-link"))))
10487 (if (functionp fun)
10488 (funcall fun)
10489 (read-string "Link (no completion support): " (concat type ":")))))
10491 (defun org-file-complete-link (&optional arg)
10492 "Create a file link using completion."
10493 (let ((file (read-file-name "File: "))
10494 (pwd (file-name-as-directory (expand-file-name ".")))
10495 (pwd1 (file-name-as-directory (abbreviate-file-name
10496 (expand-file-name ".")))))
10497 (cond ((equal arg '(16))
10498 (concat "file:"
10499 (abbreviate-file-name (expand-file-name file))))
10500 ((string-match
10501 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10502 (concat "file:" (match-string 1 file)))
10503 ((string-match
10504 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10505 (expand-file-name file))
10506 (concat "file:"
10507 (match-string 1 (expand-file-name file))))
10508 (t (concat "file:" file)))))
10510 (defun org-completing-read (&rest args)
10511 "Completing-read with SPACE being a normal character."
10512 (let ((enable-recursive-minibuffers t)
10513 (minibuffer-local-completion-map
10514 (copy-keymap minibuffer-local-completion-map)))
10515 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10516 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10517 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10518 'org-time-stamp-inactive)
10519 (apply #'completing-read args)))
10521 (define-obsolete-function-alias
10522 'org-completing-read-no-i 'completing-read "Org 9.0")
10523 (define-obsolete-function-alias
10524 'org-icompleting-read 'completing-read "Org 9.0")
10525 (define-obsolete-function-alias
10526 'org-iread-file-name 'read-file-name "Org 9.0")
10528 ;;; Opening/following a link
10530 (defvar org-link-search-failed nil)
10532 (defvar org-open-link-functions nil
10533 "Hook for functions finding a plain text link.
10534 These functions must take a single argument, the link content.
10535 They will be called for links that look like [[link text][description]]
10536 when LINK TEXT does not have a protocol like \"http:\" and does not look
10537 like a filename (e.g. \"./blue.png\").
10539 These functions will be called *before* Org attempts to resolve the
10540 link by doing text searches in the current buffer - so if you want a
10541 link \"[[target]]\" to still find \"<<target>>\", your function should
10542 handle this as a special case.
10544 When the function does handle the link, it must return a non-nil value.
10545 If it decides that it is not responsible for this link, it must return
10546 nil to indicate that that Org-mode can continue with other options
10547 like exact and fuzzy text search.")
10549 (defun org-next-link (&optional search-backward)
10550 "Move forward to the next link.
10551 If the link is in hidden text, expose it."
10552 (interactive "P")
10553 (when (and org-link-search-failed (eq this-command last-command))
10554 (goto-char (point-min))
10555 (message "Link search wrapped back to beginning of buffer"))
10556 (setq org-link-search-failed nil)
10557 (let* ((pos (point))
10558 (ct (org-context))
10559 (a (assoc :link ct))
10560 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10561 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10562 ((looking-at org-any-link-re)
10563 ;; Don't stay stuck at link without an org-link face
10564 (forward-char (if search-backward -1 1))))
10565 (if (funcall srch-fun org-any-link-re nil t)
10566 (progn
10567 (goto-char (match-beginning 0))
10568 (when (outline-invisible-p) (org-show-context)))
10569 (goto-char pos)
10570 (setq org-link-search-failed t)
10571 (message "No further link found"))))
10573 (defun org-previous-link ()
10574 "Move backward to the previous link.
10575 If the link is in hidden text, expose it."
10576 (interactive)
10577 (funcall 'org-next-link t))
10579 (defun org-translate-link (s)
10580 "Translate a link string if a translation function has been defined."
10581 (with-temp-buffer
10582 (insert (org-trim s))
10583 (org-trim (org-element-interpret-data (org-element-context)))))
10585 (defun org-translate-link-from-planner (type path)
10586 "Translate a link from Emacs Planner syntax so that Org can follow it.
10587 This is still an experimental function, your mileage may vary."
10588 (cond
10589 ((member type '("http" "https" "news" "ftp"))
10590 ;; standard Internet links are the same.
10591 nil)
10592 ((and (equal type "irc") (string-match "^//" path))
10593 ;; Planner has two / at the beginning of an irc link, we have 1.
10594 ;; We should have zero, actually....
10595 (setq path (substring path 1)))
10596 ((and (equal type "lisp") (string-match "^/" path))
10597 ;; Planner has a slash, we do not.
10598 (setq type "elisp" path (substring path 1)))
10599 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10600 ;; A typical message link. Planner has the id after the final slash,
10601 ;; we separate it with a hash mark
10602 (setq path (concat (match-string 1 path) "#"
10603 (org-remove-angle-brackets (match-string 2 path))))))
10604 (cons type path))
10606 (defun org-find-file-at-mouse (ev)
10607 "Open file link or URL at mouse."
10608 (interactive "e")
10609 (mouse-set-point ev)
10610 (org-open-at-point 'in-emacs))
10612 (defun org-open-at-mouse (ev)
10613 "Open file link or URL at mouse.
10614 See the docstring of `org-open-file' for details."
10615 (interactive "e")
10616 (mouse-set-point ev)
10617 (when (eq major-mode 'org-agenda-mode)
10618 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10619 (org-open-at-point))
10621 (defvar org-window-config-before-follow-link nil
10622 "The window configuration before following a link.
10623 This is saved in case the need arises to restore it.")
10625 ;;;###autoload
10626 (defun org-open-at-point-global ()
10627 "Follow a link or time-stamp like Org mode does.
10628 This command can be called in any mode to follow an external link
10629 or a time-stamp that has Org mode syntax. Its behavior is
10630 undefined when called on internal links (e.g., fuzzy links).
10631 Raise an error when there is nothing to follow. "
10632 (interactive)
10633 (cond ((org-in-regexp org-any-link-re)
10634 (org-open-link-from-string (match-string-no-properties 0)))
10635 ((or (org-in-regexp org-ts-regexp-both nil t)
10636 (org-in-regexp org-tsr-regexp-both nil t))
10637 (org-follow-timestamp-link))
10638 (t (user-error "No link found"))))
10640 ;;;###autoload
10641 (defun org-open-link-from-string (s &optional arg reference-buffer)
10642 "Open a link in the string S, as if it was in Org-mode."
10643 (interactive "sLink: \nP")
10644 (let ((reference-buffer (or reference-buffer (current-buffer))))
10645 (with-temp-buffer
10646 (let ((org-inhibit-startup (not reference-buffer)))
10647 (org-mode)
10648 (insert s)
10649 (goto-char (point-min))
10650 (when reference-buffer
10651 (setq org-link-abbrev-alist-local
10652 (with-current-buffer reference-buffer
10653 org-link-abbrev-alist-local)))
10654 (org-open-at-point arg reference-buffer)))))
10656 (defvar org-open-at-point-functions nil
10657 "Hook that is run when following a link at point.
10659 Functions in this hook must return t if they identify and follow
10660 a link at point. If they don't find anything interesting at point,
10661 they must return nil.")
10663 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10664 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10665 (defun org-open-at-point (&optional arg reference-buffer)
10666 "Open link, timestamp, footnote or tags at point.
10668 When point is on a link, follow it. Normally, files will be
10669 opened by an appropriate application. If the optional prefix
10670 argument ARG is non-nil, Emacs will visit the file. With
10671 a double prefix argument, try to open outside of Emacs, in the
10672 application the system uses for this file type.
10674 When point is on a timestamp, open the agenda at the day
10675 specified.
10677 When point is a footnote definition, move to the first reference
10678 found. If it is on a reference, move to the associated
10679 definition.
10681 When point is on a headline, display a list of every link in the
10682 entry, so it is possible to pick one, or all, of them. If point
10683 is on a tag, call `org-tags-view' instead.
10685 When optional argument REFERENCE-BUFFER is non-nil, it should
10686 specify a buffer from where the link search should happen. This
10687 is used internally by `org-open-link-from-string'.
10689 On top of syntactically correct links, this function will open
10690 the link at point in comments or comment blocks and the first
10691 link in a property drawer line."
10692 (interactive "P")
10693 ;; On a code block, open block's results.
10694 (unless (call-interactively 'org-babel-open-src-block-result)
10695 (org-load-modules-maybe)
10696 (setq org-window-config-before-follow-link (current-window-configuration))
10697 (org-remove-occur-highlights nil nil t)
10698 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10699 (let* ((context
10700 ;; Only consider supported types, even if they are not
10701 ;; the closest one.
10702 (org-element-lineage
10703 (org-element-context)
10704 '(clock comment comment-block footnote-definition
10705 footnote-reference headline inlinetask keyword link
10706 node-property timestamp)
10708 (type (org-element-type context))
10709 (value (org-element-property :value context)))
10710 (cond
10711 ((not context) (user-error "No link found"))
10712 ;; Exception: open timestamps and links in properties
10713 ;; drawers, keywords and comments.
10714 ((memq type '(comment comment-block keyword node-property))
10715 (call-interactively #'org-open-at-point-global))
10716 ;; On a headline or an inlinetask, but not on a timestamp,
10717 ;; a link, a footnote reference or on tags.
10718 ((and (memq type '(headline inlinetask))
10719 ;; Not on tags.
10720 (progn (save-excursion (beginning-of-line)
10721 (looking-at org-complex-heading-regexp))
10722 (or (not (match-beginning 5))
10723 (< (point) (match-beginning 5)))))
10724 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10725 (links (car data))
10726 (links-end (cdr data)))
10727 (if links
10728 (dolist (link (if (stringp links) (list links) links))
10729 (search-forward link nil links-end)
10730 (goto-char (match-beginning 0))
10731 (org-open-at-point))
10732 (require 'org-attach)
10733 (org-attach-reveal 'if-exists))))
10734 ;; On a clock line, make sure point is on the timestamp
10735 ;; before opening it.
10736 ((and (eq type 'clock)
10737 value
10738 (>= (point) (org-element-property :begin value))
10739 (<= (point) (org-element-property :end value)))
10740 (org-follow-timestamp-link))
10741 ;; Do nothing on white spaces after an object.
10742 ((>= (point)
10743 (save-excursion
10744 (goto-char (org-element-property :end context))
10745 (skip-chars-backward " \t")
10746 (point)))
10747 (user-error "No link found"))
10748 ((eq type 'timestamp) (org-follow-timestamp-link))
10749 ;; On tags within a headline or an inlinetask.
10750 ((and (memq type '(headline inlinetask))
10751 (progn (save-excursion (beginning-of-line)
10752 (looking-at org-complex-heading-regexp))
10753 (and (match-beginning 5)
10754 (>= (point) (match-beginning 5)))))
10755 (org-tags-view arg (substring (match-string 5) 0 -1)))
10756 ((eq type 'link)
10757 ;; When link is located within the description of another
10758 ;; link (e.g., an inline image), always open the parent
10759 ;; link.
10760 (let*((link (let ((up (org-element-property :parent context)))
10761 (if (eq (org-element-type up) 'link) up context)))
10762 (type (org-element-property :type link))
10763 (path (org-link-unescape (org-element-property :path link))))
10764 ;; Switch back to REFERENCE-BUFFER needed when called in
10765 ;; a temporary buffer through `org-open-link-from-string'.
10766 (with-current-buffer (or reference-buffer (current-buffer))
10767 (cond
10768 ((equal type "file")
10769 (if (string-match "[*?{]" (file-name-nondirectory path))
10770 (dired path)
10771 ;; Look into `org-link-protocols' in order to find
10772 ;; a DEDICATED-FUNCTION to open file. The function
10773 ;; will be applied on raw link instead of parsed
10774 ;; link due to the limitation in `org-add-link-type'
10775 ;; ("open" function called with a single argument).
10776 ;; If no such function is found, fallback to
10777 ;; `org-open-file'.
10779 ;; Note : "file+emacs" and "file+sys" types are
10780 ;; hard-coded in order to escape the previous
10781 ;; limitation.
10782 (let* ((option (org-element-property :search-option link))
10783 (app (org-element-property :application link))
10784 (dedicated-function
10785 (nth 1 (assoc app org-link-protocols))))
10786 (if dedicated-function
10787 (funcall dedicated-function
10788 (concat path
10789 (and option (concat "::" option))))
10790 (apply #'org-open-file
10791 path
10792 (cond (arg)
10793 ((equal app "emacs") 'emacs)
10794 ((equal app "sys") 'system))
10795 (cond ((not option) nil)
10796 ((org-string-match-p "\\`[0-9]+\\'" option)
10797 (list (string-to-number option)))
10798 (t (list nil
10799 (org-link-unescape option)))))))))
10800 ((assoc type org-link-protocols)
10801 (funcall (nth 1 (assoc type org-link-protocols)) path))
10802 ((equal type "help")
10803 (let ((f-or-v (intern path)))
10804 (cond ((fboundp f-or-v) (describe-function f-or-v))
10805 ((boundp f-or-v) (describe-variable f-or-v))
10806 (t (error "Not a known function or variable")))))
10807 ((member type '("http" "https" "ftp" "mailto" "news"))
10808 (browse-url (org-link-escape-browser (concat type ":" path))))
10809 ((equal type "doi")
10810 (browse-url
10811 (org-link-escape-browser (concat org-doi-server-url path))))
10812 ((equal type "message") (browse-url (concat type ":" path)))
10813 ((equal type "shell")
10814 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10815 (cmd path))
10816 (if (or (and (org-string-nw-p
10817 org-confirm-shell-link-not-regexp)
10818 (string-match
10819 org-confirm-shell-link-not-regexp cmd))
10820 (not org-confirm-shell-link-function)
10821 (funcall org-confirm-shell-link-function
10822 (format "Execute \"%s\" in shell? "
10823 (org-add-props cmd nil
10824 'face 'org-warning))))
10825 (progn
10826 (message "Executing %s" cmd)
10827 (shell-command cmd buf)
10828 (when (featurep 'midnight)
10829 (setq clean-buffer-list-kill-buffer-names
10830 (cons (buffer-name buf)
10831 clean-buffer-list-kill-buffer-names))))
10832 (user-error "Abort"))))
10833 ((equal type "elisp")
10834 (let ((cmd path))
10835 (if (or (and (org-string-nw-p
10836 org-confirm-elisp-link-not-regexp)
10837 (org-string-match-p
10838 org-confirm-elisp-link-not-regexp cmd))
10839 (not org-confirm-elisp-link-function)
10840 (funcall org-confirm-elisp-link-function
10841 (format "Execute \"%s\" as elisp? "
10842 (org-add-props cmd nil
10843 'face 'org-warning))))
10844 (message "%s => %s" cmd
10845 (if (eq (string-to-char cmd) ?\()
10846 (eval (read cmd))
10847 (call-interactively (read cmd))))
10848 (user-error "Abort"))))
10849 ((equal type "id")
10850 (require 'org-id)
10851 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10852 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10853 (unless (run-hook-with-args-until-success
10854 'org-open-link-functions path)
10855 (if (not arg) (org-mark-ring-push)
10856 (switch-to-buffer-other-window
10857 (org-get-buffer-for-internal-link (current-buffer))))
10858 (let ((destination
10859 (org-with-wide-buffer
10860 (if (equal type "radio")
10861 (org-search-radio-target
10862 (org-element-property :path link))
10863 (org-link-search
10864 (if (member type '("custom-id" "coderef"))
10865 (org-element-property :raw-link link)
10866 path)
10867 ;; Prevent fuzzy links from matching
10868 ;; themselves.
10869 (and (equal type "fuzzy")
10870 (+ 2 (org-element-property :begin link)))))
10871 (point))))
10872 (unless (and (<= (point-min) destination)
10873 (>= (point-max) destination))
10874 (widen))
10875 (goto-char destination))))
10876 (t (browse-url-at-point))))))
10877 ;; On a footnote reference or at a footnote definition's label.
10878 ((or (eq type 'footnote-reference)
10879 (and (eq type 'footnote-definition)
10880 (save-excursion
10881 ;; Do not validate action when point is on the
10882 ;; spaces right after the footnote label, in
10883 ;; order to be on par with behaviour on links.
10884 (skip-chars-forward " \t")
10885 (let ((begin
10886 (org-element-property :contents-begin context)))
10887 (if begin (< (point) begin)
10888 (= (org-element-property :post-affiliated context)
10889 (line-beginning-position)))))))
10890 (org-footnote-action))
10891 (t (user-error "No link found")))))
10892 (run-hook-with-args 'org-follow-link-hook)))
10894 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10895 "Offer links in the current entry and return the selected link.
10896 If there is only one link, return it.
10897 If NTH is an integer, return the NTH link found.
10898 If ZERO is a string, check also this string for a link, and if
10899 there is one, return it."
10900 (with-current-buffer buffer
10901 (save-excursion
10902 (save-restriction
10903 (widen)
10904 (goto-char marker)
10905 (let ((cnt ?0)
10906 have-zero end links link c)
10907 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10908 (push (match-string 0 zero) links)
10909 (setq cnt (1- cnt) have-zero t))
10910 (save-excursion
10911 (org-back-to-heading t)
10912 (setq end (save-excursion (outline-next-heading) (point)))
10913 (while (re-search-forward org-any-link-re end t)
10914 (push (match-string 0) links))
10915 (setq links (org-uniquify (reverse links))))
10916 (cond
10917 ((null links)
10918 (message "No links"))
10919 ((equal (length links) 1)
10920 (setq link (car links)))
10921 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10922 (setq link (nth (if have-zero nth (1- nth)) links)))
10923 (t ; we have to select a link
10924 (save-excursion
10925 (save-window-excursion
10926 (delete-other-windows)
10927 (with-output-to-temp-buffer "*Select Link*"
10928 (dolist (l links)
10929 (cond
10930 ((not (string-match org-bracket-link-regexp l))
10931 (princ (format "[%c] %s\n" (cl-incf cnt)
10932 (org-remove-angle-brackets l))))
10933 ((match-end 3)
10934 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10935 (match-string 3 l) (match-string 1 l))))
10936 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10937 (match-string 1 l)))))))
10938 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10939 (message "Select link to open, RET to open all:")
10940 (setq c (read-char-exclusive))
10941 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10942 (when (equal c ?q) (user-error "Abort"))
10943 (if (equal c ?\C-m)
10944 (setq link links)
10945 (setq nth (- c ?0))
10946 (when have-zero (setq nth (1+ nth)))
10947 (unless (and (integerp nth) (>= (length links) nth))
10948 (user-error "Invalid link selection"))
10949 (setq link (nth (1- nth) links)))))
10950 (cons link end))))))
10952 ;; TODO: These functions are deprecated since `org-open-at-point'
10953 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10954 (defun org-open-file-with-system (path)
10955 "Open file at PATH using the system way of opening it."
10956 (org-open-file path 'system))
10957 (defun org-open-file-with-emacs (path)
10958 "Open file at PATH in Emacs."
10959 (org-open-file path 'emacs))
10962 ;;; File search
10964 (defvar org-create-file-search-functions nil
10965 "List of functions to construct the right search string for a file link.
10966 These functions are called in turn with point at the location to
10967 which the link should point.
10969 A function in the hook should first test if it would like to
10970 handle this file type, for example by checking the `major-mode'
10971 or the file extension. If it decides not to handle this file, it
10972 should just return nil to give other functions a chance. If it
10973 does handle the file, it must return the search string to be used
10974 when following the link. The search string will be part of the
10975 file link, given after a double colon, and `org-open-at-point'
10976 will automatically search for it. If special measures must be
10977 taken to make the search successful, another function should be
10978 added to the companion hook `org-execute-file-search-functions',
10979 which see.
10981 A function in this hook may also use `setq' to set the variable
10982 `description' to provide a suggestion for the descriptive text to
10983 be used for this link when it gets inserted into an Org-mode
10984 buffer with \\[org-insert-link].")
10986 (defvar org-execute-file-search-functions nil
10987 "List of functions to execute a file search triggered by a link.
10989 Functions added to this hook must accept a single argument, the
10990 search string that was part of the file link, the part after the
10991 double colon. The function must first check if it would like to
10992 handle this search, for example by checking the `major-mode' or
10993 the file extension. If it decides not to handle this search, it
10994 should just return nil to give other functions a chance. If it
10995 does handle the search, it must return a non-nil value to keep
10996 other functions from trying.
10998 Each function can access the current prefix argument through the
10999 variable `current-prefix-arg'. Note that a single prefix is used
11000 to force opening a link in Emacs, so it may be good to only use a
11001 numeric or double prefix to guide the search function.
11003 In case this is needed, a function in this hook can also restore
11004 the window configuration before `org-open-at-point' was called using:
11006 \(set-window-configuration org-window-config-before-follow-link)")
11008 (defun org-search-radio-target (target)
11009 "Search a radio target matching TARGET in current buffer.
11010 White spaces are not significant."
11011 (let ((re (format "<<<%s>>>"
11012 (mapconcat #'regexp-quote
11013 (org-split-string target "[ \t\n]+")
11014 "[ \t]+\\(?:\n[ \t]*\\)?")))
11015 (origin (point)))
11016 (goto-char (point-min))
11017 (catch :radio-match
11018 (while (re-search-forward re nil t)
11019 (backward-char)
11020 (let ((object (org-element-context)))
11021 (when (eq (org-element-type object) 'radio-target)
11022 (goto-char (org-element-property :begin object))
11023 (org-show-context 'link-search)
11024 (throw :radio-match nil))))
11025 (goto-char origin)
11026 (user-error "No match for radio target: %s" target))))
11028 (defun org-link-search (s &optional avoid-pos stealth)
11029 "Search for a search string S.
11031 If S starts with \"#\", it triggers a custom ID search.
11033 If S is enclosed within parenthesis, it initiates a coderef
11034 search.
11036 If S is surrounded by forward slashes, it is interpreted as
11037 a regular expression. In Org mode files, this will create an
11038 `org-occur' sparse tree. In ordinary files, `occur' will be used
11039 to list matches. If the current buffer is in `dired-mode', grep
11040 will be used to search in all files.
11042 When AVOID-POS is given, ignore matches near that position.
11044 When optional argument STEALTH is non-nil, do not modify
11045 visibility around point, thus ignoring `org-show-context-detail'
11046 variable.
11048 Search is case-insensitive and ignores white spaces. Return type
11049 of matched result, with is either `dedicated' or `fuzzy'."
11050 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11051 (let* ((case-fold-search t)
11052 (origin (point))
11053 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11054 (words (org-split-string s "[ \t\n]+"))
11055 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11056 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11057 type)
11058 (cond
11059 ;; Check if there are any special search functions.
11060 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11061 ((eq (string-to-char s) ?#)
11062 ;; Look for a custom ID S if S starts with "#".
11063 (let* ((id (substring normalized 1))
11064 (match (org-find-property "CUSTOM_ID" id)))
11065 (if match (progn (goto-char match) (setf type 'dedicated))
11066 (error "No match for custom ID: %s" id))))
11067 ((string-match "\\`(\\(.*\\))\\'" normalized)
11068 ;; Look for coderef targets if S is enclosed within parenthesis.
11069 (let ((coderef (match-string-no-properties 1 normalized))
11070 (re (substring s-single-re 1 -1)))
11071 (goto-char (point-min))
11072 (catch :coderef-match
11073 (while (re-search-forward re nil t)
11074 (let ((element (org-element-at-point)))
11075 (when (and (memq (org-element-type element)
11076 '(example-block src-block))
11077 ;; Build proper regexp according to current
11078 ;; block's label format.
11079 (let ((label-fmt
11080 (regexp-quote
11081 (or (org-element-property :label-fmt element)
11082 org-coderef-label-format))))
11083 (save-excursion
11084 (beginning-of-line)
11085 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11086 (format label-fmt coderef))))))
11087 (setq type 'dedicated)
11088 (goto-char (match-beginning 1))
11089 (throw :coderef-match nil))))
11090 (goto-char origin)
11091 (error "No match for coderef: %s" coderef))))
11092 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11093 ;; Look for a regular expression.
11094 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11095 (match-string 1 s)))
11096 ;; Fuzzy links.
11098 (let ((starred (eq (string-to-char normalized) ?*)))
11099 (cond
11100 ;; Look for targets, only if not in a headline search.
11101 ((and (not starred)
11102 (let ((target (format "<<%s>>" s-multi-re)))
11103 (catch :target-match
11104 (goto-char (point-min))
11105 (while (re-search-forward target nil t)
11106 (backward-char)
11107 (let ((context (org-element-context)))
11108 (when (eq (org-element-type context) 'target)
11109 (setq type 'dedicated)
11110 (goto-char (org-element-property :begin context))
11111 (throw :target-match t))))
11112 nil))))
11113 ;; Look for elements named after S, only if not in a headline
11114 ;; search.
11115 ((and (not starred)
11116 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11117 (catch :name-match
11118 (goto-char (point-min))
11119 (while (re-search-forward name nil t)
11120 (let ((element (org-element-at-point)))
11121 (when (equal (org-split-string
11122 (org-element-property :name element)
11123 "[ \t]+")
11124 words)
11125 (setq type 'dedicated)
11126 (beginning-of-line)
11127 (throw :name-match t))))
11128 nil))))
11129 ;; Regular text search. Prefer headlines in Org mode
11130 ;; buffers.
11131 ((and (derived-mode-p 'org-mode)
11132 (let* ((wspace "[ \t]")
11133 (wspaceopt (concat wspace "*"))
11134 (cookie (concat "\\(?:"
11135 wspaceopt
11136 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11137 wspaceopt
11138 "\\)"))
11139 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11140 (re (concat
11141 org-outline-regexp-bol
11142 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11143 "\\(?:\\[#.\\][ \t]+\\)?"
11144 "\\(?:" org-comment-string "[ \t]+\\)?"
11145 sep "?"
11146 (let ((title (mapconcat #'regexp-quote
11147 words
11148 sep)))
11149 (if starred (substring title 1) title))
11150 sep "?"
11151 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11152 "[ \t]*$")))
11153 (goto-char (point-min))
11154 (re-search-forward re nil t)))
11155 (goto-char (match-beginning 0))
11156 (setq type 'dedicated))
11157 ;; Offer to create non-existent headline depending on
11158 ;; `org-link-search-must-match-exact-headline'.
11159 ((and (derived-mode-p 'org-mode)
11160 (not org-link-search-inhibit-query)
11161 (eq org-link-search-must-match-exact-headline 'query-to-create)
11162 (yes-or-no-p "No match - create this as a new heading? "))
11163 (goto-char (point-max))
11164 (unless (bolp) (newline))
11165 (org-insert-heading nil t t)
11166 (insert s "\n")
11167 (beginning-of-line 0))
11168 ;; Only headlines are looked after. No need to process
11169 ;; further: throw an error.
11170 ((and (derived-mode-p 'org-mode)
11171 (or starred org-link-search-must-match-exact-headline))
11172 (goto-char origin)
11173 (error "No match for fuzzy expression: %s" normalized))
11174 ;; Regular text search.
11175 ((catch :fuzzy-match
11176 (goto-char (point-min))
11177 (while (re-search-forward s-multi-re nil t)
11178 ;; Skip match if it contains AVOID-POS or it is included
11179 ;; in a link with a description but outside the
11180 ;; description.
11181 (unless (or (and avoid-pos
11182 (<= (match-beginning 0) avoid-pos)
11183 (> (match-end 0) avoid-pos))
11184 (and (save-match-data
11185 (org-in-regexp org-bracket-link-regexp))
11186 (match-beginning 3)
11187 (or (> (match-beginning 3) (point))
11188 (<= (match-end 3) (point)))
11189 (org-element-lineage
11190 (save-match-data (org-element-context))
11191 '(link) t)))
11192 (goto-char (match-beginning 0))
11193 (setq type 'fuzzy)
11194 (throw :fuzzy-match t)))
11195 nil))
11196 ;; All failed. Throw an error.
11197 (t (goto-char origin)
11198 (error "No match for fuzzy expression: %s" normalized))))))
11199 ;; Disclose surroundings of match, if appropriate.
11200 (when (and (derived-mode-p 'org-mode) (not stealth))
11201 (org-show-context 'link-search))
11202 type))
11204 (defun org-get-buffer-for-internal-link (buffer)
11205 "Return a buffer to be used for displaying the link target of internal links."
11206 (cond
11207 ((not org-display-internal-link-with-indirect-buffer)
11208 buffer)
11209 ((string-match "(Clone)$" (buffer-name buffer))
11210 (message "Buffer is already a clone, not making another one")
11211 ;; we also do not modify visibility in this case
11212 buffer)
11213 (t ; make a new indirect buffer for displaying the link
11214 (let* ((bn (buffer-name buffer))
11215 (ibn (concat bn "(Clone)"))
11216 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11217 (with-current-buffer ib (org-overview))
11218 ib))))
11220 (defun org-do-occur (regexp &optional cleanup)
11221 "Call the Emacs command `occur'.
11222 If CLEANUP is non-nil, remove the printout of the regular expression
11223 in the *Occur* buffer. This is useful if the regex is long and not useful
11224 to read."
11225 (occur regexp)
11226 (when cleanup
11227 (let ((cwin (selected-window)) win beg end)
11228 (when (setq win (get-buffer-window "*Occur*"))
11229 (select-window win))
11230 (goto-char (point-min))
11231 (when (re-search-forward "match[a-z]+" nil t)
11232 (setq beg (match-end 0))
11233 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11234 (setq end (1- (match-beginning 0)))))
11235 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11236 (goto-char (point-min))
11237 (select-window cwin))))
11239 ;;; The mark ring for links jumps
11241 (defvar org-mark-ring nil
11242 "Mark ring for positions before jumps in Org-mode.")
11243 (defvar org-mark-ring-last-goto nil
11244 "Last position in the mark ring used to go back.")
11245 ;; Fill and close the ring
11246 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11247 (dotimes (_ org-mark-ring-length)
11248 (push (make-marker) org-mark-ring))
11249 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11250 org-mark-ring)
11252 (defun org-mark-ring-push (&optional pos buffer)
11253 "Put the current position or POS into the mark ring and rotate it."
11254 (interactive)
11255 (setq pos (or pos (point)))
11256 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11257 (move-marker (car org-mark-ring)
11258 (or pos (point))
11259 (or buffer (current-buffer)))
11260 (message "%s"
11261 (substitute-command-keys
11262 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11264 (defun org-mark-ring-goto (&optional n)
11265 "Jump to the previous position in the mark ring.
11266 With prefix arg N, jump back that many stored positions. When
11267 called several times in succession, walk through the entire ring.
11268 Org-mode commands jumping to a different position in the current file,
11269 or to another Org-mode file, automatically push the old position
11270 onto the ring."
11271 (interactive "p")
11272 (let (p m)
11273 (if (eq last-command this-command)
11274 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11275 (setq p org-mark-ring))
11276 (setq org-mark-ring-last-goto p)
11277 (setq m (car p))
11278 (org-pop-to-buffer-same-window (marker-buffer m))
11279 (goto-char m)
11280 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11282 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11283 ;;; Emacs 24.4+
11284 (defun org-remove-angle-brackets (s)
11285 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11286 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11288 (defun org-add-angle-brackets (s)
11289 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11290 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11292 (defun org-remove-double-quotes (s)
11293 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11294 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11297 ;;; Following specific links
11299 (defvar org-agenda-buffer-tmp-name)
11300 (defvar org-agenda-start-on-weekday)
11301 (defun org-follow-timestamp-link ()
11302 "Open an agenda view for the time-stamp date/range at point."
11303 (cond
11304 ((org-at-date-range-p t)
11305 (let ((org-agenda-start-on-weekday)
11306 (t1 (match-string 1))
11307 (t2 (match-string 2)) tt1 tt2)
11308 (setq tt1 (time-to-days (org-time-string-to-time t1))
11309 tt2 (time-to-days (org-time-string-to-time t2)))
11310 (let ((org-agenda-buffer-tmp-name
11311 (format "*Org Agenda(a:%s)"
11312 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11313 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11314 ((org-at-timestamp-p t)
11315 (let ((org-agenda-buffer-tmp-name
11316 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11317 (org-agenda-list nil (time-to-days (org-time-string-to-time
11318 (substring (match-string 1) 0 10)))
11319 1)))
11320 (t (error "This should not happen"))))
11323 ;;; Following file links
11324 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11325 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11326 (declare-function mailcap-mime-info
11327 "mailcap" (string &optional request no-decode))
11328 (defvar org-wait nil)
11329 (defun org-open-file (path &optional in-emacs line search)
11330 "Open the file at PATH.
11331 First, this expands any special file name abbreviations. Then the
11332 configuration variable `org-file-apps' is checked if it contains an
11333 entry for this file type, and if yes, the corresponding command is launched.
11335 If no application is found, Emacs simply visits the file.
11337 With optional prefix argument IN-EMACS, Emacs will visit the file.
11338 With a double \\[universal-argument] \\[universal-argument] \
11339 prefix arg, Org tries to avoid opening in Emacs
11340 and to use an external application to visit the file.
11342 Optional LINE specifies a line to go to, optional SEARCH a string
11343 to search for. If LINE or SEARCH is given, the file will be
11344 opened in Emacs, unless an entry from org-file-apps that makes
11345 use of groups in a regexp matches.
11347 If you want to change the way frames are used when following a
11348 link, please customize `org-link-frame-setup'.
11350 If the file does not exist, an error is thrown."
11351 (let* ((file (if (equal path "")
11352 buffer-file-name
11353 (substitute-in-file-name (expand-file-name path))))
11354 (file-apps (append org-file-apps (org-default-apps)))
11355 (apps (cl-remove-if
11356 'org-file-apps-entry-match-against-dlink-p file-apps))
11357 (apps-dlink (cl-remove-if-not
11358 'org-file-apps-entry-match-against-dlink-p file-apps))
11359 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11360 (dirp (unless remp (file-directory-p file)))
11361 (file (if (and dirp org-open-directory-means-index-dot-org)
11362 (concat (file-name-as-directory file) "index.org")
11363 file))
11364 (a-m-a-p (assq 'auto-mode apps))
11365 (dfile (downcase file))
11366 ;; Reconstruct the original link from the PATH, LINE and
11367 ;; SEARCH args.
11368 (link (cond (line (concat file "::" (number-to-string line)))
11369 (search (concat file "::" search))
11370 (t file)))
11371 (dlink (downcase link))
11372 (old-buffer (current-buffer))
11373 (old-pos (point))
11374 (old-mode major-mode)
11375 (ext
11376 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11377 (match-string 1 dfile)))
11378 cmd link-match-data)
11379 (cond
11380 ((member in-emacs '((16) system))
11381 (setq cmd (cdr (assq 'system apps))))
11382 (in-emacs (setq cmd 'emacs))
11384 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11385 (and dirp (cdr (assq 'directory apps)))
11386 ;; First, try matching against apps-dlink if we
11387 ;; get a match here, store the match data for
11388 ;; later.
11389 (let ((match (assoc-default dlink apps-dlink
11390 'string-match)))
11391 (if match
11392 (progn (setq link-match-data (match-data))
11393 match)
11394 (progn (setq in-emacs (or in-emacs line search))
11395 nil))) ; if we have no match in apps-dlink,
11396 ; always open the file in emacs if line or search
11397 ; is given (for backwards compatibility)
11398 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11399 'string-match)
11400 (cdr (assoc ext apps))
11401 (cdr (assq t apps))))))
11402 (when (eq cmd 'system)
11403 (setq cmd (cdr (assoc 'system apps))))
11404 (when (eq cmd 'default)
11405 (setq cmd (cdr (assoc t apps))))
11406 (when (eq cmd 'mailcap)
11407 (require 'mailcap)
11408 (mailcap-parse-mailcaps)
11409 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11410 (command (mailcap-mime-info mime-type)))
11411 (if (stringp command)
11412 (setq cmd command)
11413 (setq cmd 'emacs))))
11414 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11415 (not (file-exists-p file))
11416 (not org-open-non-existing-files))
11417 (user-error "No such file: %s" file))
11418 (cond
11419 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11420 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11421 (while (string-match "['\"]%s['\"]" cmd)
11422 (setq cmd (replace-match "%s" t t cmd)))
11423 (while (string-match "%s" cmd)
11424 (setq cmd (replace-match
11425 (save-match-data
11426 (shell-quote-argument
11427 (convert-standard-filename file)))
11428 t t cmd)))
11430 ;; Replace "%1", "%2" etc. in command with group matches from regex
11431 (save-match-data
11432 (let ((match-index 1)
11433 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11434 (set-match-data link-match-data)
11435 (while (<= match-index number-of-groups)
11436 (let ((regex (concat "%" (number-to-string match-index)))
11437 (replace-with (match-string match-index dlink)))
11438 (while (string-match regex cmd)
11439 (setq cmd (replace-match replace-with t t cmd))))
11440 (setq match-index (+ match-index 1)))))
11442 (save-window-excursion
11443 (message "Running %s...done" cmd)
11444 (start-process-shell-command cmd nil cmd)
11445 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11446 ((or (stringp cmd)
11447 (eq cmd 'emacs))
11448 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11449 (widen)
11450 (cond (line (org-goto-line line)
11451 (when (derived-mode-p 'org-mode) (org-reveal)))
11452 (search (org-link-search search))))
11453 ((functionp cmd)
11454 (save-match-data
11455 (set-match-data link-match-data)
11456 (condition-case nil
11457 (funcall cmd file link)
11458 ;; FIXME: Remove this check when most default installations
11459 ;; of Emacs have at least Org 9.0.
11460 ((debug wrong-number-of-arguments wrong-type-argument
11461 invalid-function)
11462 (user-error "Please see Org News for version 9.0 about \
11463 `org-file-apps'--Lisp error: %S" cmd)))))
11464 ((consp cmd)
11465 ;; FIXME: Remove this check when most default installations of
11466 ;; Emacs have at least Org 9.0.
11467 ;; Heads-up instead of silently fall back to
11468 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11469 ;; with sexp instead of a function for `cmd'.
11470 (user-error "Please see Org News for version 9.0 about \
11471 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11472 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11473 (and (derived-mode-p 'org-mode)
11474 (eq old-mode 'org-mode)
11475 (or (not (eq old-buffer (current-buffer)))
11476 (not (eq old-pos (point))))
11477 (org-mark-ring-push old-pos old-buffer))))
11479 (defun org-file-apps-entry-match-against-dlink-p (entry)
11480 "This function returns non-nil if `entry' uses a regular
11481 expression which should be matched against the whole link by
11482 org-open-file.
11484 It assumes that is the case when the entry uses a regular
11485 expression which has at least one grouping construct and the
11486 action is either a lisp form or a command string containing
11487 `%1', i.e. using at least one subexpression match as a
11488 parameter."
11489 (let ((selector (car entry))
11490 (action (cdr entry)))
11491 (if (stringp selector)
11492 (and (> (regexp-opt-depth selector) 0)
11493 (or (and (stringp action)
11494 (string-match "%[0-9]" action))
11495 (consp action)))
11496 nil)))
11498 (defun org-default-apps ()
11499 "Return the default applications for this operating system."
11500 (cond
11501 ((eq system-type 'darwin)
11502 org-file-apps-defaults-macosx)
11503 ((eq system-type 'windows-nt)
11504 org-file-apps-defaults-windowsnt)
11505 (t org-file-apps-defaults-gnu)))
11507 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11508 "Convert extensions to regular expressions in the cars of LIST.
11509 Also, weed out any non-string entries, because the return value is used
11510 only for regexp matching.
11511 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11512 point to the symbol `emacs', indicating that the file should
11513 be opened in Emacs."
11514 (append
11515 (delq nil
11516 (mapcar (lambda (x)
11517 (unless (not (stringp (car x)))
11518 (if (string-match "\\W" (car x))
11520 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11521 list))
11522 (when add-auto-mode
11523 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11525 (defvar ange-ftp-name-format)
11526 (defun org-file-remote-p (file)
11527 "Test whether FILE specifies a location on a remote system.
11528 Return non-nil if the location is indeed remote.
11530 For example, the filename \"/user@host:/foo\" specifies a location
11531 on the system \"/user@host:\"."
11532 (cond ((fboundp 'file-remote-p)
11533 (file-remote-p file))
11534 ((fboundp 'tramp-handle-file-remote-p)
11535 (tramp-handle-file-remote-p file))
11536 ((and (boundp 'ange-ftp-name-format)
11537 (string-match (car ange-ftp-name-format) file))
11538 t)))
11541 ;;;; Refiling
11543 (defun org-get-org-file ()
11544 "Read a filename, with default directory `org-directory'."
11545 (let ((default (or org-default-notes-file remember-data-file)))
11546 (read-file-name (format "File name [%s]: " default)
11547 (file-name-as-directory org-directory)
11548 default)))
11550 (defun org-notes-order-reversed-p ()
11551 "Check if the current file should receive notes in reversed order."
11552 (cond
11553 ((not org-reverse-note-order) nil)
11554 ((eq t org-reverse-note-order) t)
11555 ((not (listp org-reverse-note-order)) nil)
11556 (t (catch 'exit
11557 (dolist (entry org-reverse-note-order)
11558 (when (string-match (car entry) buffer-file-name)
11559 (throw 'exit (cdr entry))))))))
11561 (defvar org-refile-target-table nil
11562 "The list of refile targets, created by `org-refile'.")
11564 (defvar org-agenda-new-buffers nil
11565 "Buffers created to visit agenda files.")
11567 (defvar org-refile-cache nil
11568 "Cache for refile targets.")
11570 (defvar org-refile-markers nil
11571 "All the markers used for caching refile locations.")
11573 (defun org-refile-marker (pos)
11574 "Get a new refile marker, but only if caching is in use."
11575 (if (not org-refile-use-cache)
11577 (let ((m (make-marker)))
11578 (move-marker m pos)
11579 (push m org-refile-markers)
11580 m)))
11582 (defun org-refile-cache-clear ()
11583 "Clear the refile cache and disable all the markers."
11584 (dolist (m org-refile-markers) (move-marker m nil))
11585 (setq org-refile-markers nil)
11586 (setq org-refile-cache nil)
11587 (message "Refile cache has been cleared"))
11589 (defun org-refile-cache-check-set (set)
11590 "Check if all the markers in the cache still have live buffers."
11591 (let (marker)
11592 (catch 'exit
11593 (while (and set (setq marker (nth 3 (pop set))))
11594 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11595 (when (and marker (null (marker-buffer marker)))
11596 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11597 (sit-for 3)
11598 (throw 'exit nil)))
11599 t)))
11601 (defun org-refile-cache-put (set &rest identifiers)
11602 "Push the refile targets SET into the cache, under IDENTIFIERS."
11603 (let* ((key (sha1 (prin1-to-string identifiers)))
11604 (entry (assoc key org-refile-cache)))
11605 (if entry
11606 (setcdr entry set)
11607 (push (cons key set) org-refile-cache))))
11609 (defun org-refile-cache-get (&rest identifiers)
11610 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11611 (cond
11612 ((not org-refile-cache) nil)
11613 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11615 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11616 org-refile-cache))))
11617 (and set (org-refile-cache-check-set set) set)))))
11619 (defvar org-outline-path-cache nil
11620 "Alist between buffer positions and outline paths.
11621 It value is an alist (POSITION . PATH) where POSITION is the
11622 buffer position at the beginning of an entry and PATH is a list
11623 of strings describing the outline path for that entry, in reverse
11624 order.")
11626 (defun org-refile-get-targets (&optional default-buffer)
11627 "Produce a table with refile targets."
11628 (let ((case-fold-search nil)
11629 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11630 (entries (or org-refile-targets '((nil . (:level . 1)))))
11631 targets tgs files desc descre)
11632 (message "Getting targets...")
11633 (with-current-buffer (or default-buffer (current-buffer))
11634 (dolist (entry entries)
11635 (setq files (car entry) desc (cdr entry))
11636 (cond
11637 ((null files) (setq files (list (current-buffer))))
11638 ((eq files 'org-agenda-files)
11639 (setq files (org-agenda-files 'unrestricted)))
11640 ((and (symbolp files) (fboundp files))
11641 (setq files (funcall files)))
11642 ((and (symbolp files) (boundp files))
11643 (setq files (symbol-value files))))
11644 (when (stringp files) (setq files (list files)))
11645 (cond
11646 ((eq (car desc) :tag)
11647 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11648 ((eq (car desc) :todo)
11649 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11650 ((eq (car desc) :regexp)
11651 (setq descre (cdr desc)))
11652 ((eq (car desc) :level)
11653 (setq descre (concat "^\\*\\{" (number-to-string
11654 (if org-odd-levels-only
11655 (1- (* 2 (cdr desc)))
11656 (cdr desc)))
11657 "\\}[ \t]")))
11658 ((eq (car desc) :maxlevel)
11659 (setq descre (concat "^\\*\\{1," (number-to-string
11660 (if org-odd-levels-only
11661 (1- (* 2 (cdr desc)))
11662 (cdr desc)))
11663 "\\}[ \t]")))
11664 (t (error "Bad refiling target description %s" desc)))
11665 (dolist (f files)
11666 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11668 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11669 (progn
11670 (when (bufferp f)
11671 (setq f (buffer-file-name (buffer-base-buffer f))))
11672 (setq f (and f (expand-file-name f)))
11673 (when (eq org-refile-use-outline-path 'file)
11674 (push (list (file-name-nondirectory f) f nil nil) tgs))
11675 (org-with-wide-buffer
11676 (goto-char (point-min))
11677 (setq org-outline-path-cache nil)
11678 (while (re-search-forward descre nil t)
11679 (beginning-of-line)
11680 (looking-at org-complex-heading-regexp)
11681 (let ((begin (point))
11682 (heading (match-string-no-properties 4)))
11683 (unless (or (and
11684 org-refile-target-verify-function
11685 (not
11686 (funcall org-refile-target-verify-function)))
11687 (not heading))
11688 (let ((re (format org-complex-heading-regexp-format
11689 (regexp-quote heading)))
11690 (target
11691 (if (not org-refile-use-outline-path) heading
11692 (mapconcat
11693 #'org-protect-slash
11694 (append
11695 (pcase org-refile-use-outline-path
11696 (`file (list (file-name-nondirectory
11697 (buffer-file-name
11698 (buffer-base-buffer)))))
11699 (`full-file-path
11700 (list (buffer-file-name
11701 (buffer-base-buffer))))
11702 (_ nil))
11703 (org-get-outline-path t t))
11704 "/"))))
11705 (push (list target f re (org-refile-marker (point)))
11706 tgs)))
11707 (when (= (point) begin)
11708 ;; Verification function has not moved point.
11709 (end-of-line)))))))
11710 (when org-refile-use-cache
11711 (org-refile-cache-put tgs (buffer-file-name) descre))
11712 (setq targets (append tgs targets))))))
11713 (message "Getting targets...done")
11714 (nreverse targets)))
11716 (defun org-protect-slash (s)
11717 (while (string-match "/" s)
11718 (setq s (replace-match "\\" t t s)))
11721 (defun org--get-outline-path-1 (&optional use-cache)
11722 "Return outline path to current headline.
11724 Outline path is a list of strings, in reverse order. When
11725 optional argument USE-CACHE is non-nil, make use of a cache. See
11726 `org-get-outline-path' for details.
11728 Assume buffer is widened and point is on a headline."
11729 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11730 (let ((p (point))
11731 (heading (progn
11732 (looking-at org-complex-heading-regexp)
11733 (if (not (match-end 4)) ""
11734 ;; Remove statistics cookies.
11735 (org-trim
11736 (org-link-display-format
11737 (replace-regexp-in-string
11738 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11739 (match-string-no-properties 4))))))))
11740 (if (org-up-heading-safe)
11741 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11742 (when use-cache
11743 (push (cons p path) org-outline-path-cache))
11744 path)
11745 ;; This is a new root node. Since we assume we are moving
11746 ;; forward, we can drop previous cache so as to limit number
11747 ;; of associations there.
11748 (let ((path (list heading)))
11749 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11750 path)))))
11752 (defun org-get-outline-path (&optional with-self use-cache)
11753 "Return the outline path to the current entry.
11755 An outline path is a list of ancestors for current headline, as
11756 a list of strings. Statistics cookies are removed and links are
11757 replaced with their description, if any, or their path otherwise.
11759 When optional argument WITH-SELF is non-nil, the path also
11760 includes the current headline.
11762 When optional argument USE-CACHE is non-nil, cache outline paths
11763 between calls to this function so as to avoid backtracking. This
11764 argument is useful when planning to find more than one outline
11765 path in the same document. In that case, there are two
11766 conditions to satisfy:
11767 - `org-outline-path-cache' is set to nil before starting the
11768 process;
11769 - outline paths are computed by increasing buffer positions."
11770 (org-with-wide-buffer
11771 (and (or (and with-self (org-back-to-heading t))
11772 (org-up-heading-safe))
11773 (reverse (org--get-outline-path-1 use-cache)))))
11775 (defun org-format-outline-path (path &optional width prefix separator)
11776 "Format the outline path PATH for display.
11777 WIDTH is the maximum number of characters that is available.
11778 PREFIX is a prefix to be included in the returned string,
11779 such as the file name.
11780 SEPARATOR is inserted between the different parts of the path,
11781 the default is \"/\"."
11782 (setq width (or width 79))
11783 (setq path (delq nil path))
11784 (unless (> width 0)
11785 (user-error "Argument `width' must be positive"))
11786 (setq separator (or separator "/"))
11787 (let* ((org-odd-levels-only nil)
11788 (fpath (concat
11789 prefix (and prefix path separator)
11790 (mapconcat
11791 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11792 (cl-loop for head in path
11793 for n from 0
11794 collect (org-add-props
11795 head nil 'face
11796 (nth (% n org-n-level-faces) org-level-faces)))
11797 separator))))
11798 (when (> (length fpath) width)
11799 (if (< width 7)
11800 ;; It's unlikely that `width' will be this small, but don't
11801 ;; waste characters by adding ".." if it is.
11802 (setq fpath (substring fpath 0 width))
11803 (setf (substring fpath (- width 2)) "..")))
11804 fpath))
11806 (defun org-display-outline-path (&optional file current separator just-return-string)
11807 "Display the current outline path in the echo area.
11809 If FILE is non-nil, prepend the output with the file name.
11810 If CURRENT is non-nil, append the current heading to the output.
11811 SEPARATOR is passed through to `org-format-outline-path'. It separates
11812 the different parts of the path and defaults to \"/\".
11813 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11814 (interactive "P")
11815 (let* (case-fold-search
11816 (bfn (buffer-file-name (buffer-base-buffer)))
11817 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11818 res)
11819 (when current (setq path (append path
11820 (save-excursion
11821 (org-back-to-heading t)
11822 (when (looking-at org-complex-heading-regexp)
11823 (list (match-string 4)))))))
11824 (setq res
11825 (org-format-outline-path
11826 path
11827 (1- (frame-width))
11828 (and file bfn (concat (file-name-nondirectory bfn) separator))
11829 separator))
11830 (if just-return-string
11831 (org-no-properties res)
11832 (org-unlogged-message "%s" res))))
11834 (defvar org-refile-history nil
11835 "History for refiling operations.")
11837 (defvar org-after-refile-insert-hook nil
11838 "Hook run after `org-refile' has inserted its stuff at the new location.
11839 Note that this is still *before* the stuff will be removed from
11840 the *old* location.")
11842 (defvar org-capture-last-stored-marker)
11843 (defvar org-refile-keep nil
11844 "Non-nil means `org-refile' will copy instead of refile.")
11846 (defun org-copy ()
11847 "Like `org-refile', but copy."
11848 (interactive)
11849 (let ((org-refile-keep t))
11850 (funcall 'org-refile nil nil nil "Copy")))
11852 (defun org-refile (&optional arg default-buffer rfloc msg)
11853 "Move the entry or entries at point to another heading.
11854 The list of target headings is compiled using the information in
11855 `org-refile-targets', which see.
11857 At the target location, the entry is filed as a subitem of the
11858 target heading. Depending on `org-reverse-note-order', the new
11859 subitem will either be the first or the last subitem.
11861 If there is an active region, all entries in that region will be
11862 refiled. However, the region must fulfill the requirement that
11863 the first heading sets the top-level of the moved text.
11865 With prefix arg ARG, the command will only visit the target
11866 location and not actually move anything.
11868 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11869 refiling operation has put the subtree.
11871 With a numeric prefix argument of `2', refile to the running clock.
11873 With a numeric prefix argument of `3', emulate `org-refile-keep'
11874 being set to t and copy to the target location, don't move it.
11875 Beware that keeping refiled entries may result in duplicated ID
11876 properties.
11878 RFLOC can be a refile location obtained in a different way.
11880 MSG is a string to replace \"Refile\" in the default prompt with
11881 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11883 See also `org-refile-use-outline-path'.
11885 If you are using target caching (see `org-refile-use-cache'), you
11886 have to clear the target cache in order to find new targets.
11887 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11888 prefix argument (`C-u C-u C-u C-c C-w')."
11889 (interactive "P")
11890 (if (member arg '(0 (64)))
11891 (org-refile-cache-clear)
11892 (let* ((actionmsg (cond (msg msg)
11893 ((equal arg 3) "Refile (and keep)")
11894 (t "Refile")))
11895 (regionp (org-region-active-p))
11896 (region-start (and regionp (region-beginning)))
11897 (region-end (and regionp (region-end)))
11898 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11899 pos it nbuf file level reversed)
11900 (setq last-command nil)
11901 (when regionp
11902 (goto-char region-start)
11903 (or (bolp) (goto-char (point-at-bol)))
11904 (setq region-start (point))
11905 (unless (or (org-kill-is-subtree-p
11906 (buffer-substring region-start region-end))
11907 (prog1 org-refile-active-region-within-subtree
11908 (let ((s (point-at-eol)))
11909 (org-toggle-heading)
11910 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11911 (user-error "The region is not a (sequence of) subtree(s)")))
11912 (if (equal arg '(16))
11913 (org-refile-goto-last-stored)
11914 (when (or
11915 (and (equal arg 2)
11916 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11917 (prog1
11918 (setq it (list (or org-clock-heading "running clock")
11919 (buffer-file-name
11920 (marker-buffer org-clock-hd-marker))
11922 (marker-position org-clock-hd-marker)))
11923 (setq arg nil)))
11924 (setq it
11925 (or rfloc
11926 (let (heading-text)
11927 (save-excursion
11928 (unless (and arg (listp arg))
11929 (org-back-to-heading t)
11930 (setq heading-text
11931 (replace-regexp-in-string
11932 org-bracket-link-regexp
11933 "\\3"
11934 (nth 4 (org-heading-components)))))
11935 (org-refile-get-location
11936 (cond ((and arg (listp arg)) "Goto")
11937 (regionp (concat actionmsg " region to"))
11938 (t (concat actionmsg " subtree \""
11939 heading-text "\" to")))
11940 default-buffer
11941 (and (not (equal '(4) arg))
11942 org-refile-allow-creating-parent-nodes)))))))
11943 (setq file (nth 1 it)
11944 pos (nth 3 it))
11945 (when (and (not arg)
11947 (equal (buffer-file-name) file)
11948 (if regionp
11949 (and (>= pos region-start)
11950 (<= pos region-end))
11951 (and (>= pos (point))
11952 (< pos (save-excursion
11953 (org-end-of-subtree t t))))))
11954 (error "Cannot refile to position inside the tree or region"))
11955 (setq nbuf (or (find-buffer-visiting file)
11956 (find-file-noselect file)))
11957 (if (and arg (not (equal arg 3)))
11958 (progn
11959 (org-pop-to-buffer-same-window nbuf)
11960 (goto-char pos)
11961 (org-show-context 'org-goto))
11962 (if regionp
11963 (progn
11964 (org-kill-new (buffer-substring region-start region-end))
11965 (org-save-markers-in-region region-start region-end))
11966 (org-copy-subtree 1 nil t))
11967 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11968 (find-file-noselect file)))
11969 (setq reversed (org-notes-order-reversed-p))
11970 (save-excursion
11971 (save-restriction
11972 (widen)
11973 (if pos
11974 (progn
11975 (goto-char pos)
11976 (looking-at org-outline-regexp)
11977 (setq level (org-get-valid-level (funcall outline-level) 1))
11978 (goto-char
11979 (if reversed
11980 (or (outline-next-heading) (point-max))
11981 (or (save-excursion (org-get-next-sibling))
11982 (org-end-of-subtree t t)
11983 (point-max)))))
11984 (setq level 1)
11985 (if (not reversed)
11986 (goto-char (point-max))
11987 (goto-char (point-min))
11988 (or (outline-next-heading) (goto-char (point-max)))))
11989 (unless (bolp) (newline))
11990 (org-paste-subtree level nil nil t)
11991 (when org-log-refile
11992 (org-add-log-setup 'refile nil nil org-log-refile)
11993 (unless (eq org-log-refile 'note)
11994 (save-excursion (org-add-log-note))))
11995 (and org-auto-align-tags
11996 (let ((org-loop-over-headlines-in-active-region nil))
11997 (org-set-tags nil t)))
11998 (let ((bookmark-name (plist-get org-bookmark-names-plist
11999 :last-refile)))
12000 (when bookmark-name
12001 (with-demoted-errors
12002 (bookmark-set bookmark-name))))
12003 ;; If we are refiling for capture, make sure that the
12004 ;; last-capture pointers point here
12005 (when (org-bound-and-true-p org-capture-is-refiling)
12006 (let ((bookmark-name (plist-get org-bookmark-names-plist
12007 :last-capture-marker)))
12008 (when bookmark-name
12009 (with-demoted-errors
12010 (bookmark-set bookmark-name))))
12011 (move-marker org-capture-last-stored-marker (point)))
12012 (when (fboundp 'deactivate-mark) (deactivate-mark))
12013 (run-hooks 'org-after-refile-insert-hook))))
12014 (unless org-refile-keep
12015 (if regionp
12016 (delete-region (point) (+ (point) (- region-end region-start)))
12017 (delete-region
12018 (and (org-back-to-heading t) (point))
12019 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12020 (when (featurep 'org-inlinetask)
12021 (org-inlinetask-remove-END-maybe))
12022 (setq org-markers-to-move nil)
12023 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12025 (defun org-refile-goto-last-stored ()
12026 "Go to the location where the last refile was stored."
12027 (interactive)
12028 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12029 (message "This is the location of the last refile"))
12031 (defun org-refile--get-location (refloc tbl)
12032 "When user refile to REFLOC, find the associated target in TBL.
12033 Also check `org-refile-target-table'."
12034 (car (delq
12036 (mapcar
12037 (lambda (r) (or (assoc r tbl)
12038 (assoc r org-refile-target-table)))
12039 (list (replace-regexp-in-string "/$" "" refloc)
12040 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12042 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12043 "Prompt the user for a refile location, using PROMPT.
12044 PROMPT should not be suffixed with a colon and a space, because
12045 this function appends the default value from
12046 `org-refile-history' automatically, if that is not empty."
12047 (let ((org-refile-targets org-refile-targets)
12048 (org-refile-use-outline-path org-refile-use-outline-path))
12049 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12050 (unless org-refile-target-table
12051 (user-error "No refile targets"))
12052 (let* ((cbuf (current-buffer))
12053 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12054 (cfunc (if (and org-refile-use-outline-path
12055 org-outline-path-complete-in-steps)
12056 #'org-olpath-completing-read
12057 #'completing-read))
12058 (extra (if org-refile-use-outline-path "/" ""))
12059 (cbnex (concat (buffer-name) extra))
12060 (filename (and cfn (expand-file-name cfn)))
12061 (tbl (mapcar
12062 (lambda (x)
12063 (if (and (not (member org-refile-use-outline-path
12064 '(file full-file-path)))
12065 (not (equal filename (nth 1 x))))
12066 (cons (concat (car x) extra " ("
12067 (file-name-nondirectory (nth 1 x)) ")")
12068 (cdr x))
12069 (cons (concat (car x) extra) (cdr x))))
12070 org-refile-target-table))
12071 (completion-ignore-case t)
12072 cdef
12073 (prompt (concat prompt
12074 (or (and (car org-refile-history)
12075 (concat " (default " (car org-refile-history) ")"))
12076 (and (assoc cbnex tbl) (setq cdef cbnex)
12077 (concat " (default " cbnex ")"))) ": "))
12078 pa answ parent-target child parent old-hist)
12079 (setq old-hist org-refile-history)
12080 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12081 nil 'org-refile-history (or cdef (car org-refile-history))))
12082 (if (setq pa (org-refile--get-location answ tbl))
12083 (progn
12084 (org-refile-check-position pa)
12085 (when (or (not org-refile-history)
12086 (not (eq old-hist org-refile-history))
12087 (not (equal (car pa) (car org-refile-history))))
12088 (setq org-refile-history
12089 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12090 org-refile-history
12091 (cdr org-refile-history))))
12092 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12093 (pop org-refile-history)))
12095 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12096 (progn
12097 (setq parent (match-string 1 answ)
12098 child (match-string 2 answ))
12099 (setq parent-target (org-refile--get-location parent tbl))
12100 (when (and parent-target
12101 (or (eq new-nodes t)
12102 (and (eq new-nodes 'confirm)
12103 (y-or-n-p (format "Create new node \"%s\"? "
12104 child)))))
12105 (org-refile-new-child parent-target child)))
12106 (user-error "Invalid target location")))))
12108 (declare-function org-string-nw-p "org-macs" (s))
12109 (defun org-refile-check-position (refile-pointer)
12110 "Check if the refile pointer matches the headline to which it points."
12111 (let* ((file (nth 1 refile-pointer))
12112 (re (nth 2 refile-pointer))
12113 (pos (nth 3 refile-pointer))
12114 buffer)
12115 (if (and (not (markerp pos)) (not file))
12116 (user-error "Please indicate a target file in the refile path")
12117 (when (org-string-nw-p re)
12118 (setq buffer (if (markerp pos)
12119 (marker-buffer pos)
12120 (or (find-buffer-visiting file)
12121 (find-file-noselect file))))
12122 (with-current-buffer buffer
12123 (save-excursion
12124 (save-restriction
12125 (widen)
12126 (goto-char pos)
12127 (beginning-of-line 1)
12128 (unless (looking-at-p re)
12129 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12131 (defun org-refile-new-child (parent-target child)
12132 "Use refile target PARENT-TARGET to add new CHILD below it."
12133 (unless parent-target
12134 (error "Cannot find parent for new node"))
12135 (let ((file (nth 1 parent-target))
12136 (pos (nth 3 parent-target))
12137 level)
12138 (with-current-buffer (or (find-buffer-visiting file)
12139 (find-file-noselect file))
12140 (save-excursion
12141 (save-restriction
12142 (widen)
12143 (if pos
12144 (goto-char pos)
12145 (goto-char (point-max))
12146 (unless (bolp) (newline)))
12147 (when (looking-at org-outline-regexp)
12148 (setq level (funcall outline-level))
12149 (org-end-of-subtree t t))
12150 (org-back-over-empty-lines)
12151 (insert "\n" (make-string
12152 (if pos (org-get-valid-level level 1) 1) ?*)
12153 " " child "\n")
12154 (beginning-of-line 0)
12155 (list (concat (car parent-target) "/" child) file "" (point)))))))
12157 (defun org-olpath-completing-read (prompt collection &rest args)
12158 "Read an outline path like a file name."
12159 (let ((thetable collection))
12160 (apply #'completing-read
12161 prompt
12162 (lambda (string predicate &optional flag)
12163 (cond
12164 ((eq flag nil) (try-completion string thetable))
12165 ((eq flag t)
12166 (let ((l (length string)))
12167 (mapcar (lambda (x)
12168 (let ((r (substring x l))
12169 (f (if (string-match " ([^)]*)$" x)
12170 (match-string 0 x)
12171 "")))
12172 (if (string-match "/" r)
12173 (concat string (substring r 0 (match-end 0)) f)
12174 x)))
12175 (all-completions string thetable predicate))))
12176 ;; Exact match?
12177 ((eq flag 'lambda) (assoc string thetable))))
12178 args)))
12180 ;;;; Dynamic blocks
12182 (defun org-find-dblock (name)
12183 "Find the first dynamic block with name NAME in the buffer.
12184 If not found, stay at current position and return nil."
12185 (let ((case-fold-search t) pos)
12186 (save-excursion
12187 (goto-char (point-min))
12188 (setq pos (and (re-search-forward
12189 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12190 (match-beginning 0))))
12191 (when pos (goto-char pos))
12192 pos))
12194 (defun org-create-dblock (plist)
12195 "Create a dynamic block section, with parameters taken from PLIST.
12196 PLIST must contain a :name entry which is used as the name of the block."
12197 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12198 (end-of-line 1)
12199 (newline))
12200 (let ((col (current-column))
12201 (name (plist-get plist :name)))
12202 (insert "#+BEGIN: " name)
12203 (while plist
12204 (if (eq (car plist) :name)
12205 (setq plist (cddr plist))
12206 (insert " " (prin1-to-string (pop plist)))))
12207 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12208 (beginning-of-line -2)))
12210 (defun org-prepare-dblock ()
12211 "Prepare dynamic block for refresh.
12212 This empties the block, puts the cursor at the insert position and returns
12213 the property list including an extra property :name with the block name."
12214 (unless (looking-at org-dblock-start-re)
12215 (user-error "Not at a dynamic block"))
12216 (let* ((begdel (1+ (match-end 0)))
12217 (name (org-no-properties (match-string 1)))
12218 (params (append (list :name name)
12219 (read (concat "(" (match-string 3) ")")))))
12220 (save-excursion
12221 (beginning-of-line 1)
12222 (skip-chars-forward " \t")
12223 (setq params (plist-put params :indentation-column (current-column))))
12224 (unless (re-search-forward org-dblock-end-re nil t)
12225 (error "Dynamic block not terminated"))
12226 (setq params
12227 (append params
12228 (list :content (buffer-substring
12229 begdel (match-beginning 0)))))
12230 (delete-region begdel (match-beginning 0))
12231 (goto-char begdel)
12232 (open-line 1)
12233 params))
12235 (defun org-map-dblocks (&optional command)
12236 "Apply COMMAND to all dynamic blocks in the current buffer.
12237 If COMMAND is not given, use `org-update-dblock'."
12238 (let ((cmd (or command 'org-update-dblock)))
12239 (save-excursion
12240 (goto-char (point-min))
12241 (while (re-search-forward org-dblock-start-re nil t)
12242 (goto-char (match-beginning 0))
12243 (save-excursion
12244 (condition-case nil
12245 (funcall cmd)
12246 (error (message "Error during update of dynamic block"))))
12247 (unless (re-search-forward org-dblock-end-re nil t)
12248 (error "Dynamic block not terminated"))))))
12250 (defun org-dblock-update (&optional arg)
12251 "User command for updating dynamic blocks.
12252 Update the dynamic block at point. With prefix ARG, update all dynamic
12253 blocks in the buffer."
12254 (interactive "P")
12255 (if arg
12256 (org-update-all-dblocks)
12257 (or (looking-at org-dblock-start-re)
12258 (org-beginning-of-dblock))
12259 (org-update-dblock)))
12261 (defun org-update-dblock ()
12262 "Update the dynamic block at point.
12263 This means to empty the block, parse for parameters and then call
12264 the correct writing function."
12265 (interactive)
12266 (save-excursion
12267 (let* ((win (selected-window))
12268 (pos (point))
12269 (line (org-current-line))
12270 (params (org-prepare-dblock))
12271 (name (plist-get params :name))
12272 (indent (plist-get params :indentation-column))
12273 (cmd (intern (concat "org-dblock-write:" name))))
12274 (message "Updating dynamic block `%s' at line %d..." name line)
12275 (funcall cmd params)
12276 (message "Updating dynamic block `%s' at line %d...done" name line)
12277 (goto-char pos)
12278 (when (and indent (> indent 0))
12279 (setq indent (make-string indent ?\ ))
12280 (save-excursion
12281 (select-window win)
12282 (org-beginning-of-dblock)
12283 (forward-line 1)
12284 (while (not (looking-at org-dblock-end-re))
12285 (insert indent)
12286 (beginning-of-line 2))
12287 (when (looking-at org-dblock-end-re)
12288 (and (looking-at "[ \t]+")
12289 (replace-match ""))
12290 (insert indent)))))))
12292 (defun org-beginning-of-dblock ()
12293 "Find the beginning of the dynamic block at point.
12294 Error if there is no such block at point."
12295 (let ((pos (point))
12296 beg)
12297 (end-of-line 1)
12298 (if (and (re-search-backward org-dblock-start-re nil t)
12299 (setq beg (match-beginning 0))
12300 (re-search-forward org-dblock-end-re nil t)
12301 (> (match-end 0) pos))
12302 (goto-char beg)
12303 (goto-char pos)
12304 (error "Not in a dynamic block"))))
12306 (defun org-update-all-dblocks ()
12307 "Update all dynamic blocks in the buffer.
12308 This function can be used in a hook."
12309 (interactive)
12310 (when (derived-mode-p 'org-mode)
12311 (org-map-dblocks 'org-update-dblock)))
12314 ;;;; Completion
12316 (declare-function org-export-backend-options "ox" (cl-x) t)
12317 (defun org-get-export-keywords ()
12318 "Return a list of all currently understood export keywords.
12319 Export keywords include options, block names, attributes and
12320 keywords relative to each registered export back-end."
12321 (let (keywords)
12322 (dolist (backend
12323 (org-bound-and-true-p org-export-registered-backends)
12324 (delq nil keywords))
12325 ;; Back-end name (for keywords, like #+LATEX:)
12326 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12327 (dolist (option-entry (org-export-backend-options backend))
12328 ;; Back-end options.
12329 (push (nth 1 option-entry) keywords)))))
12331 (defconst org-options-keywords
12332 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12333 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12334 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12335 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12336 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12338 (defcustom org-structure-template-alist
12339 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12340 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12341 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12342 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12343 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12344 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12345 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12346 ("L" "#+LaTeX: ")
12347 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12348 ("H" "#+HTML: ")
12349 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12350 ("A" "#+ASCII: ")
12351 ("i" "#+INDEX: ?")
12352 ("I" "#+INCLUDE: %file ?"))
12353 "Structure completion elements.
12354 This is a list of abbreviation keys and values. The value gets inserted
12355 if you type `<' followed by the key and then press the completion key,
12356 usually `TAB'. %file will be replaced by a file name after prompting
12357 for the file using completion. The cursor will be placed at the position
12358 of the `?' in the template.
12359 There are two templates for each key, the first uses the original Org syntax,
12360 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12361 the default when the /org-mtags.el/ module has been loaded. See also the
12362 variable `org-mtags-prefer-muse-templates'."
12363 :group 'org-completion
12364 :type '(repeat
12365 (list
12366 (string :tag "Key")
12367 (string :tag "Template")))
12368 :version "25.1"
12369 :package-version '(Org . "8.3"))
12371 (defun org-try-structure-completion ()
12372 "Try to complete a structure template before point.
12373 This looks for strings like \"<e\" on an otherwise empty line and
12374 expands them."
12375 (let ((l (buffer-substring (point-at-bol) (point)))
12377 (when (and (looking-at "[ \t]*$")
12378 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12379 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12380 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12381 (match-beginning 1)) a)
12382 t)))
12384 (defun org-complete-expand-structure-template (start cell)
12385 "Expand a structure template."
12386 (let ((rpl (nth 1 cell))
12387 (ind ""))
12388 (delete-region start (point))
12389 (when (string-match "\\`[ \t]*#\\+" rpl)
12390 (cond
12391 ((bolp))
12392 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12393 (setq ind (buffer-substring (point-at-bol) (point))))
12394 (t (newline))))
12395 (setq start (point))
12396 (when (string-match "%file" rpl)
12397 (setq rpl (replace-match
12398 (concat
12399 "\""
12400 (save-match-data
12401 (abbreviate-file-name (read-file-name "Include file: ")))
12402 "\"")
12403 t t rpl)))
12404 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12405 (concat "\n" ind)))
12406 (insert rpl)
12407 (when (re-search-backward "\\?" start t) (delete-char 1))))
12409 ;;;; TODO, DEADLINE, Comments
12411 (defun org-toggle-comment ()
12412 "Change the COMMENT state of an entry."
12413 (interactive)
12414 (save-excursion
12415 (org-back-to-heading)
12416 (looking-at org-complex-heading-regexp)
12417 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12418 (skip-chars-forward " \t")
12419 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12420 (if (org-in-commented-heading-p t)
12421 (delete-region (point)
12422 (progn (search-forward " " (line-end-position) 'move)
12423 (skip-chars-forward " \t")
12424 (point)))
12425 (insert org-comment-string)
12426 (unless (eolp) (insert " ")))))
12428 (defvar org-last-todo-state-is-todo nil
12429 "This is non-nil when the last TODO state change led to a TODO state.
12430 If the last change removed the TODO tag or switched to DONE, then
12431 this is nil.")
12433 (defvar org-setting-tags nil) ; dynamically skipped
12435 (defvar org-todo-setup-filter-hook nil
12436 "Hook for functions that pre-filter todo specs.
12437 Each function takes a todo spec and returns either nil or the spec
12438 transformed into canonical form." )
12440 (defvar org-todo-get-default-hook nil
12441 "Hook for functions that get a default item for todo.
12442 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12443 nil or a string to be used for the todo mark." )
12445 (defvar org-agenda-headline-snapshot-before-repeat)
12447 (defun org-current-effective-time ()
12448 "Return current time adjusted for `org-extend-today-until' variable."
12449 (let* ((ct (org-current-time))
12450 (dct (decode-time ct))
12451 (ct1
12452 (cond
12453 (org-use-last-clock-out-time-as-effective-time
12454 (or (org-clock-get-last-clock-out-time) ct))
12455 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12456 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12457 (t ct))))
12458 ct1))
12460 (defun org-todo-yesterday (&optional arg)
12461 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12462 (interactive "P")
12463 (if (eq major-mode 'org-agenda-mode)
12464 (apply 'org-agenda-todo-yesterday arg)
12465 (let* ((org-use-effective-time t)
12466 (hour (nth 2 (decode-time (org-current-time))))
12467 (org-extend-today-until (1+ hour)))
12468 (org-todo arg))))
12470 (defvar org-block-entry-blocking ""
12471 "First entry preventing the TODO state change.")
12473 (defun org-cancel-repeater ()
12474 "Cancel a repeater by setting its numeric value to zero."
12475 (interactive)
12476 (save-excursion
12477 (org-back-to-heading t)
12478 (let ((bound1 (point))
12479 (bound0 (save-excursion (outline-next-heading) (point))))
12480 (when (and (re-search-forward
12481 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12482 org-deadline-time-regexp "\\)\\|\\("
12483 org-ts-regexp "\\)")
12484 bound0 t)
12485 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12486 bound1 t))
12487 (replace-match "0" t nil nil 1)))))
12489 (defvar org-state) ;; dynamically scoped into this function
12490 (defun org-todo (&optional arg)
12491 "Change the TODO state of an item.
12492 The state of an item is given by a keyword at the start of the heading,
12493 like
12494 *** TODO Write paper
12495 *** DONE Call mom
12497 The different keywords are specified in the variable `org-todo-keywords'.
12498 By default the available states are \"TODO\" and \"DONE\".
12499 So for this example: when the item starts with TODO, it is changed to DONE.
12500 When it starts with DONE, the DONE is removed. And when neither TODO nor
12501 DONE are present, add TODO at the beginning of the heading.
12503 With \\[universal-argument] prefix arg, use completion to determine the new \
12504 state.
12505 With numeric prefix arg, switch to that state.
12506 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12507 keywords (nextset).
12508 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12509 With a numeric prefix arg of 0, inhibit note taking for the change.
12510 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12512 When called through ELisp, arg is also interpreted in the following way:
12513 `none' -> empty state
12514 \"\"(empty string) -> switch to empty state
12515 `done' -> switch to DONE
12516 `nextset' -> switch to the next set of keywords
12517 `previousset' -> switch to the previous set of keywords
12518 \"WAITING\" -> switch to the specified keyword, but only if it
12519 really is a member of `org-todo-keywords'."
12520 (interactive "P")
12521 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12522 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12523 'region-start-level 'region))
12524 org-loop-over-headlines-in-active-region)
12525 (org-map-entries
12526 `(org-todo ,arg)
12527 org-loop-over-headlines-in-active-region
12528 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12529 (when (equal arg '(16)) (setq arg 'nextset))
12530 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12531 (let ((org-blocker-hook org-blocker-hook)
12532 commentp
12533 case-fold-search)
12534 (when (equal arg '(64))
12535 (setq arg nil org-blocker-hook nil))
12536 (when (and org-blocker-hook
12537 (or org-inhibit-blocking
12538 (org-entry-get nil "NOBLOCKING")))
12539 (setq org-blocker-hook nil))
12540 (save-excursion
12541 (catch 'exit
12542 (org-back-to-heading t)
12543 (when (org-in-commented-heading-p t)
12544 (org-toggle-comment)
12545 (setq commentp t))
12546 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12547 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12548 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12549 (let* ((match-data (match-data))
12550 (startpos (point-at-bol))
12551 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12552 (org-log-done org-log-done)
12553 (org-log-repeat org-log-repeat)
12554 (org-todo-log-states org-todo-log-states)
12555 (org-inhibit-logging
12556 (if (equal arg 0)
12557 (progn (setq arg nil) 'note) org-inhibit-logging))
12558 (this (match-string 1))
12559 (hl-pos (match-beginning 0))
12560 (head (org-get-todo-sequence-head this))
12561 (ass (assoc head org-todo-kwd-alist))
12562 (interpret (nth 1 ass))
12563 (done-word (nth 3 ass))
12564 (final-done-word (nth 4 ass))
12565 (org-last-state (or this ""))
12566 (completion-ignore-case t)
12567 (member (member this org-todo-keywords-1))
12568 (tail (cdr member))
12569 (org-state (cond
12570 ((and org-todo-key-trigger
12571 (or (and (equal arg '(4))
12572 (eq org-use-fast-todo-selection 'prefix))
12573 (and (not arg) org-use-fast-todo-selection
12574 (not (eq org-use-fast-todo-selection
12575 'prefix)))))
12576 ;; Use fast selection
12577 (org-fast-todo-selection))
12578 ((and (equal arg '(4))
12579 (or (not org-use-fast-todo-selection)
12580 (not org-todo-key-trigger)))
12581 ;; Read a state with completion
12582 (completing-read
12583 "State: " (mapcar #'list org-todo-keywords-1)
12584 nil t))
12585 ((eq arg 'right)
12586 (if this
12587 (if tail (car tail) nil)
12588 (car org-todo-keywords-1)))
12589 ((eq arg 'left)
12590 (unless (equal member org-todo-keywords-1)
12591 (if this
12592 (nth (- (length org-todo-keywords-1)
12593 (length tail) 2)
12594 org-todo-keywords-1)
12595 (org-last org-todo-keywords-1))))
12596 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12597 (setq arg nil))) ; hack to fall back to cycling
12598 (arg
12599 ;; user or caller requests a specific state
12600 (cond
12601 ((equal arg "") nil)
12602 ((eq arg 'none) nil)
12603 ((eq arg 'done) (or done-word (car org-done-keywords)))
12604 ((eq arg 'nextset)
12605 (or (car (cdr (member head org-todo-heads)))
12606 (car org-todo-heads)))
12607 ((eq arg 'previousset)
12608 (let ((org-todo-heads (reverse org-todo-heads)))
12609 (or (car (cdr (member head org-todo-heads)))
12610 (car org-todo-heads))))
12611 ((car (member arg org-todo-keywords-1)))
12612 ((stringp arg)
12613 (user-error "State `%s' not valid in this file" arg))
12614 ((nth (1- (prefix-numeric-value arg))
12615 org-todo-keywords-1))))
12616 ((null member) (or head (car org-todo-keywords-1)))
12617 ((equal this final-done-word) nil) ;; -> make empty
12618 ((null tail) nil) ;; -> first entry
12619 ((memq interpret '(type priority))
12620 (if (eq this-command last-command)
12621 (car tail)
12622 (if (> (length tail) 0)
12623 (or done-word (car org-done-keywords))
12624 nil)))
12626 (car tail))))
12627 (org-state (or
12628 (run-hook-with-args-until-success
12629 'org-todo-get-default-hook org-state org-last-state)
12630 org-state))
12631 (next (if org-state (concat " " org-state " ") " "))
12632 (change-plist (list :type 'todo-state-change :from this :to org-state
12633 :position startpos))
12634 dolog now-done-p)
12635 (when org-blocker-hook
12636 (setq org-last-todo-state-is-todo
12637 (not (member this org-done-keywords)))
12638 (unless (save-excursion
12639 (save-match-data
12640 (org-with-wide-buffer
12641 (run-hook-with-args-until-failure
12642 'org-blocker-hook change-plist))))
12643 (if (org-called-interactively-p 'interactive)
12644 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12645 this org-state org-block-entry-blocking)
12646 ;; fail silently
12647 (message "TODO state change from %s to %s blocked (by \"%s\")"
12648 this org-state org-block-entry-blocking)
12649 (throw 'exit nil))))
12650 (store-match-data match-data)
12651 (replace-match next t t)
12652 (cond ((equal this org-state)
12653 (message "TODO state was already %s" (org-trim next)))
12654 ((pos-visible-in-window-p hl-pos)
12655 (message "TODO state changed to %s" (org-trim next))))
12656 (unless head
12657 (setq head (org-get-todo-sequence-head org-state)
12658 ass (assoc head org-todo-kwd-alist)
12659 interpret (nth 1 ass)
12660 done-word (nth 3 ass)
12661 final-done-word (nth 4 ass)))
12662 (when (memq arg '(nextset previousset))
12663 (message "Keyword-Set %d/%d: %s"
12664 (- (length org-todo-sets) -1
12665 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12666 (length org-todo-sets)
12667 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12668 (setq org-last-todo-state-is-todo
12669 (not (member org-state org-done-keywords)))
12670 (setq now-done-p (and (member org-state org-done-keywords)
12671 (not (member this org-done-keywords))))
12672 (and logging (org-local-logging logging))
12673 (when (and (or org-todo-log-states org-log-done)
12674 (not (eq org-inhibit-logging t))
12675 (not (memq arg '(nextset previousset))))
12676 ;; we need to look at recording a time and note
12677 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12678 (nth 2 (assoc this org-todo-log-states))))
12679 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12680 (setq dolog 'time))
12681 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12682 (and org-state
12683 (member org-state org-not-done-keywords)
12684 (not (member this org-not-done-keywords))))
12685 ;; This is now a todo state and was not one before
12686 ;; If there was a CLOSED time stamp, get rid of it.
12687 (org-add-planning-info nil nil 'closed))
12688 (when (and now-done-p org-log-done)
12689 ;; It is now done, and it was not done before
12690 (org-add-planning-info 'closed (org-current-effective-time))
12691 (when (and (not dolog) (eq 'note org-log-done))
12692 (org-add-log-setup 'done org-state this 'note)))
12693 (when (and org-state dolog)
12694 ;; This is a non-nil state, and we need to log it
12695 (org-add-log-setup 'state org-state this dolog)))
12696 ;; Fixup tag positioning
12697 (org-todo-trigger-tag-changes org-state)
12698 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12699 (when org-provide-todo-statistics
12700 (org-update-parent-todo-statistics))
12701 (run-hooks 'org-after-todo-state-change-hook)
12702 (when (and arg (not (member org-state org-done-keywords)))
12703 (setq head (org-get-todo-sequence-head org-state)))
12704 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12705 ;; Do we need to trigger a repeat?
12706 (when now-done-p
12707 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12708 ;; This is for the agenda, take a snapshot of the headline.
12709 (save-match-data
12710 (setq org-agenda-headline-snapshot-before-repeat
12711 (org-get-heading))))
12712 (org-auto-repeat-maybe org-state))
12713 ;; Fixup cursor location if close to the keyword
12714 (when (and (outline-on-heading-p)
12715 (not (bolp))
12716 (save-excursion (beginning-of-line 1)
12717 (looking-at org-todo-line-regexp))
12718 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12719 (goto-char (or (match-end 2) (match-end 1)))
12720 (and (looking-at " ") (just-one-space)))
12721 (when org-trigger-hook
12722 (save-excursion
12723 (run-hook-with-args 'org-trigger-hook change-plist)))
12724 (when commentp (org-toggle-comment))))))))
12726 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12727 "Block turning an entry into a TODO, using the hierarchy.
12728 This checks whether the current task should be blocked from state
12729 changes. Such blocking occurs when:
12731 1. The task has children which are not all in a completed state.
12733 2. A task has a parent with the property :ORDERED:, and there
12734 are siblings prior to the current task with incomplete
12735 status.
12737 3. The parent of the task is blocked because it has siblings that should
12738 be done first, or is child of a block grandparent TODO entry."
12740 (if (not org-enforce-todo-dependencies)
12741 t ; if locally turned off don't block
12742 (catch 'dont-block
12743 ;; If this is not a todo state change, or if this entry is already DONE,
12744 ;; do not block
12745 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12746 (member (plist-get change-plist :from)
12747 (cons 'done org-done-keywords))
12748 (member (plist-get change-plist :to)
12749 (cons 'todo org-not-done-keywords))
12750 (not (plist-get change-plist :to)))
12751 (throw 'dont-block t))
12752 ;; If this task has children, and any are undone, it's blocked
12753 (save-excursion
12754 (org-back-to-heading t)
12755 (let ((this-level (funcall outline-level)))
12756 (outline-next-heading)
12757 (let ((child-level (funcall outline-level)))
12758 (while (and (not (eobp))
12759 (> child-level this-level))
12760 ;; this todo has children, check whether they are all
12761 ;; completed
12762 (when (and (not (org-entry-is-done-p))
12763 (org-entry-is-todo-p))
12764 (setq org-block-entry-blocking (org-get-heading))
12765 (throw 'dont-block nil))
12766 (outline-next-heading)
12767 (setq child-level (funcall outline-level))))))
12768 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12769 ;; any previous siblings are undone, it's blocked
12770 (save-excursion
12771 (org-back-to-heading t)
12772 (let* ((pos (point))
12773 (parent-pos (and (org-up-heading-safe) (point))))
12774 (unless parent-pos (throw 'dont-block t)) ; no parent
12775 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12776 (forward-line 1)
12777 (re-search-forward org-not-done-heading-regexp pos t))
12778 (setq org-block-entry-blocking (match-string 0))
12779 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12780 ;; Search further up the hierarchy, to see if an ancestor is blocked
12781 (while t
12782 (goto-char parent-pos)
12783 (unless (looking-at org-not-done-heading-regexp)
12784 (throw 'dont-block t)) ; do not block, parent is not a TODO
12785 (setq pos (point))
12786 (setq parent-pos (and (org-up-heading-safe) (point)))
12787 (unless parent-pos (throw 'dont-block t)) ; no parent
12788 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12789 (forward-line 1)
12790 (re-search-forward org-not-done-heading-regexp pos t)
12791 (setq org-block-entry-blocking (org-get-heading)))
12792 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12794 (defcustom org-track-ordered-property-with-tag nil
12795 "Should the ORDERED property also be shown as a tag?
12796 The ORDERED property decides if an entry should require subtasks to be
12797 completed in sequence. Since a property is not very visible, setting
12798 this option means that toggling the ORDERED property with the command
12799 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12800 not relevant for the behavior, but it makes things more visible.
12802 Note that toggling the tag with tags commands will not change the property
12803 and therefore not influence behavior!
12805 This can be t, meaning the tag ORDERED should be used, It can also be a
12806 string to select a different tag for this task."
12807 :group 'org-todo
12808 :type '(choice
12809 (const :tag "No tracking" nil)
12810 (const :tag "Track with ORDERED tag" t)
12811 (string :tag "Use other tag")))
12813 (defun org-toggle-ordered-property ()
12814 "Toggle the ORDERED property of the current entry.
12815 For better visibility, you can track the value of this property with a tag.
12816 See variable `org-track-ordered-property-with-tag'."
12817 (interactive)
12818 (let* ((t1 org-track-ordered-property-with-tag)
12819 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12820 (save-excursion
12821 (org-back-to-heading)
12822 (if (org-entry-get nil "ORDERED")
12823 (progn
12824 (org-delete-property "ORDERED")
12825 (and tag (org-toggle-tag tag 'off))
12826 (message "Subtasks can be completed in arbitrary order"))
12827 (org-entry-put nil "ORDERED" "t")
12828 (and tag (org-toggle-tag tag 'on))
12829 (message "Subtasks must be completed in sequence")))))
12831 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12832 (defun org-block-todo-from-checkboxes (change-plist)
12833 "Block turning an entry into a TODO, using checkboxes.
12834 This checks whether the current task should be blocked from state
12835 changes because there are unchecked boxes in this entry."
12836 (if (not org-enforce-todo-checkbox-dependencies)
12837 t ; if locally turned off don't block
12838 (catch 'dont-block
12839 ;; If this is not a todo state change, or if this entry is already DONE,
12840 ;; do not block
12841 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12842 (member (plist-get change-plist :from)
12843 (cons 'done org-done-keywords))
12844 (member (plist-get change-plist :to)
12845 (cons 'todo org-not-done-keywords))
12846 (not (plist-get change-plist :to)))
12847 (throw 'dont-block t))
12848 ;; If this task has checkboxes that are not checked, it's blocked
12849 (save-excursion
12850 (org-back-to-heading t)
12851 (let ((beg (point)) end)
12852 (outline-next-heading)
12853 (setq end (point))
12854 (goto-char beg)
12855 (when (org-list-search-forward
12856 (concat (org-item-beginning-re)
12857 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12858 "\\[[- ]\\]")
12859 end t)
12860 (when (boundp 'org-blocked-by-checkboxes)
12861 (setq org-blocked-by-checkboxes t))
12862 (throw 'dont-block nil))))
12863 t))) ; do not block
12865 (defun org-entry-blocked-p ()
12866 "Non-nil if entry at point is blocked."
12867 (and (not (org-entry-get nil "NOBLOCKING"))
12868 (member (org-entry-get nil "TODO") org-not-done-keywords)
12869 (not (run-hook-with-args-until-failure
12870 'org-blocker-hook
12871 (list :type 'todo-state-change
12872 :position (point)
12873 :from 'todo
12874 :to 'done)))))
12876 (defun org-update-statistics-cookies (all)
12877 "Update the statistics cookie, either from TODO or from checkboxes.
12878 This should be called with the cursor in a line with a statistics cookie."
12879 (interactive "P")
12880 (if all
12881 (progn
12882 (org-update-checkbox-count 'all)
12883 (org-map-entries 'org-update-parent-todo-statistics))
12884 (if (not (org-at-heading-p))
12885 (org-update-checkbox-count)
12886 (let ((pos (point-marker))
12887 end l1 l2)
12888 (ignore-errors (org-back-to-heading t))
12889 (if (not (org-at-heading-p))
12890 (org-update-checkbox-count)
12891 (setq l1 (org-outline-level))
12892 (setq end (save-excursion
12893 (outline-next-heading)
12894 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12895 (point)))
12896 (if (and (save-excursion
12897 (re-search-forward
12898 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12899 (not (save-excursion (re-search-forward
12900 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12901 (org-update-checkbox-count)
12902 (if (and l2 (> l2 l1))
12903 (progn
12904 (goto-char end)
12905 (org-update-parent-todo-statistics))
12906 (goto-char pos)
12907 (beginning-of-line 1)
12908 (while (re-search-forward
12909 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12910 (point-at-eol) t)
12911 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12912 (goto-char pos)
12913 (move-marker pos nil)))))
12915 (defvar org-entry-property-inherited-from) ;; defined below
12916 (defun org-update-parent-todo-statistics ()
12917 "Update any statistics cookie in the parent of the current headline.
12918 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12919 the entire subtree and this will travel up the hierarchy and update
12920 statistics everywhere."
12921 (let* ((prop (save-excursion (org-up-heading-safe)
12922 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12923 (recursive (or (not org-hierarchical-todo-statistics)
12924 (and prop (string-match "\\<recursive\\>" prop))))
12925 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12927 (first t)
12928 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12929 level ltoggle l1 new ndel
12930 (cnt-all 0) (cnt-done 0) is-percent kwd
12931 checkbox-beg ov ovs ove cookie-present)
12932 (catch 'exit
12933 (save-excursion
12934 (beginning-of-line 1)
12935 (setq ltoggle (funcall outline-level))
12936 ;; Three situations are to consider:
12938 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12939 ;; to the top-level ancestor on the headline;
12941 ;; 2. If parent has "recursive" property, repeat up to the
12942 ;; headline setting that property, taking inheritance into
12943 ;; account;
12945 ;; 3. Else, move up to direct parent and proceed only once.
12946 (while (and (setq level (org-up-heading-safe))
12947 (or recursive first)
12948 (>= (point) lim))
12949 (setq first nil cookie-present nil)
12950 (unless (and level
12951 (not (string-match
12952 "\\<checkbox\\>"
12953 (downcase (or (org-entry-get nil "COOKIE_DATA")
12954 "")))))
12955 (throw 'exit nil))
12956 (while (re-search-forward box-re (point-at-eol) t)
12957 (setq cnt-all 0 cnt-done 0 cookie-present t)
12958 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12959 (save-match-data
12960 (unless (outline-next-heading) (throw 'exit nil))
12961 (while (and (looking-at org-complex-heading-regexp)
12962 (> (setq l1 (length (match-string 1))) level))
12963 (setq kwd (and (or recursive (= l1 ltoggle))
12964 (match-string 2)))
12965 (if (or (eq org-provide-todo-statistics 'all-headlines)
12966 (and (eq org-provide-todo-statistics t)
12967 (or (member kwd org-done-keywords)))
12968 (and (listp org-provide-todo-statistics)
12969 (stringp (car org-provide-todo-statistics))
12970 (or (member kwd org-provide-todo-statistics)
12971 (member kwd org-done-keywords)))
12972 (and (listp org-provide-todo-statistics)
12973 (listp (car org-provide-todo-statistics))
12974 (or (member kwd (car org-provide-todo-statistics))
12975 (and (member kwd org-done-keywords)
12976 (member kwd (cadr org-provide-todo-statistics))))))
12977 (setq cnt-all (1+ cnt-all))
12978 (and (eq org-provide-todo-statistics t)
12980 (setq cnt-all (1+ cnt-all))))
12981 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12982 (member kwd org-done-keywords))
12983 (and (listp org-provide-todo-statistics)
12984 (listp (car org-provide-todo-statistics))
12985 (member kwd org-done-keywords)
12986 (member kwd (cadr org-provide-todo-statistics)))
12987 (and (listp org-provide-todo-statistics)
12988 (stringp (car org-provide-todo-statistics))
12989 (member kwd org-done-keywords)))
12990 (setq cnt-done (1+ cnt-done)))
12991 (outline-next-heading)))
12992 (setq new
12993 (if is-percent
12994 (format "[%d%%]" (floor (* 100.0 cnt-done)
12995 (max 1 cnt-all)))
12996 (format "[%d/%d]" cnt-done cnt-all))
12997 ndel (- (match-end 0) checkbox-beg))
12998 ;; handle overlays when updating cookie from column view
12999 (when (setq ov (car (overlays-at checkbox-beg)))
13000 (setq ovs (overlay-start ov) ove (overlay-end ov))
13001 (delete-overlay ov))
13002 (goto-char checkbox-beg)
13003 (insert new)
13004 (delete-region (point) (+ (point) ndel))
13005 (when org-auto-align-tags (org-fix-tags-on-the-fly))
13006 (when ov (move-overlay ov ovs ove)))
13007 (when cookie-present
13008 (run-hook-with-args 'org-after-todo-statistics-hook
13009 cnt-done (- cnt-all cnt-done))))))
13010 (run-hooks 'org-todo-statistics-hook)))
13012 (defvar org-after-todo-statistics-hook nil
13013 "Hook that is called after a TODO statistics cookie has been updated.
13014 Each function is called with two arguments: the number of not-done entries
13015 and the number of done entries.
13017 For example, the following function, when added to this hook, will switch
13018 an entry to DONE when all children are done, and back to TODO when new
13019 entries are set to a TODO status. Note that this hook is only called
13020 when there is a statistics cookie in the headline!
13022 \(defun org-summary-todo (n-done n-not-done)
13023 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13024 \(let (org-log-done org-log-states) ; turn off logging
13025 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13028 (defvar org-todo-statistics-hook nil
13029 "Hook that is run whenever Org thinks TODO statistics should be updated.
13030 This hook runs even if there is no statistics cookie present, in which case
13031 `org-after-todo-statistics-hook' would not run.")
13033 (defun org-todo-trigger-tag-changes (state)
13034 "Apply the changes defined in `org-todo-state-tags-triggers'."
13035 (let ((l org-todo-state-tags-triggers)
13036 changes)
13037 (when (or (not state) (equal state ""))
13038 (setq changes (append changes (cdr (assoc "" l)))))
13039 (when (and (stringp state) (> (length state) 0))
13040 (setq changes (append changes (cdr (assoc state l)))))
13041 (when (member state org-not-done-keywords)
13042 (setq changes (append changes (cdr (assoc 'todo l)))))
13043 (when (member state org-done-keywords)
13044 (setq changes (append changes (cdr (assoc 'done l)))))
13045 (dolist (c changes)
13046 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13048 (defun org-local-logging (value)
13049 "Get logging settings from a property VALUE."
13050 ;; Directly set the variables, they are already local.
13051 (setq org-log-done nil
13052 org-log-repeat nil
13053 org-todo-log-states nil)
13054 (dolist (w (org-split-string value))
13055 (let (a)
13056 (cond
13057 ((setq a (assoc w org-startup-options))
13058 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13059 (set (nth 1 a) (nth 2 a))))
13060 ((setq a (org-extract-log-state-settings w))
13061 (and (member (car a) org-todo-keywords-1)
13062 (push a org-todo-log-states)))))))
13064 (defun org-get-todo-sequence-head (kwd)
13065 "Return the head of the TODO sequence to which KWD belongs.
13066 If KWD is not set, check if there is a text property remembering the
13067 right sequence."
13068 (let (p)
13069 (cond
13070 ((not kwd)
13071 (or (get-text-property (point-at-bol) 'org-todo-head)
13072 (progn
13073 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13074 nil (point-at-eol)))
13075 (get-text-property p 'org-todo-head))))
13076 ((not (member kwd org-todo-keywords-1))
13077 (car org-todo-keywords-1))
13078 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13080 (defun org-fast-todo-selection ()
13081 "Fast TODO keyword selection with single keys.
13082 Returns the new TODO keyword, or nil if no state change should occur."
13083 (let* ((fulltable org-todo-key-alist)
13084 (done-keywords org-done-keywords) ;; needed for the faces.
13085 (maxlen (apply 'max (mapcar
13086 (lambda (x)
13087 (if (stringp (car x)) (string-width (car x)) 0))
13088 fulltable)))
13089 (expert nil)
13090 (fwidth (+ maxlen 3 1 3))
13091 (ncol (/ (- (window-width) 4) fwidth))
13092 tg cnt e c tbl
13093 groups ingroup)
13094 (save-excursion
13095 (save-window-excursion
13096 (if expert
13097 (set-buffer (get-buffer-create " *Org todo*"))
13098 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13099 (erase-buffer)
13100 (setq-local org-done-keywords done-keywords)
13101 (setq tbl fulltable cnt 0)
13102 (while (setq e (pop tbl))
13103 (cond
13104 ((equal e '(:startgroup))
13105 (push '() groups) (setq ingroup t)
13106 (unless (= cnt 0)
13107 (setq cnt 0)
13108 (insert "\n"))
13109 (insert "{ "))
13110 ((equal e '(:endgroup))
13111 (setq ingroup nil cnt 0)
13112 (insert "}\n"))
13113 ((equal e '(:newline))
13114 (unless (= cnt 0)
13115 (setq cnt 0)
13116 (insert "\n")
13117 (setq e (car tbl))
13118 (while (equal (car tbl) '(:newline))
13119 (insert "\n")
13120 (setq tbl (cdr tbl)))))
13122 (setq tg (car e) c (cdr e))
13123 (when ingroup (push tg (car groups)))
13124 (setq tg (org-add-props tg nil 'face
13125 (org-get-todo-face tg)))
13126 (when (and (= cnt 0) (not ingroup)) (insert " "))
13127 (insert "[" c "] " tg (make-string
13128 (- fwidth 4 (length tg)) ?\ ))
13129 (when (= (setq cnt (1+ cnt)) ncol)
13130 (insert "\n")
13131 (when ingroup (insert " "))
13132 (setq cnt 0)))))
13133 (insert "\n")
13134 (goto-char (point-min))
13135 (unless expert (org-fit-window-to-buffer))
13136 (message "[a-z..]:Set [SPC]:clear")
13137 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13138 (cond
13139 ((or (= c ?\C-g)
13140 (and (= c ?q) (not (rassoc c fulltable))))
13141 (setq quit-flag t))
13142 ((= c ?\ ) nil)
13143 ((setq e (rassoc c fulltable) tg (car e))
13145 (t (setq quit-flag t)))))))
13147 (defun org-entry-is-todo-p ()
13148 (member (org-get-todo-state) org-not-done-keywords))
13150 (defun org-entry-is-done-p ()
13151 (member (org-get-todo-state) org-done-keywords))
13153 (defun org-get-todo-state ()
13154 "Return the TODO keyword of the current subtree."
13155 (save-excursion
13156 (org-back-to-heading t)
13157 (and (looking-at org-todo-line-regexp)
13158 (match-end 2)
13159 (match-string 2))))
13161 (defun org-at-date-range-p (&optional inactive-ok)
13162 "Non-nil if point is inside a date range.
13164 When optional argument INACTIVE-OK is non-nil, also consider
13165 inactive time ranges.
13167 When this function returns a non-nil value, match data is set
13168 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13169 on INACTIVE-OK."
13170 (interactive)
13171 (save-excursion
13172 (catch 'exit
13173 (let ((pos (point)))
13174 (skip-chars-backward "^[<\r\n")
13175 (skip-chars-backward "<[")
13176 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13177 (>= (match-end 0) pos)
13178 (throw 'exit t))
13179 (skip-chars-backward "^<[\r\n")
13180 (skip-chars-backward "<[")
13181 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13182 (>= (match-end 0) pos)
13183 (throw 'exit t)))
13184 nil)))
13186 (defun org-get-repeat (&optional tagline)
13187 "Check if there is a deadline/schedule with repeater in this entry."
13188 (save-match-data
13189 (save-excursion
13190 (org-back-to-heading t)
13191 (and (re-search-forward (if tagline
13192 (concat tagline "\\s-*" org-repeat-re)
13193 org-repeat-re)
13194 (org-entry-end-position) t)
13195 (match-string-no-properties 1)))))
13197 (defvar org-last-changed-timestamp)
13198 (defvar org-last-inserted-timestamp)
13199 (defvar org-log-post-message)
13200 (defvar org-log-note-purpose)
13201 (defvar org-log-note-how nil)
13202 (defvar org-log-note-extra)
13203 (defun org-auto-repeat-maybe (done-word)
13204 "Check if the current headline contains a repeated time-stamp.
13206 If yes, set TODO state back to what it was and change the base date
13207 of repeating deadline/scheduled time stamps to new date.
13209 This function is run automatically after each state change to a DONE state."
13210 (let* ((repeat (org-get-repeat))
13211 (aa (assoc org-last-state org-todo-kwd-alist))
13212 (interpret (nth 1 aa))
13213 (head (nth 2 aa))
13214 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13215 (msg "Entry repeats: ")
13216 (org-log-done nil)
13217 (org-todo-log-states nil))
13218 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13219 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13220 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13221 org-todo-repeat-to-state)))
13222 (unless (and to-state (member to-state org-todo-keywords-1))
13223 (setq to-state (if (eq interpret 'type) org-last-state head)))
13224 (org-todo to-state))
13225 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13226 (org-entry-put nil "LAST_REPEAT" (format-time-string
13227 (org-time-stamp-format t t))))
13228 (when org-log-repeat
13229 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13230 (memq 'org-add-log-note post-command-hook))
13231 ;; We are already setup for some record.
13232 (when (eq org-log-repeat 'note)
13233 ;; Make sure we take a note, not only a time stamp.
13234 (setq org-log-note-how 'note))
13235 ;; Set up for taking a record.
13236 (org-add-log-setup 'state
13237 (or done-word (car org-done-keywords))
13238 org-last-state
13239 org-log-repeat)))
13240 (org-back-to-heading t)
13241 (org-add-planning-info nil nil 'closed)
13242 (let ((end (save-excursion (outline-next-heading) (point))))
13243 (while (re-search-forward org-ts-regexp end t)
13244 (when (save-match-data
13245 (or (org-at-planning-p)
13246 (org-at-property-p)
13247 (eq (org-element-type (save-excursion
13248 (backward-char)
13249 (org-element-context)))
13250 'timestamp)))
13251 (let ((type (cond ((match-end 1) org-scheduled-string)
13252 ((match-end 3) org-deadline-string)
13253 (t "Plain:")))
13254 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13255 (cond
13256 ((not
13257 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13258 ;; Time-stamps without a repeater are usually skipped.
13259 ;; However, a SCHEDULED time-stamp without one is
13260 ;; removed, as it is considered as no longer relevant.
13261 (when (equal type org-scheduled-string)
13262 (org-remove-timestamp-with-keyword type)))
13264 (let ((n (string-to-number (match-string 2 ts)))
13265 (what (match-string 3 ts)))
13266 (when (equal what "w") (setq n (* n 7) what "d"))
13267 (when (and (equal what "h")
13268 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13269 ts)))
13270 (user-error
13271 "Cannot repeat in Repeat in %d hour(s) because no hour \
13272 has been set"
13274 ;; Preparation, see if we need to modify the start
13275 ;; date for the change.
13276 (when (match-end 1)
13277 (let ((time (save-match-data (org-time-string-to-time ts))))
13278 (cond
13279 ((equal (match-string 1 ts) ".")
13280 ;; Shift starting date to today
13281 (org-timestamp-change
13282 (- (org-today) (time-to-days time))
13283 'day))
13284 ((equal (match-string 1 ts) "+")
13285 (let ((nshiftmax 10)
13286 (nshift 0))
13287 (while (or (= nshift 0)
13288 (<= (time-to-days time)
13289 (time-to-days (current-time))))
13290 (when (= (cl-incf nshift) nshiftmax)
13291 (or (y-or-n-p
13292 (format "%d repeater intervals were not \
13293 enough to shift date past today. Continue? "
13294 nshift))
13295 (user-error "Abort")))
13296 (org-timestamp-change n (cdr (assoc what whata)))
13297 (org-at-timestamp-p t)
13298 (setq ts (match-string 1))
13299 (setq time
13300 (save-match-data
13301 (org-time-string-to-time ts)))))
13302 (org-timestamp-change (- n) (cdr (assoc what whata)))
13303 ;; Rematch, so that we have everything in
13304 ;; place for the real shift.
13305 (org-at-timestamp-p t)
13306 (setq ts (match-string 1))
13307 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13308 ts)))))
13309 (save-excursion
13310 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13311 (setq msg
13312 (concat
13313 msg type " " org-last-changed-timestamp " ")))))))))
13314 (setq org-log-post-message msg)
13315 (message "%s" msg))))
13317 (defun org-show-todo-tree (arg)
13318 "Make a compact tree which shows all headlines marked with TODO.
13319 The tree will show the lines where the regexp matches, and all higher
13320 headlines above the match.
13321 With a \\[universal-argument] prefix, prompt for a regexp to match.
13322 With a numeric prefix N, construct a sparse tree for the Nth element
13323 of `org-todo-keywords-1'."
13324 (interactive "P")
13325 (let ((case-fold-search nil)
13326 (kwd-re
13327 (cond ((null arg) org-not-done-regexp)
13328 ((equal arg '(4))
13329 (let ((kwd
13330 (completing-read "Keyword (or KWD1|KWD2|...): "
13331 (mapcar #'list org-todo-keywords-1))))
13332 (concat "\\("
13333 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13334 "\\)\\>")))
13335 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13336 (regexp-quote (nth (1- (prefix-numeric-value arg))
13337 org-todo-keywords-1)))
13338 (t (user-error "Invalid prefix argument: %s" arg)))))
13339 (message "%d TODO entries found"
13340 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13342 (defun org-deadline (arg &optional time)
13343 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13344 With one universal prefix argument, remove any deadline from the item.
13345 With two universal prefix arguments, prompt for a warning delay.
13346 With argument TIME, set the deadline at the corresponding date. TIME
13347 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13348 (interactive "P")
13349 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13350 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13351 'region-start-level 'region))
13352 org-loop-over-headlines-in-active-region)
13353 (org-map-entries
13354 `(org-deadline ',arg ,time)
13355 org-loop-over-headlines-in-active-region
13356 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13357 (let* ((old-date (org-entry-get nil "DEADLINE"))
13358 (old-date-time (when old-date (org-time-string-to-time old-date)))
13359 (repeater (and old-date
13360 (string-match
13361 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13362 old-date)
13363 (match-string 1 old-date))))
13364 (cond
13365 ((equal arg '(4))
13366 (when (and old-date org-log-redeadline)
13367 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13368 (org-remove-timestamp-with-keyword org-deadline-string)
13369 (message "Item no longer has a deadline."))
13370 ((equal arg '(16))
13371 (save-excursion
13372 (org-back-to-heading t)
13373 (if (re-search-forward
13374 org-deadline-time-regexp
13375 (save-excursion (outline-next-heading) (point)) t)
13376 (let* ((rpl0 (match-string 1))
13377 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13378 (replace-match
13379 (concat org-deadline-string
13380 " <" rpl
13381 (format " -%dd"
13382 (abs
13383 (- (time-to-days
13384 (save-match-data
13385 (org-read-date nil t nil "Warn starting from" old-date-time)))
13386 (time-to-days old-date-time))))
13387 ">") t t))
13388 (user-error "No deadline information to update"))))
13390 (org-add-planning-info 'deadline time 'closed)
13391 (when (and old-date
13392 org-log-redeadline
13393 (not (equal old-date org-last-inserted-timestamp)))
13394 (org-add-log-setup
13395 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13396 (when repeater
13397 (save-excursion
13398 (org-back-to-heading t)
13399 (when (re-search-forward (concat org-deadline-string " "
13400 org-last-inserted-timestamp)
13401 (save-excursion
13402 (outline-next-heading) (point)) t)
13403 (goto-char (1- (match-end 0)))
13404 (insert " " repeater)
13405 (setq org-last-inserted-timestamp
13406 (concat (substring org-last-inserted-timestamp 0 -1)
13407 " " repeater
13408 (substring org-last-inserted-timestamp -1))))))
13409 (message "Deadline on %s" org-last-inserted-timestamp))))))
13411 (defun org-schedule (arg &optional time)
13412 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13413 With one universal prefix argument, remove any scheduling date from the item.
13414 With two universal prefix arguments, prompt for a delay cookie.
13415 With argument TIME, scheduled at the corresponding date. TIME can
13416 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13417 (interactive "P")
13418 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13419 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13420 'region-start-level 'region))
13421 org-loop-over-headlines-in-active-region)
13422 (org-map-entries
13423 `(org-schedule ',arg ,time)
13424 org-loop-over-headlines-in-active-region
13425 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13426 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13427 (old-date-time (when old-date (org-time-string-to-time old-date)))
13428 (repeater (and old-date
13429 (string-match
13430 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13431 old-date)
13432 (match-string 1 old-date))))
13433 (cond
13434 ((equal arg '(4))
13435 (progn
13436 (when (and old-date org-log-reschedule)
13437 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13438 (org-remove-timestamp-with-keyword org-scheduled-string)
13439 (message "Item is no longer scheduled.")))
13440 ((equal arg '(16))
13441 (save-excursion
13442 (org-back-to-heading t)
13443 (if (re-search-forward
13444 org-scheduled-time-regexp
13445 (save-excursion (outline-next-heading) (point)) t)
13446 (let* ((rpl0 (match-string 1))
13447 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13448 (replace-match
13449 (concat org-scheduled-string
13450 " <" rpl
13451 (format " -%dd"
13452 (abs
13453 (- (time-to-days
13454 (save-match-data
13455 (org-read-date nil t nil "Delay until" old-date-time)))
13456 (time-to-days old-date-time))))
13457 ">") t t))
13458 (user-error "No scheduled information to update"))))
13460 (org-add-planning-info 'scheduled time 'closed)
13461 (when (and old-date
13462 org-log-reschedule
13463 (not (equal old-date org-last-inserted-timestamp)))
13464 (org-add-log-setup
13465 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13466 (when repeater
13467 (save-excursion
13468 (org-back-to-heading t)
13469 (when (re-search-forward (concat org-scheduled-string " "
13470 org-last-inserted-timestamp)
13471 (save-excursion
13472 (outline-next-heading) (point)) t)
13473 (goto-char (1- (match-end 0)))
13474 (insert " " repeater)
13475 (setq org-last-inserted-timestamp
13476 (concat (substring org-last-inserted-timestamp 0 -1)
13477 " " repeater
13478 (substring org-last-inserted-timestamp -1))))))
13479 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13481 (defun org-get-scheduled-time (pom &optional inherit)
13482 "Get the scheduled time as a time tuple, of a format suitable
13483 for calling org-schedule with, or if there is no scheduling,
13484 returns nil."
13485 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13486 (when time
13487 (apply 'encode-time (org-parse-time-string time)))))
13489 (defun org-get-deadline-time (pom &optional inherit)
13490 "Get the deadline as a time tuple, of a format suitable for
13491 calling org-deadline with, or if there is no scheduling, returns
13492 nil."
13493 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13494 (when time
13495 (apply 'encode-time (org-parse-time-string time)))))
13497 (defun org-remove-timestamp-with-keyword (keyword)
13498 "Remove all time stamps with KEYWORD in the current entry."
13499 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13500 beg)
13501 (save-excursion
13502 (org-back-to-heading t)
13503 (setq beg (point))
13504 (outline-next-heading)
13505 (while (re-search-backward re beg t)
13506 (replace-match "")
13507 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13508 (equal (char-before) ?\ ))
13509 (backward-delete-char 1)
13510 (when (string-match "^[ \t]*$" (buffer-substring
13511 (point-at-bol) (point-at-eol)))
13512 (delete-region (point-at-bol)
13513 (min (point-max) (1+ (point-at-eol))))))))))
13515 (defvar org-time-was-given) ; dynamically scoped parameter
13516 (defvar org-end-time-was-given) ; dynamically scoped parameter
13518 (defun org-at-planning-p ()
13519 "Non-nil when point is on a planning info line."
13520 ;; This is as accurate and faster than `org-element-at-point' since
13521 ;; planning info location is fixed in the section.
13522 (org-with-wide-buffer
13523 (beginning-of-line)
13524 (and (looking-at-p org-planning-line-re)
13525 (eq (point)
13526 (ignore-errors
13527 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13528 (org-back-to-heading t)
13529 (org-with-limited-levels (org-back-to-heading t)))
13530 (line-beginning-position 2))))))
13532 (defun org-add-planning-info (what &optional time &rest remove)
13533 "Insert new timestamp with keyword in the planning line.
13534 WHAT indicates what kind of time stamp to add. It is a symbol
13535 among `closed', `deadline', `scheduled' and nil. TIME indicates
13536 the time to use. If none is given, the user is prompted for
13537 a date. REMOVE indicates what kind of entries to remove. An old
13538 WHAT entry will also be removed."
13539 (let (org-time-was-given org-end-time-was-given default-time default-input)
13540 (catch 'exit
13541 (when (and (memq what '(scheduled deadline))
13542 (or (not time)
13543 (and (stringp time)
13544 (string-match "^[-+]+[0-9]" time))))
13545 ;; Try to get a default date/time from existing timestamp
13546 (save-excursion
13547 (org-back-to-heading t)
13548 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13549 (when (re-search-forward (if (eq what 'scheduled)
13550 org-scheduled-time-regexp
13551 org-deadline-time-regexp)
13552 end t)
13553 (setq ts (match-string 1)
13554 default-time (apply 'encode-time (org-parse-time-string ts))
13555 default-input (and ts (org-get-compact-tod ts)))))))
13556 (when what
13557 (setq time
13558 (if (stringp time)
13559 ;; This is a string (relative or absolute), set
13560 ;; proper date.
13561 (apply #'encode-time
13562 (org-read-date-analyze
13563 time default-time (decode-time default-time)))
13564 ;; If necessary, get the time from the user
13565 (or time (org-read-date nil 'to-time nil nil
13566 default-time default-input)))))
13568 (org-with-wide-buffer
13569 (org-back-to-heading t)
13570 (forward-line)
13571 (unless (bolp) (insert "\n"))
13572 (cond ((looking-at-p org-planning-line-re)
13573 ;; Move to current indentation.
13574 (skip-chars-forward " \t")
13575 ;; Check if we have to remove something.
13576 (dolist (type (if what (cons what remove) remove))
13577 (save-excursion
13578 (when (re-search-forward
13579 (cl-case type
13580 (closed org-closed-time-regexp)
13581 (deadline org-deadline-time-regexp)
13582 (scheduled org-scheduled-time-regexp)
13583 (otherwise
13584 (error "Invalid planning type: %s" type)))
13585 (line-end-position) t)
13586 ;; Delete until next keyword or end of line.
13587 (delete-region
13588 (match-beginning 0)
13589 (if (re-search-forward org-keyword-time-not-clock-regexp
13590 (line-end-position)
13592 (match-beginning 0)
13593 (line-end-position))))))
13594 ;; If there is nothing more to add and no more keyword
13595 ;; is left, remove the line completely.
13596 (if (and (looking-at-p "[ \t]*$") (not what))
13597 (delete-region (line-beginning-position)
13598 (line-beginning-position 2))
13599 ;; If we removed last keyword, do not leave trailing
13600 ;; white space at the end of line.
13601 (let ((p (point)))
13602 (save-excursion
13603 (end-of-line)
13604 (unless (= (skip-chars-backward " \t" p) 0)
13605 (delete-region (point) (line-end-position)))))))
13606 ((not what) (throw 'exit nil)) ; Nothing to do.
13607 (t (insert-before-markers "\n")
13608 (backward-char 1)
13609 (when org-adapt-indentation
13610 (indent-to-column (1+ (org-outline-level))))))
13611 (when what
13612 ;; Insert planning keyword.
13613 (insert (cl-case what
13614 (closed org-closed-string)
13615 (deadline org-deadline-string)
13616 (scheduled org-scheduled-string)
13617 (otherwise (error "Invalid planning type: %s" what)))
13618 " ")
13619 ;; Insert associated timestamp.
13620 (let ((ts (org-insert-time-stamp
13621 time
13622 (or org-time-was-given
13623 (and (eq what 'closed) org-log-done-with-time))
13624 (eq what 'closed)
13625 nil nil (list org-end-time-was-given))))
13626 (unless (eolp) (insert " "))
13627 ts))))))
13629 (defvar org-log-note-marker (make-marker)
13630 "Marker pointing at the entry where the note is to be inserted.")
13631 (defvar org-log-note-purpose nil)
13632 (defvar org-log-note-state nil)
13633 (defvar org-log-note-previous-state nil)
13634 (defvar org-log-note-extra nil)
13635 (defvar org-log-note-window-configuration nil)
13636 (defvar org-log-note-return-to (make-marker))
13637 (defvar org-log-note-effective-time nil
13638 "Remembered current time so that dynamically scoped
13639 `org-extend-today-until' affects timestamps in state change log")
13641 (defvar org-log-post-message nil
13642 "Message to be displayed after a log note has been stored.
13643 The auto-repeater uses this.")
13645 (defun org-add-note ()
13646 "Add a note to the current entry.
13647 This is done in the same way as adding a state change note."
13648 (interactive)
13649 (org-add-log-setup 'note))
13651 (defun org-log-beginning (&optional create)
13652 "Return expected start of log notes in current entry.
13653 When optional argument CREATE is non-nil, the function creates
13654 a drawer to store notes, if necessary. Returned position ignores
13655 narrowing."
13656 (org-with-wide-buffer
13657 (let ((drawer (org-log-into-drawer)))
13658 (cond
13659 (drawer
13660 (org-end-of-meta-data)
13661 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13662 (end (if (org-at-heading-p) (point)
13663 (save-excursion (outline-next-heading) (point))))
13664 (case-fold-search t))
13665 (catch 'exit
13666 ;; Try to find existing drawer.
13667 (while (re-search-forward regexp end t)
13668 (let ((element (org-element-at-point)))
13669 (when (eq (org-element-type element) 'drawer)
13670 (let ((cend (org-element-property :contents-end element)))
13671 (when (and (not org-log-states-order-reversed) cend)
13672 (goto-char cend)))
13673 (throw 'exit nil))))
13674 ;; No drawer found. Create one, if permitted.
13675 (when create
13676 (unless (bolp) (insert "\n"))
13677 (let ((beg (point)))
13678 (insert ":" drawer ":\n:END:\n")
13679 (org-indent-region beg (point)))
13680 (end-of-line -1)))))
13682 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13683 (skip-chars-forward " \t\n")
13684 (beginning-of-line)
13685 (unless org-log-states-order-reversed
13686 (org-skip-over-state-notes)
13687 (skip-chars-backward " \t\n")
13688 (forward-line)))))
13689 (if (bolp) (point) (line-beginning-position 2))))
13691 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13692 "Set up the post command hook to take a note.
13693 If this is about to TODO state change, the new state is expected in STATE.
13694 HOW is an indicator what kind of note should be created.
13695 EXTRA is additional text that will be inserted into the notes buffer."
13696 (move-marker org-log-note-marker (point))
13697 (setq org-log-note-purpose purpose
13698 org-log-note-state state
13699 org-log-note-previous-state prev-state
13700 org-log-note-how how
13701 org-log-note-extra extra
13702 org-log-note-effective-time (org-current-effective-time))
13703 (add-hook 'post-command-hook 'org-add-log-note 'append))
13705 (defun org-skip-over-state-notes ()
13706 "Skip past the list of State notes in an entry."
13707 (when (ignore-errors (goto-char (org-in-item-p)))
13708 (let* ((struct (org-list-struct))
13709 (prevs (org-list-prevs-alist struct))
13710 (regexp
13711 (concat "[ \t]*- +"
13712 (replace-regexp-in-string
13713 " +" " +"
13714 (org-replace-escapes
13715 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13716 `(("%d" . ,org-ts-regexp-inactive)
13717 ("%D" . ,org-ts-regexp)
13718 ("%s" . "\"\\S-+\"")
13719 ("%S" . "\"\\S-+\"")
13720 ("%t" . ,org-ts-regexp-inactive)
13721 ("%T" . ,org-ts-regexp)
13722 ("%u" . ".*?")
13723 ("%U" . ".*?")))))))
13724 (while (looking-at-p regexp)
13725 (goto-char (or (org-list-get-next-item (point) struct prevs)
13726 (org-list-get-item-end (point) struct)))))))
13728 (defun org-add-log-note (&optional _purpose)
13729 "Pop up a window for taking a note, and add this note later."
13730 (remove-hook 'post-command-hook 'org-add-log-note)
13731 (setq org-log-note-window-configuration (current-window-configuration))
13732 (delete-other-windows)
13733 (move-marker org-log-note-return-to (point))
13734 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13735 (goto-char org-log-note-marker)
13736 (org-switch-to-buffer-other-window "*Org Note*")
13737 (erase-buffer)
13738 (if (memq org-log-note-how '(time state))
13739 (let (current-prefix-arg) (org-store-log-note))
13740 (let ((org-inhibit-startup t)) (org-mode))
13741 (insert (format "# Insert note for %s.
13742 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13743 (cond
13744 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13745 ((eq org-log-note-purpose 'done) "closed todo item")
13746 ((eq org-log-note-purpose 'state)
13747 (format "state change from \"%s\" to \"%s\""
13748 (or org-log-note-previous-state "")
13749 (or org-log-note-state "")))
13750 ((eq org-log-note-purpose 'reschedule)
13751 "rescheduling")
13752 ((eq org-log-note-purpose 'delschedule)
13753 "no longer scheduled")
13754 ((eq org-log-note-purpose 'redeadline)
13755 "changing deadline")
13756 ((eq org-log-note-purpose 'deldeadline)
13757 "removing deadline")
13758 ((eq org-log-note-purpose 'refile)
13759 "refiling")
13760 ((eq org-log-note-purpose 'note)
13761 "this entry")
13762 (t (error "This should not happen")))))
13763 (when org-log-note-extra (insert org-log-note-extra))
13764 (setq-local org-finish-function 'org-store-log-note)
13765 (run-hooks 'org-log-buffer-setup-hook)))
13767 (defvar org-note-abort nil) ; dynamically scoped
13768 (defun org-store-log-note ()
13769 "Finish taking a log note, and insert it to where it belongs."
13770 (let ((txt (prog1 (buffer-string)
13771 (kill-buffer)))
13772 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13773 lines)
13774 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13775 (setq txt (replace-match "" t t txt)))
13776 (when (string-match "\\s-+\\'" txt)
13777 (setq txt (replace-match "" t t txt)))
13778 (setq lines (org-split-string txt "\n"))
13779 (when (org-string-nw-p note)
13780 (setq note
13781 (org-replace-escapes
13782 note
13783 (list (cons "%u" (user-login-name))
13784 (cons "%U" user-full-name)
13785 (cons "%t" (format-time-string
13786 (org-time-stamp-format 'long 'inactive)
13787 org-log-note-effective-time))
13788 (cons "%T" (format-time-string
13789 (org-time-stamp-format 'long nil)
13790 org-log-note-effective-time))
13791 (cons "%d" (format-time-string
13792 (org-time-stamp-format nil 'inactive)
13793 org-log-note-effective-time))
13794 (cons "%D" (format-time-string
13795 (org-time-stamp-format nil nil)
13796 org-log-note-effective-time))
13797 (cons "%s" (cond
13798 ((not org-log-note-state) "")
13799 ((org-string-match-p org-ts-regexp
13800 org-log-note-state)
13801 (format "\"[%s]\""
13802 (substring org-log-note-state 1 -1)))
13803 (t (format "\"%s\"" org-log-note-state))))
13804 (cons "%S"
13805 (cond
13806 ((not org-log-note-previous-state) "")
13807 ((org-string-match-p org-ts-regexp
13808 org-log-note-previous-state)
13809 (format "\"[%s]\""
13810 (substring
13811 org-log-note-previous-state 1 -1)))
13812 (t (format "\"%s\""
13813 org-log-note-previous-state)))))))
13814 (when lines (setq note (concat note " \\\\")))
13815 (push note lines))
13816 (when (and lines (not (or current-prefix-arg org-note-abort)))
13817 (with-current-buffer (marker-buffer org-log-note-marker)
13818 (org-with-wide-buffer
13819 ;; Find location for the new note.
13820 (goto-char org-log-note-marker)
13821 (set-marker org-log-note-marker nil)
13822 (goto-char (org-log-beginning t))
13823 ;; Make sure point is at the beginning of an empty line.
13824 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13825 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13826 ;; In an existing list, add a new item at the top level.
13827 ;; Otherwise, indent line like a regular one.
13828 (let ((itemp (org-in-item-p)))
13829 (if itemp
13830 (indent-line-to
13831 (let ((struct (save-excursion
13832 (goto-char itemp) (org-list-struct))))
13833 (org-list-get-ind (org-list-get-top-point struct) struct)))
13834 (org-indent-line)))
13835 (insert (org-list-bullet-string "-") (pop lines))
13836 (let ((ind (org-list-item-body-column (line-beginning-position))))
13837 (dolist (line lines)
13838 (insert "\n")
13839 (indent-line-to ind)
13840 (insert line)))
13841 (message "Note stored")
13842 (org-back-to-heading t)
13843 (org-cycle-hide-drawers 'children))
13844 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13845 ;; from within `org-add-log-note' because `buffer-undo-list'
13846 ;; is then modified outside of `org-with-remote-undo'.
13847 (when (eq this-command 'org-agenda-todo)
13848 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13849 ;; Don't add undo information when called from `org-agenda-todo'.
13850 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13851 (set-window-configuration org-log-note-window-configuration)
13852 (with-current-buffer (marker-buffer org-log-note-return-to)
13853 (goto-char org-log-note-return-to))
13854 (move-marker org-log-note-return-to nil)
13855 (when org-log-post-message (message "%s" org-log-post-message))))
13857 (defun org-remove-empty-drawer-at (pos)
13858 "Remove an empty drawer at position POS.
13859 POS may also be a marker."
13860 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13861 (org-with-wide-buffer
13862 (goto-char pos)
13863 (let ((drawer (org-element-at-point)))
13864 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13865 (not (org-element-property :contents-begin drawer)))
13866 (delete-region (org-element-property :begin drawer)
13867 (progn (goto-char (org-element-property :end drawer))
13868 (skip-chars-backward " \r\t\n")
13869 (forward-line)
13870 (point))))))))
13872 (defvar org-ts-type nil)
13873 (defun org-sparse-tree (&optional arg type)
13874 "Create a sparse tree, prompt for the details.
13875 This command can create sparse trees. You first need to select the type
13876 of match used to create the tree:
13878 t Show all TODO entries.
13879 T Show entries with a specific TODO keyword.
13880 m Show entries selected by a tags/property match.
13881 p Enter a property name and its value (both with completion on existing
13882 names/values) and show entries with that property.
13883 r Show entries matching a regular expression (`/' can be used as well).
13884 b Show deadlines and scheduled items before a date.
13885 a Show deadlines and scheduled items after a date.
13886 d Show deadlines due within `org-deadline-warning-days'.
13887 D Show deadlines and scheduled items between a date range."
13888 (interactive "P")
13889 (setq type (or type org-sparse-tree-default-date-type))
13890 (setq org-ts-type type)
13891 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13892 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13893 \[c]ycle through date types: %s"
13894 (cl-case type
13895 (all "all timestamps")
13896 (scheduled "only scheduled")
13897 (deadline "only deadline")
13898 (active "only active timestamps")
13899 (inactive "only inactive timestamps")
13900 (closed "with a closed time-stamp")
13901 (otherwise "scheduled/deadline")))
13902 (let ((answer (read-char-exclusive)))
13903 (cl-case answer
13905 (org-sparse-tree
13907 (cadr
13908 (memq type '(nil all scheduled deadline active inactive closed)))))
13909 (?d (call-interactively 'org-check-deadlines))
13910 (?b (call-interactively 'org-check-before-date))
13911 (?a (call-interactively 'org-check-after-date))
13912 (?D (call-interactively 'org-check-dates-range))
13913 (?t (call-interactively 'org-show-todo-tree))
13914 (?T (org-show-todo-tree '(4)))
13915 (?m (call-interactively 'org-match-sparse-tree))
13916 ((?p ?P)
13917 (let* ((kwd (completing-read
13918 "Property: " (mapcar #'list (org-buffer-property-keys))))
13919 (value (completing-read
13920 "Value: " (mapcar #'list (org-property-values kwd)))))
13921 (unless (string-match "\\`{.*}\\'" value)
13922 (setq value (concat "\"" value "\"")))
13923 (org-match-sparse-tree arg (concat kwd "=" value))))
13924 ((?r ?R ?/) (call-interactively 'org-occur))
13925 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13927 (defvar-local org-occur-highlights nil
13928 "List of overlays used for occur matches.")
13929 (defvar-local org-occur-parameters nil
13930 "Parameters of the active org-occur calls.
13931 This is a list, each call to org-occur pushes as cons cell,
13932 containing the regular expression and the callback, onto the list.
13933 The list can contain several entries if `org-occur' has been called
13934 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13935 will only contain one set of parameters. When the highlights are
13936 removed (for example with `C-c C-c', or with the next edit (depending
13937 on `org-remove-highlights-with-change'), this variable is emptied
13938 as well.")
13940 (defun org-occur (regexp &optional keep-previous callback)
13941 "Make a compact tree which shows all matches of REGEXP.
13943 The tree will show the lines where the regexp matches, and any other context
13944 defined in `org-show-context-detail', which see.
13946 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13947 done by a previous call to `org-occur' will be kept, to allow stacking of
13948 calls to this command.
13950 Optional argument CALLBACK can be a function of no argument. In this case,
13951 it is called with point at the end of the match, match data being set
13952 accordingly. Current match is shown only if the return value is non-nil.
13953 The function must neither move point nor alter narrowing."
13954 (interactive "sRegexp: \nP")
13955 (when (equal regexp "")
13956 (user-error "Regexp cannot be empty"))
13957 (unless keep-previous
13958 (org-remove-occur-highlights nil nil t))
13959 (push (cons regexp callback) org-occur-parameters)
13960 (let ((cnt 0))
13961 (save-excursion
13962 (goto-char (point-min))
13963 (when (or (not keep-previous) ; do not want to keep
13964 (not org-occur-highlights)) ; no previous matches
13965 ;; hide everything
13966 (org-overview))
13967 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13968 (isearch-no-upper-case-p regexp t)
13969 org-occur-case-fold-search)))
13970 (while (re-search-forward regexp nil t)
13971 (when (or (not callback)
13972 (save-match-data (funcall callback)))
13973 (setq cnt (1+ cnt))
13974 (when org-highlight-sparse-tree-matches
13975 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13976 (org-show-context 'occur-tree)))))
13977 (when org-remove-highlights-with-change
13978 (add-hook 'before-change-functions 'org-remove-occur-highlights
13979 nil 'local))
13980 (unless org-sparse-tree-open-archived-trees
13981 (org-hide-archived-subtrees (point-min) (point-max)))
13982 (run-hooks 'org-occur-hook)
13983 (when (org-called-interactively-p 'interactive)
13984 (message "%d match(es) for regexp %s" cnt regexp))
13985 cnt))
13987 (defun org-occur-next-match (&optional n _reset)
13988 "Function for `next-error-function' to find sparse tree matches.
13989 N is the number of matches to move, when negative move backwards.
13990 This function always goes back to the starting point when no
13991 match is found."
13992 (let* ((limit (if (< n 0) (point-min) (point-max)))
13993 (search-func (if (< n 0)
13994 'previous-single-char-property-change
13995 'next-single-char-property-change))
13996 (n (abs n))
13997 (pos (point))
13999 (catch 'exit
14000 (while (setq p1 (funcall search-func (point) 'org-type))
14001 (when (equal p1 limit)
14002 (goto-char pos)
14003 (user-error "No more matches"))
14004 (when (equal (get-char-property p1 'org-type) 'org-occur)
14005 (setq n (1- n))
14006 (when (= n 0)
14007 (goto-char p1)
14008 (throw 'exit (point))))
14009 (goto-char p1))
14010 (goto-char p1)
14011 (user-error "No more matches"))))
14013 (defun org-show-context (&optional key)
14014 "Make sure point and context are visible.
14015 Optional argument KEY, when non-nil, is a symbol. See
14016 `org-show-context-detail' for allowed values and how much is to
14017 be shown."
14018 (org-show-set-visibility
14019 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14020 ((cdr (assq key org-show-context-detail)))
14021 (t (cdr (assq 'default org-show-context-detail))))))
14023 (defun org-show-set-visibility (detail)
14024 "Set visibility around point according to DETAIL.
14025 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14026 `tree', `canonical' or t. See `org-show-context-detail' for more
14027 information."
14028 ;; Show current heading and possibly its entry, following headline
14029 ;; or all children.
14030 (if (and (org-at-heading-p) (not (eq detail 'local)))
14031 (org-flag-heading nil)
14032 (org-show-entry)
14033 ;; If point is hidden within a drawer or a block, make sure to
14034 ;; expose it.
14035 (dolist (o (overlays-at (point)))
14036 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14037 (delete-overlay o)))
14038 (unless (org-before-first-heading-p)
14039 (org-with-limited-levels
14040 (cl-case detail
14041 ((tree canonical t) (org-show-children))
14042 ((nil minimal ancestors))
14043 (t (save-excursion
14044 (outline-next-heading)
14045 (org-flag-heading nil)))))))
14046 ;; Show all siblings.
14047 (when (eq detail 'lineage) (org-show-siblings))
14048 ;; Show ancestors, possibly with their children.
14049 (when (memq detail '(ancestors lineage tree canonical t))
14050 (save-excursion
14051 (while (org-up-heading-safe)
14052 (org-flag-heading nil)
14053 (when (memq detail '(canonical t)) (org-show-entry))
14054 (when (memq detail '(tree canonical t)) (org-show-children))))))
14056 (defvar org-reveal-start-hook nil
14057 "Hook run before revealing a location.")
14059 (defun org-reveal (&optional siblings)
14060 "Show current entry, hierarchy above it, and the following headline.
14062 This can be used to show a consistent set of context around
14063 locations exposed with `org-show-context'.
14065 With optional argument SIBLINGS, on each level of the hierarchy all
14066 siblings are shown. This repairs the tree structure to what it would
14067 look like when opened with hierarchical calls to `org-cycle'.
14069 With double optional argument \\[universal-argument] \\[universal-argument], \
14070 go to the parent and show the
14071 entire tree."
14072 (interactive "P")
14073 (run-hooks 'org-reveal-start-hook)
14074 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14075 ((equal siblings '(16))
14076 (save-excursion
14077 (when (org-up-heading-safe)
14078 (org-show-subtree)
14079 (run-hook-with-args 'org-cycle-hook 'subtree))))
14080 (t (org-show-set-visibility 'lineage))))
14082 (defun org-highlight-new-match (beg end)
14083 "Highlight from BEG to END and mark the highlight is an occur headline."
14084 (let ((ov (make-overlay beg end)))
14085 (overlay-put ov 'face 'secondary-selection)
14086 (overlay-put ov 'org-type 'org-occur)
14087 (push ov org-occur-highlights)))
14089 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14090 "Remove the occur highlights from the buffer.
14091 BEG and END are ignored. If NOREMOVE is nil, remove this function
14092 from the `before-change-functions' in the current buffer."
14093 (interactive)
14094 (unless org-inhibit-highlight-removal
14095 (mapc #'delete-overlay org-occur-highlights)
14096 (setq org-occur-highlights nil)
14097 (setq org-occur-parameters nil)
14098 (unless noremove
14099 (remove-hook 'before-change-functions
14100 'org-remove-occur-highlights 'local))))
14102 ;;;; Priorities
14104 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14105 "Regular expression matching the priority indicator.")
14107 (defvar org-remove-priority-next-time nil)
14109 (defun org-priority-up ()
14110 "Increase the priority of the current item."
14111 (interactive)
14112 (org-priority 'up))
14114 (defun org-priority-down ()
14115 "Decrease the priority of the current item."
14116 (interactive)
14117 (org-priority 'down))
14119 (defun org-priority (&optional action _show)
14120 "Change the priority of an item.
14121 ACTION can be `set', `up', `down', or a character."
14122 (interactive "P")
14123 (if (equal action '(4))
14124 (org-show-priority)
14125 (unless org-enable-priority-commands
14126 (user-error "Priority commands are disabled"))
14127 (setq action (or action 'set))
14128 (let (current new news have remove)
14129 (save-excursion
14130 (org-back-to-heading t)
14131 (when (looking-at org-priority-regexp)
14132 (setq current (string-to-char (match-string 2))
14133 have t))
14134 (cond
14135 ((eq action 'remove)
14136 (setq remove t new ?\ ))
14137 ((or (eq action 'set)
14138 (integerp action))
14139 (if (not (eq action 'set))
14140 (setq new action)
14141 (message "Priority %c-%c, SPC to remove: "
14142 org-highest-priority org-lowest-priority)
14143 (save-match-data
14144 (setq new (read-char-exclusive))))
14145 (when (and (= (upcase org-highest-priority) org-highest-priority)
14146 (= (upcase org-lowest-priority) org-lowest-priority))
14147 (setq new (upcase new)))
14148 (cond ((equal new ?\ ) (setq remove t))
14149 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14150 (user-error "Priority must be between `%c' and `%c'"
14151 org-highest-priority org-lowest-priority))))
14152 ((eq action 'up)
14153 (setq new (if have
14154 (1- current) ; normal cycling
14155 ;; last priority was empty
14156 (if (eq last-command this-command)
14157 org-lowest-priority ; wrap around empty to lowest
14158 ;; default
14159 (if org-priority-start-cycle-with-default
14160 org-default-priority
14161 (1- org-default-priority))))))
14162 ((eq action 'down)
14163 (setq new (if have
14164 (1+ current) ; normal cycling
14165 ;; last priority was empty
14166 (if (eq last-command this-command)
14167 org-highest-priority ; wrap around empty to highest
14168 ;; default
14169 (if org-priority-start-cycle-with-default
14170 org-default-priority
14171 (1+ org-default-priority))))))
14172 (t (user-error "Invalid action")))
14173 (when (or (< (upcase new) org-highest-priority)
14174 (> (upcase new) org-lowest-priority))
14175 (if (and (memq action '(up down))
14176 (not have) (not (eq last-command this-command)))
14177 ;; `new' is from default priority
14178 (error
14179 "The default can not be set, see `org-default-priority' why")
14180 ;; normal cycling: `new' is beyond highest/lowest priority
14181 ;; and is wrapped around to the empty priority
14182 (setq remove t)))
14183 (setq news (format "%c" new))
14184 (if have
14185 (if remove
14186 (replace-match "" t t nil 1)
14187 (replace-match news t t nil 2))
14188 (if remove
14189 (user-error "No priority cookie found in line")
14190 (let ((case-fold-search nil))
14191 (looking-at org-todo-line-regexp))
14192 (if (match-end 2)
14193 (progn
14194 (goto-char (match-end 2))
14195 (insert " [#" news "]"))
14196 (goto-char (match-beginning 3))
14197 (insert "[#" news "] "))))
14198 (org-set-tags nil 'align))
14199 (if remove
14200 (message "Priority removed")
14201 (message "Priority of current item set to %s" news)))))
14203 (defun org-show-priority ()
14204 "Show the priority of the current item.
14205 This priority is composed of the main priority given with the [#A] cookies,
14206 and by additional input from the age of a schedules or deadline entry."
14207 (interactive)
14208 (let ((pri (if (eq major-mode 'org-agenda-mode)
14209 (org-get-at-bol 'priority)
14210 (save-excursion
14211 (save-match-data
14212 (beginning-of-line)
14213 (and (looking-at org-heading-regexp)
14214 (org-get-priority (match-string 0))))))))
14215 (message "Priority is %d" (if pri pri -1000))))
14217 (defun org-get-priority (s)
14218 "Find priority cookie and return priority."
14219 (save-match-data
14220 (if (functionp org-get-priority-function)
14221 (funcall org-get-priority-function)
14222 (if (not (string-match org-priority-regexp s))
14223 (* 1000 (- org-lowest-priority org-default-priority))
14224 (* 1000 (- org-lowest-priority
14225 (string-to-char (match-string 2 s))))))))
14227 ;;;; Tags
14229 (defvar org-agenda-archives-mode)
14230 (defvar org-map-continue-from nil
14231 "Position from where mapping should continue.
14232 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14234 (defvar org-scanner-tags nil
14235 "The current tag list while the tags scanner is running.")
14237 (defvar org-trust-scanner-tags nil
14238 "Should `org-get-tags-at' use the tags for the scanner.
14239 This is for internal dynamical scoping only.
14240 When this is non-nil, the function `org-get-tags-at' will return the value
14241 of `org-scanner-tags' instead of building the list by itself. This
14242 can lead to large speed-ups when the tags scanner is used in a file with
14243 many entries, and when the list of tags is retrieved, for example to
14244 obtain a list of properties. Building the tags list for each entry in such
14245 a file becomes an N^2 operation - but with this variable set, it scales
14246 as N.")
14248 (defvar org--matcher-tags-todo-only nil)
14250 (defun org-scan-tags (action matcher todo-only &optional start-level)
14251 "Scan headline tags with inheritance and produce output ACTION.
14253 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14254 or `agenda' to produce an entry list for an agenda view. It can also be
14255 a Lisp form or a function that should be called at each matched headline, in
14256 this case the return value is a list of all return values from these calls.
14258 MATCHER is a function accepting three arguments, returning
14259 a non-nil value whenever a given set of tags qualifies a headline
14260 for inclusion. See `org-make-tags-matcher' for more information.
14261 As a special case, it can also be set to t (respectively nil) in
14262 order to match all (respectively none) headline.
14264 When TODO-ONLY is non-nil, only lines with a not-done TODO
14265 keyword are included in the output.
14267 START-LEVEL can be a string with asterisks, reducing the scope to
14268 headlines matching this string."
14269 (require 'org-agenda)
14270 (let* ((re (concat "^"
14271 (if start-level
14272 ;; Get the correct level to match
14273 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14274 org-outline-regexp)
14275 " *\\(\\<\\("
14276 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14277 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14278 (props (list 'face 'default
14279 'done-face 'org-agenda-done
14280 'undone-face 'default
14281 'mouse-face 'highlight
14282 'org-not-done-regexp org-not-done-regexp
14283 'org-todo-regexp org-todo-regexp
14284 'org-complex-heading-regexp org-complex-heading-regexp
14285 'help-echo
14286 (format "mouse-2 or RET jump to org file %s"
14287 (abbreviate-file-name
14288 (or (buffer-file-name (buffer-base-buffer))
14289 (buffer-name (buffer-base-buffer)))))))
14290 (org-map-continue-from nil)
14291 lspos tags tags-list
14292 (tags-alist (list (cons 0 org-file-tags)))
14293 (llast 0) rtn rtn1 level category i txt
14294 todo marker entry priority
14295 ts-date ts-date-type ts-date-pair)
14296 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14297 (setq action (list 'lambda nil action)))
14298 (save-excursion
14299 (goto-char (point-min))
14300 (when (eq action 'sparse-tree)
14301 (org-overview)
14302 (org-remove-occur-highlights))
14303 (while (let (case-fold-search)
14304 (re-search-forward re nil t))
14305 (setq org-map-continue-from nil)
14306 (catch :skip
14307 (setq todo
14308 ;; TODO: is the 1-2 difference a bug?
14309 (when (match-end 1) (match-string-no-properties 2))
14310 tags (when (match-end 4) (match-string-no-properties 4)))
14311 (goto-char (setq lspos (match-beginning 0)))
14312 (setq level (org-reduced-level (org-outline-level))
14313 category (org-get-category))
14314 (when (eq action 'agenda)
14315 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14316 ts-date (car ts-date-pair)
14317 ts-date-type (cdr ts-date-pair)))
14318 (setq i llast llast level)
14319 ;; remove tag lists from same and sublevels
14320 (while (>= i level)
14321 (when (setq entry (assoc i tags-alist))
14322 (setq tags-alist (delete entry tags-alist)))
14323 (setq i (1- i)))
14324 ;; add the next tags
14325 (when tags
14326 (setq tags (org-split-string tags ":")
14327 tags-alist
14328 (cons (cons level tags) tags-alist)))
14329 ;; compile tags for current headline
14330 (setq tags-list
14331 (if org-use-tag-inheritance
14332 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14333 tags)
14334 org-scanner-tags tags-list)
14335 (when org-use-tag-inheritance
14336 (setcdr (car tags-alist)
14337 (mapcar (lambda (x)
14338 (setq x (copy-sequence x))
14339 (org-add-prop-inherited x))
14340 (cdar tags-alist))))
14341 (when (and tags org-use-tag-inheritance
14342 (or (not (eq t org-use-tag-inheritance))
14343 org-tags-exclude-from-inheritance))
14344 ;; Selective inheritance, remove uninherited ones.
14345 (setcdr (car tags-alist)
14346 (org-remove-uninherited-tags (cdar tags-alist))))
14347 (when (and
14349 ;; eval matcher only when the todo condition is OK
14350 (and (or (not todo-only) (member todo org-not-done-keywords))
14351 (if (functionp matcher)
14352 (let ((case-fold-search t) (org-trust-scanner-tags t))
14353 (funcall matcher todo tags-list level))
14354 matcher))
14356 ;; Call the skipper, but return t if it does not
14357 ;; skip, so that the `and' form continues evaluating.
14358 (progn
14359 (unless (eq action 'sparse-tree) (org-agenda-skip))
14362 ;; Check if timestamps are deselecting this entry
14363 (or (not todo-only)
14364 (and (member todo org-not-done-keywords)
14365 (or (not org-agenda-tags-todo-honor-ignore-options)
14366 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14368 ;; select this headline
14369 (cond
14370 ((eq action 'sparse-tree)
14371 (and org-highlight-sparse-tree-matches
14372 (org-get-heading) (match-end 0)
14373 (org-highlight-new-match
14374 (match-beginning 1) (match-end 1)))
14375 (org-show-context 'tags-tree))
14376 ((eq action 'agenda)
14377 (setq txt (org-agenda-format-item
14379 (concat
14380 (if (eq org-tags-match-list-sublevels 'indented)
14381 (make-string (1- level) ?.) "")
14382 (org-get-heading))
14383 (make-string level ?\s)
14384 category
14385 tags-list)
14386 priority (org-get-priority txt))
14387 (goto-char lspos)
14388 (setq marker (org-agenda-new-marker))
14389 (org-add-props txt props
14390 'org-marker marker 'org-hd-marker marker 'org-category category
14391 'todo-state todo
14392 'ts-date ts-date
14393 'priority priority
14394 'type (concat "tagsmatch" ts-date-type))
14395 (push txt rtn))
14396 ((functionp action)
14397 (setq org-map-continue-from nil)
14398 (save-excursion
14399 (setq rtn1 (funcall action))
14400 (push rtn1 rtn)))
14401 (t (user-error "Invalid action")))
14403 ;; if we are to skip sublevels, jump to end of subtree
14404 (unless org-tags-match-list-sublevels
14405 (org-end-of-subtree t)
14406 (backward-char 1))))
14407 ;; Get the correct position from where to continue
14408 (if org-map-continue-from
14409 (goto-char org-map-continue-from)
14410 (and (= (point) lspos) (end-of-line 1)))))
14411 (when (and (eq action 'sparse-tree)
14412 (not org-sparse-tree-open-archived-trees))
14413 (org-hide-archived-subtrees (point-min) (point-max)))
14414 (nreverse rtn)))
14416 (defun org-remove-uninherited-tags (tags)
14417 "Remove all tags that are not inherited from the list TAGS."
14418 (cond
14419 ((eq org-use-tag-inheritance t)
14420 (if org-tags-exclude-from-inheritance
14421 (org-delete-all org-tags-exclude-from-inheritance tags)
14422 tags))
14423 ((not org-use-tag-inheritance) nil)
14424 ((stringp org-use-tag-inheritance)
14425 (delq nil (mapcar
14426 (lambda (x)
14427 (if (and (string-match org-use-tag-inheritance x)
14428 (not (member x org-tags-exclude-from-inheritance)))
14429 x nil))
14430 tags)))
14431 ((listp org-use-tag-inheritance)
14432 (delq nil (mapcar
14433 (lambda (x)
14434 (if (member x org-use-tag-inheritance) x nil))
14435 tags)))))
14437 (defun org-match-sparse-tree (&optional todo-only match)
14438 "Create a sparse tree according to tags string MATCH.
14439 MATCH can contain positive and negative selection of tags, like
14440 \"+WORK+URGENT-WITHBOSS\".
14441 If optional argument TODO-ONLY is non-nil, only select lines that are
14442 also TODO lines."
14443 (interactive "P")
14444 (org-agenda-prepare-buffers (list (current-buffer)))
14445 (let ((org--matcher-tags-todo-only todo-only))
14446 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14447 org--matcher-tags-todo-only)))
14449 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14451 (defvar org-cached-props nil)
14452 (defun org-cached-entry-get (pom property)
14453 (if (or (eq t org-use-property-inheritance)
14454 (and (stringp org-use-property-inheritance)
14455 (let ((case-fold-search t))
14456 (org-string-match-p org-use-property-inheritance property)))
14457 (and (listp org-use-property-inheritance)
14458 (member-ignore-case property org-use-property-inheritance)))
14459 ;; Caching is not possible, check it directly.
14460 (org-entry-get pom property 'inherit)
14461 ;; Get all properties, so we can do complicated checks easily.
14462 (cdr (assoc-string property
14463 (or org-cached-props
14464 (setq org-cached-props (org-entry-properties pom)))
14465 t))))
14467 (defun org-global-tags-completion-table (&optional files)
14468 "Return the list of all tags in all agenda buffer/files.
14469 Optional FILES argument is a list of files which can be used
14470 instead of the agenda files."
14471 (save-excursion
14472 (org-uniquify
14473 (delq nil
14474 (apply #'append
14475 (mapcar
14476 (lambda (file)
14477 (set-buffer (find-file-noselect file))
14478 (mapcar (lambda (x)
14479 (and (stringp (car-safe x))
14480 (list (car-safe x))))
14481 (or org-current-tag-alist (org-get-buffer-tags))))
14482 (if (car-safe files) files
14483 (org-agenda-files))))))))
14485 (defun org-make-tags-matcher (match)
14486 "Create the TAGS/TODO matcher form for the selection string MATCH.
14488 Returns a cons of the selection string MATCH and a function
14489 implementing the matcher.
14491 The matcher is to be called at an Org entry, with point on the
14492 headline, and returns non-nil if the entry matches the selection
14493 string MATCH. It must be called with three arguments: the TODO
14494 keyword at the entry (or nil if none), the list of all tags at
14495 the entry including inherited ones and the reduced level of the
14496 headline. Additionally, the category of the entry, if any, must
14497 be specified as the text property `org-category' on the headline.
14499 This function sets the variable `org--matcher-tags-todo-only' to
14500 a non-nil value if the matcher restricts matching to TODO
14501 entries, otherwise it is not touched.
14503 See also `org-scan-tags'."
14504 (unless match
14505 ;; Get a new match request, with completion against the global
14506 ;; tags table and the local tags in current buffer.
14507 (let ((org-last-tags-completion-table
14508 (org-uniquify
14509 (delq nil (append (org-get-buffer-tags)
14510 (org-global-tags-completion-table))))))
14511 (setq match
14512 (completing-read
14513 "Match: "
14514 'org-tags-completion-function nil nil nil 'org-tags-history))))
14516 (let ((match0 match)
14517 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14518 (start 0)
14519 tagsmatch todomatch tagsmatcher todomatcher)
14521 ;; Expand group tags.
14522 (setq match (org-tags-expand match))
14524 ;; Check if there is a TODO part of this match, which would be the
14525 ;; part after a "/". To make sure that this slash is not part of
14526 ;; a property value to be matched against, we also check that
14527 ;; there is no / after that slash. First, find the last slash.
14528 (let ((s 0))
14529 (while (string-match "/+" match s)
14530 (setq start (match-beginning 0))
14531 (setq s (match-end 0))))
14532 (if (and (string-match "/+" match start)
14533 (not (string-match-p "\"" match start)))
14534 ;; Match contains also a TODO-matching request.
14535 (progn
14536 (setq tagsmatch (substring match 0 (match-beginning 0)))
14537 (setq todomatch (substring match (match-end 0)))
14538 (when (string-match "\\`!" todomatch)
14539 (setq org--matcher-tags-todo-only t)
14540 (setq todomatch (substring todomatch 1)))
14541 (when (string-match "\\`\\s-*\\'" todomatch)
14542 (setq todomatch nil)))
14543 ;; Only matching tags.
14544 (setq tagsmatch match)
14545 (setq todomatch nil))
14547 ;; Make the tags matcher.
14548 (when (org-string-nw-p tagsmatch)
14549 (let ((orlist nil)
14550 (orterms (org-split-string tagsmatch "|"))
14551 term)
14552 (while (setq term (pop orterms))
14553 (while (and (equal (substring term -1) "\\") orterms)
14554 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14555 (while (string-match re term)
14556 (let* ((rest (substring term (match-end 0)))
14557 (minus (and (match-end 1)
14558 (equal (match-string 1 term) "-")))
14559 (tag (save-match-data
14560 (replace-regexp-in-string
14561 "\\\\-" "-" (match-string 2 term))))
14562 (regexp (eq (string-to-char tag) ?{))
14563 (levelp (match-end 4))
14564 (propp (match-end 5))
14566 (cond
14567 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14568 (levelp
14569 `(,(org-op-to-function (match-string 3 term))
14570 level
14571 ,(string-to-number (match-string 4 term))))
14572 (propp
14573 (let* ((gv (pcase (upcase (match-string 5 term))
14574 ("CATEGORY"
14575 '(get-text-property (point) 'org-category))
14576 ("TODO" 'todo)
14577 (p `(org-cached-entry-get nil ,p))))
14578 (pv (match-string 7 term))
14579 (regexp (eq (string-to-char pv) ?{))
14580 (strp (eq (string-to-char pv) ?\"))
14581 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14582 (po (org-op-to-function (match-string 6 term)
14583 (if timep 'time strp))))
14584 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14585 (when timep (setq pv (org-matcher-time pv)))
14586 (cond ((and regexp (eq po 'org<>))
14587 `(not (string-match ,pv (or ,gv ""))))
14588 (regexp `(string-match ,pv (or ,gv "")))
14589 (strp `(,po (or ,gv "") ,pv))
14591 `(,po
14592 (string-to-number (or ,gv ""))
14593 ,(string-to-number pv))))))
14594 (t `(member ,tag tags-list)))))
14595 (push (if minus `(not ,mm) mm) tagsmatcher)
14596 (setq term rest)))
14597 (push `(and ,@tagsmatcher) orlist)
14598 (setq tagsmatcher nil))
14599 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14601 ;; Make the TODO matcher.
14602 (when (org-string-nw-p todomatch)
14603 (let ((orlist nil))
14604 (dolist (term (org-split-string todomatch "|"))
14605 (while (string-match re term)
14606 (let* ((minus (and (match-end 1)
14607 (equal (match-string 1 term) "-")))
14608 (kwd (match-string 2 term))
14609 (regexp (eq (string-to-char kwd) ?{))
14610 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14611 `(equal todo ,kwd))))
14612 (push (if minus `(not ,mm) mm) todomatcher))
14613 (setq term (substring term (match-end 0))))
14614 (push (if (> (length todomatcher) 1)
14615 (cons 'and todomatcher)
14616 (car todomatcher))
14617 orlist)
14618 (setq todomatcher nil))
14619 (setq todomatcher (cons 'or orlist))))
14621 ;; Return the string and function of the matcher. If no
14622 ;; tags-specific or todo-specific matcher exists, match
14623 ;; everything.
14624 (let ((matcher (if (and tagsmatcher todomatcher)
14625 `(and ,tagsmatcher ,todomatcher)
14626 (or tagsmatcher todomatcher t))))
14627 (when org--matcher-tags-todo-only
14628 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14629 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14631 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14632 "Expand group tags in MATCH.
14634 This replaces every group tag in MATCH with a regexp tag search.
14635 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14636 will be replaced like this:
14638 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14639 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14640 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14642 Replacing by a regexp preserves the structure of the match.
14643 E.g., this expansion
14645 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14647 will match anything tagged with \"Lab\" and \"Home\", or tagged
14648 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14650 A group tag in MATCH can contain regular expressions of its own.
14651 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14652 will be replaced like this:
14654 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14656 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14657 assumed to be a single group tag, and the function will return
14658 the list of tags in this group.
14660 When DOWNCASE is non-nil, expand downcased TAGS."
14661 (if org-group-tags
14662 (let* ((case-fold-search t)
14663 (stable org-mode-syntax-table)
14664 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14665 (taggroups (if downcased
14666 (mapcar (lambda (tg) (mapcar #'downcase tg))
14667 taggroups)
14668 taggroups))
14669 (taggroups-keys (mapcar #'car taggroups))
14670 (return-match (if downcased (downcase match) match))
14671 (count 0)
14672 (work-already-expanded tags-already-expanded)
14673 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14674 ;; @ and _ are allowed as word-components in tags.
14675 (modify-syntax-entry ?@ "w" stable)
14676 (modify-syntax-entry ?_ "w" stable)
14677 ;; Temporarily replace regexp-expressions in the match-expression.
14678 (while (string-match "{.+?}" return-match)
14679 (cl-incf count)
14680 (push (match-string 0 return-match) regexps-in-match)
14681 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14682 (while (and taggroups-keys
14683 (with-syntax-table stable
14684 (string-match
14685 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14686 (regexp-opt taggroups-keys) "\\>\\)")
14687 return-match)))
14688 (let* ((dir (match-string 1 return-match))
14689 (tag (match-string 2 return-match))
14690 (tag (if downcased (downcase tag) tag)))
14691 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14692 (member tag work-already-expanded))
14693 (setq tags-in-group (assoc tag taggroups))
14694 (push tag work-already-expanded)
14695 ;; Recursively expand each tag in the group, if the tag hasn't
14696 ;; already been expanded. Restore the match-data after all recursive calls.
14697 (save-match-data
14698 (let (tags-expanded)
14699 (dolist (x (cdr tags-in-group))
14700 (if (and (member x taggroups-keys)
14701 (not (member x work-already-expanded)))
14702 (setq tags-expanded
14703 (delete-dups
14704 (append
14705 (org-tags-expand x t downcased
14706 work-already-expanded)
14707 tags-expanded)))
14708 (setq tags-expanded
14709 (append (list x) tags-expanded)))
14710 (setq work-already-expanded
14711 (delete-dups
14712 (append tags-expanded
14713 work-already-expanded))))
14714 (setq tags-in-group
14715 (delete-dups (cons (car tags-in-group)
14716 tags-expanded)))))
14717 ;; Filter tag-regexps from tags.
14718 (setq regexp-in-group-escaped
14719 (delq nil (mapcar (lambda (x)
14720 (if (stringp x)
14721 (and (equal "{" (substring x 0 1))
14722 (equal "}" (substring x -1))
14725 tags-in-group))
14726 regexp-in-group
14727 (mapcar (lambda (x)
14728 (substring x 1 -1))
14729 regexp-in-group-escaped)
14730 tags-in-group
14731 (delq nil (mapcar (lambda (x)
14732 (if (stringp x)
14733 (and (not (equal "{" (substring x 0 1)))
14734 (not (equal "}" (substring x -1)))
14737 tags-in-group)))
14738 ;; If single-as-list, do no more in the while-loop.
14739 (if (not single-as-list)
14740 (progn
14741 (when regexp-in-group
14742 (setq regexp-in-group
14743 (concat "\\|"
14744 (mapconcat 'identity regexp-in-group
14745 "\\|"))))
14746 (setq tags-in-group
14747 (concat dir
14748 "{\\<"
14749 (regexp-opt tags-in-group)
14750 "\\>"
14751 regexp-in-group
14752 "}"))
14753 (when (stringp tags-in-group)
14754 (org-add-props tags-in-group '(grouptag t)))
14755 (setq return-match
14756 (replace-match tags-in-group t t return-match)))
14757 (setq tags-in-group
14758 (append regexp-in-group-escaped tags-in-group))))
14759 (setq taggroups-keys (delete tag taggroups-keys))))
14760 ;; Add the regular expressions back into the match-expression again.
14761 (while regexps-in-match
14762 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14763 (pop regexps-in-match)
14764 return-match t t))
14765 (cl-decf count))
14766 (if single-as-list
14767 (if tags-in-group tags-in-group (list return-match))
14768 return-match))
14769 (if single-as-list
14770 (list (if downcased (downcase match) match))
14771 match)))
14773 (defun org-op-to-function (op &optional stringp)
14774 "Turn an operator into the appropriate function."
14775 (setq op
14776 (cond
14777 ((equal op "<" ) '(< string< org-time<))
14778 ((equal op ">" ) '(> org-string> org-time>))
14779 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14780 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14781 ((member op '("=" "==")) '(= string= org-time=))
14782 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14783 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14785 (defun org<> (a b) (not (= a b)))
14786 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14787 (defun org-string>= (a b) (not (string< a b)))
14788 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14789 (defun org-string<> (a b) (not (string= a b)))
14790 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14791 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14792 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14793 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14794 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14795 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14796 (defun org-2ft (s)
14797 "Convert S to a floating point time.
14798 If S is already a number, just return it. If it is a string, parse
14799 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14800 (cond
14801 ((numberp s) s)
14802 ((stringp s)
14803 (condition-case nil
14804 (float-time (apply 'encode-time (org-parse-time-string s)))
14805 (error 0.)))
14806 (t 0.)))
14808 (defun org-time-today ()
14809 "Time in seconds today at 0:00.
14810 Returns the float number of seconds since the beginning of the
14811 epoch to the beginning of today (00:00)."
14812 (float-time (apply 'encode-time
14813 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14815 (defun org-matcher-time (s)
14816 "Interpret a time comparison value."
14817 (save-match-data
14818 (cond
14819 ((string= s "<now>") (float-time))
14820 ((string= s "<today>") (org-time-today))
14821 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14822 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14823 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14824 (+ (org-time-today)
14825 (* (string-to-number (match-string 1 s))
14826 (cdr (assoc (match-string 2 s)
14827 '(("d" . 86400.0) ("w" . 604800.0)
14828 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14829 (t (org-2ft s)))))
14831 (defun org-match-any-p (re list)
14832 "Does re match any element of list?"
14833 (setq list (mapcar (lambda (x) (string-match re x)) list))
14834 (delq nil list))
14836 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14837 (defvar org-tags-overlay (make-overlay 1 1))
14838 (delete-overlay org-tags-overlay)
14840 (defun org-get-local-tags-at (&optional pos)
14841 "Get a list of tags defined in the current headline."
14842 (org-get-tags-at pos 'local))
14844 (defun org-get-local-tags ()
14845 "Get a list of tags defined in the current headline."
14846 (org-get-tags-at nil 'local))
14848 (defun org-get-tags-at (&optional pos local)
14849 "Get a list of all headline tags applicable at POS.
14850 POS defaults to point. If tags are inherited, the list contains
14851 the targets in the same sequence as the headlines appear, i.e.
14852 the tags of the current headline come last.
14853 When LOCAL is non-nil, only return tags from the current headline,
14854 ignore inherited ones."
14855 (interactive)
14856 (if (and org-trust-scanner-tags
14857 (or (not pos) (equal pos (point)))
14858 (not local))
14859 org-scanner-tags
14860 (let (tags ltags lastpos parent)
14861 (save-excursion
14862 (save-restriction
14863 (widen)
14864 (goto-char (or pos (point)))
14865 (save-match-data
14866 (catch 'done
14867 (condition-case nil
14868 (progn
14869 (org-back-to-heading t)
14870 (while (not (equal lastpos (point)))
14871 (setq lastpos (point))
14872 (when (looking-at ".+:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14873 (setq ltags (org-split-string
14874 (match-string-no-properties 1) ":"))
14875 (when parent
14876 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14877 (setq tags (append
14878 (if parent
14879 (org-remove-uninherited-tags ltags)
14880 ltags)
14881 tags)))
14882 (or org-use-tag-inheritance (throw 'done t))
14883 (when local (throw 'done t))
14884 (or (org-up-heading-safe) (error nil))
14885 (setq parent t)))
14886 (error nil)))))
14887 (if local
14888 tags
14889 (reverse (delete-dups
14890 (reverse (append
14891 (org-remove-uninherited-tags
14892 org-file-tags)
14893 tags)))))))))
14895 (defun org-add-prop-inherited (s)
14896 (add-text-properties 0 (length s) '(inherited t) s)
14899 (defun org-toggle-tag (tag &optional onoff)
14900 "Toggle the tag TAG for the current line.
14901 If ONOFF is `on' or `off', don't toggle but set to this state."
14902 (let (res current)
14903 (save-excursion
14904 (org-back-to-heading t)
14905 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14906 (point-at-eol) t)
14907 (progn
14908 (setq current (match-string 1))
14909 (replace-match ""))
14910 (setq current ""))
14911 (setq current (nreverse (org-split-string current ":")))
14912 (cond
14913 ((eq onoff 'on)
14914 (setq res t)
14915 (or (member tag current) (push tag current)))
14916 ((eq onoff 'off)
14917 (or (not (member tag current)) (setq current (delete tag current))))
14918 (t (if (member tag current)
14919 (setq current (delete tag current))
14920 (setq res t)
14921 (push tag current))))
14922 (end-of-line 1)
14923 (if current
14924 (progn
14925 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14926 (org-set-tags nil t))
14927 (delete-horizontal-space))
14928 (run-hooks 'org-after-tags-change-hook))
14929 res))
14931 (defun org-align-tags-here (to-col)
14932 ;; Assumes that this is a headline
14933 "Align tags on the current headline to TO-COL."
14934 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14935 (beginning-of-line 1)
14936 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14937 (< pos (match-beginning 2)))
14938 (progn
14939 (setq tags-l (- (match-end 2) (match-beginning 2)))
14940 (goto-char (match-beginning 1))
14941 (insert " ")
14942 (delete-region (point) (1+ (match-beginning 2)))
14943 (setq ncol (max (current-column)
14944 (1+ col)
14945 (if (> to-col 0)
14946 to-col
14947 (- (abs to-col) tags-l))))
14948 (setq p (point))
14949 (insert (make-string (- ncol (current-column)) ?\ ))
14950 (setq ncol (current-column))
14951 (when indent-tabs-mode (tabify p (point-at-eol)))
14952 (org-move-to-column (min ncol col)))
14953 (goto-char pos))))
14955 (defun org-set-tags-command (&optional arg just-align)
14956 "Call the set-tags command for the current entry."
14957 (interactive "P")
14958 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14959 (org-set-tags arg just-align)
14960 (save-excursion
14961 (unless (and (org-region-active-p)
14962 org-loop-over-headlines-in-active-region)
14963 (org-back-to-heading t))
14964 (org-set-tags arg just-align))))
14966 (defun org-set-tags-to (data)
14967 "Set the tags of the current entry to DATA, replacing the current tags.
14968 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14969 If DATA is nil or the empty string, any tags will be removed."
14970 (interactive "sTags: ")
14971 (setq data
14972 (cond
14973 ((eq data nil) "")
14974 ((equal data "") "")
14975 ((stringp data)
14976 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14977 ":"))
14978 ((listp data)
14979 (concat ":" (mapconcat 'identity data ":") ":"))))
14980 (when data
14981 (save-excursion
14982 (org-back-to-heading t)
14983 (when (looking-at org-complex-heading-regexp)
14984 (if (match-end 5)
14985 (progn
14986 (goto-char (match-beginning 5))
14987 (insert data)
14988 (delete-region (point) (point-at-eol))
14989 (org-set-tags nil 'align))
14990 (goto-char (point-at-eol))
14991 (insert " " data)
14992 (org-set-tags nil 'align)))
14993 (beginning-of-line 1)
14994 (when (looking-at ".*?\\([ \t]+\\)$")
14995 (delete-region (match-beginning 1) (match-end 1))))))
14997 (defun org-align-all-tags ()
14998 "Align the tags in all headings."
14999 (interactive)
15000 (save-excursion
15001 (or (ignore-errors (org-back-to-heading t))
15002 (outline-next-heading))
15003 (if (org-at-heading-p)
15004 (org-set-tags t)
15005 (message "No headings"))))
15007 (defvar org-indent-indentation-per-level)
15008 (defun org-set-tags (&optional arg just-align)
15009 "Set the tags for the current headline.
15010 With prefix ARG, realign all tags in headings in the current buffer.
15011 When JUST-ALIGN is non-nil, only align tags."
15012 (interactive "P")
15013 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15014 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15015 'region-start-level
15016 'region))
15017 org-loop-over-headlines-in-active-region)
15018 (org-map-entries
15019 ;; We don't use ARG and JUST-ALIGN here because these args
15020 ;; are not useful when looping over headlines.
15021 #'org-set-tags
15022 org-loop-over-headlines-in-active-region
15024 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15025 (let ((org-setting-tags t))
15026 (if arg
15027 (save-excursion
15028 (goto-char (point-min))
15029 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15030 (while (re-search-forward org-outline-regexp-bol nil t)
15031 (org-set-tags nil t)
15032 (end-of-line)))
15033 (message "All tags realigned to column %d" org-tags-column))
15034 (let* ((current (org-get-tags-string))
15035 (col (current-column))
15036 (tags
15037 (if just-align current
15038 ;; Get a new set of tags from the user.
15039 (save-excursion
15040 (let* ((seen)
15041 (table
15042 (setq
15043 org-last-tags-completion-table
15044 ;; Uniquify tags in alists, yet preserve
15045 ;; structure (i.e., keywords).
15046 (delq nil
15047 (mapcar
15048 (lambda (pair)
15049 (let ((head (car pair)))
15050 (cond ((symbolp head) pair)
15051 ((member head seen) nil)
15052 (t (push head seen)
15053 pair))))
15054 (append
15055 (or org-current-tag-alist
15056 (org-get-buffer-tags))
15057 (and
15058 org-complete-tags-always-offer-all-agenda-tags
15059 (org-global-tags-completion-table
15060 (org-agenda-files))))))))
15061 (current-tags (org-split-string current ":"))
15062 (inherited-tags
15063 (nreverse (nthcdr (length current-tags)
15064 (nreverse (org-get-tags-at))))))
15065 (replace-regexp-in-string
15066 "\\([-+&]+\\|,\\)"
15068 (if (or (eq t org-use-fast-tag-selection)
15069 (and org-use-fast-tag-selection
15070 (delq nil (mapcar #'cdr table))))
15071 (org-fast-tag-selection
15072 current-tags inherited-tags table
15073 (and org-fast-tag-selection-include-todo
15074 org-todo-key-alist))
15075 (let ((org-add-colon-after-tag-completion
15076 (< 1 (length table))))
15077 (org-trim
15078 (completing-read
15079 "Tags: "
15080 #'org-tags-completion-function
15081 nil nil current 'org-tags-history))))))))))
15083 (when org-tags-sort-function
15084 (setq tags
15085 (mapconcat
15086 #'identity
15087 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15088 org-tags-sort-function)
15089 ":")))
15091 (if (not (org-string-nw-p tags)) (setq tags "")
15092 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15093 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15095 ;; Insert new tags at the correct column
15096 (beginning-of-line)
15097 (let ((level (if (looking-at org-outline-regexp)
15098 (- (match-end 0) (point) 1)
15099 1)))
15100 (cond
15101 ((and (equal current "") (equal tags "")))
15102 ((re-search-forward
15103 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15104 (line-end-position)
15106 (if (equal tags "") (replace-match "" t t)
15107 (goto-char (match-beginning 0))
15108 (let* ((c0 (current-column))
15109 ;; Compute offset for the case of org-indent-mode
15110 ;; active.
15111 (di (if (org-bound-and-true-p org-indent-mode)
15112 (* (1- org-indent-indentation-per-level)
15113 (1- level))
15115 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15116 (tc (+ org-tags-column
15117 (if (> org-tags-column 0) (- di) di)))
15118 (c1 (max (1+ c0)
15119 (if (> tc 0) tc
15120 (- (- tc) (string-width tags)))))
15121 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15122 (replace-match rpl t t)
15123 (when indent-tabs-mode (tabify p0 (point))))))
15124 (t (error "Tags alignment failed"))))
15125 (org-move-to-column col))
15126 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15128 (defun org-change-tag-in-region (beg end tag off)
15129 "Add or remove TAG for each entry in the region.
15130 This works in the agenda, and also in an org-mode buffer."
15131 (interactive
15132 (list (region-beginning) (region-end)
15133 (let ((org-last-tags-completion-table
15134 (if (derived-mode-p 'org-mode)
15135 (org-uniquify
15136 (delq nil (append (org-get-buffer-tags)
15137 (org-global-tags-completion-table))))
15138 (org-global-tags-completion-table))))
15139 (completing-read
15140 "Tag: " 'org-tags-completion-function nil nil nil
15141 'org-tags-history))
15142 (progn
15143 (message "[s]et or [r]emove? ")
15144 (equal (read-char-exclusive) ?r))))
15145 (when (fboundp 'deactivate-mark) (deactivate-mark))
15146 (let ((agendap (equal major-mode 'org-agenda-mode))
15147 l1 l2 m buf pos newhead (cnt 0))
15148 (goto-char end)
15149 (setq l2 (1- (org-current-line)))
15150 (goto-char beg)
15151 (setq l1 (org-current-line))
15152 (cl-loop for l from l1 to l2 do
15153 (org-goto-line l)
15154 (setq m (get-text-property (point) 'org-hd-marker))
15155 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15156 (and agendap m))
15157 (setq buf (if agendap (marker-buffer m) (current-buffer))
15158 pos (if agendap m (point)))
15159 (with-current-buffer buf
15160 (save-excursion
15161 (save-restriction
15162 (goto-char pos)
15163 (setq cnt (1+ cnt))
15164 (org-toggle-tag tag (if off 'off 'on))
15165 (setq newhead (org-get-heading)))))
15166 (and agendap (org-agenda-change-all-lines newhead m))))
15167 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15169 (defun org-tags-completion-function (string _predicate &optional flag)
15170 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15171 (confirm (lambda (x) (stringp (car x)))))
15172 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15173 (setq s1 (match-string 1 string)
15174 s2 (match-string 2 string))
15175 (setq s1 "" s2 string))
15176 (cond
15177 ((eq flag nil)
15178 ;; try completion
15179 (setq rtn (try-completion s2 ctable confirm))
15180 (when (stringp rtn)
15181 (setq rtn
15182 (concat s1 s2 (substring rtn (length s2))
15183 (if (and org-add-colon-after-tag-completion
15184 (assoc rtn ctable))
15185 ":" ""))))
15186 rtn)
15187 ((eq flag t)
15188 ;; all-completions
15189 (all-completions s2 ctable confirm))
15190 ((eq flag 'lambda)
15191 ;; exact match?
15192 (assoc s2 ctable)))))
15194 (defun org-fast-tag-insert (kwd tags face &optional end)
15195 "Insert KDW, and the TAGS, the latter with face FACE.
15196 Also insert END."
15197 (insert (format "%-12s" (concat kwd ":"))
15198 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15199 (or end "")))
15201 (defun org-fast-tag-show-exit (flag)
15202 (save-excursion
15203 (org-goto-line 3)
15204 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15205 (replace-match ""))
15206 (when flag
15207 (end-of-line 1)
15208 (org-move-to-column (- (window-width) 19) t)
15209 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15211 (defun org-set-current-tags-overlay (current prefix)
15212 "Add an overlay to CURRENT tag with PREFIX."
15213 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15214 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15215 (org-overlay-display org-tags-overlay (concat prefix s))))
15217 (defvar org-last-tag-selection-key nil)
15218 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15219 "Fast tag selection with single keys.
15220 CURRENT is the current list of tags in the headline, INHERITED is the
15221 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15222 possibly with grouping information. TODO-TABLE is a similar table with
15223 TODO keywords, should these have keys assigned to them.
15224 If the keys are nil, a-z are automatically assigned.
15225 Returns the new tags string, or nil to not change the current settings."
15226 (let* ((fulltable (append table todo-table))
15227 (maxlen (apply 'max (mapcar
15228 (lambda (x)
15229 (if (stringp (car x)) (string-width (car x)) 0))
15230 fulltable)))
15231 (buf (current-buffer))
15232 (expert (eq org-fast-tag-selection-single-key 'expert))
15233 (buffer-tags nil)
15234 (fwidth (+ maxlen 3 1 3))
15235 (ncol (/ (- (window-width) 4) fwidth))
15236 (i-face 'org-done)
15237 (c-face 'org-todo)
15238 tg cnt e c char c1 c2 ntable tbl rtn
15239 ov-start ov-end ov-prefix
15240 (exit-after-next org-fast-tag-selection-single-key)
15241 (done-keywords org-done-keywords)
15242 groups ingroup intaggroup)
15243 (save-excursion
15244 (beginning-of-line 1)
15245 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15246 (setq ov-start (match-beginning 1)
15247 ov-end (match-end 1)
15248 ov-prefix "")
15249 (setq ov-start (1- (point-at-eol))
15250 ov-end (1+ ov-start))
15251 (skip-chars-forward "^\n\r")
15252 (setq ov-prefix
15253 (concat
15254 (buffer-substring (1- (point)) (point))
15255 (if (> (current-column) org-tags-column)
15257 (make-string (- org-tags-column (current-column)) ?\ ))))))
15258 (move-overlay org-tags-overlay ov-start ov-end)
15259 (save-window-excursion
15260 (if expert
15261 (set-buffer (get-buffer-create " *Org tags*"))
15262 (delete-other-windows)
15263 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15264 (org-switch-to-buffer-other-window " *Org tags*"))
15265 (erase-buffer)
15266 (setq-local org-done-keywords done-keywords)
15267 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15268 (org-fast-tag-insert "Current" current c-face "\n\n")
15269 (org-fast-tag-show-exit exit-after-next)
15270 (org-set-current-tags-overlay current ov-prefix)
15271 (setq tbl fulltable char ?a cnt 0)
15272 (while (setq e (pop tbl))
15273 (cond
15274 ((eq (car e) :startgroup)
15275 (push '() groups) (setq ingroup t)
15276 (unless (zerop cnt)
15277 (setq cnt 0)
15278 (insert "\n"))
15279 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15280 ((eq (car e) :endgroup)
15281 (setq ingroup nil cnt 0)
15282 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15283 ((eq (car e) :startgrouptag)
15284 (setq intaggroup t)
15285 (unless (zerop cnt)
15286 (setq cnt 0)
15287 (insert "\n"))
15288 (insert "[ "))
15289 ((eq (car e) :endgrouptag)
15290 (setq intaggroup nil cnt 0)
15291 (insert "]\n"))
15292 ((equal e '(:newline))
15293 (unless (zerop cnt)
15294 (setq cnt 0)
15295 (insert "\n")
15296 (setq e (car tbl))
15297 (while (equal (car tbl) '(:newline))
15298 (insert "\n")
15299 (setq tbl (cdr tbl)))))
15300 ((equal e '(:grouptags)) (insert " : "))
15302 (setq tg (copy-sequence (car e)) c2 nil)
15303 (if (cdr e)
15304 (setq c (cdr e))
15305 ;; automatically assign a character.
15306 (setq c1 (string-to-char
15307 (downcase (substring
15308 tg (if (= (string-to-char tg) ?@) 1 0)))))
15309 (if (or (rassoc c1 ntable) (rassoc c1 table))
15310 (while (or (rassoc char ntable) (rassoc char table))
15311 (setq char (1+ char)))
15312 (setq c2 c1))
15313 (setq c (or c2 char)))
15314 (when ingroup (push tg (car groups)))
15315 (setq tg (org-add-props tg nil 'face
15316 (cond
15317 ((not (assoc tg table))
15318 (org-get-todo-face tg))
15319 ((member tg current) c-face)
15320 ((member tg inherited) i-face))))
15321 (when (equal (caar tbl) :grouptags)
15322 (org-add-props tg nil 'face 'org-tag-group))
15323 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15324 (insert "[" c "] " tg (make-string
15325 (- fwidth 4 (length tg)) ?\ ))
15326 (push (cons tg c) ntable)
15327 (when (= (cl-incf cnt) ncol)
15328 (insert "\n")
15329 (when (or ingroup intaggroup) (insert " "))
15330 (setq cnt 0)))))
15331 (setq ntable (nreverse ntable))
15332 (insert "\n")
15333 (goto-char (point-min))
15334 (unless expert (org-fit-window-to-buffer))
15335 (setq rtn
15336 (catch 'exit
15337 (while t
15338 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15339 (if (not groups) "no " "")
15340 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15341 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15342 (setq org-last-tag-selection-key c)
15343 (cond
15344 ((= c ?\r) (throw 'exit t))
15345 ((= c ?!)
15346 (setq groups (not groups))
15347 (goto-char (point-min))
15348 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15349 ((= c ?\C-c)
15350 (if (not expert)
15351 (org-fast-tag-show-exit
15352 (setq exit-after-next (not exit-after-next)))
15353 (setq expert nil)
15354 (delete-other-windows)
15355 (set-window-buffer (split-window-vertically) " *Org tags*")
15356 (org-switch-to-buffer-other-window " *Org tags*")
15357 (org-fit-window-to-buffer)))
15358 ((or (= c ?\C-g)
15359 (and (= c ?q) (not (rassoc c ntable))))
15360 (delete-overlay org-tags-overlay)
15361 (setq quit-flag t))
15362 ((= c ?\ )
15363 (setq current nil)
15364 (when exit-after-next (setq exit-after-next 'now)))
15365 ((= c ?\t)
15366 (condition-case nil
15367 (setq tg (completing-read
15368 "Tag: "
15369 (or buffer-tags
15370 (with-current-buffer buf
15371 (setq buffer-tags
15372 (org-get-buffer-tags))))))
15373 (quit (setq tg "")))
15374 (when (string-match "\\S-" tg)
15375 (cl-pushnew (list tg) buffer-tags :test #'equal)
15376 (if (member tg current)
15377 (setq current (delete tg current))
15378 (push tg current)))
15379 (when exit-after-next (setq exit-after-next 'now)))
15380 ((setq e (rassoc c todo-table) tg (car e))
15381 (with-current-buffer buf
15382 (save-excursion (org-todo tg)))
15383 (when exit-after-next (setq exit-after-next 'now)))
15384 ((setq e (rassoc c ntable) tg (car e))
15385 (if (member tg current)
15386 (setq current (delete tg current))
15387 (cl-loop for g in groups do
15388 (when (member tg g)
15389 (dolist (x g) (setq current (delete x current)))))
15390 (push tg current))
15391 (when exit-after-next (setq exit-after-next 'now))))
15393 ;; Create a sorted list
15394 (setq current
15395 (sort current
15396 (lambda (a b)
15397 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15398 (when (eq exit-after-next 'now) (throw 'exit t))
15399 (goto-char (point-min))
15400 (beginning-of-line 2)
15401 (delete-region (point) (point-at-eol))
15402 (org-fast-tag-insert "Current" current c-face)
15403 (org-set-current-tags-overlay current ov-prefix)
15404 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15405 (setq tg (match-string 1))
15406 (add-text-properties
15407 (match-beginning 1) (match-end 1)
15408 (list 'face
15409 (cond
15410 ((member tg current) c-face)
15411 ((member tg inherited) i-face)
15412 (t (get-text-property (match-beginning 1) 'face))))))
15413 (goto-char (point-min)))))
15414 (delete-overlay org-tags-overlay)
15415 (if rtn
15416 (mapconcat 'identity current ":")
15417 nil))))
15419 (defun org-get-tags-string ()
15420 "Get the TAGS string in the current headline."
15421 (unless (org-at-heading-p t)
15422 (user-error "Not on a heading"))
15423 (save-excursion
15424 (beginning-of-line 1)
15425 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15426 (match-string-no-properties 1)
15427 "")))
15429 (defun org-get-tags ()
15430 "Get the list of tags specified in the current headline."
15431 (org-split-string (org-get-tags-string) ":"))
15433 (defun org-get-buffer-tags ()
15434 "Get a table of all tags used in the buffer, for completion."
15435 (org-with-wide-buffer
15436 (goto-char (point-min))
15437 (let ((tag-re (concat org-outline-regexp-bol
15438 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15439 tags)
15440 (while (re-search-forward tag-re nil t)
15441 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15442 (push tag tags)))
15443 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15445 ;;;; The mapping API
15447 (defvar org-agenda-skip-comment-trees)
15448 (defvar org-agenda-skip-function)
15449 (defun org-map-entries (func &optional match scope &rest skip)
15450 "Call FUNC at each headline selected by MATCH in SCOPE.
15452 FUNC is a function or a lisp form. The function will be called without
15453 arguments, with the cursor positioned at the beginning of the headline.
15454 The return values of all calls to the function will be collected and
15455 returned as a list.
15457 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15458 does not need to preserve point. After evaluation, the cursor will be
15459 moved to the end of the line (presumably of the headline of the
15460 processed entry) and search continues from there. Under some
15461 circumstances, this may not produce the wanted results. For example,
15462 if you have removed (e.g. archived) the current (sub)tree it could
15463 mean that the next entry will be skipped entirely. In such cases, you
15464 can specify the position from where search should continue by making
15465 FUNC set the variable `org-map-continue-from' to the desired buffer
15466 position.
15468 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15469 Only headlines that are matched by this query will be considered during
15470 the iteration. When MATCH is nil or t, all headlines will be
15471 visited by the iteration.
15473 SCOPE determines the scope of this command. It can be any of:
15475 nil The current buffer, respecting the restriction if any
15476 tree The subtree started with the entry at point
15477 region The entries within the active region, if any
15478 region-start-level
15479 The entries within the active region, but only those at
15480 the same level than the first one.
15481 file The current buffer, without restriction
15482 file-with-archives
15483 The current buffer, and any archives associated with it
15484 agenda All agenda files
15485 agenda-with-archives
15486 All agenda files with any archive files associated with them
15487 \(file1 file2 ...)
15488 If this is a list, all files in the list will be scanned
15490 The remaining args are treated as settings for the skipping facilities of
15491 the scanner. The following items can be given here:
15493 archive skip trees with the archive tag
15494 comment skip trees with the COMMENT keyword
15495 function or Emacs Lisp form:
15496 will be used as value for `org-agenda-skip-function', so
15497 whenever the function returns a position, FUNC will not be
15498 called for that entry and search will continue from the
15499 position returned
15501 If your function needs to retrieve the tags including inherited tags
15502 at the *current* entry, you can use the value of the variable
15503 `org-scanner-tags' which will be much faster than getting the value
15504 with `org-get-tags-at'. If your function gets properties with
15505 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15506 to t around the call to `org-entry-properties' to get the same speedup.
15507 Note that if your function moves around to retrieve tags and properties at
15508 a *different* entry, you cannot use these techniques."
15509 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15510 (not (org-region-active-p)))
15511 (let* ((org-agenda-archives-mode nil) ; just to make sure
15512 (org-agenda-skip-archived-trees (memq 'archive skip))
15513 (org-agenda-skip-comment-trees (memq 'comment skip))
15514 (org-agenda-skip-function
15515 (car (org-delete-all '(comment archive) skip)))
15516 (org-tags-match-list-sublevels t)
15517 (start-level (eq scope 'region-start-level))
15518 matcher res
15519 org-todo-keywords-for-agenda
15520 org-done-keywords-for-agenda
15521 org-todo-keyword-alist-for-agenda
15522 org-tag-alist-for-agenda
15523 org--matcher-tags-todo-only)
15525 (cond
15526 ((eq match t) (setq matcher t))
15527 ((eq match nil) (setq matcher t))
15528 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15530 (save-excursion
15531 (save-restriction
15532 (cond ((eq scope 'tree)
15533 (org-back-to-heading t)
15534 (org-narrow-to-subtree)
15535 (setq scope nil))
15536 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15537 (org-region-active-p))
15538 ;; If needed, set start-level to a string like "2"
15539 (when start-level
15540 (save-excursion
15541 (goto-char (region-beginning))
15542 (unless (org-at-heading-p) (outline-next-heading))
15543 (setq start-level (org-current-level))))
15544 (narrow-to-region (region-beginning)
15545 (save-excursion
15546 (goto-char (region-end))
15547 (unless (and (bolp) (org-at-heading-p))
15548 (outline-next-heading))
15549 (point)))
15550 (setq scope nil)))
15552 (if (not scope)
15553 (progn
15554 (org-agenda-prepare-buffers
15555 (and buffer-file-name (list buffer-file-name)))
15556 (setq res
15557 (org-scan-tags
15558 func matcher org--matcher-tags-todo-only start-level)))
15559 ;; Get the right scope
15560 (cond
15561 ((and scope (listp scope) (symbolp (car scope)))
15562 (setq scope (eval scope)))
15563 ((eq scope 'agenda)
15564 (setq scope (org-agenda-files t)))
15565 ((eq scope 'agenda-with-archives)
15566 (setq scope (org-agenda-files t))
15567 (setq scope (org-add-archive-files scope)))
15568 ((eq scope 'file)
15569 (setq scope (and buffer-file-name (list buffer-file-name))))
15570 ((eq scope 'file-with-archives)
15571 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15572 (org-agenda-prepare-buffers scope)
15573 (dolist (file scope)
15574 (with-current-buffer (org-find-base-buffer-visiting file)
15575 (save-excursion
15576 (save-restriction
15577 (widen)
15578 (goto-char (point-min))
15579 (setq res
15580 (append
15582 (org-scan-tags
15583 func matcher org--matcher-tags-todo-only))))))))))
15584 res)))
15586 ;;; Properties API
15588 (defconst org-special-properties
15589 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15590 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15591 "The special properties valid in Org mode.
15592 These are properties that are not defined in the property drawer,
15593 but in some other way.")
15595 (defconst org-default-properties
15596 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15597 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15598 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15599 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15600 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15601 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15602 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15603 "Some properties that are used by Org mode for various purposes.
15604 Being in this list makes sure that they are offered for completion.")
15606 (defun org--valid-property-p (property)
15607 "Non nil when string PROPERTY is a valid property name."
15608 (not
15609 (or (equal property "")
15610 (org-string-match-p "\\s-" property))))
15612 (defun org--update-property-plist (key val props)
15613 "Associate KEY to VAL in alist PROPS.
15614 Modifications are made by side-effect. Return new alist."
15615 (let* ((appending (string= (substring key -1) "+"))
15616 (key (if appending (substring key 0 -1) key))
15617 (old (assoc-string key props t)))
15618 (if (not old) (cons (cons key val) props)
15619 (setcdr old (if appending (concat (cdr old) " " val) val))
15620 props)))
15622 (defun org-get-property-block (&optional beg force)
15623 "Return the (beg . end) range of the body of the property drawer.
15624 BEG is the beginning of the current subtree, or of the part
15625 before the first headline. If it is not given, it will be found.
15626 If the drawer does not exist, create it if FORCE is non-nil, or
15627 return nil."
15628 (org-with-wide-buffer
15629 (when beg (goto-char beg))
15630 (unless (org-before-first-heading-p)
15631 (let ((beg (cond (beg)
15632 ((or (not (featurep 'org-inlinetask))
15633 (org-inlinetask-in-task-p))
15634 (org-back-to-heading t))
15635 (t (org-with-limited-levels (org-back-to-heading t))))))
15636 (forward-line)
15637 (when (looking-at-p org-planning-line-re) (forward-line))
15638 (cond ((looking-at org-property-drawer-re)
15639 (forward-line)
15640 (cons (point) (progn (goto-char (match-end 0))
15641 (line-beginning-position))))
15642 (force
15643 (goto-char beg)
15644 (org-insert-property-drawer)
15645 (let ((pos (save-excursion (search-forward ":END:")
15646 (line-beginning-position))))
15647 (cons pos pos))))))))
15649 (defun org-at-property-p ()
15650 "Non-nil when point is inside a property drawer.
15651 See `org-property-re' for match data, if applicable."
15652 (save-excursion
15653 (beginning-of-line)
15654 (and (looking-at org-property-re)
15655 (let ((property-drawer (save-match-data (org-get-property-block))))
15656 (and property-drawer
15657 (>= (point) (car property-drawer))
15658 (< (point) (cdr property-drawer)))))))
15660 (defun org-property-action ()
15661 "Do an action on properties."
15662 (interactive)
15663 (unless (org-at-property-p) (user-error "Not at a property"))
15664 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15665 (let ((c (read-char-exclusive)))
15666 (cl-case c
15667 (?s (call-interactively #'org-set-property))
15668 (?d (call-interactively #'org-delete-property))
15669 (?D (call-interactively #'org-delete-property-globally))
15670 (?c (call-interactively #'org-compute-property-at-point))
15671 (otherwise (user-error "No such property action %c" c)))))
15673 (defun org-inc-effort ()
15674 "Increment the value of the effort property in the current entry."
15675 (interactive)
15676 (org-set-effort nil t))
15678 (defvar org-clock-effort) ; Defined in org-clock.el.
15679 (defvar org-clock-current-task) ; Defined in org-clock.el.
15680 (defun org-set-effort (&optional value increment)
15681 "Set the effort property of the current entry.
15682 With numerical prefix arg, use the nth allowed value, 0 stands for the
15683 10th allowed value.
15685 When INCREMENT is non-nil, set the property to the next allowed value."
15686 (interactive "P")
15687 (when (equal value 0) (setq value 10))
15688 (let* ((completion-ignore-case t)
15689 (prop org-effort-property)
15690 (cur (org-entry-get nil prop))
15691 (allowed (org-property-get-allowed-values nil prop 'table))
15692 (existing (mapcar 'list (org-property-values prop)))
15693 (heading (nth 4 (org-heading-components)))
15695 (val (cond
15696 ((stringp value) value)
15697 ((and allowed (integerp value))
15698 (or (car (nth (1- value) allowed))
15699 (car (org-last allowed))))
15700 ((and allowed increment)
15701 (or (cl-caadr (member (list cur) allowed))
15702 (user-error "Allowed effort values are not set")))
15703 (allowed
15704 (message "Select 1-9,0, [RET%s]: %s"
15705 (if cur (concat "=" cur) "")
15706 (mapconcat 'car allowed " "))
15707 (setq rpl (read-char-exclusive))
15708 (if (equal rpl ?\r)
15710 (setq rpl (- rpl ?0))
15711 (when (equal rpl 0) (setq rpl 10))
15712 (if (and (> rpl 0) (<= rpl (length allowed)))
15713 (car (nth (1- rpl) allowed))
15714 (org-completing-read "Effort: " allowed nil))))
15716 (org-completing-read
15717 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15718 (concat "[" cur "]") "")
15719 ": ")
15720 existing nil nil "" nil cur)))))
15721 (unless (equal (org-entry-get nil prop) val)
15722 (org-entry-put nil prop val))
15723 (org-refresh-property
15724 '((effort . identity)
15725 (effort-minutes . org-duration-string-to-minutes))
15726 val)
15727 (when (string= heading org-clock-current-task)
15728 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15729 (org-clock-update-mode-line))
15730 (message "%s is now %s" prop val)))
15732 (defun org-entry-properties (&optional pom which)
15733 "Get all properties of the current entry.
15735 When POM is a buffer position, get all properties from the entry
15736 there instead.
15738 This includes the TODO keyword, the tags, time strings for
15739 deadline, scheduled, and clocking, and any additional properties
15740 defined in the entry.
15742 If WHICH is nil or `all', get all properties. If WHICH is
15743 `special' or `standard', only get that subclass. If WHICH is
15744 a string, only get that property.
15746 Return value is an alist. Keys are properties, as upcased
15747 strings."
15748 (org-with-point-at pom
15749 (when (and (derived-mode-p 'org-mode)
15750 (ignore-errors (org-back-to-heading t)))
15751 (catch 'exit
15752 (let* ((beg (point))
15753 (specific (and (stringp which) (upcase which)))
15754 (which (cond ((not specific) which)
15755 ((member specific org-special-properties) 'special)
15756 (t 'standard)))
15757 props)
15758 ;; Get the special properties, like TODO and TAGS.
15759 (when (memq which '(nil all special))
15760 (when (or (not specific) (string= specific "CLOCKSUM"))
15761 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15762 (when clocksum
15763 (push (cons "CLOCKSUM"
15764 (org-minutes-to-clocksum-string clocksum))
15765 props)))
15766 (when specific (throw 'exit props)))
15767 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15768 (let ((clocksumt (get-text-property (point)
15769 :org-clock-minutes-today)))
15770 (when clocksumt
15771 (push (cons "CLOCKSUM_T"
15772 (org-minutes-to-clocksum-string clocksumt))
15773 props)))
15774 (when specific (throw 'exit props)))
15775 (when (or (not specific) (string= specific "ITEM"))
15776 (when (looking-at org-complex-heading-regexp)
15777 (push (cons "ITEM"
15778 (let ((title (match-string-no-properties 4)))
15779 (if (org-string-nw-p title)
15780 (org-remove-tabs title)
15781 "")))
15782 props))
15783 (when specific (throw 'exit props)))
15784 (when (or (not specific) (string= specific "TODO"))
15785 (let ((case-fold-search nil))
15786 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15787 (push (cons "TODO" (match-string-no-properties 2)) props)))
15788 (when specific (throw 'exit props)))
15789 (when (or (not specific) (string= specific "PRIORITY"))
15790 (push (cons "PRIORITY"
15791 (if (looking-at org-priority-regexp)
15792 (match-string-no-properties 2)
15793 (char-to-string org-default-priority)))
15794 props)
15795 (when specific (throw 'exit props)))
15796 (when (or (not specific) (string= specific "FILE"))
15797 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15798 props)
15799 (when specific (throw 'exit props)))
15800 (when (or (not specific) (string= specific "TAGS"))
15801 (let ((value (org-string-nw-p (org-get-tags-string))))
15802 (when value (push (cons "TAGS" value) props)))
15803 (when specific (throw 'exit props)))
15804 (when (or (not specific) (string= specific "ALLTAGS"))
15805 (let ((value (org-get-tags-at)))
15806 (when value
15807 (push (cons "ALLTAGS"
15808 (format ":%s:" (mapconcat #'identity value ":")))
15809 props)))
15810 (when specific (throw 'exit props)))
15811 (when (or (not specific) (string= specific "BLOCKED"))
15812 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15813 (when specific (throw 'exit props)))
15814 (when (or (not specific)
15815 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15816 (forward-line)
15817 (when (looking-at-p org-planning-line-re)
15818 (end-of-line)
15819 (let ((bol (line-beginning-position))
15820 ;; Backward compatibility: time keywords used to
15821 ;; be configurable (before 8.3). Make sure we
15822 ;; get the correct keyword.
15823 (key-assoc `(("CLOSED" . ,org-closed-string)
15824 ("DEADLINE" . ,org-deadline-string)
15825 ("SCHEDULED" . ,org-scheduled-string))))
15826 (dolist (pair (if specific (list (assoc specific key-assoc))
15827 key-assoc))
15828 (save-excursion
15829 (when (search-backward (cdr pair) bol t)
15830 (goto-char (match-end 0))
15831 (skip-chars-forward " \t")
15832 (and (looking-at org-ts-regexp-both)
15833 (push (cons (car pair)
15834 (match-string-no-properties 0))
15835 props)))))))
15836 (when specific (throw 'exit props)))
15837 (when (or (not specific)
15838 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15839 (let ((find-ts
15840 (lambda (end ts)
15841 ;; Fix next time-stamp before END. TS is the
15842 ;; list of time-stamps found so far.
15843 (let ((ts ts)
15844 (regexp (cond
15845 ((string= specific "TIMESTAMP")
15846 org-ts-regexp)
15847 ((string= specific "TIMESTAMP_IA")
15848 org-ts-regexp-inactive)
15849 ((assoc "TIMESTAMP_IA" ts)
15850 org-ts-regexp)
15851 ((assoc "TIMESTAMP" ts)
15852 org-ts-regexp-inactive)
15853 (t org-ts-regexp-both))))
15854 (catch 'next
15855 (while (re-search-forward regexp end t)
15856 (backward-char)
15857 (let ((object (org-element-context)))
15858 ;; Accept to match timestamps in node
15859 ;; properties, too.
15860 (when (memq (org-element-type object)
15861 '(node-property timestamp))
15862 (let ((type
15863 (org-element-property :type object)))
15864 (cond
15865 ((and (memq type '(active active-range))
15866 (not (equal specific "TIMESTAMP_IA")))
15867 (unless (assoc "TIMESTAMP" ts)
15868 (push (cons "TIMESTAMP"
15869 (org-element-property
15870 :raw-value object))
15872 (when specific (throw 'exit ts))))
15873 ((and (memq type '(inactive inactive-range))
15874 (not (string= specific "TIMESTAMP")))
15875 (unless (assoc "TIMESTAMP_IA" ts)
15876 (push (cons "TIMESTAMP_IA"
15877 (org-element-property
15878 :raw-value object))
15880 (when specific (throw 'exit ts))))))
15881 ;; Both timestamp types are found,
15882 ;; move to next part.
15883 (when (= (length ts) 2) (throw 'next ts)))))
15884 ts)))))
15885 (goto-char beg)
15886 ;; First look for timestamps within headline.
15887 (let ((ts (funcall find-ts (line-end-position) nil)))
15888 (if (= (length ts) 2) (setq props (nconc ts props))
15889 (forward-line)
15890 ;; Then find timestamps in the section, skipping
15891 ;; planning line.
15892 (when (looking-at-p org-planning-line-re)
15893 (forward-line))
15894 (let ((end (save-excursion (outline-next-heading))))
15895 (setq props (nconc (funcall find-ts end ts) props))))))))
15896 ;; Get the standard properties, like :PROP:.
15897 (when (memq which '(nil all standard))
15898 ;; If we are looking after a specific property, delegate
15899 ;; to `org-entry-get', which is faster. However, make an
15900 ;; exception for "CATEGORY", since it can be also set
15901 ;; through keywords (i.e. #+CATEGORY).
15902 (if (and specific (not (equal specific "CATEGORY")))
15903 (let ((value (org-entry-get beg specific nil t)))
15904 (throw 'exit (and value (list (cons specific value)))))
15905 (let ((range (org-get-property-block beg)))
15906 (when range
15907 (let ((end (cdr range)) seen-base)
15908 (goto-char (car range))
15909 ;; Unlike to `org--update-property-plist', we
15910 ;; handle the case where base values is found
15911 ;; after its extension. We also forbid standard
15912 ;; properties to be named as special properties.
15913 (while (re-search-forward org-property-re end t)
15914 (let* ((key (upcase (match-string-no-properties 2)))
15915 (extendp (org-string-match-p "\\+\\'" key))
15916 (key-base (if extendp (substring key 0 -1) key))
15917 (value (match-string-no-properties 3)))
15918 (cond
15919 ((member-ignore-case key-base org-special-properties))
15920 (extendp
15921 (setq props
15922 (org--update-property-plist key value props)))
15923 ((member key seen-base))
15924 (t (push key seen-base)
15925 (let ((p (assoc-string key props t)))
15926 (if p (setcdr p (concat value " " (cdr p)))
15927 (push (cons key value) props))))))))))))
15928 (unless (assoc "CATEGORY" props)
15929 (push (cons "CATEGORY" (org-get-category beg)) props)
15930 (when (string= specific "CATEGORY") (throw 'exit props)))
15931 ;; Return value.
15932 props)))))
15934 (defun org-property--local-values (property literal-nil)
15935 "Return value for PROPERTY in current entry.
15936 Value is a list whose car is the base value for PROPERTY and cdr
15937 a list of accumulated values. Return nil if neither is found in
15938 the entry. Also return nil when PROPERTY is set to \"nil\",
15939 unless LITERAL-NIL is non-nil."
15940 (let ((range (org-get-property-block)))
15941 (when range
15942 (goto-char (car range))
15943 (let* ((case-fold-search t)
15944 (end (cdr range))
15945 (value
15946 ;; Base value.
15947 (save-excursion
15948 (let ((v (and (re-search-forward
15949 (org-re-property property nil t) end t)
15950 (match-string-no-properties 3))))
15951 (list (if literal-nil v (org-not-nil v)))))))
15952 ;; Find additional values.
15953 (let* ((property+ (org-re-property (concat property "+") nil t)))
15954 (while (re-search-forward property+ end t)
15955 (push (match-string-no-properties 3) value)))
15956 ;; Return final values.
15957 (and (not (equal value '(nil))) (nreverse value))))))
15959 (defun org-entry-get (pom property &optional inherit literal-nil)
15960 "Get value of PROPERTY for entry or content at point-or-marker POM.
15962 If INHERIT is non-nil and the entry does not have the property,
15963 then also check higher levels of the hierarchy. If INHERIT is
15964 the symbol `selective', use inheritance only if the setting in
15965 `org-use-property-inheritance' selects PROPERTY for inheritance.
15967 If the property is present but empty, the return value is the
15968 empty string. If the property is not present at all, nil is
15969 returned. In any other case, return the value as a string.
15970 Search is case-insensitive.
15972 If LITERAL-NIL is set, return the string value \"nil\" as
15973 a string, do not interpret it as the list atom nil. This is used
15974 for inheritance when a \"nil\" value can supersede a non-nil
15975 value higher up the hierarchy."
15976 (org-with-point-at pom
15977 (cond
15978 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15979 ;; We need a special property. Use `org-entry-properties' to
15980 ;; retrieve it, but specify the wanted property.
15981 (cdr (assoc-string property (org-entry-properties nil property))))
15982 ((and inherit
15983 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15984 (org-entry-get-with-inheritance property literal-nil))
15986 (let* ((local (org-property--local-values property literal-nil))
15987 (value (and local (mapconcat #'identity (delq nil local) " "))))
15988 (if literal-nil value (org-not-nil value)))))))
15990 (defun org-property-or-variable-value (var &optional inherit)
15991 "Check if there is a property fixing the value of VAR.
15992 If yes, return this value. If not, return the current value of the variable."
15993 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15994 (if (and prop (stringp prop) (string-match "\\S-" prop))
15995 (read prop)
15996 (symbol-value var))))
15998 (defun org-entry-delete (pom property)
15999 "Delete PROPERTY from entry at point-or-marker POM.
16000 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16001 non-nil when a property was removed."
16002 (unless (member property org-special-properties)
16003 (org-with-point-at pom
16004 (let ((range (org-get-property-block)))
16005 (when range
16006 (let* ((begin (car range))
16007 (origin (cdr range))
16008 (end (copy-marker origin))
16009 (re (org-re-property
16010 (concat (regexp-quote property) "\\+?") t t)))
16011 (goto-char begin)
16012 (while (re-search-forward re end t)
16013 (delete-region (match-beginning 0) (line-beginning-position 2)))
16014 ;; If drawer is empty, remove it altogether.
16015 (when (= begin end)
16016 (delete-region (line-beginning-position 0)
16017 (line-beginning-position 2)))
16018 ;; Return non-nil if some property was removed.
16019 (prog1 (/= end origin) (set-marker end nil))))))))
16021 ;; Multi-values properties are properties that contain multiple values
16022 ;; These values are assumed to be single words, separated by whitespace.
16023 (defun org-entry-add-to-multivalued-property (pom property value)
16024 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16025 (let* ((old (org-entry-get pom property))
16026 (values (and old (org-split-string old "[ \t]"))))
16027 (setq value (org-entry-protect-space value))
16028 (unless (member value values)
16029 (setq values (append values (list value)))
16030 (org-entry-put pom property
16031 (mapconcat 'identity values " ")))))
16033 (defun org-entry-remove-from-multivalued-property (pom property value)
16034 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16035 (let* ((old (org-entry-get pom property))
16036 (values (and old (org-split-string old "[ \t]"))))
16037 (setq value (org-entry-protect-space value))
16038 (when (member value values)
16039 (setq values (delete value values))
16040 (org-entry-put pom property
16041 (mapconcat 'identity values " ")))))
16043 (defun org-entry-member-in-multivalued-property (pom property value)
16044 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16045 (let* ((old (org-entry-get pom property))
16046 (values (and old (org-split-string old "[ \t]"))))
16047 (setq value (org-entry-protect-space value))
16048 (member value values)))
16050 (defun org-entry-get-multivalued-property (pom property)
16051 "Return a list of values in a multivalued property."
16052 (let* ((value (org-entry-get pom property))
16053 (values (and value (org-split-string value "[ \t]"))))
16054 (mapcar 'org-entry-restore-space values)))
16056 (defun org-entry-put-multivalued-property (pom property &rest values)
16057 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16058 VALUES should be a list of strings. Spaces will be protected."
16059 (org-entry-put pom property
16060 (mapconcat 'org-entry-protect-space values " "))
16061 (let* ((value (org-entry-get pom property))
16062 (values (and value (org-split-string value "[ \t]"))))
16063 (mapcar 'org-entry-restore-space values)))
16065 (defun org-entry-protect-space (s)
16066 "Protect spaces and newline in string S."
16067 (while (string-match " " s)
16068 (setq s (replace-match "%20" t t s)))
16069 (while (string-match "\n" s)
16070 (setq s (replace-match "%0A" t t s)))
16073 (defun org-entry-restore-space (s)
16074 "Restore spaces and newline in string S."
16075 (while (string-match "%20" s)
16076 (setq s (replace-match " " t t s)))
16077 (while (string-match "%0A" s)
16078 (setq s (replace-match "\n" t t s)))
16081 (defvar org-entry-property-inherited-from (make-marker)
16082 "Marker pointing to the entry from where a property was inherited.
16083 Each call to `org-entry-get-with-inheritance' will set this marker to the
16084 location of the entry where the inheritance search matched. If there was
16085 no match, the marker will point nowhere.
16086 Note that also `org-entry-get' calls this function, if the INHERIT flag
16087 is set.")
16089 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16090 "Get PROPERTY of entry or content at point, search higher levels if needed.
16091 The search will stop at the first ancestor which has the property defined.
16092 If the value found is \"nil\", return nil to show that the property
16093 should be considered as undefined (this is the meaning of nil here).
16094 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16095 (move-marker org-entry-property-inherited-from nil)
16096 (org-with-wide-buffer
16097 (let (value)
16098 (catch 'exit
16099 (while t
16100 (let ((v (org-property--local-values property literal-nil)))
16101 (when v
16102 (setq value
16103 (concat (mapconcat #'identity (delq nil v) " ")
16104 (and value " ")
16105 value)))
16106 (cond
16107 ((car v)
16108 (org-back-to-heading t)
16109 (move-marker org-entry-property-inherited-from (point))
16110 (throw 'exit nil))
16111 ((org-up-heading-safe))
16113 (let ((global
16114 (cdr (or (assoc-string property org-file-properties t)
16115 (assoc-string property org-global-properties t)
16116 (assoc-string property org-global-properties-fixed t)))))
16117 (cond ((not global))
16118 (value (setq value (concat global " " value)))
16119 (t (setq value global))))
16120 (throw 'exit nil))))))
16121 (if literal-nil value (org-not-nil value)))))
16123 (defvar org-property-changed-functions nil
16124 "Hook called when the value of a property has changed.
16125 Each hook function should accept two arguments, the name of the property
16126 and the new value.")
16128 (defun org-entry-put (pom property value)
16129 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16131 If the value is nil, it is converted to the empty string. If it
16132 is not a string, an error is raised. Also raise an error on
16133 invalid property names.
16135 PROPERTY can be any regular property (see
16136 `org-special-properties'). It can also be \"TODO\",
16137 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16139 For the last two properties, VALUE may have any of the special
16140 values \"earlier\" and \"later\". The function then increases or
16141 decreases scheduled or deadline date by one day."
16142 (cond ((null value) (setq value ""))
16143 ((not (stringp value)) (error "Properties values should be strings"))
16144 ((not (org--valid-property-p property))
16145 (user-error "Invalid property name: \"%s\"" property)))
16146 (org-with-point-at pom
16147 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16148 (org-back-to-heading t)
16149 (org-with-limited-levels (org-back-to-heading t)))
16150 (let ((beg (point)))
16151 (cond
16152 ((equal property "TODO")
16153 (cond ((not (org-string-nw-p value)) (setq value 'none))
16154 ((not (member value org-todo-keywords-1))
16155 (user-error "\"%s\" is not a valid TODO state" value)))
16156 (org-todo value)
16157 (org-set-tags nil 'align))
16158 ((equal property "PRIORITY")
16159 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16160 (org-set-tags nil 'align))
16161 ((equal property "SCHEDULED")
16162 (forward-line)
16163 (if (and (looking-at-p org-planning-line-re)
16164 (re-search-forward
16165 org-scheduled-time-regexp (line-end-position) t))
16166 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16167 ((string= value "later") (org-timestamp-change 1 'day))
16168 ((string= value "") (org-schedule '(4)))
16169 (t (org-schedule nil value)))
16170 (if (member value '("earlier" "later" ""))
16171 (call-interactively #'org-schedule)
16172 (org-schedule nil value))))
16173 ((equal property "DEADLINE")
16174 (forward-line)
16175 (if (and (looking-at-p org-planning-line-re)
16176 (re-search-forward
16177 org-deadline-time-regexp (line-end-position) t))
16178 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16179 ((string= value "later") (org-timestamp-change 1 'day))
16180 ((string= value "") (org-deadline '(4)))
16181 (t (org-deadline nil value)))
16182 (if (member value '("earlier" "later" ""))
16183 (call-interactively #'org-deadline)
16184 (org-deadline nil value))))
16185 ((member property org-special-properties)
16186 (error "The %s property cannot be set with `org-entry-put'" property))
16188 (let* ((range (org-get-property-block beg 'force))
16189 (end (cdr range))
16190 (case-fold-search t))
16191 (goto-char (car range))
16192 (if (re-search-forward (org-re-property property nil t) end t)
16193 (progn (delete-region (match-beginning 0) (match-end 0))
16194 (goto-char (match-beginning 0)))
16195 (goto-char end)
16196 (insert "\n")
16197 (backward-char))
16198 (insert ":" property ":")
16199 (when value (insert " " value))
16200 (org-indent-line)))))
16201 (run-hook-with-args 'org-property-changed-functions property value)))
16203 (defun org-buffer-property-keys
16204 (&optional specials defaults columns ignore-malformed)
16205 "Get all property keys in the current buffer.
16207 When SPECIALS is non-nil, also list the special properties that
16208 reflect things like tags and TODO state.
16210 When DEFAULTS is non-nil, also include properties that has
16211 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16212 DESCRIPTION, LOCATION, and LOGGING and others.
16214 When COLUMNS in non-nil, also include property names given in
16215 COLUMN formats in the current buffer.
16217 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16218 automatically performed, such drawers will be silently ignored."
16219 (let ((case-fold-search t)
16220 (props (append
16221 (and specials org-special-properties)
16222 (and defaults (cons org-effort-property org-default-properties))
16223 nil)))
16224 (org-with-wide-buffer
16225 (goto-char (point-min))
16226 (while (re-search-forward org-property-start-re nil t)
16227 (let ((range (org-get-property-block)))
16228 (catch 'skip
16229 (unless range
16230 (when (and (not ignore-malformed)
16231 (not (org-before-first-heading-p))
16232 (y-or-n-p (format "Malformed drawer at %d, repair?"
16233 (line-beginning-position))))
16234 (org-get-property-block nil t))
16235 (throw 'skip nil))
16236 (goto-char (car range))
16237 (let ((begin (car range))
16238 (end (cdr range)))
16239 ;; Make sure that found property block is not located
16240 ;; before current point, as it would generate an infloop.
16241 ;; It can happen, for example, in the following
16242 ;; situation:
16244 ;; * Headline
16245 ;; :PROPERTIES:
16246 ;; ...
16247 ;; :END:
16248 ;; *************** Inlinetask
16249 ;; #+BEGIN_EXAMPLE
16250 ;; :PROPERTIES:
16251 ;; #+END_EXAMPLE
16253 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16254 (while (< (point) end)
16255 (let ((p (progn (looking-at org-property-re)
16256 (match-string-no-properties 2))))
16257 ;; Only add true property name, not extension symbol.
16258 (push (if (not (org-string-match-p "\\+\\'" p)) p
16259 (substring p 0 -1))
16260 props))
16261 (forward-line))))
16262 (outline-next-heading)))
16263 (when columns
16264 (goto-char (point-min))
16265 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16266 (let ((element (org-element-at-point)))
16267 (when (memq (org-element-type element) '(keyword node-property))
16268 (let ((value (org-element-property :value element))
16269 (start 0))
16270 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16271 (setq start (match-end 0))
16272 (let ((p (match-string-no-properties 1 value)))
16273 (unless (member-ignore-case p org-special-properties)
16274 (push p props))))))))))
16275 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16277 (defun org-property-values (key)
16278 "List all non-nil values of property KEY in current buffer."
16279 (org-with-wide-buffer
16280 (goto-char (point-min))
16281 (let ((case-fold-search t)
16282 (re (org-re-property key))
16283 values)
16284 (while (re-search-forward re nil t)
16285 (push (org-entry-get (point) key) values))
16286 (delete-dups values))))
16288 (defun org-insert-property-drawer ()
16289 "Insert a property drawer into the current entry."
16290 (org-with-wide-buffer
16291 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16292 (org-back-to-heading t)
16293 (org-with-limited-levels (org-back-to-heading t)))
16294 (forward-line)
16295 (when (looking-at-p org-planning-line-re) (forward-line))
16296 (unless (looking-at-p org-property-drawer-re)
16297 ;; Make sure we start editing a line from current entry, not from
16298 ;; next one. It prevents extending text properties or overlays
16299 ;; belonging to the latter.
16300 (when (bolp) (backward-char))
16301 (let ((begin (1+ (point)))
16302 (inhibit-read-only t))
16303 (insert "\n:PROPERTIES:\n:END:")
16304 (when (eobp) (insert "\n"))
16305 (org-indent-region begin (point))))))
16307 (defun org-insert-drawer (&optional arg drawer)
16308 "Insert a drawer at point.
16310 When optional argument ARG is non-nil, insert a property drawer.
16312 Optional argument DRAWER, when non-nil, is a string representing
16313 drawer's name. Otherwise, the user is prompted for a name.
16315 If a region is active, insert the drawer around that region
16316 instead.
16318 Point is left between drawer's boundaries."
16319 (interactive "P")
16320 (let* ((drawer (if arg "PROPERTIES"
16321 (or drawer (read-from-minibuffer "Drawer: ")))))
16322 (cond
16323 ;; With C-u, fall back on `org-insert-property-drawer'
16324 (arg (org-insert-property-drawer))
16325 ;; Check validity of suggested drawer's name.
16326 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16327 (user-error "Invalid drawer name"))
16328 ;; With an active region, insert a drawer at point.
16329 ((not (org-region-active-p))
16330 (progn
16331 (unless (bolp) (insert "\n"))
16332 (insert (format ":%s:\n\n:END:\n" drawer))
16333 (forward-line -2)))
16334 ;; Otherwise, insert the drawer at point
16336 (let ((rbeg (region-beginning))
16337 (rend (copy-marker (region-end))))
16338 (unwind-protect
16339 (progn
16340 (goto-char rbeg)
16341 (beginning-of-line)
16342 (when (save-excursion
16343 (re-search-forward org-outline-regexp-bol rend t))
16344 (user-error "Drawers cannot contain headlines"))
16345 ;; Position point at the beginning of the first
16346 ;; non-blank line in region. Insert drawer's opening
16347 ;; there, then indent it.
16348 (org-skip-whitespace)
16349 (beginning-of-line)
16350 (insert ":" drawer ":\n")
16351 (forward-line -1)
16352 (indent-for-tab-command)
16353 ;; Move point to the beginning of the first blank line
16354 ;; after the last non-blank line in region. Insert
16355 ;; drawer's closing, then indent it.
16356 (goto-char rend)
16357 (skip-chars-backward " \r\t\n")
16358 (insert "\n:END:")
16359 (deactivate-mark t)
16360 (indent-for-tab-command)
16361 (unless (eolp) (insert "\n")))
16362 ;; Clear marker, whatever the outcome of insertion is.
16363 (set-marker rend nil)))))))
16365 (defvar org-property-set-functions-alist nil
16366 "Property set function alist.
16367 Each entry should have the following format:
16369 (PROPERTY . READ-FUNCTION)
16371 The read function will be called with the same argument as
16372 `org-completing-read'.")
16374 (defun org-set-property-function (property)
16375 "Get the function that should be used to set PROPERTY.
16376 This is computed according to `org-property-set-functions-alist'."
16377 (or (cdr (assoc property org-property-set-functions-alist))
16378 'org-completing-read))
16380 (defun org-read-property-value (property)
16381 "Read PROPERTY value from user."
16382 (let* ((completion-ignore-case t)
16383 (allowed (org-property-get-allowed-values nil property 'table))
16384 (cur (org-entry-get nil property))
16385 (prompt (concat property " value"
16386 (if (and cur (string-match "\\S-" cur))
16387 (concat " [" cur "]") "") ": "))
16388 (set-function (org-set-property-function property))
16389 (val (if allowed
16390 (funcall set-function prompt allowed nil
16391 (not (get-text-property 0 'org-unrestricted
16392 (caar allowed))))
16393 (funcall set-function prompt
16394 (mapcar 'list (org-property-values property))
16395 nil nil "" nil cur))))
16396 (org-trim val)))
16398 (defvar org-last-set-property nil)
16399 (defvar org-last-set-property-value nil)
16400 (defun org-read-property-name ()
16401 "Read a property name."
16402 (let ((completion-ignore-case t)
16403 (default-prop (or (and (org-at-property-p)
16404 (match-string-no-properties 2))
16405 org-last-set-property)))
16406 (org-completing-read
16407 (concat "Property"
16408 (if default-prop (concat " [" default-prop "]") "")
16409 ": ")
16410 (mapcar #'list (org-buffer-property-keys nil t t))
16411 nil nil nil nil default-prop)))
16413 (defun org-set-property-and-value (use-last)
16414 "Allow to set [PROPERTY]: [value] direction from prompt.
16415 When use-default, don't even ask, just use the last
16416 \"[PROPERTY]: [value]\" string from the history."
16417 (interactive "P")
16418 (let* ((completion-ignore-case t)
16419 (pv (or (and use-last org-last-set-property-value)
16420 (org-completing-read
16421 "Enter a \"[Property]: [value]\" pair: "
16422 nil nil nil nil nil
16423 org-last-set-property-value)))
16424 prop val)
16425 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16426 (setq prop (match-string 1 pv)
16427 val (match-string 2 pv))
16428 (org-set-property prop val))))
16430 (defun org-set-property (property value)
16431 "In the current entry, set PROPERTY to VALUE.
16433 When called interactively, this will prompt for a property name, offering
16434 completion on existing and default properties. And then it will prompt
16435 for a value, offering completion either on allowed values (via an inherited
16436 xxx_ALL property) or on existing values in other instances of this property
16437 in the current file.
16439 Throw an error when trying to set a property with an invalid name."
16440 (interactive (list nil nil))
16441 (let ((property (or property (org-read-property-name))))
16442 ;; `org-entry-put' also makes the following check, but this one
16443 ;; avoids polluting `org-last-set-property' and
16444 ;; `org-last-set-property-value' needlessly.
16445 (unless (org--valid-property-p property)
16446 (user-error "Invalid property name: \"%s\"" property))
16447 (let ((value (or value (org-read-property-value property)))
16448 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16449 (setq org-last-set-property property)
16450 (setq org-last-set-property-value (concat property ": " value))
16451 ;; Possibly postprocess the inserted value:
16452 (when fn (setq value (funcall fn value)))
16453 (unless (equal (org-entry-get nil property) value)
16454 (org-entry-put nil property value)))))
16456 (defun org-find-property (property &optional value)
16457 "Find first entry in buffer that sets PROPERTY.
16459 When optional argument VALUE is non-nil, only consider an entry
16460 if it contains PROPERTY set to this value. If PROPERTY should be
16461 explicitly set to nil, use string \"nil\" for VALUE.
16463 Return position where the entry begins, or nil if there is no
16464 such entry. If narrowing is in effect, only search the visible
16465 part of the buffer."
16466 (save-excursion
16467 (goto-char (point-min))
16468 (let ((case-fold-search t)
16469 (re (org-re-property property nil (not value) value)))
16470 (catch 'exit
16471 (while (re-search-forward re nil t)
16472 (when (if value (org-at-property-p)
16473 (org-entry-get (point) property nil t))
16474 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16476 (defun org-delete-property (property)
16477 "In the current entry, delete PROPERTY."
16478 (interactive
16479 (let* ((completion-ignore-case t)
16480 (cat (org-entry-get (point) "CATEGORY"))
16481 (props0 (org-entry-properties nil 'standard))
16482 (props (if cat props0
16483 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16484 (prop (if (< 1 (length props))
16485 (completing-read "Property: " props nil t)
16486 (caar props))))
16487 (list prop)))
16488 (if (not property)
16489 (message "No property to delete in this entry")
16490 (org-entry-delete nil property)
16491 (message "Property \"%s\" deleted" property)))
16493 (defun org-delete-property-globally (property)
16494 "Remove PROPERTY globally, from all entries.
16495 This function ignores narrowing, if any."
16496 (interactive
16497 (let* ((completion-ignore-case t)
16498 (prop (completing-read
16499 "Globally remove property: "
16500 (mapcar #'list (org-buffer-property-keys)))))
16501 (list prop)))
16502 (org-with-wide-buffer
16503 (goto-char (point-min))
16504 (let ((count 0)
16505 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16506 (while (re-search-forward re nil t)
16507 (when (org-entry-delete (point) property) (cl-incf count)))
16508 (message "Property \"%s\" removed from %d entries" property count))))
16510 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16512 (defun org-compute-property-at-point ()
16513 "Compute the property at point.
16514 This looks for an enclosing column format, extracts the operator and
16515 then applies it to the property in the column format's scope."
16516 (interactive)
16517 (unless (org-at-property-p)
16518 (user-error "Not at a property"))
16519 (let ((prop (match-string-no-properties 2)))
16520 (org-columns-get-format-and-top-level)
16521 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16522 (user-error "No operator defined for property %s" prop))
16523 (org-columns-compute prop)))
16525 (defvar org-property-allowed-value-functions nil
16526 "Hook for functions supplying allowed values for a specific property.
16527 The functions must take a single argument, the name of the property, and
16528 return a flat list of allowed values. If \":ETC\" is one of
16529 the values, this means that these values are intended as defaults for
16530 completion, but that other values should be allowed too.
16531 The functions must return nil if they are not responsible for this
16532 property.")
16534 (defun org-property-get-allowed-values (pom property &optional table)
16535 "Get allowed values for the property PROPERTY.
16536 When TABLE is non-nil, return an alist that can directly be used for
16537 completion."
16538 (let (vals)
16539 (cond
16540 ((equal property "TODO")
16541 (setq vals (org-with-point-at pom
16542 (append org-todo-keywords-1 '("")))))
16543 ((equal property "PRIORITY")
16544 (let ((n org-lowest-priority))
16545 (while (>= n org-highest-priority)
16546 (push (char-to-string n) vals)
16547 (setq n (1- n)))))
16548 ((equal property "CATEGORY"))
16549 ((member property org-special-properties))
16550 ((setq vals (run-hook-with-args-until-success
16551 'org-property-allowed-value-functions property)))
16553 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16554 (when (and vals (string-match "\\S-" vals))
16555 (setq vals (car (read-from-string (concat "(" vals ")"))))
16556 (setq vals (mapcar (lambda (x)
16557 (cond ((stringp x) x)
16558 ((numberp x) (number-to-string x))
16559 ((symbolp x) (symbol-name x))
16560 (t "???")))
16561 vals)))))
16562 (when (member ":ETC" vals)
16563 (setq vals (remove ":ETC" vals))
16564 (org-add-props (car vals) '(org-unrestricted t)))
16565 (if table (mapcar 'list vals) vals)))
16567 (defun org-property-previous-allowed-value (&optional _previous)
16568 "Switch to the next allowed value for this property."
16569 (interactive)
16570 (org-property-next-allowed-value t))
16572 (defun org-property-next-allowed-value (&optional previous)
16573 "Switch to the next allowed value for this property."
16574 (interactive)
16575 (unless (org-at-property-p)
16576 (user-error "Not at a property"))
16577 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16578 (key (match-string 2))
16579 (value (match-string 3))
16580 (allowed (or (org-property-get-allowed-values (point) key)
16581 (and (member value '("[ ]" "[-]" "[X]"))
16582 '("[ ]" "[X]"))))
16583 (heading (save-match-data (nth 4 (org-heading-components))))
16584 nval)
16585 (unless allowed
16586 (user-error "Allowed values for this property have not been defined"))
16587 (when previous (setq allowed (reverse allowed)))
16588 (when (member value allowed)
16589 (setq nval (car (cdr (member value allowed)))))
16590 (setq nval (or nval (car allowed)))
16591 (when (equal nval value)
16592 (user-error "Only one allowed value for this property"))
16593 (org-at-property-p)
16594 (replace-match (concat " :" key ": " nval) t t)
16595 (org-indent-line)
16596 (beginning-of-line 1)
16597 (skip-chars-forward " \t")
16598 (when (equal prop org-effort-property)
16599 (org-refresh-property
16600 '((effort . identity)
16601 (effort-minutes . org-duration-string-to-minutes))
16602 nval)
16603 (when (string= org-clock-current-task heading)
16604 (setq org-clock-effort nval)
16605 (org-clock-update-mode-line)))
16606 (run-hook-with-args 'org-property-changed-functions key nval)))
16608 (defun org-find-olp (path &optional this-buffer)
16609 "Return a marker pointing to the entry at outline path OLP.
16610 If anything goes wrong, throw an error.
16611 You can wrap this call to catch the error like this:
16613 \(condition-case msg
16614 \(org-mobile-locate-entry (match-string 4))
16615 \(error (nth 1 msg)))
16617 The return value will then be either a string with the error message,
16618 or a marker if everything is OK.
16620 If THIS-BUFFER is set, the outline path does not contain a file,
16621 only headings."
16622 (let* ((file (if this-buffer buffer-file-name (pop path)))
16623 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16624 (level 1)
16625 (lmin 1)
16626 (lmax 1)
16627 end found flevel)
16628 (unless buffer (error "File not found :%s" file))
16629 (with-current-buffer buffer
16630 (org-with-wide-buffer
16631 (goto-char (point-min))
16632 (dolist (heading path)
16633 (let ((re (format org-complex-heading-regexp-format
16634 (regexp-quote heading)))
16635 (cnt 0))
16636 (while (re-search-forward re end t)
16637 (setq level (- (match-end 1) (match-beginning 1)))
16638 (when (and (>= level lmin) (<= level lmax))
16639 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16640 (when (= cnt 0)
16641 (error "Heading not found on level %d: %s" lmax heading))
16642 (when (> cnt 1)
16643 (error "Heading not unique on level %d: %s" lmax heading))
16644 (goto-char found)
16645 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16646 (setq end (save-excursion (org-end-of-subtree t t)))))
16647 (when (org-at-heading-p)
16648 (point-marker))))))
16650 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16651 "Find node HEADING in BUFFER.
16652 Return a marker to the heading if it was found, or nil if not.
16653 If POS-ONLY is set, return just the position instead of a marker.
16655 The heading text must match exact, but it may have a TODO keyword,
16656 a priority cookie and tags in the standard locations."
16657 (with-current-buffer (or buffer (current-buffer))
16658 (save-excursion
16659 (save-restriction
16660 (widen)
16661 (goto-char (point-min))
16662 (let (case-fold-search)
16663 (when (re-search-forward
16664 (format org-complex-heading-regexp-format
16665 (regexp-quote heading)) nil t)
16666 (if pos-only
16667 (match-beginning 0)
16668 (move-marker (make-marker) (match-beginning 0)))))))))
16670 (defun org-find-exact-heading-in-directory (heading &optional dir)
16671 "Find Org node headline HEADING in all .org files in directory DIR.
16672 When the target headline is found, return a marker to this location."
16673 (let ((files (directory-files (or dir default-directory)
16674 t "\\`[^.#].*\\.org\\'"))
16675 visiting m buffer)
16676 (catch 'found
16677 (dolist (file files)
16678 (message "trying %s" file)
16679 (setq visiting (org-find-base-buffer-visiting file))
16680 (setq buffer (or visiting (find-file-noselect file)))
16681 (setq m (org-find-exact-headline-in-buffer
16682 heading buffer))
16683 (when (and (not m) (not visiting)) (kill-buffer buffer))
16684 (and m (throw 'found m))))))
16686 (defun org-find-entry-with-id (ident)
16687 "Locate the entry that contains the ID property with exact value IDENT.
16688 IDENT can be a string, a symbol or a number, this function will search for
16689 the string representation of it.
16690 Return the position where this entry starts, or nil if there is no such entry."
16691 (interactive "sID: ")
16692 (let ((id (cond
16693 ((stringp ident) ident)
16694 ((symbolp ident) (symbol-name ident))
16695 ((numberp ident) (number-to-string ident))
16696 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16697 (org-with-wide-buffer (org-find-property "ID" id))))
16699 ;;;; Timestamps
16701 (defvar org-last-changed-timestamp nil)
16702 (defvar org-last-inserted-timestamp nil
16703 "The last time stamp inserted with `org-insert-time-stamp'.")
16704 (defvar org-ts-what) ; dynamically scoped parameter
16706 (defun org-time-stamp (arg &optional inactive)
16707 "Prompt for a date/time and insert a time stamp.
16709 If the user specifies a time like HH:MM or if this command is
16710 called with at least one prefix argument, the time stamp contains
16711 the date and the time. Otherwise, only the date is included.
16713 All parts of a date not specified by the user are filled in from
16714 the timestamp at point, if any, or the current date/time
16715 otherwise.
16717 If there is already a timestamp at the cursor, it is replaced.
16719 With two universal prefix arguments, insert an active timestamp
16720 with the current time without prompting the user.
16722 When called from lisp, the timestamp is inactive if INACTIVE is
16723 non-nil."
16724 (interactive "P")
16725 (let* ((ts (cond
16726 ((org-at-date-range-p t)
16727 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16728 ((org-at-timestamp-p t) (match-string 0))))
16729 ;; Default time is either the timestamp at point or today.
16730 ;; When entering a range, only the range start is considered.
16731 (default-time (if (not ts) (current-time)
16732 (apply #'encode-time (org-parse-time-string ts))))
16733 (default-input (and ts (org-get-compact-tod ts)))
16734 (repeater (and ts
16735 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16736 (match-string 0 ts)))
16737 org-time-was-given
16738 org-end-time-was-given
16739 (time
16740 (and (if (equal arg '(16)) (current-time)
16741 ;; Preserve `this-command' and `last-command'.
16742 (let ((this-command this-command)
16743 (last-command last-command))
16744 (org-read-date
16745 arg 'totime nil nil default-time default-input
16746 inactive))))))
16747 (cond
16748 ((and ts
16749 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16750 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16751 (insert "--")
16752 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16754 ;; Make sure we're on a timestamp. When in the middle of a date
16755 ;; range, move arbitrarily to range end.
16756 (unless (org-at-timestamp-p t)
16757 (skip-chars-forward "-")
16758 (org-at-timestamp-p t))
16759 (replace-match "")
16760 (setq org-last-changed-timestamp
16761 (org-insert-time-stamp
16762 time (or org-time-was-given arg)
16763 inactive nil nil (list org-end-time-was-given)))
16764 (when repeater
16765 (backward-char)
16766 (insert " " repeater)
16767 (setq org-last-changed-timestamp
16768 (concat (substring org-last-inserted-timestamp 0 -1)
16769 " " repeater ">")))
16770 (message "Timestamp updated"))
16771 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16772 (t (org-insert-time-stamp
16773 time (or org-time-was-given arg) inactive nil nil
16774 (list org-end-time-was-given))))))
16776 ;; FIXME: can we use this for something else, like computing time differences?
16777 (defun org-get-compact-tod (s)
16778 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16779 (let* ((t1 (match-string 1 s))
16780 (h1 (string-to-number (match-string 2 s)))
16781 (m1 (string-to-number (match-string 3 s)))
16782 (t2 (and (match-end 4) (match-string 5 s)))
16783 (h2 (and t2 (string-to-number (match-string 6 s))))
16784 (m2 (and t2 (string-to-number (match-string 7 s))))
16785 dh dm)
16786 (if (not t2)
16788 (setq dh (- h2 h1) dm (- m2 m1))
16789 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16790 (concat t1 "+" (number-to-string dh)
16791 (and (/= 0 dm) (format ":%02d" dm)))))))
16793 (defun org-time-stamp-inactive (&optional arg)
16794 "Insert an inactive time stamp.
16795 An inactive time stamp is enclosed in square brackets instead of angle
16796 brackets. It is inactive in the sense that it does not trigger agenda entries,
16797 does not link to the calendar and cannot be changed with the S-cursor keys.
16798 So these are more for recording a certain time/date."
16799 (interactive "P")
16800 (org-time-stamp arg 'inactive))
16802 (defvar org-date-ovl (make-overlay 1 1))
16803 (overlay-put org-date-ovl 'face 'org-date-selected)
16804 (delete-overlay org-date-ovl)
16806 (defvar org-ans1) ; dynamically scoped parameter
16807 (defvar org-ans2) ; dynamically scoped parameter
16809 (defvar org-plain-time-of-day-regexp) ; defined below
16811 (defvar org-overriding-default-time nil) ; dynamically scoped
16812 (defvar org-read-date-overlay nil)
16813 (defvar org-dcst nil) ; dynamically scoped
16814 (defvar org-read-date-history nil)
16815 (defvar org-read-date-final-answer nil)
16816 (defvar org-read-date-analyze-futurep nil)
16817 (defvar org-read-date-analyze-forced-year nil)
16818 (defvar org-read-date-inactive)
16820 (defvar org-read-date-minibuffer-local-map
16821 (let* ((map (make-sparse-keymap)))
16822 (set-keymap-parent map minibuffer-local-map)
16823 (org-defkey map (kbd ".")
16824 (lambda () (interactive)
16825 ;; Are we at the beginning of the prompt?
16826 (if (looking-back "^[^:]+: "
16827 (let ((inhibit-field-text-motion t))
16828 (line-beginning-position)))
16829 (org-eval-in-calendar '(calendar-goto-today))
16830 (insert "."))))
16831 (org-defkey map (kbd "C-.")
16832 (lambda () (interactive)
16833 (org-eval-in-calendar '(calendar-goto-today))))
16834 (org-defkey map [(meta shift left)]
16835 (lambda () (interactive)
16836 (org-eval-in-calendar '(calendar-backward-month 1))))
16837 (org-defkey map [(meta shift right)]
16838 (lambda () (interactive)
16839 (org-eval-in-calendar '(calendar-forward-month 1))))
16840 (org-defkey map [(meta shift up)]
16841 (lambda () (interactive)
16842 (org-eval-in-calendar '(calendar-backward-year 1))))
16843 (org-defkey map [(meta shift down)]
16844 (lambda () (interactive)
16845 (org-eval-in-calendar '(calendar-forward-year 1))))
16846 (org-defkey map [?\e (shift left)]
16847 (lambda () (interactive)
16848 (org-eval-in-calendar '(calendar-backward-month 1))))
16849 (org-defkey map [?\e (shift right)]
16850 (lambda () (interactive)
16851 (org-eval-in-calendar '(calendar-forward-month 1))))
16852 (org-defkey map [?\e (shift up)]
16853 (lambda () (interactive)
16854 (org-eval-in-calendar '(calendar-backward-year 1))))
16855 (org-defkey map [?\e (shift down)]
16856 (lambda () (interactive)
16857 (org-eval-in-calendar '(calendar-forward-year 1))))
16858 (org-defkey map [(shift up)]
16859 (lambda () (interactive)
16860 (org-eval-in-calendar '(calendar-backward-week 1))))
16861 (org-defkey map [(shift down)]
16862 (lambda () (interactive)
16863 (org-eval-in-calendar '(calendar-forward-week 1))))
16864 (org-defkey map [(shift left)]
16865 (lambda () (interactive)
16866 (org-eval-in-calendar '(calendar-backward-day 1))))
16867 (org-defkey map [(shift right)]
16868 (lambda () (interactive)
16869 (org-eval-in-calendar '(calendar-forward-day 1))))
16870 (org-defkey map "!"
16871 (lambda () (interactive)
16872 (org-eval-in-calendar '(diary-view-entries))
16873 (message "")))
16874 (org-defkey map ">"
16875 (lambda () (interactive)
16876 (org-eval-in-calendar '(calendar-scroll-left 1))))
16877 (org-defkey map "<"
16878 (lambda () (interactive)
16879 (org-eval-in-calendar '(calendar-scroll-right 1))))
16880 (org-defkey map "\C-v"
16881 (lambda () (interactive)
16882 (org-eval-in-calendar
16883 '(calendar-scroll-left-three-months 1))))
16884 (org-defkey map "\M-v"
16885 (lambda () (interactive)
16886 (org-eval-in-calendar
16887 '(calendar-scroll-right-three-months 1))))
16888 map)
16889 "Keymap for minibuffer commands when using `org-read-date'.")
16891 (defvar org-def)
16892 (defvar org-defdecode)
16893 (defvar org-with-time)
16895 (defvar calendar-setup) ; Dynamically scoped.
16896 (defun org-read-date (&optional with-time to-time from-string prompt
16897 default-time default-input inactive)
16898 "Read a date, possibly a time, and make things smooth for the user.
16899 The prompt will suggest to enter an ISO date, but you can also enter anything
16900 which will at least partially be understood by `parse-time-string'.
16901 Unrecognized parts of the date will default to the current day, month, year,
16902 hour and minute. If this command is called to replace a timestamp at point,
16903 or to enter the second timestamp of a range, the default time is taken
16904 from the existing stamp. Furthermore, the command prefers the future,
16905 so if you are giving a date where the year is not given, and the day-month
16906 combination is already past in the current year, it will assume you
16907 mean next year. For details, see the manual. A few examples:
16909 3-2-5 --> 2003-02-05
16910 feb 15 --> currentyear-02-15
16911 2/15 --> currentyear-02-15
16912 sep 12 9 --> 2009-09-12
16913 12:45 --> today 12:45
16914 22 sept 0:34 --> currentyear-09-22 0:34
16915 12 --> currentyear-currentmonth-12
16916 Fri --> nearest Friday after today
16917 -Tue --> last Tuesday
16918 etc.
16920 Furthermore you can specify a relative date by giving, as the *first* thing
16921 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16922 change in days weeks, months, years.
16923 With a single plus or minus, the date is relative to today. With a double
16924 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16925 +4d --> four days from today
16926 +4 --> same as above
16927 +2w --> two weeks from today
16928 ++5 --> five days from default date
16930 The function understands only English month and weekday abbreviations.
16932 While prompting, a calendar is popped up - you can also select the
16933 date with the mouse (button 1). The calendar shows a period of three
16934 months. To scroll it to other months, use the keys `>' and `<'.
16935 If you don't like the calendar, turn it off with
16936 (setq org-read-date-popup-calendar nil)
16938 With optional argument TO-TIME, the date will immediately be converted
16939 to an internal time.
16940 With an optional argument WITH-TIME, the prompt will suggest to
16941 also insert a time. Note that when WITH-TIME is not set, you can
16942 still enter a time, and this function will inform the calling routine
16943 about this change. The calling routine may then choose to change the
16944 format used to insert the time stamp into the buffer to include the time.
16945 With optional argument FROM-STRING, read from this string instead from
16946 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16947 the time/date that is used for everything that is not specified by the
16948 user."
16949 (require 'parse-time)
16950 (let* ((org-with-time with-time)
16951 (org-time-stamp-rounding-minutes
16952 (if (equal org-with-time '(16))
16953 '(0 0)
16954 org-time-stamp-rounding-minutes))
16955 (org-dcst org-display-custom-times)
16956 (ct (org-current-time))
16957 (org-def (or org-overriding-default-time default-time ct))
16958 (org-defdecode (decode-time org-def))
16959 (cur-frame (selected-frame))
16960 (mouse-autoselect-window nil) ; Don't let the mouse jump
16961 (calendar-setup
16962 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16963 (calendar-move-hook nil)
16964 (calendar-view-diary-initially-flag nil)
16965 (calendar-view-holidays-initially-flag nil)
16966 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16967 ;; Rationalize `org-def' and `org-defdecode', if required.
16968 (when (< (nth 2 org-defdecode) org-extend-today-until)
16969 (setf (nth 2 org-defdecode) -1)
16970 (setf (nth 1 org-defdecode) 59)
16971 (setq org-def (apply #'encode-time org-defdecode))
16972 (setq org-defdecode (decode-time org-def)))
16973 (let* ((timestr (format-time-string
16974 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16975 org-def))
16976 (prompt (concat (if prompt (concat prompt " ") "")
16977 (format "Date+time [%s]: " timestr))))
16978 (cond
16979 (from-string (setq ans from-string))
16980 (org-read-date-popup-calendar
16981 (save-excursion
16982 (save-window-excursion
16983 (calendar)
16984 (when (eq calendar-setup 'calendar-only)
16985 (setq cal-frame
16986 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16987 (select-frame cal-frame))
16988 (org-eval-in-calendar '(setq cursor-type nil) t)
16989 (unwind-protect
16990 (progn
16991 (calendar-forward-day (- (time-to-days org-def)
16992 (calendar-absolute-from-gregorian
16993 (calendar-current-date))))
16994 (org-eval-in-calendar nil t)
16995 (let* ((old-map (current-local-map))
16996 (map (copy-keymap calendar-mode-map))
16997 (minibuffer-local-map
16998 (copy-keymap org-read-date-minibuffer-local-map)))
16999 (org-defkey map (kbd "RET") 'org-calendar-select)
17000 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17001 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17002 (unwind-protect
17003 (progn
17004 (use-local-map map)
17005 (setq org-read-date-inactive inactive)
17006 (add-hook 'post-command-hook 'org-read-date-display)
17007 (setq org-ans0
17008 (read-string prompt
17009 default-input
17010 'org-read-date-history
17011 nil))
17012 ;; org-ans0: from prompt
17013 ;; org-ans1: from mouse click
17014 ;; org-ans2: from calendar motion
17015 (setq ans
17016 (concat org-ans0 " " (or org-ans1 org-ans2))))
17017 (remove-hook 'post-command-hook 'org-read-date-display)
17018 (use-local-map old-map)
17019 (when org-read-date-overlay
17020 (delete-overlay org-read-date-overlay)
17021 (setq org-read-date-overlay nil)))))
17022 (bury-buffer "*Calendar*")
17023 (when cal-frame
17024 (delete-frame cal-frame)
17025 (select-frame-set-input-focus cur-frame))))))
17027 (t ; Naked prompt only
17028 (unwind-protect
17029 (setq ans (read-string prompt default-input
17030 'org-read-date-history timestr))
17031 (when org-read-date-overlay
17032 (delete-overlay org-read-date-overlay)
17033 (setq org-read-date-overlay nil))))))
17035 (setq final (org-read-date-analyze ans org-def org-defdecode))
17037 (when org-read-date-analyze-forced-year
17038 (message "Year was forced into %s"
17039 (if org-read-date-force-compatible-dates
17040 "compatible range (1970-2037)"
17041 "range representable on this machine"))
17042 (ding))
17044 ;; One round trip to get rid of 34th of August and stuff like that....
17045 (setq final (decode-time (apply 'encode-time final)))
17047 (setq org-read-date-final-answer ans)
17049 (if to-time
17050 (apply 'encode-time final)
17051 (if (and (boundp 'org-time-was-given) org-time-was-given)
17052 (format "%04d-%02d-%02d %02d:%02d"
17053 (nth 5 final) (nth 4 final) (nth 3 final)
17054 (nth 2 final) (nth 1 final))
17055 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17057 (defun org-read-date-display ()
17058 "Display the current date prompt interpretation in the minibuffer."
17059 (when org-read-date-display-live
17060 (when org-read-date-overlay
17061 (delete-overlay org-read-date-overlay))
17062 (when (minibufferp (current-buffer))
17063 (save-excursion
17064 (end-of-line 1)
17065 (while (not (equal (buffer-substring
17066 (max (point-min) (- (point) 4)) (point))
17067 " "))
17068 (insert " ")))
17069 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17070 " " (or org-ans1 org-ans2)))
17071 (org-end-time-was-given nil)
17072 (f (org-read-date-analyze ans org-def org-defdecode))
17073 (fmts (if org-dcst
17074 org-time-stamp-custom-formats
17075 org-time-stamp-formats))
17076 (fmt (if (or org-with-time
17077 (and (boundp 'org-time-was-given) org-time-was-given))
17078 (cdr fmts)
17079 (car fmts)))
17080 (txt (format-time-string fmt (apply 'encode-time f)))
17081 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17082 (txt (concat "=> " txt)))
17083 (when (and org-end-time-was-given
17084 (string-match org-plain-time-of-day-regexp txt))
17085 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17086 org-end-time-was-given
17087 (substring txt (match-end 0)))))
17088 (when org-read-date-analyze-futurep
17089 (setq txt (concat txt " (=>F)")))
17090 (setq org-read-date-overlay
17091 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17092 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17094 (defun org-read-date-analyze (ans def defdecode)
17095 "Analyze the combined answer of the date prompt."
17096 ;; FIXME: cleanup and comment
17097 ;; Pass `current-time' result to `decode-time' (instead of calling
17098 ;; without arguments) so that only `current-time' has to be
17099 ;; overriden in tests.
17100 (let ((org-def def)
17101 (org-defdecode defdecode)
17102 (nowdecode (decode-time (current-time)))
17103 delta deltan deltaw deltadef year month day
17104 hour minute second wday pm h2 m2 tl wday1
17105 iso-year iso-weekday iso-week iso-date futurep kill-year)
17106 (setq org-read-date-analyze-futurep nil
17107 org-read-date-analyze-forced-year nil)
17108 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17109 (setq ans "+0"))
17111 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17112 (setq ans (replace-match "" t t ans)
17113 deltan (car delta)
17114 deltaw (nth 1 delta)
17115 deltadef (nth 2 delta)))
17117 ;; Check if there is an iso week date in there. If yes, store the
17118 ;; info and postpone interpreting it until the rest of the parsing
17119 ;; is done.
17120 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17121 (setq iso-year (when (match-end 1)
17122 (org-small-year-to-year
17123 (string-to-number (match-string 1 ans))))
17124 iso-weekday (when (match-end 3)
17125 (string-to-number (match-string 3 ans)))
17126 iso-week (string-to-number (match-string 2 ans)))
17127 (setq ans (replace-match "" t t ans)))
17129 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17130 (when (string-match
17131 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17132 (setq year (if (match-end 2)
17133 (string-to-number (match-string 2 ans))
17134 (progn (setq kill-year t)
17135 (string-to-number (format-time-string "%Y"))))
17136 month (string-to-number (match-string 3 ans))
17137 day (string-to-number (match-string 4 ans)))
17138 (setq year (org-small-year-to-year year))
17139 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17140 t nil ans)))
17142 ;; Help matching dotted european dates
17143 (when (string-match
17144 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17145 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17146 (setq kill-year t)
17147 (string-to-number (format-time-string "%Y")))
17148 day (string-to-number (match-string 1 ans))
17149 month (string-to-number (match-string 2 ans))
17150 ans (replace-match (format "%04d-%02d-%02d" year month day)
17151 t nil ans)))
17153 ;; Help matching american dates, like 5/30 or 5/30/7
17154 (when (string-match
17155 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17156 (setq year (if (match-end 4)
17157 (string-to-number (match-string 4 ans))
17158 (progn (setq kill-year t)
17159 (string-to-number (format-time-string "%Y"))))
17160 month (string-to-number (match-string 1 ans))
17161 day (string-to-number (match-string 2 ans)))
17162 (setq year (org-small-year-to-year year))
17163 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17164 t nil ans)))
17165 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17166 ;; If there is a time with am/pm, and *no* time without it, we convert
17167 ;; so that matching will be successful.
17168 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17169 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17170 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17171 (setq hour (string-to-number (match-string 1 ans))
17172 minute (if (match-end 3)
17173 (string-to-number (match-string 3 ans))
17175 pm (equal ?p
17176 (string-to-char (downcase (match-string 4 ans)))))
17177 (if (and (= hour 12) (not pm))
17178 (setq hour 0)
17179 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17180 (setq ans (replace-match (format "%02d:%02d" hour minute)
17181 t t ans))))
17183 ;; Check if a time range is given as a duration
17184 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17185 (setq hour (string-to-number (match-string 1 ans))
17186 h2 (+ hour (string-to-number (match-string 3 ans)))
17187 minute (string-to-number (match-string 2 ans))
17188 m2 (+ minute (if (match-end 5) (string-to-number
17189 (match-string 5 ans))0)))
17190 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17191 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17192 t t ans)))
17194 ;; Check if there is a time range
17195 (when (boundp 'org-end-time-was-given)
17196 (setq org-time-was-given nil)
17197 (when (and (string-match org-plain-time-of-day-regexp ans)
17198 (match-end 8))
17199 (setq org-end-time-was-given (match-string 8 ans))
17200 (setq ans (concat (substring ans 0 (match-beginning 7))
17201 (substring ans (match-end 7))))))
17203 (setq tl (parse-time-string ans)
17204 day (or (nth 3 tl) (nth 3 org-defdecode))
17205 month
17206 (cond ((nth 4 tl))
17207 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17208 ;; Day was specified. Make sure DAY+MONTH
17209 ;; combination happens in the future.
17210 ((nth 3 tl)
17211 (setq futurep t)
17212 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17213 (nth 4 nowdecode)))
17214 (t (nth 4 org-defdecode)))
17215 year
17216 (cond ((and (not kill-year) (nth 5 tl)))
17217 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17218 ;; Month was guessed in the future and is at least
17219 ;; equal to NOWDECODE's. Fix year accordingly.
17220 (futurep
17221 (if (or (> month (nth 4 nowdecode))
17222 (>= day (nth 3 nowdecode)))
17223 (nth 5 nowdecode)
17224 (1+ (nth 5 nowdecode))))
17225 ;; Month was specified. Make sure MONTH+YEAR
17226 ;; combination happens in the future.
17227 ((nth 4 tl)
17228 (setq futurep t)
17229 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17230 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17231 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17232 (t (nth 5 nowdecode))))
17233 (t (nth 5 org-defdecode)))
17234 hour (or (nth 2 tl) (nth 2 org-defdecode))
17235 minute (or (nth 1 tl) (nth 1 org-defdecode))
17236 second (or (nth 0 tl) 0)
17237 wday (nth 6 tl))
17239 (when (and (eq org-read-date-prefer-future 'time)
17240 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17241 (equal day (nth 3 nowdecode))
17242 (equal month (nth 4 nowdecode))
17243 (equal year (nth 5 nowdecode))
17244 (nth 2 tl)
17245 (or (< (nth 2 tl) (nth 2 nowdecode))
17246 (and (= (nth 2 tl) (nth 2 nowdecode))
17247 (nth 1 tl)
17248 (< (nth 1 tl) (nth 1 nowdecode)))))
17249 (setq day (1+ day)
17250 futurep t))
17252 ;; Special date definitions below
17253 (cond
17254 (iso-week
17255 ;; There was an iso week
17256 (require 'cal-iso)
17257 (setq futurep nil)
17258 (setq year (or iso-year year)
17259 day (or iso-weekday wday 1)
17260 wday nil ; to make sure that the trigger below does not match
17261 iso-date (calendar-gregorian-from-absolute
17262 (calendar-iso-to-absolute
17263 (list iso-week day year))))
17264 ; FIXME: Should we also push ISO weeks into the future?
17265 ; (when (and org-read-date-prefer-future
17266 ; (not iso-year)
17267 ; (< (calendar-absolute-from-gregorian iso-date)
17268 ; (time-to-days (current-time))))
17269 ; (setq year (1+ year)
17270 ; iso-date (calendar-gregorian-from-absolute
17271 ; (calendar-iso-to-absolute
17272 ; (list iso-week day year)))))
17273 (setq month (car iso-date)
17274 year (nth 2 iso-date)
17275 day (nth 1 iso-date)))
17276 (deltan
17277 (setq futurep nil)
17278 (unless deltadef
17279 ;; Pass `current-time' result to `decode-time' (instead of
17280 ;; calling without arguments) so that only `current-time' has
17281 ;; to be overriden in tests.
17282 (let ((now (decode-time (current-time))))
17283 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17284 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17285 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17286 ((equal deltaw "m") (setq month (+ month deltan)))
17287 ((equal deltaw "y") (setq year (+ year deltan)))))
17288 ((and wday (not (nth 3 tl)))
17289 ;; Weekday was given, but no day, so pick that day in the week
17290 ;; on or after the derived date.
17291 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17292 (unless (equal wday wday1)
17293 (setq day (+ day (% (- wday wday1 -7) 7))))))
17294 (when (and (boundp 'org-time-was-given)
17295 (nth 2 tl))
17296 (setq org-time-was-given t))
17297 (when (< year 100) (setq year (+ 2000 year)))
17298 ;; Check of the date is representable
17299 (if org-read-date-force-compatible-dates
17300 (progn
17301 (when (< year 1970)
17302 (setq year 1970 org-read-date-analyze-forced-year t))
17303 (when (> year 2037)
17304 (setq year 2037 org-read-date-analyze-forced-year t)))
17305 (condition-case nil
17306 (ignore (encode-time second minute hour day month year))
17307 (error
17308 (setq year (nth 5 org-defdecode))
17309 (setq org-read-date-analyze-forced-year t))))
17310 (setq org-read-date-analyze-futurep futurep)
17311 (list second minute hour day month year)))
17313 (defvar parse-time-weekdays)
17314 (defun org-read-date-get-relative (s today default)
17315 "Check string S for special relative date string.
17316 TODAY and DEFAULT are internal times, for today and for a default.
17317 Return shift list (N what def-flag)
17318 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17319 N is the number of WHATs to shift.
17320 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17321 the DEFAULT date rather than TODAY."
17322 (require 'parse-time)
17323 (when (and
17324 (string-match
17325 (concat
17326 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17327 "\\([0-9]+\\)?"
17328 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17329 "\\([ \t]\\|$\\)") s)
17330 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17331 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17332 (string-to-char (substring (match-string 1 s) -1))
17333 ?+))
17334 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17335 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17336 (what (if (match-end 3) (match-string 3 s) "d"))
17337 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17338 (date (if rel default today))
17339 (wday (nth 6 (decode-time date)))
17340 delta)
17341 (if wday1
17342 (progn
17343 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17344 (when (= delta 0) (setq delta 7))
17345 (when (= dir ?-)
17346 (setq delta (- delta 7))
17347 (when (= delta 0) (setq delta -7)))
17348 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17349 (list delta "d" rel))
17350 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17352 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17353 "Turn a user-specified date into the internal representation.
17354 The internal representation needed by the calendar is (month day year).
17355 This is a wrapper to handle the brain-dead convention in calendar that
17356 user function argument order change dependent on argument order."
17357 (if (boundp 'calendar-date-style)
17358 (cond
17359 ((eq calendar-date-style 'american)
17360 (list arg1 arg2 arg3))
17361 ((eq calendar-date-style 'european)
17362 (list arg2 arg1 arg3))
17363 ((eq calendar-date-style 'iso)
17364 (list arg2 arg3 arg1)))
17365 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17366 (if (org-bound-and-true-p european-calendar-style)
17367 (list arg2 arg1 arg3)
17368 (list arg1 arg2 arg3)))))
17370 (defun org-eval-in-calendar (form &optional keepdate)
17371 "Eval FORM in the calendar window and return to current window.
17372 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17373 (let ((sf (selected-frame))
17374 (sw (selected-window)))
17375 (select-window (get-buffer-window "*Calendar*" t))
17376 (eval form)
17377 (when (and (not keepdate) (calendar-cursor-to-date))
17378 (let* ((date (calendar-cursor-to-date))
17379 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17380 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17381 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17382 (select-window sw)
17383 (select-frame-set-input-focus sf)))
17385 (defun org-calendar-select ()
17386 "Return to `org-read-date' with the date currently selected.
17387 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17388 (interactive)
17389 (when (calendar-cursor-to-date)
17390 (let* ((date (calendar-cursor-to-date))
17391 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17392 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17393 (when (active-minibuffer-window) (exit-minibuffer))))
17395 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17396 "Insert a date stamp for the date given by the internal TIME.
17397 See `format-time-string' for the format of TIME.
17398 WITH-HM means use the stamp format that includes the time of the day.
17399 INACTIVE means use square brackets instead of angular ones, so that the
17400 stamp will not contribute to the agenda.
17401 PRE and POST are optional strings to be inserted before and after the
17402 stamp.
17403 The command returns the inserted time stamp."
17404 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17405 stamp)
17406 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17407 (insert-before-markers (or pre ""))
17408 (when (listp extra)
17409 (setq extra (car extra))
17410 (if (and (stringp extra)
17411 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17412 (setq extra (format "-%02d:%02d"
17413 (string-to-number (match-string 1 extra))
17414 (string-to-number (match-string 2 extra))))
17415 (setq extra nil)))
17416 (when extra
17417 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17418 (insert-before-markers (setq stamp (format-time-string fmt time)))
17419 (insert-before-markers (or post ""))
17420 (setq org-last-inserted-timestamp stamp)))
17422 (defun org-toggle-time-stamp-overlays ()
17423 "Toggle the use of custom time stamp formats."
17424 (interactive)
17425 (setq org-display-custom-times (not org-display-custom-times))
17426 (unless org-display-custom-times
17427 (let ((p (point-min)) (bmp (buffer-modified-p)))
17428 (while (setq p (next-single-property-change p 'display))
17429 (when (and (get-text-property p 'display)
17430 (eq (get-text-property p 'face) 'org-date))
17431 (remove-text-properties
17432 p (setq p (next-single-property-change p 'display))
17433 '(display t))))
17434 (set-buffer-modified-p bmp)))
17435 (org-restart-font-lock)
17436 (setq org-table-may-need-update t)
17437 (if org-display-custom-times
17438 (message "Time stamps are overlaid with custom format")
17439 (message "Time stamp overlays removed")))
17441 (defun org-display-custom-time (beg end)
17442 "Overlay modified time stamp format over timestamp between BEG and END."
17443 (let* ((ts (buffer-substring beg end))
17444 t1 w1 with-hm tf time str w2 (off 0))
17445 (save-match-data
17446 (setq t1 (org-parse-time-string ts t))
17447 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17448 (setq off (- (match-end 0) (match-beginning 0)))))
17449 (setq end (- end off))
17450 (setq w1 (- end beg)
17451 with-hm (and (nth 1 t1) (nth 2 t1))
17452 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17453 time (org-fix-decoded-time t1)
17454 str (org-add-props
17455 (format-time-string
17456 (substring tf 1 -1) (apply 'encode-time time))
17457 nil 'mouse-face 'highlight)
17458 w2 (length str))
17459 (unless (= w2 w1)
17460 (add-text-properties (1+ beg) (+ 2 beg)
17461 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17462 (put-text-property beg end 'display str)))
17464 (defun org-fix-decoded-time (time)
17465 "Set 0 instead of nil for the first 6 elements of time.
17466 Don't touch the rest."
17467 (let ((n 0))
17468 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17470 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17472 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17473 "Difference between TIMESTAMP-STRING and now in days.
17474 If SECONDS is non-nil, return the difference in seconds."
17475 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17476 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17477 (funcall fdiff (current-time)))))
17479 (defun org-deadline-close (timestamp-string &optional ndays)
17480 "Is the time in TIMESTAMP-STRING close to the current date?"
17481 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17482 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17483 (not (org-entry-is-done-p))))
17485 (defun org-get-wdays (ts &optional delay zero-delay)
17486 "Get the deadline lead time appropriate for timestring TS.
17487 When DELAY is non-nil, get the delay time for scheduled items
17488 instead of the deadline lead time. When ZERO-DELAY is non-nil
17489 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17490 don't try to find the delay cookie in the scheduled timestamp."
17491 (let ((tv (if delay org-scheduled-delay-days
17492 org-deadline-warning-days)))
17493 (cond
17494 ((or (and delay (< tv 0))
17495 (and delay zero-delay (<= tv 0))
17496 (and (not delay) (<= tv 0)))
17497 ;; Enforce this value no matter what
17498 (- tv))
17499 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17500 ;; lead time is specified.
17501 (floor (* (string-to-number (match-string 1 ts))
17502 (cdr (assoc (match-string 2 ts)
17503 '(("d" . 1) ("w" . 7)
17504 ("m" . 30.4) ("y" . 365.25)
17505 ("h" . 0.041667)))))))
17506 ;; go for the default.
17507 (t tv))))
17509 (defun org-calendar-select-mouse (ev)
17510 "Return to `org-read-date' with the date currently selected.
17511 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17512 (interactive "e")
17513 (mouse-set-point ev)
17514 (when (calendar-cursor-to-date)
17515 (let* ((date (calendar-cursor-to-date))
17516 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17517 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17518 (when (active-minibuffer-window) (exit-minibuffer))))
17520 (defun org-check-deadlines (ndays)
17521 "Check if there are any deadlines due or past due.
17522 A deadline is considered due if it happens within `org-deadline-warning-days'
17523 days from today's date. If the deadline appears in an entry marked DONE,
17524 it is not shown. The prefix arg NDAYS can be used to test that many
17525 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17526 (interactive "P")
17527 (let* ((org-warn-days
17528 (cond
17529 ((equal ndays '(4)) 100000)
17530 (ndays (prefix-numeric-value ndays))
17531 (t (abs org-deadline-warning-days))))
17532 (case-fold-search nil)
17533 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17534 (callback
17535 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17536 (message "%d deadlines past-due or due within %d days"
17537 (org-occur regexp nil callback)
17538 org-warn-days)))
17540 (defsubst org-re-timestamp (type)
17541 "Return a regexp for timestamp TYPE.
17542 Allowed values for TYPE are:
17544 all: all timestamps
17545 active: only active timestamps (<...>)
17546 inactive: only inactive timestamps ([...])
17547 scheduled: only scheduled timestamps
17548 deadline: only deadline timestamps
17549 closed: only closed time-stamps
17551 When TYPE is nil, fall back on returning a regexp that matches
17552 both scheduled and deadline timestamps."
17553 (cl-case type
17554 (all org-ts-regexp-both)
17555 (active org-ts-regexp)
17556 (inactive org-ts-regexp-inactive)
17557 (scheduled org-scheduled-time-regexp)
17558 (deadline org-deadline-time-regexp)
17559 (closed org-closed-time-regexp)
17560 (otherwise
17561 (concat "\\<"
17562 (regexp-opt (list org-deadline-string org-scheduled-string))
17563 " *<\\([^>]+\\)>"))))
17565 (defun org-check-before-date (d)
17566 "Check if there are deadlines or scheduled entries before date D."
17567 (interactive (list (org-read-date)))
17568 (let* ((case-fold-search nil)
17569 (regexp (org-re-timestamp org-ts-type))
17570 (ts-type org-ts-type)
17571 (callback
17572 (lambda ()
17573 (let ((match (match-string 1)))
17574 (and (if (memq ts-type '(active inactive all))
17575 (eq (org-element-type (save-excursion
17576 (backward-char)
17577 (org-element-context)))
17578 'timestamp)
17579 (org-at-planning-p))
17580 (time-less-p
17581 (org-time-string-to-time match)
17582 (org-time-string-to-time d)))))))
17583 (message "%d entries before %s"
17584 (org-occur regexp nil callback)
17585 d)))
17587 (defun org-check-after-date (d)
17588 "Check if there are deadlines or scheduled entries after date D."
17589 (interactive (list (org-read-date)))
17590 (let* ((case-fold-search nil)
17591 (regexp (org-re-timestamp org-ts-type))
17592 (ts-type org-ts-type)
17593 (callback
17594 (lambda ()
17595 (let ((match (match-string 1)))
17596 (and (if (memq ts-type '(active inactive all))
17597 (eq (org-element-type (save-excursion
17598 (backward-char)
17599 (org-element-context)))
17600 'timestamp)
17601 (org-at-planning-p))
17602 (not (time-less-p
17603 (org-time-string-to-time match)
17604 (org-time-string-to-time d))))))))
17605 (message "%d entries after %s"
17606 (org-occur regexp nil callback)
17607 d)))
17609 (defun org-check-dates-range (start-date end-date)
17610 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17611 (interactive (list (org-read-date nil nil nil "Range starts")
17612 (org-read-date nil nil nil "Range end")))
17613 (let ((case-fold-search nil)
17614 (regexp (org-re-timestamp org-ts-type))
17615 (callback
17616 (let ((type org-ts-type))
17617 (lambda ()
17618 (let ((match (match-string 1)))
17619 (and
17620 (if (memq type '(active inactive all))
17621 (eq (org-element-type (save-excursion
17622 (backward-char)
17623 (org-element-context)))
17624 'timestamp)
17625 (org-at-planning-p))
17626 (not (time-less-p
17627 (org-time-string-to-time match)
17628 (org-time-string-to-time start-date)))
17629 (time-less-p
17630 (org-time-string-to-time match)
17631 (org-time-string-to-time end-date))))))))
17632 (message "%d entries between %s and %s"
17633 (org-occur regexp nil callback) start-date end-date)))
17635 (defun org-evaluate-time-range (&optional to-buffer)
17636 "Evaluate a time range by computing the difference between start and end.
17637 Normally the result is just printed in the echo area, but with prefix arg
17638 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17639 If the time range is actually in a table, the result is inserted into the
17640 next column.
17641 For time difference computation, a year is assumed to be exactly 365
17642 days in order to avoid rounding problems."
17643 (interactive "P")
17645 (org-clock-update-time-maybe)
17646 (save-excursion
17647 (unless (org-at-date-range-p t)
17648 (goto-char (point-at-bol))
17649 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17650 (unless (org-at-date-range-p t)
17651 (user-error "Not at a time-stamp range, and none found in current line")))
17652 (let* ((ts1 (match-string 1))
17653 (ts2 (match-string 2))
17654 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17655 (match-end (match-end 0))
17656 (time1 (org-time-string-to-time ts1))
17657 (time2 (org-time-string-to-time ts2))
17658 (t1 (float-time time1))
17659 (t2 (float-time time2))
17660 (diff (abs (- t2 t1)))
17661 (negative (< (- t2 t1) 0))
17662 ;; (ys (floor (* 365 24 60 60)))
17663 (ds (* 24 60 60))
17664 (hs (* 60 60))
17665 (fy "%dy %dd %02d:%02d")
17666 (fy1 "%dy %dd")
17667 (fd "%dd %02d:%02d")
17668 (fd1 "%dd")
17669 (fh "%02d:%02d")
17670 y d h m align)
17671 (if havetime
17672 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17674 d (floor (/ diff ds)) diff (mod diff ds)
17675 h (floor (/ diff hs)) diff (mod diff hs)
17676 m (floor (/ diff 60)))
17677 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17679 d (floor (+ (/ diff ds) 0.5))
17680 h 0 m 0))
17681 (if (not to-buffer)
17682 (message "%s" (org-make-tdiff-string y d h m))
17683 (if (org-at-table-p)
17684 (progn
17685 (goto-char match-end)
17686 (setq align t)
17687 (and (looking-at " *|") (goto-char (match-end 0))))
17688 (goto-char match-end))
17689 (when (looking-at
17690 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17691 (replace-match ""))
17692 (when negative (insert " -"))
17693 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17694 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17695 (insert " " (format fh h m))))
17696 (when align (org-table-align))
17697 (message "Time difference inserted")))))
17699 (defun org-make-tdiff-string (y d h m)
17700 (let ((fmt "")
17701 (l nil))
17702 (when (> y 0)
17703 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17704 (push y l))
17705 (when (> d 0)
17706 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17707 (push d l))
17708 (when (> h 0)
17709 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17710 (push h l))
17711 (when (> m 0)
17712 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17713 (push m l))
17714 (apply 'format fmt (nreverse l))))
17716 (defun org-time-string-to-time (s &optional buffer pos)
17717 "Convert a timestamp string into internal time."
17718 (condition-case errdata
17719 (apply 'encode-time (org-parse-time-string s))
17720 (error (error "Bad timestamp `%s'%s\nError was: %s"
17721 s (if (not (and buffer pos))
17723 (format-message " at %d in buffer `%s'" pos buffer))
17724 (cdr errdata)))))
17726 (defun org-time-string-to-seconds (s)
17727 "Convert a timestamp string to a number of seconds."
17728 (float-time (org-time-string-to-time s)))
17730 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17732 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17733 "Convert time stamp S to an absolute day number.
17735 If DAYNR in non-nil, and there is a specifier for a cyclic time
17736 stamp, get the closest date to DAYNR. If PREFER is
17737 `past' (respectively `future') return a date past (respectively
17738 after) or equal to DAYNR.
17740 POS is the location of time stamp S, as a buffer position in
17741 BUFFER.
17743 Diary sexp timestamps are matched against DAYNR, when non-nil.
17744 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17745 signalled."
17746 (cond
17747 ((string-match "\\`%%\\((.*)\\)" s)
17748 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17749 ;; only able to match individual dates. If it fails, raise an
17750 ;; error.
17751 (if (and daynr
17752 (org-diary-sexp-entry
17753 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17754 daynr
17755 (signal 'org-diary-sexp-no-match (list s))))
17756 ((and daynr show-all) (org-closest-date s daynr prefer))
17757 (t (time-to-days
17758 (condition-case errdata
17759 (apply #'encode-time (org-parse-time-string s))
17760 (error (error "Bad timestamp `%s'%s\nError was: %s"
17762 (if (not (and buffer pos)) ""
17763 (format-message " at %d in buffer `%s'" pos buffer))
17764 (cdr errdata))))))))
17766 (defun org-days-to-iso-week (days)
17767 "Return the iso week number."
17768 (require 'cal-iso)
17769 (car (calendar-iso-from-absolute days)))
17771 (defun org-small-year-to-year (year)
17772 "Convert 2-digit years into 4-digit years.
17773 YEAR is expanded into one of the 30 next years, if possible, or
17774 into a past one. Any year larger than 99 is returned unchanged."
17775 (if (>= year 100) year
17776 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17777 (century (/ current 100))
17778 (offset (- year (% current 100))))
17779 (cond ((> offset 30) (+ (* (1- century) 100) year))
17780 ((> offset -70) (+ (* century 100) year))
17781 (t (+ (* (1+ century) 100) year))))))
17783 (defun org-time-from-absolute (d)
17784 "Return the time corresponding to date D.
17785 D may be an absolute day number, or a calendar-type list (month day year)."
17786 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17787 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17789 (defvar org-agenda-current-date)
17790 (defun org-calendar-holiday ()
17791 "List of holidays, for Diary display in Org mode."
17792 (require 'holidays)
17793 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17794 (and hl (mapconcat #'identity hl "; "))))
17796 (defun org-diary-sexp-entry (sexp entry d)
17797 "Process a SEXP diary ENTRY for date D."
17798 (require 'diary-lib)
17799 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17800 ;; dynamically.
17801 (let* ((sexp `(let ((entry ,entry)
17802 (date ',d))
17803 ,(car (read-from-string sexp))))
17804 (result (if calendar-debug-sexp (eval sexp)
17805 (condition-case nil
17806 (eval sexp)
17807 (error
17808 (beep)
17809 (message "Bad sexp at line %d in %s: %s"
17810 (org-current-line)
17811 (buffer-file-name) sexp)
17812 (sleep-for 2))))))
17813 (cond ((stringp result) (split-string result "; "))
17814 ((and (consp result)
17815 (not (consp (cdr result)))
17816 (stringp (cdr result))) (cdr result))
17817 ((and (consp result)
17818 (stringp (car result))) result)
17819 (result entry))))
17821 (defun org-diary-to-ical-string (frombuf)
17822 "Get iCalendar entries from diary entries in buffer FROMBUF.
17823 This uses the icalendar.el library."
17824 (let* ((tmpdir temporary-file-directory)
17825 (tmpfile (make-temp-name
17826 (expand-file-name "orgics" tmpdir)))
17827 buf rtn b e)
17828 (with-current-buffer frombuf
17829 (icalendar-export-region (point-min) (point-max) tmpfile)
17830 (setq buf (find-buffer-visiting tmpfile))
17831 (set-buffer buf)
17832 (goto-char (point-min))
17833 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17834 (setq b (match-beginning 0)))
17835 (goto-char (point-max))
17836 (when (re-search-backward "^END:VEVENT" nil t)
17837 (setq e (match-end 0)))
17838 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17839 (kill-buffer buf)
17840 (delete-file tmpfile)
17841 rtn))
17843 (defun org-closest-date (start current prefer)
17844 "Return closest date to CURRENT starting from START.
17846 CURRENT and START are both time stamps.
17848 When PREFER is `past', return a date that is either CURRENT or
17849 past. When PREFER is `future', return a date that is either
17850 CURRENT or future.
17852 Only time stamps with a repeater are modified. Any other time
17853 stamp stay unchanged. In any case, return value is an absolute
17854 day number."
17855 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17856 ;; No repeater. Do not shift time stamp.
17857 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17858 (let ((value (string-to-number (match-string 1 start)))
17859 (type (match-string 2 start)))
17860 (if (= 0 value)
17861 ;; Repeater with a 0-value is considered as void.
17862 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17863 (let* ((base (org-date-to-gregorian start))
17864 (target (org-date-to-gregorian current))
17865 (sday (calendar-absolute-from-gregorian base))
17866 (cday (calendar-absolute-from-gregorian target))
17867 n1 n2)
17868 ;; If START is already past CURRENT, just return START.
17869 (if (<= cday sday) sday
17870 ;; Compute closest date before (N1) and closest date past
17871 ;; (N2) CURRENT.
17872 (pcase type
17873 ("h"
17874 (let ((missing-hours
17875 (mod (+ (- (* 24 (- cday sday))
17876 (nth 2 (org-parse-time-string start)))
17877 org-extend-today-until)
17878 value)))
17879 (setf n1 (if (= missing-hours 0) cday
17880 (- cday (1+ (/ missing-hours 24)))))
17881 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17882 ((or "d" "w")
17883 (let ((value (if (equal type "w") (* 7 value) value)))
17884 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17885 (setf n2 (+ n1 value))))
17886 ("m"
17887 (let* ((add-months
17888 (lambda (d n)
17889 ;; Add N months to gregorian date D, i.e.,
17890 ;; a list (MONTH DAY YEAR). Return a valid
17891 ;; gregorian date.
17892 (let ((m (+ (nth 0 d) n)))
17893 (list (mod m 12)
17894 (nth 1 d)
17895 (+ (/ m 12) (nth 2 d))))))
17896 (months ; Complete months to TARGET.
17897 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17898 (- (nth 0 target) (nth 0 base))
17899 ;; If START's day is greater than
17900 ;; TARGET's, remove incomplete month.
17901 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17902 value)
17903 value))
17904 (before (funcall add-months base months)))
17905 (setf n1 (calendar-absolute-from-gregorian before))
17906 (setf n2
17907 (calendar-absolute-from-gregorian
17908 (funcall add-months before value)))))
17910 (let* ((d (nth 1 base))
17911 (m (nth 0 base))
17912 (y (nth 2 base))
17913 (years ; Complete years to TARGET.
17914 (* (/ (- (nth 2 target)
17916 ;; If START's month and day are
17917 ;; greater than TARGET's, remove
17918 ;; incomplete year.
17919 (if (or (> (nth 0 target) m)
17920 (and (= (nth 0 target) m)
17921 (> (nth 1 target) d)))
17924 value)
17925 value))
17926 (before (list m d (+ y years))))
17927 (setf n1 (calendar-absolute-from-gregorian before))
17928 (setf n2 (calendar-absolute-from-gregorian
17929 (list m d (+ (nth 2 before) value)))))))
17930 ;; Handle PREFER parameter, if any.
17931 (cond
17932 ((eq prefer 'past) (if (= cday n2) n2 n1))
17933 ((eq prefer 'future) (if (= cday n1) n1 n2))
17934 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17936 (defun org-date-to-gregorian (d)
17937 "Turn any specification of date D into a Gregorian date for the calendar."
17938 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17939 ((and (listp d) (= (length d) 3)) d)
17940 ((stringp d)
17941 (let ((d (org-parse-time-string d)))
17942 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17943 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17945 (defun org-parse-time-string (s &optional nodefault)
17946 "Parse the standard Org-mode time string.
17947 This should be a lot faster than the normal `parse-time-string'.
17948 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17949 hour and minute fields will be nil if not given."
17950 (cond ((string-match org-ts-regexp0 s)
17951 (list 0
17952 (when (or (match-beginning 8) (not nodefault))
17953 (string-to-number (or (match-string 8 s) "0")))
17954 (when (or (match-beginning 7) (not nodefault))
17955 (string-to-number (or (match-string 7 s) "0")))
17956 (string-to-number (match-string 4 s))
17957 (string-to-number (match-string 3 s))
17958 (string-to-number (match-string 2 s))
17959 nil nil nil))
17960 ((string-match "^<[^>]+>$" s)
17961 (decode-time (seconds-to-time (org-matcher-time s))))
17962 (t (error "Not a standard Org-mode time string: %s" s))))
17964 (defun org-timestamp-up (&optional arg)
17965 "Increase the date item at the cursor by one.
17966 If the cursor is on the year, change the year. If it is on the month,
17967 the day or the time, change that.
17968 With prefix ARG, change by that many units."
17969 (interactive "p")
17970 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17972 (defun org-timestamp-down (&optional arg)
17973 "Decrease the date item at the cursor by one.
17974 If the cursor is on the year, change the year. If it is on the month,
17975 the day or the time, change that.
17976 With prefix ARG, change by that many units."
17977 (interactive "p")
17978 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17980 (defun org-timestamp-up-day (&optional arg)
17981 "Increase the date in the time stamp by one day.
17982 With prefix ARG, change that many days."
17983 (interactive "p")
17984 (if (and (not (org-at-timestamp-p t))
17985 (org-at-heading-p))
17986 (org-todo 'up)
17987 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17989 (defun org-timestamp-down-day (&optional arg)
17990 "Decrease the date in the time stamp by one day.
17991 With prefix ARG, change that many days."
17992 (interactive "p")
17993 (if (and (not (org-at-timestamp-p t))
17994 (org-at-heading-p))
17995 (org-todo 'down)
17996 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17998 (defun org-at-timestamp-p (&optional inactive-ok)
17999 "Non-nil if point is inside a timestamp.
18001 When optional argument INACTIVE-OK is non-nil, also consider
18002 inactive timestamps.
18004 When this function returns a non-nil value, match data is set
18005 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18006 INACTIVE-OK."
18007 (interactive)
18008 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18009 (pos (point))
18010 (ans (or (looking-at tsr)
18011 (save-excursion
18012 (skip-chars-backward "^[<\n\r\t")
18013 (when (> (point) (point-min)) (backward-char 1))
18014 (and (looking-at tsr)
18015 (> (- (match-end 0) pos) -1))))))
18016 (and ans
18017 (boundp 'org-ts-what)
18018 (setq org-ts-what
18019 (cond
18020 ((= pos (match-beginning 0)) 'bracket)
18021 ;; Point is considered to be "on the bracket" whether
18022 ;; it's really on it or right after it.
18023 ((= pos (1- (match-end 0))) 'bracket)
18024 ((= pos (match-end 0)) 'after)
18025 ((org-pos-in-match-range pos 2) 'year)
18026 ((org-pos-in-match-range pos 3) 'month)
18027 ((org-pos-in-match-range pos 7) 'hour)
18028 ((org-pos-in-match-range pos 8) 'minute)
18029 ((or (org-pos-in-match-range pos 4)
18030 (org-pos-in-match-range pos 5)) 'day)
18031 ((and (> pos (or (match-end 8) (match-end 5)))
18032 (< pos (match-end 0)))
18033 (- pos (or (match-end 8) (match-end 5))))
18034 (t 'day))))
18035 ans))
18037 (defun org-toggle-timestamp-type ()
18038 "Toggle the type (<active> or [inactive]) of a time stamp."
18039 (interactive)
18040 (when (org-at-timestamp-p t)
18041 (let ((beg (match-beginning 0)) (end (match-end 0))
18042 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18043 (save-excursion
18044 (goto-char beg)
18045 (while (re-search-forward "[][<>]" end t)
18046 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18047 t t)))
18048 (message "Timestamp is now %sactive"
18049 (if (equal (char-after beg) ?<) "" "in")))))
18051 (defun org-at-clock-log-p nil
18052 "Is the cursor on the clock log line?"
18053 (save-excursion
18054 (move-beginning-of-line 1)
18055 (looking-at org-clock-line-re)))
18057 (defvar org-clock-history) ; defined in org-clock.el
18058 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18059 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18060 "Change the date in the time stamp at point.
18061 The date will be changed by N times WHAT. WHAT can be `day', `month',
18062 `year', `minute', `second'. If WHAT is not given, the cursor position
18063 in the timestamp determines what will be changed.
18064 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18065 (let ((origin (point)) origin-cat
18066 with-hm inactive
18067 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18068 org-ts-what
18069 extra rem
18070 ts time time0 fixnext clrgx)
18071 (unless (org-at-timestamp-p t)
18072 (user-error "Not at a timestamp"))
18073 (if (and (not what) (eq org-ts-what 'bracket))
18074 (org-toggle-timestamp-type)
18075 ;; Point isn't on brackets. Remember the part of the time-stamp
18076 ;; the point was in. Indeed, size of time-stamps may change,
18077 ;; but point must be kept in the same category nonetheless.
18078 (setq origin-cat org-ts-what)
18079 (when (and (not what) (not (eq org-ts-what 'day))
18080 org-display-custom-times
18081 (get-text-property (point) 'display)
18082 (not (get-text-property (1- (point)) 'display)))
18083 (setq org-ts-what 'day))
18084 (setq org-ts-what (or what org-ts-what)
18085 inactive (= (char-after (match-beginning 0)) ?\[)
18086 ts (match-string 0))
18087 (replace-match "")
18088 (when (string-match
18089 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18091 (setq extra (match-string 1 ts))
18092 (when suppress-tmp-delay
18093 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18094 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18095 (setq with-hm t))
18096 (setq time0 (org-parse-time-string ts))
18097 (when (and updown
18098 (eq org-ts-what 'minute)
18099 (not current-prefix-arg))
18100 ;; This looks like s-up and s-down. Change by one rounding step.
18101 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18102 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18103 (setcar (cdr time0) (+ (nth 1 time0)
18104 (if (> n 0) (- rem) (- dm rem))))))
18105 (setq time
18106 (apply #'encode-time
18107 (or (car time0) 0)
18108 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18109 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18110 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18111 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18112 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18113 (nthcdr 6 time0)))
18114 (when (and (member org-ts-what '(hour minute))
18115 extra
18116 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18117 (setq extra (org-modify-ts-extra
18118 extra
18119 (if (eq org-ts-what 'hour) 2 5)
18120 n dm)))
18121 (when (integerp org-ts-what)
18122 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18123 (when (eq what 'calendar)
18124 (let ((cal-date (org-get-date-from-calendar)))
18125 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18126 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18127 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18128 (setcar time0 (or (car time0) 0))
18129 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18130 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18131 (setq time (apply 'encode-time time0))))
18132 ;; Insert the new time-stamp, and ensure point stays in the same
18133 ;; category as before (i.e. not after the last position in that
18134 ;; category).
18135 (let ((pos (point)))
18136 ;; Stay before inserted string. `save-excursion' is of no use.
18137 (setq org-last-changed-timestamp
18138 (org-insert-time-stamp time with-hm inactive nil nil extra))
18139 (goto-char pos))
18140 (save-match-data
18141 (looking-at org-ts-regexp3)
18142 (goto-char (cond
18143 ;; `day' category ends before `hour' if any, or at
18144 ;; the end of the day name.
18145 ((eq origin-cat 'day)
18146 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18147 ((eq origin-cat 'hour) (min (match-end 7) origin))
18148 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18149 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18150 ;; `year' and `month' have both fixed size: point
18151 ;; couldn't have moved into another part.
18152 (t origin))))
18153 ;; Update clock if on a CLOCK line.
18154 (org-clock-update-time-maybe)
18155 ;; Maybe adjust the closest clock in `org-clock-history'
18156 (when org-clock-adjust-closest
18157 (if (not (and (org-at-clock-log-p)
18158 (< 1 (length (delq nil (mapcar 'marker-position
18159 org-clock-history))))))
18160 (message "No clock to adjust")
18161 (cond ((save-excursion ; fix previous clock?
18162 (re-search-backward org-ts-regexp0 nil t)
18163 (looking-back (concat org-clock-string " \\[")
18164 (line-beginning-position)))
18165 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18166 ((save-excursion ; fix next clock?
18167 (re-search-backward org-ts-regexp0 nil t)
18168 (looking-at (concat org-ts-regexp0 "\\] =>")))
18169 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18170 (save-window-excursion
18171 ;; Find closest clock to point, adjust the previous/next one in history
18172 (let* ((p (save-excursion (org-back-to-heading t)))
18173 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18174 (clfixnth
18175 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18176 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18177 (if (not clfixpos)
18178 (message "No clock to adjust")
18179 (save-excursion
18180 (org-goto-marker-or-bmk clfixpos)
18181 (org-show-subtree)
18182 (when (re-search-forward clrgx nil t)
18183 (goto-char (match-beginning 1))
18184 (let (org-clock-adjust-closest)
18185 (org-timestamp-change n org-ts-what updown))
18186 (message "Clock adjusted in %s for heading: %s"
18187 (file-name-nondirectory (buffer-file-name))
18188 (org-get-heading t t)))))))))
18189 ;; Try to recenter the calendar window, if any.
18190 (when (and org-calendar-follow-timestamp-change
18191 (get-buffer-window "*Calendar*" t)
18192 (memq org-ts-what '(day month year)))
18193 (org-recenter-calendar (time-to-days time))))))
18195 (defun org-modify-ts-extra (s pos n dm)
18196 "Change the different parts of the lead-time and repeat fields in timestamp."
18197 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18198 ng h m new rem)
18199 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18200 (cond
18201 ((or (org-pos-in-match-range pos 2)
18202 (org-pos-in-match-range pos 3))
18203 (setq m (string-to-number (match-string 3 s))
18204 h (string-to-number (match-string 2 s)))
18205 (if (org-pos-in-match-range pos 2)
18206 (setq h (+ h n))
18207 (setq n (* dm (org-no-warnings (signum n))))
18208 (unless (= 0 (setq rem (% m dm)))
18209 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18210 (setq m (+ m n)))
18211 (when (< m 0) (setq m (+ m 60) h (1- h)))
18212 (when (> m 59) (setq m (- m 60) h (1+ h)))
18213 (setq h (mod h 24))
18214 (setq ng 1 new (format "-%02d:%02d" h m)))
18215 ((org-pos-in-match-range pos 6)
18216 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18217 ((org-pos-in-match-range pos 5)
18218 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18220 ((org-pos-in-match-range pos 9)
18221 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18222 ((org-pos-in-match-range pos 8)
18223 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18225 (when ng
18226 (setq s (concat
18227 (substring s 0 (match-beginning ng))
18229 (substring s (match-end ng))))))
18232 (defun org-recenter-calendar (d)
18233 "If the calendar is visible, recenter it to date D."
18234 (let ((cwin (get-buffer-window "*Calendar*" t)))
18235 (when cwin
18236 (let ((calendar-move-hook nil))
18237 (with-selected-window cwin
18238 (calendar-goto-date
18239 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18241 (defun org-goto-calendar (&optional arg)
18242 "Go to the Emacs calendar at the current date.
18243 If there is a time stamp in the current line, go to that date.
18244 A prefix ARG can be used to force the current date."
18245 (interactive "P")
18246 (let ((tsr org-ts-regexp) diff
18247 (calendar-move-hook nil)
18248 (calendar-view-holidays-initially-flag nil)
18249 (calendar-view-diary-initially-flag nil))
18250 (when (or (org-at-timestamp-p)
18251 (save-excursion
18252 (beginning-of-line 1)
18253 (looking-at (concat ".*" tsr))))
18254 (let ((d1 (time-to-days (current-time)))
18255 (d2 (time-to-days
18256 (org-time-string-to-time (match-string 1)))))
18257 (setq diff (- d2 d1))))
18258 (calendar)
18259 (calendar-goto-today)
18260 (when (and diff (not arg)) (calendar-forward-day diff))))
18262 (defun org-get-date-from-calendar ()
18263 "Return a list (month day year) of date at point in calendar."
18264 (with-current-buffer "*Calendar*"
18265 (save-match-data
18266 (calendar-cursor-to-date))))
18268 (defun org-date-from-calendar ()
18269 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18270 If there is already a time stamp at the cursor position, update it."
18271 (interactive)
18272 (if (org-at-timestamp-p t)
18273 (org-timestamp-change 0 'calendar)
18274 (let ((cal-date (org-get-date-from-calendar)))
18275 (org-insert-time-stamp
18276 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18278 (defcustom org-effort-durations
18279 `(("min" . 1)
18280 ("h" . 60)
18281 ("d" . ,(* 60 8))
18282 ("w" . ,(* 60 8 5))
18283 ("m" . ,(* 60 8 5 4))
18284 ("y" . ,(* 60 8 5 40)))
18285 "Conversion factor to minutes for an effort modifier.
18287 Each entry has the form (MODIFIER . MINUTES).
18289 In an effort string, a number followed by MODIFIER is multiplied
18290 by the specified number of MINUTES to obtain an effort in
18291 minutes.
18293 For example, if the value of this variable is ((\"hours\" . 60)), then an
18294 effort string \"2hours\" is equivalent to 120 minutes."
18295 :group 'org-agenda
18296 :version "25.1"
18297 :package-version '(Org . "8.3")
18298 :type '(alist :key-type (string :tag "Modifier")
18299 :value-type (number :tag "Minutes")))
18301 (defun org-minutes-to-clocksum-string (m)
18302 "Format number of minutes as a clocksum string.
18303 The format is determined by `org-time-clocksum-format',
18304 `org-time-clocksum-use-fractional' and
18305 `org-time-clocksum-fractional-format' and
18306 `org-time-clocksum-use-effort-durations'."
18307 (let ((clocksum "")
18308 (m (round m)) ; Don't allow fractions of minutes
18309 h d w mo y fmt n)
18310 (setq h (if org-time-clocksum-use-effort-durations
18311 (cdr (assoc "h" org-effort-durations)) 60)
18312 d (if org-time-clocksum-use-effort-durations
18313 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18314 w (if org-time-clocksum-use-effort-durations
18315 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18316 mo (if org-time-clocksum-use-effort-durations
18317 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18318 y (if org-time-clocksum-use-effort-durations
18319 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18320 ;; fractional format
18321 (if org-time-clocksum-use-fractional
18322 (cond
18323 ;; single format string
18324 ((stringp org-time-clocksum-fractional-format)
18325 (format org-time-clocksum-fractional-format (/ m (float h))))
18326 ;; choice of fractional formats for different time units
18327 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18328 (> (/ (truncate m) (* y d h)) 0))
18329 (format fmt (/ m (* y d (float h)))))
18330 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18331 (> (/ (truncate m) (* mo d h)) 0))
18332 (format fmt (/ m (* mo d (float h)))))
18333 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18334 (> (/ (truncate m) (* w d h)) 0))
18335 (format fmt (/ m (* w d (float h)))))
18336 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18337 (> (/ (truncate m) (* d h)) 0))
18338 (format fmt (/ m (* d (float h)))))
18339 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18340 (> (/ (truncate m) h) 0))
18341 (format fmt (/ m (float h))))
18342 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18343 (format fmt m))
18344 ;; fall back to smallest time unit with a format
18345 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18346 (format fmt (/ m (float h))))
18347 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18348 (format fmt (/ m (* d (float h)))))
18349 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18350 (format fmt (/ m (* w d (float h)))))
18351 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18352 (format fmt (/ m (* mo d (float h)))))
18353 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18354 (format fmt (/ m (* y d (float h))))))
18355 ;; standard (non-fractional) format, with single format string
18356 (if (stringp org-time-clocksum-format)
18357 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18358 ;; separate formats components
18359 (and (setq fmt (plist-get org-time-clocksum-format :years))
18360 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18361 (plist-get org-time-clocksum-format :require-years))
18362 (setq clocksum (concat clocksum (format fmt n))
18363 m (- m (* n y d h))))
18364 (and (setq fmt (plist-get org-time-clocksum-format :months))
18365 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18366 (plist-get org-time-clocksum-format :require-months))
18367 (setq clocksum (concat clocksum (format fmt n))
18368 m (- m (* n mo d h))))
18369 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18370 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18371 (plist-get org-time-clocksum-format :require-weeks))
18372 (setq clocksum (concat clocksum (format fmt n))
18373 m (- m (* n w d h))))
18374 (and (setq fmt (plist-get org-time-clocksum-format :days))
18375 (or (> (setq n (/ (truncate m) (* d h))) 0)
18376 (plist-get org-time-clocksum-format :require-days))
18377 (setq clocksum (concat clocksum (format fmt n))
18378 m (- m (* n d h))))
18379 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18380 (or (> (setq n (/ (truncate m) h)) 0)
18381 (plist-get org-time-clocksum-format :require-hours))
18382 (setq clocksum (concat clocksum (format fmt n))
18383 m (- m (* n h))))
18384 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18385 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18386 (setq clocksum (concat clocksum (format fmt m))))
18387 ;; return formatted time duration
18388 clocksum))))
18390 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18391 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18392 "Org mode version 8.0")
18394 (defun org-hours-to-clocksum-string (n)
18395 (org-minutes-to-clocksum-string (* n 60)))
18397 (defun org-hh:mm-string-to-minutes (s)
18398 "Convert a string H:MM to a number of minutes.
18399 If the string is just a number, interpret it as minutes.
18400 In fact, the first hh:mm or number in the string will be taken,
18401 there can be extra stuff in the string.
18402 If no number is found, the return value is 0."
18403 (cond
18404 ((integerp s) s)
18405 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18406 (+ (* (string-to-number (match-string 1 s)) 60)
18407 (string-to-number (match-string 2 s))))
18408 ((string-match "\\([0-9]+\\)" s)
18409 (string-to-number (match-string 1 s)))
18410 (t 0)))
18412 (defcustom org-image-actual-width t
18413 "Should we use the actual width of images when inlining them?
18415 When set to t, always use the image width.
18417 When set to a number, use imagemagick (when available) to set
18418 the image's width to this value.
18420 When set to a number in a list, try to get the width from any
18421 #+ATTR.* keyword if it matches a width specification like
18423 #+ATTR_HTML: :width 300px
18425 and fall back on that number if none is found.
18427 When set to nil, try to get the width from an #+ATTR.* keyword
18428 and fall back on the original width if none is found.
18430 This requires Emacs >= 24.1, build with imagemagick support."
18431 :group 'org-appearance
18432 :version "24.4"
18433 :package-version '(Org . "8.0")
18434 :type '(choice
18435 (const :tag "Use the image width" t)
18436 (integer :tag "Use a number of pixels")
18437 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18438 (const :tag "Use #+ATTR* or don't resize" nil)))
18440 (defcustom org-agenda-inhibit-startup nil
18441 "Inhibit startup when preparing agenda buffers.
18442 When this variable is t, the initialization of the Org agenda
18443 buffers is inhibited: e.g. the visibility state is not set, the
18444 tables are not re-aligned, etc."
18445 :type 'boolean
18446 :version "24.3"
18447 :group 'org-agenda)
18449 (define-obsolete-variable-alias
18450 'org-agenda-ignore-drawer-properties
18451 'org-agenda-ignore-properties "25.1")
18453 (defcustom org-agenda-ignore-properties nil
18454 "Avoid updating text properties when building the agenda.
18455 Properties are used to prepare buffers for effort estimates,
18456 appointments, statistics and subtree-local categories.
18457 If you don't use these in the agenda, you can add them to this
18458 list and agenda building will be a bit faster.
18459 The value is a list, with zero or more of the symbols `effort', `appt',
18460 `stats' or `category'."
18461 :type '(set :greedy t
18462 (const effort)
18463 (const appt)
18464 (const stats)
18465 (const category))
18466 :version "25.1"
18467 :package-version '(Org . "8.3")
18468 :group 'org-agenda)
18470 (defun org-duration-string-to-minutes (s &optional output-to-string)
18471 "Convert a duration string S to minutes.
18473 A bare number is interpreted as minutes, modifiers can be set by
18474 customizing `org-effort-durations' (which see).
18476 Entries containing a colon are interpreted as H:MM by
18477 `org-hh:mm-string-to-minutes'."
18478 (let ((result 0)
18479 (re (concat "\\([0-9.]+\\) *\\("
18480 (regexp-opt (mapcar 'car org-effort-durations))
18481 "\\)")))
18482 (while (string-match re s)
18483 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18484 (string-to-number (match-string 1 s))))
18485 (setq s (replace-match "" nil t s)))
18486 (setq result (floor result))
18487 (cl-incf result (org-hh:mm-string-to-minutes s))
18488 (if output-to-string (number-to-string result) result)))
18490 ;;;; Files
18492 (defun org-save-all-org-buffers ()
18493 "Save all Org-mode buffers without user confirmation."
18494 (interactive)
18495 (message "Saving all Org-mode buffers...")
18496 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18497 (when (featurep 'org-id) (org-id-locations-save))
18498 (message "Saving all Org-mode buffers... done"))
18500 (defun org-revert-all-org-buffers ()
18501 "Revert all Org-mode buffers.
18502 Prompt for confirmation when there are unsaved changes.
18503 Be sure you know what you are doing before letting this function
18504 overwrite your changes.
18506 This function is useful in a setup where one tracks org files
18507 with a version control system, to revert on one machine after pulling
18508 changes from another. I believe the procedure must be like this:
18510 1. M-x org-save-all-org-buffers
18511 2. Pull changes from the other machine, resolve conflicts
18512 3. M-x org-revert-all-org-buffers"
18513 (interactive)
18514 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18515 (user-error "Abort"))
18516 (save-excursion
18517 (save-window-excursion
18518 (dolist (b (buffer-list))
18519 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18520 (with-current-buffer b buffer-file-name))
18521 (org-pop-to-buffer-same-window b)
18522 (revert-buffer t 'no-confirm)))
18523 (when (and (featurep 'org-id) org-id-track-globally)
18524 (org-id-locations-load)))))
18526 ;;;; Agenda files
18528 ;;;###autoload
18529 (defun org-switchb (&optional arg)
18530 "Switch between Org buffers.
18532 With \\[universal-argument] prefix, restrict available buffers to files.
18534 With \\[universal-argument] \\[universal-argument] \
18535 prefix, restrict available buffers to agenda files."
18536 (interactive "P")
18537 (let ((blist (org-buffer-list
18538 (cond ((equal arg '(4)) 'files)
18539 ((equal arg '(16)) 'agenda)))))
18540 (org-pop-to-buffer-same-window
18541 (completing-read "Org buffer: "
18542 (mapcar #'list (mapcar #'buffer-name blist))
18543 nil t))))
18545 (defun org-buffer-list (&optional predicate exclude-tmp)
18546 "Return a list of Org buffers.
18547 PREDICATE can be `export', `files' or `agenda'.
18549 export restrict the list to Export buffers.
18550 files restrict the list to buffers visiting Org files.
18551 agenda restrict the list to buffers visiting agenda files.
18553 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18554 (let* ((bfn nil)
18555 (agenda-files (and (eq predicate 'agenda)
18556 (mapcar 'file-truename (org-agenda-files t))))
18557 (filter
18558 (cond
18559 ((eq predicate 'files)
18560 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18561 ((eq predicate 'export)
18562 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18563 ((eq predicate 'agenda)
18564 (lambda (b)
18565 (with-current-buffer b
18566 (and (derived-mode-p 'org-mode)
18567 (setq bfn (buffer-file-name b))
18568 (member (file-truename bfn) agenda-files)))))
18569 (t (lambda (b) (with-current-buffer b
18570 (or (derived-mode-p 'org-mode)
18571 (string-match "\\*Org .*Export"
18572 (buffer-name b)))))))))
18573 (delq nil
18574 (mapcar
18575 (lambda(b)
18576 (if (and (funcall filter b)
18577 (or (not exclude-tmp)
18578 (not (string-match "tmp" (buffer-name b)))))
18580 nil))
18581 (buffer-list)))))
18583 (defun org-agenda-files (&optional unrestricted archives)
18584 "Get the list of agenda files.
18585 Optional UNRESTRICTED means return the full list even if a restriction
18586 is currently in place.
18587 When ARCHIVES is t, include all archive files that are really being
18588 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18589 `org-agenda-archives-mode' is t."
18590 (let ((files
18591 (cond
18592 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18593 ((stringp org-agenda-files) (org-read-agenda-file-list))
18594 ((listp org-agenda-files) org-agenda-files)
18595 (t (error "Invalid value of `org-agenda-files'")))))
18596 (setq files (apply 'append
18597 (mapcar (lambda (f)
18598 (if (file-directory-p f)
18599 (directory-files
18600 f t org-agenda-file-regexp)
18601 (list f)))
18602 files)))
18603 (when org-agenda-skip-unavailable-files
18604 (setq files (delq nil
18605 (mapcar (function
18606 (lambda (file)
18607 (and (file-readable-p file) file)))
18608 files))))
18609 (when (or (eq archives t)
18610 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18611 (setq files (org-add-archive-files files)))
18612 files))
18614 (defun org-agenda-file-p (&optional file)
18615 "Return non-nil, if FILE is an agenda file.
18616 If FILE is omitted, use the file associated with the current
18617 buffer."
18618 (let ((fname (or file (buffer-file-name))))
18619 (and fname
18620 (member (file-truename fname)
18621 (mapcar #'file-truename (org-agenda-files t))))))
18623 (defun org-edit-agenda-file-list ()
18624 "Edit the list of agenda files.
18625 Depending on setup, this either uses customize to edit the variable
18626 `org-agenda-files', or it visits the file that is holding the list. In the
18627 latter case, the buffer is set up in a way that saving it automatically kills
18628 the buffer and restores the previous window configuration."
18629 (interactive)
18630 (if (stringp org-agenda-files)
18631 (let ((cw (current-window-configuration)))
18632 (find-file org-agenda-files)
18633 (setq-local org-window-configuration cw)
18634 (add-hook 'after-save-hook
18635 (lambda ()
18636 (set-window-configuration
18637 (prog1 org-window-configuration
18638 (kill-buffer (current-buffer))))
18639 (org-install-agenda-files-menu)
18640 (message "New agenda file list installed"))
18641 nil 'local)
18642 (message "%s" (substitute-command-keys
18643 "Edit list and finish with \\[save-buffer]")))
18644 (customize-variable 'org-agenda-files)))
18646 (defun org-store-new-agenda-file-list (list)
18647 "Set new value for the agenda file list and save it correctly."
18648 (if (stringp org-agenda-files)
18649 (let ((fe (org-read-agenda-file-list t)) b u)
18650 (while (setq b (find-buffer-visiting org-agenda-files))
18651 (kill-buffer b))
18652 (with-temp-file org-agenda-files
18653 (insert
18654 (mapconcat
18655 (lambda (f) ;; Keep un-expanded entries.
18656 (if (setq u (assoc f fe))
18657 (cdr u)
18659 list "\n")
18660 "\n")))
18661 (let ((org-mode-hook nil) (org-inhibit-startup t)
18662 (org-insert-mode-line-in-empty-file nil))
18663 (setq org-agenda-files list)
18664 (customize-save-variable 'org-agenda-files org-agenda-files))))
18666 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18667 "Read the list of agenda files from a file.
18668 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18669 filenames, used by `org-store-new-agenda-file-list' to write back
18670 un-expanded file names."
18671 (when (file-directory-p org-agenda-files)
18672 (error "`org-agenda-files' cannot be a single directory"))
18673 (when (stringp org-agenda-files)
18674 (with-temp-buffer
18675 (insert-file-contents org-agenda-files)
18676 (mapcar
18677 (lambda (f)
18678 (let ((e (expand-file-name (substitute-in-file-name f)
18679 org-directory)))
18680 (if pair-with-expansion
18681 (cons e f)
18682 e)))
18683 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18685 ;;;###autoload
18686 (defun org-cycle-agenda-files ()
18687 "Cycle through the files in `org-agenda-files'.
18688 If the current buffer visits an agenda file, find the next one in the list.
18689 If the current buffer does not, find the first agenda file."
18690 (interactive)
18691 (let* ((fs (or (org-agenda-files t)
18692 (user-error "No agenda files")))
18693 (files (copy-sequence fs))
18694 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18695 file)
18696 (when tcf
18697 (while (and (setq file (pop files))
18698 (not (equal (file-truename file) tcf)))))
18699 (find-file (car (or files fs)))
18700 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18702 (defun org-agenda-file-to-front (&optional to-end)
18703 "Move/add the current file to the top of the agenda file list.
18704 If the file is not present in the list, it is added to the front. If it is
18705 present, it is moved there. With optional argument TO-END, add/move to the
18706 end of the list."
18707 (interactive "P")
18708 (let ((org-agenda-skip-unavailable-files nil)
18709 (file-alist (mapcar (lambda (x)
18710 (cons (file-truename x) x))
18711 (org-agenda-files t)))
18712 (ctf (file-truename
18713 (or buffer-file-name
18714 (user-error "Please save the current buffer to a file"))))
18715 x had)
18716 (setq x (assoc ctf file-alist) had x)
18718 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18719 (if to-end
18720 (setq file-alist (append (delq x file-alist) (list x)))
18721 (setq file-alist (cons x (delq x file-alist))))
18722 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18723 (org-install-agenda-files-menu)
18724 (message "File %s to %s of agenda file list"
18725 (if had "moved" "added") (if to-end "end" "front"))))
18727 (defun org-remove-file (&optional file)
18728 "Remove current file from the list of files in variable `org-agenda-files'.
18729 These are the files which are being checked for agenda entries.
18730 Optional argument FILE means use this file instead of the current."
18731 (interactive)
18732 (let* ((org-agenda-skip-unavailable-files nil)
18733 (file (or file buffer-file-name
18734 (user-error "Current buffer does not visit a file")))
18735 (true-file (file-truename file))
18736 (afile (abbreviate-file-name file))
18737 (files (delq nil (mapcar
18738 (lambda (x)
18739 (unless (equal true-file
18740 (file-truename x))
18742 (org-agenda-files t)))))
18743 (if (not (= (length files) (length (org-agenda-files t))))
18744 (progn
18745 (org-store-new-agenda-file-list files)
18746 (org-install-agenda-files-menu)
18747 (message "Removed from Org Agenda list: %s" afile))
18748 (message "File was not in list: %s (not removed)" afile))))
18750 (defun org-file-menu-entry (file)
18751 (vector file (list 'find-file file) t))
18753 (defun org-check-agenda-file (file)
18754 "Make sure FILE exists. If not, ask user what to do."
18755 (unless (file-exists-p file)
18756 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18757 (abbreviate-file-name file))
18758 (let ((r (downcase (read-char-exclusive))))
18759 (cond
18760 ((equal r ?r)
18761 (org-remove-file file)
18762 (throw 'nextfile t))
18763 (t (user-error "Abort"))))))
18765 (defun org-get-agenda-file-buffer (file)
18766 "Get an agenda buffer visiting FILE.
18767 If the buffer needs to be created, add it to the list of buffers
18768 which might be released later."
18769 (let ((buf (org-find-base-buffer-visiting file)))
18770 (if buf
18771 buf ; just return it
18772 ;; Make a new buffer and remember it
18773 (setq buf (find-file-noselect file))
18774 (when buf (push buf org-agenda-new-buffers))
18775 buf)))
18777 (defun org-release-buffers (blist)
18778 "Release all buffers in list, asking the user for confirmation when needed.
18779 When a buffer is unmodified, it is just killed. When modified, it is saved
18780 \(if the user agrees) and then killed."
18781 (let (file)
18782 (dolist (buf blist)
18783 (setq file (buffer-file-name buf))
18784 (when (and (buffer-modified-p buf)
18785 file
18786 (y-or-n-p (format "Save file %s? " file)))
18787 (with-current-buffer buf (save-buffer)))
18788 (kill-buffer buf))))
18790 (defun org-agenda-prepare-buffers (files)
18791 "Create buffers for all agenda files, protect archived trees and comments."
18792 (interactive)
18793 (let ((pa '(:org-archived t))
18794 (pc '(:org-comment t))
18795 (pall '(:org-archived t :org-comment t))
18796 (inhibit-read-only t)
18797 (org-inhibit-startup org-agenda-inhibit-startup)
18798 (rea (concat ":" org-archive-tag ":"))
18799 re pos)
18800 (setq org-tag-alist-for-agenda nil
18801 org-tag-groups-alist-for-agenda nil)
18802 (save-excursion
18803 (save-restriction
18804 (dolist (file files)
18805 (catch 'nextfile
18806 (if (bufferp file)
18807 (set-buffer file)
18808 (org-check-agenda-file file)
18809 (set-buffer (org-get-agenda-file-buffer file)))
18810 (widen)
18811 (org-set-regexps-and-options 'tags-only)
18812 (setq pos (point))
18813 (or (memq 'category org-agenda-ignore-properties)
18814 (org-refresh-category-properties))
18815 (or (memq 'stats org-agenda-ignore-properties)
18816 (org-refresh-stats-properties))
18817 (or (memq 'effort org-agenda-ignore-properties)
18818 (org-refresh-effort-properties))
18819 (or (memq 'appt org-agenda-ignore-properties)
18820 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18821 (setq org-todo-keywords-for-agenda
18822 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18823 (setq org-done-keywords-for-agenda
18824 (append org-done-keywords-for-agenda org-done-keywords))
18825 (setq org-todo-keyword-alist-for-agenda
18826 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18827 (setq org-tag-alist-for-agenda
18828 (org-uniquify
18829 (append org-tag-alist-for-agenda
18830 org-current-tag-alist)))
18831 ;; Merge current file's tag groups into global
18832 ;; `org-tag-groups-alist-for-agenda'.
18833 (when org-group-tags
18834 (dolist (alist org-tag-groups-alist)
18835 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18836 (if old
18837 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18838 (push alist org-tag-groups-alist-for-agenda)))))
18839 (org-with-silent-modifications
18840 (save-excursion
18841 (remove-text-properties (point-min) (point-max) pall)
18842 (when org-agenda-skip-archived-trees
18843 (goto-char (point-min))
18844 (while (re-search-forward rea nil t)
18845 (when (org-at-heading-p t)
18846 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18847 (goto-char (point-min))
18848 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18849 (while (re-search-forward re nil t)
18850 (when (save-match-data (org-in-commented-heading-p t))
18851 (add-text-properties
18852 (match-beginning 0) (org-end-of-subtree t) pc)))))
18853 (goto-char pos)))))
18854 (setq org-todo-keywords-for-agenda
18855 (org-uniquify org-todo-keywords-for-agenda))
18856 (setq org-todo-keyword-alist-for-agenda
18857 (org-uniquify org-todo-keyword-alist-for-agenda))))
18860 ;;;; CDLaTeX minor mode
18862 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18863 "Keymap for the minor `org-cdlatex-mode'.")
18865 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18866 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18867 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18868 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18869 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18871 (defvar org-cdlatex-texmathp-advice-is-done nil
18872 "Flag remembering if we have applied the advice to texmathp already.")
18874 (define-minor-mode org-cdlatex-mode
18875 "Toggle the minor `org-cdlatex-mode'.
18876 This mode supports entering LaTeX environment and math in LaTeX fragments
18877 in Org-mode.
18878 \\{org-cdlatex-mode-map}"
18879 nil " OCDL" nil
18880 (when org-cdlatex-mode
18881 (require 'cdlatex)
18882 (run-hooks 'cdlatex-mode-hook)
18883 (cdlatex-compute-tables))
18884 (unless org-cdlatex-texmathp-advice-is-done
18885 (setq org-cdlatex-texmathp-advice-is-done t)
18886 (defadvice texmathp (around org-math-always-on activate)
18887 "Always return t in org-mode buffers.
18888 This is because we want to insert math symbols without dollars even outside
18889 the LaTeX math segments. If Orgmode thinks that point is actually inside
18890 an embedded LaTeX fragment, let texmathp do its job.
18891 \\[org-cdlatex-mode-map]"
18892 (interactive)
18893 (let (p)
18894 (cond
18895 ((not (derived-mode-p 'org-mode)) ad-do-it)
18896 ((eq this-command 'cdlatex-math-symbol)
18897 (setq ad-return-value t
18898 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18900 (let ((p (org-inside-LaTeX-fragment-p)))
18901 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18902 (setq ad-return-value t
18903 texmathp-why '("Org-mode embedded math" . 0))
18904 (when p ad-do-it)))))))))
18906 (defun turn-on-org-cdlatex ()
18907 "Unconditionally turn on `org-cdlatex-mode'."
18908 (org-cdlatex-mode 1))
18910 (defun org-try-cdlatex-tab ()
18911 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18912 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18913 - inside a LaTeX fragment, or
18914 - after the first word in a line, where an abbreviation expansion could
18915 insert a LaTeX environment."
18916 (when org-cdlatex-mode
18917 (cond
18918 ;; Before any word on the line: No expansion possible.
18919 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18920 ;; Just after first word on the line: Expand it. Make sure it
18921 ;; cannot happen on headlines, though.
18922 ((save-excursion
18923 (skip-chars-backward "a-zA-Z0-9*")
18924 (skip-chars-backward " \t")
18925 (and (bolp) (not (org-at-heading-p))))
18926 (cdlatex-tab) t)
18927 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18929 (defun org-cdlatex-underscore-caret (&optional _arg)
18930 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18931 Revert to the normal definition outside of these fragments."
18932 (interactive "P")
18933 (if (org-inside-LaTeX-fragment-p)
18934 (call-interactively 'cdlatex-sub-superscript)
18935 (let (org-cdlatex-mode)
18936 (call-interactively (key-binding (vector last-input-event))))))
18938 (defun org-cdlatex-math-modify (&optional _arg)
18939 "Execute `cdlatex-math-modify' in LaTeX fragments.
18940 Revert to the normal definition outside of these fragments."
18941 (interactive "P")
18942 (if (org-inside-LaTeX-fragment-p)
18943 (call-interactively 'cdlatex-math-modify)
18944 (let (org-cdlatex-mode)
18945 (call-interactively (key-binding (vector last-input-event))))))
18947 (defun org-cdlatex-environment-indent (&optional environment item)
18948 "Execute `cdlatex-environment' and indent the inserted environment.
18950 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18952 The inserted environment is indented to current indentation
18953 unless point is at the beginning of the line, in which the
18954 environment remains unintended."
18955 (interactive)
18956 ;; cdlatex-environment always return nil. Therefore, capture output
18957 ;; first and determine if an environment was selected.
18958 (let* ((beg (point-marker))
18959 (end (copy-marker (point) t))
18960 (inserted (progn
18961 (ignore-errors (cdlatex-environment environment item))
18962 (< beg end)))
18963 ;; Figure out how many lines to move forward after the
18964 ;; environment has been inserted.
18965 (lines (when inserted
18966 (save-excursion
18967 (- (cl-loop while (< beg (point))
18968 with x = 0
18969 do (forward-line -1)
18970 (cl-incf x)
18971 finally return x)
18972 (if (progn (goto-char beg)
18973 (and (progn (skip-chars-forward " \t") (eolp))
18974 (progn (skip-chars-backward " \t") (bolp))))
18975 1 0)))))
18976 (env (org-trim (delete-and-extract-region beg end))))
18977 (when inserted
18978 ;; Get indentation of next line unless at column 0.
18979 (let ((ind (if (bolp) 0
18980 (save-excursion
18981 (org-return-indent)
18982 (prog1 (org-get-indentation)
18983 (when (progn (skip-chars-forward " \t") (eolp))
18984 (delete-region beg (point)))))))
18985 (bol (progn (skip-chars-backward " \t") (bolp))))
18986 ;; Insert a newline before environment unless at column zero
18987 ;; to "escape" the current line. Insert a newline if
18988 ;; something is one the same line as \end{ENVIRONMENT}.
18989 (insert
18990 (concat (unless bol "\n") env
18991 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18992 (unless (zerop ind)
18993 (save-excursion
18994 (goto-char beg)
18995 (while (< (point) end)
18996 (unless (eolp) (indent-line-to ind))
18997 (forward-line))))
18998 (goto-char beg)
18999 (forward-line lines)
19000 (indent-line-to ind)))
19001 (set-marker beg nil)
19002 (set-marker end nil)))
19005 ;;;; LaTeX fragments
19007 (defun org-inside-LaTeX-fragment-p ()
19008 "Test if point is inside a LaTeX fragment.
19009 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19010 sequence appearing also before point.
19011 Even though the matchers for math are configurable, this function assumes
19012 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19013 delimiters are skipped when they have been removed by customization.
19014 The return value is nil, or a cons cell with the delimiter and the
19015 position of this delimiter.
19017 This function does a reasonably good job, but can locally be fooled by
19018 for example currency specifications. For example it will assume being in
19019 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19020 fragments that are properly closed, but during editing, we have to live
19021 with the uncertainty caused by missing closing delimiters. This function
19022 looks only before point, not after."
19023 (catch 'exit
19024 (let ((pos (point))
19025 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19026 (lim (progn
19027 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19028 (point)))
19029 dd-on str (start 0) m re)
19030 (goto-char pos)
19031 (when dodollar
19032 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19033 re (nth 1 (assoc "$" org-latex-regexps)))
19034 (while (string-match re str start)
19035 (cond
19036 ((= (match-end 0) (length str))
19037 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19038 ((= (match-end 0) (- (length str) 5))
19039 (throw 'exit nil))
19040 (t (setq start (match-end 0))))))
19041 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19042 (goto-char pos)
19043 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19044 (and (match-beginning 2) (throw 'exit nil))
19045 ;; count $$
19046 (while (re-search-backward "\\$\\$" lim t)
19047 (setq dd-on (not dd-on)))
19048 (goto-char pos)
19049 (when dd-on (cons "$$" m))))))
19051 (defun org-inside-latex-macro-p ()
19052 "Is point inside a LaTeX macro or its arguments?"
19053 (save-match-data
19054 (org-in-regexp
19055 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19057 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19058 "Build an overlay between BEG and END using IMAGE file.
19059 Argument IMAGETYPE is the extension of the displayed image,
19060 as a string. It defaults to \"png\"."
19061 (let ((ov (make-overlay beg end))
19062 (imagetype (or (intern imagetype) 'png)))
19063 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19064 (overlay-put ov 'evaporate t)
19065 (overlay-put ov
19066 'modification-hooks
19067 (list (lambda (o _flag _beg _end &optional _l)
19068 (delete-overlay o))))
19069 (overlay-put ov
19070 'display
19071 (list 'image :type imagetype :file image :ascent 'center))))
19073 (defun org--list-latex-overlays (&optional beg end)
19074 "List all Org LaTeX overlays in current buffer.
19075 Limit to overlays between BEG and END when those are provided."
19076 (cl-remove-if-not
19077 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19078 (overlays-in (or beg (point-min)) (or end (point-max)))))
19080 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19081 "Remove all overlays with LaTeX fragment images in current buffer.
19082 When optional arguments BEG and END are non-nil, remove all
19083 overlays between them instead. Return a non-nil value when some
19084 overlays were removed, nil otherwise."
19085 (let ((overlays (org--list-latex-overlays beg end)))
19086 (mapc #'delete-overlay overlays)
19087 overlays))
19089 (define-obsolete-function-alias
19090 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
19091 (defun org-toggle-latex-fragment (&optional arg)
19092 "Preview the LaTeX fragment at point, or all locally or globally.
19094 If the cursor is on a LaTeX fragment, create the image and overlay
19095 it over the source code, if there is none. Remove it otherwise.
19096 If there is no fragment at point, display all fragments in the
19097 current section.
19099 With prefix ARG, preview or clear image for all fragments in the
19100 current subtree or in the whole buffer when used before the first
19101 headline. With a double prefix ARG \\[universal-argument] \
19102 \\[universal-argument] preview or clear images
19103 for all fragments in the buffer."
19104 (interactive "P")
19105 (when (display-graphic-p)
19106 (catch 'exit
19107 (save-excursion
19108 (let ((window-start (window-start)) msg)
19109 (save-restriction
19110 (cond
19111 ((or (equal arg '(16))
19112 (and (equal arg '(4))
19113 (org-with-limited-levels (org-before-first-heading-p))))
19114 (if (org-remove-latex-fragment-image-overlays)
19115 (progn (message "LaTeX fragments images removed from buffer")
19116 (throw 'exit nil))
19117 (setq msg "Creating images for buffer...")))
19118 ((equal arg '(4))
19119 (org-with-limited-levels (org-back-to-heading t))
19120 (let ((beg (point))
19121 (end (progn (org-end-of-subtree t) (point))))
19122 (if (org-remove-latex-fragment-image-overlays beg end)
19123 (progn
19124 (message "LaTeX fragment images removed from subtree")
19125 (throw 'exit nil))
19126 (setq msg "Creating images for subtree...")
19127 (narrow-to-region beg end))))
19128 ((let ((datum (org-element-context)))
19129 (when (memq (org-element-type datum)
19130 '(latex-environment latex-fragment))
19131 (let* ((beg (org-element-property :begin datum))
19132 (end (org-element-property :end datum)))
19133 (if (org-remove-latex-fragment-image-overlays beg end)
19134 (progn (message "LaTeX fragment image removed")
19135 (throw 'exit nil))
19136 (narrow-to-region beg end)
19137 (setq msg "Creating image..."))))))
19139 (org-with-limited-levels
19140 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19141 (outline-previous-heading)
19142 (point)))
19143 (end (progn (outline-next-heading) (point))))
19144 (if (org-remove-latex-fragment-image-overlays beg end)
19145 (progn
19146 (message "LaTeX fragment images removed from section")
19147 (throw 'exit nil))
19148 (setq msg "Creating images for section...")
19149 (narrow-to-region beg end))))))
19150 (let ((file (buffer-file-name (buffer-base-buffer))))
19151 (org-format-latex
19152 (concat org-preview-latex-image-directory "org-ltximg")
19153 ;; Emacs cannot overlay images from remote hosts.
19154 ;; Create it in `temporary-file-directory' instead.
19155 (if (or (not file) (file-remote-p file))
19156 temporary-file-directory
19157 default-directory)
19158 'overlays msg 'forbuffer org-preview-latex-default-process)))
19159 ;; Work around a bug that doesn't restore window's start
19160 ;; when widening back the buffer.
19161 (set-window-start nil window-start)
19162 (message (concat msg "done")))))))
19164 (defun org-format-latex
19165 (prefix &optional dir overlays msg forbuffer processing-type)
19166 "Replace LaTeX fragments with links to an image, and produce images.
19168 When optional argument OVERLAYS is non-nil, display the image on
19169 top of the fragment instead of replacing it.
19171 PROCESSING-TYPE is the conversion method to use, as a symbol.
19173 Some of the options can be changed using the variable
19174 `org-format-latex-options', which see."
19175 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19176 (unless (eq processing-type 'verbatim)
19177 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19178 (cnt 0)
19179 checkdir-flag)
19180 (goto-char (point-min))
19181 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19182 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19183 (overlay-recenter (point-max)))
19184 (while (re-search-forward math-regexp nil t)
19185 (unless (and overlays
19186 (eq (get-char-property (point) 'org-overlay-type)
19187 'org-latex-overlay))
19188 (let* ((context (org-element-context))
19189 (type (org-element-type context)))
19190 (when (memq type '(latex-environment latex-fragment))
19191 (let ((block-type (eq type 'latex-environment))
19192 (value (org-element-property :value context))
19193 (beg (org-element-property :begin context))
19194 (end (save-excursion
19195 (goto-char (org-element-property :end context))
19196 (skip-chars-backward " \r\t\n")
19197 (point))))
19198 (cond
19199 ((eq processing-type 'mathjax)
19200 ;; Prepare for MathJax processing.
19201 (if (not (string-match "\\`\\$\\$?" value))
19202 (goto-char end)
19203 (delete-region beg end)
19204 (if (string= (match-string 0 value) "$$")
19205 (insert "\\[" (substring value 2 -2) "\\]")
19206 (insert "\\(" (substring value 1 -1) "\\)"))))
19207 ((assq processing-type org-preview-latex-process-alist)
19208 ;; Process to an image.
19209 (cl-incf cnt)
19210 (goto-char beg)
19211 (let* ((processing-info
19212 (cdr (assq processing-type org-preview-latex-process-alist)))
19213 (face (face-at-point))
19214 ;; Get the colors from the face at point.
19216 (let ((color (plist-get org-format-latex-options
19217 :foreground)))
19218 (if (and forbuffer (eq color 'auto))
19219 (face-attribute face :foreground nil 'default)
19220 color)))
19222 (let ((color (plist-get org-format-latex-options
19223 :background)))
19224 (if (and forbuffer (eq color 'auto))
19225 (face-attribute face :background nil 'default)
19226 color)))
19227 (hash (sha1 (prin1-to-string
19228 (list org-format-latex-header
19229 org-latex-default-packages-alist
19230 org-latex-packages-alist
19231 org-format-latex-options
19232 forbuffer value fg bg))))
19233 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19234 (absprefix (expand-file-name prefix dir))
19235 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19236 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19237 (sep (and block-type "\n\n"))
19238 (link (concat sep "[[file:" linkfile "]]" sep))
19239 (options
19240 (org-combine-plists
19241 org-format-latex-options
19242 `(:foreground ,fg :background ,bg))))
19243 (when msg (message msg cnt))
19244 (unless checkdir-flag ; Ensure the directory exists.
19245 (setq checkdir-flag t)
19246 (let ((todir (file-name-directory absprefix)))
19247 (unless (file-directory-p todir)
19248 (make-directory todir t))))
19249 (unless (file-exists-p movefile)
19250 (org-create-formula-image
19251 value movefile options forbuffer processing-type))
19252 (if overlays
19253 (progn
19254 (dolist (o (overlays-in beg end))
19255 (when (eq (overlay-get o 'org-overlay-type)
19256 'org-latex-overlay)
19257 (delete-overlay o)))
19258 (org--format-latex-make-overlay beg end movefile imagetype)
19259 (goto-char end))
19260 (delete-region beg end)
19261 (insert
19262 (org-add-props link
19263 (list 'org-latex-src
19264 (replace-regexp-in-string "\"" "" value)
19265 'org-latex-src-embed-type
19266 (if block-type 'paragraph 'character)))))))
19267 ((eq processing-type 'mathml)
19268 ;; Process to MathML.
19269 (unless (org-format-latex-mathml-available-p)
19270 (user-error "LaTeX to MathML converter not configured"))
19271 (cl-incf cnt)
19272 (when msg (message msg cnt))
19273 (goto-char beg)
19274 (delete-region beg end)
19275 (insert (org-format-latex-as-mathml
19276 value block-type prefix dir)))
19278 (error "Unknown conversion process %s for LaTeX fragments"
19279 processing-type)))))))))))
19281 (defun org-create-math-formula (latex-frag &optional mathml-file)
19282 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19283 Use `org-latex-to-mathml-convert-command'. If the conversion is
19284 sucessful, return the portion between \"<math...> </math>\"
19285 elements otherwise return nil. When MATHML-FILE is specified,
19286 write the results in to that file. When invoked as an
19287 interactive command, prompt for LATEX-FRAG, with initial value
19288 set to the current active region and echo the results for user
19289 inspection."
19290 (interactive (list (let ((frag (when (org-region-active-p)
19291 (buffer-substring-no-properties
19292 (region-beginning) (region-end)))))
19293 (read-string "LaTeX Fragment: " frag nil frag))))
19294 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19295 (let* ((tmp-in-file
19296 (let ((file (file-relative-name
19297 (make-temp-name (expand-file-name "ltxmathml-in")))))
19298 (write-region latex-frag nil file)
19299 file))
19300 (tmp-out-file (file-relative-name
19301 (make-temp-name (expand-file-name "ltxmathml-out"))))
19302 (cmd (format-spec
19303 org-latex-to-mathml-convert-command
19304 `((?j . ,(and org-latex-to-mathml-jar-file
19305 (shell-quote-argument
19306 (expand-file-name
19307 org-latex-to-mathml-jar-file))))
19308 (?I . ,(shell-quote-argument tmp-in-file))
19309 (?i . ,latex-frag)
19310 (?o . ,(shell-quote-argument tmp-out-file)))))
19311 mathml shell-command-output)
19312 (when (org-called-interactively-p 'any)
19313 (unless (org-format-latex-mathml-available-p)
19314 (user-error "LaTeX to MathML converter not configured")))
19315 (message "Running %s" cmd)
19316 (setq shell-command-output (shell-command-to-string cmd))
19317 (setq mathml
19318 (when (file-readable-p tmp-out-file)
19319 (with-current-buffer (find-file-noselect tmp-out-file t)
19320 (goto-char (point-min))
19321 (when (re-search-forward
19322 (concat
19323 (regexp-quote
19324 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19325 "[^>]*?>"
19326 "\\(.\\|\n\\)*"
19327 "</math>")
19328 nil t)
19329 (prog1 (match-string 0) (kill-buffer))))))
19330 (cond
19331 (mathml
19332 (setq mathml
19333 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19334 (when mathml-file
19335 (write-region mathml nil mathml-file))
19336 (when (org-called-interactively-p 'any)
19337 (message mathml)))
19338 ((message "LaTeX to MathML conversion failed")
19339 (message shell-command-output)))
19340 (delete-file tmp-in-file)
19341 (when (file-exists-p tmp-out-file)
19342 (delete-file tmp-out-file))
19343 mathml))
19345 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19346 prefix &optional dir)
19347 "Use `org-create-math-formula' but check local cache first."
19348 (let* ((absprefix (expand-file-name prefix dir))
19349 (print-length nil) (print-level nil)
19350 (formula-id (concat
19351 "formula-"
19352 (sha1
19353 (prin1-to-string
19354 (list latex-frag
19355 org-latex-to-mathml-convert-command)))))
19356 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19357 (formula-cache-dir (file-name-directory formula-cache)))
19359 (unless (file-directory-p formula-cache-dir)
19360 (make-directory formula-cache-dir t))
19362 (unless (file-exists-p formula-cache)
19363 (org-create-math-formula latex-frag formula-cache))
19365 (if (file-exists-p formula-cache)
19366 ;; Successful conversion. Return the link to MathML file.
19367 (org-add-props
19368 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19369 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19370 'org-latex-src-embed-type (if latex-frag-type
19371 'paragraph 'character)))
19372 ;; Failed conversion. Return the LaTeX fragment verbatim
19373 latex-frag)))
19375 (declare-function org-export-get-backend "ox" (name))
19376 (declare-function org-export--get-global-options "ox" (&optional backend))
19377 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19378 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19379 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19380 (defun org-create-formula--latex-header ()
19381 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19382 (let ((info (org-combine-plists (org-export--get-global-options
19383 (org-export-get-backend 'latex))
19384 (org-export--get-inbuffer-options
19385 (org-export-get-backend 'latex)))))
19386 (org-latex-guess-babel-language
19387 (org-latex-guess-inputenc
19388 (org-splice-latex-header
19389 org-format-latex-header
19390 org-latex-default-packages-alist
19391 org-latex-packages-alist t
19392 (plist-get info :latex-header)))
19393 info)))
19395 (defun org--get-display-dpi ()
19396 "Get the DPI of the display.
19398 Assumes that the display has the same pixel width in the
19399 horizontal and vertical directions."
19400 (if (display-graphic-p)
19401 (round (/ (display-pixel-height)
19402 (/ (display-mm-height) 25.4)))
19403 (error "Attempt to calculate the dpi of a non-graphic display")))
19405 (defun org-create-formula-image
19406 (string tofile options buffer &optional processing-type)
19407 "Create an image from LaTeX source using external processes.
19409 The LaTeX STRING is saved to a temporary LaTeX file, then
19410 converted to an image file by process PROCESSING-TYPE defined in
19411 `org-preview-latex-process-alist'. A nil value defaults to
19412 `org-preview-latex-default-process'.
19414 The generated image file is eventually moved to TOFILE.
19416 The OPTIONS argument controls the size, foreground color and
19417 background color of the generated image.
19419 When BUFFER non-nil, this function is used for LaTeX previewing.
19420 Otherwise, it is used to deal with LaTeX snippets showed in
19421 a HTML file."
19422 (let* ((processing-type (or processing-type
19423 org-preview-latex-default-process))
19424 (processing-info
19425 (cdr (assq processing-type org-preview-latex-process-alist)))
19426 (programs (plist-get processing-info :programs))
19427 (error-message (or (plist-get processing-info :message) ""))
19428 (use-xcolor (plist-get processing-info :use-xcolor))
19429 (image-input-type (plist-get processing-info :image-input-type))
19430 (image-output-type (plist-get processing-info :image-output-type))
19431 (post-clean (or (plist-get processing-info :post-clean)
19432 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19433 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19434 (latex-header (or (plist-get processing-info :latex-header)
19435 (org-create-formula--latex-header)))
19436 (latex-compiler (plist-get processing-info :latex-compiler))
19437 (image-converter (plist-get processing-info :image-converter))
19438 (tmpdir temporary-file-directory)
19439 (texfilebase (make-temp-name
19440 (expand-file-name "orgtex" tmpdir)))
19441 (texfile (concat texfilebase ".tex"))
19442 (font-height (face-attribute 'default :height nil))
19443 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19444 '(1.0 . 1.0)))
19445 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19446 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19447 (dpi (* scale (floor (if buffer font-height 140.0))))
19448 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19449 "Black"))
19450 (bg (or (plist-get options (if buffer :background :html-background))
19451 "Transparent"))
19452 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19453 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19454 (dolist (program programs)
19455 (org-check-external-command program error-message))
19456 (if use-xcolor
19457 (progn (if (eq fg 'default)
19458 (setq fg (org-latex-color :foreground))
19459 (setq fg (org-latex-color-format fg)))
19460 (if (eq bg 'default)
19461 (setq bg (org-latex-color :background))
19462 (setq bg (org-latex-color-format
19463 (if (string= bg "Transparent") "white" bg))))
19464 (with-temp-file texfile
19465 (insert latex-header)
19466 (insert "\n\\begin{document}\n"
19467 "\\definecolor{fg}{rgb}{" fg "}\n"
19468 "\\definecolor{bg}{rgb}{" bg "}\n"
19469 "\n\\pagecolor{bg}\n"
19470 "\n{\\color{fg}\n"
19471 string
19472 "\n}\n"
19473 "\n\\end{document}\n")))
19474 (if (eq fg 'default)
19475 (setq fg (org-dvipng-color :foreground))
19476 (unless (string= fg "Transparent")
19477 (setq fg (org-dvipng-color-format fg))))
19478 (if (eq bg 'default)
19479 (setq bg (org-dvipng-color :background))
19480 (unless (string= bg "Transparent")
19481 (setq bg (org-dvipng-color-format bg))))
19482 (with-temp-file texfile
19483 (insert latex-header)
19484 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19486 (let* ((err-msg (format "Please adjust '%s' part of \
19487 `org-preview-latex-process-alist'."
19488 processing-type))
19489 (image-input-file
19490 (org-compile-file
19491 texfile latex-compiler image-input-type err-msg log-buf))
19492 (image-output-file
19493 (org-compile-file
19494 image-input-file image-converter image-output-type err-msg log-buf
19495 `((?F . ,(shell-quote-argument fg))
19496 (?B . ,(shell-quote-argument bg))
19497 (?D . ,(shell-quote-argument (format "%s" dpi)))
19498 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19499 (copy-file image-output-file tofile 'replace)
19500 (dolist (e post-clean)
19501 (when (file-exists-p (concat texfilebase e))
19502 (delete-file (concat texfilebase e))))
19503 image-output-file)))
19505 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19506 "Fill a LaTeX header template TPL.
19507 In the template, the following place holders will be recognized:
19509 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19510 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19511 [PACKAGES] \\usepackage statements for PKG
19512 [NO-PACKAGES] do not include PKG
19513 [EXTRA] the string EXTRA
19514 [NO-EXTRA] do not include EXTRA
19516 For backward compatibility, if both the positive and the negative place
19517 holder is missing, the positive one (without the \"NO-\") will be
19518 assumed to be present at the end of the template.
19519 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19520 EXTRA is a string.
19521 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19522 (let (rpl (end ""))
19523 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19524 (setq rpl (if (or (match-end 1) (not def-pkg))
19525 "" (org-latex-packages-to-string def-pkg snippets-p t))
19526 tpl (replace-match rpl t t tpl))
19527 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19529 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19530 (setq rpl (if (or (match-end 1) (not pkg))
19531 "" (org-latex-packages-to-string pkg snippets-p t))
19532 tpl (replace-match rpl t t tpl))
19533 (when pkg (setq end
19534 (concat end "\n"
19535 (org-latex-packages-to-string pkg snippets-p)))))
19537 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19538 (setq rpl (if (or (match-end 1) (not extra))
19539 "" (concat extra "\n"))
19540 tpl (replace-match rpl t t tpl))
19541 (when (and extra (string-match "\\S-" extra))
19542 (setq end (concat end "\n" extra))))
19544 (if (string-match "\\S-" end)
19545 (concat tpl "\n" end)
19546 tpl)))
19548 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19549 "Turn an alist of packages into a string with the \\usepackage macros."
19550 (setq pkg (mapconcat (lambda(p)
19551 (cond
19552 ((stringp p) p)
19553 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19554 (format "%% Package %s omitted" (cadr p)))
19555 ((equal "" (car p))
19556 (format "\\usepackage{%s}" (cadr p)))
19558 (format "\\usepackage[%s]{%s}"
19559 (car p) (cadr p)))))
19561 "\n"))
19562 (if newline (concat pkg "\n") pkg))
19564 (defun org-dvipng-color (attr)
19565 "Return a RGB color specification for dvipng."
19566 (apply #'format "rgb %s %s %s"
19567 (mapcar #'org-normalize-color
19568 (color-values (face-attribute 'default attr nil)))))
19570 (defun org-dvipng-color-format (color-name)
19571 "Convert COLOR-NAME to a RGB color value for dvipng."
19572 (apply 'format "rgb %s %s %s"
19573 (mapcar 'org-normalize-color
19574 (color-values color-name))))
19576 (defun org-latex-color (attr)
19577 "Return a RGB color for the LaTeX color package."
19578 (apply #'format "%s,%s,%s"
19579 (mapcar #'org-normalize-color
19580 (color-values (face-attribute 'default attr nil)))))
19582 (defun org-latex-color-format (color-name)
19583 "Convert COLOR-NAME to a RGB color value."
19584 (apply 'format "%s,%s,%s"
19585 (mapcar 'org-normalize-color
19586 (color-values color-name))))
19588 (defun org-normalize-color (value)
19589 "Return string to be used as color value for an RGB component."
19590 (format "%g" (/ value 65535.0)))
19594 ;; Image display
19596 (defvar-local org-inline-image-overlays nil)
19598 (defun org-toggle-inline-images (&optional include-linked)
19599 "Toggle the display of inline images.
19600 INCLUDE-LINKED is passed to `org-display-inline-images'."
19601 (interactive "P")
19602 (if org-inline-image-overlays
19603 (progn
19604 (org-remove-inline-images)
19605 (when (org-called-interactively-p 'interactive)
19606 (message "Inline image display turned off")))
19607 (org-display-inline-images include-linked)
19608 (when (org-called-interactively-p 'interactive)
19609 (message (if org-inline-image-overlays
19610 (format "%d images displayed inline"
19611 (length org-inline-image-overlays))
19612 "No images to display inline")))))
19614 (defun org-redisplay-inline-images ()
19615 "Refresh the display of inline images."
19616 (interactive)
19617 (if (not org-inline-image-overlays)
19618 (org-toggle-inline-images)
19619 (org-toggle-inline-images)
19620 (org-toggle-inline-images)))
19622 (defun org-display-inline-images (&optional include-linked refresh beg end)
19623 "Display inline images.
19625 An inline image is a link which follows either of these
19626 conventions:
19628 1. Its path is a file with an extension matching return value
19629 from `image-file-name-regexp' and it has no contents.
19631 2. Its description consists in a single link of the previous
19632 type.
19634 When optional argument INCLUDE-LINKED is non-nil, also links with
19635 a text description part will be inlined. This can be nice for
19636 a quick look at those images, but it does not reflect what
19637 exported files will look like.
19639 When optional argument REFRESH is non-nil, refresh existing
19640 images between BEG and END. This will create new image displays
19641 only if necessary. BEG and END default to the buffer
19642 boundaries."
19643 (interactive "P")
19644 (when (display-graphic-p)
19645 (unless refresh
19646 (org-remove-inline-images)
19647 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19648 (org-with-wide-buffer
19649 (goto-char (or beg (point-min)))
19650 (let ((case-fold-search t)
19651 (file-extension-re (image-file-name-regexp)))
19652 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19653 (let ((link (save-match-data (org-element-context))))
19654 ;; Check if we're at an inline image.
19655 (when (and (equal (org-element-property :type link) "file")
19656 (or include-linked
19657 (not (org-element-property :contents-begin link)))
19658 (let ((parent (org-element-property :parent link)))
19659 (or (not (eq (org-element-type parent) 'link))
19660 (not (cdr (org-element-contents parent)))))
19661 (org-string-match-p file-extension-re
19662 (org-element-property :path link)))
19663 (let ((file (expand-file-name
19664 (org-link-unescape
19665 (org-element-property :path link)))))
19666 (when (file-exists-p file)
19667 (let ((width
19668 ;; Apply `org-image-actual-width' specifications.
19669 (cond
19670 ((not (image-type-available-p 'imagemagick)) nil)
19671 ((eq org-image-actual-width t) nil)
19672 ((listp org-image-actual-width)
19674 ;; First try to find a width among
19675 ;; attributes associated to the paragraph
19676 ;; containing link.
19677 (let ((paragraph
19678 (let ((e link))
19679 (while (and (setq e (org-element-property
19680 :parent e))
19681 (not (eq (org-element-type e)
19682 'paragraph))))
19683 e)))
19684 (when paragraph
19685 (save-excursion
19686 (goto-char (org-element-property :begin paragraph))
19687 (when
19688 (re-search-forward
19689 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19690 (org-element-property
19691 :post-affiliated paragraph)
19693 (string-to-number (match-string 1))))))
19694 ;; Otherwise, fall-back to provided number.
19695 (car org-image-actual-width)))
19696 ((numberp org-image-actual-width)
19697 org-image-actual-width)))
19698 (old (get-char-property-and-overlay
19699 (org-element-property :begin link)
19700 'org-image-overlay)))
19701 (if (and (car-safe old) refresh)
19702 (image-refresh (overlay-get (cdr old) 'display))
19703 (let ((image (create-image file
19704 (and width 'imagemagick)
19706 :width width)))
19707 (when image
19708 (let* ((link
19709 ;; If inline image is the description
19710 ;; of another link, be sure to
19711 ;; consider the latter as the one to
19712 ;; apply the overlay on.
19713 (let ((parent
19714 (org-element-property :parent link)))
19715 (if (eq (org-element-type parent) 'link)
19716 parent
19717 link)))
19718 (ov (make-overlay
19719 (org-element-property :begin link)
19720 (progn
19721 (goto-char
19722 (org-element-property :end link))
19723 (skip-chars-backward " \t")
19724 (point)))))
19725 (overlay-put ov 'display image)
19726 (overlay-put ov 'face 'default)
19727 (overlay-put ov 'org-image-overlay t)
19728 (overlay-put
19729 ov 'modification-hooks
19730 (list 'org-display-inline-remove-overlay))
19731 (push ov org-inline-image-overlays)))))))))))))))
19733 (define-obsolete-function-alias
19734 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19736 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19737 "Remove inline-display overlay if a corresponding region is modified."
19738 (let ((inhibit-modification-hooks t))
19739 (when (and ov after)
19740 (delete ov org-inline-image-overlays)
19741 (delete-overlay ov))))
19743 (defun org-remove-inline-images ()
19744 "Remove inline display of images."
19745 (interactive)
19746 (mapc #'delete-overlay org-inline-image-overlays)
19747 (setq org-inline-image-overlays nil))
19749 ;;;; Key bindings
19751 ;; Outline functions from `outline-mode-prefix-map'
19752 ;; that can be remapped in Org:
19753 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19754 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19755 (define-key org-mode-map [remap outline-forward-same-level]
19756 'org-forward-heading-same-level)
19757 (define-key org-mode-map [remap outline-backward-same-level]
19758 'org-backward-heading-same-level)
19759 (define-key org-mode-map [remap outline-show-branches]
19760 'org-kill-note-or-show-branches)
19761 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19762 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19763 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19764 (define-key org-mode-map [remap outline-next-visible-heading]
19765 'org-next-visible-heading)
19766 (define-key org-mode-map [remap outline-previous-visible-heading]
19767 'org-previous-visible-heading)
19768 (define-key org-mode-map [remap show-children] 'org-show-children)
19770 ;; Outline functions from `outline-mode-prefix-map' that can not
19771 ;; be remapped in Org:
19773 ;; - the column "key binding" shows whether the Outline function is still
19774 ;; available in Org mode on the same key that it has been bound to in
19775 ;; Outline mode:
19776 ;; - "overridden": key used for a different functionality in Org mode
19777 ;; - else: key still bound to the same Outline function in Org mode
19779 ;; | Outline function | key binding | Org replacement |
19780 ;; |------------------------------------+-------------+--------------------------|
19781 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19782 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19783 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19784 ;; | `show-entry' | overridden | no replacement |
19785 ;; | `show-branches' | `C-c C-k' | still same function |
19786 ;; | `show-subtree' | overridden | visibility cycling |
19787 ;; | `show-all' | overridden | no replacement |
19788 ;; | `hide-subtree' | overridden | visibility cycling |
19789 ;; | `hide-body' | overridden | no replacement |
19790 ;; | `hide-entry' | overridden | visibility cycling |
19791 ;; | `hide-leaves' | overridden | no replacement |
19792 ;; | `hide-sublevels' | overridden | no replacement |
19793 ;; | `hide-other' | overridden | no replacement |
19795 ;; Make `C-c C-x' a prefix key
19796 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19798 ;; TAB key with modifiers
19799 (org-defkey org-mode-map "\C-i" 'org-cycle)
19800 (org-defkey org-mode-map [(tab)] 'org-cycle)
19801 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19802 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19803 ;; The following line is necessary under Suse GNU/Linux
19804 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19805 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19806 (define-key org-mode-map [backtab] 'org-shifttab)
19808 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19809 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19810 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19812 ;; Cursor keys with modifiers
19813 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19814 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19815 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19816 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19818 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19819 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19820 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19821 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19822 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19823 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19825 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19826 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19827 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19828 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19830 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19831 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19832 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19833 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19835 ;; Babel keys
19836 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19837 (dolist (pair org-babel-key-bindings)
19838 (define-key org-babel-map (car pair) (cdr pair)))
19840 ;;; Extra keys for tty access.
19841 ;; We only set them when really needed because otherwise the
19842 ;; menus don't show the simple keys
19844 (when (or org-use-extra-keys (not window-system))
19845 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19846 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19847 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19848 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19849 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19850 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19851 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19852 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19853 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19854 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19855 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19856 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19857 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19858 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19859 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19860 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19861 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19862 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19863 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19864 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19865 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19866 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19867 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19868 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19869 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19870 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19871 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19872 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19874 ;; All the other keys
19876 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19877 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19878 (if (boundp 'narrow-map)
19879 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19880 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19881 (if (boundp 'narrow-map)
19882 (org-defkey narrow-map "b" 'org-narrow-to-block)
19883 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19884 (if (boundp 'narrow-map)
19885 (org-defkey narrow-map "e" 'org-narrow-to-element)
19886 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19887 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19888 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19889 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19890 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19891 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19892 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19893 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19894 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19895 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19896 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19897 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19898 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19899 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19900 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19901 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19902 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19903 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19904 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19905 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19906 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19907 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19908 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19909 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19910 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19911 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19912 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19913 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19914 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19915 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19916 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19917 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19918 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19919 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19920 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19921 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19922 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19923 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19924 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19925 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19926 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19927 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19928 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19929 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19930 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19931 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19932 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19933 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19934 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19935 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19936 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19937 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19938 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19939 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19940 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19941 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19942 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19943 (org-defkey org-mode-map "\C-c^" 'org-sort)
19944 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19945 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19946 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19947 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19948 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19949 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19950 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19951 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19952 (org-defkey org-mode-map "\C-m" 'org-return)
19953 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19954 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19955 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19956 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19957 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19958 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19959 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19960 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19961 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19962 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19963 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19964 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19965 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19966 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19967 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19968 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19969 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19970 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19971 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19972 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19973 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19974 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19975 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19976 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19977 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19979 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19980 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19981 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19983 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19984 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19985 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19986 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19987 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19988 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19989 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19990 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19991 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19992 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19993 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19994 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19995 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19996 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19997 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19998 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19999 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20000 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20001 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20002 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20003 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20004 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20006 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20007 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20008 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20009 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20010 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20012 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20014 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20016 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20017 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20019 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20022 (defconst org-speed-commands-default
20024 ("Outline Navigation")
20025 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20026 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20027 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20028 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20029 ("F" . org-next-block)
20030 ("B" . org-previous-block)
20031 ("u" . (org-speed-move-safe 'outline-up-heading))
20032 ("j" . org-goto)
20033 ("g" . (org-refile t))
20034 ("Outline Visibility")
20035 ("c" . org-cycle)
20036 ("C" . org-shifttab)
20037 (" " . org-display-outline-path)
20038 ("s" . org-narrow-to-subtree)
20039 ("=" . org-columns)
20040 ("Outline Structure Editing")
20041 ("U" . org-metaup)
20042 ("D" . org-metadown)
20043 ("r" . org-metaright)
20044 ("l" . org-metaleft)
20045 ("R" . org-shiftmetaright)
20046 ("L" . org-shiftmetaleft)
20047 ("i" . (progn (forward-char 1) (call-interactively
20048 'org-insert-heading-respect-content)))
20049 ("^" . org-sort)
20050 ("w" . org-refile)
20051 ("a" . org-archive-subtree-default-with-confirmation)
20052 ("@" . org-mark-subtree)
20053 ("#" . org-toggle-comment)
20054 ("Clock Commands")
20055 ("I" . org-clock-in)
20056 ("O" . org-clock-out)
20057 ("Meta Data Editing")
20058 ("t" . org-todo)
20059 ("," . (org-priority))
20060 ("0" . (org-priority ?\ ))
20061 ("1" . (org-priority ?A))
20062 ("2" . (org-priority ?B))
20063 ("3" . (org-priority ?C))
20064 (":" . org-set-tags-command)
20065 ("e" . org-set-effort)
20066 ("E" . org-inc-effort)
20067 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20068 (org-entry-put (point) "APPT_WARNTIME" m)))
20069 ("Agenda Views etc")
20070 ("v" . org-agenda)
20071 ("/" . org-sparse-tree)
20072 ("Misc")
20073 ("o" . org-open-at-point)
20074 ("?" . org-speed-command-help)
20075 ("<" . (org-agenda-set-restriction-lock 'subtree))
20076 (">" . (org-agenda-remove-restriction-lock))
20078 "The default speed commands.")
20080 (defun org-print-speed-command (e)
20081 (if (> (length (car e)) 1)
20082 (progn
20083 (princ "\n")
20084 (princ (car e))
20085 (princ "\n")
20086 (princ (make-string (length (car e)) ?-))
20087 (princ "\n"))
20088 (princ (car e))
20089 (princ " ")
20090 (if (symbolp (cdr e))
20091 (princ (symbol-name (cdr e)))
20092 (prin1 (cdr e)))
20093 (princ "\n")))
20095 (defun org-speed-command-help ()
20096 "Show the available speed commands."
20097 (interactive)
20098 (if (not org-use-speed-commands)
20099 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20100 (with-output-to-temp-buffer "*Help*"
20101 (princ "User-defined Speed commands\n===========================\n")
20102 (mapc #'org-print-speed-command org-speed-commands-user)
20103 (princ "\n")
20104 (princ "Built-in Speed commands\n=======================\n")
20105 (mapc #'org-print-speed-command org-speed-commands-default))
20106 (with-current-buffer "*Help*"
20107 (setq truncate-lines t))))
20109 (defun org-speed-move-safe (cmd)
20110 "Execute CMD, but make sure that the cursor always ends up in a headline.
20111 If not, return to the original position and throw an error."
20112 (interactive)
20113 (let ((pos (point)))
20114 (call-interactively cmd)
20115 (unless (and (bolp) (org-at-heading-p))
20116 (goto-char pos)
20117 (error "Boundary reached while executing %s" cmd))))
20119 (defvar org-self-insert-command-undo-counter 0)
20121 (defvar org-table-auto-blank-field) ; defined in org-table.el
20122 (defvar org-speed-command nil)
20124 (define-obsolete-function-alias
20125 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20127 (defun org-speed-command-activate (keys)
20128 "Hook for activating single-letter speed commands.
20129 `org-speed-commands-default' specifies a minimal command set.
20130 Use `org-speed-commands-user' for further customization."
20131 (when (or (and (bolp) (looking-at org-outline-regexp))
20132 (and (functionp org-use-speed-commands)
20133 (funcall org-use-speed-commands)))
20134 (cdr (assoc keys (append org-speed-commands-user
20135 org-speed-commands-default)))))
20137 (define-obsolete-function-alias
20138 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20140 (defun org-babel-speed-command-activate (keys)
20141 "Hook for activating single-letter code block commands."
20142 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20143 (cdr (assoc keys org-babel-key-bindings))))
20145 (defcustom org-speed-command-hook
20146 '(org-speed-command-default-hook org-babel-speed-command-hook)
20147 "Hook for activating speed commands at strategic locations.
20148 Hook functions are called in sequence until a valid handler is
20149 found.
20151 Each hook takes a single argument, a user-pressed command key
20152 which is also a `self-insert-command' from the global map.
20154 Within the hook, examine the cursor position and the command key
20155 and return nil or a valid handler as appropriate. Handler could
20156 be one of an interactive command, a function, or a form.
20158 Set `org-use-speed-commands' to non-nil value to enable this
20159 hook. The default setting is `org-speed-command-activate'."
20160 :group 'org-structure
20161 :version "24.1"
20162 :type 'hook)
20164 (defun org-self-insert-command (N)
20165 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20166 If the cursor is in a table looking at whitespace, the whitespace is
20167 overwritten, and the table is not marked as requiring realignment."
20168 (interactive "p")
20169 (org-check-before-invisible-edit 'insert)
20170 (cond
20171 ((and org-use-speed-commands
20172 (let ((kv (this-command-keys-vector)))
20173 (setq org-speed-command
20174 (run-hook-with-args-until-success
20175 'org-speed-command-hook
20176 (make-string 1 (aref kv (1- (length kv))))))))
20177 (cond
20178 ((commandp org-speed-command)
20179 (setq this-command org-speed-command)
20180 (call-interactively org-speed-command))
20181 ((functionp org-speed-command)
20182 (funcall org-speed-command))
20183 ((and org-speed-command (listp org-speed-command))
20184 (eval org-speed-command))
20185 (t (let (org-use-speed-commands)
20186 (call-interactively 'org-self-insert-command)))))
20187 ((and
20188 (org-at-table-p)
20189 (progn
20190 ;; Check if we blank the field, and if that triggers align.
20191 (and (featurep 'org-table) org-table-auto-blank-field
20192 (memq last-command
20193 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20194 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20195 ;; Got extra space, this field does not determine
20196 ;; column width.
20197 (let (org-table-may-need-update) (org-table-blank-field))
20198 ;; No extra space, this field may determine column
20199 ;; width.
20200 (org-table-blank-field)))
20202 (eq N 1)
20203 (looking-at "[^|\n]* \\( \\)|"))
20204 ;; There is room for insertion without re-aligning the table.
20205 (delete-region (match-beginning 1) (match-end 1))
20206 (self-insert-command N))
20208 (setq org-table-may-need-update t)
20209 (self-insert-command N)
20210 (org-fix-tags-on-the-fly)
20211 (when org-self-insert-cluster-for-undo
20212 (if (not (eq last-command 'org-self-insert-command))
20213 (setq org-self-insert-command-undo-counter 1)
20214 (if (>= org-self-insert-command-undo-counter 20)
20215 (setq org-self-insert-command-undo-counter 1)
20216 (and (> org-self-insert-command-undo-counter 0)
20217 buffer-undo-list (listp buffer-undo-list)
20218 (not (cadr buffer-undo-list)) ; remove nil entry
20219 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20220 (setq org-self-insert-command-undo-counter
20221 (1+ org-self-insert-command-undo-counter))))))))
20223 (defun org-check-before-invisible-edit (kind)
20224 "Check is editing if kind KIND would be dangerous with invisible text around.
20225 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20226 ;; First, try to get out of here as quickly as possible, to reduce overhead
20227 (when (and org-catch-invisible-edits
20228 (or (not (boundp 'visible-mode)) (not visible-mode))
20229 (or (get-char-property (point) 'invisible)
20230 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20231 ;; OK, we need to take a closer look
20232 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20233 (invisible-before-point (unless (bobp) (get-char-property
20234 (1- (point)) 'invisible)))
20235 (border-and-ok-direction
20237 ;; Check if we are acting predictably before invisible text
20238 (and invisible-at-point (not invisible-before-point)
20239 (memq kind '(insert delete-backward)))
20240 ;; Check if we are acting predictably after invisible text
20241 ;; This works not well, and I have turned it off. It seems
20242 ;; better to always show and stop after invisible text.
20243 ;; (and (not invisible-at-point) invisible-before-point
20244 ;; (memq kind '(insert delete)))
20246 (when (or (memq invisible-at-point '(outline org-hide-block t))
20247 (memq invisible-before-point '(outline org-hide-block t)))
20248 (when (eq org-catch-invisible-edits 'error)
20249 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20250 (if (and org-custom-properties-overlays
20251 (y-or-n-p "Display invisible properties in this buffer? "))
20252 (org-toggle-custom-properties-visibility)
20253 ;; Make the area visible
20254 (save-excursion
20255 (when invisible-before-point
20256 (goto-char (previous-single-char-property-change
20257 (point) 'invisible)))
20258 (outline-show-subtree))
20259 (cond
20260 ((eq org-catch-invisible-edits 'show)
20261 ;; That's it, we do the edit after showing
20262 (message
20263 "Unfolding invisible region around point before editing")
20264 (sit-for 1))
20265 ((and (eq org-catch-invisible-edits 'smart)
20266 border-and-ok-direction)
20267 (message "Unfolding invisible region around point before editing"))
20269 ;; Don't do the edit, make the user repeat it in full visibility
20270 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20272 (defun org-fix-tags-on-the-fly ()
20273 (when (and (equal (char-after (point-at-bol)) ?*)
20274 (org-at-heading-p))
20275 (org-align-tags-here org-tags-column)))
20277 (defun org-delete-backward-char (N)
20278 "Like `delete-backward-char', insert whitespace at field end in tables.
20279 When deleting backwards, in tables this function will insert whitespace in
20280 front of the next \"|\" separator, to keep the table aligned. The table will
20281 still be marked for re-alignment if the field did fill the entire column,
20282 because, in this case the deletion might narrow the column."
20283 (interactive "p")
20284 (save-match-data
20285 (org-check-before-invisible-edit 'delete-backward)
20286 (if (and (org-at-table-p)
20287 (eq N 1)
20288 (string-match "|" (buffer-substring (point-at-bol) (point)))
20289 (looking-at ".*?|"))
20290 (let ((pos (point))
20291 (noalign (looking-at "[^|\n\r]* |"))
20292 (c org-table-may-need-update))
20293 (backward-delete-char N)
20294 (unless overwrite-mode
20295 (skip-chars-forward "^|")
20296 (insert " ")
20297 (goto-char (1- pos)))
20298 ;; noalign: if there were two spaces at the end, this field
20299 ;; does not determine the width of the column.
20300 (when noalign (setq org-table-may-need-update c)))
20301 (backward-delete-char N)
20302 (org-fix-tags-on-the-fly))))
20304 (defun org-delete-char (N)
20305 "Like `delete-char', but insert whitespace at field end in tables.
20306 When deleting characters, in tables this function will insert whitespace in
20307 front of the next \"|\" separator, to keep the table aligned. The table will
20308 still be marked for re-alignment if the field did fill the entire column,
20309 because, in this case the deletion might narrow the column."
20310 (interactive "p")
20311 (save-match-data
20312 (org-check-before-invisible-edit 'delete)
20313 (if (and (org-at-table-p)
20314 (not (bolp))
20315 (not (= (char-after) ?|))
20316 (eq N 1))
20317 (if (looking-at ".*?|")
20318 (let ((pos (point))
20319 (noalign (looking-at "[^|\n\r]* |"))
20320 (c org-table-may-need-update))
20321 (replace-match
20322 (concat (substring (match-string 0) 1 -1) " |") nil t)
20323 (goto-char pos)
20324 ;; noalign: if there were two spaces at the end, this field
20325 ;; does not determine the width of the column.
20326 (when noalign (setq org-table-may-need-update c)))
20327 (delete-char N))
20328 (delete-char N)
20329 (org-fix-tags-on-the-fly))))
20331 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20332 (put 'org-self-insert-command 'delete-selection
20333 (lambda ()
20334 (not (run-hook-with-args-until-success
20335 'self-insert-uses-region-functions))))
20336 (put 'orgtbl-self-insert-command 'delete-selection
20337 (lambda ()
20338 (not (run-hook-with-args-until-success
20339 'self-insert-uses-region-functions))))
20340 (put 'org-delete-char 'delete-selection 'supersede)
20341 (put 'org-delete-backward-char 'delete-selection 'supersede)
20342 (put 'org-yank 'delete-selection 'yank)
20344 ;; Make `flyspell-mode' delay after some commands
20345 (put 'org-self-insert-command 'flyspell-delayed t)
20346 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20347 (put 'org-delete-char 'flyspell-delayed t)
20348 (put 'org-delete-backward-char 'flyspell-delayed t)
20350 ;; Make pabbrev-mode expand after org-mode commands
20351 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20352 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20354 (defun org-remap (map &rest commands)
20355 "In MAP, remap the functions given in COMMANDS.
20356 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20357 (let (new old)
20358 (while commands
20359 (setq old (pop commands) new (pop commands))
20360 (if (fboundp 'command-remapping)
20361 (org-defkey map (vector 'remap old) new)
20362 (substitute-key-definition old new map global-map)))))
20364 (defun org-transpose-words ()
20365 "Transpose words for Org.
20366 This uses the `org-mode-transpose-word-syntax-table' syntax
20367 table, which interprets characters in `org-emphasis-alist' as
20368 word constituents."
20369 (interactive)
20370 (with-syntax-table org-mode-transpose-word-syntax-table
20371 (call-interactively 'transpose-words)))
20372 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20374 (when (eq org-enable-table-editor 'optimized)
20375 ;; If the user wants maximum table support, we need to hijack
20376 ;; some standard editing functions
20377 (org-remap org-mode-map
20378 'self-insert-command 'org-self-insert-command
20379 'delete-char 'org-delete-char
20380 'delete-backward-char 'org-delete-backward-char)
20381 (org-defkey org-mode-map "|" 'org-force-self-insert))
20383 (defvar org-ctrl-c-ctrl-c-hook nil
20384 "Hook for functions attaching themselves to `C-c C-c'.
20386 This can be used to add additional functionality to the C-c C-c
20387 key which executes context-dependent commands. This hook is run
20388 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20389 run after the last test.
20391 Each function will be called with no arguments. The function
20392 must check if the context is appropriate for it to act. If yes,
20393 it should do its thing and then return a non-nil value. If the
20394 context is wrong, just do nothing and return nil.")
20396 (defvar org-ctrl-c-ctrl-c-final-hook nil
20397 "Hook for functions attaching themselves to `C-c C-c'.
20399 This can be used to add additional functionality to the C-c C-c
20400 key which executes context-dependent commands. This hook is run
20401 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20402 before the first test.
20404 Each function will be called with no arguments. The function
20405 must check if the context is appropriate for it to act. If yes,
20406 it should do its thing and then return a non-nil value. If the
20407 context is wrong, just do nothing and return nil.")
20409 (defvar org-tab-first-hook nil
20410 "Hook for functions to attach themselves to TAB.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.
20412 This hook runs as the first action when TAB is pressed, even before
20413 `org-cycle' messes around with the `outline-regexp' to cater for
20414 inline tasks and plain list item folding.
20415 If any function in this hook returns t, any other actions that
20416 would have been caused by TAB (such as table field motion or visibility
20417 cycling) will not occur.")
20419 (defvar org-tab-after-check-for-table-hook nil
20420 "Hook for functions to attach themselves to TAB.
20421 See `org-ctrl-c-ctrl-c-hook' for more information.
20422 This hook runs after it has been established that the cursor is not in a
20423 table, but before checking if the cursor is in a headline or if global cycling
20424 should be done.
20425 If any function in this hook returns t, not other actions like visibility
20426 cycling will be done.")
20428 (defvar org-tab-after-check-for-cycling-hook nil
20429 "Hook for functions to attach themselves to TAB.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.
20431 This hook runs after it has been established that not table field motion and
20432 not visibility should be done because of current context. This is probably
20433 the place where a package like yasnippets can hook in.")
20435 (defvar org-tab-before-tab-emulation-hook nil
20436 "Hook for functions to attach themselves to TAB.
20437 See `org-ctrl-c-ctrl-c-hook' for more information.
20438 This hook runs after every other options for TAB have been exhausted, but
20439 before indentation and \t insertion takes place.")
20441 (defvar org-metaleft-hook nil
20442 "Hook for functions attaching themselves to `M-left'.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-metaright-hook nil
20445 "Hook for functions attaching themselves to `M-right'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-metaup-hook nil
20448 "Hook for functions attaching themselves to `M-up'.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-metadown-hook nil
20451 "Hook for functions attaching themselves to `M-down'.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-shiftmetaleft-hook nil
20454 "Hook for functions attaching themselves to `M-S-left'.
20455 See `org-ctrl-c-ctrl-c-hook' for more information.")
20456 (defvar org-shiftmetaright-hook nil
20457 "Hook for functions attaching themselves to `M-S-right'.
20458 See `org-ctrl-c-ctrl-c-hook' for more information.")
20459 (defvar org-shiftmetaup-hook nil
20460 "Hook for functions attaching themselves to `M-S-up'.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.")
20462 (defvar org-shiftmetadown-hook nil
20463 "Hook for functions attaching themselves to `M-S-down'.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-metareturn-hook nil
20466 "Hook for functions attaching themselves to `M-RET'.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-shiftup-hook nil
20469 "Hook for functions attaching themselves to `S-up'.
20470 See `org-ctrl-c-ctrl-c-hook' for more information.")
20471 (defvar org-shiftup-final-hook nil
20472 "Hook for functions attaching themselves to `S-up'.
20473 This one runs after all other options except shift-select have been excluded.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.")
20475 (defvar org-shiftdown-hook nil
20476 "Hook for functions attaching themselves to `S-down'.
20477 See `org-ctrl-c-ctrl-c-hook' for more information.")
20478 (defvar org-shiftdown-final-hook nil
20479 "Hook for functions attaching themselves to `S-down'.
20480 This one runs after all other options except shift-select have been excluded.
20481 See `org-ctrl-c-ctrl-c-hook' for more information.")
20482 (defvar org-shiftleft-hook nil
20483 "Hook for functions attaching themselves to `S-left'.
20484 See `org-ctrl-c-ctrl-c-hook' for more information.")
20485 (defvar org-shiftleft-final-hook nil
20486 "Hook for functions attaching themselves to `S-left'.
20487 This one runs after all other options except shift-select have been excluded.
20488 See `org-ctrl-c-ctrl-c-hook' for more information.")
20489 (defvar org-shiftright-hook nil
20490 "Hook for functions attaching themselves to `S-right'.
20491 See `org-ctrl-c-ctrl-c-hook' for more information.")
20492 (defvar org-shiftright-final-hook nil
20493 "Hook for functions attaching themselves to `S-right'.
20494 This one runs after all other options except shift-select have been excluded.
20495 See `org-ctrl-c-ctrl-c-hook' for more information.")
20497 (defun org-modifier-cursor-error ()
20498 "Throw an error, a modified cursor command was applied in wrong context."
20499 (user-error "This command is active in special context like tables, headlines or items"))
20501 (defun org-shiftselect-error ()
20502 "Throw an error because Shift-Cursor command was applied in wrong context."
20503 (if (and (boundp 'shift-select-mode) shift-select-mode)
20504 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20505 (user-error "This command works only in special context like headlines or timestamps")))
20507 (defun org-call-for-shift-select (cmd)
20508 (let ((this-command-keys-shift-translated t))
20509 (call-interactively cmd)))
20511 (defun org-shifttab (&optional arg)
20512 "Global visibility cycling or move to previous table field.
20513 Call `org-table-previous-field' within a table.
20514 When ARG is nil, cycle globally through visibility states.
20515 When ARG is a numeric prefix, show contents of this level."
20516 (interactive "P")
20517 (cond
20518 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20519 ((integerp arg)
20520 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20521 (message "Content view to level: %d" arg)
20522 (org-content (prefix-numeric-value arg2))
20523 (org-cycle-show-empty-lines t)
20524 (setq org-cycle-global-status 'overview)))
20525 (t (call-interactively 'org-global-cycle))))
20527 (defun org-shiftmetaleft ()
20528 "Promote subtree or delete table column.
20529 Calls `org-promote-subtree', `org-outdent-item-tree', or
20530 `org-table-delete-column', depending on context. See the
20531 individual commands for more information."
20532 (interactive)
20533 (cond
20534 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20535 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20536 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20537 ((if (not (org-region-active-p)) (org-at-item-p)
20538 (save-excursion (goto-char (region-beginning))
20539 (org-at-item-p)))
20540 (call-interactively 'org-outdent-item-tree))
20541 (t (org-modifier-cursor-error))))
20543 (defun org-shiftmetaright ()
20544 "Demote subtree or insert table column.
20545 Calls `org-demote-subtree', `org-indent-item-tree', or
20546 `org-table-insert-column', depending on context. See the
20547 individual commands for more information."
20548 (interactive)
20549 (cond
20550 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20551 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20552 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20553 ((if (not (org-region-active-p)) (org-at-item-p)
20554 (save-excursion (goto-char (region-beginning))
20555 (org-at-item-p)))
20556 (call-interactively 'org-indent-item-tree))
20557 (t (org-modifier-cursor-error))))
20559 (defun org-shiftmetaup (&optional _arg)
20560 "Drag the line at point up.
20561 In a table, kill the current row.
20562 On a clock timestamp, update the value of the timestamp like `S-<up>'
20563 but also adjust the previous clocked item in the clock history.
20564 Everywhere else, drag the line at point up."
20565 (interactive "P")
20566 (cond
20567 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20568 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20569 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20570 (call-interactively 'org-timestamp-up)))
20571 (t (call-interactively 'org-drag-line-backward))))
20573 (defun org-shiftmetadown (&optional _arg)
20574 "Drag the line at point down.
20575 In a table, insert an empty row at the current line.
20576 On a clock timestamp, update the value of the timestamp like `S-<down>'
20577 but also adjust the previous clocked item in the clock history.
20578 Everywhere else, drag the line at point down."
20579 (interactive "P")
20580 (cond
20581 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20582 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20583 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20584 (call-interactively 'org-timestamp-down)))
20585 (t (call-interactively 'org-drag-line-forward))))
20587 (defsubst org-hidden-tree-error ()
20588 (user-error
20589 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20591 (defun org-metaleft (&optional _arg)
20592 "Promote heading, list item at point or move table column left.
20594 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20595 depending on context. With no specific context, calls the Emacs
20596 default `backward-word'. See the individual commands for more
20597 information.
20599 This function runs the hook `org-metaleft-hook' as a first step,
20600 and returns at first non-nil value."
20601 (interactive "P")
20602 (cond
20603 ((run-hook-with-args-until-success 'org-metaleft-hook))
20604 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20605 ((org-with-limited-levels
20606 (or (org-at-heading-p)
20607 (and (org-region-active-p)
20608 (save-excursion
20609 (goto-char (region-beginning))
20610 (org-at-heading-p)))))
20611 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20612 (call-interactively 'org-do-promote))
20613 ;; At an inline task.
20614 ((org-at-heading-p)
20615 (call-interactively 'org-inlinetask-promote))
20616 ((or (org-at-item-p)
20617 (and (org-region-active-p)
20618 (save-excursion
20619 (goto-char (region-beginning))
20620 (org-at-item-p))))
20621 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20622 (call-interactively 'org-outdent-item))
20623 (t (call-interactively 'backward-word))))
20625 (defun org-metaright (&optional _arg)
20626 "Demote heading, list item at point or move table column right.
20628 In front of a drawer or a block keyword, indent it correctly.
20630 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20631 `org-indnet-drawer' or `org-indent-block' depending on context.
20632 With no specific context, calls the Emacs default `forward-word'.
20633 See the individual commands for more information.
20635 This function runs the hook `org-metaright-hook' as a first step,
20636 and returns at first non-nil value."
20637 (interactive "P")
20638 (cond
20639 ((run-hook-with-args-until-success 'org-metaright-hook))
20640 ((org-at-table-p) (call-interactively 'org-table-move-column))
20641 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20642 ((org-at-block-p) (call-interactively 'org-indent-block))
20643 ((org-with-limited-levels
20644 (or (org-at-heading-p)
20645 (and (org-region-active-p)
20646 (save-excursion
20647 (goto-char (region-beginning))
20648 (org-at-heading-p)))))
20649 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20650 (call-interactively 'org-do-demote))
20651 ;; At an inline task.
20652 ((org-at-heading-p)
20653 (call-interactively 'org-inlinetask-demote))
20654 ((or (org-at-item-p)
20655 (and (org-region-active-p)
20656 (save-excursion
20657 (goto-char (region-beginning))
20658 (org-at-item-p))))
20659 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20660 (call-interactively 'org-indent-item))
20661 (t (call-interactively 'forward-word))))
20663 (defun org-check-for-hidden (what)
20664 "Check if there are hidden headlines/items in the current visual line.
20665 WHAT can be either `headlines' or `items'. If the current line is
20666 an outline or item heading and it has a folded subtree below it,
20667 this function returns t, nil otherwise."
20668 (let ((re (cond
20669 ((eq what 'headlines) org-outline-regexp-bol)
20670 ((eq what 'items) (org-item-beginning-re))
20671 (t (error "This should not happen"))))
20672 beg end)
20673 (save-excursion
20674 (catch 'exit
20675 (unless (org-region-active-p)
20676 (setq beg (point-at-bol))
20677 (beginning-of-line 2)
20678 (while (and (not (eobp)) ;; this is like `next-line'
20679 (get-char-property (1- (point)) 'invisible))
20680 (beginning-of-line 2))
20681 (setq end (point))
20682 (goto-char beg)
20683 (goto-char (point-at-eol))
20684 (setq end (max end (point)))
20685 (while (re-search-forward re end t)
20686 (when (get-char-property (match-beginning 0) 'invisible)
20687 (throw 'exit t))))
20688 nil))))
20690 (defun org-metaup (&optional _arg)
20691 "Move subtree up or move table row up.
20692 Calls `org-move-subtree-up' or `org-table-move-row' or
20693 `org-move-item-up', depending on context. See the individual commands
20694 for more information."
20695 (interactive "P")
20696 (cond
20697 ((run-hook-with-args-until-success 'org-metaup-hook))
20698 ((org-region-active-p)
20699 (let* ((a (min (region-beginning) (region-end)))
20700 (b (1- (max (region-beginning) (region-end))))
20701 (c (save-excursion (goto-char a)
20702 (move-beginning-of-line 0)))
20703 (d (save-excursion (goto-char a)
20704 (move-end-of-line 0) (point))))
20705 (transpose-regions a b c d)
20706 (goto-char c)))
20707 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20708 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20709 ((org-at-item-p) (call-interactively 'org-move-item-up))
20710 (t (org-drag-element-backward))))
20712 (defun org-metadown (&optional _arg)
20713 "Move subtree down or move table row down.
20714 Calls `org-move-subtree-down' or `org-table-move-row' or
20715 `org-move-item-down', depending on context. See the individual
20716 commands for more information."
20717 (interactive "P")
20718 (cond
20719 ((run-hook-with-args-until-success 'org-metadown-hook))
20720 ((org-region-active-p)
20721 (let* ((a (min (region-beginning) (region-end)))
20722 (b (max (region-beginning) (region-end)))
20723 (c (save-excursion (goto-char b)
20724 (move-beginning-of-line 1)))
20725 (d (save-excursion (goto-char b)
20726 (move-end-of-line 1) (1+ (point)))))
20727 (transpose-regions a b c d)
20728 (goto-char d)))
20729 ((org-at-table-p) (call-interactively 'org-table-move-row))
20730 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20731 ((org-at-item-p) (call-interactively 'org-move-item-down))
20732 (t (org-drag-element-forward))))
20734 (defun org-shiftup (&optional arg)
20735 "Increase item in timestamp or increase priority of current headline.
20736 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20737 depending on context. See the individual commands for more information."
20738 (interactive "P")
20739 (cond
20740 ((run-hook-with-args-until-success 'org-shiftup-hook))
20741 ((and org-support-shift-select (org-region-active-p))
20742 (org-call-for-shift-select 'previous-line))
20743 ((org-at-timestamp-p t)
20744 (call-interactively (if org-edit-timestamp-down-means-later
20745 'org-timestamp-down 'org-timestamp-up)))
20746 ((and (not (eq org-support-shift-select 'always))
20747 org-enable-priority-commands
20748 (org-at-heading-p))
20749 (call-interactively 'org-priority-up))
20750 ((and (not org-support-shift-select) (org-at-item-p))
20751 (call-interactively 'org-previous-item))
20752 ((org-clocktable-try-shift 'up arg))
20753 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20754 (org-support-shift-select
20755 (org-call-for-shift-select 'previous-line))
20756 (t (org-shiftselect-error))))
20758 (defun org-shiftdown (&optional arg)
20759 "Decrease item in timestamp or decrease priority of current headline.
20760 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20761 depending on context. See the individual commands for more information."
20762 (interactive "P")
20763 (cond
20764 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20765 ((and org-support-shift-select (org-region-active-p))
20766 (org-call-for-shift-select 'next-line))
20767 ((org-at-timestamp-p t)
20768 (call-interactively (if org-edit-timestamp-down-means-later
20769 'org-timestamp-up 'org-timestamp-down)))
20770 ((and (not (eq org-support-shift-select 'always))
20771 org-enable-priority-commands
20772 (org-at-heading-p))
20773 (call-interactively 'org-priority-down))
20774 ((and (not org-support-shift-select) (org-at-item-p))
20775 (call-interactively 'org-next-item))
20776 ((org-clocktable-try-shift 'down arg))
20777 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20778 (org-support-shift-select
20779 (org-call-for-shift-select 'next-line))
20780 (t (org-shiftselect-error))))
20782 (defun org-shiftright (&optional arg)
20783 "Cycle the thing at point or in the current line, depending on context.
20784 Depending on context, this does one of the following:
20786 - switch a timestamp at point one day into the future
20787 - on a headline, switch to the next TODO keyword.
20788 - on an item, switch entire list to the next bullet type
20789 - on a property line, switch to the next allowed value
20790 - on a clocktable definition line, move time block into the future"
20791 (interactive "P")
20792 (cond
20793 ((run-hook-with-args-until-success 'org-shiftright-hook))
20794 ((and org-support-shift-select (org-region-active-p))
20795 (org-call-for-shift-select 'forward-char))
20796 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20797 ((and (not (eq org-support-shift-select 'always))
20798 (org-at-heading-p))
20799 (let ((org-inhibit-logging
20800 (not org-treat-S-cursor-todo-selection-as-state-change))
20801 (org-inhibit-blocking
20802 (not org-treat-S-cursor-todo-selection-as-state-change)))
20803 (org-call-with-arg 'org-todo 'right)))
20804 ((or (and org-support-shift-select
20805 (not (eq org-support-shift-select 'always))
20806 (org-at-item-bullet-p))
20807 (and (not org-support-shift-select) (org-at-item-p)))
20808 (org-call-with-arg 'org-cycle-list-bullet nil))
20809 ((and (not (eq org-support-shift-select 'always))
20810 (org-at-property-p))
20811 (call-interactively 'org-property-next-allowed-value))
20812 ((org-clocktable-try-shift 'right arg))
20813 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20814 (org-support-shift-select
20815 (org-call-for-shift-select 'forward-char))
20816 (t (org-shiftselect-error))))
20818 (defun org-shiftleft (&optional arg)
20819 "Cycle the thing at point or in the current line, depending on context.
20820 Depending on context, this does one of the following:
20822 - switch a timestamp at point one day into the past
20823 - on a headline, switch to the previous TODO keyword.
20824 - on an item, switch entire list to the previous bullet type
20825 - on a property line, switch to the previous allowed value
20826 - on a clocktable definition line, move time block into the past"
20827 (interactive "P")
20828 (cond
20829 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20830 ((and org-support-shift-select (org-region-active-p))
20831 (org-call-for-shift-select 'backward-char))
20832 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20833 ((and (not (eq org-support-shift-select 'always))
20834 (org-at-heading-p))
20835 (let ((org-inhibit-logging
20836 (not org-treat-S-cursor-todo-selection-as-state-change))
20837 (org-inhibit-blocking
20838 (not org-treat-S-cursor-todo-selection-as-state-change)))
20839 (org-call-with-arg 'org-todo 'left)))
20840 ((or (and org-support-shift-select
20841 (not (eq org-support-shift-select 'always))
20842 (org-at-item-bullet-p))
20843 (and (not org-support-shift-select) (org-at-item-p)))
20844 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20845 ((and (not (eq org-support-shift-select 'always))
20846 (org-at-property-p))
20847 (call-interactively 'org-property-previous-allowed-value))
20848 ((org-clocktable-try-shift 'left arg))
20849 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20850 (org-support-shift-select
20851 (org-call-for-shift-select 'backward-char))
20852 (t (org-shiftselect-error))))
20854 (defun org-shiftcontrolright ()
20855 "Switch to next TODO set."
20856 (interactive)
20857 (cond
20858 ((and org-support-shift-select (org-region-active-p))
20859 (org-call-for-shift-select 'forward-word))
20860 ((and (not (eq org-support-shift-select 'always))
20861 (org-at-heading-p))
20862 (org-call-with-arg 'org-todo 'nextset))
20863 (org-support-shift-select
20864 (org-call-for-shift-select 'forward-word))
20865 (t (org-shiftselect-error))))
20867 (defun org-shiftcontrolleft ()
20868 "Switch to previous TODO set."
20869 (interactive)
20870 (cond
20871 ((and org-support-shift-select (org-region-active-p))
20872 (org-call-for-shift-select 'backward-word))
20873 ((and (not (eq org-support-shift-select 'always))
20874 (org-at-heading-p))
20875 (org-call-with-arg 'org-todo 'previousset))
20876 (org-support-shift-select
20877 (org-call-for-shift-select 'backward-word))
20878 (t (org-shiftselect-error))))
20880 (defun org-shiftcontrolup (&optional n)
20881 "Change timestamps synchronously up in CLOCK log lines.
20882 Optional argument N tells to change by that many units."
20883 (interactive "P")
20884 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20885 (let (org-support-shift-select)
20886 (org-clock-timestamps-up n))
20887 (user-error "Not at a clock log")))
20889 (defun org-shiftcontroldown (&optional n)
20890 "Change timestamps synchronously down in CLOCK log lines.
20891 Optional argument N tells to change by that many units."
20892 (interactive "P")
20893 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20894 (let (org-support-shift-select)
20895 (org-clock-timestamps-down n))
20896 (user-error "Not at a clock log")))
20898 (defun org-increase-number-at-point (&optional inc)
20899 "Increment the number at point.
20900 With an optional prefix numeric argument INC, increment using
20901 this numeric value."
20902 (interactive "p")
20903 (if (not (number-at-point))
20904 (user-error "Not on a number")
20905 (unless inc (setq inc 1))
20906 (let ((pos (point))
20907 (beg (skip-chars-backward "-+^/*0-9eE."))
20908 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20909 (setq nap (buffer-substring-no-properties
20910 (+ pos beg) (+ pos beg end)))
20911 (delete-region (+ pos beg) (+ pos beg end))
20912 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20913 (when (org-at-table-p)
20914 (org-table-align)
20915 (org-table-end-of-field 1))))
20917 (defun org-decrease-number-at-point (&optional inc)
20918 "Decrement the number at point.
20919 With an optional prefix numeric argument INC, decrement using
20920 this numeric value."
20921 (interactive "p")
20922 (org-increase-number-at-point (- (or inc 1))))
20924 (defun org-ctrl-c-ret ()
20925 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20926 (interactive)
20927 (cond
20928 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20929 (t (call-interactively 'org-insert-heading))))
20931 (defun org-find-visible ()
20932 (let ((s (point)))
20933 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20934 (get-char-property s 'invisible)))
20936 (defun org-find-invisible ()
20937 (let ((s (point)))
20938 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20939 (not (get-char-property s 'invisible))))
20942 (defun org-copy-visible (beg end)
20943 "Copy the visible parts of the region."
20944 (interactive "r")
20945 (let (snippets s)
20946 (save-excursion
20947 (save-restriction
20948 (narrow-to-region beg end)
20949 (setq s (goto-char (point-min)))
20950 (while (not (= (point) (point-max)))
20951 (goto-char (org-find-invisible))
20952 (push (buffer-substring s (point)) snippets)
20953 (setq s (goto-char (org-find-visible))))))
20954 (kill-new (apply 'concat (nreverse snippets)))))
20956 (defun org-copy-special ()
20957 "Copy region in table or copy current subtree.
20958 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20959 See the individual commands for more information."
20960 (interactive)
20961 (call-interactively
20962 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20964 (defun org-cut-special ()
20965 "Cut region in table or cut current subtree.
20966 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20967 See the individual commands for more information."
20968 (interactive)
20969 (call-interactively
20970 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20972 (defun org-paste-special (arg)
20973 "Paste rectangular region into table, or past subtree relative to level.
20974 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20975 See the individual commands for more information."
20976 (interactive "P")
20977 (if (org-at-table-p)
20978 (org-table-paste-rectangle)
20979 (org-paste-subtree arg)))
20981 (defsubst org-in-fixed-width-region-p ()
20982 "Is point in a fixed-width region?"
20983 (save-match-data
20984 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20986 (defun org-edit-special (&optional arg)
20987 "Call a special editor for the element at point.
20988 When at a table, call the formula editor with `org-table-edit-formulas'.
20989 When in a source code block, call `org-edit-src-code'.
20990 When in a fixed-width region, call `org-edit-fixed-width-region'.
20991 When in an export block, call `org-edit-export-block'.
20992 When at an #+INCLUDE keyword, visit the included file.
20993 When at a footnote reference, call `org-edit-footnote-reference'
20994 On a link, call `ffap' to visit the link at point.
20995 Otherwise, return a user error."
20996 (interactive "P")
20997 (let ((element (org-element-at-point)))
20998 (cl-assert (not buffer-read-only) nil
20999 "Buffer is read-only: %s" (buffer-name))
21000 (pcase (org-element-type element)
21001 (`src-block
21002 (if (not arg) (org-edit-src-code)
21003 (let* ((info (org-babel-get-src-block-info))
21004 (lang (nth 0 info))
21005 (params (nth 2 info))
21006 (session (cdr (assq :session params))))
21007 (if (not session) (org-edit-src-code)
21008 ;; At a src-block with a session and function called with
21009 ;; an ARG: switch to the buffer related to the inferior
21010 ;; process.
21011 (switch-to-buffer
21012 (funcall (intern (concat "org-babel-prep-session:" lang))
21013 session params))))))
21014 (`keyword
21015 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21016 (org-open-link-from-string
21017 (format "[[%s]]"
21018 (expand-file-name
21019 (let ((value (org-element-property :value element)))
21020 (cond ((not (org-string-nw-p value))
21021 (user-error "No file to edit"))
21022 ((string-match "\\`\"\\(.*?\\)\"" value)
21023 (match-string 1 value))
21024 ((string-match "\\`[^ \t\"]\\S-*" value)
21025 (match-string 0 value))
21026 (t (user-error "No valid file specified")))))))
21027 (user-error "No special environment to edit here")))
21028 (`table
21029 (if (eq (org-element-property :type element) 'table.el)
21030 (org-edit-table.el)
21031 (call-interactively 'org-table-edit-formulas)))
21032 ;; Only Org tables contain `table-row' type elements.
21033 (`table-row (call-interactively 'org-table-edit-formulas))
21034 (`example-block (org-edit-src-code))
21035 (`export-block (org-edit-export-block))
21036 (`fixed-width (org-edit-fixed-width-region))
21038 ;; No notable element at point. Though, we may be at a link or
21039 ;; a footnote reference, which are objects. Thus, scan deeper.
21040 (let ((context (org-element-context element)))
21041 (pcase (org-element-type context)
21042 (`footnote-reference (org-edit-footnote-reference))
21043 (`inline-src-block (org-edit-inline-src-code))
21044 (`link (call-interactively #'ffap))
21045 (_ (user-error "No special environment to edit here"))))))))
21047 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21048 (defun org-ctrl-c-ctrl-c (&optional arg)
21049 "Set tags in headline, or update according to changed information at point.
21051 This command does many different things, depending on context:
21053 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21054 this is what we do.
21056 - If the cursor is on a statistics cookie, update it.
21058 - If the cursor is in a headline, prompt for tags and insert them
21059 into the current line, aligned to `org-tags-column'. When called
21060 with prefix arg, realign all tags in the current buffer.
21062 - If the cursor is in one of the special #+KEYWORD lines, this
21063 triggers scanning the buffer for these lines and updating the
21064 information.
21066 - If the cursor is inside a table, realign the table. This command
21067 works even if the automatic table editor has been turned off.
21069 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21070 the entire table.
21072 - If the cursor is at a footnote reference or definition, jump to
21073 the corresponding definition or references, respectively.
21075 - If the cursor is a the beginning of a dynamic block, update it.
21077 - If the current buffer is a capture buffer, close note and file it.
21079 - If the cursor is on a <<<target>>>, update radio targets and
21080 corresponding links in this buffer.
21082 - If the cursor is on a numbered item in a plain list, renumber the
21083 ordered list.
21085 - If the cursor is on a checkbox, toggle it.
21087 - If the cursor is on a code block, evaluate it. The variable
21088 `org-confirm-babel-evaluate' can be used to control prompting
21089 before code block evaluation, by default every code block
21090 evaluation requires confirmation. Code block evaluation can be
21091 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21092 (interactive "P")
21093 (cond
21094 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21095 org-occur-highlights)
21096 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21097 (org-remove-occur-highlights)
21098 (message "Temporary highlights/overlays removed from current buffer"))
21099 ((and (local-variable-p 'org-finish-function (current-buffer))
21100 (fboundp org-finish-function))
21101 (funcall org-finish-function))
21102 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21104 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21105 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21106 (user-error "C-c C-c can do nothing useful at this location"))
21107 (let* ((context (org-element-context))
21108 (type (org-element-type context)))
21109 (cl-case type
21110 ;; When at a link, act according to the parent instead.
21111 (link (setq context (org-element-property :parent context))
21112 (setq type (org-element-type context)))
21113 ;; Unsupported object types: refer to the first supported
21114 ;; element or object containing it.
21115 ((bold code entity export-snippet inline-babel-call inline-src-block
21116 italic latex-fragment line-break macro strike-through subscript
21117 superscript underline verbatim)
21118 (setq context
21119 (org-element-lineage
21120 context '(radio-target paragraph verse-block table-cell)))))
21121 ;; For convenience: at the first line of a paragraph on the
21122 ;; same line as an item, apply function on that item instead.
21123 (when (eq type 'paragraph)
21124 (let ((parent (org-element-property :parent context)))
21125 (when (and (eq (org-element-type parent) 'item)
21126 (= (line-beginning-position)
21127 (org-element-property :begin parent)))
21128 (setq context parent type 'item))))
21129 ;; Act according to type of element or object at point.
21130 (cl-case type
21131 (clock (org-clock-update-time-maybe))
21132 (dynamic-block
21133 (save-excursion
21134 (goto-char (org-element-property :post-affiliated context))
21135 (org-update-dblock)))
21136 (footnote-definition
21137 (goto-char (org-element-property :post-affiliated context))
21138 (call-interactively 'org-footnote-action))
21139 (footnote-reference (call-interactively 'org-footnote-action))
21140 ((headline inlinetask)
21141 (save-excursion (goto-char (org-element-property :begin context))
21142 (call-interactively 'org-set-tags)))
21143 (item
21144 ;; At an item: a double C-u set checkbox to "[-]"
21145 ;; unconditionally, whereas a single one will toggle its
21146 ;; presence. Without a universal argument, if the item
21147 ;; has a checkbox, toggle it. Otherwise repair the list.
21148 (let* ((box (org-element-property :checkbox context))
21149 (struct (org-element-property :structure context))
21150 (old-struct (copy-tree struct))
21151 (parents (org-list-parents-alist struct))
21152 (prevs (org-list-prevs-alist struct))
21153 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21154 (org-list-set-checkbox
21155 (org-element-property :begin context) struct
21156 (cond ((equal arg '(16)) "[-]")
21157 ((and (not box) (equal arg '(4))) "[ ]")
21158 ((or (not box) (equal arg '(4))) nil)
21159 ((eq box 'on) "[ ]")
21160 (t "[X]")))
21161 ;; Mimic `org-list-write-struct' but with grabbing
21162 ;; a return value from `org-list-struct-fix-box'.
21163 (org-list-struct-fix-ind struct parents 2)
21164 (org-list-struct-fix-item-end struct)
21165 (org-list-struct-fix-bul struct prevs)
21166 (org-list-struct-fix-ind struct parents)
21167 (let ((block-item
21168 (org-list-struct-fix-box struct parents prevs orderedp)))
21169 (if (and box (equal struct old-struct))
21170 (if (equal arg '(16))
21171 (message "Checkboxes already reset")
21172 (user-error "Cannot toggle this checkbox: %s"
21173 (if (eq box 'on)
21174 "all subitems checked"
21175 "unchecked subitems")))
21176 (org-list-struct-apply-struct struct old-struct)
21177 (org-update-checkbox-count-maybe))
21178 (when block-item
21179 (message "Checkboxes were removed due to empty box at line %d"
21180 (org-current-line block-item))))))
21181 (keyword
21182 (let ((org-inhibit-startup-visibility-stuff t)
21183 (org-startup-align-all-tables nil))
21184 (when (boundp 'org-table-coordinate-overlays)
21185 (mapc #'delete-overlay org-table-coordinate-overlays)
21186 (setq org-table-coordinate-overlays nil))
21187 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21188 (message "Local setup has been refreshed"))
21189 (plain-list
21190 ;; At a plain list, with a double C-u argument, set
21191 ;; checkboxes of each item to "[-]", whereas a single one
21192 ;; will toggle their presence according to the state of the
21193 ;; first item in the list. Without an argument, repair the
21194 ;; list.
21195 (let* ((begin (org-element-property :contents-begin context))
21196 (beginm (move-marker (make-marker) begin))
21197 (struct (org-element-property :structure context))
21198 (old-struct (copy-tree struct))
21199 (first-box (save-excursion
21200 (goto-char begin)
21201 (looking-at org-list-full-item-re)
21202 (match-string-no-properties 3)))
21203 (new-box (cond ((equal arg '(16)) "[-]")
21204 ((equal arg '(4)) (unless first-box "[ ]"))
21205 ((equal first-box "[X]") "[ ]")
21206 (t "[X]"))))
21207 (cond
21208 (arg
21209 (dolist (pos
21210 (org-list-get-all-items
21211 begin struct (org-list-prevs-alist struct)))
21212 (org-list-set-checkbox pos struct new-box)))
21213 ((and first-box (eq (point) begin))
21214 ;; For convenience, when point is at bol on the first
21215 ;; item of the list and no argument is provided, simply
21216 ;; toggle checkbox of that item, if any.
21217 (org-list-set-checkbox begin struct new-box)))
21218 (org-list-write-struct
21219 struct (org-list-parents-alist struct) old-struct)
21220 (org-update-checkbox-count-maybe)
21221 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21222 ((property-drawer node-property)
21223 (call-interactively 'org-property-action))
21224 ((radio-target target)
21225 (call-interactively 'org-update-radio-target-regexp))
21226 (statistics-cookie
21227 (call-interactively 'org-update-statistics-cookies))
21228 ((table table-cell table-row)
21229 ;; At a table, recalculate every field and align it. Also
21230 ;; send the table if necessary. If the table has
21231 ;; a `table.el' type, just give up. At a table row or
21232 ;; cell, maybe recalculate line but always align table.
21233 (if (eq (org-element-property :type context) 'table.el)
21234 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21235 Use \\[org-edit-special] to edit table.el tables"))
21236 (let ((org-enable-table-editor t))
21237 (if (or (eq type 'table)
21238 ;; Check if point is at a TBLFM line.
21239 (and (eq type 'table-row)
21240 (= (point) (org-element-property :end context))))
21241 (save-excursion
21242 (if (org-at-TBLFM-p)
21243 (progn (require 'org-table)
21244 (org-table-calc-current-TBLFM))
21245 (goto-char (org-element-property :contents-begin context))
21246 (org-call-with-arg 'org-table-recalculate (or arg t))
21247 (orgtbl-send-table 'maybe)))
21248 (org-table-maybe-eval-formula)
21249 (cond (arg (call-interactively 'org-table-recalculate))
21250 ((org-table-maybe-recalculate-line))
21251 (t (org-table-align)))))))
21252 (timestamp (org-timestamp-change 0 'day))
21253 (otherwise
21254 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21255 (user-error
21256 "C-c C-c can do nothing useful at this location")))))))))
21258 (defun org-mode-restart ()
21259 (interactive)
21260 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21261 (funcall major-mode)
21262 (hack-local-variables)
21263 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21264 (org-indent-mode -1)))
21265 (message "%s restarted" major-mode))
21267 (defun org-kill-note-or-show-branches ()
21268 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21269 (interactive)
21270 (if (not org-finish-function)
21271 (progn
21272 (outline-hide-subtree)
21273 (call-interactively 'outline-show-branches))
21274 (let ((org-note-abort t))
21275 (funcall org-finish-function))))
21277 (defun org-delete-indentation (&optional ARG)
21278 "Join current line to previous and fix whitespace at join.
21280 If previous line is a headline add to headline title. Otherwise
21281 the function calls `delete-indentation'.
21283 With argument, join this line to following line."
21284 (interactive "*P")
21285 (if (save-excursion
21286 (if ARG (beginning-of-line)
21287 (forward-line -1))
21288 (looking-at org-complex-heading-regexp))
21289 ;; At headline.
21290 (let ((tags-column (when (match-beginning 5)
21291 (save-excursion (goto-char (match-beginning 5))
21292 (current-column))))
21293 (string (concat " " (progn (when ARG (forward-line 1))
21294 (org-trim (delete-and-extract-region
21295 (line-beginning-position)
21296 (line-end-position)))))))
21297 (unless (bobp) (delete-region (point) (1- (point))))
21298 (goto-char (or (match-end 4)
21299 (match-beginning 5)
21300 (match-end 0)))
21301 (skip-chars-backward " \t")
21302 (save-excursion (insert string))
21303 ;; Adjust alignment of tags.
21304 (when tags-column
21305 (org-align-tags-here (if org-auto-align-tags
21306 org-tags-column
21307 tags-column))))
21308 (delete-indentation ARG)))
21310 (defun org-open-line (n)
21311 "Insert a new row in tables, call `open-line' elsewhere.
21312 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21313 (interactive "*p")
21314 (cond
21315 ((not org-special-ctrl-o)
21316 (open-line n))
21317 ((org-at-table-p)
21318 (org-table-insert-row))
21320 (open-line n))))
21322 (defun org-return (&optional indent)
21323 "Goto next table row or insert a newline.
21325 Calls `org-table-next-row' or `newline', depending on context.
21327 When optional INDENT argument is non-nil, call
21328 `newline-and-indent' instead of `newline'.
21330 When `org-return-follows-link' is non-nil and point is on
21331 a timestamp or a link, call `org-open-at-point'. However, it
21332 will not happen if point is in a table or on a \"dead\"
21333 object (e.g., within a comment). In these case, you need to use
21334 `org-open-at-point' directly."
21335 (interactive)
21336 (let ((context (if org-return-follows-link (org-element-context)
21337 (org-element-at-point))))
21338 (cond
21339 ;; In a table, call `org-table-next-row'.
21340 ((or (and (eq (org-element-type context) 'table)
21341 (>= (point) (org-element-property :contents-begin context))
21342 (< (point) (org-element-property :contents-end context)))
21343 (org-element-lineage context '(table-row table-cell) t))
21344 (org-table-justify-field-maybe)
21345 (call-interactively #'org-table-next-row))
21346 ;; On a link or a timestamp, call `org-open-at-point' if
21347 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21348 ;; locations, e.g., in a comment, as `org-open-at-point'.
21349 ((and org-return-follows-link
21350 (or (org-in-regexp org-ts-regexp-both nil t)
21351 (org-in-regexp org-tsr-regexp-both nil t)
21352 (org-in-regexp org-any-link-re nil t)))
21353 (call-interactively #'org-open-at-point))
21354 ;; Insert newline in heading, but preserve tags.
21355 ((and (not (bolp))
21356 (save-excursion (beginning-of-line)
21357 (looking-at org-complex-heading-regexp)))
21358 ;; At headline. Split line. However, if point is on keyword,
21359 ;; priority cookie or tags, do not break any of them: add
21360 ;; a newline after the headline instead.
21361 (let ((tags-column (and (match-beginning 5)
21362 (save-excursion (goto-char (match-beginning 5))
21363 (current-column))))
21364 (string
21365 (when (and (match-end 4)
21366 (>= (point)
21367 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21368 (<= (point) (match-end 4)))
21369 (delete-and-extract-region (point) (match-end 4)))))
21370 (when (and tags-column string) ; Adjust tag alignment.
21371 (org-align-tags-here
21372 (if org-auto-align-tags org-tags-column tags-column)))
21373 (end-of-line)
21374 (org-show-entry)
21375 (if indent (newline-and-indent) (newline))
21376 (when string (save-excursion (insert (org-trim string))))))
21377 ;; In a list, make sure indenting keeps trailing text within.
21378 ((and indent
21379 (not (eolp))
21380 (org-element-lineage context '(item)))
21381 (let ((trailing-data
21382 (delete-and-extract-region (point) (line-end-position))))
21383 (newline-and-indent)
21384 (save-excursion (insert trailing-data))))
21385 (t (if indent (newline-and-indent) (newline))))))
21387 (defun org-return-indent ()
21388 "Goto next table row or insert a newline and indent.
21389 Calls `org-table-next-row' or `newline-and-indent', depending on
21390 context. See the individual commands for more information."
21391 (interactive)
21392 (org-return t))
21394 (defun org-ctrl-c-star ()
21395 "Compute table, or change heading status of lines.
21396 Calls `org-table-recalculate' or `org-toggle-heading',
21397 depending on context."
21398 (interactive)
21399 (cond
21400 ((org-at-table-p)
21401 (call-interactively 'org-table-recalculate))
21403 ;; Convert all lines in region to list items
21404 (call-interactively 'org-toggle-heading))))
21406 (defun org-ctrl-c-minus ()
21407 "Insert separator line in table or modify bullet status of line.
21408 Also turns a plain line or a region of lines into list items.
21409 Calls `org-table-insert-hline', `org-toggle-item', or
21410 `org-cycle-list-bullet', depending on context."
21411 (interactive)
21412 (cond
21413 ((org-at-table-p)
21414 (call-interactively 'org-table-insert-hline))
21415 ((org-region-active-p)
21416 (call-interactively 'org-toggle-item))
21417 ((org-in-item-p)
21418 (call-interactively 'org-cycle-list-bullet))
21420 (call-interactively 'org-toggle-item))))
21422 (defun org-toggle-item (arg)
21423 "Convert headings or normal lines to items, items to normal lines.
21424 If there is no active region, only the current line is considered.
21426 If the first non blank line in the region is a headline, convert
21427 all headlines to items, shifting text accordingly.
21429 If it is an item, convert all items to normal lines.
21431 If it is normal text, change region into a list of items.
21432 With a prefix argument ARG, change the region in a single item."
21433 (interactive "P")
21434 (let ((shift-text
21435 (function
21436 ;; Shift text in current section to IND, from point to END.
21437 ;; The function leaves point to END line.
21438 (lambda (ind end)
21439 (let ((min-i 1000) (end (copy-marker end)))
21440 ;; First determine the minimum indentation (MIN-I) of
21441 ;; the text.
21442 (save-excursion
21443 (catch 'exit
21444 (while (< (point) end)
21445 (let ((i (org-get-indentation)))
21446 (cond
21447 ;; Skip blank lines and inline tasks.
21448 ((looking-at "^[ \t]*$"))
21449 ((looking-at org-outline-regexp-bol))
21450 ;; We can't find less than 0 indentation.
21451 ((zerop i) (throw 'exit (setq min-i 0)))
21452 ((< i min-i) (setq min-i i))))
21453 (forward-line))))
21454 ;; Then indent each line so that a line indented to
21455 ;; MIN-I becomes indented to IND. Ignore blank lines
21456 ;; and inline tasks in the process.
21457 (let ((delta (- ind min-i)))
21458 (while (< (point) end)
21459 (unless (or (looking-at "^[ \t]*$")
21460 (looking-at org-outline-regexp-bol))
21461 (indent-line-to (+ (org-get-indentation) delta)))
21462 (forward-line)))))))
21463 (skip-blanks
21464 (function
21465 ;; Return beginning of first non-blank line, starting from
21466 ;; line at POS.
21467 (lambda (pos)
21468 (save-excursion
21469 (goto-char pos)
21470 (skip-chars-forward " \r\t\n")
21471 (point-at-bol)))))
21472 beg end)
21473 ;; Determine boundaries of changes.
21474 (if (org-region-active-p)
21475 (setq beg (funcall skip-blanks (region-beginning))
21476 end (copy-marker (region-end)))
21477 (setq beg (funcall skip-blanks (point-at-bol))
21478 end (copy-marker (point-at-eol))))
21479 ;; Depending on the starting line, choose an action on the text
21480 ;; between BEG and END.
21481 (org-with-limited-levels
21482 (save-excursion
21483 (goto-char beg)
21484 (cond
21485 ;; Case 1. Start at an item: de-itemize. Note that it only
21486 ;; happens when a region is active: `org-ctrl-c-minus'
21487 ;; would call `org-cycle-list-bullet' otherwise.
21488 ((org-at-item-p)
21489 (while (< (point) end)
21490 (when (org-at-item-p)
21491 (skip-chars-forward " \t")
21492 (delete-region (point) (match-end 0)))
21493 (forward-line)))
21494 ;; Case 2. Start at an heading: convert to items.
21495 ((org-at-heading-p)
21496 (let* ((bul (org-list-bullet-string "-"))
21497 (bul-len (length bul))
21498 (done (org-entry-is-done-p))
21499 (todo (org-entry-is-todo-p))
21500 ;; Indentation of the first heading. It should be
21501 ;; relative to the indentation of its parent, if any.
21502 (start-ind (save-excursion
21503 (cond
21504 ((not org-adapt-indentation) 0)
21505 ((not (outline-previous-heading)) 0)
21506 (t (length (match-string 0))))))
21507 ;; Level of first heading. Further headings will be
21508 ;; compared to it to determine hierarchy in the list.
21509 (ref-level (org-reduced-level (org-outline-level))))
21510 (when (or done todo) (org-todo ""))
21511 (while (< (point) end)
21512 (let* ((level (org-reduced-level (org-outline-level)))
21513 (delta (max 0 (- level ref-level))))
21514 ;; If current headline is less indented than the first
21515 ;; one, set it as reference, in order to preserve
21516 ;; subtrees.
21517 (when (< level ref-level) (setq ref-level level))
21518 (replace-match bul t t)
21519 (indent-line-to (+ start-ind (* delta bul-len)))
21520 (when (or done todo)
21521 (let* ((struct (org-list-struct))
21522 (old (copy-tree struct)))
21523 (org-list-set-checkbox (line-beginning-position)
21524 struct
21525 (if done "[X]" "[ ]"))
21526 (org-list-write-struct struct
21527 (org-list-parents-alist struct)
21528 old)))
21529 ;; Ensure all text down to END (or SECTION-END) belongs
21530 ;; to the newly created item.
21531 (let ((section-end (save-excursion
21532 (or (outline-next-heading) (point)))))
21533 (forward-line)
21534 (funcall shift-text
21535 (+ start-ind (* (1+ delta) bul-len))
21536 (min end section-end)))))))
21537 ;; Case 3. Normal line with ARG: make the first line of region
21538 ;; an item, and shift indentation of others lines to
21539 ;; set them as item's body.
21540 (arg (let* ((bul (org-list-bullet-string "-"))
21541 (bul-len (length bul))
21542 (ref-ind (org-get-indentation)))
21543 (skip-chars-forward " \t")
21544 (insert bul)
21545 (forward-line)
21546 (while (< (point) end)
21547 ;; Ensure that lines less indented than first one
21548 ;; still get included in item body.
21549 (funcall shift-text
21550 (+ ref-ind bul-len)
21551 (min end (save-excursion (or (outline-next-heading)
21552 (point)))))
21553 (forward-line))))
21554 ;; Case 4. Normal line without ARG: turn each non-item line
21555 ;; into an item.
21557 (while (< (point) end)
21558 (unless (or (org-at-heading-p) (org-at-item-p))
21559 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21560 (replace-match
21561 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21562 (forward-line))))))))
21564 (defun org-toggle-heading (&optional nstars)
21565 "Convert headings to normal text, or items or text to headings.
21566 If there is no active region, only convert the current line.
21568 With a \\[universal-argument] prefix, convert the whole list at
21569 point into heading.
21571 In a region:
21573 - If the first non blank line is a headline, remove the stars
21574 from all headlines in the region.
21576 - If it is a normal line, turn each and every normal line (i.e.,
21577 not an heading or an item) in the region into headings. If you
21578 want to convert only the first line of this region, use one
21579 universal prefix argument.
21581 - If it is a plain list item, turn all plain list items into headings.
21583 When converting a line into a heading, the number of stars is chosen
21584 such that the lines become children of the current entry. However,
21585 when a numeric prefix argument is given, its value determines the
21586 number of stars to add."
21587 (interactive "P")
21588 (let ((skip-blanks
21589 (function
21590 ;; Return beginning of first non-blank line, starting from
21591 ;; line at POS.
21592 (lambda (pos)
21593 (save-excursion
21594 (goto-char pos)
21595 (while (org-at-comment-p) (forward-line))
21596 (skip-chars-forward " \r\t\n")
21597 (point-at-bol)))))
21598 beg end toggled)
21599 ;; Determine boundaries of changes. If a universal prefix has
21600 ;; been given, put the list in a region. If region ends at a bol,
21601 ;; do not consider the last line to be in the region.
21603 (when (and current-prefix-arg (org-at-item-p))
21604 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21605 (org-mark-element))
21607 (if (org-region-active-p)
21608 (setq beg (funcall skip-blanks (region-beginning))
21609 end (copy-marker (save-excursion
21610 (goto-char (region-end))
21611 (if (bolp) (point) (point-at-eol)))))
21612 (setq beg (funcall skip-blanks (point-at-bol))
21613 end (copy-marker (point-at-eol))))
21614 ;; Ensure inline tasks don't count as headings.
21615 (org-with-limited-levels
21616 (save-excursion
21617 (goto-char beg)
21618 (cond
21619 ;; Case 1. Started at an heading: de-star headings.
21620 ((org-at-heading-p)
21621 (while (< (point) end)
21622 (when (org-at-heading-p t)
21623 (looking-at org-outline-regexp) (replace-match "")
21624 (setq toggled t))
21625 (forward-line)))
21626 ;; Case 2. Started at an item: change items into headlines.
21627 ;; One star will be added by `org-list-to-subtree'.
21628 ((org-at-item-p)
21629 (while (< (point) end)
21630 (when (org-at-item-p)
21631 ;; Pay attention to cases when region ends before list.
21632 (let* ((struct (org-list-struct))
21633 (list-end
21634 (min (org-list-get-bottom-point struct) (1+ end))))
21635 (save-restriction
21636 (narrow-to-region (point) list-end)
21637 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21638 (setq toggled t))
21639 (forward-line)))
21640 ;; Case 3. Started at normal text: make every line an heading,
21641 ;; skipping headlines and items.
21642 (t (let* ((stars
21643 (make-string
21644 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21645 (add-stars
21646 (cond (nstars "") ; stars from prefix only
21647 ((equal stars "") "*") ; before first heading
21648 (org-odd-levels-only "**") ; inside heading, odd
21649 (t "*"))) ; inside heading, oddeven
21650 (rpl (concat stars add-stars " "))
21651 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21652 (while (< (point) (if (equal nstars '(4)) lend end))
21653 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21654 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21655 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21656 (forward-line)))))))
21657 (unless toggled (message "Cannot toggle heading from here"))))
21659 (defun org-meta-return (&optional _arg)
21660 "Insert a new heading or wrap a region in a table.
21661 Calls `org-insert-heading' or `org-table-wrap-region', depending
21662 on context. See the individual commands for more information."
21663 (interactive)
21664 (org-check-before-invisible-edit 'insert)
21665 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21666 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21667 #'org-insert-heading))))
21669 ;;; Menu entries
21671 (defsubst org-in-subtree-not-table-p ()
21672 "Are we in a subtree and not in a table?"
21673 (and (not (org-before-first-heading-p))
21674 (not (org-at-table-p))))
21676 ;; Define the Org-mode menus
21677 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21678 '("Tbl"
21679 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21680 ["Next Field" org-cycle (org-at-table-p)]
21681 ["Previous Field" org-shifttab (org-at-table-p)]
21682 ["Next Row" org-return (org-at-table-p)]
21683 "--"
21684 ["Blank Field" org-table-blank-field (org-at-table-p)]
21685 ["Edit Field" org-table-edit-field (org-at-table-p)]
21686 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21687 "--"
21688 ("Column"
21689 ["Move Column Left" org-metaleft (org-at-table-p)]
21690 ["Move Column Right" org-metaright (org-at-table-p)]
21691 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21692 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21693 ("Row"
21694 ["Move Row Up" org-metaup (org-at-table-p)]
21695 ["Move Row Down" org-metadown (org-at-table-p)]
21696 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21697 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21698 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21699 "--"
21700 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21701 ("Rectangle"
21702 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21703 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21704 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21705 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21706 "--"
21707 ("Calculate"
21708 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21709 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21710 ["Edit Formulas" org-edit-special (org-at-table-p)]
21711 "--"
21712 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21713 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21714 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21715 "--"
21716 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21717 "--"
21718 ["Sum Column/Rectangle" org-table-sum
21719 (or (org-at-table-p) (org-region-active-p))]
21720 ["Which Column?" org-table-current-column (org-at-table-p)])
21721 ["Debug Formulas"
21722 org-table-toggle-formula-debugger
21723 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21724 ["Show Col/Row Numbers"
21725 org-table-toggle-coordinate-overlays
21726 :style toggle
21727 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21728 "--"
21729 ["Create" org-table-create (and (not (org-at-table-p))
21730 org-enable-table-editor)]
21731 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21732 ["Import from File" org-table-import (not (org-at-table-p))]
21733 ["Export to File" org-table-export (org-at-table-p)]
21734 "--"
21735 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21736 "--"
21737 ("Plot"
21738 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21739 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21741 (easy-menu-define org-org-menu org-mode-map "Org menu"
21742 '("Org"
21743 ("Show/Hide"
21744 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21745 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21746 ["Sparse Tree..." org-sparse-tree t]
21747 ["Reveal Context" org-reveal t]
21748 ["Show All" outline-show-all t]
21749 "--"
21750 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21751 "--"
21752 ["New Heading" org-insert-heading t]
21753 ("Navigate Headings"
21754 ["Up" outline-up-heading t]
21755 ["Next" outline-next-visible-heading t]
21756 ["Previous" outline-previous-visible-heading t]
21757 ["Next Same Level" outline-forward-same-level t]
21758 ["Previous Same Level" outline-backward-same-level t]
21759 "--"
21760 ["Jump" org-goto t])
21761 ("Edit Structure"
21762 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21763 "--"
21764 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21765 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21766 "--"
21767 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21768 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21769 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21770 "--"
21771 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21772 "--"
21773 ["Copy visible text" org-copy-visible t]
21774 "--"
21775 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21776 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21777 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21778 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21779 "--"
21780 ["Sort Region/Children" org-sort t]
21781 "--"
21782 ["Convert to odd levels" org-convert-to-odd-levels t]
21783 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21784 ("Editing"
21785 ["Emphasis..." org-emphasize t]
21786 ["Edit Source Example" org-edit-special t]
21787 "--"
21788 ["Footnote new/jump" org-footnote-action t]
21789 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21790 ("Archive"
21791 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21792 "--"
21793 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21794 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21795 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21797 "--"
21798 ("Hyperlinks"
21799 ["Store Link (Global)" org-store-link t]
21800 ["Find existing link to here" org-occur-link-in-agenda-files t]
21801 ["Insert Link" org-insert-link t]
21802 ["Follow Link" org-open-at-point t]
21803 "--"
21804 ["Next link" org-next-link t]
21805 ["Previous link" org-previous-link t]
21806 "--"
21807 ["Descriptive Links"
21808 org-toggle-link-display
21809 :style radio
21810 :selected org-descriptive-links
21812 ["Literal Links"
21813 org-toggle-link-display
21814 :style radio
21815 :selected (not org-descriptive-links)])
21816 "--"
21817 ("TODO Lists"
21818 ["TODO/DONE/-" org-todo t]
21819 ("Select keyword"
21820 ["Next keyword" org-shiftright (org-at-heading-p)]
21821 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21822 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21823 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21824 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21825 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21826 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21827 "--"
21828 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21829 :selected org-enforce-todo-dependencies :style toggle :active t]
21830 "Settings for tree at point"
21831 ["Do Children sequentially" org-toggle-ordered-property :style radio
21832 :selected (org-entry-get nil "ORDERED")
21833 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21834 ["Do Children parallel" org-toggle-ordered-property :style radio
21835 :selected (not (org-entry-get nil "ORDERED"))
21836 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21837 "--"
21838 ["Set Priority" org-priority t]
21839 ["Priority Up" org-shiftup t]
21840 ["Priority Down" org-shiftdown t]
21841 "--"
21842 ["Get news from all feeds" org-feed-update-all t]
21843 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21844 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21845 ("TAGS and Properties"
21846 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21847 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21848 "--"
21849 ["Set property" org-set-property (not (org-before-first-heading-p))]
21850 ["Column view of properties" org-columns t]
21851 ["Insert Column View DBlock" org-columns-insert-dblock t])
21852 ("Dates and Scheduling"
21853 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21854 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21855 ("Change Date"
21856 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21857 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21858 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21859 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21860 ["Compute Time Range" org-evaluate-time-range t]
21861 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21862 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21863 "--"
21864 ["Custom time format" org-toggle-time-stamp-overlays
21865 :style radio :selected org-display-custom-times]
21866 "--"
21867 ["Goto Calendar" org-goto-calendar t]
21868 ["Date from Calendar" org-date-from-calendar t]
21869 "--"
21870 ["Start/Restart Timer" org-timer-start t]
21871 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21872 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21873 ["Insert Timer String" org-timer t]
21874 ["Insert Timer Item" org-timer-item t])
21875 ("Logging work"
21876 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21877 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21878 ["Clock out" org-clock-out t]
21879 ["Clock cancel" org-clock-cancel t]
21880 "--"
21881 ["Mark as default task" org-clock-mark-default-task t]
21882 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21883 ["Goto running clock" org-clock-goto t]
21884 "--"
21885 ["Display times" org-clock-display t]
21886 ["Create clock table" org-clock-report t]
21887 "--"
21888 ["Record DONE time"
21889 (progn (setq org-log-done (not org-log-done))
21890 (message "Switching to %s will %s record a timestamp"
21891 (car org-done-keywords)
21892 (if org-log-done "automatically" "not")))
21893 :style toggle :selected org-log-done])
21894 "--"
21895 ["Agenda Command..." org-agenda t]
21896 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21897 ("File List for Agenda")
21898 ("Special views current file"
21899 ["TODO Tree" org-show-todo-tree t]
21900 ["Check Deadlines" org-check-deadlines t]
21901 ["Timeline" org-timeline t]
21902 ["Tags/Property tree" org-match-sparse-tree t])
21903 "--"
21904 ["Export/Publish..." org-export-dispatch t]
21905 ("LaTeX"
21906 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21907 :selected org-cdlatex-mode]
21908 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21909 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21910 ["Modify math symbol" org-cdlatex-math-modify
21911 (org-inside-LaTeX-fragment-p)]
21912 ["Insert citation" org-reftex-citation t]
21913 "--"
21914 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21915 "--"
21916 ("MobileOrg"
21917 ["Push Files and Views" org-mobile-push t]
21918 ["Get Captured and Flagged" org-mobile-pull t]
21919 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21920 "--"
21921 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21922 "--"
21923 ("Documentation"
21924 ["Show Version" org-version t]
21925 ["Info Documentation" org-info t])
21926 ("Customize"
21927 ["Browse Org Group" org-customize t]
21928 "--"
21929 ["Expand This Menu" org-create-customize-menu
21930 (fboundp 'customize-menu-create)])
21931 ["Send bug report" org-submit-bug-report t]
21932 "--"
21933 ("Refresh/Reload"
21934 ["Refresh setup current buffer" org-mode-restart t]
21935 ["Reload Org (after update)" org-reload t]
21936 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21939 (defun org-info (&optional node)
21940 "Read documentation for Org-mode in the info system.
21941 With optional NODE, go directly to that node."
21942 (interactive)
21943 (info (format "(org)%s" (or node ""))))
21945 ;;;###autoload
21946 (defun org-submit-bug-report ()
21947 "Submit a bug report on Org-mode via mail.
21949 Don't hesitate to report any problems or inaccurate documentation.
21951 If you don't have setup sending mail from (X)Emacs, please copy the
21952 output buffer into your mail program, as it gives us important
21953 information about your Org-mode version and configuration."
21954 (interactive)
21955 (require 'reporter)
21956 (defvar reporter-prompt-for-summary-p)
21957 (org-load-modules-maybe)
21958 (org-require-autoloaded-modules)
21959 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21960 (reporter-submit-bug-report
21961 "emacs-orgmode@gnu.org"
21962 (org-version nil 'full)
21963 (let (list)
21964 (save-window-excursion
21965 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21966 (delete-other-windows)
21967 (erase-buffer)
21968 (insert "You are about to submit a bug report to the Org-mode mailing list.
21970 We would like to add your full Org-mode and Outline configuration to the
21971 bug report. This greatly simplifies the work of the maintainer and
21972 other experts on the mailing list.
21974 HOWEVER, some variables you have customized may contain private
21975 information. The names of customers, colleagues, or friends, might
21976 appear in the form of file names, tags, todo states, or search strings.
21977 If you answer yes to the prompt, you might want to check and remove
21978 such private information before sending the email.")
21979 (add-text-properties (point-min) (point-max) '(face org-warning))
21980 (when (yes-or-no-p "Include your Org-mode configuration ")
21981 (mapatoms
21982 (lambda (v)
21983 (and (boundp v)
21984 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21985 (or (and (symbol-value v)
21986 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21987 (and
21988 (get v 'custom-type) (get v 'standard-value)
21989 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21990 (push v list)))))
21991 (kill-buffer (get-buffer "*Warn about privacy*"))
21992 list))
21993 nil nil
21994 "Remember to cover the basics, that is, what you expected to happen and
21995 what in fact did happen. You don't know how to make a good report? See
21997 http://orgmode.org/manual/Feedback.html#Feedback
21999 Your bug report will be posted to the Org-mode mailing list.
22000 ------------------------------------------------------------------------")
22001 (save-excursion
22002 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
22003 (replace-match "\\1Bug: \\3 [\\2]")))))
22006 (defun org-install-agenda-files-menu ()
22007 (let ((bl (buffer-list)))
22008 (save-excursion
22009 (while bl
22010 (set-buffer (pop bl))
22011 (when (derived-mode-p 'org-mode) (setq bl nil)))
22012 (when (derived-mode-p 'org-mode)
22013 (easy-menu-change
22014 '("Org") "File List for Agenda"
22015 (append
22016 (list
22017 ["Edit File List" (org-edit-agenda-file-list) t]
22018 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
22019 ["Remove Current File from List" org-remove-file t]
22020 ["Cycle through agenda files" org-cycle-agenda-files t]
22021 ["Occur in all agenda files" org-occur-in-agenda-files t]
22022 "--")
22023 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22025 ;;;; Documentation
22027 (defun org-require-autoloaded-modules ()
22028 (interactive)
22029 (mapc #'require
22030 '(org-agenda org-archive org-attach org-clock org-colview org-id
22031 org-table org-timer)))
22033 ;;;###autoload
22034 (defun org-reload (&optional uncompiled)
22035 "Reload all org lisp files.
22036 With prefix arg UNCOMPILED, load the uncompiled versions."
22037 (interactive "P")
22038 (require 'loadhist)
22039 (let* ((org-dir (org-find-library-dir "org"))
22040 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22041 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22042 (remove-re (format "\\`%s\\'"
22043 (regexp-opt '("org" "org-loaddefs" "org-version"))))
22044 (feats (delete-dups
22045 (mapcar 'file-name-sans-extension
22046 (mapcar 'file-name-nondirectory
22047 (delq nil
22048 (mapcar 'feature-file
22049 features))))))
22050 (lfeat (append
22051 (sort
22052 (setq feats
22053 (delq nil (mapcar
22054 (lambda (f)
22055 (if (and (string-match feature-re f)
22056 (not (string-match remove-re f)))
22057 f nil))
22058 feats)))
22059 'string-lessp)
22060 (list "org-version" "org")))
22061 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22062 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22063 load-uncore load-misses)
22064 (setq load-misses
22065 (delq 't
22066 (mapcar (lambda (f)
22067 (or (org-load-noerror-mustsuffix (concat org-dir f))
22068 (and (string= org-dir contrib-dir)
22069 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22070 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22071 (add-to-list 'load-uncore f 'append)
22074 lfeat)))
22075 (when load-uncore
22076 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22077 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22078 (if load-misses
22079 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22080 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22081 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22083 ;;;###autoload
22084 (defun org-customize ()
22085 "Call the customize function with org as argument."
22086 (interactive)
22087 (org-load-modules-maybe)
22088 (org-require-autoloaded-modules)
22089 (customize-browse 'org))
22091 (defun org-create-customize-menu ()
22092 "Create a full customization menu for Org-mode, insert it into the menu."
22093 (interactive)
22094 (org-load-modules-maybe)
22095 (org-require-autoloaded-modules)
22096 (if (fboundp 'customize-menu-create)
22097 (progn
22098 (easy-menu-change
22099 '("Org") "Customize"
22100 `(["Browse Org group" org-customize t]
22101 "--"
22102 ,(customize-menu-create 'org)
22103 ["Set" Custom-set t]
22104 ["Save" Custom-save t]
22105 ["Reset to Current" Custom-reset-current t]
22106 ["Reset to Saved" Custom-reset-saved t]
22107 ["Reset to Standard Settings" Custom-reset-standard t]))
22108 (message "\"Org\"-menu now contains full customization menu"))
22109 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22111 ;;;; Miscellaneous stuff
22113 ;;; Generally useful functions
22115 (defun org-get-at-eol (property n)
22116 "Get text property PROPERTY at the end of line less N characters."
22117 (get-text-property (- (point-at-eol) n) property))
22119 (defun org-find-text-property-in-string (prop s)
22120 "Return the first non-nil value of property PROP in string S."
22121 (or (get-text-property 0 prop s)
22122 (get-text-property (or (next-single-property-change 0 prop s) 0)
22123 prop s)))
22125 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22126 "Display the given MESSAGE as a warning."
22127 (if (fboundp 'display-warning)
22128 (display-warning 'org message :warning)
22129 (let ((buf (get-buffer-create "*Org warnings*")))
22130 (with-current-buffer buf
22131 (goto-char (point-max))
22132 (insert "Warning (Org): " message)
22133 (unless (bolp)
22134 (newline)))
22135 (display-buffer buf)
22136 (sit-for 0))))
22138 (defun org-eval (form)
22139 "Eval FORM and return result."
22140 (condition-case error
22141 (eval form)
22142 (error (format "%%![Error: %s]" error))))
22144 (defun org-in-clocktable-p ()
22145 "Check if the cursor is in a clocktable."
22146 (let ((pos (point)) start)
22147 (save-excursion
22148 (end-of-line 1)
22149 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22150 (setq start (match-beginning 0))
22151 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22152 (>= (match-end 0) pos)
22153 start))))
22155 (defun org-in-verbatim-emphasis ()
22156 (save-match-data
22157 (and (org-in-regexp org-emph-re 2)
22158 (>= (point) (match-beginning 3))
22159 (<= (point) (match-end 4))
22160 (member (match-string 3) '("=" "~")))))
22162 (defun org-overlay-display (ovl text &optional face evap)
22163 "Make overlay OVL display TEXT with face FACE."
22164 (overlay-put ovl 'display text)
22165 (if face (overlay-put ovl 'face face))
22166 (if evap (overlay-put ovl 'evaporate t)))
22168 (defun org-overlay-before-string (ovl text &optional face evap)
22169 "Make overlay OVL display TEXT with face FACE."
22170 (if face (org-add-props text nil 'face face))
22171 (overlay-put ovl 'before-string text)
22172 (if evap (overlay-put ovl 'evaporate t)))
22174 (defun org-find-overlays (prop &optional pos delete)
22175 "Find all overlays specifying PROP at POS or point.
22176 If DELETE is non-nil, delete all those overlays."
22177 (let (found)
22178 (dolist (ov (overlays-at (or pos (point))) found)
22179 (cond ((not (overlay-get ov prop)))
22180 (delete (delete-overlay ov))
22181 (t (push ov found))))))
22183 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22184 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22185 (if (and marker (marker-buffer marker)
22186 (buffer-live-p (marker-buffer marker)))
22187 (progn
22188 (org-pop-to-buffer-same-window (marker-buffer marker))
22189 (when (or (> marker (point-max)) (< marker (point-min)))
22190 (widen))
22191 (goto-char marker)
22192 (org-show-context 'org-goto))
22193 (if bookmark
22194 (bookmark-jump bookmark)
22195 (error "Cannot find location"))))
22197 (defun org-quote-csv-field (s)
22198 "Quote field for inclusion in CSV material."
22199 (if (string-match "[\",]" s)
22200 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22203 (defun org-force-self-insert (N)
22204 "Needed to enforce self-insert under remapping."
22205 (interactive "p")
22206 (self-insert-command N))
22208 (defun org-string-width (s)
22209 "Compute width of string, ignoring invisible characters.
22210 This ignores character with invisibility property `org-link', and also
22211 characters with property `org-cwidth', because these will become invisible
22212 upon the next fontification round."
22213 (let (b l)
22214 (when (or (eq t buffer-invisibility-spec)
22215 (assq 'org-link buffer-invisibility-spec))
22216 (while (setq b (text-property-any 0 (length s)
22217 'invisible 'org-link s))
22218 (setq s (concat (substring s 0 b)
22219 (substring s (or (next-single-property-change
22220 b 'invisible s)
22221 (length s)))))))
22222 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22223 (setq s (concat (substring s 0 b)
22224 (substring s (or (next-single-property-change
22225 b 'org-cwidth s)
22226 (length s))))))
22227 (setq l (string-width s) b -1)
22228 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22229 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22232 (defun org-shorten-string (s maxlength)
22233 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22234 If the string is shorter or has length MAXLENGTH, just return the
22235 original string. If it is longer, the functions finds a space in the
22236 string, breaks this string off at that locations and adds three dots
22237 as ellipsis. Including the ellipsis, the string will not be longer
22238 than MAXLENGTH. If finding a good breaking point in the string does
22239 not work, the string is just chopped off in the middle of a word
22240 if necessary."
22241 (if (<= (length s) maxlength)
22243 (let* ((n (max (- maxlength 4) 1))
22244 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22245 (if (string-match re s)
22246 (concat (match-string 1 s) "...")
22247 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22249 (defun org-get-indentation (&optional line)
22250 "Get the indentation of the current line, interpreting tabs.
22251 When LINE is given, assume it represents a line and compute its indentation."
22252 (if line
22253 (when (string-match "^ *" (org-remove-tabs line))
22254 (match-end 0))
22255 (save-excursion
22256 (beginning-of-line 1)
22257 (skip-chars-forward " \t")
22258 (current-column))))
22260 (defun org-get-string-indentation (s)
22261 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22262 (let ((n -1) (i 0) (w tab-width) c)
22263 (catch 'exit
22264 (while (< (setq n (1+ n)) (length s))
22265 (setq c (aref s n))
22266 (cond ((= c ?\ ) (setq i (1+ i)))
22267 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22268 (t (throw 'exit t)))))
22271 (defun org-remove-tabs (s &optional width)
22272 "Replace tabulators in S with spaces.
22273 Assumes that s is a single line, starting in column 0."
22274 (setq width (or width tab-width))
22275 (while (string-match "\t" s)
22276 (setq s (replace-match
22277 (make-string
22278 (- (* width (/ (+ (match-beginning 0) width) width))
22279 (match-beginning 0)) ?\ )
22280 t t s)))
22283 (defun org-fix-indentation (line ind)
22284 "Fix indentation in LINE.
22285 IND is a cons cell with target and minimum indentation.
22286 If the current indentation in LINE is smaller than the minimum,
22287 leave it alone. If it is larger than ind, set it to the target."
22288 (let* ((l (org-remove-tabs line))
22289 (i (org-get-indentation l))
22290 (i1 (car ind)) (i2 (cdr ind)))
22291 (when (>= i i2) (setq l (substring line i2)))
22292 (if (> i1 0)
22293 (concat (make-string i1 ?\ ) l)
22294 l)))
22296 (defun org-remove-indentation (code &optional n)
22297 "Remove maximum common indentation in string CODE and return it.
22298 N may optionally be the number of columns to remove. Return CODE
22299 as-is if removal failed."
22300 (with-temp-buffer
22301 (insert code)
22302 (if (org-do-remove-indentation n) (buffer-string) code)))
22304 (defun org-do-remove-indentation (&optional n)
22305 "Remove the maximum common indentation from the buffer.
22306 When optional argument N is a positive integer, remove exactly
22307 that much characters from indentation, if possible. Return nil
22308 if it fails."
22309 (catch :exit
22310 (goto-char (point-min))
22311 ;; Find maximum common indentation, if not specified.
22312 (let ((n (or n
22313 (let ((min-ind (point-max)))
22314 (save-excursion
22315 (while (re-search-forward "^[ \t]*\\S-" nil t)
22316 (let ((ind (1- (current-column))))
22317 (if (zerop ind) (throw :exit nil)
22318 (setq min-ind (min min-ind ind))))))
22319 min-ind))))
22320 (if (zerop n) (throw :exit nil)
22321 ;; Remove exactly N indentation, but give up if not possible.
22322 (while (not (eobp))
22323 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22324 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22325 ((< ind n) (throw :exit nil))
22326 (t (indent-line-to (- ind n))))
22327 (forward-line)))
22328 ;; Signal success.
22329 t))))
22331 (defun org-fill-template (template alist)
22332 "Find each %key of ALIST in TEMPLATE and replace it."
22333 (let ((case-fold-search nil))
22334 (dolist (entry (sort (copy-sequence alist)
22335 (lambda (a b) (< (length (car a)) (length (car b))))))
22336 (setq template
22337 (replace-regexp-in-string
22338 (concat "%" (regexp-quote (car entry)))
22339 (or (cdr entry) "") template t t)))
22340 template))
22342 (defun org-base-buffer (buffer)
22343 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22344 (if (not buffer)
22345 buffer
22346 (or (buffer-base-buffer buffer)
22347 buffer)))
22349 (defun org-wrap (string &optional width lines)
22350 "Wrap string to either a number of lines, or a width in characters.
22351 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22352 that costs. If there is a word longer than WIDTH, the text is actually
22353 wrapped to the length of that word.
22354 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22355 many lines, whatever width that takes.
22356 The return value is a list of lines, without newlines at the end."
22357 (let* ((words (org-split-string string "[ \t\n]+"))
22358 (maxword (apply 'max (mapcar 'org-string-width words)))
22359 w ll)
22360 (cond (width
22361 (org-do-wrap words (max maxword width)))
22362 (lines
22363 (setq w maxword)
22364 (setq ll (org-do-wrap words maxword))
22365 (if (<= (length ll) lines)
22367 (setq ll words)
22368 (while (> (length ll) lines)
22369 (setq w (1+ w))
22370 (setq ll (org-do-wrap words w)))
22371 ll))
22372 (t (error "Cannot wrap this")))))
22374 (defun org-do-wrap (words width)
22375 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22376 (let (lines line)
22377 (while words
22378 (setq line (pop words))
22379 (while (and words (< (+ (length line) (length (car words))) width))
22380 (setq line (concat line " " (pop words))))
22381 (setq lines (push line lines)))
22382 (nreverse lines)))
22384 (defun org-split-string (string &optional separators)
22385 "Splits STRING into substrings at SEPARATORS.
22386 SEPARATORS is a regular expression.
22387 No empty strings are returned if there are matches at the beginning
22388 and end of string."
22389 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22390 (let ((start 0) notfirst list)
22391 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22392 (if (and notfirst
22393 (= start (match-beginning 0))
22394 (< start (length string)))
22395 (1+ start) start))
22396 (< (match-beginning 0) (length string)))
22397 (setq notfirst t)
22398 (or (eq (match-beginning 0) 0)
22399 (and (eq (match-beginning 0) (match-end 0))
22400 (eq (match-beginning 0) start))
22401 (push (substring string start (match-beginning 0)) list))
22402 (setq start (match-end 0)))
22403 (or (eq start (length string))
22404 (push (substring string start) list))
22405 (nreverse list)))
22407 (defun org-quote-vert (s)
22408 "Replace \"|\" with \"\\vert\"."
22409 (while (string-match "|" s)
22410 (setq s (replace-match "\\vert" t t s)))
22413 (defun org-uuidgen-p (s)
22414 "Is S an ID created by UUIDGEN?"
22415 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22417 (defun org-in-src-block-p (&optional inside)
22418 "Whether point is in a code source block.
22419 When INSIDE is non-nil, don't consider we are within a src block
22420 when point is at #+BEGIN_SRC or #+END_SRC."
22421 (let ((case-fold-search t))
22422 (or (and (eq (get-char-property (point) 'src-block) t))
22423 (and (not inside)
22424 (save-match-data
22425 (save-excursion
22426 (beginning-of-line)
22427 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22429 (defun org-context ()
22430 "Return a list of contexts of the current cursor position.
22431 If several contexts apply, all are returned.
22432 Each context entry is a list with a symbol naming the context, and
22433 two positions indicating start and end of the context. Possible
22434 contexts are:
22436 :headline anywhere in a headline
22437 :headline-stars on the leading stars in a headline
22438 :todo-keyword on a TODO keyword (including DONE) in a headline
22439 :tags on the TAGS in a headline
22440 :priority on the priority cookie in a headline
22441 :item on the first line of a plain list item
22442 :item-bullet on the bullet/number of a plain list item
22443 :checkbox on the checkbox in a plain list item
22444 :table in an org-mode table
22445 :table-special on a special filed in a table
22446 :table-table in a table.el table
22447 :clocktable in a clocktable
22448 :src-block in a source block
22449 :link on a hyperlink
22450 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22451 :target on a <<target>>
22452 :radio-target on a <<<radio-target>>>
22453 :latex-fragment on a LaTeX fragment
22454 :latex-preview on a LaTeX fragment with overlaid preview image
22456 This function expects the position to be visible because it uses font-lock
22457 faces as a help to recognize the following contexts: :table-special, :link,
22458 and :keyword."
22459 (let* ((f (get-text-property (point) 'face))
22460 (faces (if (listp f) f (list f)))
22461 (case-fold-search t)
22462 (p (point)) clist o)
22463 ;; First the large context
22464 (cond
22465 ((org-at-heading-p t)
22466 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22467 (when (progn
22468 (beginning-of-line 1)
22469 (looking-at org-todo-line-tags-regexp))
22470 (push (org-point-in-group p 1 :headline-stars) clist)
22471 (push (org-point-in-group p 2 :todo-keyword) clist)
22472 (push (org-point-in-group p 4 :tags) clist))
22473 (goto-char p)
22474 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22475 (when (looking-at "\\[#[A-Z0-9]\\]")
22476 (push (org-point-in-group p 0 :priority) clist)))
22478 ((org-at-item-p)
22479 (push (org-point-in-group p 2 :item-bullet) clist)
22480 (push (list :item (point-at-bol)
22481 (save-excursion (org-end-of-item) (point)))
22482 clist)
22483 (and (org-at-item-checkbox-p)
22484 (push (org-point-in-group p 0 :checkbox) clist)))
22486 ((org-at-table-p)
22487 (push (list :table (org-table-begin) (org-table-end)) clist)
22488 (when (memq 'org-formula faces)
22489 (push (list :table-special
22490 (previous-single-property-change p 'face)
22491 (next-single-property-change p 'face)) clist)))
22492 ((org-at-table-p 'any)
22493 (push (list :table-table) clist)))
22494 (goto-char p)
22496 (let ((case-fold-search t))
22497 ;; New the "medium" contexts: clocktables, source blocks
22498 (cond ((org-in-clocktable-p)
22499 (push (list :clocktable
22500 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22501 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22502 (match-beginning 1))
22503 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22504 (match-end 0))) clist))
22505 ((org-in-src-block-p)
22506 (push (list :src-block
22507 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22508 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22509 (match-beginning 1))
22510 (and (search-forward "#+END_SRC" nil t)
22511 (match-beginning 0))) clist))))
22512 (goto-char p)
22514 ;; Now the small context
22515 (cond
22516 ((org-at-timestamp-p)
22517 (push (org-point-in-group p 0 :timestamp) clist))
22518 ((memq 'org-link faces)
22519 (push (list :link
22520 (previous-single-property-change p 'face)
22521 (next-single-property-change p 'face)) clist))
22522 ((memq 'org-special-keyword faces)
22523 (push (list :keyword
22524 (previous-single-property-change p 'face)
22525 (next-single-property-change p 'face)) clist))
22526 ((org-at-target-p)
22527 (push (org-point-in-group p 0 :target) clist)
22528 (goto-char (1- (match-beginning 0)))
22529 (when (looking-at org-radio-target-regexp)
22530 (push (org-point-in-group p 0 :radio-target) clist))
22531 (goto-char p))
22532 ((setq o (cl-some
22533 (lambda (o)
22534 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22536 (overlays-at (point))))
22537 (push (list :latex-fragment
22538 (overlay-start o) (overlay-end o)) clist)
22539 (push (list :latex-preview
22540 (overlay-start o) (overlay-end o)) clist))
22541 ((org-inside-LaTeX-fragment-p)
22542 ;; FIXME: positions wrong.
22543 (push (list :latex-fragment (point) (point)) clist)))
22545 (setq clist (nreverse (delq nil clist)))
22546 clist))
22548 (defun org-in-regexp (regexp &optional nlines visually)
22549 "Check if point is inside a match of REGEXP.
22551 Normally only the current line is checked, but you can include
22552 NLINES extra lines around point into the search. If VISUALLY is
22553 set, require that the cursor is not after the match but really
22554 on, so that the block visually is on the match.
22556 Return nil or a cons cell (BEG . END) where BEG and END are,
22557 respectively, the positions at the beginning and the end of the
22558 match."
22559 (catch :exit
22560 (let ((pos (point))
22561 (eol (line-end-position (if nlines (1+ nlines) 1))))
22562 (save-excursion
22563 (beginning-of-line (- 1 (or nlines 0)))
22564 (while (and (re-search-forward regexp eol t)
22565 (<= (match-beginning 0) pos))
22566 (let ((end (match-end 0)))
22567 (when (or (> end pos) (and (= end pos) (not visually)))
22568 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22569 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22570 "Org mode 8.3")
22572 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22573 "Non-nil when point is between matches of START-RE and END-RE.
22575 Also return a non-nil value when point is on one of the matches.
22577 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22578 buffer positions. Default values are the positions of headlines
22579 surrounding the point.
22581 The functions returns a cons cell whose car (resp. cdr) is the
22582 position before START-RE (resp. after END-RE)."
22583 (save-match-data
22584 (let ((pos (point))
22585 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22586 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22587 beg end)
22588 (save-excursion
22589 ;; Point is on a block when on START-RE or if START-RE can be
22590 ;; found before it...
22591 (and (or (org-in-regexp start-re)
22592 (re-search-backward start-re limit-up t))
22593 (setq beg (match-beginning 0))
22594 ;; ... and END-RE after it...
22595 (goto-char (match-end 0))
22596 (re-search-forward end-re limit-down t)
22597 (> (setq end (match-end 0)) pos)
22598 ;; ... without another START-RE in-between.
22599 (goto-char (match-beginning 0))
22600 (not (re-search-backward start-re (1+ beg) t))
22601 ;; Return value.
22602 (cons beg end))))))
22604 (defun org-in-block-p (names)
22605 "Non-nil when point belongs to a block whose name belongs to NAMES.
22607 NAMES is a list of strings containing names of blocks.
22609 Return first block name matched, or nil. Beware that in case of
22610 nested blocks, the returned name may not belong to the closest
22611 block from point."
22612 (save-match-data
22613 (catch 'exit
22614 (let ((case-fold-search t)
22615 (lim-up (save-excursion (outline-previous-heading)))
22616 (lim-down (save-excursion (outline-next-heading))))
22617 (dolist (name names)
22618 (let ((n (regexp-quote name)))
22619 (when (org-between-regexps-p
22620 (concat "^[ \t]*#\\+begin_" n)
22621 (concat "^[ \t]*#\\+end_" n)
22622 lim-up lim-down)
22623 (throw 'exit n)))))
22624 nil)))
22626 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22627 "Call `multi-occur' with buffers for all agenda files."
22628 (interactive "sOrg-files matching: ")
22629 (let* ((files (org-agenda-files))
22630 (tnames (mapcar #'file-truename files))
22631 (extra org-agenda-text-search-extra-files))
22632 (when (eq (car extra) 'agenda-archives)
22633 (setq extra (cdr extra))
22634 (setq files (org-add-archive-files files)))
22635 (dolist (f extra)
22636 (unless (member (file-truename f) tnames)
22637 (unless (member f files) (setq files (append files (list f))))
22638 (setq tnames (append tnames (list (file-truename f))))))
22639 (multi-occur
22640 (mapcar (lambda (x)
22641 (with-current-buffer
22642 ;; FIXME: Why not just (find-file-noselect x)?
22643 ;; Is it to avoid the "revert buffer" prompt?
22644 (or (get-file-buffer x) (find-file-noselect x))
22645 (widen)
22646 (current-buffer)))
22647 files)
22648 regexp)))
22650 (if (boundp 'occur-mode-find-occurrence-hook)
22651 ;; Emacs 23
22652 (add-hook 'occur-mode-find-occurrence-hook
22653 (lambda ()
22654 (when (derived-mode-p 'org-mode)
22655 (org-reveal))))
22656 ;; Emacs 22
22657 (defadvice occur-mode-goto-occurrence
22658 (after org-occur-reveal activate)
22659 (and (derived-mode-p 'org-mode) (org-reveal)))
22660 (defadvice occur-mode-goto-occurrence-other-window
22661 (after org-occur-reveal activate)
22662 (and (derived-mode-p 'org-mode) (org-reveal)))
22663 (defadvice occur-mode-display-occurrence
22664 (after org-occur-reveal activate)
22665 (when (derived-mode-p 'org-mode)
22666 (let ((pos (occur-mode-find-occurrence)))
22667 (with-current-buffer (marker-buffer pos)
22668 (save-excursion
22669 (goto-char pos)
22670 (org-reveal)))))))
22672 (defun org-occur-link-in-agenda-files ()
22673 "Create a link and search for it in the agendas.
22674 The link is not stored in `org-stored-links', it is just created
22675 for the search purpose."
22676 (interactive)
22677 (let ((link (condition-case nil
22678 (org-store-link nil)
22679 (error "Unable to create a link to here"))))
22680 (org-occur-in-agenda-files (regexp-quote link))))
22682 (defun org-reverse-string (string)
22683 "Return the reverse of STRING."
22684 (apply 'string (reverse (string-to-list string))))
22686 ;; defsubst org-uniquify must be defined before first use
22688 (defun org-uniquify-alist (alist)
22689 "Merge elements of ALIST with the same key.
22691 For example, in this alist:
22693 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22694 => \\='((a 1 3) (b 2))
22696 merge (a 1) and (a 3) into (a 1 3).
22698 The function returns the new ALIST."
22699 (let (rtn)
22700 (dolist (e alist rtn)
22701 (let (n)
22702 (if (not (assoc (car e) rtn))
22703 (push e rtn)
22704 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22705 (setq rtn (assq-delete-all (car e) rtn))
22706 (push n rtn))))))
22708 (defun org-delete-all (elts list)
22709 "Remove all elements in ELTS from LIST."
22710 (while elts
22711 (setq list (delete (pop elts) list)))
22712 list)
22714 (defun org-back-over-empty-lines ()
22715 "Move backwards over whitespace, to the beginning of the first empty line.
22716 Returns the number of empty lines passed."
22717 (let ((pos (point)))
22718 (if (cdr (assoc 'heading org-blank-before-new-entry))
22719 (skip-chars-backward " \t\n\r")
22720 (unless (eobp)
22721 (forward-line -1)))
22722 (beginning-of-line 2)
22723 (goto-char (min (point) pos))
22724 (count-lines (point) pos)))
22726 (defun org-skip-whitespace ()
22727 (skip-chars-forward " \t\n\r"))
22729 (defun org-point-in-group (point group &optional context)
22730 "Check if POINT is in match-group GROUP.
22731 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22732 match. If the match group does not exist or point is not inside it,
22733 return nil."
22734 (and (match-beginning group)
22735 (>= point (match-beginning group))
22736 (<= point (match-end group))
22737 (if context
22738 (list context (match-beginning group) (match-end group))
22739 t)))
22741 (defun org-switch-to-buffer-other-window (&rest args)
22742 "Switch to buffer in a second window on the current frame.
22743 In particular, do not allow pop-up frames.
22744 Returns the newly created buffer."
22745 (org-no-popups
22746 (apply 'switch-to-buffer-other-window args)))
22748 (defun org-combine-plists (&rest plists)
22749 "Create a single property list from all plists in PLISTS.
22750 The process starts by copying the first list, and then setting properties
22751 from the other lists. Settings in the last list are the most significant
22752 ones and overrule settings in the other lists."
22753 (let ((rtn (copy-sequence (pop plists)))
22754 p v ls)
22755 (while plists
22756 (setq ls (pop plists))
22757 (while ls
22758 (setq p (pop ls) v (pop ls))
22759 (setq rtn (plist-put rtn p v))))
22760 rtn))
22762 (defun org-replace-escapes (string table)
22763 "Replace %-escapes in STRING with values in TABLE.
22764 TABLE is an association list with keys like \"%a\" and string values.
22765 The sequences in STRING may contain normal field width and padding information,
22766 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22767 so values can contain further %-escapes if they are define later in TABLE."
22768 (let ((tbl (copy-alist table))
22769 (case-fold-search nil)
22770 (pchg 0)
22771 re rpl)
22772 (dolist (e tbl)
22773 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22774 (when (and (cdr e) (string-match re (cdr e)))
22775 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22776 (safe "SREF"))
22777 (add-text-properties 0 3 (list 'sref sref) safe)
22778 (setcdr e (replace-match safe t t (cdr e)))))
22779 (while (string-match re string)
22780 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22781 (cdr e)))
22782 (setq string (replace-match rpl t t string))))
22783 (while (setq pchg (next-property-change pchg string))
22784 (let ((sref (get-text-property pchg 'sref string)))
22785 (when (and sref (string-match "SREF" string pchg))
22786 (setq string (replace-match sref t t string)))))
22787 string))
22789 (defun org-sublist (list start end)
22790 "Return a section of LIST, from START to END.
22792 Counting starts at 1."
22793 (cl-subseq list (1- start) end))
22794 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22796 (defun org-find-base-buffer-visiting (file)
22797 "Like `find-buffer-visiting' but always return the base buffer and
22798 not an indirect buffer."
22799 (let ((buf (or (get-file-buffer file)
22800 (find-buffer-visiting file))))
22801 (if buf
22802 (or (buffer-base-buffer buf) buf)
22803 nil)))
22805 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22806 "Org 9.0")
22808 ;;; TODO: Only called once, from ox-odt which should probably use
22809 ;;; org-export-inline-image-p or something.
22810 (defun org-file-image-p (file)
22811 "Return non-nil if FILE is an image."
22812 (save-match-data
22813 (string-match (image-file-name-regexp) file)))
22815 (defun org-get-cursor-date (&optional with-time)
22816 "Return the date at cursor in as a time.
22817 This works in the calendar and in the agenda, anywhere else it just
22818 returns the current time.
22819 If WITH-TIME is non-nil, returns the time of the event at point (in
22820 the agenda) or the current time of the day."
22821 (let (date day defd tp hod mod)
22822 (when with-time
22823 (setq tp (get-text-property (point) 'time))
22824 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22825 (setq hod (string-to-number (match-string 1 tp))
22826 mod (string-to-number (match-string 2 tp))))
22827 (or tp (let ((now (decode-time)))
22828 (setq hod (nth 2 now)
22829 mod (nth 1 now)))))
22830 (cond
22831 ((eq major-mode 'calendar-mode)
22832 (setq date (calendar-cursor-to-date)
22833 defd (encode-time 0 (or mod 0) (or hod 0)
22834 (nth 1 date) (nth 0 date) (nth 2 date))))
22835 ((eq major-mode 'org-agenda-mode)
22836 (setq day (get-text-property (point) 'day))
22837 (when day
22838 (setq date (calendar-gregorian-from-absolute day)
22839 defd (encode-time 0 (or mod 0) (or hod 0)
22840 (nth 1 date) (nth 0 date) (nth 2 date))))))
22841 (or defd (current-time))))
22843 (defun org-mark-subtree (&optional up)
22844 "Mark the current subtree.
22845 This puts point at the start of the current subtree, and mark at
22846 the end. If a numeric prefix UP is given, move up into the
22847 hierarchy of headlines by UP levels before marking the subtree."
22848 (interactive "P")
22849 (org-with-limited-levels
22850 (cond ((org-at-heading-p) (beginning-of-line))
22851 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22852 (t (outline-previous-visible-heading 1))))
22853 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22854 (if (org-called-interactively-p 'any)
22855 (call-interactively 'org-mark-element)
22856 (org-mark-element)))
22858 (defun org-file-newer-than-p (file time)
22859 "Non-nil if FILE is newer than TIME.
22860 FILE is a filename, as a string, TIME is a list of integers, as
22861 returned by, e.g., `current-time'."
22862 (and (file-exists-p file)
22863 ;; Only compare times up to whole seconds as some file-systems
22864 ;; (e.g. HFS+) do not retain any finer granularity. As
22865 ;; a consequence, make sure we return non-nil when the two
22866 ;; times are equal.
22867 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22868 (cl-subseq time 0 2)))))
22870 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22871 "Compile a SOURCE file using PROCESS.
22873 PROCESS is either a function or a list of shell commands, as
22874 strings. EXT is a file extension, without the leading dot, as
22875 a string. It is used to check if the process actually succeeded.
22877 PROCESS must create a file with the same base name and directory
22878 as SOURCE, but ending with EXT. The function then returns its
22879 filename. Otherwise, it raises an error. The error message can
22880 then be refined by providing string ERR-MSG, which is appended to
22881 the standard message.
22883 If PROCESS is a function, it is called with a single argument:
22884 the SOURCE file.
22886 If it is a list of commands, each of them is called using
22887 `shell-command'. By default, in each command, %b, %f, %F and %o
22888 are replaced with, respectively, SOURCE base name, name, full
22889 name and directory. It is possible, however, to use more
22890 place-holders by specifying them in optional argument SPEC, as an
22891 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22893 When PROCESS is a list of commands, optional argument LOG-BUF can
22894 be set to a buffer or a buffer name. `shell-command' then uses
22895 it for output.
22897 `default-directory' is set to SOURCE directory during the whole
22898 process."
22899 (let* ((source-name (file-name-nondirectory source))
22900 (base-name (file-name-sans-extension source-name))
22901 (full-name (file-truename source))
22902 (out-dir (file-name-directory source))
22903 ;; Properly set working directory for compilation.
22904 (default-directory (file-name-directory full-name))
22905 (time (current-time))
22906 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22907 (save-window-excursion
22908 (pcase process
22909 ((pred functionp) (funcall process (shell-quote-argument source)))
22910 ((pred consp)
22911 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22912 (spec (append spec
22913 `((?b . ,(shell-quote-argument base-name))
22914 (?f . ,(shell-quote-argument source-name))
22915 (?F . ,(shell-quote-argument full-name))
22916 (?o . ,(shell-quote-argument out-dir))))))
22917 (dolist (command process)
22918 (shell-command (format-spec command spec) log-buf))))
22919 (_ (error "No valid command to process %S%s" source err-msg)))
22920 ;; Check for process failure.
22921 (let ((output (concat out-dir base-name "." ext)))
22922 (unless (org-file-newer-than-p output time)
22923 (error (format "File %S wasn't produced%s" output err-msg)))
22924 output))))
22926 ;;; Indentation
22928 (defun org--get-expected-indentation (element contentsp)
22929 "Expected indentation column for current line, according to ELEMENT.
22930 ELEMENT is an element containing point. CONTENTSP is non-nil
22931 when indentation is to be computed according to contents of
22932 ELEMENT."
22933 (let ((type (org-element-type element))
22934 (start (org-element-property :begin element))
22935 (post-affiliated (org-element-property :post-affiliated element)))
22936 (org-with-wide-buffer
22937 (cond
22938 (contentsp
22939 (cl-case type
22940 ((diary-sexp footnote-definition) 0)
22941 ((headline inlinetask nil)
22942 (if (not org-adapt-indentation) 0
22943 (let ((level (org-current-level)))
22944 (if level (1+ level) 0))))
22945 ((item plain-list) (org-list-item-body-column post-affiliated))
22947 (goto-char start)
22948 (org-get-indentation))))
22949 ((memq type '(headline inlinetask nil))
22950 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22951 (org--get-expected-indentation element t)
22953 ((memq type '(diary-sexp footnote-definition)) 0)
22954 ;; First paragraph of a footnote definition or an item.
22955 ;; Indent like parent.
22956 ((< (line-beginning-position) start)
22957 (org--get-expected-indentation
22958 (org-element-property :parent element) t))
22959 ;; At first line: indent according to previous sibling, if any,
22960 ;; ignoring footnote definitions and inline tasks, or parent's
22961 ;; contents.
22962 ((= (line-beginning-position) start)
22963 (catch 'exit
22964 (while t
22965 (if (= (point-min) start) (throw 'exit 0)
22966 (goto-char (1- start))
22967 (let* ((previous (org-element-at-point))
22968 (parent previous))
22969 (while (and parent (<= (org-element-property :end parent) start))
22970 (setq previous parent
22971 parent (org-element-property :parent parent)))
22972 (cond
22973 ((not previous) (throw 'exit 0))
22974 ((> (org-element-property :end previous) start)
22975 (throw 'exit (org--get-expected-indentation previous t)))
22976 ((memq (org-element-type previous)
22977 '(footnote-definition inlinetask))
22978 (setq start (org-element-property :begin previous)))
22979 (t (goto-char (org-element-property :begin previous))
22980 (throw 'exit
22981 (if (bolp) (org-get-indentation)
22982 ;; At first paragraph in an item or
22983 ;; a footnote definition.
22984 (org--get-expected-indentation
22985 (org-element-property :parent previous) t))))))))))
22986 ;; Otherwise, move to the first non-blank line above.
22988 (beginning-of-line)
22989 (let ((pos (point)))
22990 (skip-chars-backward " \r\t\n")
22991 (cond
22992 ;; Two blank lines end a footnote definition or a plain
22993 ;; list. When we indent an empty line after them, the
22994 ;; containing list or footnote definition is over, so it
22995 ;; qualifies as a previous sibling. Therefore, we indent
22996 ;; like its first line.
22997 ((and (memq type '(footnote-definition plain-list))
22998 (> (count-lines (point) pos) 2))
22999 (goto-char start)
23000 (org-get-indentation))
23001 ;; Line above is the first one of a paragraph at the
23002 ;; beginning of an item or a footnote definition. Indent
23003 ;; like parent.
23004 ((< (line-beginning-position) start)
23005 (org--get-expected-indentation
23006 (org-element-property :parent element) t))
23007 ;; Line above is the beginning of an element, i.e., point
23008 ;; was originally on the blank lines between element's start
23009 ;; and contents.
23010 ((= (line-beginning-position) post-affiliated)
23011 (org--get-expected-indentation element t))
23012 ;; POS is after contents in a greater element. Indent like
23013 ;; the beginning of the element.
23015 ;; As a special case, if point is at the end of a footnote
23016 ;; definition or an item, indent like the very last element
23017 ;; within. If that last element is an item, indent like its
23018 ;; contents.
23019 ((and (not (eq type 'paragraph))
23020 (let ((cend (org-element-property :contents-end element)))
23021 (and cend (<= cend pos))))
23022 (if (memq type '(footnote-definition item plain-list))
23023 (let ((last (org-element-at-point)))
23024 (org--get-expected-indentation
23025 last (eq (org-element-type last) 'item)))
23026 (goto-char start)
23027 (org-get-indentation)))
23028 ;; In any other case, indent like the current line.
23029 (t (org-get-indentation)))))))))
23031 (defun org--align-node-property ()
23032 "Align node property at point.
23033 Alignment is done according to `org-property-format', which see."
23034 (when (save-excursion
23035 (beginning-of-line)
23036 (looking-at org-property-re))
23037 (replace-match
23038 (concat (match-string 4)
23039 (org-trim
23040 (format org-property-format (match-string 1) (match-string 3))))
23041 t t)))
23043 (defun org-indent-line ()
23044 "Indent line depending on context.
23046 Indentation is done according to the following rules:
23048 - Footnote definitions, diary sexps, headlines and inline tasks
23049 have to start at column 0.
23051 - On the very first line of an element, consider, in order, the
23052 next rules until one matches:
23054 1. If there's a sibling element before, ignoring footnote
23055 definitions and inline tasks, indent like its first line.
23057 2. If element has a parent, indent like its contents. More
23058 precisely, if parent is an item, indent after the
23059 description part, if any, or the bullet (see
23060 `org-list-description-max-indent'). Else, indent like
23061 parent's first line.
23063 3. Otherwise, indent relatively to current level, if
23064 `org-adapt-indentation' is non-nil, or to left margin.
23066 - On a blank line at the end of an element, indent according to
23067 the type of the element. More precisely
23069 1. If element is a plain list, an item, or a footnote
23070 definition, indent like the very last element within.
23072 2. If element is a paragraph, indent like its last non blank
23073 line.
23075 3. Otherwise, indent like its very first line.
23077 - In the code part of a source block, use language major mode
23078 to indent current line if `org-src-tab-acts-natively' is
23079 non-nil. If it is nil, do nothing.
23081 - Otherwise, indent like the first non-blank line above.
23083 The function doesn't indent an item as it could break the whole
23084 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
23085 \\[org-shiftmetaright].
23087 Also align node properties according to `org-property-format'."
23088 (interactive)
23089 (cond
23090 (orgstruct-is-++
23091 (let ((indent-line-function
23092 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
23093 (indent-according-to-mode)))
23094 ((org-at-heading-p) 'noindent)
23096 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
23097 (type (org-element-type element)))
23098 (cond ((and (memq type '(plain-list item))
23099 (= (line-beginning-position)
23100 (org-element-property :post-affiliated element)))
23101 'noindent)
23102 ((and (eq type 'src-block)
23103 org-src-tab-acts-natively
23104 (> (line-beginning-position)
23105 (org-element-property :post-affiliated element))
23106 (< (line-beginning-position)
23107 (org-with-wide-buffer
23108 (goto-char (org-element-property :end element))
23109 (skip-chars-backward " \r\t\n")
23110 (line-beginning-position))))
23111 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23113 (let ((column (org--get-expected-indentation element nil)))
23114 ;; Preserve current column.
23115 (if (<= (current-column) (current-indentation))
23116 (indent-line-to column)
23117 (save-excursion (indent-line-to column))))
23118 ;; Align node property. Also preserve current column.
23119 (when (eq type 'node-property)
23120 (let ((column (current-column)))
23121 (org--align-node-property)
23122 (org-move-to-column column)))))))))
23124 (defun org-indent-region (start end)
23125 "Indent each non-blank line in the region.
23126 Called from a program, START and END specify the region to
23127 indent. The function will not indent contents of example blocks,
23128 verse blocks and export blocks as leading white spaces are
23129 assumed to be significant there."
23130 (interactive "r")
23131 (save-excursion
23132 (goto-char start)
23133 (skip-chars-forward " \r\t\n")
23134 (unless (eobp) (beginning-of-line))
23135 (let ((indent-to
23136 (lambda (ind pos)
23137 ;; Set IND as indentation for all lines between point and
23138 ;; POS. Blank lines are ignored. Leave point after POS
23139 ;; once done.
23140 (let ((limit (copy-marker pos)))
23141 (while (< (point) limit)
23142 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23143 (forward-line))
23144 (set-marker limit nil))))
23145 (end (copy-marker end)))
23146 (while (< (point) end)
23147 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23148 (let* ((element (org-element-at-point))
23149 (type (org-element-type element))
23150 (element-end (copy-marker (org-element-property :end element)))
23151 (ind (org--get-expected-indentation element nil)))
23152 (cond
23153 ((or (memq type '(paragraph table table-row))
23154 (not (or (org-element-property :contents-begin element)
23155 (memq type
23156 '(example-block export-block src-block)))))
23157 ;; Elements here are indented as a single block. Also
23158 ;; align node properties.
23159 (when (eq type 'node-property)
23160 (org--align-node-property)
23161 (beginning-of-line))
23162 (funcall indent-to ind (min element-end end)))
23164 ;; Elements in this category consist of three parts:
23165 ;; before the contents, the contents, and after the
23166 ;; contents. The contents are treated specially,
23167 ;; according to the element type, or not indented at
23168 ;; all. Other parts are indented as a single block.
23169 (let* ((post (copy-marker
23170 (org-element-property :post-affiliated element)))
23171 (cbeg
23172 (copy-marker
23173 (cond
23174 ((not (org-element-property :contents-begin element))
23175 ;; Fake contents for source blocks.
23176 (org-with-wide-buffer
23177 (goto-char post)
23178 (forward-line)
23179 (point)))
23180 ((memq type '(footnote-definition item plain-list))
23181 ;; Contents in these elements could start on
23182 ;; the same line as the beginning of the
23183 ;; element. Make sure we start indenting
23184 ;; from the second line.
23185 (org-with-wide-buffer
23186 (goto-char post)
23187 (end-of-line)
23188 (skip-chars-forward " \r\t\n")
23189 (if (eobp) (point) (line-beginning-position))))
23190 (t (org-element-property :contents-begin element)))))
23191 (cend (copy-marker
23192 (or (org-element-property :contents-end element)
23193 ;; Fake contents for source blocks.
23194 (org-with-wide-buffer
23195 (goto-char element-end)
23196 (skip-chars-backward " \r\t\n")
23197 (line-beginning-position)))
23198 t)))
23199 ;; Do not change items indentation individually as it
23200 ;; might break the list as a whole. On the other
23201 ;; hand, when at a plain list, indent it as a whole.
23202 (cond ((eq type 'plain-list)
23203 (let ((offset (- ind (org-get-indentation))))
23204 (unless (zerop offset)
23205 (indent-rigidly (org-element-property :begin element)
23206 (org-element-property :end element)
23207 offset))
23208 (goto-char cbeg)))
23209 ((eq type 'item) (goto-char cbeg))
23210 (t (funcall indent-to ind (min cbeg end))))
23211 (when (< (point) end)
23212 (cl-case type
23213 ((example-block export-block verse-block))
23214 (src-block
23215 ;; In a source block, indent source code
23216 ;; according to language major mode, but only if
23217 ;; `org-src-tab-acts-natively' is non-nil.
23218 (when (and (< (point) end) org-src-tab-acts-natively)
23219 (ignore-errors
23220 (org-babel-do-in-edit-buffer
23221 (indent-region (point-min) (point-max))))))
23222 (t (org-indent-region (point) (min cend end))))
23223 (goto-char (min cend end))
23224 (when (< (point) end)
23225 (funcall indent-to ind (min element-end end))))
23226 (set-marker post nil)
23227 (set-marker cbeg nil)
23228 (set-marker cend nil))))
23229 (set-marker element-end nil))))
23230 (set-marker end nil))))
23232 (defun org-indent-drawer ()
23233 "Indent the drawer at point."
23234 (interactive)
23235 (unless (save-excursion
23236 (beginning-of-line)
23237 (looking-at-p org-drawer-regexp))
23238 (user-error "Not at a drawer"))
23239 (let ((element (org-element-at-point)))
23240 (unless (memq (org-element-type element) '(drawer property-drawer))
23241 (user-error "Not at a drawer"))
23242 (org-with-wide-buffer
23243 (org-indent-region (org-element-property :begin element)
23244 (org-element-property :end element))))
23245 (message "Drawer at point indented"))
23247 (defun org-indent-block ()
23248 "Indent the block at point."
23249 (interactive)
23250 (unless (save-excursion
23251 (beginning-of-line)
23252 (let ((case-fold-search t))
23253 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23254 (user-error "Not at a block"))
23255 (let ((element (org-element-at-point)))
23256 (unless (memq (org-element-type element)
23257 '(comment-block center-block dynamic-block example-block
23258 export-block quote-block special-block
23259 src-block verse-block))
23260 (user-error "Not at a block"))
23261 (org-with-wide-buffer
23262 (org-indent-region (org-element-property :begin element)
23263 (org-element-property :end element))))
23264 (message "Block at point indented"))
23267 ;;; Filling
23269 ;; We use our own fill-paragraph and auto-fill functions.
23271 ;; `org-fill-paragraph' relies on adaptive filling and context
23272 ;; checking. Appropriate `fill-prefix' is computed with
23273 ;; `org-adaptive-fill-function'.
23275 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23276 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23277 ;; `org-adaptive-fill-function' value. Internally,
23278 ;; `org-comment-line-break-function' breaks the line.
23280 ;; `org-setup-filling' installs filling and auto-filling related
23281 ;; variables during `org-mode' initialization.
23283 (defvar org-element-paragraph-separate) ; org-element.el
23284 (defun org-setup-filling ()
23285 (require 'org-element)
23286 ;; Prevent auto-fill from inserting unwanted new items.
23287 (when (boundp 'fill-nobreak-predicate)
23288 (setq-local
23289 fill-nobreak-predicate
23290 (org-uniquify
23291 (append fill-nobreak-predicate
23292 '(org-fill-line-break-nobreak-p
23293 org-fill-paragraph-with-timestamp-nobreak-p)))))
23294 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23295 (setq-local paragraph-start paragraph-ending)
23296 (setq-local paragraph-separate paragraph-ending))
23297 (setq-local fill-paragraph-function 'org-fill-paragraph)
23298 (setq-local auto-fill-inhibit-regexp nil)
23299 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23300 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23301 (setq-local comment-line-break-function 'org-comment-line-break-function))
23303 (defun org-fill-line-break-nobreak-p ()
23304 "Non-nil when a new line at point would create an Org line break."
23305 (save-excursion
23306 (skip-chars-backward "[ \t]")
23307 (skip-chars-backward "\\\\")
23308 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23310 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23311 "Non-nil when a new line at point would split a timestamp."
23312 (and (org-at-timestamp-p t)
23313 (not (looking-at org-ts-regexp-both))))
23315 (declare-function message-in-body-p "message" ())
23316 (defvar orgtbl-line-start-regexp) ; From org-table.el
23317 (defun org-adaptive-fill-function ()
23318 "Compute a fill prefix for the current line.
23319 Return fill prefix, as a string, or nil if current line isn't
23320 meant to be filled. For convenience, if `adaptive-fill-regexp'
23321 matches in paragraphs or comments, use it."
23322 (catch 'exit
23323 (when (derived-mode-p 'message-mode)
23324 (save-excursion
23325 (beginning-of-line)
23326 (cond ((not (message-in-body-p)) (throw 'exit nil))
23327 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23328 ((looking-at message-cite-prefix-regexp)
23329 (throw 'exit (match-string-no-properties 0)))
23330 ((looking-at org-outline-regexp)
23331 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23332 (org-with-wide-buffer
23333 (unless (org-at-heading-p)
23334 (let* ((p (line-beginning-position))
23335 (element (save-excursion
23336 (beginning-of-line)
23337 (org-element-at-point)))
23338 (type (org-element-type element))
23339 (post-affiliated (org-element-property :post-affiliated element)))
23340 (unless (< p post-affiliated)
23341 (cl-case type
23342 (comment
23343 (save-excursion
23344 (beginning-of-line)
23345 (looking-at "[ \t]*")
23346 (concat (match-string 0) "# ")))
23347 (footnote-definition "")
23348 ((item plain-list)
23349 (make-string (org-list-item-body-column post-affiliated) ?\s))
23350 (paragraph
23351 ;; Fill prefix is usually the same as the current line,
23352 ;; unless the paragraph is at the beginning of an item.
23353 (let ((parent (org-element-property :parent element)))
23354 (save-excursion
23355 (beginning-of-line)
23356 (cond ((eq (org-element-type parent) 'item)
23357 (make-string (org-list-item-body-column
23358 (org-element-property :begin parent))
23359 ?\s))
23360 ((and adaptive-fill-regexp
23361 ;; Locally disable
23362 ;; `adaptive-fill-function' to let
23363 ;; `fill-context-prefix' handle
23364 ;; `adaptive-fill-regexp' variable.
23365 (let (adaptive-fill-function)
23366 (fill-context-prefix
23367 post-affiliated
23368 (org-element-property :end element)))))
23369 ((looking-at "[ \t]+") (match-string 0))
23370 (t "")))))
23371 (comment-block
23372 ;; Only fill contents if P is within block boundaries.
23373 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23374 (forward-line)
23375 (point)))
23376 (cend (save-excursion
23377 (goto-char (org-element-property :end element))
23378 (skip-chars-backward " \r\t\n")
23379 (line-beginning-position))))
23380 (when (and (>= p cbeg) (< p cend))
23381 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23382 (match-string 0)
23383 "")))))))))))
23385 (declare-function message-goto-body "message" ())
23386 (defvar message-cite-prefix-regexp) ; From message.el
23387 (defun org-fill-paragraph (&optional justify)
23388 "Fill element at point, when applicable.
23390 This function only applies to comment blocks, comments, example
23391 blocks and paragraphs. Also, as a special case, re-align table
23392 when point is at one.
23394 If JUSTIFY is non-nil (interactively, with prefix argument),
23395 justify as well. If `sentence-end-double-space' is non-nil, then
23396 period followed by one space does not end a sentence, so don't
23397 break a line there. The variable `fill-column' controls the
23398 width for filling.
23400 For convenience, when point is at a plain list, an item or
23401 a footnote definition, try to fill the first paragraph within."
23402 (interactive)
23403 (if (and (derived-mode-p 'message-mode)
23404 (or (not (message-in-body-p))
23405 (save-excursion (move-beginning-of-line 1)
23406 (looking-at message-cite-prefix-regexp))))
23407 ;; First ensure filling is correct in message-mode.
23408 (let ((fill-paragraph-function
23409 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23410 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23411 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23412 (paragraph-separate
23413 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23414 (fill-paragraph nil))
23415 (with-syntax-table org-mode-transpose-word-syntax-table
23416 ;; Move to end of line in order to get the first paragraph
23417 ;; within a plain list or a footnote definition.
23418 (let ((element (save-excursion
23419 (end-of-line)
23420 (or (ignore-errors (org-element-at-point))
23421 (user-error "An element cannot be parsed line %d"
23422 (line-number-at-pos (point)))))))
23423 ;; First check if point is in a blank line at the beginning of
23424 ;; the buffer. In that case, ignore filling.
23425 (cl-case (org-element-type element)
23426 ;; Use major mode filling function is src blocks.
23427 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23428 ;; Align Org tables, leave table.el tables as-is.
23429 (table-row (org-table-align) t)
23430 (table
23431 (when (eq (org-element-property :type element) 'org)
23432 (save-excursion
23433 (goto-char (org-element-property :post-affiliated element))
23434 (org-table-align)))
23436 (paragraph
23437 ;; Paragraphs may contain `line-break' type objects.
23438 (let ((beg (max (point-min)
23439 (org-element-property :contents-begin element)))
23440 (end (min (point-max)
23441 (org-element-property :contents-end element))))
23442 ;; Do nothing if point is at an affiliated keyword.
23443 (if (< (line-end-position) beg) t
23444 (when (derived-mode-p 'message-mode)
23445 ;; In `message-mode', do not fill following citation
23446 ;; in current paragraph nor text before message body.
23447 (let ((body-start (save-excursion (message-goto-body))))
23448 (when body-start (setq beg (max body-start beg))))
23449 (when (save-excursion
23450 (re-search-forward
23451 (concat "^" message-cite-prefix-regexp) end t))
23452 (setq end (match-beginning 0))))
23453 ;; Fill paragraph, taking line breaks into account.
23454 (save-excursion
23455 (goto-char beg)
23456 (let ((cuts (list beg)))
23457 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23458 (when (eq 'line-break
23459 (org-element-type
23460 (save-excursion (backward-char)
23461 (org-element-context))))
23462 (push (point) cuts)))
23463 (dolist (c (delq end cuts))
23464 (fill-region-as-paragraph c end justify)
23465 (setq end c))))
23466 t)))
23467 ;; Contents of `comment-block' type elements should be
23468 ;; filled as plain text, but only if point is within block
23469 ;; markers.
23470 (comment-block
23471 (let* ((case-fold-search t)
23472 (beg (save-excursion
23473 (goto-char (org-element-property :begin element))
23474 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23475 (forward-line)
23476 (point)))
23477 (end (save-excursion
23478 (goto-char (org-element-property :end element))
23479 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23480 (line-beginning-position))))
23481 (if (or (< (point) beg) (> (point) end)) t
23482 (fill-region-as-paragraph
23483 (save-excursion (end-of-line)
23484 (re-search-backward "^[ \t]*$" beg 'move)
23485 (line-beginning-position))
23486 (save-excursion (beginning-of-line)
23487 (re-search-forward "^[ \t]*$" end 'move)
23488 (line-beginning-position))
23489 justify))))
23490 ;; Fill comments.
23491 (comment
23492 (let ((begin (org-element-property :post-affiliated element))
23493 (end (org-element-property :end element)))
23494 (when (and (>= (point) begin) (<= (point) end))
23495 (let ((begin (save-excursion
23496 (end-of-line)
23497 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23498 (progn (forward-line) (point))
23499 begin)))
23500 (end (save-excursion
23501 (end-of-line)
23502 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23503 (1- (line-beginning-position))
23504 (skip-chars-backward " \r\t\n")
23505 (line-end-position)))))
23506 ;; Do not fill comments when at a blank line.
23507 (when (> end begin)
23508 (let ((fill-prefix
23509 (save-excursion
23510 (beginning-of-line)
23511 (looking-at "[ \t]*#")
23512 (let ((comment-prefix (match-string 0)))
23513 (goto-char (match-end 0))
23514 (if (looking-at adaptive-fill-regexp)
23515 (concat comment-prefix (match-string 0))
23516 (concat comment-prefix " "))))))
23517 (save-excursion
23518 (fill-region-as-paragraph begin end justify))))))
23520 ;; Ignore every other element.
23521 (otherwise t))))))
23523 (defun org-auto-fill-function ()
23524 "Auto-fill function."
23525 ;; Check if auto-filling is meaningful.
23526 (let ((fc (current-fill-column)))
23527 (when (and fc (> (current-column) fc))
23528 (let* ((fill-prefix (org-adaptive-fill-function))
23529 ;; Enforce empty fill prefix, if required. Otherwise, it
23530 ;; will be computed again.
23531 (adaptive-fill-mode (not (equal fill-prefix ""))))
23532 (when fill-prefix (do-auto-fill))))))
23534 (defun org-comment-line-break-function (&optional soft)
23535 "Break line at point and indent, continuing comment if within one.
23536 The inserted newline is marked hard if variable
23537 `use-hard-newlines' is true, unless optional argument SOFT is
23538 non-nil."
23539 (if soft (insert-and-inherit ?\n) (newline 1))
23540 (save-excursion (forward-char -1) (delete-horizontal-space))
23541 (delete-horizontal-space)
23542 (indent-to-left-margin)
23543 (insert-before-markers-and-inherit fill-prefix))
23546 ;;; Fixed Width Areas
23548 (defun org-toggle-fixed-width ()
23549 "Toggle fixed-width markup.
23551 Add or remove fixed-width markup on current line, whenever it
23552 makes sense. Return an error otherwise.
23554 If a region is active and if it contains only fixed-width areas
23555 or blank lines, remove all fixed-width markup in it. If the
23556 region contains anything else, convert all non-fixed-width lines
23557 to fixed-width ones.
23559 Blank lines at the end of the region are ignored unless the
23560 region only contains such lines."
23561 (interactive)
23562 (if (not (org-region-active-p))
23563 ;; No region:
23565 ;; Remove fixed width marker only in a fixed-with element.
23567 ;; Add fixed width maker in paragraphs, in blank lines after
23568 ;; elements or at the beginning of a headline or an inlinetask,
23569 ;; and before any one-line elements (e.g., a clock).
23570 (progn
23571 (beginning-of-line)
23572 (let* ((element (org-element-at-point))
23573 (type (org-element-type element)))
23574 (cond
23575 ((and (eq type 'fixed-width)
23576 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23577 (replace-match
23578 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23579 ((and (memq type '(babel-call clock comment diary-sexp headline
23580 horizontal-rule keyword paragraph
23581 planning))
23582 (<= (org-element-property :post-affiliated element) (point)))
23583 (skip-chars-forward " \t")
23584 (insert ": "))
23585 ((and (looking-at-p "[ \t]*$")
23586 (or (eq type 'inlinetask)
23587 (save-excursion
23588 (skip-chars-forward " \r\t\n")
23589 (<= (org-element-property :end element) (point)))))
23590 (delete-region (point) (line-end-position))
23591 (org-indent-line)
23592 (insert ": "))
23593 (t (user-error "Cannot insert a fixed-width line here")))))
23594 ;; Region active.
23595 (let* ((begin (save-excursion
23596 (goto-char (region-beginning))
23597 (line-beginning-position)))
23598 (end (copy-marker
23599 (save-excursion
23600 (goto-char (region-end))
23601 (unless (eolp) (beginning-of-line))
23602 (if (save-excursion (re-search-backward "\\S-" begin t))
23603 (progn (skip-chars-backward " \r\t\n") (point))
23604 (point)))))
23605 (all-fixed-width-p
23606 (catch 'not-all-p
23607 (save-excursion
23608 (goto-char begin)
23609 (skip-chars-forward " \r\t\n")
23610 (when (eobp) (throw 'not-all-p nil))
23611 (while (< (point) end)
23612 (let ((element (org-element-at-point)))
23613 (if (eq (org-element-type element) 'fixed-width)
23614 (goto-char (org-element-property :end element))
23615 (throw 'not-all-p nil))))
23616 t))))
23617 (if all-fixed-width-p
23618 (save-excursion
23619 (goto-char begin)
23620 (while (< (point) end)
23621 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23622 (replace-match
23623 "" nil nil nil
23624 (if (= (line-end-position) (match-end 0)) 0 1)))
23625 (forward-line)))
23626 (let ((min-ind (point-max)))
23627 ;; Find minimum indentation across all lines.
23628 (save-excursion
23629 (goto-char begin)
23630 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23631 (setq min-ind 0)
23632 (catch 'zerop
23633 (while (< (point) end)
23634 (unless (looking-at-p "[ \t]*$")
23635 (let ((ind (org-get-indentation)))
23636 (setq min-ind (min min-ind ind))
23637 (when (zerop ind) (throw 'zerop t))))
23638 (forward-line)))))
23639 ;; Loop over all lines and add fixed-width markup everywhere
23640 ;; but in fixed-width lines.
23641 (save-excursion
23642 (goto-char begin)
23643 (while (< (point) end)
23644 (cond
23645 ((org-at-heading-p)
23646 (insert ": ")
23647 (forward-line)
23648 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23649 (insert ":")
23650 (forward-line)))
23651 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23652 (let* ((element (org-element-at-point))
23653 (element-end (org-element-property :end element)))
23654 (if (eq (org-element-type element) 'fixed-width)
23655 (progn (goto-char element-end)
23656 (skip-chars-backward " \r\t\n")
23657 (forward-line))
23658 (let ((limit (min end element-end)))
23659 (while (< (point) limit)
23660 (org-move-to-column min-ind t)
23661 (insert ": ")
23662 (forward-line))))))
23664 (org-move-to-column min-ind t)
23665 (insert ": ")
23666 (forward-line)))))))
23667 (set-marker end nil))))
23670 ;;; Comments
23672 ;; Org comments syntax is quite complex. It requires the entire line
23673 ;; to be just a comment. Also, even with the right syntax at the
23674 ;; beginning of line, some some elements (i.e. verse-block or
23675 ;; example-block) don't accept comments. Usual Emacs comment commands
23676 ;; cannot cope with those requirements. Therefore, Org replaces them.
23678 ;; Org still relies on `comment-dwim', but cannot trust
23679 ;; `comment-only-p'. So, `comment-region-function' and
23680 ;; `uncomment-region-function' both point
23681 ;; to`org-comment-or-uncomment-region'. Eventually,
23682 ;; `org-insert-comment' takes care of insertion of comments at the
23683 ;; beginning of line.
23685 ;; `org-setup-comments-handling' install comments related variables
23686 ;; during `org-mode' initialization.
23688 (defun org-setup-comments-handling ()
23689 (interactive)
23690 (setq-local comment-use-syntax nil)
23691 (setq-local comment-start "# ")
23692 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23693 (setq-local comment-insert-comment-function 'org-insert-comment)
23694 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23695 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23697 (defun org-insert-comment ()
23698 "Insert an empty comment above current line.
23699 If the line is empty, insert comment at its beginning. When
23700 point is within a source block, comment according to the related
23701 major mode."
23702 (if (let ((element (org-element-at-point)))
23703 (and (eq (org-element-type element) 'src-block)
23704 (< (save-excursion
23705 (goto-char (org-element-property :post-affiliated element))
23706 (line-end-position))
23707 (point))
23708 (> (save-excursion
23709 (goto-char (org-element-property :end element))
23710 (skip-chars-backward " \r\t\n")
23711 (line-beginning-position))
23712 (point))))
23713 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23714 (beginning-of-line)
23715 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23716 (open-line 1))
23717 (org-indent-line)
23718 (insert "# ")))
23720 (defvar comment-empty-lines) ; From newcomment.el.
23721 (defun org-comment-or-uncomment-region (beg end &rest _)
23722 "Comment or uncomment each non-blank line in the region.
23723 Uncomment each non-blank line between BEG and END if it only
23724 contains commented lines. Otherwise, comment them. If region is
23725 strictly within a source block, use appropriate comment syntax."
23726 (if (let ((element (org-element-at-point)))
23727 (and (eq (org-element-type element) 'src-block)
23728 (< (save-excursion
23729 (goto-char (org-element-property :post-affiliated element))
23730 (line-end-position))
23731 beg)
23732 (>= (save-excursion
23733 (goto-char (org-element-property :end element))
23734 (skip-chars-backward " \r\t\n")
23735 (line-beginning-position))
23736 end)))
23737 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23738 (save-restriction
23739 ;; Restrict region
23740 (narrow-to-region (save-excursion (goto-char beg)
23741 (skip-chars-forward " \r\t\n" end)
23742 (line-beginning-position))
23743 (save-excursion (goto-char end)
23744 (skip-chars-backward " \r\t\n" beg)
23745 (line-end-position)))
23746 (let ((uncommentp
23747 ;; UNCOMMENTP is non-nil when every non blank line between
23748 ;; BEG and END is a comment.
23749 (save-excursion
23750 (goto-char (point-min))
23751 (while (and (not (eobp))
23752 (let ((element (org-element-at-point)))
23753 (and (eq (org-element-type element) 'comment)
23754 (goto-char (min (point-max)
23755 (org-element-property
23756 :end element)))))))
23757 (eobp))))
23758 (if uncommentp
23759 ;; Only blank lines and comments in region: uncomment it.
23760 (save-excursion
23761 (goto-char (point-min))
23762 (while (not (eobp))
23763 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23764 (replace-match "" nil nil nil 1))
23765 (forward-line)))
23766 ;; Comment each line in region.
23767 (let ((min-indent (point-max)))
23768 ;; First find the minimum indentation across all lines.
23769 (save-excursion
23770 (goto-char (point-min))
23771 (while (and (not (eobp)) (not (zerop min-indent)))
23772 (unless (looking-at "[ \t]*$")
23773 (setq min-indent (min min-indent (current-indentation))))
23774 (forward-line)))
23775 ;; Then loop over all lines.
23776 (save-excursion
23777 (goto-char (point-min))
23778 (while (not (eobp))
23779 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23780 ;; Don't get fooled by invisible text (e.g. link path)
23781 ;; when moving to column MIN-INDENT.
23782 (let ((buffer-invisibility-spec nil))
23783 (org-move-to-column min-indent t))
23784 (insert comment-start))
23785 (forward-line)))))))))
23787 (defun org-comment-dwim (_arg)
23788 "Call `comment-dwim' within a source edit buffer if needed."
23789 (interactive "*P")
23790 (if (org-in-src-block-p)
23791 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23792 (call-interactively 'comment-dwim)))
23795 ;;; Timestamps API
23797 ;; This section contains tools to operate on timestamp objects, as
23798 ;; returned by, e.g. `org-element-context'.
23800 (defun org-timestamp--to-internal-time (timestamp &optional end)
23801 "Encode TIMESTAMP object into Emacs internal time.
23802 Use end of date range or time range when END is non-nil."
23803 (apply #'encode-time
23804 (cons 0
23805 (mapcar
23806 (lambda (prop) (or (org-element-property prop timestamp) 0))
23807 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23808 '(:minute-start :hour-start :day-start :month-start
23809 :year-start))))))
23811 (defun org-timestamp-has-time-p (timestamp)
23812 "Non-nil when TIMESTAMP has a time specified."
23813 (org-element-property :hour-start timestamp))
23815 (defun org-timestamp-format (timestamp format &optional end utc)
23816 "Format a TIMESTAMP object into a string.
23818 FORMAT is a format specifier to be passed to
23819 `format-time-string'.
23821 When optional argument END is non-nil, use end of date-range or
23822 time-range, if possible.
23824 When optional argument UTC is non-nil, time will be expressed as
23825 Universal Time."
23826 (format-time-string
23827 format (org-timestamp--to-internal-time timestamp end)
23828 (and utc t)))
23830 (defun org-timestamp-split-range (timestamp &optional end)
23831 "Extract a TIMESTAMP object from a date or time range.
23833 END, when non-nil, means extract the end of the range.
23834 Otherwise, extract its start.
23836 Return a new timestamp object."
23837 (let ((type (org-element-property :type timestamp)))
23838 (if (memq type '(active inactive diary)) timestamp
23839 (let ((split-ts (org-element-copy timestamp)))
23840 ;; Set new type.
23841 (org-element-put-property
23842 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23843 ;; Copy start properties over end properties if END is
23844 ;; non-nil. Otherwise, copy end properties over `start' ones.
23845 (let ((p-alist '((:minute-start . :minute-end)
23846 (:hour-start . :hour-end)
23847 (:day-start . :day-end)
23848 (:month-start . :month-end)
23849 (:year-start . :year-end))))
23850 (dolist (p-cell p-alist)
23851 (org-element-put-property
23852 split-ts
23853 (funcall (if end #'car #'cdr) p-cell)
23854 (org-element-property
23855 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23856 ;; Eventually refresh `:raw-value'.
23857 (org-element-put-property split-ts :raw-value nil)
23858 (org-element-put-property
23859 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23861 (defun org-timestamp-translate (timestamp &optional boundary)
23862 "Translate TIMESTAMP object to custom format.
23864 Format string is defined in `org-time-stamp-custom-formats',
23865 which see.
23867 When optional argument BOUNDARY is non-nil, it is either the
23868 symbol `start' or `end'. In this case, only translate the
23869 starting or ending part of TIMESTAMP if it is a date or time
23870 range. Otherwise, translate both parts.
23872 Return timestamp as-is if `org-display-custom-times' is nil or if
23873 it has a `diary' type."
23874 (let ((type (org-element-property :type timestamp)))
23875 (if (or (not org-display-custom-times) (eq type 'diary))
23876 (org-element-interpret-data timestamp)
23877 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23878 org-time-stamp-custom-formats)))
23879 (if (and (not boundary) (memq type '(active-range inactive-range)))
23880 (concat (org-timestamp-format timestamp fmt)
23881 "--"
23882 (org-timestamp-format timestamp fmt t))
23883 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23887 ;;; Other stuff.
23889 (defvar reftex-docstruct-symbol)
23890 (defvar reftex-cite-format)
23891 (defvar org--rds)
23893 (defun org-reftex-citation ()
23894 "Use reftex-citation to insert a citation into the buffer.
23895 This looks for a line like
23897 #+BIBLIOGRAPHY: foo plain option:-d
23899 and derives from it that foo.bib is the bibliography file relevant
23900 for this document. It then installs the necessary environment for RefTeX
23901 to work in this buffer and calls `reftex-citation' to insert a citation
23902 into the buffer.
23904 Export of such citations to both LaTeX and HTML is handled by the contributed
23905 package ox-bibtex by Taru Karttunen."
23906 (interactive)
23907 (let ((reftex-docstruct-symbol 'org--rds)
23908 (reftex-cite-format "\\cite{%l}")
23909 org--rds bib)
23910 (save-excursion
23911 (save-restriction
23912 (widen)
23913 (let ((case-fold-search t)
23914 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23915 (if (not (save-excursion
23916 (or (re-search-forward re nil t)
23917 (re-search-backward re nil t))))
23918 (user-error "No bibliography defined in file")
23919 (setq bib (concat (match-string 1) ".bib")
23920 org--rds (list (list 'bib bib)))))))
23921 (call-interactively 'reftex-citation)))
23923 ;;;; Functions extending outline functionality
23925 (defun org-beginning-of-line (&optional arg)
23926 "Go to the beginning of the current line. If that is invisible, continue
23927 to a visible line beginning. This makes the function of C-a more intuitive.
23928 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23929 first attempt, and only move to after the tags when the cursor is already
23930 beyond the end of the headline."
23931 (interactive "P")
23932 (let ((pos (point))
23933 (special (if (consp org-special-ctrl-a/e)
23934 (car org-special-ctrl-a/e)
23935 org-special-ctrl-a/e))
23936 deactivate-mark refpos)
23937 (call-interactively (if (org-bound-and-true-p visual-line-mode)
23938 #'beginning-of-visual-line
23939 #'move-beginning-of-line))
23940 (cond
23941 ((or arg (not special)))
23942 ((and (looking-at org-complex-heading-regexp)
23943 (eq (char-after (match-end 1)) ?\s))
23944 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23945 (point-at-eol)))
23946 (goto-char
23947 (if (eq special t)
23948 (cond ((> pos refpos) refpos)
23949 ((= pos (point)) refpos)
23950 (t (point)))
23951 (cond ((> pos (point)) (point))
23952 ((not (eq last-command this-command)) (point))
23953 (t refpos)))))
23954 ((org-at-item-p)
23955 ;; Being at an item and not looking at an the item means point
23956 ;; was previously moved to beginning of a visual line, which
23957 ;; doesn't contain the item. Therefore, do nothing special,
23958 ;; just stay here.
23959 (when (looking-at org-list-full-item-re)
23960 ;; Set special position at first white space character after
23961 ;; bullet, and check-box, if any.
23962 (let ((after-bullet
23963 (let ((box (match-end 3)))
23964 (if (not box) (match-end 1)
23965 (let ((after (char-after box)))
23966 (if (and after (= after ? )) (1+ box) box))))))
23967 ;; Special case: Move point to special position when
23968 ;; currently after it or at beginning of line.
23969 (if (eq special t)
23970 (when (or (> pos after-bullet) (= (point) pos))
23971 (goto-char after-bullet))
23972 ;; Reversed case: Move point to special position when
23973 ;; point was already at beginning of line and command is
23974 ;; repeated.
23975 (when (and (= (point) pos) (eq last-command this-command))
23976 (goto-char after-bullet))))))))
23977 (setq disable-point-adjustment
23978 (or (not (invisible-p (point)))
23979 (not (invisible-p (max (point-min) (1- (point))))))))
23981 (defun org-end-of-line (&optional arg)
23982 "Go to the end of the line.
23983 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23984 tags on the first attempt, and only move to after the tags when
23985 the cursor is already beyond the end of the headline."
23986 (interactive "P")
23987 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23988 org-special-ctrl-a/e))
23989 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23990 'end-of-visual-line)
23991 ((fboundp 'move-end-of-line) 'move-end-of-line)
23992 (t 'end-of-line)))
23993 deactivate-mark)
23994 (if (or (not special) arg) (call-interactively move-fun)
23995 (let* ((element (save-excursion (beginning-of-line)
23996 (org-element-at-point)))
23997 (type (org-element-type element)))
23998 (cond
23999 ((memq type '(headline inlinetask))
24000 (let ((pos (point)))
24001 (beginning-of-line 1)
24002 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
24003 (if (eq special t)
24004 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
24005 (goto-char (match-beginning 1))
24006 (goto-char (match-end 0)))
24007 (if (or (< pos (match-end 0))
24008 (not (eq this-command last-command)))
24009 (goto-char (match-end 0))
24010 (goto-char (match-beginning 1))))
24011 (call-interactively move-fun))))
24012 ((outline-invisible-p (line-end-position))
24013 ;; If element is hidden, `move-end-of-line' would put point
24014 ;; after it. Use `end-of-line' to stay on current line.
24015 (call-interactively 'end-of-line))
24016 (t (call-interactively move-fun))))))
24017 (setq disable-point-adjustment
24018 (or (not (invisible-p (point)))
24019 (not (invisible-p (max (point-min) (1- (point))))))))
24021 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
24022 (define-key org-mode-map "\C-e" 'org-end-of-line)
24024 (defun org-backward-sentence (&optional _arg)
24025 "Go to beginning of sentence, or beginning of table field.
24026 This will call `backward-sentence' or `org-table-beginning-of-field',
24027 depending on context."
24028 (interactive)
24029 (let* ((element (org-element-at-point))
24030 (contents-begin (org-element-property :contents-begin element))
24031 (table (org-element-lineage element '(table) t)))
24032 (if (and table
24033 (> (point) contents-begin)
24034 (<= (point) (org-element-property :contents-end table)))
24035 (call-interactively #'org-table-beginning-of-field)
24036 (save-restriction
24037 (when (and contents-begin
24038 (< (point-min) contents-begin)
24039 (> (point) contents-begin))
24040 (narrow-to-region contents-begin
24041 (org-element-property :contents-end element)))
24042 (call-interactively #'backward-sentence)))))
24044 (defun org-forward-sentence (&optional _arg)
24045 "Go to end of sentence, or end of table field.
24046 This will call `forward-sentence' or `org-table-end-of-field',
24047 depending on context."
24048 (interactive)
24049 (let* ((element (org-element-at-point))
24050 (contents-end (org-element-property :contents-end element))
24051 (table (org-element-lineage element '(table) t)))
24052 (if (and table
24053 (>= (point) (org-element-property :contents-begin table))
24054 (< (point) contents-end))
24055 (call-interactively #'org-table-end-of-field)
24056 (save-restriction
24057 (when (and contents-end
24058 (> (point-max) contents-end)
24059 ;; Skip blank lines between elements.
24060 (< (org-element-property :end element)
24061 (save-excursion (goto-char contents-end)
24062 (skip-chars-forward " \r\t\n"))))
24063 (narrow-to-region (org-element-property :contents-begin element)
24064 contents-end))
24065 (call-interactively #'forward-sentence)))))
24067 (define-key org-mode-map "\M-a" 'org-backward-sentence)
24068 (define-key org-mode-map "\M-e" 'org-forward-sentence)
24070 (defun org-kill-line (&optional _arg)
24071 "Kill line, to tags or end of line."
24072 (interactive)
24073 (cond
24074 ((or (not org-special-ctrl-k)
24075 (bolp)
24076 (not (org-at-heading-p)))
24077 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
24078 org-ctrl-k-protect-subtree
24079 (or (eq org-ctrl-k-protect-subtree 'error)
24080 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
24081 (user-error "C-k aborted as it would kill a hidden subtree"))
24082 (call-interactively
24083 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
24084 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
24085 (kill-region (point) (match-beginning 1))
24086 (org-set-tags nil t))
24087 (t (kill-region (point) (point-at-eol)))))
24089 (define-key org-mode-map "\C-k" 'org-kill-line)
24091 (defun org-yank (&optional arg)
24092 "Yank. If the kill is a subtree, treat it specially.
24093 This command will look at the current kill and check if is a single
24094 subtree, or a series of subtrees[1]. If it passes the test, and if the
24095 cursor is at the beginning of a line or after the stars of a currently
24096 empty headline, then the yank is handled specially. How exactly depends
24097 on the value of the following variables.
24099 `org-yank-folded-subtrees'
24100 By default, this variable is non-nil, which results in subtree(s)
24101 being folded after insertion, but only if doing so would now
24102 swallow text after the yanked text.
24104 `org-yank-adjusted-subtrees'
24105 When non-nil (the default value is nil), the subtree will be
24106 promoted or demoted in order to fit into the local outline tree
24107 structure, which means that the level will be adjusted so that it
24108 becomes the smaller one of the two *visible* surrounding headings.
24110 Any prefix to this command will cause `yank' to be called directly with
24111 no special treatment. In particular, a simple \\[universal-argument] prefix \
24112 will just
24113 plainly yank the text as it is.
24115 \[1] The test checks if the first non-white line is a heading
24116 and if there are no other headings with fewer stars."
24117 (interactive "P")
24118 (org-yank-generic 'yank arg))
24120 (defun org-yank-generic (command arg)
24121 "Perform some yank-like command.
24123 This function implements the behavior described in the `org-yank'
24124 documentation. However, it has been generalized to work for any
24125 interactive command with similar behavior."
24127 ;; pretend to be command COMMAND
24128 (setq this-command command)
24130 (if arg
24131 (call-interactively command)
24133 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24134 (and (org-kill-is-subtree-p)
24135 (or (bolp)
24136 (and (looking-at "[ \t]*$")
24137 (string-match
24138 "\\`\\*+\\'"
24139 (buffer-substring (point-at-bol) (point)))))))
24140 swallowp)
24141 (cond
24142 ((and subtreep org-yank-folded-subtrees)
24143 (let ((beg (point))
24144 end)
24145 (if (and subtreep org-yank-adjusted-subtrees)
24146 (org-paste-subtree nil nil 'for-yank)
24147 (call-interactively command))
24149 (setq end (point))
24150 (goto-char beg)
24151 (when (and (bolp) subtreep
24152 (not (setq swallowp
24153 (org-yank-folding-would-swallow-text beg end))))
24154 (org-with-limited-levels
24155 (or (looking-at org-outline-regexp)
24156 (re-search-forward org-outline-regexp-bol end t))
24157 (while (and (< (point) end) (looking-at org-outline-regexp))
24158 (outline-hide-subtree)
24159 (org-cycle-show-empty-lines 'folded)
24160 (condition-case nil
24161 (outline-forward-same-level 1)
24162 (error (goto-char end))))))
24163 (when swallowp
24164 (message
24165 "Inserted text not folded because that would swallow text"))
24167 (goto-char end)
24168 (skip-chars-forward " \t\n\r")
24169 (beginning-of-line 1)
24170 (push-mark beg 'nomsg)))
24171 ((and subtreep org-yank-adjusted-subtrees)
24172 (let ((beg (point-at-bol)))
24173 (org-paste-subtree nil nil 'for-yank)
24174 (push-mark beg 'nomsg)))
24176 (call-interactively command))))))
24178 (defun org-yank-folding-would-swallow-text (beg end)
24179 "Would hide-subtree at BEG swallow any text after END?"
24180 (let (level)
24181 (org-with-limited-levels
24182 (save-excursion
24183 (goto-char beg)
24184 (when (or (looking-at org-outline-regexp)
24185 (re-search-forward org-outline-regexp-bol end t))
24186 (setq level (org-outline-level)))
24187 (goto-char end)
24188 (skip-chars-forward " \t\r\n\v\f")
24189 (not (or (eobp)
24190 (and (bolp) (looking-at-p org-outline-regexp)
24191 (<= (org-outline-level) level))))))))
24193 (define-key org-mode-map "\C-y" 'org-yank)
24195 (defun org-truely-invisible-p ()
24196 "Check if point is at a character currently not visible.
24197 This version does not only check the character property, but also
24198 `visible-mode'."
24199 ;; Early versions of noutline don't have `outline-invisible-p'.
24200 (unless (org-bound-and-true-p visible-mode)
24201 (outline-invisible-p)))
24203 (defun org-invisible-p2 ()
24204 "Check if point is at a character currently not visible."
24205 (save-excursion
24206 (when (and (eolp) (not (bobp))) (backward-char 1))
24207 ;; Early versions of noutline don't have `outline-invisible-p'.
24208 (outline-invisible-p)))
24210 (defun org-back-to-heading (&optional invisible-ok)
24211 "Call `outline-back-to-heading', but provide a better error message."
24212 (condition-case nil
24213 (outline-back-to-heading invisible-ok)
24214 (error (error "Before first headline at position %d in buffer %s"
24215 (point) (current-buffer)))))
24217 (defun org-before-first-heading-p ()
24218 "Before first heading?"
24219 (save-excursion
24220 (end-of-line)
24221 (null (re-search-backward org-outline-regexp-bol nil t))))
24223 (defun org-at-heading-p (&optional ignored)
24224 (outline-on-heading-p t))
24225 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24226 ;;; warning was only added in Org 9.0, which should be taken into
24227 ;;; account when deciding when to remove the alias.
24228 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24230 (defun org-in-commented-heading-p (&optional no-inheritance)
24231 "Non-nil if point is under a commented heading.
24232 This function also checks ancestors of the current headline,
24233 unless optional argument NO-INHERITANCE is non-nil."
24234 (cond
24235 ((org-before-first-heading-p) nil)
24236 ((let ((headline (nth 4 (org-heading-components))))
24237 (and headline
24238 (let ((case-fold-search nil))
24239 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24240 headline)))))
24241 (no-inheritance nil)
24243 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24245 (defun org-at-comment-p nil
24246 "Is cursor in a commented line?"
24247 (save-excursion
24248 (save-match-data
24249 (beginning-of-line)
24250 (looking-at "^[ \t]*# "))))
24252 (defun org-at-drawer-p nil
24253 "Is cursor at a drawer keyword?"
24254 (save-excursion
24255 (move-beginning-of-line 1)
24256 (looking-at org-drawer-regexp)))
24258 (defun org-at-block-p nil
24259 "Is cursor at a block keyword?"
24260 (save-excursion
24261 (move-beginning-of-line 1)
24262 (looking-at org-block-regexp)))
24264 (defun org-point-at-end-of-empty-headline ()
24265 "If point is at the end of an empty headline, return t, else nil.
24266 If the heading only contains a TODO keyword, it is still still considered
24267 empty."
24268 (and (looking-at "[ \t]*$")
24269 (when org-todo-line-regexp
24270 (save-excursion
24271 (beginning-of-line 1)
24272 (let ((case-fold-search nil))
24273 (looking-at org-todo-line-regexp)
24274 (string= (match-string 3) ""))))))
24276 (defun org-at-heading-or-item-p ()
24277 (or (org-at-heading-p) (org-at-item-p)))
24279 (defun org-at-target-p ()
24280 (or (org-in-regexp org-radio-target-regexp)
24281 (org-in-regexp org-target-regexp)))
24282 ;; Compatibility alias with Org versions < 7.8.03
24283 (defalias 'org-on-target-p 'org-at-target-p)
24285 (defun org-up-heading-all (arg)
24286 "Move to the heading line of which the present line is a subheading.
24287 This function considers both visible and invisible heading lines.
24288 With argument, move up ARG levels."
24289 (if (fboundp 'outline-up-heading-all)
24290 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24291 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24293 (defun org-up-heading-safe ()
24294 "Move to the heading line of which the present line is a subheading.
24295 This version will not throw an error. It will return the level of the
24296 headline found, or nil if no higher level is found.
24298 Also, this function will be a lot faster than `outline-up-heading',
24299 because it relies on stars being the outline starters. This can really
24300 make a significant difference in outlines with very many siblings."
24301 (when (ignore-errors (org-back-to-heading t))
24302 (let ((level-up (1- (funcall outline-level))))
24303 (and (> level-up 0)
24304 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24305 (funcall outline-level)))))
24307 (defun org-first-sibling-p ()
24308 "Is this heading the first child of its parents?"
24309 (interactive)
24310 (let ((re org-outline-regexp-bol)
24311 level l)
24312 (unless (org-at-heading-p t)
24313 (user-error "Not at a heading"))
24314 (setq level (funcall outline-level))
24315 (save-excursion
24316 (if (not (re-search-backward re nil t))
24318 (setq l (funcall outline-level))
24319 (< l level)))))
24321 (defun org-goto-sibling (&optional previous)
24322 "Goto the next sibling, even if it is invisible.
24323 When PREVIOUS is set, go to the previous sibling instead. Returns t
24324 when a sibling was found. When none is found, return nil and don't
24325 move point."
24326 (let ((fun (if previous 're-search-backward 're-search-forward))
24327 (pos (point))
24328 (re org-outline-regexp-bol)
24329 level l)
24330 (when (ignore-errors (org-back-to-heading t))
24331 (setq level (funcall outline-level))
24332 (catch 'exit
24333 (or previous (forward-char 1))
24334 (while (funcall fun re nil t)
24335 (setq l (funcall outline-level))
24336 (when (< l level) (goto-char pos) (throw 'exit nil))
24337 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24338 (goto-char pos)
24339 nil))))
24341 (defun org-show-siblings ()
24342 "Show all siblings of the current headline."
24343 (save-excursion
24344 (while (org-goto-sibling) (org-flag-heading nil)))
24345 (save-excursion
24346 (while (org-goto-sibling 'previous)
24347 (org-flag-heading nil))))
24349 (defun org-goto-first-child ()
24350 "Goto the first child, even if it is invisible.
24351 Return t when a child was found. Otherwise don't move point and
24352 return nil."
24353 (let (level (pos (point)) (re org-outline-regexp-bol))
24354 (when (ignore-errors (org-back-to-heading t))
24355 (setq level (outline-level))
24356 (forward-char 1)
24357 (if (and (re-search-forward re nil t) (> (outline-level) level))
24358 (progn (goto-char (match-beginning 0)) t)
24359 (goto-char pos) nil))))
24361 (defun org-show-hidden-entry ()
24362 "Show an entry where even the heading is hidden."
24363 (save-excursion
24364 (org-show-entry)))
24366 (defun org-flag-heading (flag &optional entry)
24367 "Flag the current heading. FLAG non-nil means make invisible.
24368 When ENTRY is non-nil, show the entire entry."
24369 (save-excursion
24370 (org-back-to-heading t)
24371 ;; Check if we should show the entire entry
24372 (if entry
24373 (progn
24374 (org-show-entry)
24375 (save-excursion
24376 (and (outline-next-heading)
24377 (org-flag-heading nil))))
24378 (outline-flag-region (max (point-min) (1- (point)))
24379 (save-excursion (outline-end-of-heading) (point))
24380 flag))))
24382 (defun org-get-next-sibling ()
24383 "Move to next heading of the same level, and return point.
24384 If there is no such heading, return nil.
24385 This is like outline-next-sibling, but invisible headings are ok."
24386 (let ((level (funcall outline-level)))
24387 (outline-next-heading)
24388 (while (and (not (eobp)) (> (funcall outline-level) level))
24389 (outline-next-heading))
24390 (unless (or (eobp) (< (funcall outline-level) level))
24391 (point))))
24393 (defun org-get-last-sibling ()
24394 "Move to previous heading of the same level, and return point.
24395 If there is no such heading, return nil."
24396 (let ((opoint (point))
24397 (level (funcall outline-level)))
24398 (outline-previous-heading)
24399 (when (and (/= (point) opoint) (outline-on-heading-p t))
24400 (while (and (> (funcall outline-level) level)
24401 (not (bobp)))
24402 (outline-previous-heading))
24403 (unless (< (funcall outline-level) level)
24404 (point)))))
24406 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24407 "Goto to the end of a subtree."
24408 ;; This contains an exact copy of the original function, but it uses
24409 ;; `org-back-to-heading', to make it work also in invisible
24410 ;; trees. And is uses an invisible-ok argument.
24411 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24412 ;; Furthermore, when used inside Org, finding the end of a large subtree
24413 ;; with many children and grandchildren etc, this can be much faster
24414 ;; than the outline version.
24415 (org-back-to-heading invisible-ok)
24416 (let ((first t)
24417 (level (funcall outline-level)))
24418 (if (and (derived-mode-p 'org-mode) (< level 1000))
24419 ;; A true heading (not a plain list item), in Org-mode
24420 ;; This means we can easily find the end by looking
24421 ;; only for the right number of stars. Using a regexp to do
24422 ;; this is so much faster than using a Lisp loop.
24423 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24424 (forward-char 1)
24425 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24426 ;; something else, do it the slow way
24427 (while (and (not (eobp))
24428 (or first (> (funcall outline-level) level)))
24429 (setq first nil)
24430 (outline-next-heading)))
24431 (unless to-heading
24432 (when (memq (preceding-char) '(?\n ?\^M))
24433 ;; Go to end of line before heading
24434 (forward-char -1)
24435 (when (memq (preceding-char) '(?\n ?\^M))
24436 ;; leave blank line before heading
24437 (forward-char -1)))))
24438 (point))
24440 (defun org-end-of-meta-data (&optional full)
24441 "Skip planning line and properties drawer in current entry.
24442 When optional argument FULL is non-nil, also skip empty lines,
24443 clocking lines and regular drawers at the beginning of the
24444 entry."
24445 (org-back-to-heading t)
24446 (forward-line)
24447 (when (looking-at-p org-planning-line-re) (forward-line))
24448 (when (looking-at org-property-drawer-re)
24449 (goto-char (match-end 0))
24450 (forward-line))
24451 (when (and full (not (org-at-heading-p)))
24452 (catch 'exit
24453 (let ((end (save-excursion (outline-next-heading) (point)))
24454 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24455 (while (not (eobp))
24456 (cond ((looking-at-p org-drawer-regexp)
24457 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24458 (forward-line)
24459 (throw 'exit t)))
24460 ((looking-at-p re) (forward-line))
24461 (t (throw 'exit t))))))))
24463 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24464 "Move forward to the ARG'th subheading at same level as this one.
24465 Stop at the first and last subheadings of a superior heading.
24466 Normally this only looks at visible headings, but when INVISIBLE-OK is
24467 non-nil it will also look at invisible ones."
24468 (interactive "p")
24469 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24470 (if (and arg (< arg 0))
24471 (goto-char (point-min))
24472 (outline-next-heading))
24473 (org-at-heading-p)
24474 (let ((level (- (match-end 0) (match-beginning 0) 1))
24475 (f (if (and arg (< arg 0))
24476 're-search-backward
24477 're-search-forward))
24478 (count (if arg (abs arg) 1))
24479 (result (point)))
24480 (while (and (prog1 (> count 0)
24481 (forward-char (if (and arg (< arg 0)) -1 1)))
24482 (funcall f org-outline-regexp-bol nil 'move))
24483 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24484 (cond ((< l level) (setq count 0))
24485 ((and (= l level)
24486 (or invisible-ok
24487 (progn
24488 (goto-char (line-beginning-position))
24489 (not (outline-invisible-p)))))
24490 (setq count (1- count))
24491 (when (eq l level)
24492 (setq result (point)))))))
24493 (goto-char result))
24494 (beginning-of-line 1)))
24496 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24497 "Move backward to the ARG'th subheading at same level as this one.
24498 Stop at the first and last subheadings of a superior heading."
24499 (interactive "p")
24500 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24502 (defun org-next-visible-heading (arg)
24503 "Move to the next visible heading.
24505 This function wraps `outline-next-visible-heading' with
24506 `org-with-limited-levels' in order to skip over inline tasks and
24507 respect customization of `org-odd-levels-only'."
24508 (interactive "p")
24509 (org-with-limited-levels
24510 (outline-next-visible-heading arg)))
24512 (defun org-previous-visible-heading (arg)
24513 "Move to the previous visible heading.
24515 This function wraps `outline-previous-visible-heading' with
24516 `org-with-limited-levels' in order to skip over inline tasks and
24517 respect customization of `org-odd-levels-only'."
24518 (interactive "p")
24519 (org-with-limited-levels
24520 (outline-previous-visible-heading arg)))
24522 (defun org-next-block (arg &optional backward block-regexp)
24523 "Jump to the next block.
24525 With a prefix argument ARG, jump forward ARG many blocks.
24527 When BACKWARD is non-nil, jump to the previous block.
24529 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24530 Match data is set according to this regexp when the function
24531 returns.
24533 Return point at beginning of the opening line of found block.
24534 Throw an error if no block is found."
24535 (interactive "p")
24536 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24537 (case-fold-search t)
24538 (search-fn (if backward #'re-search-backward #'re-search-forward))
24539 (count (or arg 1))
24540 (origin (point))
24541 last-element)
24542 (if backward (beginning-of-line) (end-of-line))
24543 (while (and (> count 0) (funcall search-fn re nil t))
24544 (let ((element (save-excursion
24545 (goto-char (match-beginning 0))
24546 (save-match-data (org-element-at-point)))))
24547 (when (and (memq (org-element-type element)
24548 '(center-block comment-block dynamic-block
24549 example-block export-block quote-block
24550 special-block src-block verse-block))
24551 (<= (match-beginning 0)
24552 (org-element-property :post-affiliated element)))
24553 (setq last-element element)
24554 (cl-decf count))))
24555 (if (= count 0)
24556 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24557 (save-match-data (org-show-context)))
24558 (goto-char origin)
24559 (user-error "No %s code blocks" (if backward "previous" "further")))))
24561 (defun org-previous-block (arg &optional block-regexp)
24562 "Jump to the previous block.
24563 With a prefix argument ARG, jump backward ARG many source blocks.
24564 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24565 (interactive "p")
24566 (org-next-block arg t block-regexp))
24568 (defun org-forward-paragraph ()
24569 "Move forward to beginning of next paragraph or equivalent.
24571 The function moves point to the beginning of the next visible
24572 structural element, which can be a paragraph, a table, a list
24573 item, etc. It also provides some special moves for convenience:
24575 - On an affiliated keyword, jump to the beginning of the
24576 relative element.
24577 - On an item or a footnote definition, move to the second
24578 element inside, if any.
24579 - On a table or a property drawer, jump after it.
24580 - On a verse or source block, stop after blank lines."
24581 (interactive)
24582 (when (eobp) (user-error "Cannot move further down"))
24583 (let* ((deactivate-mark nil)
24584 (element (org-element-at-point))
24585 (type (org-element-type element))
24586 (post-affiliated (org-element-property :post-affiliated element))
24587 (contents-begin (org-element-property :contents-begin element))
24588 (contents-end (org-element-property :contents-end element))
24589 (end (let ((end (org-element-property :end element)) (parent element))
24590 (while (and (setq parent (org-element-property :parent parent))
24591 (= (org-element-property :contents-end parent) end))
24592 (setq end (org-element-property :end parent)))
24593 end)))
24594 (cond ((not element)
24595 (skip-chars-forward " \r\t\n")
24596 (or (eobp) (beginning-of-line)))
24597 ;; On affiliated keywords, move to element's beginning.
24598 ((< (point) post-affiliated)
24599 (goto-char post-affiliated))
24600 ;; At a table row, move to the end of the table. Similarly,
24601 ;; at a node property, move to the end of the property
24602 ;; drawer.
24603 ((memq type '(node-property table-row))
24604 (goto-char (org-element-property
24605 :end (org-element-property :parent element))))
24606 ((memq type '(property-drawer table)) (goto-char end))
24607 ;; Consider blank lines as separators in verse and source
24608 ;; blocks to ease editing.
24609 ((memq type '(src-block verse-block))
24610 (when (eq type 'src-block)
24611 (setq contents-end
24612 (save-excursion (goto-char end)
24613 (skip-chars-backward " \r\t\n")
24614 (line-beginning-position))))
24615 (beginning-of-line)
24616 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24617 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24618 (goto-char end)
24619 (skip-chars-forward " \r\t\n")
24620 (if (= (point) contents-end) (goto-char end)
24621 (beginning-of-line))))
24622 ;; With no contents, just skip element.
24623 ((not contents-begin) (goto-char end))
24624 ;; If contents are invisible, skip the element altogether.
24625 ((outline-invisible-p (line-end-position))
24626 (cl-case type
24627 (headline
24628 (org-with-limited-levels (outline-next-visible-heading 1)))
24629 ;; At a plain list, make sure we move to the next item
24630 ;; instead of skipping the whole list.
24631 (plain-list (forward-char)
24632 (org-forward-paragraph))
24633 (otherwise (goto-char end))))
24634 ((>= (point) contents-end) (goto-char end))
24635 ((>= (point) contents-begin)
24636 ;; This can only happen on paragraphs and plain lists.
24637 (cl-case type
24638 (paragraph (goto-char end))
24639 ;; At a plain list, try to move to second element in
24640 ;; first item, if possible.
24641 (plain-list (end-of-line)
24642 (org-forward-paragraph))))
24643 ;; When contents start on the middle of a line (e.g. in
24644 ;; items and footnote definitions), try to reach first
24645 ;; element starting after current line.
24646 ((> (line-end-position) contents-begin)
24647 (end-of-line)
24648 (org-forward-paragraph))
24649 (t (goto-char contents-begin)))))
24651 (defun org-backward-paragraph ()
24652 "Move backward to start of previous paragraph or equivalent.
24654 The function moves point to the beginning of the current
24655 structural element, which can be a paragraph, a table, a list
24656 item, etc., or to the beginning of the previous visible one if
24657 point is already there. It also provides some special moves for
24658 convenience:
24660 - On an affiliated keyword, jump to the first one.
24661 - On a table or a property drawer, move to its beginning.
24662 - On a verse or source block, stop before blank lines."
24663 (interactive)
24664 (when (bobp) (user-error "Cannot move further up"))
24665 (let* ((deactivate-mark nil)
24666 (element (org-element-at-point))
24667 (type (org-element-type element))
24668 (contents-begin (org-element-property :contents-begin element))
24669 (contents-end (org-element-property :contents-end element))
24670 (post-affiliated (org-element-property :post-affiliated element))
24671 (begin (org-element-property :begin element)))
24672 (cond
24673 ((not element) (goto-char (point-min)))
24674 ((= (point) begin)
24675 (backward-char)
24676 (org-backward-paragraph))
24677 ((<= (point) post-affiliated) (goto-char begin))
24678 ((memq type '(node-property table-row))
24679 (goto-char (org-element-property
24680 :post-affiliated (org-element-property :parent element))))
24681 ((memq type '(property-drawer table)) (goto-char begin))
24682 ((memq type '(src-block verse-block))
24683 (when (eq type 'src-block)
24684 (setq contents-begin
24685 (save-excursion (goto-char begin) (forward-line) (point))))
24686 (if (= (point) contents-begin) (goto-char post-affiliated)
24687 ;; Inside a verse block, see blank lines as paragraph
24688 ;; separators.
24689 (let ((origin (point)))
24690 (skip-chars-backward " \r\t\n" contents-begin)
24691 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24692 (skip-chars-forward " \r\t\n" origin)
24693 (if (= (point) origin) (goto-char contents-begin)
24694 (beginning-of-line))))))
24695 ((not contents-begin) (goto-char (or post-affiliated begin)))
24696 ((eq type 'paragraph)
24697 (goto-char contents-begin)
24698 ;; When at first paragraph in an item or a footnote definition,
24699 ;; move directly to beginning of line.
24700 (let ((parent-contents
24701 (org-element-property
24702 :contents-begin (org-element-property :parent element))))
24703 (when (and parent-contents (= parent-contents contents-begin))
24704 (beginning-of-line))))
24705 ;; At the end of a greater element, move to the beginning of the
24706 ;; last element within.
24707 ((>= (point) contents-end)
24708 (goto-char (1- contents-end))
24709 (org-backward-paragraph))
24710 (t (goto-char (or post-affiliated begin))))
24711 ;; Ensure we never leave point invisible.
24712 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24714 (defun org-forward-element ()
24715 "Move forward by one element.
24716 Move to the next element at the same level, when possible."
24717 (interactive)
24718 (cond ((eobp) (user-error "Cannot move further down"))
24719 ((org-with-limited-levels (org-at-heading-p))
24720 (let ((origin (point)))
24721 (goto-char (org-end-of-subtree nil t))
24722 (unless (org-with-limited-levels (org-at-heading-p))
24723 (goto-char origin)
24724 (user-error "Cannot move further down"))))
24726 (let* ((elem (org-element-at-point))
24727 (end (org-element-property :end elem))
24728 (parent (org-element-property :parent elem)))
24729 (cond ((and parent (= (org-element-property :contents-end parent) end))
24730 (goto-char (org-element-property :end parent)))
24731 ((integer-or-marker-p end) (goto-char end))
24732 (t (message "No element at point")))))))
24734 (defun org-backward-element ()
24735 "Move backward by one element.
24736 Move to the previous element at the same level, when possible."
24737 (interactive)
24738 (cond ((bobp) (user-error "Cannot move further up"))
24739 ((org-with-limited-levels (org-at-heading-p))
24740 ;; At a headline, move to the previous one, if any, or stay
24741 ;; here.
24742 (let ((origin (point)))
24743 (org-with-limited-levels (org-backward-heading-same-level 1))
24744 ;; When current headline has no sibling above, move to its
24745 ;; parent.
24746 (when (= (point) origin)
24747 (or (org-with-limited-levels (org-up-heading-safe))
24748 (progn (goto-char origin)
24749 (user-error "Cannot move further up"))))))
24751 (let* ((elem (org-element-at-point))
24752 (beg (org-element-property :begin elem)))
24753 (cond
24754 ;; Move to beginning of current element if point isn't
24755 ;; there already.
24756 ((null beg) (message "No element at point"))
24757 ((/= (point) beg) (goto-char beg))
24758 (t (goto-char beg)
24759 (skip-chars-backward " \r\t\n")
24760 (unless (bobp)
24761 (let ((prev (org-element-at-point)))
24762 (goto-char (org-element-property :begin prev))
24763 (while (and (setq prev (org-element-property :parent prev))
24764 (<= (org-element-property :end prev) beg))
24765 (goto-char (org-element-property :begin prev)))))))))))
24767 (defun org-up-element ()
24768 "Move to upper element."
24769 (interactive)
24770 (if (org-with-limited-levels (org-at-heading-p))
24771 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24772 (let* ((elem (org-element-at-point))
24773 (parent (org-element-property :parent elem)))
24774 (if parent (goto-char (org-element-property :begin parent))
24775 (if (org-with-limited-levels (org-before-first-heading-p))
24776 (user-error "No surrounding element")
24777 (org-with-limited-levels (org-back-to-heading)))))))
24779 (defvar org-element-greater-elements)
24780 (defun org-down-element ()
24781 "Move to inner element."
24782 (interactive)
24783 (let ((element (org-element-at-point)))
24784 (cond
24785 ((memq (org-element-type element) '(plain-list table))
24786 (goto-char (org-element-property :contents-begin element))
24787 (forward-char))
24788 ((memq (org-element-type element) org-element-greater-elements)
24789 ;; If contents are hidden, first disclose them.
24790 (when (outline-invisible-p (line-end-position)) (org-cycle))
24791 (goto-char (or (org-element-property :contents-begin element)
24792 (user-error "No content for this element"))))
24793 (t (user-error "No inner element")))))
24795 (defun org-drag-element-backward ()
24796 "Move backward element at point."
24797 (interactive)
24798 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24799 (let* ((elem (org-element-at-point))
24800 (prev-elem
24801 (save-excursion
24802 (goto-char (org-element-property :begin elem))
24803 (skip-chars-backward " \r\t\n")
24804 (unless (bobp)
24805 (let* ((beg (org-element-property :begin elem))
24806 (prev (org-element-at-point))
24807 (up prev))
24808 (while (and (setq up (org-element-property :parent up))
24809 (<= (org-element-property :end up) beg))
24810 (setq prev up))
24811 prev)))))
24812 ;; Error out if no previous element or previous element is
24813 ;; a parent of the current one.
24814 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24815 (user-error "Cannot drag element backward")
24816 (let ((pos (point)))
24817 (org-element-swap-A-B prev-elem elem)
24818 (goto-char (+ (org-element-property :begin prev-elem)
24819 (- pos (org-element-property :begin elem)))))))))
24821 (defun org-drag-element-forward ()
24822 "Move forward element at point."
24823 (interactive)
24824 (let* ((pos (point))
24825 (elem (org-element-at-point)))
24826 (when (= (point-max) (org-element-property :end elem))
24827 (user-error "Cannot drag element forward"))
24828 (goto-char (org-element-property :end elem))
24829 (let ((next-elem (org-element-at-point)))
24830 (when (or (org-element-nested-p elem next-elem)
24831 (and (eq (org-element-type next-elem) 'headline)
24832 (not (eq (org-element-type elem) 'headline))))
24833 (goto-char pos)
24834 (user-error "Cannot drag element forward"))
24835 ;; Compute new position of point: it's shifted by NEXT-ELEM
24836 ;; body's length (without final blanks) and by the length of
24837 ;; blanks between ELEM and NEXT-ELEM.
24838 (let ((size-next (- (save-excursion
24839 (goto-char (org-element-property :end next-elem))
24840 (skip-chars-backward " \r\t\n")
24841 (forward-line)
24842 ;; Small correction if buffer doesn't end
24843 ;; with a newline character.
24844 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24845 (org-element-property :begin next-elem)))
24846 (size-blank (- (org-element-property :end elem)
24847 (save-excursion
24848 (goto-char (org-element-property :end elem))
24849 (skip-chars-backward " \r\t\n")
24850 (forward-line)
24851 (point)))))
24852 (org-element-swap-A-B elem next-elem)
24853 (goto-char (+ pos size-next size-blank))))))
24855 (defun org-drag-line-forward (arg)
24856 "Drag the line at point ARG lines forward."
24857 (interactive "p")
24858 (dotimes (_ (abs arg))
24859 (let ((c (current-column)))
24860 (if (< 0 arg)
24861 (progn
24862 (beginning-of-line 2)
24863 (transpose-lines 1)
24864 (beginning-of-line 0))
24865 (transpose-lines 1)
24866 (beginning-of-line -1))
24867 (org-move-to-column c))))
24869 (defun org-drag-line-backward (arg)
24870 "Drag the line at point ARG lines backward."
24871 (interactive "p")
24872 (org-drag-line-forward (- arg)))
24874 (defun org-mark-element ()
24875 "Put point at beginning of this element, mark at end.
24877 Interactively, if this command is repeated or (in Transient Mark
24878 mode) if the mark is active, it marks the next element after the
24879 ones already marked."
24880 (interactive)
24881 (let (deactivate-mark)
24882 (if (and (org-called-interactively-p 'any)
24883 (or (and (eq last-command this-command) (mark t))
24884 (and transient-mark-mode mark-active)))
24885 (set-mark
24886 (save-excursion
24887 (goto-char (mark))
24888 (goto-char (org-element-property :end (org-element-at-point)))))
24889 (let ((element (org-element-at-point)))
24890 (end-of-line)
24891 (push-mark (org-element-property :end element) t t)
24892 (goto-char (org-element-property :begin element))))))
24894 (defun org-narrow-to-element ()
24895 "Narrow buffer to current element."
24896 (interactive)
24897 (let ((elem (org-element-at-point)))
24898 (cond
24899 ((eq (car elem) 'headline)
24900 (narrow-to-region
24901 (org-element-property :begin elem)
24902 (org-element-property :end elem)))
24903 ((memq (car elem) org-element-greater-elements)
24904 (narrow-to-region
24905 (org-element-property :contents-begin elem)
24906 (org-element-property :contents-end elem)))
24908 (narrow-to-region
24909 (org-element-property :begin elem)
24910 (org-element-property :end elem))))))
24912 (defun org-transpose-element ()
24913 "Transpose current and previous elements, keeping blank lines between.
24914 Point is moved after both elements."
24915 (interactive)
24916 (org-skip-whitespace)
24917 (let ((end (org-element-property :end (org-element-at-point))))
24918 (org-drag-element-backward)
24919 (goto-char end)))
24921 (defun org-unindent-buffer ()
24922 "Un-indent the visible part of the buffer.
24923 Relative indentation (between items, inside blocks, etc.) isn't
24924 modified."
24925 (interactive)
24926 (unless (eq major-mode 'org-mode)
24927 (user-error "Cannot un-indent a buffer not in Org mode"))
24928 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24929 (unindent-tree
24930 (lambda (contents)
24931 (dolist (element (reverse contents))
24932 (if (memq (org-element-type element) '(headline section))
24933 (funcall unindent-tree (org-element-contents element))
24934 (save-excursion
24935 (save-restriction
24936 (narrow-to-region
24937 (org-element-property :begin element)
24938 (org-element-property :end element))
24939 (org-do-remove-indentation))))))))
24940 (funcall unindent-tree (org-element-contents parse-tree))))
24942 (defun org-show-children (&optional level)
24943 "Show all direct subheadings of this heading.
24944 Prefix arg LEVEL is how many levels below the current level
24945 should be shown. Default is enough to cause the following
24946 heading to appear."
24947 (interactive "p")
24948 ;; If `orgstruct-mode' is active, use the slower version.
24949 (if orgstruct-mode (call-interactively #'outline-show-children)
24950 (save-excursion
24951 (org-back-to-heading t)
24952 (let* ((current-level (funcall outline-level))
24953 (max-level (org-get-valid-level
24954 current-level
24955 (if level (prefix-numeric-value level) 1)))
24956 (end (save-excursion (org-end-of-subtree t t)))
24957 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24958 (past-first-child nil)
24959 ;; Make sure to skip inlinetasks.
24960 (re (format regexp-fmt
24961 current-level
24962 (cond
24963 ((not (featurep 'org-inlinetask)) "")
24964 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24966 (t (1- org-inlinetask-min-level))))))
24967 ;; Display parent heading.
24968 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24969 (forward-line)
24970 ;; Display children. First child may be deeper than expected
24971 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24972 ;; MAX-LEVEL accordingly.
24973 (while (re-search-forward re end t)
24974 (unless past-first-child
24975 (setq re (format regexp-fmt
24976 current-level
24977 (max (funcall outline-level) max-level)))
24978 (setq past-first-child t))
24979 (outline-flag-region
24980 (line-end-position 0) (line-end-position) nil))))))
24982 (defun org-show-subtree ()
24983 "Show everything after this heading at deeper levels."
24984 (interactive)
24985 (outline-flag-region
24986 (point)
24987 (save-excursion
24988 (org-end-of-subtree t t))
24989 nil))
24991 (defun org-show-entry ()
24992 "Show the body directly following this heading.
24993 Show the heading too, if it is currently invisible."
24994 (interactive)
24995 (save-excursion
24996 (ignore-errors
24997 (org-back-to-heading t)
24998 (outline-flag-region
24999 (max (point-min) (1- (point)))
25000 (save-excursion
25001 (if (re-search-forward
25002 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
25003 (match-beginning 1)
25004 (point-max)))
25005 nil)
25006 (org-cycle-hide-drawers 'children))))
25008 (defun org-make-options-regexp (kwds &optional extra)
25009 "Make a regular expression for keyword lines.
25010 KWDS is a list of keywords, as strings. Optional argument EXTRA,
25011 when non-nil, is a regexp matching keywords names."
25012 (concat "^[ \t]*#\\+\\("
25013 (regexp-opt kwds)
25014 (and extra (concat (and kwds "\\|") extra))
25015 "\\):[ \t]*\\(.*\\)"))
25017 ;;;; Integration with and fixes for other packages
25019 ;;; Imenu support
25021 (defvar-local org-imenu-markers nil
25022 "All markers currently used by Imenu.")
25024 (defun org-imenu-new-marker (&optional pos)
25025 "Return a new marker for use by Imenu, and remember the marker."
25026 (let ((m (make-marker)))
25027 (move-marker m (or pos (point)))
25028 (push m org-imenu-markers)
25031 (defun org-imenu-get-tree ()
25032 "Produce the index for Imenu."
25033 (dolist (x org-imenu-markers) (move-marker x nil))
25034 (setq org-imenu-markers nil)
25035 (let* ((case-fold-search nil)
25036 (n org-imenu-depth)
25037 (re (concat "^" (org-get-limited-outline-regexp)))
25038 (subs (make-vector (1+ n) nil))
25039 (last-level 0)
25040 m level head0 head)
25041 (save-excursion
25042 (save-restriction
25043 (widen)
25044 (goto-char (point-max))
25045 (while (re-search-backward re nil t)
25046 (setq level (org-reduced-level (funcall outline-level)))
25047 (when (and (<= level n)
25048 (looking-at org-complex-heading-regexp)
25049 (setq head0 (match-string-no-properties 4)))
25050 (setq head (org-link-display-format head0)
25051 m (org-imenu-new-marker))
25052 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
25053 (if (>= level last-level)
25054 (push (cons head m) (aref subs level))
25055 (push (cons head (aref subs (1+ level))) (aref subs level))
25056 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
25057 (setq last-level level)))))
25058 (aref subs 1)))
25060 (eval-after-load "imenu"
25061 '(progn
25062 (add-hook 'imenu-after-jump-hook
25063 (lambda ()
25064 (when (derived-mode-p 'org-mode)
25065 (org-show-context 'org-goto))))))
25067 (defun org-link-display-format (s)
25068 "Replace links in string S with their description.
25069 If there is no description, use the link target."
25070 (save-match-data
25071 (replace-regexp-in-string
25072 org-bracket-link-analytic-regexp
25073 (lambda (m)
25074 (if (match-end 5) (match-string 5 m)
25075 (concat (match-string 1 m) (match-string 3 m))))
25076 s nil t)))
25078 (defun org-toggle-link-display ()
25079 "Toggle the literal or descriptive display of links."
25080 (interactive)
25081 (if org-descriptive-links
25082 (progn (org-remove-from-invisibility-spec '(org-link))
25083 (org-restart-font-lock)
25084 (setq org-descriptive-links nil))
25085 (progn (add-to-invisibility-spec '(org-link))
25086 (org-restart-font-lock)
25087 (setq org-descriptive-links t))))
25089 ;; Speedbar support
25091 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25092 "Overlay marking the agenda restriction line in speedbar.")
25093 (overlay-put org-speedbar-restriction-lock-overlay
25094 'face 'org-agenda-restriction-lock)
25095 (overlay-put org-speedbar-restriction-lock-overlay
25096 'help-echo "Agendas are currently limited to this item.")
25097 (delete-overlay org-speedbar-restriction-lock-overlay)
25099 (defun org-speedbar-set-agenda-restriction ()
25100 "Restrict future agenda commands to the location at point in speedbar.
25101 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25102 (interactive)
25103 (require 'org-agenda)
25104 (let (p m tp np dir txt)
25105 (cond
25106 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25107 'org-imenu t))
25108 (setq m (get-text-property p 'org-imenu-marker))
25109 (with-current-buffer (marker-buffer m)
25110 (goto-char m)
25111 (org-agenda-set-restriction-lock 'subtree)))
25112 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25113 'speedbar-function 'speedbar-find-file))
25114 (setq tp (previous-single-property-change
25115 (1+ p) 'speedbar-function)
25116 np (next-single-property-change
25117 tp 'speedbar-function)
25118 dir (speedbar-line-directory)
25119 txt (buffer-substring-no-properties (or tp (point-min))
25120 (or np (point-max))))
25121 (with-current-buffer (find-file-noselect
25122 (let ((default-directory dir))
25123 (expand-file-name txt)))
25124 (unless (derived-mode-p 'org-mode)
25125 (user-error "Cannot restrict to non-Org-mode file"))
25126 (org-agenda-set-restriction-lock 'file)))
25127 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25128 (move-overlay org-speedbar-restriction-lock-overlay
25129 (point-at-bol) (point-at-eol))
25130 (setq current-prefix-arg nil)
25131 (org-agenda-maybe-redo)))
25133 (defvar speedbar-file-key-map)
25134 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25135 (eval-after-load "speedbar"
25136 '(progn
25137 (speedbar-add-supported-extension ".org")
25138 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25139 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25140 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25141 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25142 (add-hook 'speedbar-visiting-tag-hook
25143 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25145 ;;; Fixes and Hacks for problems with other packages
25147 (defun org--flyspell-object-check-p (element)
25148 "Non-nil when Flyspell can check object at point.
25149 ELEMENT is the element at point."
25150 (let ((object (save-excursion
25151 (when (looking-at-p "\\>") (backward-char))
25152 (org-element-context element))))
25153 (cl-case (org-element-type object)
25154 ;; Prevent checks in links due to keybinding conflict with
25155 ;; Flyspell.
25156 ((code entity export-snippet inline-babel-call
25157 inline-src-block line-break latex-fragment link macro
25158 statistics-cookie target timestamp verbatim)
25159 nil)
25160 (footnote-reference
25161 ;; Only in inline footnotes, within the definition.
25162 (and (eq (org-element-property :type object) 'inline)
25163 (< (save-excursion
25164 (goto-char (org-element-property :begin object))
25165 (search-forward ":" nil t 2))
25166 (point))))
25167 (otherwise t))))
25169 (defun org-mode-flyspell-verify ()
25170 "Function used for `flyspell-generic-check-word-predicate'."
25171 (if (org-at-heading-p)
25172 ;; At a headline or an inlinetask, check title only. This is
25173 ;; faster than relying on `org-element-at-point'.
25174 (and (save-excursion (beginning-of-line)
25175 (and (let ((case-fold-search t))
25176 (not (looking-at "\\*+ END[ \t]*$")))
25177 (looking-at org-complex-heading-regexp)))
25178 (match-beginning 4)
25179 (>= (point) (match-beginning 4))
25180 (or (not (match-beginning 5))
25181 (< (point) (match-beginning 5))))
25182 (let* ((element (org-element-at-point))
25183 (post-affiliated (org-element-property :post-affiliated element)))
25184 (cond
25185 ;; Ignore checks in all affiliated keywords but captions.
25186 ((< (point) post-affiliated)
25187 (and (save-excursion
25188 (beginning-of-line)
25189 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25190 (> (point) (match-end 0))
25191 (org--flyspell-object-check-p element)))
25192 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25193 ((let ((log (org-log-into-drawer)))
25194 (and log
25195 (let ((drawer (org-element-lineage element '(drawer))))
25196 (and drawer
25197 (eq (compare-strings
25198 log nil nil
25199 (org-element-property :drawer-name drawer) nil nil t)
25200 t)))))
25201 nil)
25203 (cl-case (org-element-type element)
25204 ((comment quote-section) t)
25205 (comment-block
25206 ;; Allow checks between block markers, not on them.
25207 (and (> (line-beginning-position) post-affiliated)
25208 (save-excursion
25209 (end-of-line)
25210 (skip-chars-forward " \r\t\n")
25211 (< (point) (org-element-property :end element)))))
25212 ;; Arbitrary list of keywords where checks are meaningful.
25213 ;; Make sure point is on the value part of the element.
25214 (keyword
25215 (and (member (org-element-property :key element)
25216 '("DESCRIPTION" "TITLE"))
25217 (save-excursion
25218 (search-backward ":" (line-beginning-position) t))))
25219 ;; Check is globally allowed in paragraphs verse blocks and
25220 ;; table rows (after affiliated keywords) but some objects
25221 ;; must not be affected.
25222 ((paragraph table-row verse-block)
25223 (let ((cbeg (org-element-property :contents-begin element))
25224 (cend (org-element-property :contents-end element)))
25225 (and cbeg (>= (point) cbeg) (< (point) cend)
25226 (org--flyspell-object-check-p element))))))))))
25227 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25229 (defun org-remove-flyspell-overlays-in (beg end)
25230 "Remove flyspell overlays in region."
25231 (and (org-bound-and-true-p flyspell-mode)
25232 (fboundp 'flyspell-delete-region-overlays)
25233 (flyspell-delete-region-overlays beg end)))
25235 (defvar flyspell-delayed-commands)
25236 (eval-after-load "flyspell"
25237 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25239 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25240 (eval-after-load "bookmark"
25241 '(if (boundp 'bookmark-after-jump-hook)
25242 ;; We can use the hook
25243 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25244 ;; Hook not available, use advice
25245 (defadvice bookmark-jump (after org-make-visible activate)
25246 "Make the position visible."
25247 (org-bookmark-jump-unhide))))
25249 ;; Make sure saveplace shows the location if it was hidden
25250 (eval-after-load "saveplace"
25251 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25252 "Make the position visible."
25253 (org-bookmark-jump-unhide)))
25255 ;; Make sure ecb shows the location if it was hidden
25256 (eval-after-load "ecb"
25257 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25258 "Make hierarchy visible when jumping into location from ECB tree buffer."
25259 (when (derived-mode-p 'org-mode)
25260 (org-show-context))))
25262 (defun org-bookmark-jump-unhide ()
25263 "Unhide the current position, to show the bookmark location."
25264 (and (derived-mode-p 'org-mode)
25265 (or (outline-invisible-p)
25266 (save-excursion (goto-char (max (point-min) (1- (point))))
25267 (outline-invisible-p)))
25268 (org-show-context 'bookmark-jump)))
25270 (defun org-mark-jump-unhide ()
25271 "Make the point visible with `org-show-context' after jumping to the mark."
25272 (when (and (derived-mode-p 'org-mode)
25273 (outline-invisible-p))
25274 (org-show-context 'mark-goto)))
25276 (eval-after-load "simple"
25277 '(defadvice pop-to-mark-command (after org-make-visible activate)
25278 "Make the point visible with `org-show-context'."
25279 (org-mark-jump-unhide)))
25281 (eval-after-load "simple"
25282 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25283 "Make the point visible with `org-show-context'."
25284 (org-mark-jump-unhide)))
25286 (eval-after-load "simple"
25287 '(defadvice pop-global-mark (after org-make-visible activate)
25288 "Make the point visible with `org-show-context'."
25289 (org-mark-jump-unhide)))
25291 ;; Make session.el ignore our circular variable
25292 (defvar session-globals-exclude)
25293 (eval-after-load "session"
25294 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25296 ;;;; Finish up
25298 (provide 'org)
25300 (run-hooks 'org-load-hook)
25302 ;;; org.el ends here