ob-sql.el: Support sqlcmd in Cygwin environment
[org-mode.git] / lisp / org.el
blob0265d28cc2991091d751a0a7e939d5eb4e0b02df
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 See also the `org-block' face."
5917 :type 'boolean
5918 :version "24.4"
5919 :package-version '(Org . "8.3")
5920 :group 'org-appearance
5921 :group 'org-babel)
5923 (defcustom org-allow-promoting-top-level-subtree nil
5924 "When non-nil, allow promoting a top level subtree.
5925 The leading star of the top level headline will be replaced
5926 by a #."
5927 :type 'boolean
5928 :version "24.1"
5929 :group 'org-appearance)
5931 (defun org-fontify-meta-lines-and-blocks (limit)
5932 (condition-case nil
5933 (org-fontify-meta-lines-and-blocks-1 limit)
5934 (error (message "org-mode fontification error in %S at %d"
5935 (current-buffer)
5936 (line-number-at-pos)))))
5938 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5939 "Fontify #+ lines and blocks."
5940 (let ((case-fold-search t))
5941 (when (re-search-forward
5942 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5943 limit t)
5944 (let ((beg (match-beginning 0))
5945 (block-start (match-end 0))
5946 (block-end nil)
5947 (lang (match-string 7))
5948 (beg1 (line-beginning-position 2))
5949 (dc1 (downcase (match-string 2)))
5950 (dc3 (downcase (match-string 3)))
5951 end end1 quoting block-type)
5952 (cond
5953 ((and (match-end 4) (equal dc3 "+begin"))
5954 ;; Truly a block
5955 (setq block-type (downcase (match-string 5))
5956 quoting (member block-type org-protecting-blocks))
5957 (when (re-search-forward
5958 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5959 nil t) ;; on purpose, we look further than LIMIT
5960 (setq end (min (point-max) (match-end 0))
5961 end1 (min (point-max) (1- (match-beginning 0))))
5962 (setq block-end (match-beginning 0))
5963 (when quoting
5964 (org-remove-flyspell-overlays-in beg1 end1)
5965 (remove-text-properties beg end
5966 '(display t invisible t intangible t)))
5967 (add-text-properties
5968 beg end '(font-lock-fontified t font-lock-multiline t))
5969 (add-text-properties beg beg1 '(face org-meta-line))
5970 (org-remove-flyspell-overlays-in beg beg1)
5971 (add-text-properties ; For end_src
5972 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5973 (org-remove-flyspell-overlays-in end1 end)
5974 (cond
5975 ((and lang (not (string= lang "")) org-src-fontify-natively)
5976 (org-src-font-lock-fontify-block lang block-start block-end)
5977 (add-text-properties beg1 block-end '(src-block t)))
5978 (quoting
5979 (add-text-properties beg1 (min (point-max) (1+ end1))
5980 (list 'face
5981 (list :inherit
5982 (let ((face-name
5983 (intern (format "org-block-%s" lang))))
5984 (append (and (facep face-name) (list face-name))
5985 '(org-block))))))) ; end of source block
5986 ((not org-fontify-quote-and-verse-blocks))
5987 ((string= block-type "quote")
5988 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5989 ((string= block-type "verse")
5990 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5991 (add-text-properties beg beg1 '(face org-block-begin-line))
5992 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5993 '(face org-block-end-line))
5995 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5996 (org-remove-flyspell-overlays-in
5997 (match-beginning 0)
5998 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5999 (add-text-properties
6000 beg (match-end 3)
6001 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
6002 '(font-lock-fontified t invisible t)
6003 '(font-lock-fontified t face org-document-info-keyword)))
6004 (add-text-properties
6005 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6006 (if (string-equal dc1 "+title:")
6007 '(font-lock-fontified t face org-document-title)
6008 '(font-lock-fontified t face org-document-info))))
6009 ((equal dc1 "+caption:")
6010 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6011 (remove-text-properties (match-beginning 0) (match-end 0)
6012 '(display t invisible t intangible t))
6013 (add-text-properties (match-beginning 1) (match-end 3)
6014 '(font-lock-fontified t face org-meta-line))
6015 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6016 '(font-lock-fontified t face org-block))
6018 ((member dc3 '(" " ""))
6019 (org-remove-flyspell-overlays-in beg (match-end 0))
6020 (add-text-properties
6021 beg (match-end 0)
6022 '(font-lock-fontified t face font-lock-comment-face)))
6023 (t ;; just any other in-buffer setting, but not indented
6024 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6025 (remove-text-properties (match-beginning 0) (match-end 0)
6026 '(display t invisible t intangible t))
6027 (add-text-properties beg (match-end 0)
6028 '(font-lock-fontified t face org-meta-line))
6029 t))))))
6031 (defun org-fontify-drawers (limit)
6032 "Fontify drawers."
6033 (when (re-search-forward org-drawer-regexp limit t)
6034 (add-text-properties
6035 (match-beginning 0) (match-end 0)
6036 '(font-lock-fontified t face org-special-keyword))
6037 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6040 (defun org-fontify-macros (limit)
6041 "Fontify macros."
6042 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6043 (add-text-properties
6044 (match-beginning 0) (match-end 0)
6045 '(font-lock-fontified t face org-macro))
6046 (when org-hide-macro-markers
6047 (add-text-properties (match-end 2) (match-beginning 2)
6048 '(invisible t))
6049 (add-text-properties (match-beginning 1) (match-end 1)
6050 '(invisible t)))
6051 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6054 (defun org-activate-angle-links (limit)
6055 "Add text properties for angle links."
6056 (when (and (re-search-forward org-angle-link-re limit t)
6057 (not (org-in-src-block-p)))
6058 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6059 (add-text-properties (match-beginning 0) (match-end 0)
6060 (list 'mouse-face 'highlight
6061 'keymap org-mouse-map
6062 'font-lock-multiline t))
6063 (org-rear-nonsticky-at (match-end 0))
6066 (defun org-activate-footnote-links (limit)
6067 "Add text properties for footnotes."
6068 (let ((fn (org-footnote-next-reference-or-definition limit)))
6069 (when fn
6070 (let* ((beg (nth 1 fn))
6071 (end (nth 2 fn))
6072 (label (car fn))
6073 (referencep (/= (line-beginning-position) beg)))
6074 (when (and referencep (nth 3 fn))
6075 (save-excursion
6076 (goto-char beg)
6077 (search-forward (or label "fn:"))
6078 (org-remove-flyspell-overlays-in beg (match-end 0))))
6079 (add-text-properties beg end
6080 (list 'mouse-face 'highlight
6081 'keymap org-mouse-map
6082 'help-echo
6083 (if referencep "Footnote reference"
6084 "Footnote definition")
6085 'font-lock-fontified t
6086 'font-lock-multiline t
6087 'face 'org-footnote))))))
6089 (defun org-activate-bracket-links (limit)
6090 "Add text properties for bracketed links."
6091 (when (and (re-search-forward org-bracket-link-regexp limit t)
6092 (not (org-in-src-block-p)))
6093 (let* ((hl (match-string-no-properties 1))
6094 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6095 (ip (org-maybe-intangible
6096 (list 'invisible 'org-link
6097 'keymap org-mouse-map 'mouse-face 'highlight
6098 'font-lock-multiline t 'help-echo help
6099 'htmlize-link `(:uri ,hl))))
6100 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6101 'font-lock-multiline t 'help-echo help
6102 'htmlize-link `(:uri ,hl))))
6103 ;; We need to remove the invisible property here. Table narrowing
6104 ;; may have made some of this invisible.
6105 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6106 (remove-text-properties (match-beginning 0) (match-end 0)
6107 '(invisible nil))
6108 (if (match-end 3)
6109 (progn
6110 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6111 (org-rear-nonsticky-at (match-beginning 3))
6112 (add-text-properties (match-beginning 3) (match-end 3) vp)
6113 (org-rear-nonsticky-at (match-end 3))
6114 (add-text-properties (match-end 3) (match-end 0) ip)
6115 (org-rear-nonsticky-at (match-end 0)))
6116 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6117 (org-rear-nonsticky-at (match-beginning 1))
6118 (add-text-properties (match-beginning 1) (match-end 1) vp)
6119 (org-rear-nonsticky-at (match-end 1))
6120 (add-text-properties (match-end 1) (match-end 0) ip)
6121 (org-rear-nonsticky-at (match-end 0)))
6122 t)))
6124 (defun org-activate-dates (limit)
6125 "Add text properties for dates."
6126 (when (and (re-search-forward org-tsr-regexp-both limit t)
6127 (not (equal (char-before (match-beginning 0)) 91)))
6128 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6129 (add-text-properties (match-beginning 0) (match-end 0)
6130 (list 'mouse-face 'highlight
6131 'keymap org-mouse-map))
6132 (org-rear-nonsticky-at (match-end 0))
6133 (when org-display-custom-times
6134 (if (match-end 3)
6135 (org-display-custom-time (match-beginning 3) (match-end 3))
6136 (org-display-custom-time (match-beginning 1) (match-end 1))))
6139 (defvar-local org-target-link-regexp nil
6140 "Regular expression matching radio targets in plain text.")
6142 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6143 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6144 border border border))
6145 "Regular expression matching a link target.")
6147 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6148 "Regular expression matching a radio target.")
6150 (defconst org-any-target-regexp
6151 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6152 "Regular expression matching any target.")
6154 (defun org-activate-target-links (limit)
6155 "Add text properties for target matches."
6156 (when org-target-link-regexp
6157 (let ((case-fold-search t))
6158 (when (re-search-forward org-target-link-regexp limit t)
6159 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6160 (add-text-properties (match-beginning 1) (match-end 1)
6161 (list 'mouse-face 'highlight
6162 'keymap org-mouse-map
6163 'help-echo "Radio target link"
6164 'org-linked-text t))
6165 (org-rear-nonsticky-at (match-end 1))
6166 t))))
6168 (defun org-update-radio-target-regexp ()
6169 "Find all radio targets in this file and update the regular expression.
6170 Also refresh fontification if needed."
6171 (interactive)
6172 (let ((old-regexp org-target-link-regexp)
6173 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6174 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6175 (targets
6176 (org-with-wide-buffer
6177 (goto-char (point-min))
6178 (let (rtn)
6179 (while (re-search-forward org-radio-target-regexp nil t)
6180 ;; Make sure point is really within the object.
6181 (backward-char)
6182 (let ((obj (org-element-context)))
6183 (when (eq (org-element-type obj) 'radio-target)
6184 (cl-pushnew (org-element-property :value obj) rtn
6185 :test #'equal))))
6186 rtn))))
6187 (setq org-target-link-regexp
6188 (and targets
6189 (concat before-re
6190 (mapconcat
6191 (lambda (x)
6192 (replace-regexp-in-string
6193 " +" "\\s-+" (regexp-quote x) t t))
6194 targets
6195 "\\|")
6196 after-re)))
6197 (unless (equal old-regexp org-target-link-regexp)
6198 ;; Clean-up cache.
6199 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6200 ((not org-target-link-regexp) old-regexp)
6202 (concat before-re
6203 (mapconcat
6204 (lambda (re)
6205 (substring re (length before-re)
6206 (- (length after-re))))
6207 (list old-regexp org-target-link-regexp)
6208 "\\|")
6209 after-re)))))
6210 (org-with-wide-buffer
6211 (goto-char (point-min))
6212 (while (re-search-forward regexp nil t)
6213 (org-element-cache-refresh (match-beginning 1)))))
6214 ;; Re fontify buffer.
6215 (when (memq 'radio org-highlight-links)
6216 (org-restart-font-lock)))))
6218 (defun org-hide-wide-columns (limit)
6219 (let (s e)
6220 (setq s (text-property-any (point) (or limit (point-max))
6221 'org-cwidth t))
6222 (when s
6223 (setq e (next-single-property-change s 'org-cwidth))
6224 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6225 (goto-char e)
6226 t)))
6228 (defvar org-latex-and-related-regexp nil
6229 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6231 (defun org-compute-latex-and-related-regexp ()
6232 "Compute regular expression for LaTeX, entities and sub/superscript.
6233 Result depends on variable `org-highlight-latex-and-related'."
6234 (setq-local
6235 org-latex-and-related-regexp
6236 (let* ((re-sub
6237 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6238 ((eq org-use-sub-superscripts '{})
6239 (list org-match-substring-with-braces-regexp))
6240 (org-use-sub-superscripts (list org-match-substring-regexp))))
6241 (re-latex
6242 (when (memq 'latex org-highlight-latex-and-related)
6243 (let ((matchers (plist-get org-format-latex-options :matchers)))
6244 (delq nil
6245 (mapcar (lambda (x)
6246 (and (member (car x) matchers) (nth 1 x)))
6247 org-latex-regexps)))))
6248 (re-entities
6249 (when (memq 'entities org-highlight-latex-and-related)
6250 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6251 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6253 (defun org-do-latex-and-related (limit)
6254 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6255 LIMIT bounds the search for syntax to highlight. Stop at first
6256 highlighted object, if any. Return t if some highlighting was
6257 done, nil otherwise."
6258 (when (org-string-nw-p org-latex-and-related-regexp)
6259 (catch 'found
6260 (while (re-search-forward org-latex-and-related-regexp limit t)
6261 (unless
6262 (cl-some
6263 (lambda (f)
6264 (memq f '(org-code org-verbatim underline org-special-keyword)))
6265 (save-excursion
6266 (goto-char (1+ (match-beginning 0)))
6267 (face-at-point nil t)))
6268 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6269 '(?_ ?^))
6271 0)))
6272 (font-lock-prepend-text-property
6273 (+ offset (match-beginning 0)) (match-end 0)
6274 'face 'org-latex-and-related)
6275 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6276 '(font-lock-multiline t)))
6277 (throw 'found t)))
6278 nil)))
6280 (defun org-restart-font-lock ()
6281 "Restart `font-lock-mode', to force refontification."
6282 (when (and (boundp 'font-lock-mode) font-lock-mode)
6283 (font-lock-mode -1)
6284 (font-lock-mode 1)))
6286 (defun org-activate-tags (limit)
6287 (when (re-search-forward
6288 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6289 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6290 (add-text-properties (match-beginning 1) (match-end 1)
6291 (list 'mouse-face 'highlight
6292 'keymap org-mouse-map))
6293 (org-rear-nonsticky-at (match-end 1))
6296 (defun org-outline-level ()
6297 "Compute the outline level of the heading at point.
6299 If this is called at a normal headline, the level is the number
6300 of stars. Use `org-reduced-level' to remove the effect of
6301 `org-odd-levels'. Unlike to `org-current-level', this function
6302 takes into consideration inlinetasks."
6303 (org-with-wide-buffer
6304 (end-of-line)
6305 (if (re-search-backward org-outline-regexp-bol nil t)
6306 (1- (- (match-end 0) (match-beginning 0)))
6307 0)))
6309 (defvar org-font-lock-keywords nil)
6311 (defsubst org-re-property (property &optional literal allow-null value)
6312 "Return a regexp matching a PROPERTY line.
6314 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6315 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6316 non-nil, match properties even without a value.
6318 Match group 3 is set to the value when it exists. If there is no
6319 value and ALLOW-NULL is non-nil, it is set to the empty string.
6321 With optional argument VALUE, match only property lines with
6322 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6323 unless LITERAL is non-nil."
6324 (concat
6325 "^\\(?4:[ \t]*\\)"
6326 (format "\\(?1::\\(?2:%s\\):\\)"
6327 (if literal property (regexp-quote property)))
6328 (cond (value
6329 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6330 (if literal value (regexp-quote value))))
6331 (allow-null
6332 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6334 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6336 (defconst org-property-re
6337 (org-re-property "\\S-+" 'literal t)
6338 "Regular expression matching a property line.
6339 There are four matching groups:
6340 1: :PROPKEY: including the leading and trailing colon,
6341 2: PROPKEY without the leading and trailing colon,
6342 3: PROPVAL without leading or trailing spaces,
6343 4: the indentation of the current line,
6344 5: trailing whitespace.")
6346 (defvar org-font-lock-hook nil
6347 "Functions to be called for special font lock stuff.")
6349 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6351 (defvar org-font-lock-set-keywords-hook nil
6352 "Functions that can manipulate `org-font-lock-extra-keywords'.
6353 This is called after `org-font-lock-extra-keywords' is defined, but before
6354 it is installed to be used by font lock. This can be useful if something
6355 needs to be inserted at a specific position in the font-lock sequence.")
6357 (defun org-font-lock-hook (limit)
6358 "Run `org-font-lock-hook' within LIMIT."
6359 (run-hook-with-args 'org-font-lock-hook limit))
6361 (defun org-set-font-lock-defaults ()
6362 "Set font lock defaults for the current buffer."
6363 (let* ((em org-fontify-emphasized-text)
6364 (lk org-highlight-links)
6365 (org-font-lock-extra-keywords
6366 (list
6367 ;; Call the hook
6368 '(org-font-lock-hook)
6369 ;; Headlines
6370 `(,(if org-fontify-whole-heading-line
6371 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6372 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6373 (1 (org-get-level-face 1))
6374 (2 (org-get-level-face 2))
6375 (3 (org-get-level-face 3)))
6376 ;; Table lines
6377 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6378 (1 'org-table t))
6379 ;; Table internals
6380 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6381 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6382 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6383 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6384 ;; Drawers
6385 '(org-fontify-drawers)
6386 ;; Properties
6387 (list org-property-re
6388 '(1 'org-special-keyword t)
6389 '(3 'org-property-value t))
6390 ;; Links
6391 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6392 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6393 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6394 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6395 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6396 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6397 (when (memq 'footnote lk) '(org-activate-footnote-links))
6398 ;; Targets.
6399 (list org-any-target-regexp '(0 'org-target t))
6400 ;; Diary sexps.
6401 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6402 ;; Macro
6403 '(org-fontify-macros)
6404 '(org-hide-wide-columns (0 nil append))
6405 ;; TODO keyword
6406 (list (format org-heading-keyword-regexp-format
6407 org-todo-regexp)
6408 '(2 (org-get-todo-face 2) t))
6409 ;; DONE
6410 (if org-fontify-done-headline
6411 (list (format org-heading-keyword-regexp-format
6412 (concat
6413 "\\(?:"
6414 (mapconcat 'regexp-quote org-done-keywords "\\|")
6415 "\\)"))
6416 '(2 'org-headline-done t))
6417 nil)
6418 ;; Priorities
6419 '(org-font-lock-add-priority-faces)
6420 ;; Tags
6421 '(org-font-lock-add-tag-faces)
6422 ;; Tags groups
6423 (when (and org-group-tags org-tag-groups-alist)
6424 (list (concat org-outline-regexp-bol ".+\\(:"
6425 (regexp-opt (mapcar 'car org-tag-groups-alist))
6426 ":\\).*$")
6427 '(1 'org-tag-group prepend)))
6428 ;; Special keywords
6429 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6430 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6431 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6432 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6433 ;; Emphasis
6434 (when em '(org-do-emphasis-faces))
6435 ;; Checkboxes
6436 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6437 1 'org-checkbox prepend)
6438 (when (cdr (assq 'checkbox org-list-automatic-rules))
6439 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6440 (0 (org-get-checkbox-statistics-face) t)))
6441 ;; Description list items
6442 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6443 1 'org-list-dt prepend)
6444 ;; ARCHIVEd headings
6445 (list (concat
6446 org-outline-regexp-bol
6447 "\\(.*:" org-archive-tag ":.*\\)")
6448 '(1 'org-archived prepend))
6449 ;; Specials
6450 '(org-do-latex-and-related)
6451 '(org-fontify-entities)
6452 '(org-raise-scripts)
6453 ;; Code
6454 '(org-activate-code (1 'org-code t))
6455 ;; COMMENT
6456 (list (format
6457 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6458 org-todo-regexp
6459 org-comment-string)
6460 '(9 'org-special-keyword t))
6461 ;; Blocks and meta lines
6462 '(org-fontify-meta-lines-and-blocks))))
6463 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6464 (run-hooks 'org-font-lock-set-keywords-hook)
6465 ;; Now set the full font-lock-keywords
6466 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6467 (setq-local font-lock-defaults
6468 '(org-font-lock-keywords t nil nil backward-paragraph))
6469 (kill-local-variable 'font-lock-keywords) nil))
6471 (defun org-toggle-pretty-entities ()
6472 "Toggle the composition display of entities as UTF8 characters."
6473 (interactive)
6474 (setq-local org-pretty-entities (not org-pretty-entities))
6475 (org-restart-font-lock)
6476 (if org-pretty-entities
6477 (message "Entities are now displayed as UTF8 characters")
6478 (save-restriction
6479 (widen)
6480 (decompose-region (point-min) (point-max))
6481 (message "Entities are now displayed as plain text"))))
6483 (defvar-local org-custom-properties-overlays nil
6484 "List of overlays used for custom properties.")
6486 (defun org-toggle-custom-properties-visibility ()
6487 "Display or hide properties in `org-custom-properties'."
6488 (interactive)
6489 (if org-custom-properties-overlays
6490 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6491 (setq org-custom-properties-overlays nil))
6492 (when org-custom-properties
6493 (org-with-wide-buffer
6494 (goto-char (point-min))
6495 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6496 (while (re-search-forward regexp nil t)
6497 (let ((end (cdr (save-match-data (org-get-property-block)))))
6498 (when (and end (< (point) end))
6499 ;; Hide first custom property in current drawer.
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 ;; Hide additional custom properties in the same drawer.
6505 (while (re-search-forward regexp end t)
6506 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6507 (overlay-put o 'invisible t)
6508 (overlay-put o 'org-custom-property t)
6509 (push o org-custom-properties-overlays)))))
6510 ;; Each entry is limited to a single property drawer.
6511 (outline-next-heading)))))))
6513 (defun org-fontify-entities (limit)
6514 "Find an entity to fontify."
6515 (let (ee)
6516 (when org-pretty-entities
6517 (catch 'match
6518 ;; "\_ "-family is left out on purpose. Only the first one,
6519 ;; i.e., "\_ ", could be fontified anyway, and it would be
6520 ;; confusing when adding a second white space character.
6521 (while (re-search-forward
6522 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6523 limit t)
6524 (when (and (not (org-at-comment-p))
6525 (setq ee (org-entity-get (match-string 1)))
6526 (= (length (nth 6 ee)) 1))
6527 (let* ((end (if (equal (match-string 2) "{}")
6528 (match-end 2)
6529 (match-end 1))))
6530 (add-text-properties
6531 (match-beginning 0) end
6532 (list 'font-lock-fontified t))
6533 (compose-region (match-beginning 0) end
6534 (nth 6 ee) nil)
6535 (backward-char 1)
6536 (throw 'match t))))
6537 nil))))
6539 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6540 "Fontify string S like in Org-mode."
6541 (with-temp-buffer
6542 (insert s)
6543 (let ((org-odd-levels-only odd-levels))
6544 (org-mode)
6545 (org-font-lock-ensure)
6546 (buffer-string))))
6548 (defvar org-m nil)
6549 (defvar org-l nil)
6550 (defvar org-f nil)
6551 (defun org-get-level-face (n)
6552 "Get the right face for match N in font-lock matching of headlines."
6553 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6554 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6555 (if org-cycle-level-faces
6556 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6557 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6558 (cond
6559 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6560 ((eq n 2) org-f)
6561 (t (unless org-level-color-stars-only org-f))))
6563 (defun org-face-from-face-or-color (context inherit face-or-color)
6564 "Create a face list that inherits INHERIT, but sets the foreground color.
6565 When FACE-OR-COLOR is not a string, just return it."
6566 (if (stringp face-or-color)
6567 (list :inherit inherit
6568 (cdr (assoc context org-faces-easy-properties))
6569 face-or-color)
6570 face-or-color))
6572 (defun org-get-todo-face (kwd)
6573 "Get the right face for a TODO keyword KWD.
6574 If KWD is a number, get the corresponding match group."
6575 (when (numberp kwd) (setq kwd (match-string kwd)))
6576 (or (org-face-from-face-or-color
6577 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6578 (and (member kwd org-done-keywords) 'org-done)
6579 'org-todo))
6581 (defun org-get-priority-face (priority)
6582 "Get the right face for PRIORITY.
6583 PRIORITY is a character."
6584 (or (org-face-from-face-or-color
6585 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6586 'org-priority))
6588 (defun org-get-tag-face (tag)
6589 "Get the right face for TAG.
6590 If TAG is a number, get the corresponding match group."
6591 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6592 (or (org-face-from-face-or-color
6593 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6594 'org-tag)))
6596 (defun org-font-lock-add-priority-faces (limit)
6597 "Add the special priority faces."
6598 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6599 (add-text-properties
6600 (match-beginning 1) (match-end 1)
6601 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6602 'font-lock-fontified t))))
6604 (defun org-font-lock-add-tag-faces (limit)
6605 "Add the special tag faces."
6606 (when (and org-tag-faces org-tags-special-faces-re)
6607 (while (re-search-forward org-tags-special-faces-re limit t)
6608 (add-text-properties (match-beginning 1) (match-end 1)
6609 (list 'face (org-get-tag-face 1)
6610 'font-lock-fontified t))
6611 (backward-char 1))))
6613 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6614 "Remove fontification and activation overlays from links."
6615 (font-lock-default-unfontify-region beg end)
6616 (let* ((buffer-undo-list t)
6617 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6618 (inhibit-modification-hooks t)
6619 deactivate-mark buffer-file-name buffer-file-truename)
6620 (decompose-region beg end)
6621 (remove-text-properties beg end
6622 '(mouse-face t keymap t org-linked-text t
6623 invisible t intangible t
6624 org-emphasis t))
6625 (org-remove-font-lock-display-properties beg end)))
6627 (defconst org-script-display '(((raise -0.3) (height 0.7))
6628 ((raise 0.3) (height 0.7))
6629 ((raise -0.5))
6630 ((raise 0.5)))
6631 "Display properties for showing superscripts and subscripts.")
6633 (defun org-remove-font-lock-display-properties (beg end)
6634 "Remove specific display properties that have been added by font lock.
6635 The will remove the raise properties that are used to show superscripts
6636 and subscripts."
6637 (let (next prop)
6638 (while (< beg end)
6639 (setq next (next-single-property-change beg 'display nil end)
6640 prop (get-text-property beg 'display))
6641 (when (member prop org-script-display)
6642 (put-text-property beg next 'display nil))
6643 (setq beg next))))
6645 (defun org-raise-scripts (limit)
6646 "Add raise properties to sub/superscripts."
6647 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6648 (re-search-forward
6649 (if (eq org-use-sub-superscripts t)
6650 org-match-substring-regexp
6651 org-match-substring-with-braces-regexp)
6652 limit t))
6653 (let* ((pos (point)) table-p comment-p
6654 (mpos (match-beginning 3))
6655 (emph-p (get-text-property mpos 'org-emphasis))
6656 (link-p (get-text-property mpos 'mouse-face))
6657 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6658 (goto-char (point-at-bol))
6659 (setq table-p (looking-at-p org-table-dataline-regexp)
6660 comment-p (looking-at-p "^[ \t]*#[ +]"))
6661 (goto-char pos)
6662 ;; Handle a_b^c
6663 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6664 (unless (or comment-p emph-p link-p keyw-p)
6665 (put-text-property (match-beginning 3) (match-end 0)
6666 'display
6667 (if (equal (char-after (match-beginning 2)) ?^)
6668 (nth (if table-p 3 1) org-script-display)
6669 (nth (if table-p 2 0) org-script-display)))
6670 (add-text-properties (match-beginning 2) (match-end 2)
6671 (list 'invisible t
6672 'org-dwidth t 'org-dwidth-n 1))
6673 (if (and (eq (char-after (match-beginning 3)) ?{)
6674 (eq (char-before (match-end 3)) ?}))
6675 (progn
6676 (add-text-properties
6677 (match-beginning 3) (1+ (match-beginning 3))
6678 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6679 (add-text-properties
6680 (1- (match-end 3)) (match-end 3)
6681 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6682 t)))
6684 ;;;; Visibility cycling, including org-goto and indirect buffer
6686 ;;; Cycling
6688 (defvar-local org-cycle-global-status nil)
6689 (put 'org-cycle-global-status 'org-state t)
6690 (defvar-local org-cycle-subtree-status nil)
6691 (put 'org-cycle-subtree-status 'org-state t)
6693 (defvar org-inlinetask-min-level)
6695 (defun org-unlogged-message (&rest args)
6696 "Display a message, but avoid logging it in the *Messages* buffer."
6697 (let ((message-log-max nil))
6698 (apply 'message args)))
6700 ;;;###autoload
6701 (defun org-cycle (&optional arg)
6702 "TAB-action and visibility cycling for Org-mode.
6704 This is the command invoked in Org-mode by the TAB key. Its main purpose
6705 is outline visibility cycling, but it also invokes other actions
6706 in special contexts.
6708 - When this function is called with a prefix argument, rotate the entire
6709 buffer through 3 states (global cycling)
6710 1. OVERVIEW: Show only top-level headlines.
6711 2. CONTENTS: Show all headlines of all levels, but no body text.
6712 3. SHOW ALL: Show everything.
6713 With a double \\[universal-argument] prefix argument, \
6714 switch to the startup visibility,
6715 determined by the variable `org-startup-folded', and by any VISIBILITY
6716 properties in the buffer.
6717 With a triple \\[universal-argument] prefix argument, \
6718 show the entire buffer, including any drawers.
6720 - When inside a table, re-align the table and move to the next field.
6722 - When point is at the beginning of a headline, rotate the subtree started
6723 by this line through 3 different states (local cycling)
6724 1. FOLDED: Only the main headline is shown.
6725 2. CHILDREN: The main headline and the direct children are shown.
6726 From this state, you can move to one of the children
6727 and zoom in further.
6728 3. SUBTREE: Show the entire subtree, including body text.
6729 If there is no subtree, switch directly from CHILDREN to FOLDED.
6731 - When point is at the beginning of an empty headline and the variable
6732 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6733 of the headline by demoting and promoting it to likely levels. This
6734 speeds up creation document structure by pressing TAB once or several
6735 times right after creating a new headline.
6737 - When there is a numeric prefix, go up to a heading with level ARG, do
6738 a `show-subtree' and return to the previous cursor position. If ARG
6739 is negative, go up that many levels.
6741 - When point is not at the beginning of a headline, execute the global
6742 binding for TAB, which is re-indenting the line. See the option
6743 `org-cycle-emulate-tab' for details.
6745 - Special case: if point is at the beginning of the buffer and there is
6746 no headline in line 1, this function will act as if called with prefix arg
6747 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6748 But only if also the variable `org-cycle-global-at-bob' is t."
6749 (interactive "P")
6750 (org-load-modules-maybe)
6751 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6752 (and org-cycle-level-after-item/entry-creation
6753 (or (org-cycle-level)
6754 (org-cycle-item-indentation))))
6755 (let* ((limit-level
6756 (or org-cycle-max-level
6757 (and (boundp 'org-inlinetask-min-level)
6758 org-inlinetask-min-level
6759 (1- org-inlinetask-min-level))))
6760 (nstars (and limit-level
6761 (if org-odd-levels-only
6762 (and limit-level (1- (* limit-level 2)))
6763 limit-level)))
6764 (org-outline-regexp
6765 (if (not (derived-mode-p 'org-mode))
6766 outline-regexp
6767 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6768 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6769 (not (looking-at org-outline-regexp))))
6770 (org-cycle-hook
6771 (if bob-special
6772 (delq 'org-optimize-window-after-visibility-change
6773 (copy-sequence org-cycle-hook))
6774 org-cycle-hook))
6775 (pos (point)))
6777 (when (or bob-special (equal arg '(4)))
6778 ;; special case: use global cycling
6779 (setq arg t))
6781 (cond
6783 ((equal arg '(16))
6784 (setq last-command 'dummy)
6785 (org-set-startup-visibility)
6786 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6788 ((equal arg '(64))
6789 (outline-show-all)
6790 (org-unlogged-message "Entire buffer visible, including drawers"))
6792 ;; Try cdlatex TAB completion
6793 ((org-try-cdlatex-tab))
6795 ;; Table: enter it or move to the next field.
6796 ((org-at-table-p 'any)
6797 (if (org-at-table.el-p)
6798 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6799 Use \\[org-edit-special] to edit table.el tables"))
6800 (if arg (org-table-edit-field t)
6801 (org-table-justify-field-maybe)
6802 (call-interactively 'org-table-next-field))))
6804 ((run-hook-with-args-until-success
6805 'org-tab-after-check-for-table-hook))
6807 ;; Global cycling: delegate to `org-cycle-internal-global'.
6808 ((eq arg t) (org-cycle-internal-global))
6810 ;; Drawers: delegate to `org-flag-drawer'.
6811 ((save-excursion
6812 (beginning-of-line 1)
6813 (looking-at org-drawer-regexp))
6814 (org-flag-drawer ; toggle block visibility
6815 (not (get-char-property (match-end 0) 'invisible))))
6817 ;; Show-subtree, ARG levels up from here.
6818 ((integerp arg)
6819 (save-excursion
6820 (org-back-to-heading)
6821 (outline-up-heading (if (< arg 0) (- arg)
6822 (- (funcall outline-level) arg)))
6823 (org-show-subtree)))
6825 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6826 ((and (featurep 'org-inlinetask)
6827 (org-inlinetask-at-task-p)
6828 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6829 (org-inlinetask-toggle-visibility))
6831 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6832 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6833 (save-excursion (move-beginning-of-line 1)
6834 (looking-at org-outline-regexp)))
6835 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6836 (org-cycle-internal-local))
6838 ;; From there: TAB emulation and template completion.
6839 (buffer-read-only (org-back-to-heading))
6841 ((run-hook-with-args-until-success
6842 'org-tab-after-check-for-cycling-hook))
6844 ((org-try-structure-completion))
6846 ((run-hook-with-args-until-success
6847 'org-tab-before-tab-emulation-hook))
6849 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6850 (or (not (bolp))
6851 (not (looking-at org-outline-regexp))))
6852 (call-interactively (global-key-binding "\t")))
6854 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6855 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6856 (or (and (eq org-cycle-emulate-tab 'white)
6857 (= (match-end 0) (point-at-eol)))
6858 (and (eq org-cycle-emulate-tab 'whitestart)
6859 (>= (match-end 0) pos))))
6861 (eq org-cycle-emulate-tab t))
6862 (call-interactively (global-key-binding "\t")))
6864 (t (save-excursion
6865 (org-back-to-heading)
6866 (org-cycle)))))))
6868 (defun org-cycle-internal-global ()
6869 "Do the global cycling action."
6870 ;; Hack to avoid display of messages for .org attachments in Gnus
6871 (let ((ga (string-match "\\*fontification" (buffer-name))))
6872 (cond
6873 ((and (eq last-command this-command)
6874 (eq org-cycle-global-status 'overview))
6875 ;; We just created the overview - now do table of contents
6876 ;; This can be slow in very large buffers, so indicate action
6877 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6878 (unless ga (org-unlogged-message "CONTENTS..."))
6879 (org-content)
6880 (unless ga (org-unlogged-message "CONTENTS...done"))
6881 (setq org-cycle-global-status 'contents)
6882 (run-hook-with-args 'org-cycle-hook 'contents))
6884 ((and (eq last-command this-command)
6885 (eq org-cycle-global-status 'contents))
6886 ;; We just showed the table of contents - now show everything
6887 (run-hook-with-args 'org-pre-cycle-hook 'all)
6888 (outline-show-all)
6889 (unless ga (org-unlogged-message "SHOW ALL"))
6890 (setq org-cycle-global-status 'all)
6891 (run-hook-with-args 'org-cycle-hook 'all))
6894 ;; Default action: go to overview
6895 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6896 (org-overview)
6897 (unless ga (org-unlogged-message "OVERVIEW"))
6898 (setq org-cycle-global-status 'overview)
6899 (run-hook-with-args 'org-cycle-hook 'overview)))))
6901 (defvar org-called-with-limited-levels nil
6902 "Non-nil when `org-with-limited-levels' is currently active.")
6904 (defun org-cycle-internal-local ()
6905 "Do the local cycling action."
6906 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6907 ;; First, determine end of headline (EOH), end of subtree or item
6908 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6909 (save-excursion
6910 (if (org-at-item-p)
6911 (progn
6912 (beginning-of-line)
6913 (setq struct (org-list-struct))
6914 (setq eoh (point-at-eol))
6915 (setq eos (org-list-get-item-end-before-blank (point) struct))
6916 (setq has-children (org-list-has-child-p (point) struct)))
6917 (org-back-to-heading)
6918 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6919 (setq eos (save-excursion (org-end-of-subtree t t)
6920 (when (bolp) (backward-char)) (point)))
6921 (setq has-children
6922 (or (save-excursion
6923 (let ((level (funcall outline-level)))
6924 (outline-next-heading)
6925 (and (org-at-heading-p t)
6926 (> (funcall outline-level) level))))
6927 (save-excursion
6928 (org-list-search-forward (org-item-beginning-re) eos t)))))
6929 ;; Determine end invisible part of buffer (EOL)
6930 (beginning-of-line 2)
6931 (while (and (not (eobp)) ;This is like `next-line'.
6932 (get-char-property (1- (point)) 'invisible))
6933 (goto-char (next-single-char-property-change (point) 'invisible))
6934 (and (eolp) (beginning-of-line 2)))
6935 (setq eol (point)))
6936 ;; Find out what to do next and set `this-command'
6937 (cond
6938 ((= eos eoh)
6939 ;; Nothing is hidden behind this heading
6940 (unless (org-before-first-heading-p)
6941 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6942 (org-unlogged-message "EMPTY ENTRY")
6943 (setq org-cycle-subtree-status nil)
6944 (save-excursion
6945 (goto-char eos)
6946 (outline-next-heading)
6947 (when (outline-invisible-p) (org-flag-heading nil))))
6948 ((and (or (>= eol eos)
6949 (not (string-match "\\S-" (buffer-substring eol eos))))
6950 (or has-children
6951 (not (setq children-skipped
6952 org-cycle-skip-children-state-if-no-children))))
6953 ;; Entire subtree is hidden in one line: children view
6954 (unless (org-before-first-heading-p)
6955 (run-hook-with-args 'org-pre-cycle-hook 'children))
6956 (if (org-at-item-p)
6957 (org-list-set-item-visibility (point-at-bol) struct 'children)
6958 (org-show-entry)
6959 (org-with-limited-levels (org-show-children))
6960 ;; FIXME: This slows down the func way too much.
6961 ;; How keep drawers hidden in subtree anyway?
6962 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6963 ;; (org-cycle-hide-drawers 'subtree))
6965 ;; Fold every list in subtree to top-level items.
6966 (when (eq org-cycle-include-plain-lists 'integrate)
6967 (save-excursion
6968 (org-back-to-heading)
6969 (while (org-list-search-forward (org-item-beginning-re) eos t)
6970 (beginning-of-line 1)
6971 (let* ((struct (org-list-struct))
6972 (prevs (org-list-prevs-alist struct))
6973 (end (org-list-get-bottom-point struct)))
6974 (dolist (e (org-list-get-all-items (point) struct prevs))
6975 (org-list-set-item-visibility e struct 'folded))
6976 (goto-char (if (< end eos) end eos)))))))
6977 (org-unlogged-message "CHILDREN")
6978 (save-excursion
6979 (goto-char eos)
6980 (outline-next-heading)
6981 (when (outline-invisible-p) (org-flag-heading nil)))
6982 (setq org-cycle-subtree-status 'children)
6983 (unless (org-before-first-heading-p)
6984 (run-hook-with-args 'org-cycle-hook 'children)))
6985 ((or children-skipped
6986 (and (eq last-command this-command)
6987 (eq org-cycle-subtree-status 'children)))
6988 ;; We just showed the children, or no children are there,
6989 ;; now show everything.
6990 (unless (org-before-first-heading-p)
6991 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6992 (outline-flag-region eoh eos nil)
6993 (org-unlogged-message
6994 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6995 (setq org-cycle-subtree-status 'subtree)
6996 (unless (org-before-first-heading-p)
6997 (run-hook-with-args 'org-cycle-hook 'subtree)))
6999 ;; Default action: hide the subtree.
7000 (run-hook-with-args 'org-pre-cycle-hook 'folded)
7001 (outline-flag-region eoh eos t)
7002 (org-unlogged-message "FOLDED")
7003 (setq org-cycle-subtree-status 'folded)
7004 (unless (org-before-first-heading-p)
7005 (run-hook-with-args 'org-cycle-hook 'folded))))))
7007 ;;;###autoload
7008 (defun org-global-cycle (&optional arg)
7009 "Cycle the global visibility. For details see `org-cycle'.
7010 With \\[universal-argument] prefix arg, switch to startup visibility.
7011 With a numeric prefix, show all headlines up to that level."
7012 (interactive "P")
7013 (let ((org-cycle-include-plain-lists
7014 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7015 (cond
7016 ((integerp arg)
7017 (outline-show-all)
7018 (outline-hide-sublevels arg)
7019 (setq org-cycle-global-status 'contents))
7020 ((equal arg '(4))
7021 (org-set-startup-visibility)
7022 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7024 (org-cycle '(4))))))
7026 (defun org-set-startup-visibility ()
7027 "Set the visibility required by startup options and properties."
7028 (cond
7029 ((eq org-startup-folded t)
7030 (org-overview))
7031 ((eq org-startup-folded 'content)
7032 (org-content))
7033 ((or (eq org-startup-folded 'showeverything)
7034 (eq org-startup-folded nil))
7035 (outline-show-all)))
7036 (unless (eq org-startup-folded 'showeverything)
7037 (when org-hide-block-startup (org-hide-block-all))
7038 (org-set-visibility-according-to-property 'no-cleanup)
7039 (org-cycle-hide-archived-subtrees 'all)
7040 (org-cycle-hide-drawers 'all)
7041 (org-cycle-show-empty-lines t)))
7043 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7044 "Switch subtree visibilities according to :VISIBILITY: property."
7045 (interactive)
7046 (org-with-wide-buffer
7047 (goto-char (point-min))
7048 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7049 (if (not (org-at-property-p)) (outline-next-heading)
7050 (let ((state (match-string 3)))
7051 (save-excursion
7052 (org-back-to-heading t)
7053 (outline-hide-subtree)
7054 (org-reveal)
7055 (cond
7056 ((equal state "folded")
7057 (outline-hide-subtree))
7058 ((equal state "children")
7059 (org-show-hidden-entry)
7060 (org-show-children))
7061 ((equal state "content")
7062 (save-excursion
7063 (save-restriction
7064 (org-narrow-to-subtree)
7065 (org-content))))
7066 ((member state '("all" "showall"))
7067 (outline-show-subtree)))))))
7068 (unless no-cleanup
7069 (org-cycle-hide-archived-subtrees 'all)
7070 (org-cycle-hide-drawers 'all)
7071 (org-cycle-show-empty-lines 'all))))
7073 ;; This function uses outline-regexp instead of the more fundamental
7074 ;; org-outline-regexp so that org-cycle-global works outside of Org
7075 ;; buffers, where outline-regexp is needed.
7076 (defun org-overview ()
7077 "Switch to overview mode, showing only top-level headlines.
7078 This shows all headlines with a level equal or greater than the level
7079 of the first headline in the buffer. This is important, because if the
7080 first headline is not level one, then (hide-sublevels 1) gives confusing
7081 results."
7082 (interactive)
7083 (save-excursion
7084 (let ((level
7085 (save-excursion
7086 (goto-char (point-min))
7087 (when (re-search-forward (concat "^" outline-regexp) nil t)
7088 (goto-char (match-beginning 0))
7089 (funcall outline-level)))))
7090 (and level (outline-hide-sublevels level)))))
7092 (defun org-content (&optional arg)
7093 "Show all headlines in the buffer, like a table of contents.
7094 With numerical argument N, show content up to level N."
7095 (interactive "P")
7096 (org-overview)
7097 (save-excursion
7098 ;; Visit all headings and show their offspring
7099 (and (integerp arg) (org-overview))
7100 (goto-char (point-max))
7101 (catch 'exit
7102 (while (and (progn (condition-case nil
7103 (outline-previous-visible-heading 1)
7104 (error (goto-char (point-min))))
7106 (looking-at org-outline-regexp))
7107 (if (integerp arg)
7108 (org-show-children (1- arg))
7109 (outline-show-branches))
7110 (when (bobp) (throw 'exit nil))))))
7112 (defun org-optimize-window-after-visibility-change (state)
7113 "Adjust the window after a change in outline visibility.
7114 This function is the default value of the hook `org-cycle-hook'."
7115 (when (get-buffer-window (current-buffer))
7116 (cond
7117 ((eq state 'content) nil)
7118 ((eq state 'all) nil)
7119 ((eq state 'folded) nil)
7120 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7121 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7123 (defun org-remove-empty-overlays-at (pos)
7124 "Remove outline overlays that do not contain non-white stuff."
7125 (dolist (o (overlays-at pos))
7126 (and (eq 'outline (overlay-get o 'invisible))
7127 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7128 (overlay-end o))))
7129 (delete-overlay o))))
7131 (defun org-clean-visibility-after-subtree-move ()
7132 "Fix visibility issues after moving a subtree."
7133 ;; First, find a reasonable region to look at:
7134 ;; Start two siblings above, end three below
7135 (let* ((beg (save-excursion
7136 (and (org-get-last-sibling)
7137 (org-get-last-sibling))
7138 (point)))
7139 (end (save-excursion
7140 (and (org-get-next-sibling)
7141 (org-get-next-sibling)
7142 (org-get-next-sibling))
7143 (if (org-at-heading-p)
7144 (point-at-eol)
7145 (point))))
7146 (level (looking-at "\\*+"))
7147 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7148 (save-excursion
7149 (save-restriction
7150 (narrow-to-region beg end)
7151 (when re
7152 ;; Properly fold already folded siblings
7153 (goto-char (point-min))
7154 (while (re-search-forward re nil t)
7155 (when (and (not (outline-invisible-p))
7156 (save-excursion
7157 (goto-char (point-at-eol)) (outline-invisible-p)))
7158 (outline-hide-entry))))
7159 (org-cycle-show-empty-lines 'overview)
7160 (org-cycle-hide-drawers 'overview)))))
7162 (defun org-cycle-show-empty-lines (state)
7163 "Show empty lines above all visible headlines.
7164 The region to be covered depends on STATE when called through
7165 `org-cycle-hook'. Lisp program can use t for STATE to get the
7166 entire buffer covered. Note that an empty line is only shown if there
7167 are at least `org-cycle-separator-lines' empty lines before the headline."
7168 (when (/= org-cycle-separator-lines 0)
7169 (save-excursion
7170 (let* ((n (abs org-cycle-separator-lines))
7171 (re (cond
7172 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7173 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7174 (t (let ((ns (number-to-string (- n 2))))
7175 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7176 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7177 beg end)
7178 (cond
7179 ((memq state '(overview contents t))
7180 (setq beg (point-min) end (point-max)))
7181 ((memq state '(children folded))
7182 (setq beg (point)
7183 end (progn (org-end-of-subtree t t)
7184 (line-beginning-position 2)))))
7185 (when beg
7186 (goto-char beg)
7187 (while (re-search-forward re end t)
7188 (unless (get-char-property (match-end 1) 'invisible)
7189 (let ((e (match-end 1))
7190 (b (if (>= org-cycle-separator-lines 0)
7191 (match-beginning 1)
7192 (save-excursion
7193 (goto-char (match-beginning 0))
7194 (skip-chars-backward " \t\n")
7195 (line-end-position)))))
7196 (outline-flag-region b e nil))))))))
7197 ;; Never hide empty lines at the end of the file.
7198 (save-excursion
7199 (goto-char (point-max))
7200 (outline-previous-heading)
7201 (outline-end-of-heading)
7202 (when (and (looking-at "[ \t\n]+")
7203 (= (match-end 0) (point-max)))
7204 (outline-flag-region (point) (match-end 0) nil))))
7206 (defun org-show-empty-lines-in-parent ()
7207 "Move to the parent and re-show empty lines before visible headlines."
7208 (save-excursion
7209 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7210 (org-cycle-show-empty-lines context))))
7212 (defun org-files-list ()
7213 "Return `org-agenda-files' list, plus all open org-mode files.
7214 This is useful for operations that need to scan all of a user's
7215 open and agenda-wise Org files."
7216 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7217 (dolist (buf (buffer-list))
7218 (with-current-buffer buf
7219 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7220 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7221 files))
7223 (defsubst org-entry-beginning-position ()
7224 "Return the beginning position of the current entry."
7225 (save-excursion (org-back-to-heading t) (point)))
7227 (defsubst org-entry-end-position ()
7228 "Return the end position of the current entry."
7229 (save-excursion (outline-next-heading) (point)))
7231 (defun org-cycle-hide-drawers (state &optional exceptions)
7232 "Re-hide all drawers after a visibility state change.
7233 When non-nil, optional argument EXCEPTIONS is a list of strings
7234 specifying which drawers should not be hidden."
7235 (when (and (derived-mode-p 'org-mode)
7236 (not (memq state '(overview folded contents))))
7237 (save-excursion
7238 (let* ((globalp (memq state '(contents all)))
7239 (beg (if globalp (point-min) (point)))
7240 (end (if globalp (point-max)
7241 (if (eq state 'children)
7242 (save-excursion (outline-next-heading) (point))
7243 (org-end-of-subtree t)))))
7244 (goto-char beg)
7245 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7246 (unless (member-ignore-case (match-string 1) exceptions)
7247 (let ((drawer (org-element-at-point)))
7248 (when (memq (org-element-type drawer) '(drawer property-drawer))
7249 (org-flag-drawer t drawer)
7250 ;; Make sure to skip drawer entirely or we might flag
7251 ;; it another time when matching its ending line with
7252 ;; `org-drawer-regexp'.
7253 (goto-char (org-element-property :end drawer))))))))))
7255 (defun org-flag-drawer (flag &optional element)
7256 "When FLAG is non-nil, hide the drawer we are at.
7257 Otherwise make it visible. When optional argument ELEMENT is
7258 a parsed drawer, as returned by `org-element-at-point', hide or
7259 show that drawer instead."
7260 (let ((drawer (or element
7261 (and (save-excursion
7262 (beginning-of-line)
7263 (looking-at-p org-drawer-regexp))
7264 (org-element-at-point)))))
7265 (when (memq (org-element-type drawer) '(drawer property-drawer))
7266 (let ((post (org-element-property :post-affiliated drawer)))
7267 (save-excursion
7268 (outline-flag-region
7269 (progn (goto-char post) (line-end-position))
7270 (progn (goto-char (org-element-property :end drawer))
7271 (skip-chars-backward " \r\t\n")
7272 (line-end-position))
7273 flag))
7274 ;; When the drawer is hidden away, make sure point lies in
7275 ;; a visible part of the buffer.
7276 (when (and flag (> (line-beginning-position) post))
7277 (goto-char post))))))
7279 (defun org-subtree-end-visible-p ()
7280 "Is the end of the current subtree visible?"
7281 (pos-visible-in-window-p
7282 (save-excursion (org-end-of-subtree t) (point))))
7284 (defun org-first-headline-recenter ()
7285 "Move cursor to the first headline and recenter the headline."
7286 (let ((window (get-buffer-window)))
7287 (when window
7288 (goto-char (point-min))
7289 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7290 (set-window-start window (line-beginning-position))))))
7292 ;;; Saving and restoring visibility
7294 (defun org-outline-overlay-data (&optional use-markers)
7295 "Return a list of the locations of all outline overlays.
7296 These are overlays with the `invisible' property value `outline'.
7297 The return value is a list of cons cells, with start and stop
7298 positions for each overlay.
7299 If USE-MARKERS is set, return the positions as markers."
7300 (let (beg end)
7301 (save-excursion
7302 (save-restriction
7303 (widen)
7304 (delq nil
7305 (mapcar (lambda (o)
7306 (when (eq (overlay-get o 'invisible) 'outline)
7307 (setq beg (overlay-start o)
7308 end (overlay-end o))
7309 (and beg end (> end beg)
7310 (if use-markers
7311 (cons (copy-marker beg)
7312 (copy-marker end t))
7313 (cons beg end)))))
7314 (overlays-in (point-min) (point-max))))))))
7316 (defun org-set-outline-overlay-data (data)
7317 "Create visibility overlays for all positions in DATA.
7318 DATA should have been made by `org-outline-overlay-data'."
7319 (org-with-wide-buffer
7320 (outline-show-all)
7321 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7323 ;;; Folding of blocks
7325 (defvar-local org-hide-block-overlays nil
7326 "Overlays hiding blocks.")
7328 (defun org-block-map (function &optional start end)
7329 "Call FUNCTION at the head of all source blocks in the current buffer.
7330 Optional arguments START and END can be used to limit the range."
7331 (let ((start (or start (point-min)))
7332 (end (or end (point-max))))
7333 (save-excursion
7334 (goto-char start)
7335 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7336 (save-excursion
7337 (save-match-data
7338 (goto-char (match-beginning 0))
7339 (funcall function)))))))
7341 (defun org-hide-block-toggle-all ()
7342 "Toggle the visibility of all blocks in the current buffer."
7343 (org-block-map 'org-hide-block-toggle))
7345 (defun org-hide-block-all ()
7346 "Fold all blocks in the current buffer."
7347 (interactive)
7348 (org-show-block-all)
7349 (org-block-map 'org-hide-block-toggle-maybe))
7351 (defun org-show-block-all ()
7352 "Unfold all blocks in the current buffer."
7353 (interactive)
7354 (mapc #'delete-overlay org-hide-block-overlays)
7355 (setq org-hide-block-overlays nil))
7357 (defun org-hide-block-toggle-maybe ()
7358 "Toggle visibility of block at point.
7359 Unlike to `org-hide-block-toggle', this function does not throw
7360 an error. Return a non-nil value when toggling is successful."
7361 (interactive)
7362 (ignore-errors (org-hide-block-toggle)))
7364 (defun org-hide-block-toggle (&optional force)
7365 "Toggle the visibility of the current block.
7366 When optional argument FORCE is `off', make block visible. If it
7367 is non-nil, hide it unconditionally. Throw an error when not at
7368 a block. Return a non-nil value when toggling is successful."
7369 (interactive)
7370 (let ((element (org-element-at-point)))
7371 (unless (memq (org-element-type element)
7372 '(center-block comment-block dynamic-block example-block
7373 export-block quote-block special-block
7374 src-block verse-block))
7375 (user-error "Not at a block"))
7376 (let* ((start (save-excursion
7377 (goto-char (org-element-property :post-affiliated element))
7378 (line-end-position)))
7379 (end (save-excursion
7380 (goto-char (org-element-property :end element))
7381 (skip-chars-backward " \r\t\n")
7382 (line-end-position)))
7383 (overlays (overlays-at start)))
7384 (cond
7385 ;; Do nothing when not before or at the block opening line or
7386 ;; at the block closing line.
7387 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7388 ((and (not (eq force 'off))
7389 (not (memq t (mapcar
7390 (lambda (o)
7391 (eq (overlay-get o 'invisible) 'org-hide-block))
7392 overlays))))
7393 (let ((ov (make-overlay start end)))
7394 (overlay-put ov 'invisible 'org-hide-block)
7395 ;; Make the block accessible to `isearch'.
7396 (overlay-put
7397 ov 'isearch-open-invisible
7398 (lambda (ov)
7399 (when (memq ov org-hide-block-overlays)
7400 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7401 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7402 (delete-overlay ov))))
7403 (push ov org-hide-block-overlays)
7404 ;; When the block is hidden away, make sure point is left in
7405 ;; a visible part of the buffer.
7406 (when (> (line-beginning-position) start)
7407 (goto-char start)
7408 (beginning-of-line))
7409 ;; Signal successful toggling.
7411 ((or (not force) (eq force 'off))
7412 (dolist (ov overlays t)
7413 (when (memq ov org-hide-block-overlays)
7414 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7415 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7416 (delete-overlay ov))))))))
7418 ;; org-tab-after-check-for-cycling-hook
7419 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7420 ;; Remove overlays when changing major mode
7421 (add-hook 'org-mode-hook
7422 (lambda () (add-hook 'change-major-mode-hook
7423 'org-show-block-all 'append 'local)))
7425 ;;; Org-goto
7427 (defvar org-goto-window-configuration nil)
7428 (defvar org-goto-marker nil)
7429 (defvar org-goto-map)
7430 (defun org-goto-map ()
7431 "Set the keymap `org-goto'."
7432 (setq org-goto-map
7433 (let ((map (make-sparse-keymap)))
7434 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7435 mouse-drag-region universal-argument org-occur)))
7436 (dolist (cmd cmds)
7437 (substitute-key-definition cmd cmd map global-map)))
7438 (suppress-keymap map)
7439 (org-defkey map "\C-m" 'org-goto-ret)
7440 (org-defkey map [(return)] 'org-goto-ret)
7441 (org-defkey map [(left)] 'org-goto-left)
7442 (org-defkey map [(right)] 'org-goto-right)
7443 (org-defkey map [(control ?g)] 'org-goto-quit)
7444 (org-defkey map "\C-i" 'org-cycle)
7445 (org-defkey map [(tab)] 'org-cycle)
7446 (org-defkey map [(down)] 'outline-next-visible-heading)
7447 (org-defkey map [(up)] 'outline-previous-visible-heading)
7448 (if org-goto-auto-isearch
7449 (if (fboundp 'define-key-after)
7450 (define-key-after map [t] 'org-goto-local-auto-isearch)
7451 nil)
7452 (org-defkey map "q" 'org-goto-quit)
7453 (org-defkey map "n" 'outline-next-visible-heading)
7454 (org-defkey map "p" 'outline-previous-visible-heading)
7455 (org-defkey map "f" 'outline-forward-same-level)
7456 (org-defkey map "b" 'outline-backward-same-level)
7457 (org-defkey map "u" 'outline-up-heading))
7458 (org-defkey map "/" 'org-occur)
7459 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7460 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7461 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7462 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7463 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7464 map)))
7466 (defconst org-goto-help
7467 "Browse buffer copy, to find location or copy text.%s
7468 RET=jump to location C-g=quit and return to previous location
7469 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7471 (defvar org-goto-start-pos) ; dynamically scoped parameter
7473 (defun org-goto (&optional alternative-interface)
7474 "Look up a different location in the current file, keeping current visibility.
7476 When you want look-up or go to a different location in a
7477 document, the fastest way is often to fold the entire buffer and
7478 then dive into the tree. This method has the disadvantage, that
7479 the previous location will be folded, which may not be what you
7480 want.
7482 This command works around this by showing a copy of the current
7483 buffer in an indirect buffer, in overview mode. You can dive
7484 into the tree in that copy, use org-occur and incremental search
7485 to find a location. When pressing RET or `Q', the command
7486 returns to the original buffer in which the visibility is still
7487 unchanged. After RET it will also jump to the location selected
7488 in the indirect buffer and expose the headline hierarchy above.
7490 With a prefix argument, use the alternative interface: e.g., if
7491 `org-goto-interface' is `outline' use `outline-path-completion'."
7492 (interactive "P")
7493 (org-goto-map)
7494 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7495 (org-refile-use-outline-path t)
7496 (org-refile-target-verify-function nil)
7497 (interface
7498 (if (not alternative-interface)
7499 org-goto-interface
7500 (if (eq org-goto-interface 'outline)
7501 'outline-path-completion
7502 'outline)))
7503 (org-goto-start-pos (point))
7504 (selected-point
7505 (if (eq interface 'outline)
7506 (car (org-get-location (current-buffer) org-goto-help))
7507 (let ((pa (org-refile-get-location "Goto")))
7508 (org-refile-check-position pa)
7509 (nth 3 pa)))))
7510 (if selected-point
7511 (progn
7512 (org-mark-ring-push org-goto-start-pos)
7513 (goto-char selected-point)
7514 (when (or (outline-invisible-p) (org-invisible-p2))
7515 (org-show-context 'org-goto)))
7516 (message "Quit"))))
7518 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7519 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7520 (defvar org-goto-local-auto-isearch-map) ; defined below
7522 (defun org-get-location (_buf help)
7523 "Let the user select a location in current buffer.
7524 This function uses a recursive edit. It returns the selected position
7525 or nil."
7526 (org-no-popups
7527 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7528 (isearch-hide-immediately nil)
7529 (isearch-search-fun-function
7530 (lambda () 'org-goto-local-search-headings))
7531 (org-goto-selected-point org-goto-exit-command))
7532 (save-excursion
7533 (save-window-excursion
7534 (delete-other-windows)
7535 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7536 (org-pop-to-buffer-same-window
7537 (condition-case nil
7538 (make-indirect-buffer (current-buffer) "*org-goto*")
7539 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7540 (with-output-to-temp-buffer "*Org Help*"
7541 (princ (format help (if org-goto-auto-isearch
7542 " Just type for auto-isearch."
7543 " n/p/f/b/u to navigate, q to quit."))))
7544 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7545 (setq buffer-read-only nil)
7546 (let ((org-startup-truncated t)
7547 (org-startup-folded nil)
7548 (org-startup-align-all-tables nil))
7549 (org-mode)
7550 (org-overview))
7551 (setq buffer-read-only t)
7552 (if (and (boundp 'org-goto-start-pos)
7553 (integer-or-marker-p org-goto-start-pos))
7554 (progn (goto-char org-goto-start-pos)
7555 (when (outline-invisible-p)
7556 (org-show-set-visibility 'lineage)))
7557 (goto-char (point-min)))
7558 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7559 (message "Select location and press RET")
7560 (use-local-map org-goto-map)
7561 (recursive-edit)))
7562 (kill-buffer "*org-goto*")
7563 (cons org-goto-selected-point org-goto-exit-command))))
7565 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7566 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7567 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7568 (if (fboundp 'isearch-other-control-char)
7569 (progn
7570 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7571 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7572 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7573 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7574 (define-key org-goto-local-auto-isearch-map [return] nil))
7576 (defun org-goto-local-search-headings (string bound noerror)
7577 "Search and make sure that any matches are in headlines."
7578 (catch 'return
7579 (while (if isearch-forward
7580 (search-forward string bound noerror)
7581 (search-backward string bound noerror))
7582 (when (save-match-data
7583 (and (save-excursion
7584 (beginning-of-line)
7585 (looking-at org-complex-heading-regexp))
7586 (or (not (match-beginning 5))
7587 (< (point) (match-beginning 5)))))
7588 (throw 'return (point))))))
7590 (defun org-goto-local-auto-isearch ()
7591 "Start isearch."
7592 (interactive)
7593 (goto-char (point-min))
7594 (let ((keys (this-command-keys)))
7595 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7596 (isearch-mode t)
7597 (isearch-process-search-char (string-to-char keys)))))
7599 (defun org-goto-ret (&optional _arg)
7600 "Finish `org-goto' by going to the new location."
7601 (interactive "P")
7602 (setq org-goto-selected-point (point))
7603 (setq org-goto-exit-command 'return)
7604 (throw 'exit nil))
7606 (defun org-goto-left ()
7607 "Finish `org-goto' by going to the new location."
7608 (interactive)
7609 (if (org-at-heading-p)
7610 (progn
7611 (beginning-of-line 1)
7612 (setq org-goto-selected-point (point)
7613 org-goto-exit-command 'left)
7614 (throw 'exit nil))
7615 (user-error "Not on a heading")))
7617 (defun org-goto-right ()
7618 "Finish `org-goto' by going to the new location."
7619 (interactive)
7620 (if (org-at-heading-p)
7621 (progn
7622 (setq org-goto-selected-point (point)
7623 org-goto-exit-command 'right)
7624 (throw 'exit nil))
7625 (user-error "Not on a heading")))
7627 (defun org-goto-quit ()
7628 "Finish `org-goto' without cursor motion."
7629 (interactive)
7630 (setq org-goto-selected-point nil)
7631 (setq org-goto-exit-command 'quit)
7632 (throw 'exit nil))
7634 ;;; Indirect buffer display of subtrees
7636 (defvar org-indirect-dedicated-frame nil
7637 "This is the frame being used for indirect tree display.")
7638 (defvar org-last-indirect-buffer nil)
7640 (defun org-tree-to-indirect-buffer (&optional arg)
7641 "Create indirect buffer and narrow it to current subtree.
7642 With a numerical prefix ARG, go up to this level and then take that tree.
7643 If ARG is negative, go up that many levels.
7645 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7646 indirect buffer previously made with this command, to avoid proliferation of
7647 indirect buffers. However, when you call the command with a \
7648 \\[universal-argument] prefix, or
7649 when `org-indirect-buffer-display' is `new-frame', the last buffer
7650 is kept so that you can work with several indirect buffers at the same time.
7651 If `org-indirect-buffer-display' is `dedicated-frame', the \
7652 \\[universal-argument] prefix also
7653 requests that a new frame be made for the new buffer, so that the dedicated
7654 frame is not changed."
7655 (interactive "P")
7656 (let ((cbuf (current-buffer))
7657 (cwin (selected-window))
7658 (pos (point))
7659 beg end level heading ibuf)
7660 (save-excursion
7661 (org-back-to-heading t)
7662 (when (numberp arg)
7663 (setq level (org-outline-level))
7664 (when (< arg 0) (setq arg (+ level arg)))
7665 (while (> (setq level (org-outline-level)) arg)
7666 (org-up-heading-safe)))
7667 (setq beg (point)
7668 heading (org-get-heading 'no-tags))
7669 (org-end-of-subtree t t)
7670 (when (org-at-heading-p) (backward-char 1))
7671 (setq end (point)))
7672 (when (and (buffer-live-p org-last-indirect-buffer)
7673 (not (eq org-indirect-buffer-display 'new-frame))
7674 (not arg))
7675 (kill-buffer org-last-indirect-buffer))
7676 (setq ibuf (org-get-indirect-buffer cbuf heading)
7677 org-last-indirect-buffer ibuf)
7678 (cond
7679 ((or (eq org-indirect-buffer-display 'new-frame)
7680 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7681 (select-frame (make-frame))
7682 (delete-other-windows)
7683 (org-pop-to-buffer-same-window ibuf)
7684 (org-set-frame-title heading))
7685 ((eq org-indirect-buffer-display 'dedicated-frame)
7686 (raise-frame
7687 (select-frame (or (and org-indirect-dedicated-frame
7688 (frame-live-p org-indirect-dedicated-frame)
7689 org-indirect-dedicated-frame)
7690 (setq org-indirect-dedicated-frame (make-frame)))))
7691 (delete-other-windows)
7692 (org-pop-to-buffer-same-window ibuf)
7693 (org-set-frame-title (concat "Indirect: " heading)))
7694 ((eq org-indirect-buffer-display 'current-window)
7695 (org-pop-to-buffer-same-window ibuf))
7696 ((eq org-indirect-buffer-display 'other-window)
7697 (pop-to-buffer ibuf))
7698 (t (error "Invalid value")))
7699 (narrow-to-region beg end)
7700 (outline-show-all)
7701 (goto-char pos)
7702 (run-hook-with-args 'org-cycle-hook 'all)
7703 (and (window-live-p cwin) (select-window cwin))))
7705 (defun org-get-indirect-buffer (&optional buffer heading)
7706 (setq buffer (or buffer (current-buffer)))
7707 (let ((n 1) (base (buffer-name buffer)) bname)
7708 (while (buffer-live-p
7709 (get-buffer
7710 (setq bname
7711 (concat base "-"
7712 (if heading (concat heading "-" (number-to-string n))
7713 (number-to-string n))))))
7714 (setq n (1+ n)))
7715 (condition-case nil
7716 (make-indirect-buffer buffer bname 'clone)
7717 (error (make-indirect-buffer buffer bname)))))
7719 (defun org-set-frame-title (title)
7720 "Set the title of the current frame to the string TITLE."
7721 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7723 ;;;; Structure editing
7725 ;;; Inserting headlines
7727 (defun org--line-empty-p (n)
7728 "Is the Nth next line empty?
7730 Counts the current line as N = 1 and the previous line as N = 0;
7731 see `beginning-of-line'."
7732 (save-excursion
7733 (and (not (bobp))
7734 (or (beginning-of-line n) t)
7735 (save-match-data
7736 (looking-at "[ \t]*$")))))
7738 (defun org-previous-line-empty-p ()
7739 "Is the previous line a blank line?
7740 When NEXT is non-nil, check the next line instead."
7741 (org--line-empty-p 0))
7743 (defun org-next-line-empty-p ()
7744 "Is the previous line a blank line?
7745 When NEXT is non-nil, check the next line instead."
7746 (org--line-empty-p 2))
7748 (defun org-insert-heading (&optional arg invisible-ok top)
7749 "Insert a new heading or an item with the same depth at point.
7751 If point is at the beginning of a heading or a list item, insert
7752 a new heading or a new item above the current one. If point is
7753 at the beginning of a normal line, turn the line into a heading.
7755 If point is in the middle of a headline or a list item, split the
7756 headline or the item and create a new headline/item with the text
7757 in the current line after point \(see `org-M-RET-may-split-line'
7758 on how to modify this behavior).
7760 With one universal prefix argument, set the user option
7761 `org-insert-heading-respect-content' to t for the duration of
7762 the command. This modifies the behavior described above in this
7763 ways: on list items and at the beginning of normal lines, force
7764 the insertion of a heading after the current subtree.
7766 With two universal prefix arguments, insert the heading at the
7767 end of the grandparent subtree. For example, if point is within
7768 a 2nd-level heading, then it will insert a 2nd-level heading at
7769 the end of the 1st-level parent heading.
7771 If point is at the beginning of a headline, insert a sibling
7772 before the current headline. If point is not at the beginning,
7773 split the line and create a new headline with the text in the
7774 current line after point \(see `org-M-RET-may-split-line' on how
7775 to modify this behavior).
7777 If point is at the beginning of a normal line, turn this line
7778 into a heading.
7780 When INVISIBLE-OK is set, stop at invisible headlines when going
7781 back. This is important for non-interactive uses of the
7782 command.
7784 When optional argument TOP is non-nil, insert a level 1 heading,
7785 unconditionally."
7786 (interactive "P")
7787 (let ((itemp (and (not top) (org-in-item-p)))
7788 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7789 (respect-content (or org-insert-heading-respect-content
7790 (equal arg '(4))))
7791 (initial-content ""))
7793 (cond
7795 ((or (= (buffer-size) 0)
7796 (and (not (save-excursion
7797 (and (ignore-errors (org-back-to-heading invisible-ok))
7798 (org-at-heading-p))))
7799 (or arg (not itemp))))
7800 ;; At beginning of buffer or so high up that only a heading
7801 ;; makes sense.
7802 (cond ((and (bolp) (not respect-content)) (insert "* "))
7803 ((not respect-content)
7804 (unless may-split (end-of-line))
7805 (insert "\n* "))
7806 ((re-search-forward org-outline-regexp-bol nil t)
7807 (beginning-of-line)
7808 (insert "* \n")
7809 (backward-char))
7810 (t (goto-char (point-max))
7811 (insert "\n* ")))
7812 (run-hooks 'org-insert-heading-hook))
7814 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7817 ;; Maybe move at the end of the subtree
7818 (when (equal arg '(16))
7819 (org-up-heading-safe)
7820 (org-end-of-subtree t))
7821 ;; Insert a heading
7822 (save-restriction
7823 (widen)
7824 (let* ((level nil)
7825 (on-heading (org-at-heading-p))
7826 (empty-line-p (if on-heading
7827 (org-previous-line-empty-p)
7828 ;; We will decide later
7829 nil))
7830 ;; Get a level string to fall back on.
7831 (fix-level
7832 (if (org-before-first-heading-p) "*"
7833 (save-excursion
7834 (org-back-to-heading t)
7835 (when (org-previous-line-empty-p) (setq empty-line-p t))
7836 (looking-at org-outline-regexp)
7837 (make-string (1- (length (match-string 0))) ?*))))
7838 (stars
7839 (save-excursion
7840 (condition-case nil
7841 (if top "* "
7842 (org-back-to-heading invisible-ok)
7843 (when (and (not on-heading)
7844 (featurep 'org-inlinetask)
7845 (integerp org-inlinetask-min-level)
7846 (>= (length (match-string 0))
7847 org-inlinetask-min-level))
7848 ;; Find a heading level before the inline
7849 ;; task.
7850 (while (and (setq level (org-up-heading-safe))
7851 (>= level org-inlinetask-min-level)))
7852 (if (org-at-heading-p)
7853 (org-back-to-heading invisible-ok)
7854 (error "This should not happen")))
7855 (unless (and (save-excursion
7856 (save-match-data
7857 (org-backward-heading-same-level
7858 1 invisible-ok))
7859 (= (point) (match-beginning 0)))
7860 (not (org-next-line-empty-p)))
7861 (setq empty-line-p (or empty-line-p
7862 (org-previous-line-empty-p))))
7863 (match-string 0))
7864 (error (or fix-level "* ")))))
7865 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7866 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7868 ;; If we insert after content, move there and clean up
7869 ;; whitespace.
7870 (when (and respect-content
7871 (not (looking-at-p org-outline-regexp-bol)))
7872 (if (not (org-before-first-heading-p))
7873 (org-end-of-subtree nil t)
7874 (re-search-forward org-outline-regexp-bol)
7875 (beginning-of-line 0))
7876 (skip-chars-backward " \r\t\n")
7877 (and (not (looking-back "^\\*+" (line-beginning-position)))
7878 (looking-at "[ \t]+") (replace-match ""))
7879 (unless (eobp) (forward-char 1))
7880 (when (looking-at "^\\*")
7881 (unless (bobp) (backward-char 1))
7882 (insert "\n")))
7884 ;; If we are splitting, grab the text that should be moved
7885 ;; to the new headline.
7886 (when may-split
7887 (if (org-at-heading-p)
7888 ;; This is a heading: split intelligently (keeping
7889 ;; tags).
7890 (let ((pos (point)))
7891 (beginning-of-line)
7892 (unless (looking-at org-complex-heading-regexp)
7893 (error "This should not happen"))
7894 (when (and (match-beginning 4)
7895 (> pos (match-beginning 4))
7896 (< pos (match-end 4)))
7897 (setq initial-content (buffer-substring pos (match-end 4)))
7898 (goto-char pos)
7899 (delete-region (point) (match-end 4))
7900 (if (looking-at "[ \t]*$")
7901 (replace-match "")
7902 (insert (make-string (length initial-content) ?\s)))
7903 (setq initial-content (org-trim initial-content)))
7904 (goto-char pos))
7905 ;; A normal line.
7906 (setq initial-content
7907 (org-trim
7908 (delete-and-extract-region (point) (line-end-position))))))
7910 ;; If we are at the beginning of the line, insert before it.
7911 ;; Otherwise, after it.
7912 (cond
7913 ((and (bolp) (looking-at "[ \t]*$")))
7914 ((bolp) (save-excursion (insert "\n")))
7915 (t (end-of-line)
7916 (insert "\n")))
7918 ;; Insert the new heading
7919 (insert stars)
7920 (just-one-space)
7921 (insert initial-content)
7922 (unless (and blank (org-previous-line-empty-p))
7923 (org-N-empty-lines-before-current (if blank 1 0)))
7924 ;; Adjust visibility, which may be messed up if we removed
7925 ;; blank lines while previous entry was hidden.
7926 (let ((bol (line-beginning-position)))
7927 (dolist (o (overlays-at (1- bol)))
7928 (when (and (eq (overlay-get o 'invisible) 'outline)
7929 (eq (overlay-end o) bol))
7930 (move-overlay o (overlay-start o) (1- bol)))))
7931 (run-hooks 'org-insert-heading-hook)))))))
7933 (defun org-N-empty-lines-before-current (N)
7934 "Make the number of empty lines before current exactly N.
7935 So this will delete or add empty lines."
7936 (save-excursion
7937 (beginning-of-line)
7938 (let ((p (point)))
7939 (skip-chars-backward " \r\t\n")
7940 (unless (bolp) (forward-line))
7941 (delete-region (point) p))
7942 (when (> N 0) (insert (make-string N ?\n)))))
7944 (defun org-get-heading (&optional no-tags no-todo)
7945 "Return the heading of the current entry, without the stars.
7946 When NO-TAGS is non-nil, don't include tags.
7947 When NO-TODO is non-nil, don't include TODO keywords."
7948 (save-excursion
7949 (org-back-to-heading t)
7950 (let ((case-fold-search nil))
7951 (cond
7952 ((and no-tags no-todo)
7953 (looking-at org-complex-heading-regexp)
7954 (match-string 4))
7955 (no-tags
7956 (looking-at (concat org-outline-regexp
7957 "\\(.*?\\)"
7958 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7959 (match-string 1))
7960 (no-todo
7961 (looking-at org-todo-line-regexp)
7962 (match-string 3))
7963 (t (looking-at org-heading-regexp)
7964 (match-string 2))))))
7966 (defvar orgstruct-mode) ; defined below
7968 (defun org-heading-components ()
7969 "Return the components of the current heading.
7970 This is a list with the following elements:
7971 - the level as an integer
7972 - the reduced level, different if `org-odd-levels-only' is set.
7973 - the TODO keyword, or nil
7974 - the priority character, like ?A, or nil if no priority is given
7975 - the headline text itself, or the tags string if no headline text
7976 - the tags string, or nil."
7977 (save-excursion
7978 (org-back-to-heading t)
7979 (when (let (case-fold-search)
7980 (looking-at
7981 (if orgstruct-mode
7982 org-heading-regexp
7983 org-complex-heading-regexp)))
7984 (if orgstruct-mode
7985 (list (length (match-string 1))
7986 (org-reduced-level (length (match-string 1)))
7989 (match-string 2)
7990 nil)
7991 (list (length (match-string 1))
7992 (org-reduced-level (length (match-string 1)))
7993 (match-string-no-properties 2)
7994 (and (match-end 3) (aref (match-string 3) 2))
7995 (match-string-no-properties 4)
7996 (match-string-no-properties 5))))))
7998 (defun org-get-entry ()
7999 "Get the entry text, after heading, entire subtree."
8000 (save-excursion
8001 (org-back-to-heading t)
8002 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
8004 (defun org-edit-headline (&optional heading)
8005 "Edit the current headline.
8006 Set it to HEADING when provided."
8007 (interactive)
8008 (org-with-wide-buffer
8009 (org-back-to-heading t)
8010 (when (looking-at org-complex-heading-regexp)
8011 (let* ((old (match-string-no-properties 4))
8012 (new (save-match-data
8013 (org-trim (or heading (read-string "Edit: " old))))))
8014 (unless (equal old new)
8015 (if old (replace-match new t t nil 4)
8016 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8017 (insert " " new))
8018 (org-set-tags nil t)
8019 (when (looking-at "[ \t]*$") (replace-match "")))))))
8021 (defun org-insert-heading-after-current ()
8022 "Insert a new heading with same level as current, after current subtree."
8023 (interactive)
8024 (org-back-to-heading)
8025 (org-insert-heading)
8026 (org-move-subtree-down)
8027 (end-of-line 1))
8029 (defun org-insert-heading-respect-content (&optional invisible-ok)
8030 "Insert heading with `org-insert-heading-respect-content' set to t."
8031 (interactive)
8032 (org-insert-heading '(4) invisible-ok))
8034 (defun org-insert-todo-heading-respect-content (&optional force-state)
8035 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8036 (interactive)
8037 (org-insert-todo-heading force-state '(4)))
8039 (defun org-insert-todo-heading (arg &optional force-heading)
8040 "Insert a new heading with the same level and TODO state as current heading.
8041 If the heading has no TODO state, or if the state is DONE, use the first
8042 state (TODO by default). Also with one prefix arg, force first state. With
8043 two prefix args, force inserting at the end of the parent subtree."
8044 (interactive "P")
8045 (when (or force-heading (not (org-insert-item 'checkbox)))
8046 (org-insert-heading (or (and (equal arg '(16)) '(16))
8047 force-heading))
8048 (save-excursion
8049 (org-back-to-heading)
8050 (outline-previous-heading)
8051 (looking-at org-todo-line-regexp))
8052 (let*
8053 ((new-mark-x
8054 (if (or (equal arg '(4))
8055 (not (match-beginning 2))
8056 (member (match-string 2) org-done-keywords))
8057 (car org-todo-keywords-1)
8058 (match-string 2)))
8059 (new-mark
8061 (run-hook-with-args-until-success
8062 'org-todo-get-default-hook new-mark-x nil)
8063 new-mark-x)))
8064 (beginning-of-line 1)
8065 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8066 (if org-treat-insert-todo-heading-as-state-change
8067 (org-todo new-mark)
8068 (insert new-mark " "))))
8069 (when org-provide-todo-statistics
8070 (org-update-parent-todo-statistics))))
8072 (defun org-insert-subheading (arg)
8073 "Insert a new subheading and demote it.
8074 Works for outline headings and for plain lists alike."
8075 (interactive "P")
8076 (org-insert-heading arg)
8077 (cond
8078 ((org-at-heading-p) (org-do-demote))
8079 ((org-at-item-p) (org-indent-item))))
8081 (defun org-insert-todo-subheading (arg)
8082 "Insert a new subheading with TODO keyword or checkbox and demote it.
8083 Works for outline headings and for plain lists alike."
8084 (interactive "P")
8085 (org-insert-todo-heading arg)
8086 (cond
8087 ((org-at-heading-p) (org-do-demote))
8088 ((org-at-item-p) (org-indent-item))))
8090 ;;; Promotion and Demotion
8092 (defvar org-after-demote-entry-hook nil
8093 "Hook run after an entry has been demoted.
8094 The cursor will be at the beginning of the entry.
8095 When a subtree is being demoted, the hook will be called for each node.")
8097 (defvar org-after-promote-entry-hook nil
8098 "Hook run after an entry has been promoted.
8099 The cursor will be at the beginning of the entry.
8100 When a subtree is being promoted, the hook will be called for each node.")
8102 (defun org-promote-subtree ()
8103 "Promote the entire subtree.
8104 See also `org-promote'."
8105 (interactive)
8106 (save-excursion
8107 (org-with-limited-levels (org-map-tree 'org-promote)))
8108 (org-fix-position-after-promote))
8110 (defun org-demote-subtree ()
8111 "Demote the entire subtree.
8112 See `org-demote' and `org-promote'."
8113 (interactive)
8114 (save-excursion
8115 (org-with-limited-levels (org-map-tree 'org-demote)))
8116 (org-fix-position-after-promote))
8118 (defun org-do-promote ()
8119 "Promote the current heading higher up the tree.
8120 If the region is active in `transient-mark-mode', promote all
8121 headings in the region."
8122 (interactive)
8123 (save-excursion
8124 (if (org-region-active-p)
8125 (org-map-region 'org-promote (region-beginning) (region-end))
8126 (org-promote)))
8127 (org-fix-position-after-promote))
8129 (defun org-do-demote ()
8130 "Demote the current heading lower down the tree.
8131 If the region is active in `transient-mark-mode', demote all
8132 headings in the region."
8133 (interactive)
8134 (save-excursion
8135 (if (org-region-active-p)
8136 (org-map-region 'org-demote (region-beginning) (region-end))
8137 (org-demote)))
8138 (org-fix-position-after-promote))
8140 (defun org-fix-position-after-promote ()
8141 "Fix cursor position and indentation after demoting/promoting."
8142 (let ((pos (point)))
8143 (when (save-excursion
8144 (beginning-of-line 1)
8145 (looking-at org-todo-line-regexp)
8146 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8147 (cond ((eobp) (insert " "))
8148 ((eolp) (insert " "))
8149 ((equal (char-after) ?\ ) (forward-char 1))))))
8151 (defun org-current-level ()
8152 "Return the level of the current entry, or nil if before the first headline.
8153 The level is the number of stars at the beginning of the
8154 headline. Use `org-reduced-level' to remove the effect of
8155 `org-odd-levels'. Unlike to `org-outline-level', this function
8156 ignores inlinetasks."
8157 (let ((level (org-with-limited-levels (org-outline-level))))
8158 (and (> level 0) level)))
8160 (defun org-get-previous-line-level ()
8161 "Return the outline depth of the last headline before the current line.
8162 Returns 0 for the first headline in the buffer, and nil if before the
8163 first headline."
8164 (and (org-current-level)
8165 (or (and (/= (line-beginning-position) (point-min))
8166 (save-excursion (beginning-of-line 0) (org-current-level)))
8167 0)))
8169 (defun org-reduced-level (l)
8170 "Compute the effective level of a heading.
8171 This takes into account the setting of `org-odd-levels-only'."
8172 (cond
8173 ((zerop l) 0)
8174 (org-odd-levels-only (1+ (floor (/ l 2))))
8175 (t l)))
8177 (defun org-level-increment ()
8178 "Return the number of stars that will be added or removed at a
8179 time to headlines when structure editing, based on the value of
8180 `org-odd-levels-only'."
8181 (if org-odd-levels-only 2 1))
8183 (defun org-get-valid-level (level &optional change)
8184 "Rectify a level change under the influence of `org-odd-levels-only'
8185 LEVEL is a current level, CHANGE is by how much the level should be
8186 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8187 even level numbers will become the next higher odd number."
8188 (if org-odd-levels-only
8189 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8190 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8191 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8192 (max 1 (+ level (or change 0)))))
8193 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8195 (defun org-promote ()
8196 "Promote the current heading higher up the tree."
8197 (org-with-wide-buffer
8198 (org-back-to-heading t)
8199 (let* ((after-change-functions (remq 'flyspell-after-change-function
8200 after-change-functions))
8201 (level (save-match-data (funcall outline-level)))
8202 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8203 (diff (abs (- level (length up-head) -1))))
8204 (cond
8205 ((and (= level 1) org-allow-promoting-top-level-subtree)
8206 (replace-match "# " nil t))
8207 ((= level 1)
8208 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8209 (t (replace-match up-head nil t)))
8210 (unless (= level 1)
8211 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8212 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8213 (run-hooks 'org-after-promote-entry-hook))))
8215 (defun org-demote ()
8216 "Demote the current heading lower down the tree."
8217 (org-with-wide-buffer
8218 (org-back-to-heading t)
8219 (let* ((after-change-functions (remq 'flyspell-after-change-function
8220 after-change-functions))
8221 (level (save-match-data (funcall outline-level)))
8222 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8223 (diff (abs (- level (length down-head) -1))))
8224 (replace-match down-head nil t)
8225 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8226 (when org-adapt-indentation (org-fixup-indentation diff))
8227 (run-hooks 'org-after-demote-entry-hook))))
8229 (defun org-cycle-level ()
8230 "Cycle the level of an empty headline through possible states.
8231 This goes first to child, then to parent, level, then up the hierarchy.
8232 After top level, it switches back to sibling level."
8233 (interactive)
8234 (let ((org-adapt-indentation nil))
8235 (when (org-point-at-end-of-empty-headline)
8236 (setq this-command 'org-cycle-level) ; Only needed for caching
8237 (let ((cur-level (org-current-level))
8238 (prev-level (org-get-previous-line-level)))
8239 (cond
8240 ;; If first headline in file, promote to top-level.
8241 ((= prev-level 0)
8242 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8243 do (org-do-promote)))
8244 ;; If same level as prev, demote one.
8245 ((= prev-level cur-level)
8246 (org-do-demote))
8247 ;; If parent is top-level, promote to top level if not already.
8248 ((= prev-level 1)
8249 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8250 do (org-do-promote)))
8251 ;; If top-level, return to prev-level.
8252 ((= cur-level 1)
8253 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8254 do (org-do-demote)))
8255 ;; If less than prev-level, promote one.
8256 ((< cur-level prev-level)
8257 (org-do-promote))
8258 ;; If deeper than prev-level, promote until higher than
8259 ;; prev-level.
8260 ((> cur-level prev-level)
8261 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8262 do (org-do-promote))))
8263 t))))
8265 (defun org-map-tree (fun)
8266 "Call FUN for every heading underneath the current one."
8267 (org-back-to-heading)
8268 (let ((level (funcall outline-level)))
8269 (save-excursion
8270 (funcall fun)
8271 (while (and (progn
8272 (outline-next-heading)
8273 (> (funcall outline-level) level))
8274 (not (eobp)))
8275 (funcall fun)))))
8277 (defun org-map-region (fun beg end)
8278 "Call FUN for every heading between BEG and END."
8279 (let ((org-ignore-region t))
8280 (save-excursion
8281 (setq end (copy-marker end))
8282 (goto-char beg)
8283 (when (and (re-search-forward org-outline-regexp-bol nil t)
8284 (< (point) end))
8285 (funcall fun))
8286 (while (and (progn
8287 (outline-next-heading)
8288 (< (point) end))
8289 (not (eobp)))
8290 (funcall fun)))))
8292 (defun org-fixup-indentation (diff)
8293 "Change the indentation in the current entry by DIFF.
8295 DIFF is an integer. Indentation is done according to the
8296 following rules:
8298 - Planning information and property drawers are always indented
8299 according to the new level of the headline;
8301 - Footnote definitions and their contents are ignored;
8303 - Inlinetasks' boundaries are not shifted;
8305 - Empty lines are ignored;
8307 - Other lines' indentation are shifted by DIFF columns, unless
8308 it would introduce a structural change in the document, in
8309 which case no shifting is done at all.
8311 Assume point is at a heading or an inlinetask beginning."
8312 (org-with-wide-buffer
8313 (narrow-to-region (line-beginning-position)
8314 (save-excursion
8315 (if (org-with-limited-levels (org-at-heading-p))
8316 (org-with-limited-levels (outline-next-heading))
8317 (org-inlinetask-goto-end))
8318 (point)))
8319 (forward-line)
8320 ;; Indent properly planning info and property drawer.
8321 (when (looking-at-p org-planning-line-re)
8322 (org-indent-line)
8323 (forward-line))
8324 (when (looking-at org-property-drawer-re)
8325 (goto-char (match-end 0))
8326 (forward-line)
8327 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8328 (catch 'no-shift
8329 (when (zerop diff) (throw 'no-shift nil))
8330 ;; If DIFF is negative, first check if a shift is possible at all
8331 ;; (e.g., it doesn't break structure). This can only happen if
8332 ;; some contents are not properly indented.
8333 (let ((case-fold-search t))
8334 (when (< diff 0)
8335 (let ((diff (- diff))
8336 (forbidden-re (concat org-outline-regexp
8337 "\\|"
8338 (substring org-footnote-definition-re 1))))
8339 (save-excursion
8340 (while (not (eobp))
8341 (cond
8342 ((looking-at-p "[ \t]*$") (forward-line))
8343 ((and (looking-at-p org-footnote-definition-re)
8344 (let ((e (org-element-at-point)))
8345 (and (eq (org-element-type e) 'footnote-definition)
8346 (goto-char (org-element-property :end e))))))
8347 ((looking-at-p org-outline-regexp) (forward-line))
8348 ;; Give up if shifting would move before column 0 or
8349 ;; if it would introduce a headline or a footnote
8350 ;; definition.
8352 (skip-chars-forward " \t")
8353 (let ((ind (current-column)))
8354 (when (or (< ind diff)
8355 (and (= ind diff) (looking-at-p forbidden-re)))
8356 (throw 'no-shift nil)))
8357 ;; Ignore contents of example blocks and source
8358 ;; blocks if their indentation is meant to be
8359 ;; preserved. Jump to block's closing line.
8360 (beginning-of-line)
8361 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8362 (let ((e (org-element-at-point)))
8363 (and (memq (org-element-type e)
8364 '(example-block src-block))
8365 (or org-src-preserve-indentation
8366 (org-element-property :preserve-indent e))
8367 (goto-char (org-element-property :end e))
8368 (progn (skip-chars-backward " \r\t\n")
8369 (beginning-of-line)
8370 t))))
8371 (forward-line))))))))
8372 ;; Shift lines but footnote definitions, inlinetasks boundaries
8373 ;; by DIFF. Also skip contents of source or example blocks
8374 ;; when indentation is meant to be preserved.
8375 (while (not (eobp))
8376 (cond
8377 ((and (looking-at-p org-footnote-definition-re)
8378 (let ((e (org-element-at-point)))
8379 (and (eq (org-element-type e) 'footnote-definition)
8380 (goto-char (org-element-property :end e))))))
8381 ((looking-at-p org-outline-regexp) (forward-line))
8382 ((looking-at-p "[ \t]*$") (forward-line))
8384 (indent-line-to (+ (org-get-indentation) diff))
8385 (beginning-of-line)
8386 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8387 (let ((e (org-element-at-point)))
8388 (and (memq (org-element-type e)
8389 '(example-block src-block))
8390 (or org-src-preserve-indentation
8391 (org-element-property :preserve-indent e))
8392 (goto-char (org-element-property :end e))
8393 (progn (skip-chars-backward " \r\t\n")
8394 (beginning-of-line)
8395 t))))
8396 (forward-line)))))))))
8398 (defun org-convert-to-odd-levels ()
8399 "Convert an org-mode file with all levels allowed to one with odd levels.
8400 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8401 level 5 etc."
8402 (interactive)
8403 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8404 (let ((outline-level 'org-outline-level)
8405 (org-odd-levels-only nil) n)
8406 (save-excursion
8407 (goto-char (point-min))
8408 (while (re-search-forward "^\\*\\*+ " nil t)
8409 (setq n (- (length (match-string 0)) 2))
8410 (while (>= (setq n (1- n)) 0)
8411 (org-demote))
8412 (end-of-line 1))))))
8414 (defun org-convert-to-oddeven-levels ()
8415 "Convert an org-mode file with only odd levels to one with odd/even levels.
8416 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8417 file contains a section with an even level, conversion would
8418 destroy the structure of the file. An error is signaled in this
8419 case."
8420 (interactive)
8421 (goto-char (point-min))
8422 ;; First check if there are no even levels
8423 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8424 (org-show-set-visibility 'canonical)
8425 (error "Not all levels are odd in this file. Conversion not possible"))
8426 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8427 (let ((outline-regexp org-outline-regexp)
8428 (outline-level 'org-outline-level)
8429 (org-odd-levels-only nil) n)
8430 (save-excursion
8431 (goto-char (point-min))
8432 (while (re-search-forward "^\\*\\*+ " nil t)
8433 (setq n (/ (1- (length (match-string 0))) 2))
8434 (while (>= (setq n (1- n)) 0)
8435 (org-promote))
8436 (end-of-line 1))))))
8438 (defun org-tr-level (n)
8439 "Make N odd if required."
8440 (if org-odd-levels-only (1+ (/ n 2)) n))
8442 ;;; Vertical tree motion, cutting and pasting of subtrees
8444 (defun org-move-subtree-up (&optional arg)
8445 "Move the current subtree up past ARG headlines of the same level."
8446 (interactive "p")
8447 (org-move-subtree-down (- (prefix-numeric-value arg))))
8449 (defun org-move-subtree-down (&optional arg)
8450 "Move the current subtree down past ARG headlines of the same level."
8451 (interactive "p")
8452 (setq arg (prefix-numeric-value arg))
8453 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8454 'org-get-last-sibling))
8455 (ins-point (make-marker))
8456 (cnt (abs arg))
8457 (col (current-column))
8458 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8459 ;; Select the tree
8460 (org-back-to-heading)
8461 (setq beg0 (point))
8462 (save-excursion
8463 (setq ne-beg (org-back-over-empty-lines))
8464 (setq beg (point)))
8465 (save-match-data
8466 (save-excursion (outline-end-of-heading)
8467 (setq folded (outline-invisible-p)))
8468 (progn (org-end-of-subtree nil t)
8469 (unless (eobp) (backward-char))))
8470 (outline-next-heading)
8471 (setq ne-end (org-back-over-empty-lines))
8472 (setq end (point))
8473 (goto-char beg0)
8474 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8475 ;; include less whitespace
8476 (save-excursion
8477 (goto-char beg)
8478 (forward-line (- ne-beg ne-end))
8479 (setq beg (point))))
8480 ;; Find insertion point, with error handling
8481 (while (> cnt 0)
8482 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8483 (progn (goto-char beg0)
8484 (user-error "Cannot move past superior level or buffer limit")))
8485 (setq cnt (1- cnt)))
8486 (when (> arg 0)
8487 ;; Moving forward - still need to move over subtree
8488 (org-end-of-subtree t t)
8489 (save-excursion
8490 (org-back-over-empty-lines)
8491 (or (bolp) (newline))))
8492 (setq ne-ins (org-back-over-empty-lines))
8493 (move-marker ins-point (point))
8494 (setq txt (buffer-substring beg end))
8495 (org-save-markers-in-region beg end)
8496 (delete-region beg end)
8497 (org-remove-empty-overlays-at beg)
8498 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8499 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8500 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8501 (let ((bbb (point)))
8502 (insert-before-markers txt)
8503 (org-reinstall-markers-in-region bbb)
8504 (move-marker ins-point bbb))
8505 (or (bolp) (insert "\n"))
8506 (setq ins-end (point))
8507 (goto-char ins-point)
8508 (org-skip-whitespace)
8509 (when (and (< arg 0)
8510 (org-first-sibling-p)
8511 (> ne-ins ne-beg))
8512 ;; Move whitespace back to beginning
8513 (save-excursion
8514 (goto-char ins-end)
8515 (let ((kill-whole-line t))
8516 (kill-line (- ne-ins ne-beg)) (point)))
8517 (insert (make-string (- ne-ins ne-beg) ?\n)))
8518 (move-marker ins-point nil)
8519 (if folded
8520 (outline-hide-subtree)
8521 (org-show-entry)
8522 (org-show-children)
8523 (org-cycle-hide-drawers 'children))
8524 (org-clean-visibility-after-subtree-move)
8525 ;; move back to the initial column we were at
8526 (move-to-column col)))
8528 (defvar org-subtree-clip ""
8529 "Clipboard for cut and paste of subtrees.
8530 This is actually only a copy of the kill, because we use the normal kill
8531 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8533 (defvar org-subtree-clip-folded nil
8534 "Was the last copied subtree folded?
8535 This is used to fold the tree back after pasting.")
8537 (defun org-cut-subtree (&optional n)
8538 "Cut the current subtree into the clipboard.
8539 With prefix arg N, cut this many sequential subtrees.
8540 This is a short-hand for marking the subtree and then cutting it."
8541 (interactive "p")
8542 (org-copy-subtree n 'cut))
8544 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8545 "Copy the current subtree it in the clipboard.
8546 With prefix arg N, copy this many sequential subtrees.
8547 This is a short-hand for marking the subtree and then copying it.
8548 If CUT is non-nil, actually cut the subtree.
8549 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8550 of some markers in the region, even if CUT is non-nil. This is
8551 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8552 (interactive "p")
8553 (let (beg end folded (beg0 (point)))
8554 (if (org-called-interactively-p 'any)
8555 (org-back-to-heading nil) ; take what looks like a subtree
8556 (org-back-to-heading t)) ; take what is really there
8557 (setq beg (point))
8558 (skip-chars-forward " \t\r\n")
8559 (save-match-data
8560 (if nosubtrees
8561 (outline-next-heading)
8562 (save-excursion (outline-end-of-heading)
8563 (setq folded (outline-invisible-p)))
8564 (ignore-errors (org-forward-heading-same-level (1- n) t))
8565 (org-end-of-subtree t t)))
8566 ;; Include the end of an inlinetask
8567 (when (and (featurep 'org-inlinetask)
8568 (looking-at-p (concat (org-inlinetask-outline-regexp)
8569 "END[ \t]*$")))
8570 (end-of-line))
8571 (setq end (point))
8572 (goto-char beg0)
8573 (when (> end beg)
8574 (setq org-subtree-clip-folded folded)
8575 (when (or cut force-store-markers)
8576 (org-save-markers-in-region beg end))
8577 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8578 (setq org-subtree-clip (current-kill 0))
8579 (message "%s: Subtree(s) with %d characters"
8580 (if cut "Cut" "Copied")
8581 (length org-subtree-clip)))))
8583 (defun org-paste-subtree (&optional level tree for-yank remove)
8584 "Paste the clipboard as a subtree, with modification of headline level.
8585 The entire subtree is promoted or demoted in order to match a new headline
8586 level.
8588 If the cursor is at the beginning of a headline, the same level as
8589 that headline is used to paste the tree.
8591 If not, the new level is derived from the *visible* headings
8592 before and after the insertion point, and taken to be the inferior headline
8593 level of the two. So if the previous visible heading is level 3 and the
8594 next is level 4 (or vice versa), level 4 will be used for insertion.
8595 This makes sure that the subtree remains an independent subtree and does
8596 not swallow low level entries.
8598 You can also force a different level, either by using a numeric prefix
8599 argument, or by inserting the heading marker by hand. For example, if the
8600 cursor is after \"*****\", then the tree will be shifted to level 5.
8602 If optional TREE is given, use this text instead of the kill ring.
8604 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8605 move back over whitespace before inserting, and move point to the end of
8606 the inserted text when done.
8608 When REMOVE is non-nil, remove the subtree from the clipboard."
8609 (interactive "P")
8610 (setq tree (or tree (and kill-ring (current-kill 0))))
8611 (unless (org-kill-is-subtree-p tree)
8612 (user-error "%s"
8613 (substitute-command-keys
8614 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8615 (org-with-limited-levels
8616 (let* ((visp (not (outline-invisible-p)))
8617 (txt tree)
8618 (^re_ "\\(\\*+\\)[ \t]*")
8619 (old-level (if (string-match org-outline-regexp-bol txt)
8620 (- (match-end 0) (match-beginning 0) 1)
8621 -1))
8622 (force-level (cond (level (prefix-numeric-value level))
8623 ((and (looking-at "[ \t]*$")
8624 (string-match
8625 "^\\*+$" (buffer-substring
8626 (point-at-bol) (point))))
8627 (- (match-end 0) (match-beginning 0)))
8628 ((and (bolp)
8629 (looking-at org-outline-regexp))
8630 (- (match-end 0) (point) 1))))
8631 (previous-level (save-excursion
8632 (condition-case nil
8633 (progn
8634 (outline-previous-visible-heading 1)
8635 (if (looking-at ^re_)
8636 (- (match-end 0) (match-beginning 0) 1)
8638 (error 1))))
8639 (next-level (save-excursion
8640 (condition-case nil
8641 (progn
8642 (or (looking-at org-outline-regexp)
8643 (outline-next-visible-heading 1))
8644 (if (looking-at ^re_)
8645 (- (match-end 0) (match-beginning 0) 1)
8647 (error 1))))
8648 (new-level (or force-level (max previous-level next-level)))
8649 (shift (if (or (= old-level -1)
8650 (= new-level -1)
8651 (= old-level new-level))
8653 (- new-level old-level)))
8654 (delta (if (> shift 0) -1 1))
8655 (func (if (> shift 0) 'org-demote 'org-promote))
8656 (org-odd-levels-only nil)
8657 beg end newend)
8658 ;; Remove the forced level indicator
8659 (when force-level
8660 (delete-region (point-at-bol) (point)))
8661 ;; Paste
8662 (beginning-of-line (if (bolp) 1 2))
8663 (setq beg (point))
8664 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8665 (insert-before-markers txt)
8666 (unless (string-match "\n\\'" txt) (insert "\n"))
8667 (setq newend (point))
8668 (org-reinstall-markers-in-region beg)
8669 (setq end (point))
8670 (goto-char beg)
8671 (skip-chars-forward " \t\n\r")
8672 (setq beg (point))
8673 (when (and (outline-invisible-p) visp)
8674 (save-excursion (outline-show-heading)))
8675 ;; Shift if necessary
8676 (unless (= shift 0)
8677 (save-restriction
8678 (narrow-to-region beg end)
8679 (while (not (= shift 0))
8680 (org-map-region func (point-min) (point-max))
8681 (setq shift (+ delta shift)))
8682 (goto-char (point-min))
8683 (setq newend (point-max))))
8684 (when (or (org-called-interactively-p 'interactive) for-yank)
8685 (message "Clipboard pasted as level %d subtree" new-level))
8686 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8687 kill-ring
8688 (eq org-subtree-clip (current-kill 0))
8689 org-subtree-clip-folded)
8690 ;; The tree was folded before it was killed/copied
8691 (outline-hide-subtree))
8692 (and for-yank (goto-char newend))
8693 (and remove (setq kill-ring (cdr kill-ring))))))
8695 (defun org-kill-is-subtree-p (&optional txt)
8696 "Check if the current kill is an outline subtree, or a set of trees.
8697 Returns nil if kill does not start with a headline, or if the first
8698 headline level is not the largest headline level in the tree.
8699 So this will actually accept several entries of equal levels as well,
8700 which is OK for `org-paste-subtree'.
8701 If optional TXT is given, check this string instead of the current kill."
8702 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8703 (re (org-get-limited-outline-regexp))
8704 (^re (concat "^" re))
8705 (start-level (and kill
8706 (string-match
8707 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8708 kill)
8709 (- (match-end 2) (match-beginning 2) 1)))
8710 (start (1+ (or (match-beginning 2) -1))))
8711 (if (not start-level)
8712 (progn
8713 nil) ;; does not even start with a heading
8714 (catch 'exit
8715 (while (setq start (string-match ^re kill (1+ start)))
8716 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8717 (throw 'exit nil)))
8718 t))))
8720 (defvar org-markers-to-move nil
8721 "Markers that should be moved with a cut-and-paste operation.
8722 Those markers are stored together with their positions relative to
8723 the start of the region.")
8725 (defun org-save-markers-in-region (beg end)
8726 "Check markers in region.
8727 If these markers are between BEG and END, record their position relative
8728 to BEG, so that after moving the block of text, we can put the markers back
8729 into place.
8730 This function gets called just before an entry or tree gets cut from the
8731 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8732 called immediately, to move the markers with the entries."
8733 (setq org-markers-to-move nil)
8734 (when (featurep 'org-clock)
8735 (org-clock-save-markers-for-cut-and-paste beg end))
8736 (when (featurep 'org-agenda)
8737 (org-agenda-save-markers-for-cut-and-paste beg end)))
8739 (defun org-check-and-save-marker (marker beg end)
8740 "Check if MARKER is between BEG and END.
8741 If yes, remember the marker and the distance to BEG."
8742 (when (and (marker-buffer marker)
8743 (equal (marker-buffer marker) (current-buffer))
8744 (>= marker beg) (< marker end))
8745 (push (cons marker (- marker beg)) org-markers-to-move)))
8747 (defun org-reinstall-markers-in-region (beg)
8748 "Move all remembered markers to their position relative to BEG."
8749 (dolist (x org-markers-to-move)
8750 (move-marker (car x) (+ beg (cdr x))))
8751 (setq org-markers-to-move nil))
8753 (defun org-narrow-to-subtree ()
8754 "Narrow buffer to the current subtree."
8755 (interactive)
8756 (save-excursion
8757 (save-match-data
8758 (org-with-limited-levels
8759 (narrow-to-region
8760 (progn (org-back-to-heading t) (point))
8761 (progn (org-end-of-subtree t t)
8762 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8763 (point)))))))
8765 (defun org-narrow-to-block ()
8766 "Narrow buffer to the current block."
8767 (interactive)
8768 (let* ((case-fold-search t)
8769 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8770 "^[ \t]*#\\+end_.*")))
8771 (if blockp
8772 (narrow-to-region (car blockp) (cdr blockp))
8773 (user-error "Not in a block"))))
8775 (defun org-clone-subtree-with-time-shift (n &optional shift)
8776 "Clone the task (subtree) at point N times.
8777 The clones will be inserted as siblings.
8779 In interactive use, the user will be prompted for the number of
8780 clones to be produced. If the entry has a timestamp, the user
8781 will also be prompted for a time shift, which may be a repeater
8782 as used in time stamps, for example `+3d'. To disable this,
8783 you can call the function with a universal prefix argument.
8785 When a valid repeater is given and the entry contains any time
8786 stamps, the clones will become a sequence in time, with time
8787 stamps in the subtree shifted for each clone produced. If SHIFT
8788 is nil or the empty string, time stamps will be left alone. The
8789 ID property of the original subtree is removed.
8791 If the original subtree did contain time stamps with a repeater,
8792 the following will happen:
8793 - the repeater will be removed in each clone
8794 - an additional clone will be produced, with the current, unshifted
8795 date(s) in the entry.
8796 - the original entry will be placed *after* all the clones, with
8797 repeater intact.
8798 - the start days in the repeater in the original entry will be shifted
8799 to past the last clone.
8800 In this way you can spell out a number of instances of a repeating task,
8801 and still retain the repeater to cover future instances of the task.
8803 As described above, N+1 clones are produced when the original
8804 subtree has a repeater. Setting N to 0, then, can be used to
8805 remove the repeater from a subtree and create a shifted clone
8806 with the original repeater."
8807 (interactive "nNumber of clones to produce: ")
8808 (let ((shift
8809 (or shift
8810 (if (and (not (equal current-prefix-arg '(4)))
8811 (save-excursion
8812 (re-search-forward org-ts-regexp-both
8813 (save-excursion
8814 (org-end-of-subtree t)
8815 (point)) t)))
8816 (read-from-minibuffer
8817 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8818 ""))) ;; No time shift
8819 (n-no-remove -1)
8820 (drawer-re org-drawer-regexp)
8821 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8822 beg end template task idprop
8823 shift-n shift-what doshift nmin nmax)
8824 (unless (wholenump n)
8825 (user-error "Invalid number of replications %s" n))
8826 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8827 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8828 shift)))
8829 (user-error "Invalid shift specification %s" shift))
8830 (when doshift
8831 (setq shift-n (string-to-number (match-string 1 shift))
8832 shift-what (cdr (assoc (match-string 2 shift)
8833 '(("d" . day) ("w" . week)
8834 ("m" . month) ("y" . year))))))
8835 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8836 (setq nmin 1 nmax n)
8837 (org-back-to-heading t)
8838 (setq beg (point))
8839 (setq idprop (org-entry-get nil "ID"))
8840 (org-end-of-subtree t t)
8841 (or (bolp) (insert "\n"))
8842 (setq end (point))
8843 (setq template (buffer-substring beg end))
8844 (when (and doshift
8845 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8846 (delete-region beg end)
8847 (setq end beg)
8848 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8849 (goto-char end)
8850 (cl-loop for n from nmin to nmax do
8851 ;; prepare clone
8852 (with-temp-buffer
8853 (insert template)
8854 (org-mode)
8855 (goto-char (point-min))
8856 (org-show-subtree)
8857 (and idprop (if org-clone-delete-id
8858 (org-entry-delete nil "ID")
8859 (org-id-get-create t)))
8860 (unless (= n 0)
8861 (while (re-search-forward org-clock-re nil t)
8862 (kill-whole-line))
8863 (goto-char (point-min))
8864 (while (re-search-forward drawer-re nil t)
8865 (org-remove-empty-drawer-at (point))))
8866 (goto-char (point-min))
8867 (when doshift
8868 (while (re-search-forward org-ts-regexp-both nil t)
8869 (org-timestamp-change (* n shift-n) shift-what))
8870 (unless (= n n-no-remove)
8871 (goto-char (point-min))
8872 (while (re-search-forward org-ts-regexp nil t)
8873 (save-excursion
8874 (goto-char (match-beginning 0))
8875 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8876 (delete-region (match-beginning 1) (match-end 1)))))))
8877 (setq task (buffer-string)))
8878 (insert task))
8879 (goto-char beg)))
8881 ;;; Outline Sorting
8883 (defun org-sort (with-case)
8884 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8885 Optional argument WITH-CASE means sort case-sensitively."
8886 (interactive "P")
8887 (cond
8888 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8889 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8891 (org-call-with-arg 'org-sort-entries with-case))))
8893 (defun org-sort-remove-invisible (s)
8894 "Remove invisible links from string S."
8895 (remove-text-properties 0 (length s) org-rm-props s)
8896 (while (string-match org-bracket-link-regexp s)
8897 (setq s (replace-match (if (match-end 2)
8898 (match-string 3 s)
8899 (match-string 1 s))
8900 t t s)))
8901 (let ((st (format " %s " s)))
8902 (while (string-match org-emph-re st)
8903 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8904 (setq s (substring st 1 -1)))
8907 (defvar org-priority-regexp) ; defined later in the file
8909 (defvar org-after-sorting-entries-or-items-hook nil
8910 "Hook that is run after a bunch of entries or items have been sorted.
8911 When children are sorted, the cursor is in the parent line when this
8912 hook gets called. When a region or a plain list is sorted, the cursor
8913 will be in the first entry of the sorted region/list.")
8915 (defun org-sort-entries
8916 (&optional with-case sorting-type getkey-func compare-func property)
8917 "Sort entries on a certain level of an outline tree.
8918 If there is an active region, the entries in the region are sorted.
8919 Else, if the cursor is before the first entry, sort the top-level items.
8920 Else, the children of the entry at point are sorted.
8922 Sorting can be alphabetically, numerically, by date/time as given by
8923 a time stamp, by a property, by priority order, or by a custom function.
8925 The command prompts for the sorting type unless it has been given to the
8926 function through the SORTING-TYPE argument, which needs to be a character,
8927 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8928 the precise meaning of each character:
8930 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8931 c By creation time, which is assumed to be the first inactive time stamp
8932 at the beginning of a line.
8933 d By deadline date/time.
8934 k By clocking time.
8935 n Numerically, by converting the beginning of the entry/item to a number.
8936 o By order of TODO keywords.
8937 p By priority according to the cookie.
8938 r By the value of a property.
8939 s By scheduled date/time.
8940 t By date/time, either the first active time stamp in the entry, or, if
8941 none exist, by the first inactive one.
8943 Capital letters will reverse the sort order.
8945 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8946 called with point at the beginning of the record. It must return either
8947 a string or a number that should serve as the sorting key for that record.
8949 Comparing entries ignores case by default. However, with an optional argument
8950 WITH-CASE, the sorting considers case as well.
8952 Sorting is done against the visible part of the headlines, it ignores hidden
8953 links.
8955 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8956 (interactive "P")
8957 (let ((case-func (if with-case 'identity 'downcase))
8958 (cmstr
8959 ;; The clock marker is lost when using `sort-subr', let's
8960 ;; store the clocking string.
8961 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8962 (save-excursion
8963 (goto-char org-clock-marker)
8964 (buffer-substring-no-properties (line-beginning-position)
8965 (point)))))
8966 start beg end stars re re2
8967 txt what tmp)
8968 ;; Find beginning and end of region to sort
8969 (cond
8970 ((org-region-active-p)
8971 ;; we will sort the region
8972 (setq end (region-end)
8973 what "region")
8974 (goto-char (region-beginning))
8975 (unless (org-at-heading-p) (outline-next-heading))
8976 (setq start (point)))
8977 ((or (org-at-heading-p)
8978 (ignore-errors (progn (org-back-to-heading) t)))
8979 ;; we will sort the children of the current headline
8980 (org-back-to-heading)
8981 (setq start (point)
8982 end (progn (org-end-of-subtree t t)
8983 (or (bolp) (insert "\n"))
8984 (when (>= (org-back-over-empty-lines) 1)
8985 (forward-line 1))
8986 (point))
8987 what "children")
8988 (goto-char start)
8989 (outline-show-subtree)
8990 (outline-next-heading))
8992 ;; we will sort the top-level entries in this file
8993 (goto-char (point-min))
8994 (or (org-at-heading-p) (outline-next-heading))
8995 (setq start (point))
8996 (goto-char (point-max))
8997 (beginning-of-line 1)
8998 (when (looking-at ".*?\\S-")
8999 ;; File ends in a non-white line
9000 (end-of-line 1)
9001 (insert "\n"))
9002 (setq end (point-max))
9003 (setq what "top-level")
9004 (goto-char start)
9005 (outline-show-all)))
9007 (setq beg (point))
9008 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9010 (looking-at "\\(\\*+\\)")
9011 (setq stars (match-string 1)
9012 re (concat "^" (regexp-quote stars) " +")
9013 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9014 txt (buffer-substring beg end))
9015 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9016 (when (and (not (equal stars "*")) (string-match re2 txt))
9017 (user-error "Region to sort contains a level above the first entry"))
9019 (unless sorting-type
9020 (message
9021 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9022 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9023 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9024 what)
9025 (setq sorting-type (read-char-exclusive))
9027 (unless getkey-func
9028 (and (= (downcase sorting-type) ?f)
9029 (setq getkey-func
9030 (completing-read "Sort using function: "
9031 obarray 'fboundp t nil nil))
9032 (setq getkey-func (intern getkey-func))))
9034 (and (= (downcase sorting-type) ?r)
9035 (not property)
9036 (setq property
9037 (completing-read "Property: "
9038 (mapcar #'list (org-buffer-property-keys t))
9039 nil t))))
9041 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9042 (message "Sorting entries...")
9044 (save-restriction
9045 (narrow-to-region start end)
9046 (let ((dcst (downcase sorting-type))
9047 (case-fold-search nil)
9048 (now (current-time)))
9049 (sort-subr
9050 (/= dcst sorting-type)
9051 ;; This function moves to the beginning character of the "record" to
9052 ;; be sorted.
9053 (lambda nil
9054 (if (re-search-forward re nil t)
9055 (goto-char (match-beginning 0))
9056 (goto-char (point-max))))
9057 ;; This function moves to the last character of the "record" being
9058 ;; sorted.
9059 (lambda nil
9060 (save-match-data
9061 (condition-case nil
9062 (outline-forward-same-level 1)
9063 (error
9064 (goto-char (point-max))))))
9065 ;; This function returns the value that gets sorted against.
9066 (lambda nil
9067 (cond
9068 ((= dcst ?n)
9069 (if (looking-at org-complex-heading-regexp)
9070 (string-to-number (org-sort-remove-invisible (match-string 4)))
9071 nil))
9072 ((= dcst ?a)
9073 (if (looking-at org-complex-heading-regexp)
9074 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9075 nil))
9076 ((= dcst ?k)
9077 (or (get-text-property (point) :org-clock-minutes) 0))
9078 ((= dcst ?t)
9079 (let ((end (save-excursion (outline-next-heading) (point))))
9080 (if (or (re-search-forward org-ts-regexp end t)
9081 (re-search-forward org-ts-regexp-both end t))
9082 (org-time-string-to-seconds (match-string 0))
9083 (float-time now))))
9084 ((= dcst ?c)
9085 (let ((end (save-excursion (outline-next-heading) (point))))
9086 (if (re-search-forward
9087 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9088 end t)
9089 (org-time-string-to-seconds (match-string 0))
9090 (float-time now))))
9091 ((= dcst ?s)
9092 (let ((end (save-excursion (outline-next-heading) (point))))
9093 (if (re-search-forward org-scheduled-time-regexp end t)
9094 (org-time-string-to-seconds (match-string 1))
9095 (float-time now))))
9096 ((= dcst ?d)
9097 (let ((end (save-excursion (outline-next-heading) (point))))
9098 (if (re-search-forward org-deadline-time-regexp end t)
9099 (org-time-string-to-seconds (match-string 1))
9100 (float-time now))))
9101 ((= dcst ?p)
9102 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9103 (string-to-char (match-string 2))
9104 org-default-priority))
9105 ((= dcst ?r)
9106 (or (org-entry-get nil property) ""))
9107 ((= dcst ?o)
9108 (when (looking-at org-complex-heading-regexp)
9109 (let* ((m (match-string 2))
9110 (s (if (member m org-done-keywords) '- '+)))
9111 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9112 ((= dcst ?f)
9113 (if getkey-func
9114 (progn
9115 (setq tmp (funcall getkey-func))
9116 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9117 tmp)
9118 (error "Invalid key function `%s'" getkey-func)))
9119 (t (error "Invalid sorting type `%c'" sorting-type))))
9121 (cond
9122 ((= dcst ?a) 'string<)
9123 ((= dcst ?f) compare-func)
9124 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9125 (run-hooks 'org-after-sorting-entries-or-items-hook)
9126 ;; Reset the clock marker if needed
9127 (when cmstr
9128 (save-excursion
9129 (goto-char start)
9130 (search-forward cmstr nil t)
9131 (move-marker org-clock-marker (point))))
9132 (message "Sorting entries...done")))
9134 ;;; The orgstruct minor mode
9136 ;; Define a minor mode which can be used in other modes in order to
9137 ;; integrate the org-mode structure editing commands.
9139 ;; This is really a hack, because the org-mode structure commands use
9140 ;; keys which normally belong to the major mode. Here is how it
9141 ;; works: The minor mode defines all the keys necessary to operate the
9142 ;; structure commands, but wraps the commands into a function which
9143 ;; tests if the cursor is currently at a headline or a plain list
9144 ;; item. If that is the case, the structure command is used,
9145 ;; temporarily setting many Org-mode variables like regular
9146 ;; expressions for filling etc. However, when any of those keys is
9147 ;; used at a different location, function uses `key-binding' to look
9148 ;; up if the key has an associated command in another currently active
9149 ;; keymap (minor modes, major mode, global), and executes that
9150 ;; command. There might be problems if any of the keys is otherwise
9151 ;; used as a prefix key.
9153 (defcustom orgstruct-heading-prefix-regexp ""
9154 "Regexp that matches the custom prefix of Org headlines in
9155 orgstruct(++)-mode."
9156 :group 'org
9157 :version "24.4"
9158 :package-version '(Org . "8.3")
9159 :type 'regexp)
9160 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9162 (defcustom orgstruct-setup-hook nil
9163 "Hook run after orgstruct-mode-map is filled."
9164 :group 'org
9165 :version "24.4"
9166 :package-version '(Org . "8.0")
9167 :type 'hook)
9169 (defvar orgstruct-initialized nil)
9171 (defvar org-local-vars nil
9172 "List of local variables, for use by `orgstruct-mode'.")
9174 ;;;###autoload
9175 (define-minor-mode orgstruct-mode
9176 "Toggle the minor mode `orgstruct-mode'.
9177 This mode is for using Org-mode structure commands in other
9178 modes. The following keys behave as if Org-mode were active, if
9179 the cursor is on a headline, or on a plain list item (both as
9180 defined by Org-mode)."
9181 nil " OrgStruct" (make-sparse-keymap)
9182 (funcall (if orgstruct-mode
9183 'add-to-invisibility-spec
9184 'remove-from-invisibility-spec)
9185 '(outline . t))
9186 (when orgstruct-mode
9187 (org-load-modules-maybe)
9188 (unless orgstruct-initialized
9189 (orgstruct-setup)
9190 (setq orgstruct-initialized t))))
9192 ;;;###autoload
9193 (defun turn-on-orgstruct ()
9194 "Unconditionally turn on `orgstruct-mode'."
9195 (orgstruct-mode 1))
9197 (defvar-local orgstruct-is-++ nil
9198 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9199 (defvar-local org-fb-vars nil)
9200 (defun orgstruct++-mode (&optional arg)
9201 "Toggle `orgstruct-mode', the enhanced version of it.
9202 In addition to setting orgstruct-mode, this also exports all
9203 indentation and autofilling variables from org-mode into the
9204 buffer. It will also recognize item context in multiline items."
9205 (interactive "P")
9206 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9207 (if (< arg 1)
9208 (progn (orgstruct-mode -1)
9209 (dolist (v org-fb-vars)
9210 (set (make-local-variable (car v))
9211 (if (eq (car-safe (cadr v)) 'quote)
9212 (cl-cadadr v)
9213 (nth 1 v)))))
9214 (orgstruct-mode 1)
9215 (setq org-fb-vars nil)
9216 (unless org-local-vars
9217 (setq org-local-vars (org-get-local-variables)))
9218 (let (var val)
9219 (dolist (x org-local-vars)
9220 (when (string-match
9221 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9222 \\|fill-prefix\\|indent-\\)"
9223 (symbol-name (car x)))
9224 (setq var (car x) val (nth 1 x))
9225 (push (list var `(quote ,(eval var))) org-fb-vars)
9226 (set (make-local-variable var)
9227 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9228 (setq-local orgstruct-is-++ t))))
9230 ;;;###autoload
9231 (defun turn-on-orgstruct++ ()
9232 "Unconditionally turn on `orgstruct++-mode'."
9233 (orgstruct++-mode 1))
9235 (defun orgstruct-error ()
9236 "Error when there is no default binding for a structure key."
9237 (interactive)
9238 (funcall (if (fboundp 'user-error)
9239 'user-error
9240 'error)
9241 "This key has no function outside structure elements"))
9243 (defun orgstruct-setup ()
9244 "Setup orgstruct keymap."
9245 (dolist (cell '((org-demote . t)
9246 (org-metaleft . t)
9247 (org-metaright . t)
9248 (org-promote . t)
9249 (org-shiftmetaleft . t)
9250 (org-shiftmetaright . t)
9251 org-backward-element
9252 org-backward-heading-same-level
9253 org-ctrl-c-ret
9254 org-ctrl-c-minus
9255 org-ctrl-c-star
9256 org-cycle
9257 org-force-cycle-archived
9258 org-forward-heading-same-level
9259 org-insert-heading
9260 org-insert-heading-respect-content
9261 org-kill-note-or-show-branches
9262 org-mark-subtree
9263 org-meta-return
9264 org-metadown
9265 org-metaup
9266 org-narrow-to-subtree
9267 org-promote-subtree
9268 org-reveal
9269 org-shiftdown
9270 org-shiftleft
9271 org-shiftmetadown
9272 org-shiftmetaup
9273 org-shiftright
9274 org-shifttab
9275 org-shifttab
9276 org-shiftup
9277 org-show-children
9278 org-show-subtree
9279 org-sort
9280 org-up-element
9281 outline-demote
9282 outline-next-visible-heading
9283 outline-previous-visible-heading
9284 outline-promote
9285 outline-up-heading))
9286 (let ((f (or (car-safe cell) cell))
9287 (disable-when-heading-prefix (cdr-safe cell)))
9288 (when (fboundp f)
9289 (let ((new-bindings))
9290 (dolist (binding (nconc (where-is-internal f org-mode-map)
9291 (where-is-internal f outline-mode-map)))
9292 (push binding new-bindings)
9293 ;; TODO use local-function-key-map
9294 (dolist (rep '(("<tab>" . "TAB")
9295 ("<return>" . "RET")
9296 ("<escape>" . "ESC")
9297 ("<delete>" . "DEL")))
9298 (setq binding (read-kbd-macro
9299 (let ((case-fold-search))
9300 (replace-regexp-in-string
9301 (regexp-quote (cdr rep))
9302 (car rep)
9303 (key-description binding)))))
9304 (cl-pushnew binding new-bindings :test 'equal)))
9305 (dolist (binding new-bindings)
9306 (let ((key (lookup-key orgstruct-mode-map binding)))
9307 (when (or (not key) (numberp key))
9308 (ignore-errors
9309 (org-defkey orgstruct-mode-map
9310 binding
9311 (orgstruct-make-binding
9312 f binding disable-when-heading-prefix))))))))))
9313 (run-hooks 'orgstruct-setup-hook))
9315 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9316 "Create a function for binding in the structure minor mode.
9317 FUN is the command to call inside a table. KEY is the key that
9318 should be checked in for a command to execute outside of tables.
9319 Non-nil `disable-when-heading-prefix' means to disable the command
9320 if `orgstruct-heading-prefix-regexp' is not empty."
9321 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9322 (let ((nname name)
9323 (i 0))
9324 (while (fboundp (intern nname))
9325 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9326 (setq name (intern nname)))
9327 (eval
9328 (let ((bindings '((org-heading-regexp
9329 (concat "^"
9330 orgstruct-heading-prefix-regexp
9331 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9332 (org-outline-regexp
9333 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9334 (org-outline-regexp-bol
9335 (concat "^" org-outline-regexp))
9336 (outline-regexp org-outline-regexp)
9337 (outline-heading-end-regexp "\n")
9338 (outline-level 'org-outline-level)
9339 (outline-heading-alist))))
9340 `(defun ,name (arg)
9341 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9342 "Outside of structure, run the binding of `"
9343 (key-description key) "'."
9344 (when disable-when-heading-prefix
9345 (concat
9346 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9347 "back to the default binding due to limitations of Org's implementation of\n"
9348 "`" (symbol-name fun) "'.")))
9349 (interactive "p")
9350 (let* ((disable
9351 ,(and disable-when-heading-prefix
9352 '(not (string= orgstruct-heading-prefix-regexp ""))))
9353 (fallback
9354 (or disable
9355 (not
9356 (let* ,bindings
9357 (org-context-p 'headline 'item
9358 ,(when (memq fun
9359 '(org-insert-heading
9360 org-insert-heading-respect-content
9361 org-meta-return))
9362 '(when orgstruct-is-++
9363 'item-body))))))))
9364 (if fallback
9365 (let* ((orgstruct-mode)
9366 (binding
9367 (let ((key ,key))
9368 (catch 'exit
9369 (dolist
9370 (rep
9371 '(nil
9372 ("<\\([^>]*\\)tab>" . "\\1TAB")
9373 ("<\\([^>]*\\)return>" . "\\1RET")
9374 ("<\\([^>]*\\)escape>" . "\\1ESC")
9375 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9376 nil)
9377 (when rep
9378 (setq key (read-kbd-macro
9379 (let ((case-fold-search))
9380 (replace-regexp-in-string
9381 (car rep)
9382 (cdr rep)
9383 (key-description key))))))
9384 (when (key-binding key)
9385 (throw 'exit (key-binding key))))))))
9386 (if (keymapp binding)
9387 (org-set-transient-map binding)
9388 (let ((func (or binding
9389 (unless disable
9390 'orgstruct-error))))
9391 (when func
9392 (call-interactively func)))))
9393 (org-run-like-in-org-mode
9394 (lambda ()
9395 (interactive)
9396 (let* ,bindings
9397 (call-interactively ',fun)))))))))
9398 name))
9400 (defun org-contextualize-keys (alist contexts)
9401 "Return valid elements in ALIST depending on CONTEXTS.
9403 `org-agenda-custom-commands' or `org-capture-templates' are the
9404 values used for ALIST, and `org-agenda-custom-commands-contexts'
9405 or `org-capture-templates-contexts' are the associated contexts
9406 definitions."
9407 (let ((contexts
9408 ;; normalize contexts
9409 (mapcar
9410 (lambda(c) (cond ((listp (cadr c))
9411 (list (car c) (car c) (nth 1 c)))
9412 ((string= "" (cadr c))
9413 (list (car c) (car c) (nth 2 c)))
9414 (t c)))
9415 contexts))
9416 (a alist) r s)
9417 ;; loop over all commands or templates
9418 (dolist (c a)
9419 (let (vrules repl)
9420 (cond
9421 ((not (assoc (car c) contexts))
9422 (push c r))
9423 ((and (assoc (car c) contexts)
9424 (setq vrules (org-contextualize-validate-key
9425 (car c) contexts)))
9426 (mapc (lambda (vr)
9427 (unless (equal (car vr) (cadr vr))
9428 (setq repl vr)))
9429 vrules)
9430 (if (not repl) (push c r)
9431 (push (cadr repl) s)
9432 (push
9433 (cons (car c)
9434 (cdr (or (assoc (cadr repl) alist)
9435 (error "Undefined key `%s' as contextual replacement for `%s'"
9436 (cadr repl) (car c)))))
9437 r))))))
9438 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9439 (delq
9441 (delete-dups
9442 (mapcar (lambda (x)
9443 (let ((tpl (car x)))
9444 (unless (delq
9446 (mapcar (lambda (y)
9447 (equal y tpl))
9449 x)))
9450 (reverse r))))))
9452 (defun org-contextualize-validate-key (key contexts)
9453 "Check CONTEXTS for agenda or capture KEY."
9454 (let (res)
9455 (dolist (r contexts)
9456 (dolist (rr (car (last r)))
9457 (when
9458 (and (equal key (car r))
9459 (if (functionp rr) (funcall rr)
9460 (or (and (eq (car rr) 'in-file)
9461 (buffer-file-name)
9462 (string-match (cdr rr) (buffer-file-name)))
9463 (and (eq (car rr) 'in-mode)
9464 (string-match (cdr rr) (symbol-name major-mode)))
9465 (and (eq (car rr) 'in-buffer)
9466 (string-match (cdr rr) (buffer-name)))
9467 (when (and (eq (car rr) 'not-in-file)
9468 (buffer-file-name))
9469 (not (string-match (cdr rr) (buffer-file-name))))
9470 (when (eq (car rr) 'not-in-mode)
9471 (not (string-match (cdr rr) (symbol-name major-mode))))
9472 (when (eq (car rr) 'not-in-buffer)
9473 (not (string-match (cdr rr) (buffer-name)))))))
9474 (push r res))))
9475 (delete-dups (delq nil res))))
9477 (defun org-context-p (&rest contexts)
9478 "Check if local context is any of CONTEXTS.
9479 Possible values in the list of contexts are `table', `headline', and `item'."
9480 (let ((pos (point)))
9481 (goto-char (point-at-bol))
9482 (prog1 (or (and (memq 'table contexts)
9483 (looking-at "[ \t]*|"))
9484 (and (memq 'headline contexts)
9485 (looking-at org-outline-regexp))
9486 (and (memq 'item contexts)
9487 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9488 (and (memq 'item-body contexts)
9489 (org-in-item-p)))
9490 (goto-char pos))))
9492 (defconst org-unique-local-variables
9493 '(org-element--cache
9494 org-element--cache-objects
9495 org-element--cache-sync-keys
9496 org-element--cache-sync-requests
9497 org-element--cache-sync-timer)
9498 "List of local variables that cannot be transferred to another buffer.")
9500 (defun org-get-local-variables ()
9501 "Return a list of all local variables in an Org mode buffer."
9502 (delq nil
9503 (mapcar
9504 (lambda (x)
9505 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9506 (name (car binding)))
9507 (and (not (get name 'org-state))
9508 (not (memq name org-unique-local-variables))
9509 (string-match-p
9510 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9511 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9512 (symbol-name name))
9513 binding)))
9514 (with-temp-buffer
9515 (org-mode)
9516 (buffer-local-variables)))))
9518 (defun org-clone-local-variables (from-buffer &optional regexp)
9519 "Clone local variables from FROM-BUFFER.
9520 Optional argument REGEXP selects variables to clone."
9521 (dolist (pair (buffer-local-variables from-buffer))
9522 (let ((name (car pair)))
9523 (when (and (symbolp name)
9524 (not (memq name org-unique-local-variables))
9525 (or (null regexp) (string-match regexp (symbol-name name))))
9526 (set (make-local-variable name) (cdr pair))))))
9528 ;;;###autoload
9529 (defun org-run-like-in-org-mode (cmd)
9530 "Run a command, pretending that the current buffer is in Org-mode.
9531 This will temporarily bind local variables that are typically bound in
9532 Org-mode to the values they have in Org-mode, and then interactively
9533 call CMD."
9534 (org-load-modules-maybe)
9535 (unless org-local-vars
9536 (setq org-local-vars (org-get-local-variables)))
9537 (let (binds)
9538 (dolist (var org-local-vars)
9539 (when (or (not (boundp (car var)))
9540 (eq (symbol-value (car var))
9541 (default-value (car var))))
9542 (push (list (car var) `(quote ,(cadr var))) binds)))
9543 (eval `(let ,binds
9544 (call-interactively (quote ,cmd))))))
9546 (defun org-get-category (&optional pos force-refresh)
9547 "Get the category applying to position POS."
9548 (save-match-data
9549 (when force-refresh (org-refresh-category-properties))
9550 (let ((pos (or pos (point))))
9551 (or (get-text-property pos 'org-category)
9552 (progn (org-refresh-category-properties)
9553 (get-text-property pos 'org-category))))))
9555 ;;; Refresh properties
9557 (defun org-refresh-properties (dprop tprop)
9558 "Refresh buffer text properties.
9559 DPROP is the drawer property and TPROP is either the
9560 corresponding text property to set, or an alist with each element
9561 being a text property (as a symbol) and a function to apply to
9562 the value of the drawer property."
9563 (let ((case-fold-search t)
9564 (inhibit-read-only t))
9565 (org-with-silent-modifications
9566 (save-excursion
9567 (save-restriction
9568 (widen)
9569 (goto-char (point-min))
9570 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9571 (org-refresh-property tprop (match-string-no-properties 1))))))))
9573 (defun org-refresh-property (tprop p)
9574 "Refresh the buffer text property TPROP from the drawer property P.
9575 The refresh happens only for the current tree (not subtree)."
9576 (unless (org-before-first-heading-p)
9577 (save-excursion
9578 (org-back-to-heading t)
9579 (if (symbolp tprop)
9580 ;; TPROP is a text property symbol
9581 (put-text-property
9582 (point) (or (outline-next-heading) (point-max)) tprop p)
9583 ;; TPROP is an alist with (properties . function) elements
9584 (dolist (al tprop)
9585 (save-excursion
9586 (put-text-property
9587 (line-beginning-position) (or (outline-next-heading) (point-max))
9588 (car al)
9589 (funcall (cdr al) p))))))))
9591 (defun org-refresh-category-properties ()
9592 "Refresh category text properties in the buffer."
9593 (let ((case-fold-search t)
9594 (inhibit-read-only t)
9595 (default-category
9596 (cond ((null org-category)
9597 (if buffer-file-name
9598 (file-name-sans-extension
9599 (file-name-nondirectory buffer-file-name))
9600 "???"))
9601 ((symbolp org-category) (symbol-name org-category))
9602 (t org-category))))
9603 (org-with-silent-modifications
9604 (org-with-wide-buffer
9605 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9606 ;; This is the default category for the buffer. If none is
9607 ;; found, fall-back to `org-category' or buffer file name.
9608 (put-text-property
9609 (point-min) (point-max)
9610 'org-category
9611 (catch 'buffer-category
9612 (goto-char (point-max))
9613 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9614 (let ((element (org-element-at-point)))
9615 (when (eq (org-element-type element) 'keyword)
9616 (throw 'buffer-category
9617 (org-element-property :value element)))))
9618 default-category))
9619 ;; Set sub-tree specific categories.
9620 (goto-char (point-min))
9621 (let ((regexp (org-re-property "CATEGORY")))
9622 (while (re-search-forward regexp nil t)
9623 (let ((value (match-string-no-properties 3)))
9624 (when (org-at-property-p)
9625 (put-text-property
9626 (save-excursion (org-back-to-heading t) (point))
9627 (save-excursion (org-end-of-subtree t t) (point))
9628 'org-category
9629 value)))))))))
9631 (defun org-refresh-stats-properties ()
9632 "Refresh stats text properties in the buffer."
9633 (let (stats)
9634 (org-with-silent-modifications
9635 (save-excursion
9636 (save-restriction
9637 (widen)
9638 (goto-char (point-min))
9639 (while (re-search-forward
9640 (concat org-outline-regexp-bol ".*"
9641 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9642 nil t)
9643 (setq stats (cond ((equal (match-string 3) "0") 0)
9644 ((match-string 2)
9645 (/ (* (string-to-number (match-string 2)) 100)
9646 (string-to-number (match-string 3))))
9647 (t (string-to-number (match-string 1)))))
9648 (org-back-to-heading t)
9649 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9650 'org-stats stats)))))))
9652 (defun org-refresh-effort-properties ()
9653 "Refresh effort properties"
9654 (org-refresh-properties
9655 org-effort-property
9656 '((effort . identity)
9657 (effort-minutes . org-duration-string-to-minutes))))
9659 ;;;; Link Stuff
9661 ;;; Link abbreviations
9663 (defun org-link-expand-abbrev (link)
9664 "Apply replacements as defined in `org-link-abbrev-alist'."
9665 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9666 (let* ((key (match-string 1 link))
9667 (as (or (assoc key org-link-abbrev-alist-local)
9668 (assoc key org-link-abbrev-alist)))
9669 (tag (and (match-end 2) (match-string 3 link)))
9670 rpl)
9671 (if (not as)
9672 link
9673 (setq rpl (cdr as))
9674 (cond
9675 ((symbolp rpl) (funcall rpl tag))
9676 ((string-match "%(\\([^)]+\\))" rpl)
9677 (replace-match
9678 (save-match-data
9679 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9680 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9681 ((string-match "%h" rpl)
9682 (replace-match (url-hexify-string (or tag "")) t t rpl))
9683 (t (concat rpl tag)))))
9684 link))
9686 ;;; Storing and inserting links
9688 (defvar org-insert-link-history nil
9689 "Minibuffer history for links inserted with `org-insert-link'.")
9691 (defvar org-stored-links nil
9692 "Contains the links stored with `org-store-link'.")
9694 (defvar org-store-link-plist nil
9695 "Plist with info about the most recently link created with `org-store-link'.")
9697 (defvar org-link-protocols nil
9698 "Link protocols added to Org-mode using `org-add-link-type'.")
9700 (defvar org-store-link-functions nil
9701 "List of functions that are called to create and store a link.
9702 Each function will be called in turn until one returns a non-nil
9703 value. Each function should check if it is responsible for creating
9704 this link (for example by looking at the major mode).
9705 If not, it must exit and return nil.
9706 If yes, it should return a non-nil value after a calling
9707 `org-store-link-props' with a list of properties and values.
9708 Special properties are:
9710 :type The link prefix, like \"http\". This must be given.
9711 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9712 This is obligatory as well.
9713 :description Optional default description for the second pair
9714 of brackets in an Org-mode link. The user can still change
9715 this when inserting this link into an Org-mode buffer.
9717 In addition to these, any additional properties can be specified
9718 and then used in capture templates.")
9720 (defun org-add-link-type (type &optional follow export)
9721 "Add TYPE to the list of `org-link-types'.
9722 Re-compute all regular expressions depending on `org-link-types'
9724 FOLLOW and EXPORT are two functions.
9726 FOLLOW should take the link path as the single argument and do whatever
9727 is necessary to follow the link, for example find a file or display
9728 a mail message.
9730 EXPORT should format the link path for export to one of the export formats.
9731 It should be a function accepting three arguments:
9733 path the path of the link, the text after the prefix (like \"http:\")
9734 desc the description of the link, if any
9735 format the export format, a symbol like `html' or `latex' or `ascii'.
9737 The function may use the FORMAT information to return different values
9738 depending on the format. The return value will be put literally into
9739 the exported file. If the return value is nil, this means Org should
9740 do what it normally does with links which do not have EXPORT defined.
9742 Org mode has a built-in default for exporting links. If you are happy with
9743 this default, there is no need to define an export function for the link
9744 type. For a simple example of an export function, see `org-bbdb.el'."
9745 (add-to-list 'org-link-types type t)
9746 (org-make-link-regexps)
9747 (org-element-update-syntax)
9748 (if (assoc type org-link-protocols)
9749 (setcdr (assoc type org-link-protocols) (list follow export))
9750 (push (list type follow export) org-link-protocols)))
9752 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9753 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9755 ;;;###autoload
9756 (defun org-store-link (arg)
9757 "\\<org-mode-map>Store an org-link to the current location.
9758 This link is added to `org-stored-links' and can later be inserted
9759 into an Org buffer with \\[org-insert-link].
9761 For some link types, a prefix ARG is interpreted.
9762 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9763 For file links, ARG negates `org-context-in-file-links'.
9765 A double prefix ARG force skipping storing functions that are not
9766 part of Org's core.
9768 A triple prefix ARG force storing a link for each line in the
9769 active region."
9770 (interactive "P")
9771 (org-load-modules-maybe)
9772 (if (and (equal arg '(64)) (org-region-active-p))
9773 (save-excursion
9774 (let ((end (region-end)))
9775 (goto-char (region-beginning))
9776 (set-mark (point))
9777 (while (< (point-at-eol) end)
9778 (move-end-of-line 1) (activate-mark)
9779 (let (current-prefix-arg)
9780 (call-interactively 'org-store-link))
9781 (move-beginning-of-line 2)
9782 (set-mark (point)))))
9783 (org-with-limited-levels
9784 (setq org-store-link-plist nil)
9785 (let (link cpltxt desc description search
9786 txt custom-id agenda-link sfuns sfunsn)
9787 (cond
9789 ;; Store a link using an external link type
9790 ((and (not (equal arg '(16)))
9791 (setq sfuns
9792 (delq
9793 nil (mapcar (lambda (f)
9794 (let (fs) (if (funcall f) (push f fs))))
9795 org-store-link-functions))
9796 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9797 (or (and (cdr sfuns)
9798 (funcall (intern
9799 (completing-read
9800 "Which function for creating the link? "
9801 sfunsn nil t (car sfunsn)))))
9802 (funcall (caar sfuns)))
9803 (setq link (plist-get org-store-link-plist :link)
9804 desc (or (plist-get org-store-link-plist
9805 :description)
9806 link))))
9808 ;; Store a link from a source code buffer.
9809 ((org-src-edit-buffer-p)
9810 (cond
9811 ((save-excursion
9812 (beginning-of-line)
9813 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9814 "[ \t]*$")))
9815 (setq link (format "(%s)" (match-string-no-properties 1))))
9816 ((org-called-interactively-p 'any)
9817 (let (label)
9818 (while (or (not label)
9819 (org-with-wide-buffer
9820 (goto-char (point-min))
9821 (re-search-forward
9822 (regexp-quote (format org-coderef-label-format label))
9823 nil t)))
9824 (when label (message "Label exists already") (sit-for 2))
9825 (setq label (read-string "Code line label: " label)))
9826 (end-of-line)
9827 (setq link (format org-coderef-label-format label))
9828 (let ((gc (- 79 (length link))))
9829 (if (< (current-column) gc) (org-move-to-column gc t)
9830 (insert " ")))
9831 (insert link)
9832 (setq link (concat "(" label ")") desc nil)))
9833 (t (setq link nil))))
9835 ;; We are in the agenda, link to referenced location
9836 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9837 (let ((m (or (get-text-property (point) 'org-hd-marker)
9838 (get-text-property (point) 'org-marker))))
9839 (when m
9840 (org-with-point-at m
9841 (setq agenda-link
9842 (if (org-called-interactively-p 'any)
9843 (call-interactively 'org-store-link)
9844 (org-store-link nil)))))))
9846 ((eq major-mode 'calendar-mode)
9847 (let ((cd (calendar-cursor-to-date)))
9848 (setq link
9849 (format-time-string
9850 (car org-time-stamp-formats)
9851 (apply 'encode-time
9852 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9853 nil nil nil))))
9854 (org-store-link-props :type "calendar" :date cd)))
9856 ((eq major-mode 'help-mode)
9857 (setq link (concat "help:" (save-excursion
9858 (goto-char (point-min))
9859 (looking-at "^[^ ]+")
9860 (match-string 0))))
9861 (org-store-link-props :type "help"))
9863 ((eq major-mode 'w3-mode)
9864 (setq cpltxt (if (and (buffer-name)
9865 (not (string-match "Untitled" (buffer-name))))
9866 (buffer-name)
9867 (url-view-url t))
9868 link (url-view-url t))
9869 (org-store-link-props :type "w3" :url (url-view-url t)))
9871 ((eq major-mode 'image-mode)
9872 (setq cpltxt (concat "file:"
9873 (abbreviate-file-name buffer-file-name))
9874 link cpltxt)
9875 (org-store-link-props :type "image" :file buffer-file-name))
9877 ;; In dired, store a link to the file of the current line
9878 ((derived-mode-p 'dired-mode)
9879 (let ((file (dired-get-filename nil t)))
9880 (setq file (if file
9881 (abbreviate-file-name
9882 (expand-file-name (dired-get-filename nil t)))
9883 ;; otherwise, no file so use current directory.
9884 default-directory))
9885 (setq cpltxt (concat "file:" file)
9886 link cpltxt)))
9888 ((setq search (run-hook-with-args-until-success
9889 'org-create-file-search-functions))
9890 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9891 "::" search))
9892 (setq cpltxt (or description link)))
9894 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9895 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9896 (cond
9897 ;; Store a link using the target at point
9898 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9899 (setq cpltxt
9900 (concat "file:"
9901 (abbreviate-file-name
9902 (buffer-file-name (buffer-base-buffer)))
9903 "::" (match-string 1))
9904 link cpltxt))
9905 ((and (featurep 'org-id)
9906 (or (eq org-id-link-to-org-use-id t)
9907 (and (org-called-interactively-p 'any)
9908 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9909 (and (eq org-id-link-to-org-use-id
9910 'create-if-interactive-and-no-custom-id)
9911 (not custom-id))))
9912 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9913 ;; Store a link using the ID at point
9914 (setq link (condition-case nil
9915 (prog1 (org-id-store-link)
9916 (setq desc (or (plist-get org-store-link-plist
9917 :description)
9918 "")))
9919 (error
9920 ;; Probably before first headline, link only to file
9921 (concat "file:"
9922 (abbreviate-file-name
9923 (buffer-file-name (buffer-base-buffer))))))))
9925 ;; Just link to current headline
9926 (setq cpltxt (concat "file:"
9927 (abbreviate-file-name
9928 (buffer-file-name (buffer-base-buffer)))))
9929 ;; Add a context search string
9930 (when (org-xor org-context-in-file-links arg)
9931 (let* ((element (org-element-at-point))
9932 (name (org-element-property :name element)))
9933 (setq txt (cond
9934 ((org-at-heading-p) nil)
9935 (name)
9936 ((org-region-active-p)
9937 (buffer-substring (region-beginning) (region-end)))))
9938 (when (or (null txt) (string-match "\\S-" txt))
9939 (setq cpltxt
9940 (concat cpltxt "::"
9941 (condition-case nil
9942 (org-make-org-heading-search-string txt)
9943 (error "")))
9944 desc (or name
9945 (nth 4 (ignore-errors (org-heading-components)))
9946 "NONE")))))
9947 (when (string-match "::\\'" cpltxt)
9948 (setq cpltxt (substring cpltxt 0 -2)))
9949 (setq link cpltxt))))
9951 ((buffer-file-name (buffer-base-buffer))
9952 ;; Just link to this file here.
9953 (setq cpltxt (concat "file:"
9954 (abbreviate-file-name
9955 (buffer-file-name (buffer-base-buffer)))))
9956 ;; Add a context string.
9957 (when (org-xor org-context-in-file-links arg)
9958 (setq txt (if (org-region-active-p)
9959 (buffer-substring (region-beginning) (region-end))
9960 (buffer-substring (point-at-bol) (point-at-eol))))
9961 ;; Only use search option if there is some text.
9962 (when (string-match "\\S-" txt)
9963 (setq cpltxt
9964 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9965 desc "NONE")))
9966 (setq link cpltxt))
9968 ((org-called-interactively-p 'interactive)
9969 (user-error "No method for storing a link from this buffer"))
9971 (t (setq link nil)))
9973 ;; We're done setting link and desc, clean up
9974 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9975 (setq link (or link cpltxt)
9976 desc (or desc cpltxt))
9977 (cond ((not desc))
9978 ((equal desc "NONE") (setq desc nil))
9979 (t (setq desc
9980 (replace-regexp-in-string
9981 org-bracket-link-analytic-regexp
9982 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9983 desc))))
9984 ;; Return the link
9985 (if (not (and (or (org-called-interactively-p 'any)
9986 executing-kbd-macro)
9987 link))
9988 (or agenda-link (and link (org-make-link-string link desc)))
9989 (push (list link desc) org-stored-links)
9990 (message "Stored: %s" (or desc link))
9991 (when custom-id
9992 (setq link (concat "file:" (abbreviate-file-name
9993 (buffer-file-name)) "::#" custom-id))
9994 (push (list link desc) org-stored-links))
9995 (car org-stored-links))))))
9997 (defun org-store-link-props (&rest plist)
9998 "Store link properties, extract names, addresses and dates."
9999 (let ((x (plist-get plist :from)))
10000 (when x
10001 (let ((adr (mail-extract-address-components x)))
10002 (setq plist (plist-put plist :fromname (car adr)))
10003 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
10004 (let ((x (plist-get plist :to)))
10005 (when x
10006 (let ((adr (mail-extract-address-components x)))
10007 (setq plist (plist-put plist :toname (car adr)))
10008 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10009 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10010 (when x
10011 (setq plist (plist-put plist :date-timestamp
10012 (format-time-string
10013 (org-time-stamp-format t) x)))
10014 (setq plist (plist-put plist :date-timestamp-inactive
10015 (format-time-string
10016 (org-time-stamp-format t t) x)))))
10017 (let ((from (plist-get plist :from))
10018 (to (plist-get plist :to)))
10019 (when (and from to org-from-is-user-regexp)
10020 (setq plist
10021 (plist-put plist :fromto
10022 (if (string-match org-from-is-user-regexp from)
10023 (concat "to %t")
10024 (concat "from %f"))))))
10025 (setq org-store-link-plist plist))
10027 (defun org-add-link-props (&rest plist)
10028 "Add these properties to the link property list."
10029 (let (key value)
10030 (while plist
10031 (setq key (pop plist) value (pop plist))
10032 (setq org-store-link-plist
10033 (plist-put org-store-link-plist key value)))))
10035 (defun org-email-link-description (&optional fmt)
10036 "Return the description part of an email link.
10037 This takes information from `org-store-link-plist' and formats it
10038 according to FMT (default from `org-email-link-description-format')."
10039 (setq fmt (or fmt org-email-link-description-format))
10040 (let* ((p org-store-link-plist)
10041 (to (plist-get p :toaddress))
10042 (from (plist-get p :fromaddress))
10043 (table
10044 (list
10045 (cons "%c" (plist-get p :fromto))
10046 (cons "%F" (plist-get p :from))
10047 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10048 (cons "%T" (plist-get p :to))
10049 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10050 (cons "%s" (plist-get p :subject))
10051 (cons "%d" (plist-get p :date))
10052 (cons "%m" (plist-get p :message-id)))))
10053 (when (string-match "%c" fmt)
10054 ;; Check if the user wrote this message
10055 (if (and org-from-is-user-regexp from to
10056 (save-match-data (string-match org-from-is-user-regexp from)))
10057 (setq fmt (replace-match "to %t" t t fmt))
10058 (setq fmt (replace-match "from %f" t t fmt))))
10059 (org-replace-escapes fmt table)))
10061 (defun org-make-org-heading-search-string (&optional string)
10062 "Make search string for the current headline or STRING."
10063 (let ((s (or string
10064 (and (derived-mode-p 'org-mode)
10065 (save-excursion
10066 (org-back-to-heading t)
10067 (org-element-property :raw-value (org-element-at-point))))))
10068 (lines org-context-in-file-links))
10069 (or string (setq s (concat "*" s))) ; Add * for headlines
10070 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10071 (when (and string (integerp lines) (> lines 0))
10072 (let ((slines (org-split-string s "\n")))
10073 (when (< lines (length slines))
10074 (setq s (mapconcat
10075 'identity
10076 (reverse (nthcdr (- (length slines) lines)
10077 (reverse slines))) "\n")))))
10078 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10080 (defun org-make-link-string (link &optional description)
10081 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10082 (unless (org-string-nw-p link) (error "Empty link"))
10083 (let ((uri (cond ((string-match org-link-types-re link)
10084 (concat (match-string 1 link)
10085 (org-link-escape (substring link (match-end 1)))))
10086 ;; For readability, url-encode internal links only
10087 ;; when absolutely needed (i.e, when they contain
10088 ;; square brackets). File links however, are
10089 ;; encoded since, e.g., spaces are significant.
10090 ((or (file-name-absolute-p link)
10091 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10092 (org-link-escape link))
10093 (t link)))
10094 (description
10095 (and (org-string-nw-p description)
10096 ;; Remove brackets from description, as they are fatal.
10097 (replace-regexp-in-string
10098 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10099 (org-trim description)))))
10100 (format "[[%s]%s]"
10102 (if description (format "[%s]" description) ""))))
10104 (defconst org-link-escape-chars
10105 ;;%20 %5B %5D %25
10106 '(?\s ?\[ ?\] ?%)
10107 "List of characters that should be escaped in a link when stored to Org.
10108 This is the list that is used for internal purposes.")
10110 (defconst org-link-escape-chars-browser
10111 ;;%20 %22
10112 '(?\s ?\")
10113 "List of characters to be escaped before handing over to the browser.
10114 If you consider using this constant then you probably want to use
10115 the function `org-link-escape-browser' instead. See there why
10116 this constant is a candidate to be removed once Org drops support
10117 for Emacs 24.1 and 24.2.")
10119 (defun org-link-escape (text &optional table merge)
10120 "Return percent escaped representation of TEXT.
10121 TEXT is a string with the text to escape.
10122 Optional argument TABLE is a list with characters that should be
10123 escaped. When nil, `org-link-escape-chars' is used.
10124 If optional argument MERGE is set, merge TABLE into
10125 `org-link-escape-chars'."
10126 (let ((characters-to-encode
10127 (cond ((null table) org-link-escape-chars)
10128 (merge (append org-link-escape-chars table))
10129 (t table))))
10130 (mapconcat
10131 (lambda (c)
10132 (if (or (memq c characters-to-encode)
10133 (and org-url-hexify-p (or (< c 32) (> c 126))))
10134 (mapconcat (lambda (e) (format "%%%.2X" e))
10135 (or (encode-coding-char c 'utf-8)
10136 (error "Unable to percent escape character: %c" c))
10138 (char-to-string c)))
10139 text "")))
10141 (defun org-link-escape-browser (text)
10142 "Escape some characters before handing over to the browser.
10143 This function is a candidate to be removed together with the
10144 constant `org-link-escape-chars-browser' once Org drops support
10145 for Emacs 24.1 and 24.2. All calls to this function will have to
10146 be replaced with `url-encode-url' which is available since Emacs
10147 24.3.1."
10148 ;; Example with the Org link
10149 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10150 ;; to open the browser with +subject:"Release 8.2" filled into the
10151 ;; query field: In this case the variable TEXT contains the
10152 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10153 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10154 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10155 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10156 (if (fboundp 'url-encode-url)
10157 (url-encode-url text)
10158 (if (org-string-match-p
10159 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10160 text)
10161 (org-link-escape text org-link-escape-chars-browser)
10162 text)))
10164 (defun org-link-unescape (str)
10165 "Unhex hexified Unicode parts in string STR.
10166 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10167 reciprocal of `org-link-escape', which see."
10168 (if (org-string-nw-p str)
10169 (replace-regexp-in-string
10170 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10171 str))
10173 (defun org-link-unescape-compound (hex)
10174 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10175 Note: this function also decodes single byte encodings like
10176 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10177 (save-match-data
10178 (let* ((bytes (cdr (split-string hex "%")))
10179 (ret "")
10180 (eat 0)
10181 (sum 0))
10182 (while bytes
10183 (let* ((val (string-to-number (pop bytes) 16))
10184 (shift-xor
10185 (if (= 0 eat)
10186 (cond
10187 ((>= val 252) (cons 6 252))
10188 ((>= val 248) (cons 5 248))
10189 ((>= val 240) (cons 4 240))
10190 ((>= val 224) (cons 3 224))
10191 ((>= val 192) (cons 2 192))
10192 (t (cons 0 0)))
10193 (cons 6 128))))
10194 (when (>= val 192) (setq eat (car shift-xor)))
10195 (setq val (logxor val (cdr shift-xor)))
10196 (setq sum (+ (lsh sum (car shift-xor)) val))
10197 (when (> eat 0) (setq eat (- eat 1)))
10198 (cond
10199 ((= 0 eat) ;multi byte
10200 (setq ret (concat ret (org-char-to-string sum)))
10201 (setq sum 0))
10202 ((not bytes) ; single byte(s)
10203 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10204 ret)))
10206 (defun org-link-unescape-single-byte-sequence (hex)
10207 "Unhexify hex-encoded single byte character sequences."
10208 (mapconcat (lambda (byte)
10209 (char-to-string (string-to-number byte 16)))
10210 (cdr (split-string hex "%")) ""))
10212 (defun org-xor (a b)
10213 "Exclusive or."
10214 (if a (not b) b))
10216 (defun org-fixup-message-id-for-http (s)
10217 "Replace special characters in a message id, so it can be used in an http query."
10218 (when (string-match "%" s)
10219 (setq s (mapconcat (lambda (c)
10220 (if (eq c ?%)
10221 "%25"
10222 (char-to-string c)))
10223 s "")))
10224 (while (string-match "<" s)
10225 (setq s (replace-match "%3C" t t s)))
10226 (while (string-match ">" s)
10227 (setq s (replace-match "%3E" t t s)))
10228 (while (string-match "@" s)
10229 (setq s (replace-match "%40" t t s)))
10232 (defun org-link-prettify (link)
10233 "Return a human-readable representation of LINK.
10234 The car of LINK must be a raw link.
10235 The cdr of LINK must be either a link description or nil."
10236 (let ((desc (or (cadr link) "<no description>")))
10237 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10238 "<" (car link) ">")))
10240 ;;;###autoload
10241 (defun org-insert-link-global ()
10242 "Insert a link like Org-mode does.
10243 This command can be called in any mode to insert a link in Org-mode syntax."
10244 (interactive)
10245 (org-load-modules-maybe)
10246 (org-run-like-in-org-mode 'org-insert-link))
10248 (defun org-insert-all-links (arg &optional pre post)
10249 "Insert all links in `org-stored-links'.
10250 When a universal prefix, do not delete the links from `org-stored-links'.
10251 When `ARG' is a number, insert the last N link(s).
10252 `PRE' and `POST' are optional arguments to define a string to
10253 prepend or to append."
10254 (interactive "P")
10255 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10256 (links (copy-sequence org-stored-links))
10257 (pr (or pre "- "))
10258 (po (or post "\n"))
10259 (cnt 1) l)
10260 (if (null org-stored-links)
10261 (message "No link to insert")
10262 (while (and (or (listp arg) (>= arg cnt))
10263 (setq l (if (listp arg)
10264 (pop links)
10265 (pop org-stored-links))))
10266 (setq cnt (1+ cnt))
10267 (insert pr)
10268 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10269 (insert po)))))
10271 (defun org-insert-last-stored-link (arg)
10272 "Insert the last link stored in `org-stored-links'."
10273 (interactive "p")
10274 (org-insert-all-links arg "" "\n"))
10276 (defun org-link-fontify-links-to-this-file ()
10277 "Fontify links to the current file in `org-stored-links'."
10278 (let ((f (buffer-file-name)) a b)
10279 (setq a (mapcar (lambda(l)
10280 (let ((ll (car l)))
10281 (when (and (string-match "^file:\\(.+\\)::" ll)
10282 (equal f (expand-file-name (match-string 1 ll))))
10283 ll)))
10284 org-stored-links))
10285 (when (featurep 'org-id)
10286 (setq b (mapcar (lambda(l)
10287 (let ((ll (car l)))
10288 (when (and (string-match "^id:\\(.+\\)$" ll)
10289 (equal f (expand-file-name
10290 (or (org-id-find-id-file
10291 (match-string 1 ll)) ""))))
10292 ll)))
10293 org-stored-links)))
10294 (mapcar (lambda(l)
10295 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10296 (delq nil (append a b)))))
10298 (defvar org--links-history nil)
10299 (defun org-insert-link (&optional complete-file link-location default-description)
10300 "Insert a link. At the prompt, enter the link.
10302 Completion can be used to insert any of the link protocol prefixes like
10303 http or ftp in use.
10305 The history can be used to select a link previously stored with
10306 `org-store-link'. When the empty string is entered (i.e. if you just
10307 press RET at the prompt), the link defaults to the most recently
10308 stored link. As SPC triggers completion in the minibuffer, you need to
10309 use M-SPC or C-q SPC to force the insertion of a space character.
10311 You will also be prompted for a description, and if one is given, it will
10312 be displayed in the buffer instead of the link.
10314 If there is already a link at point, this command will allow you to edit link
10315 and description parts.
10317 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10318 be selected using completion. The path to the file will be relative to the
10319 current directory if the file is in the current directory or a subdirectory.
10320 Otherwise, the link will be the absolute path as completed in the minibuffer
10321 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10322 option `org-link-file-path-type'.
10324 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10325 the current directory or below.
10327 With three \\[universal-argument] prefixes, negate the meaning of
10328 `org-keep-stored-link-after-insertion'.
10330 If `org-make-link-description-function' is non-nil, this function will be
10331 called with the link target, and the result will be the default
10332 link description.
10334 If the LINK-LOCATION parameter is non-nil, this value will be
10335 used as the link location instead of reading one interactively.
10337 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10338 be used as the default description."
10339 (interactive "P")
10340 (let* ((wcf (current-window-configuration))
10341 (origbuf (current-buffer))
10342 (region (when (org-region-active-p)
10343 (buffer-substring (region-beginning) (region-end))))
10344 (remove (and region (list (region-beginning) (region-end))))
10345 (desc region)
10346 (link link-location)
10347 (abbrevs org-link-abbrev-alist-local)
10348 entry all-prefixes auto-desc)
10349 (cond
10350 (link-location) ; specified by arg, just use it.
10351 ((org-in-regexp org-bracket-link-regexp 1)
10352 ;; We do have a link at point, and we are going to edit it.
10353 (setq remove (list (match-beginning 0) (match-end 0)))
10354 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10355 (setq link (read-string "Link: "
10356 (org-link-unescape
10357 (match-string-no-properties 1)))))
10358 ((or (org-in-regexp org-angle-link-re)
10359 (org-in-regexp org-plain-link-re))
10360 ;; Convert to bracket link
10361 (setq remove (list (match-beginning 0) (match-end 0))
10362 link (read-string "Link: "
10363 (org-remove-angle-brackets (match-string 0)))))
10364 ((member complete-file '((4) (16)))
10365 ;; Completing read for file names.
10366 (setq link (org-file-complete-link complete-file)))
10368 ;; Read link, with completion for stored links.
10369 (org-link-fontify-links-to-this-file)
10370 (org-switch-to-buffer-other-window "*Org Links*")
10371 (with-current-buffer "*Org Links*"
10372 (erase-buffer)
10373 (insert "Insert a link.
10374 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10375 (when org-stored-links
10376 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10377 (insert (mapconcat 'org-link-prettify
10378 (reverse org-stored-links) "\n")))
10379 (goto-char (point-min)))
10380 (let ((cw (selected-window)))
10381 (select-window (get-buffer-window "*Org Links*" 'visible))
10382 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10383 (unless (pos-visible-in-window-p (point-max))
10384 (org-fit-window-to-buffer))
10385 (and (window-live-p cw) (select-window cw)))
10386 (setq all-prefixes (append (mapcar 'car abbrevs)
10387 (mapcar 'car org-link-abbrev-alist)
10388 org-link-types))
10389 (unwind-protect
10390 ;; Fake a link history, containing the stored links.
10391 (let ((org--links-history
10392 (append (mapcar #'car org-stored-links)
10393 org-insert-link-history)))
10394 (setq link
10395 (org-completing-read
10396 "Link: "
10397 (append
10398 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10399 (mapcar #'car org-stored-links))
10400 nil nil nil
10401 'org--links-history
10402 (caar org-stored-links)))
10403 (unless (org-string-nw-p link) (user-error "No link selected"))
10404 (dolist (l org-stored-links)
10405 (when (equal link (cadr l))
10406 (setq link (car l))
10407 (setq auto-desc t)))
10408 (when (or (member link all-prefixes)
10409 (and (equal ":" (substring link -1))
10410 (member (substring link 0 -1) all-prefixes)
10411 (setq link (substring link 0 -1))))
10412 (setq link (with-current-buffer origbuf
10413 (org-link-try-special-completion link)))))
10414 (set-window-configuration wcf)
10415 (kill-buffer "*Org Links*"))
10416 (setq entry (assoc link org-stored-links))
10417 (or entry (push link org-insert-link-history))
10418 (setq desc (or desc (nth 1 entry)))))
10420 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10421 (not org-keep-stored-link-after-insertion))
10422 (setq org-stored-links (delq (assoc link org-stored-links)
10423 org-stored-links)))
10425 (when (and (string-match org-plain-link-re link)
10426 (not (string-match org-ts-regexp link)))
10427 ;; URL-like link, normalize the use of angular brackets.
10428 (setq link (org-remove-angle-brackets link)))
10430 ;; Check if we are linking to the current file with a search
10431 ;; option If yes, simplify the link by using only the search
10432 ;; option.
10433 (when (and buffer-file-name
10434 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10435 (let* ((path (match-string 1 link))
10436 (case-fold-search nil)
10437 (search (match-string 2 link)))
10438 (save-match-data
10439 (when (equal (file-truename buffer-file-name) (file-truename path))
10440 ;; We are linking to this same file, with a search option
10441 (setq link search)))))
10443 ;; Check if we can/should use a relative path. If yes, simplify the link
10444 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10445 (let* ((type (match-string 1 link))
10446 (path (match-string 2 link))
10447 (origpath path)
10448 (case-fold-search nil))
10449 (cond
10450 ((or (eq org-link-file-path-type 'absolute)
10451 (equal complete-file '(16)))
10452 (setq path (abbreviate-file-name (expand-file-name path))))
10453 ((eq org-link-file-path-type 'noabbrev)
10454 (setq path (expand-file-name path)))
10455 ((eq org-link-file-path-type 'relative)
10456 (setq path (file-relative-name path)))
10458 (save-match-data
10459 (if (string-match (concat "^" (regexp-quote
10460 (expand-file-name
10461 (file-name-as-directory
10462 default-directory))))
10463 (expand-file-name path))
10464 ;; We are linking a file with relative path name.
10465 (setq path (substring (expand-file-name path)
10466 (match-end 0)))
10467 (setq path (abbreviate-file-name (expand-file-name path)))))))
10468 (setq link (concat type path))
10469 (when (equal desc origpath)
10470 (setq desc path))))
10472 (if org-make-link-description-function
10473 (setq desc
10474 (or (condition-case nil
10475 (funcall org-make-link-description-function link desc)
10476 (error (progn (message "Can't get link description from `%s'"
10477 (symbol-name org-make-link-description-function))
10478 (sit-for 2) nil)))
10479 (read-string "Description: " default-description)))
10480 (if default-description (setq desc default-description)
10481 (setq desc (or (and auto-desc desc)
10482 (read-string "Description: " desc)))))
10484 (unless (string-match "\\S-" desc) (setq desc nil))
10485 (when remove (apply 'delete-region remove))
10486 (insert (org-make-link-string link desc))
10487 ;; Redisplay so as the new link has proper invisible characters.
10488 (sit-for 0)))
10490 (defun org-link-try-special-completion (type)
10491 "If there is completion support for link type TYPE, offer it."
10492 (let ((fun (intern (concat "org-" type "-complete-link"))))
10493 (if (functionp fun)
10494 (funcall fun)
10495 (read-string "Link (no completion support): " (concat type ":")))))
10497 (defun org-file-complete-link (&optional arg)
10498 "Create a file link using completion."
10499 (let ((file (read-file-name "File: "))
10500 (pwd (file-name-as-directory (expand-file-name ".")))
10501 (pwd1 (file-name-as-directory (abbreviate-file-name
10502 (expand-file-name ".")))))
10503 (cond ((equal arg '(16))
10504 (concat "file:"
10505 (abbreviate-file-name (expand-file-name file))))
10506 ((string-match
10507 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10508 (concat "file:" (match-string 1 file)))
10509 ((string-match
10510 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10511 (expand-file-name file))
10512 (concat "file:"
10513 (match-string 1 (expand-file-name file))))
10514 (t (concat "file:" file)))))
10516 (defun org-completing-read (&rest args)
10517 "Completing-read with SPACE being a normal character."
10518 (let ((enable-recursive-minibuffers t)
10519 (minibuffer-local-completion-map
10520 (copy-keymap minibuffer-local-completion-map)))
10521 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10522 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10523 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10524 'org-time-stamp-inactive)
10525 (apply #'completing-read args)))
10527 (define-obsolete-function-alias
10528 'org-completing-read-no-i 'completing-read "Org 9.0")
10529 (define-obsolete-function-alias
10530 'org-icompleting-read 'completing-read "Org 9.0")
10531 (define-obsolete-function-alias
10532 'org-iread-file-name 'read-file-name "Org 9.0")
10534 ;;; Opening/following a link
10536 (defvar org-link-search-failed nil)
10538 (defvar org-open-link-functions nil
10539 "Hook for functions finding a plain text link.
10540 These functions must take a single argument, the link content.
10541 They will be called for links that look like [[link text][description]]
10542 when LINK TEXT does not have a protocol like \"http:\" and does not look
10543 like a filename (e.g. \"./blue.png\").
10545 These functions will be called *before* Org attempts to resolve the
10546 link by doing text searches in the current buffer - so if you want a
10547 link \"[[target]]\" to still find \"<<target>>\", your function should
10548 handle this as a special case.
10550 When the function does handle the link, it must return a non-nil value.
10551 If it decides that it is not responsible for this link, it must return
10552 nil to indicate that that Org-mode can continue with other options
10553 like exact and fuzzy text search.")
10555 (defun org-next-link (&optional search-backward)
10556 "Move forward to the next link.
10557 If the link is in hidden text, expose it."
10558 (interactive "P")
10559 (when (and org-link-search-failed (eq this-command last-command))
10560 (goto-char (point-min))
10561 (message "Link search wrapped back to beginning of buffer"))
10562 (setq org-link-search-failed nil)
10563 (let* ((pos (point))
10564 (ct (org-context))
10565 (a (assoc :link ct))
10566 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10567 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10568 ((looking-at org-any-link-re)
10569 ;; Don't stay stuck at link without an org-link face
10570 (forward-char (if search-backward -1 1))))
10571 (if (funcall srch-fun org-any-link-re nil t)
10572 (progn
10573 (goto-char (match-beginning 0))
10574 (when (outline-invisible-p) (org-show-context)))
10575 (goto-char pos)
10576 (setq org-link-search-failed t)
10577 (message "No further link found"))))
10579 (defun org-previous-link ()
10580 "Move backward to the previous link.
10581 If the link is in hidden text, expose it."
10582 (interactive)
10583 (funcall 'org-next-link t))
10585 (defun org-translate-link (s)
10586 "Translate a link string if a translation function has been defined."
10587 (with-temp-buffer
10588 (insert (org-trim s))
10589 (org-trim (org-element-interpret-data (org-element-context)))))
10591 (defun org-translate-link-from-planner (type path)
10592 "Translate a link from Emacs Planner syntax so that Org can follow it.
10593 This is still an experimental function, your mileage may vary."
10594 (cond
10595 ((member type '("http" "https" "news" "ftp"))
10596 ;; standard Internet links are the same.
10597 nil)
10598 ((and (equal type "irc") (string-match "^//" path))
10599 ;; Planner has two / at the beginning of an irc link, we have 1.
10600 ;; We should have zero, actually....
10601 (setq path (substring path 1)))
10602 ((and (equal type "lisp") (string-match "^/" path))
10603 ;; Planner has a slash, we do not.
10604 (setq type "elisp" path (substring path 1)))
10605 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10606 ;; A typical message link. Planner has the id after the final slash,
10607 ;; we separate it with a hash mark
10608 (setq path (concat (match-string 1 path) "#"
10609 (org-remove-angle-brackets (match-string 2 path))))))
10610 (cons type path))
10612 (defun org-find-file-at-mouse (ev)
10613 "Open file link or URL at mouse."
10614 (interactive "e")
10615 (mouse-set-point ev)
10616 (org-open-at-point 'in-emacs))
10618 (defun org-open-at-mouse (ev)
10619 "Open file link or URL at mouse.
10620 See the docstring of `org-open-file' for details."
10621 (interactive "e")
10622 (mouse-set-point ev)
10623 (when (eq major-mode 'org-agenda-mode)
10624 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10625 (org-open-at-point))
10627 (defvar org-window-config-before-follow-link nil
10628 "The window configuration before following a link.
10629 This is saved in case the need arises to restore it.")
10631 ;;;###autoload
10632 (defun org-open-at-point-global ()
10633 "Follow a link or time-stamp like Org mode does.
10634 This command can be called in any mode to follow an external link
10635 or a time-stamp that has Org mode syntax. Its behavior is
10636 undefined when called on internal links (e.g., fuzzy links).
10637 Raise an error when there is nothing to follow. "
10638 (interactive)
10639 (cond ((org-in-regexp org-any-link-re)
10640 (org-open-link-from-string (match-string-no-properties 0)))
10641 ((or (org-in-regexp org-ts-regexp-both nil t)
10642 (org-in-regexp org-tsr-regexp-both nil t))
10643 (org-follow-timestamp-link))
10644 (t (user-error "No link found"))))
10646 ;;;###autoload
10647 (defun org-open-link-from-string (s &optional arg reference-buffer)
10648 "Open a link in the string S, as if it was in Org-mode."
10649 (interactive "sLink: \nP")
10650 (let ((reference-buffer (or reference-buffer (current-buffer))))
10651 (with-temp-buffer
10652 (let ((org-inhibit-startup (not reference-buffer)))
10653 (org-mode)
10654 (insert s)
10655 (goto-char (point-min))
10656 (when reference-buffer
10657 (setq org-link-abbrev-alist-local
10658 (with-current-buffer reference-buffer
10659 org-link-abbrev-alist-local)))
10660 (org-open-at-point arg reference-buffer)))))
10662 (defvar org-open-at-point-functions nil
10663 "Hook that is run when following a link at point.
10665 Functions in this hook must return t if they identify and follow
10666 a link at point. If they don't find anything interesting at point,
10667 they must return nil.")
10669 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10670 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10671 (defun org-open-at-point (&optional arg reference-buffer)
10672 "Open link, timestamp, footnote or tags at point.
10674 When point is on a link, follow it. Normally, files will be
10675 opened by an appropriate application. If the optional prefix
10676 argument ARG is non-nil, Emacs will visit the file. With
10677 a double prefix argument, try to open outside of Emacs, in the
10678 application the system uses for this file type.
10680 When point is on a timestamp, open the agenda at the day
10681 specified.
10683 When point is a footnote definition, move to the first reference
10684 found. If it is on a reference, move to the associated
10685 definition.
10687 When point is on a headline, display a list of every link in the
10688 entry, so it is possible to pick one, or all, of them. If point
10689 is on a tag, call `org-tags-view' instead.
10691 When optional argument REFERENCE-BUFFER is non-nil, it should
10692 specify a buffer from where the link search should happen. This
10693 is used internally by `org-open-link-from-string'.
10695 On top of syntactically correct links, this function will open
10696 the link at point in comments or comment blocks and the first
10697 link in a property drawer line."
10698 (interactive "P")
10699 ;; On a code block, open block's results.
10700 (unless (call-interactively 'org-babel-open-src-block-result)
10701 (org-load-modules-maybe)
10702 (setq org-window-config-before-follow-link (current-window-configuration))
10703 (org-remove-occur-highlights nil nil t)
10704 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10705 (let* ((context
10706 ;; Only consider supported types, even if they are not
10707 ;; the closest one.
10708 (org-element-lineage
10709 (org-element-context)
10710 '(clock comment comment-block footnote-definition
10711 footnote-reference headline inlinetask keyword link
10712 node-property timestamp)
10714 (type (org-element-type context))
10715 (value (org-element-property :value context)))
10716 (cond
10717 ((not context) (user-error "No link found"))
10718 ;; Exception: open timestamps and links in properties
10719 ;; drawers, keywords and comments.
10720 ((memq type '(comment comment-block keyword node-property))
10721 (call-interactively #'org-open-at-point-global))
10722 ;; On a headline or an inlinetask, but not on a timestamp,
10723 ;; a link, a footnote reference or on tags.
10724 ((and (memq type '(headline inlinetask))
10725 ;; Not on tags.
10726 (progn (save-excursion (beginning-of-line)
10727 (looking-at org-complex-heading-regexp))
10728 (or (not (match-beginning 5))
10729 (< (point) (match-beginning 5)))))
10730 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10731 (links (car data))
10732 (links-end (cdr data)))
10733 (if links
10734 (dolist (link (if (stringp links) (list links) links))
10735 (search-forward link nil links-end)
10736 (goto-char (match-beginning 0))
10737 (org-open-at-point))
10738 (require 'org-attach)
10739 (org-attach-reveal 'if-exists))))
10740 ;; On a clock line, make sure point is on the timestamp
10741 ;; before opening it.
10742 ((and (eq type 'clock)
10743 value
10744 (>= (point) (org-element-property :begin value))
10745 (<= (point) (org-element-property :end value)))
10746 (org-follow-timestamp-link))
10747 ;; Do nothing on white spaces after an object.
10748 ((>= (point)
10749 (save-excursion
10750 (goto-char (org-element-property :end context))
10751 (skip-chars-backward " \t")
10752 (point)))
10753 (user-error "No link found"))
10754 ((eq type 'timestamp) (org-follow-timestamp-link))
10755 ;; On tags within a headline or an inlinetask.
10756 ((and (memq type '(headline inlinetask))
10757 (progn (save-excursion (beginning-of-line)
10758 (looking-at org-complex-heading-regexp))
10759 (and (match-beginning 5)
10760 (>= (point) (match-beginning 5)))))
10761 (org-tags-view arg (substring (match-string 5) 0 -1)))
10762 ((eq type 'link)
10763 ;; When link is located within the description of another
10764 ;; link (e.g., an inline image), always open the parent
10765 ;; link.
10766 (let*((link (let ((up (org-element-property :parent context)))
10767 (if (eq (org-element-type up) 'link) up context)))
10768 (type (org-element-property :type link))
10769 (path (org-link-unescape (org-element-property :path link))))
10770 ;; Switch back to REFERENCE-BUFFER needed when called in
10771 ;; a temporary buffer through `org-open-link-from-string'.
10772 (with-current-buffer (or reference-buffer (current-buffer))
10773 (cond
10774 ((equal type "file")
10775 (if (string-match "[*?{]" (file-name-nondirectory path))
10776 (dired path)
10777 ;; Look into `org-link-protocols' in order to find
10778 ;; a DEDICATED-FUNCTION to open file. The function
10779 ;; will be applied on raw link instead of parsed
10780 ;; link due to the limitation in `org-add-link-type'
10781 ;; ("open" function called with a single argument).
10782 ;; If no such function is found, fallback to
10783 ;; `org-open-file'.
10785 ;; Note : "file+emacs" and "file+sys" types are
10786 ;; hard-coded in order to escape the previous
10787 ;; limitation.
10788 (let* ((option (org-element-property :search-option link))
10789 (app (org-element-property :application link))
10790 (dedicated-function
10791 (nth 1 (assoc app org-link-protocols))))
10792 (if dedicated-function
10793 (funcall dedicated-function
10794 (concat path
10795 (and option (concat "::" option))))
10796 (apply #'org-open-file
10797 path
10798 (cond (arg)
10799 ((equal app "emacs") 'emacs)
10800 ((equal app "sys") 'system))
10801 (cond ((not option) nil)
10802 ((org-string-match-p "\\`[0-9]+\\'" option)
10803 (list (string-to-number option)))
10804 (t (list nil
10805 (org-link-unescape option)))))))))
10806 ((assoc type org-link-protocols)
10807 (funcall (nth 1 (assoc type org-link-protocols)) path))
10808 ((equal type "help")
10809 (let ((f-or-v (intern path)))
10810 (cond ((fboundp f-or-v) (describe-function f-or-v))
10811 ((boundp f-or-v) (describe-variable f-or-v))
10812 (t (error "Not a known function or variable")))))
10813 ((member type '("http" "https" "ftp" "mailto" "news"))
10814 (browse-url (org-link-escape-browser (concat type ":" path))))
10815 ((equal type "doi")
10816 (browse-url
10817 (org-link-escape-browser (concat org-doi-server-url path))))
10818 ((equal type "message") (browse-url (concat type ":" path)))
10819 ((equal type "shell")
10820 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10821 (cmd path))
10822 (if (or (and (org-string-nw-p
10823 org-confirm-shell-link-not-regexp)
10824 (string-match
10825 org-confirm-shell-link-not-regexp cmd))
10826 (not org-confirm-shell-link-function)
10827 (funcall org-confirm-shell-link-function
10828 (format "Execute \"%s\" in shell? "
10829 (org-add-props cmd nil
10830 'face 'org-warning))))
10831 (progn
10832 (message "Executing %s" cmd)
10833 (shell-command cmd buf)
10834 (when (featurep 'midnight)
10835 (setq clean-buffer-list-kill-buffer-names
10836 (cons (buffer-name buf)
10837 clean-buffer-list-kill-buffer-names))))
10838 (user-error "Abort"))))
10839 ((equal type "elisp")
10840 (let ((cmd path))
10841 (if (or (and (org-string-nw-p
10842 org-confirm-elisp-link-not-regexp)
10843 (org-string-match-p
10844 org-confirm-elisp-link-not-regexp cmd))
10845 (not org-confirm-elisp-link-function)
10846 (funcall org-confirm-elisp-link-function
10847 (format "Execute \"%s\" as elisp? "
10848 (org-add-props cmd nil
10849 'face 'org-warning))))
10850 (message "%s => %s" cmd
10851 (if (eq (string-to-char cmd) ?\()
10852 (eval (read cmd))
10853 (call-interactively (read cmd))))
10854 (user-error "Abort"))))
10855 ((equal type "id")
10856 (require 'org-id)
10857 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10858 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10859 (unless (run-hook-with-args-until-success
10860 'org-open-link-functions path)
10861 (if (not arg) (org-mark-ring-push)
10862 (switch-to-buffer-other-window
10863 (org-get-buffer-for-internal-link (current-buffer))))
10864 (let ((destination
10865 (org-with-wide-buffer
10866 (if (equal type "radio")
10867 (org-search-radio-target
10868 (org-element-property :path link))
10869 (org-link-search
10870 (if (member type '("custom-id" "coderef"))
10871 (org-element-property :raw-link link)
10872 path)
10873 ;; Prevent fuzzy links from matching
10874 ;; themselves.
10875 (and (equal type "fuzzy")
10876 (+ 2 (org-element-property :begin link)))))
10877 (point))))
10878 (unless (and (<= (point-min) destination)
10879 (>= (point-max) destination))
10880 (widen))
10881 (goto-char destination))))
10882 (t (browse-url-at-point))))))
10883 ;; On a footnote reference or at a footnote definition's label.
10884 ((or (eq type 'footnote-reference)
10885 (and (eq type 'footnote-definition)
10886 (save-excursion
10887 ;; Do not validate action when point is on the
10888 ;; spaces right after the footnote label, in
10889 ;; order to be on par with behaviour on links.
10890 (skip-chars-forward " \t")
10891 (let ((begin
10892 (org-element-property :contents-begin context)))
10893 (if begin (< (point) begin)
10894 (= (org-element-property :post-affiliated context)
10895 (line-beginning-position)))))))
10896 (org-footnote-action))
10897 (t (user-error "No link found")))))
10898 (run-hook-with-args 'org-follow-link-hook)))
10900 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10901 "Offer links in the current entry and return the selected link.
10902 If there is only one link, return it.
10903 If NTH is an integer, return the NTH link found.
10904 If ZERO is a string, check also this string for a link, and if
10905 there is one, return it."
10906 (with-current-buffer buffer
10907 (save-excursion
10908 (save-restriction
10909 (widen)
10910 (goto-char marker)
10911 (let ((cnt ?0)
10912 have-zero end links link c)
10913 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10914 (push (match-string 0 zero) links)
10915 (setq cnt (1- cnt) have-zero t))
10916 (save-excursion
10917 (org-back-to-heading t)
10918 (setq end (save-excursion (outline-next-heading) (point)))
10919 (while (re-search-forward org-any-link-re end t)
10920 (push (match-string 0) links))
10921 (setq links (org-uniquify (reverse links))))
10922 (cond
10923 ((null links)
10924 (message "No links"))
10925 ((equal (length links) 1)
10926 (setq link (car links)))
10927 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10928 (setq link (nth (if have-zero nth (1- nth)) links)))
10929 (t ; we have to select a link
10930 (save-excursion
10931 (save-window-excursion
10932 (delete-other-windows)
10933 (with-output-to-temp-buffer "*Select Link*"
10934 (dolist (l links)
10935 (cond
10936 ((not (string-match org-bracket-link-regexp l))
10937 (princ (format "[%c] %s\n" (cl-incf cnt)
10938 (org-remove-angle-brackets l))))
10939 ((match-end 3)
10940 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10941 (match-string 3 l) (match-string 1 l))))
10942 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10943 (match-string 1 l)))))))
10944 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10945 (message "Select link to open, RET to open all:")
10946 (setq c (read-char-exclusive))
10947 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10948 (when (equal c ?q) (user-error "Abort"))
10949 (if (equal c ?\C-m)
10950 (setq link links)
10951 (setq nth (- c ?0))
10952 (when have-zero (setq nth (1+ nth)))
10953 (unless (and (integerp nth) (>= (length links) nth))
10954 (user-error "Invalid link selection"))
10955 (setq link (nth (1- nth) links)))))
10956 (cons link end))))))
10958 ;; TODO: These functions are deprecated since `org-open-at-point'
10959 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10960 (defun org-open-file-with-system (path)
10961 "Open file at PATH using the system way of opening it."
10962 (org-open-file path 'system))
10963 (defun org-open-file-with-emacs (path)
10964 "Open file at PATH in Emacs."
10965 (org-open-file path 'emacs))
10968 ;;; File search
10970 (defvar org-create-file-search-functions nil
10971 "List of functions to construct the right search string for a file link.
10972 These functions are called in turn with point at the location to
10973 which the link should point.
10975 A function in the hook should first test if it would like to
10976 handle this file type, for example by checking the `major-mode'
10977 or the file extension. If it decides not to handle this file, it
10978 should just return nil to give other functions a chance. If it
10979 does handle the file, it must return the search string to be used
10980 when following the link. The search string will be part of the
10981 file link, given after a double colon, and `org-open-at-point'
10982 will automatically search for it. If special measures must be
10983 taken to make the search successful, another function should be
10984 added to the companion hook `org-execute-file-search-functions',
10985 which see.
10987 A function in this hook may also use `setq' to set the variable
10988 `description' to provide a suggestion for the descriptive text to
10989 be used for this link when it gets inserted into an Org-mode
10990 buffer with \\[org-insert-link].")
10992 (defvar org-execute-file-search-functions nil
10993 "List of functions to execute a file search triggered by a link.
10995 Functions added to this hook must accept a single argument, the
10996 search string that was part of the file link, the part after the
10997 double colon. The function must first check if it would like to
10998 handle this search, for example by checking the `major-mode' or
10999 the file extension. If it decides not to handle this search, it
11000 should just return nil to give other functions a chance. If it
11001 does handle the search, it must return a non-nil value to keep
11002 other functions from trying.
11004 Each function can access the current prefix argument through the
11005 variable `current-prefix-arg'. Note that a single prefix is used
11006 to force opening a link in Emacs, so it may be good to only use a
11007 numeric or double prefix to guide the search function.
11009 In case this is needed, a function in this hook can also restore
11010 the window configuration before `org-open-at-point' was called using:
11012 \(set-window-configuration org-window-config-before-follow-link)")
11014 (defun org-search-radio-target (target)
11015 "Search a radio target matching TARGET in current buffer.
11016 White spaces are not significant."
11017 (let ((re (format "<<<%s>>>"
11018 (mapconcat #'regexp-quote
11019 (org-split-string target "[ \t\n]+")
11020 "[ \t]+\\(?:\n[ \t]*\\)?")))
11021 (origin (point)))
11022 (goto-char (point-min))
11023 (catch :radio-match
11024 (while (re-search-forward re nil t)
11025 (backward-char)
11026 (let ((object (org-element-context)))
11027 (when (eq (org-element-type object) 'radio-target)
11028 (goto-char (org-element-property :begin object))
11029 (org-show-context 'link-search)
11030 (throw :radio-match nil))))
11031 (goto-char origin)
11032 (user-error "No match for radio target: %s" target))))
11034 (defun org-link-search (s &optional avoid-pos stealth)
11035 "Search for a search string S.
11037 If S starts with \"#\", it triggers a custom ID search.
11039 If S is enclosed within parenthesis, it initiates a coderef
11040 search.
11042 If S is surrounded by forward slashes, it is interpreted as
11043 a regular expression. In Org mode files, this will create an
11044 `org-occur' sparse tree. In ordinary files, `occur' will be used
11045 to list matches. If the current buffer is in `dired-mode', grep
11046 will be used to search in all files.
11048 When AVOID-POS is given, ignore matches near that position.
11050 When optional argument STEALTH is non-nil, do not modify
11051 visibility around point, thus ignoring `org-show-context-detail'
11052 variable.
11054 Search is case-insensitive and ignores white spaces. Return type
11055 of matched result, with is either `dedicated' or `fuzzy'."
11056 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11057 (let* ((case-fold-search t)
11058 (origin (point))
11059 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11060 (words (org-split-string s "[ \t\n]+"))
11061 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11062 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11063 type)
11064 (cond
11065 ;; Check if there are any special search functions.
11066 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11067 ((eq (string-to-char s) ?#)
11068 ;; Look for a custom ID S if S starts with "#".
11069 (let* ((id (substring normalized 1))
11070 (match (org-find-property "CUSTOM_ID" id)))
11071 (if match (progn (goto-char match) (setf type 'dedicated))
11072 (error "No match for custom ID: %s" id))))
11073 ((string-match "\\`(\\(.*\\))\\'" normalized)
11074 ;; Look for coderef targets if S is enclosed within parenthesis.
11075 (let ((coderef (match-string-no-properties 1 normalized))
11076 (re (substring s-single-re 1 -1)))
11077 (goto-char (point-min))
11078 (catch :coderef-match
11079 (while (re-search-forward re nil t)
11080 (let ((element (org-element-at-point)))
11081 (when (and (memq (org-element-type element)
11082 '(example-block src-block))
11083 ;; Build proper regexp according to current
11084 ;; block's label format.
11085 (let ((label-fmt
11086 (regexp-quote
11087 (or (org-element-property :label-fmt element)
11088 org-coderef-label-format))))
11089 (save-excursion
11090 (beginning-of-line)
11091 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11092 (format label-fmt coderef))))))
11093 (setq type 'dedicated)
11094 (goto-char (match-beginning 1))
11095 (throw :coderef-match nil))))
11096 (goto-char origin)
11097 (error "No match for coderef: %s" coderef))))
11098 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11099 ;; Look for a regular expression.
11100 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11101 (match-string 1 s)))
11102 ;; Fuzzy links.
11104 (let ((starred (eq (string-to-char normalized) ?*)))
11105 (cond
11106 ;; Look for targets, only if not in a headline search.
11107 ((and (not starred)
11108 (let ((target (format "<<%s>>" s-multi-re)))
11109 (catch :target-match
11110 (goto-char (point-min))
11111 (while (re-search-forward target nil t)
11112 (backward-char)
11113 (let ((context (org-element-context)))
11114 (when (eq (org-element-type context) 'target)
11115 (setq type 'dedicated)
11116 (goto-char (org-element-property :begin context))
11117 (throw :target-match t))))
11118 nil))))
11119 ;; Look for elements named after S, only if not in a headline
11120 ;; search.
11121 ((and (not starred)
11122 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11123 (catch :name-match
11124 (goto-char (point-min))
11125 (while (re-search-forward name nil t)
11126 (let ((element (org-element-at-point)))
11127 (when (equal (org-split-string
11128 (org-element-property :name element)
11129 "[ \t]+")
11130 words)
11131 (setq type 'dedicated)
11132 (beginning-of-line)
11133 (throw :name-match t))))
11134 nil))))
11135 ;; Regular text search. Prefer headlines in Org mode
11136 ;; buffers.
11137 ((and (derived-mode-p 'org-mode)
11138 (let* ((wspace "[ \t]")
11139 (wspaceopt (concat wspace "*"))
11140 (cookie (concat "\\(?:"
11141 wspaceopt
11142 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11143 wspaceopt
11144 "\\)"))
11145 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11146 (re (concat
11147 org-outline-regexp-bol
11148 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11149 "\\(?:\\[#.\\][ \t]+\\)?"
11150 "\\(?:" org-comment-string "[ \t]+\\)?"
11151 sep "?"
11152 (let ((title (mapconcat #'regexp-quote
11153 words
11154 sep)))
11155 (if starred (substring title 1) title))
11156 sep "?"
11157 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11158 "[ \t]*$")))
11159 (goto-char (point-min))
11160 (re-search-forward re nil t)))
11161 (goto-char (match-beginning 0))
11162 (setq type 'dedicated))
11163 ;; Offer to create non-existent headline depending on
11164 ;; `org-link-search-must-match-exact-headline'.
11165 ((and (derived-mode-p 'org-mode)
11166 (not org-link-search-inhibit-query)
11167 (eq org-link-search-must-match-exact-headline 'query-to-create)
11168 (yes-or-no-p "No match - create this as a new heading? "))
11169 (goto-char (point-max))
11170 (unless (bolp) (newline))
11171 (org-insert-heading nil t t)
11172 (insert s "\n")
11173 (beginning-of-line 0))
11174 ;; Only headlines are looked after. No need to process
11175 ;; further: throw an error.
11176 ((and (derived-mode-p 'org-mode)
11177 (or starred org-link-search-must-match-exact-headline))
11178 (goto-char origin)
11179 (error "No match for fuzzy expression: %s" normalized))
11180 ;; Regular text search.
11181 ((catch :fuzzy-match
11182 (goto-char (point-min))
11183 (while (re-search-forward s-multi-re nil t)
11184 ;; Skip match if it contains AVOID-POS or it is included
11185 ;; in a link with a description but outside the
11186 ;; description.
11187 (unless (or (and avoid-pos
11188 (<= (match-beginning 0) avoid-pos)
11189 (> (match-end 0) avoid-pos))
11190 (and (save-match-data
11191 (org-in-regexp org-bracket-link-regexp))
11192 (match-beginning 3)
11193 (or (> (match-beginning 3) (point))
11194 (<= (match-end 3) (point)))
11195 (org-element-lineage
11196 (save-match-data (org-element-context))
11197 '(link) t)))
11198 (goto-char (match-beginning 0))
11199 (setq type 'fuzzy)
11200 (throw :fuzzy-match t)))
11201 nil))
11202 ;; All failed. Throw an error.
11203 (t (goto-char origin)
11204 (error "No match for fuzzy expression: %s" normalized))))))
11205 ;; Disclose surroundings of match, if appropriate.
11206 (when (and (derived-mode-p 'org-mode) (not stealth))
11207 (org-show-context 'link-search))
11208 type))
11210 (defun org-get-buffer-for-internal-link (buffer)
11211 "Return a buffer to be used for displaying the link target of internal links."
11212 (cond
11213 ((not org-display-internal-link-with-indirect-buffer)
11214 buffer)
11215 ((string-match "(Clone)$" (buffer-name buffer))
11216 (message "Buffer is already a clone, not making another one")
11217 ;; we also do not modify visibility in this case
11218 buffer)
11219 (t ; make a new indirect buffer for displaying the link
11220 (let* ((bn (buffer-name buffer))
11221 (ibn (concat bn "(Clone)"))
11222 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11223 (with-current-buffer ib (org-overview))
11224 ib))))
11226 (defun org-do-occur (regexp &optional cleanup)
11227 "Call the Emacs command `occur'.
11228 If CLEANUP is non-nil, remove the printout of the regular expression
11229 in the *Occur* buffer. This is useful if the regex is long and not useful
11230 to read."
11231 (occur regexp)
11232 (when cleanup
11233 (let ((cwin (selected-window)) win beg end)
11234 (when (setq win (get-buffer-window "*Occur*"))
11235 (select-window win))
11236 (goto-char (point-min))
11237 (when (re-search-forward "match[a-z]+" nil t)
11238 (setq beg (match-end 0))
11239 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11240 (setq end (1- (match-beginning 0)))))
11241 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11242 (goto-char (point-min))
11243 (select-window cwin))))
11245 ;;; The mark ring for links jumps
11247 (defvar org-mark-ring nil
11248 "Mark ring for positions before jumps in Org-mode.")
11249 (defvar org-mark-ring-last-goto nil
11250 "Last position in the mark ring used to go back.")
11251 ;; Fill and close the ring
11252 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11253 (dotimes (_ org-mark-ring-length)
11254 (push (make-marker) org-mark-ring))
11255 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11256 org-mark-ring)
11258 (defun org-mark-ring-push (&optional pos buffer)
11259 "Put the current position or POS into the mark ring and rotate it."
11260 (interactive)
11261 (setq pos (or pos (point)))
11262 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11263 (move-marker (car org-mark-ring)
11264 (or pos (point))
11265 (or buffer (current-buffer)))
11266 (message "%s"
11267 (substitute-command-keys
11268 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11270 (defun org-mark-ring-goto (&optional n)
11271 "Jump to the previous position in the mark ring.
11272 With prefix arg N, jump back that many stored positions. When
11273 called several times in succession, walk through the entire ring.
11274 Org-mode commands jumping to a different position in the current file,
11275 or to another Org-mode file, automatically push the old position
11276 onto the ring."
11277 (interactive "p")
11278 (let (p m)
11279 (if (eq last-command this-command)
11280 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11281 (setq p org-mark-ring))
11282 (setq org-mark-ring-last-goto p)
11283 (setq m (car p))
11284 (org-pop-to-buffer-same-window (marker-buffer m))
11285 (goto-char m)
11286 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11288 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11289 ;;; Emacs 24.4+
11290 (defun org-remove-angle-brackets (s)
11291 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11292 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11294 (defun org-add-angle-brackets (s)
11295 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11296 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11298 (defun org-remove-double-quotes (s)
11299 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11300 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11303 ;;; Following specific links
11305 (defvar org-agenda-buffer-tmp-name)
11306 (defvar org-agenda-start-on-weekday)
11307 (defun org-follow-timestamp-link ()
11308 "Open an agenda view for the time-stamp date/range at point."
11309 (cond
11310 ((org-at-date-range-p t)
11311 (let ((org-agenda-start-on-weekday)
11312 (t1 (match-string 1))
11313 (t2 (match-string 2)) tt1 tt2)
11314 (setq tt1 (time-to-days (org-time-string-to-time t1))
11315 tt2 (time-to-days (org-time-string-to-time t2)))
11316 (let ((org-agenda-buffer-tmp-name
11317 (format "*Org Agenda(a:%s)"
11318 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11319 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11320 ((org-at-timestamp-p t)
11321 (let ((org-agenda-buffer-tmp-name
11322 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11323 (org-agenda-list nil (time-to-days (org-time-string-to-time
11324 (substring (match-string 1) 0 10)))
11325 1)))
11326 (t (error "This should not happen"))))
11329 ;;; Following file links
11330 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11331 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11332 (declare-function mailcap-mime-info
11333 "mailcap" (string &optional request no-decode))
11334 (defvar org-wait nil)
11335 (defun org-open-file (path &optional in-emacs line search)
11336 "Open the file at PATH.
11337 First, this expands any special file name abbreviations. Then the
11338 configuration variable `org-file-apps' is checked if it contains an
11339 entry for this file type, and if yes, the corresponding command is launched.
11341 If no application is found, Emacs simply visits the file.
11343 With optional prefix argument IN-EMACS, Emacs will visit the file.
11344 With a double \\[universal-argument] \\[universal-argument] \
11345 prefix arg, Org tries to avoid opening in Emacs
11346 and to use an external application to visit the file.
11348 Optional LINE specifies a line to go to, optional SEARCH a string
11349 to search for. If LINE or SEARCH is given, the file will be
11350 opened in Emacs, unless an entry from org-file-apps that makes
11351 use of groups in a regexp matches.
11353 If you want to change the way frames are used when following a
11354 link, please customize `org-link-frame-setup'.
11356 If the file does not exist, an error is thrown."
11357 (let* ((file (if (equal path "")
11358 buffer-file-name
11359 (substitute-in-file-name (expand-file-name path))))
11360 (file-apps (append org-file-apps (org-default-apps)))
11361 (apps (cl-remove-if
11362 'org-file-apps-entry-match-against-dlink-p file-apps))
11363 (apps-dlink (cl-remove-if-not
11364 'org-file-apps-entry-match-against-dlink-p file-apps))
11365 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11366 (dirp (unless remp (file-directory-p file)))
11367 (file (if (and dirp org-open-directory-means-index-dot-org)
11368 (concat (file-name-as-directory file) "index.org")
11369 file))
11370 (a-m-a-p (assq 'auto-mode apps))
11371 (dfile (downcase file))
11372 ;; Reconstruct the original link from the PATH, LINE and
11373 ;; SEARCH args.
11374 (link (cond (line (concat file "::" (number-to-string line)))
11375 (search (concat file "::" search))
11376 (t file)))
11377 (dlink (downcase link))
11378 (old-buffer (current-buffer))
11379 (old-pos (point))
11380 (old-mode major-mode)
11381 (ext
11382 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11383 (match-string 1 dfile)))
11384 cmd link-match-data)
11385 (cond
11386 ((member in-emacs '((16) system))
11387 (setq cmd (cdr (assq 'system apps))))
11388 (in-emacs (setq cmd 'emacs))
11390 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11391 (and dirp (cdr (assq 'directory apps)))
11392 ;; First, try matching against apps-dlink if we
11393 ;; get a match here, store the match data for
11394 ;; later.
11395 (let ((match (assoc-default dlink apps-dlink
11396 'string-match)))
11397 (if match
11398 (progn (setq link-match-data (match-data))
11399 match)
11400 (progn (setq in-emacs (or in-emacs line search))
11401 nil))) ; if we have no match in apps-dlink,
11402 ; always open the file in emacs if line or search
11403 ; is given (for backwards compatibility)
11404 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11405 'string-match)
11406 (cdr (assoc ext apps))
11407 (cdr (assq t apps))))))
11408 (when (eq cmd 'system)
11409 (setq cmd (cdr (assoc 'system apps))))
11410 (when (eq cmd 'default)
11411 (setq cmd (cdr (assoc t apps))))
11412 (when (eq cmd 'mailcap)
11413 (require 'mailcap)
11414 (mailcap-parse-mailcaps)
11415 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11416 (command (mailcap-mime-info mime-type)))
11417 (if (stringp command)
11418 (setq cmd command)
11419 (setq cmd 'emacs))))
11420 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11421 (not (file-exists-p file))
11422 (not org-open-non-existing-files))
11423 (user-error "No such file: %s" file))
11424 (cond
11425 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11426 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11427 (while (string-match "['\"]%s['\"]" cmd)
11428 (setq cmd (replace-match "%s" t t cmd)))
11429 (while (string-match "%s" cmd)
11430 (setq cmd (replace-match
11431 (save-match-data
11432 (shell-quote-argument
11433 (convert-standard-filename file)))
11434 t t cmd)))
11436 ;; Replace "%1", "%2" etc. in command with group matches from regex
11437 (save-match-data
11438 (let ((match-index 1)
11439 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11440 (set-match-data link-match-data)
11441 (while (<= match-index number-of-groups)
11442 (let ((regex (concat "%" (number-to-string match-index)))
11443 (replace-with (match-string match-index dlink)))
11444 (while (string-match regex cmd)
11445 (setq cmd (replace-match replace-with t t cmd))))
11446 (setq match-index (+ match-index 1)))))
11448 (save-window-excursion
11449 (message "Running %s...done" cmd)
11450 (start-process-shell-command cmd nil cmd)
11451 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11452 ((or (stringp cmd)
11453 (eq cmd 'emacs))
11454 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11455 (widen)
11456 (cond (line (org-goto-line line)
11457 (when (derived-mode-p 'org-mode) (org-reveal)))
11458 (search (org-link-search search))))
11459 ((functionp cmd)
11460 (save-match-data
11461 (set-match-data link-match-data)
11462 (condition-case nil
11463 (funcall cmd file link)
11464 ;; FIXME: Remove this check when most default installations
11465 ;; of Emacs have at least Org 9.0.
11466 ((debug wrong-number-of-arguments wrong-type-argument
11467 invalid-function)
11468 (user-error "Please see Org News for version 9.0 about \
11469 `org-file-apps'--Lisp error: %S" cmd)))))
11470 ((consp cmd)
11471 ;; FIXME: Remove this check when most default installations of
11472 ;; Emacs have at least Org 9.0.
11473 ;; Heads-up instead of silently fall back to
11474 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11475 ;; with sexp instead of a function for `cmd'.
11476 (user-error "Please see Org News for version 9.0 about \
11477 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11478 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11479 (and (derived-mode-p 'org-mode)
11480 (eq old-mode 'org-mode)
11481 (or (not (eq old-buffer (current-buffer)))
11482 (not (eq old-pos (point))))
11483 (org-mark-ring-push old-pos old-buffer))))
11485 (defun org-file-apps-entry-match-against-dlink-p (entry)
11486 "This function returns non-nil if `entry' uses a regular
11487 expression which should be matched against the whole link by
11488 org-open-file.
11490 It assumes that is the case when the entry uses a regular
11491 expression which has at least one grouping construct and the
11492 action is either a lisp form or a command string containing
11493 `%1', i.e. using at least one subexpression match as a
11494 parameter."
11495 (let ((selector (car entry))
11496 (action (cdr entry)))
11497 (if (stringp selector)
11498 (and (> (regexp-opt-depth selector) 0)
11499 (or (and (stringp action)
11500 (string-match "%[0-9]" action))
11501 (consp action)))
11502 nil)))
11504 (defun org-default-apps ()
11505 "Return the default applications for this operating system."
11506 (cond
11507 ((eq system-type 'darwin)
11508 org-file-apps-defaults-macosx)
11509 ((eq system-type 'windows-nt)
11510 org-file-apps-defaults-windowsnt)
11511 (t org-file-apps-defaults-gnu)))
11513 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11514 "Convert extensions to regular expressions in the cars of LIST.
11515 Also, weed out any non-string entries, because the return value is used
11516 only for regexp matching.
11517 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11518 point to the symbol `emacs', indicating that the file should
11519 be opened in Emacs."
11520 (append
11521 (delq nil
11522 (mapcar (lambda (x)
11523 (unless (not (stringp (car x)))
11524 (if (string-match "\\W" (car x))
11526 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11527 list))
11528 (when add-auto-mode
11529 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11531 (defvar ange-ftp-name-format)
11532 (defun org-file-remote-p (file)
11533 "Test whether FILE specifies a location on a remote system.
11534 Return non-nil if the location is indeed remote.
11536 For example, the filename \"/user@host:/foo\" specifies a location
11537 on the system \"/user@host:\"."
11538 (cond ((fboundp 'file-remote-p)
11539 (file-remote-p file))
11540 ((fboundp 'tramp-handle-file-remote-p)
11541 (tramp-handle-file-remote-p file))
11542 ((and (boundp 'ange-ftp-name-format)
11543 (string-match (car ange-ftp-name-format) file))
11544 t)))
11547 ;;;; Refiling
11549 (defun org-get-org-file ()
11550 "Read a filename, with default directory `org-directory'."
11551 (let ((default (or org-default-notes-file remember-data-file)))
11552 (read-file-name (format "File name [%s]: " default)
11553 (file-name-as-directory org-directory)
11554 default)))
11556 (defun org-notes-order-reversed-p ()
11557 "Check if the current file should receive notes in reversed order."
11558 (cond
11559 ((not org-reverse-note-order) nil)
11560 ((eq t org-reverse-note-order) t)
11561 ((not (listp org-reverse-note-order)) nil)
11562 (t (catch 'exit
11563 (dolist (entry org-reverse-note-order)
11564 (when (string-match (car entry) buffer-file-name)
11565 (throw 'exit (cdr entry))))))))
11567 (defvar org-refile-target-table nil
11568 "The list of refile targets, created by `org-refile'.")
11570 (defvar org-agenda-new-buffers nil
11571 "Buffers created to visit agenda files.")
11573 (defvar org-refile-cache nil
11574 "Cache for refile targets.")
11576 (defvar org-refile-markers nil
11577 "All the markers used for caching refile locations.")
11579 (defun org-refile-marker (pos)
11580 "Get a new refile marker, but only if caching is in use."
11581 (if (not org-refile-use-cache)
11583 (let ((m (make-marker)))
11584 (move-marker m pos)
11585 (push m org-refile-markers)
11586 m)))
11588 (defun org-refile-cache-clear ()
11589 "Clear the refile cache and disable all the markers."
11590 (dolist (m org-refile-markers) (move-marker m nil))
11591 (setq org-refile-markers nil)
11592 (setq org-refile-cache nil)
11593 (message "Refile cache has been cleared"))
11595 (defun org-refile-cache-check-set (set)
11596 "Check if all the markers in the cache still have live buffers."
11597 (let (marker)
11598 (catch 'exit
11599 (while (and set (setq marker (nth 3 (pop set))))
11600 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11601 (when (and marker (null (marker-buffer marker)))
11602 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11603 (sit-for 3)
11604 (throw 'exit nil)))
11605 t)))
11607 (defun org-refile-cache-put (set &rest identifiers)
11608 "Push the refile targets SET into the cache, under IDENTIFIERS."
11609 (let* ((key (sha1 (prin1-to-string identifiers)))
11610 (entry (assoc key org-refile-cache)))
11611 (if entry
11612 (setcdr entry set)
11613 (push (cons key set) org-refile-cache))))
11615 (defun org-refile-cache-get (&rest identifiers)
11616 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11617 (cond
11618 ((not org-refile-cache) nil)
11619 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11621 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11622 org-refile-cache))))
11623 (and set (org-refile-cache-check-set set) set)))))
11625 (defvar org-outline-path-cache nil
11626 "Alist between buffer positions and outline paths.
11627 It value is an alist (POSITION . PATH) where POSITION is the
11628 buffer position at the beginning of an entry and PATH is a list
11629 of strings describing the outline path for that entry, in reverse
11630 order.")
11632 (defun org-refile-get-targets (&optional default-buffer)
11633 "Produce a table with refile targets."
11634 (let ((case-fold-search nil)
11635 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11636 (entries (or org-refile-targets '((nil . (:level . 1)))))
11637 targets tgs files desc descre)
11638 (message "Getting targets...")
11639 (with-current-buffer (or default-buffer (current-buffer))
11640 (dolist (entry entries)
11641 (setq files (car entry) desc (cdr entry))
11642 (cond
11643 ((null files) (setq files (list (current-buffer))))
11644 ((eq files 'org-agenda-files)
11645 (setq files (org-agenda-files 'unrestricted)))
11646 ((and (symbolp files) (fboundp files))
11647 (setq files (funcall files)))
11648 ((and (symbolp files) (boundp files))
11649 (setq files (symbol-value files))))
11650 (when (stringp files) (setq files (list files)))
11651 (cond
11652 ((eq (car desc) :tag)
11653 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11654 ((eq (car desc) :todo)
11655 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11656 ((eq (car desc) :regexp)
11657 (setq descre (cdr desc)))
11658 ((eq (car desc) :level)
11659 (setq descre (concat "^\\*\\{" (number-to-string
11660 (if org-odd-levels-only
11661 (1- (* 2 (cdr desc)))
11662 (cdr desc)))
11663 "\\}[ \t]")))
11664 ((eq (car desc) :maxlevel)
11665 (setq descre (concat "^\\*\\{1," (number-to-string
11666 (if org-odd-levels-only
11667 (1- (* 2 (cdr desc)))
11668 (cdr desc)))
11669 "\\}[ \t]")))
11670 (t (error "Bad refiling target description %s" desc)))
11671 (dolist (f files)
11672 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11674 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11675 (progn
11676 (when (bufferp f)
11677 (setq f (buffer-file-name (buffer-base-buffer f))))
11678 (setq f (and f (expand-file-name f)))
11679 (when (eq org-refile-use-outline-path 'file)
11680 (push (list (file-name-nondirectory f) f nil nil) tgs))
11681 (org-with-wide-buffer
11682 (goto-char (point-min))
11683 (setq org-outline-path-cache nil)
11684 (while (re-search-forward descre nil t)
11685 (beginning-of-line)
11686 (looking-at org-complex-heading-regexp)
11687 (let ((begin (point))
11688 (heading (match-string-no-properties 4)))
11689 (unless (or (and
11690 org-refile-target-verify-function
11691 (not
11692 (funcall org-refile-target-verify-function)))
11693 (not heading))
11694 (let ((re (format org-complex-heading-regexp-format
11695 (regexp-quote heading)))
11696 (target
11697 (if (not org-refile-use-outline-path) heading
11698 (mapconcat
11699 #'org-protect-slash
11700 (append
11701 (pcase org-refile-use-outline-path
11702 (`file (list (file-name-nondirectory
11703 (buffer-file-name
11704 (buffer-base-buffer)))))
11705 (`full-file-path
11706 (list (buffer-file-name
11707 (buffer-base-buffer))))
11708 (_ nil))
11709 (org-get-outline-path t t))
11710 "/"))))
11711 (push (list target f re (org-refile-marker (point)))
11712 tgs)))
11713 (when (= (point) begin)
11714 ;; Verification function has not moved point.
11715 (end-of-line)))))))
11716 (when org-refile-use-cache
11717 (org-refile-cache-put tgs (buffer-file-name) descre))
11718 (setq targets (append tgs targets))))))
11719 (message "Getting targets...done")
11720 (nreverse targets)))
11722 (defun org-protect-slash (s)
11723 (while (string-match "/" s)
11724 (setq s (replace-match "\\" t t s)))
11727 (defun org--get-outline-path-1 (&optional use-cache)
11728 "Return outline path to current headline.
11730 Outline path is a list of strings, in reverse order. When
11731 optional argument USE-CACHE is non-nil, make use of a cache. See
11732 `org-get-outline-path' for details.
11734 Assume buffer is widened and point is on a headline."
11735 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11736 (let ((p (point))
11737 (heading (progn
11738 (looking-at org-complex-heading-regexp)
11739 (if (not (match-end 4)) ""
11740 ;; Remove statistics cookies.
11741 (org-trim
11742 (org-link-display-format
11743 (replace-regexp-in-string
11744 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11745 (match-string-no-properties 4))))))))
11746 (if (org-up-heading-safe)
11747 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11748 (when use-cache
11749 (push (cons p path) org-outline-path-cache))
11750 path)
11751 ;; This is a new root node. Since we assume we are moving
11752 ;; forward, we can drop previous cache so as to limit number
11753 ;; of associations there.
11754 (let ((path (list heading)))
11755 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11756 path)))))
11758 (defun org-get-outline-path (&optional with-self use-cache)
11759 "Return the outline path to the current entry.
11761 An outline path is a list of ancestors for current headline, as
11762 a list of strings. Statistics cookies are removed and links are
11763 replaced with their description, if any, or their path otherwise.
11765 When optional argument WITH-SELF is non-nil, the path also
11766 includes the current headline.
11768 When optional argument USE-CACHE is non-nil, cache outline paths
11769 between calls to this function so as to avoid backtracking. This
11770 argument is useful when planning to find more than one outline
11771 path in the same document. In that case, there are two
11772 conditions to satisfy:
11773 - `org-outline-path-cache' is set to nil before starting the
11774 process;
11775 - outline paths are computed by increasing buffer positions."
11776 (org-with-wide-buffer
11777 (and (or (and with-self (org-back-to-heading t))
11778 (org-up-heading-safe))
11779 (reverse (org--get-outline-path-1 use-cache)))))
11781 (defun org-format-outline-path (path &optional width prefix separator)
11782 "Format the outline path PATH for display.
11783 WIDTH is the maximum number of characters that is available.
11784 PREFIX is a prefix to be included in the returned string,
11785 such as the file name.
11786 SEPARATOR is inserted between the different parts of the path,
11787 the default is \"/\"."
11788 (setq width (or width 79))
11789 (setq path (delq nil path))
11790 (unless (> width 0)
11791 (user-error "Argument `width' must be positive"))
11792 (setq separator (or separator "/"))
11793 (let* ((org-odd-levels-only nil)
11794 (fpath (concat
11795 prefix (and prefix path separator)
11796 (mapconcat
11797 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11798 (cl-loop for head in path
11799 for n from 0
11800 collect (org-add-props
11801 head nil 'face
11802 (nth (% n org-n-level-faces) org-level-faces)))
11803 separator))))
11804 (when (> (length fpath) width)
11805 (if (< width 7)
11806 ;; It's unlikely that `width' will be this small, but don't
11807 ;; waste characters by adding ".." if it is.
11808 (setq fpath (substring fpath 0 width))
11809 (setf (substring fpath (- width 2)) "..")))
11810 fpath))
11812 (defun org-display-outline-path (&optional file current separator just-return-string)
11813 "Display the current outline path in the echo area.
11815 If FILE is non-nil, prepend the output with the file name.
11816 If CURRENT is non-nil, append the current heading to the output.
11817 SEPARATOR is passed through to `org-format-outline-path'. It separates
11818 the different parts of the path and defaults to \"/\".
11819 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11820 (interactive "P")
11821 (let* (case-fold-search
11822 (bfn (buffer-file-name (buffer-base-buffer)))
11823 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11824 res)
11825 (when current (setq path (append path
11826 (save-excursion
11827 (org-back-to-heading t)
11828 (when (looking-at org-complex-heading-regexp)
11829 (list (match-string 4)))))))
11830 (setq res
11831 (org-format-outline-path
11832 path
11833 (1- (frame-width))
11834 (and file bfn (concat (file-name-nondirectory bfn) separator))
11835 separator))
11836 (if just-return-string
11837 (org-no-properties res)
11838 (org-unlogged-message "%s" res))))
11840 (defvar org-refile-history nil
11841 "History for refiling operations.")
11843 (defvar org-after-refile-insert-hook nil
11844 "Hook run after `org-refile' has inserted its stuff at the new location.
11845 Note that this is still *before* the stuff will be removed from
11846 the *old* location.")
11848 (defvar org-capture-last-stored-marker)
11849 (defvar org-refile-keep nil
11850 "Non-nil means `org-refile' will copy instead of refile.")
11852 (defun org-copy ()
11853 "Like `org-refile', but copy."
11854 (interactive)
11855 (let ((org-refile-keep t))
11856 (funcall 'org-refile nil nil nil "Copy")))
11858 (defun org-refile (&optional arg default-buffer rfloc msg)
11859 "Move the entry or entries at point to another heading.
11860 The list of target headings is compiled using the information in
11861 `org-refile-targets', which see.
11863 At the target location, the entry is filed as a subitem of the
11864 target heading. Depending on `org-reverse-note-order', the new
11865 subitem will either be the first or the last subitem.
11867 If there is an active region, all entries in that region will be
11868 refiled. However, the region must fulfill the requirement that
11869 the first heading sets the top-level of the moved text.
11871 With prefix arg ARG, the command will only visit the target
11872 location and not actually move anything.
11874 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11875 refiling operation has put the subtree.
11877 With a numeric prefix argument of `2', refile to the running clock.
11879 With a numeric prefix argument of `3', emulate `org-refile-keep'
11880 being set to t and copy to the target location, don't move it.
11881 Beware that keeping refiled entries may result in duplicated ID
11882 properties.
11884 RFLOC can be a refile location obtained in a different way.
11886 MSG is a string to replace \"Refile\" in the default prompt with
11887 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11889 See also `org-refile-use-outline-path'.
11891 If you are using target caching (see `org-refile-use-cache'), you
11892 have to clear the target cache in order to find new targets.
11893 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11894 prefix argument (`C-u C-u C-u C-c C-w')."
11895 (interactive "P")
11896 (if (member arg '(0 (64)))
11897 (org-refile-cache-clear)
11898 (let* ((actionmsg (cond (msg msg)
11899 ((equal arg 3) "Refile (and keep)")
11900 (t "Refile")))
11901 (regionp (org-region-active-p))
11902 (region-start (and regionp (region-beginning)))
11903 (region-end (and regionp (region-end)))
11904 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11905 pos it nbuf file level reversed)
11906 (setq last-command nil)
11907 (when regionp
11908 (goto-char region-start)
11909 (or (bolp) (goto-char (point-at-bol)))
11910 (setq region-start (point))
11911 (unless (or (org-kill-is-subtree-p
11912 (buffer-substring region-start region-end))
11913 (prog1 org-refile-active-region-within-subtree
11914 (let ((s (point-at-eol)))
11915 (org-toggle-heading)
11916 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11917 (user-error "The region is not a (sequence of) subtree(s)")))
11918 (if (equal arg '(16))
11919 (org-refile-goto-last-stored)
11920 (when (or
11921 (and (equal arg 2)
11922 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11923 (prog1
11924 (setq it (list (or org-clock-heading "running clock")
11925 (buffer-file-name
11926 (marker-buffer org-clock-hd-marker))
11928 (marker-position org-clock-hd-marker)))
11929 (setq arg nil)))
11930 (setq it
11931 (or rfloc
11932 (let (heading-text)
11933 (save-excursion
11934 (unless (and arg (listp arg))
11935 (org-back-to-heading t)
11936 (setq heading-text
11937 (replace-regexp-in-string
11938 org-bracket-link-regexp
11939 "\\3"
11940 (nth 4 (org-heading-components)))))
11941 (org-refile-get-location
11942 (cond ((and arg (listp arg)) "Goto")
11943 (regionp (concat actionmsg " region to"))
11944 (t (concat actionmsg " subtree \""
11945 heading-text "\" to")))
11946 default-buffer
11947 (and (not (equal '(4) arg))
11948 org-refile-allow-creating-parent-nodes)))))))
11949 (setq file (nth 1 it)
11950 pos (nth 3 it))
11951 (when (and (not arg)
11953 (equal (buffer-file-name) file)
11954 (if regionp
11955 (and (>= pos region-start)
11956 (<= pos region-end))
11957 (and (>= pos (point))
11958 (< pos (save-excursion
11959 (org-end-of-subtree t t))))))
11960 (error "Cannot refile to position inside the tree or region"))
11961 (setq nbuf (or (find-buffer-visiting file)
11962 (find-file-noselect file)))
11963 (if (and arg (not (equal arg 3)))
11964 (progn
11965 (org-pop-to-buffer-same-window nbuf)
11966 (goto-char pos)
11967 (org-show-context 'org-goto))
11968 (if regionp
11969 (progn
11970 (org-kill-new (buffer-substring region-start region-end))
11971 (org-save-markers-in-region region-start region-end))
11972 (org-copy-subtree 1 nil t))
11973 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11974 (find-file-noselect file)))
11975 (setq reversed (org-notes-order-reversed-p))
11976 (save-excursion
11977 (save-restriction
11978 (widen)
11979 (if pos
11980 (progn
11981 (goto-char pos)
11982 (looking-at org-outline-regexp)
11983 (setq level (org-get-valid-level (funcall outline-level) 1))
11984 (goto-char
11985 (if reversed
11986 (or (outline-next-heading) (point-max))
11987 (or (save-excursion (org-get-next-sibling))
11988 (org-end-of-subtree t t)
11989 (point-max)))))
11990 (setq level 1)
11991 (if (not reversed)
11992 (goto-char (point-max))
11993 (goto-char (point-min))
11994 (or (outline-next-heading) (goto-char (point-max)))))
11995 (unless (bolp) (newline))
11996 (org-paste-subtree level nil nil t)
11997 (when org-log-refile
11998 (org-add-log-setup 'refile nil nil org-log-refile)
11999 (unless (eq org-log-refile 'note)
12000 (save-excursion (org-add-log-note))))
12001 (and org-auto-align-tags
12002 (let ((org-loop-over-headlines-in-active-region nil))
12003 (org-set-tags nil t)))
12004 (let ((bookmark-name (plist-get org-bookmark-names-plist
12005 :last-refile)))
12006 (when bookmark-name
12007 (with-demoted-errors
12008 (bookmark-set bookmark-name))))
12009 ;; If we are refiling for capture, make sure that the
12010 ;; last-capture pointers point here
12011 (when (org-bound-and-true-p org-capture-is-refiling)
12012 (let ((bookmark-name (plist-get org-bookmark-names-plist
12013 :last-capture-marker)))
12014 (when bookmark-name
12015 (with-demoted-errors
12016 (bookmark-set bookmark-name))))
12017 (move-marker org-capture-last-stored-marker (point)))
12018 (when (fboundp 'deactivate-mark) (deactivate-mark))
12019 (run-hooks 'org-after-refile-insert-hook))))
12020 (unless org-refile-keep
12021 (if regionp
12022 (delete-region (point) (+ (point) (- region-end region-start)))
12023 (delete-region
12024 (and (org-back-to-heading t) (point))
12025 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12026 (when (featurep 'org-inlinetask)
12027 (org-inlinetask-remove-END-maybe))
12028 (setq org-markers-to-move nil)
12029 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12031 (defun org-refile-goto-last-stored ()
12032 "Go to the location where the last refile was stored."
12033 (interactive)
12034 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12035 (message "This is the location of the last refile"))
12037 (defun org-refile--get-location (refloc tbl)
12038 "When user refile to REFLOC, find the associated target in TBL.
12039 Also check `org-refile-target-table'."
12040 (car (delq
12042 (mapcar
12043 (lambda (r) (or (assoc r tbl)
12044 (assoc r org-refile-target-table)))
12045 (list (replace-regexp-in-string "/$" "" refloc)
12046 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12048 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12049 "Prompt the user for a refile location, using PROMPT.
12050 PROMPT should not be suffixed with a colon and a space, because
12051 this function appends the default value from
12052 `org-refile-history' automatically, if that is not empty."
12053 (let ((org-refile-targets org-refile-targets)
12054 (org-refile-use-outline-path org-refile-use-outline-path))
12055 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12056 (unless org-refile-target-table
12057 (user-error "No refile targets"))
12058 (let* ((cbuf (current-buffer))
12059 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12060 (cfunc (if (and org-refile-use-outline-path
12061 org-outline-path-complete-in-steps)
12062 #'org-olpath-completing-read
12063 #'completing-read))
12064 (extra (if org-refile-use-outline-path "/" ""))
12065 (cbnex (concat (buffer-name) extra))
12066 (filename (and cfn (expand-file-name cfn)))
12067 (tbl (mapcar
12068 (lambda (x)
12069 (if (and (not (member org-refile-use-outline-path
12070 '(file full-file-path)))
12071 (not (equal filename (nth 1 x))))
12072 (cons (concat (car x) extra " ("
12073 (file-name-nondirectory (nth 1 x)) ")")
12074 (cdr x))
12075 (cons (concat (car x) extra) (cdr x))))
12076 org-refile-target-table))
12077 (completion-ignore-case t)
12078 cdef
12079 (prompt (concat prompt
12080 (or (and (car org-refile-history)
12081 (concat " (default " (car org-refile-history) ")"))
12082 (and (assoc cbnex tbl) (setq cdef cbnex)
12083 (concat " (default " cbnex ")"))) ": "))
12084 pa answ parent-target child parent old-hist)
12085 (setq old-hist org-refile-history)
12086 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12087 nil 'org-refile-history (or cdef (car org-refile-history))))
12088 (if (setq pa (org-refile--get-location answ tbl))
12089 (progn
12090 (org-refile-check-position pa)
12091 (when (or (not org-refile-history)
12092 (not (eq old-hist org-refile-history))
12093 (not (equal (car pa) (car org-refile-history))))
12094 (setq org-refile-history
12095 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12096 org-refile-history
12097 (cdr org-refile-history))))
12098 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12099 (pop org-refile-history)))
12101 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12102 (progn
12103 (setq parent (match-string 1 answ)
12104 child (match-string 2 answ))
12105 (setq parent-target (org-refile--get-location parent tbl))
12106 (when (and parent-target
12107 (or (eq new-nodes t)
12108 (and (eq new-nodes 'confirm)
12109 (y-or-n-p (format "Create new node \"%s\"? "
12110 child)))))
12111 (org-refile-new-child parent-target child)))
12112 (user-error "Invalid target location")))))
12114 (declare-function org-string-nw-p "org-macs" (s))
12115 (defun org-refile-check-position (refile-pointer)
12116 "Check if the refile pointer matches the headline to which it points."
12117 (let* ((file (nth 1 refile-pointer))
12118 (re (nth 2 refile-pointer))
12119 (pos (nth 3 refile-pointer))
12120 buffer)
12121 (if (and (not (markerp pos)) (not file))
12122 (user-error "Please indicate a target file in the refile path")
12123 (when (org-string-nw-p re)
12124 (setq buffer (if (markerp pos)
12125 (marker-buffer pos)
12126 (or (find-buffer-visiting file)
12127 (find-file-noselect file))))
12128 (with-current-buffer buffer
12129 (save-excursion
12130 (save-restriction
12131 (widen)
12132 (goto-char pos)
12133 (beginning-of-line 1)
12134 (unless (looking-at-p re)
12135 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12137 (defun org-refile-new-child (parent-target child)
12138 "Use refile target PARENT-TARGET to add new CHILD below it."
12139 (unless parent-target
12140 (error "Cannot find parent for new node"))
12141 (let ((file (nth 1 parent-target))
12142 (pos (nth 3 parent-target))
12143 level)
12144 (with-current-buffer (or (find-buffer-visiting file)
12145 (find-file-noselect file))
12146 (save-excursion
12147 (save-restriction
12148 (widen)
12149 (if pos
12150 (goto-char pos)
12151 (goto-char (point-max))
12152 (unless (bolp) (newline)))
12153 (when (looking-at org-outline-regexp)
12154 (setq level (funcall outline-level))
12155 (org-end-of-subtree t t))
12156 (org-back-over-empty-lines)
12157 (insert "\n" (make-string
12158 (if pos (org-get-valid-level level 1) 1) ?*)
12159 " " child "\n")
12160 (beginning-of-line 0)
12161 (list (concat (car parent-target) "/" child) file "" (point)))))))
12163 (defun org-olpath-completing-read (prompt collection &rest args)
12164 "Read an outline path like a file name."
12165 (let ((thetable collection))
12166 (apply #'completing-read
12167 prompt
12168 (lambda (string predicate &optional flag)
12169 (cond
12170 ((eq flag nil) (try-completion string thetable))
12171 ((eq flag t)
12172 (let ((l (length string)))
12173 (mapcar (lambda (x)
12174 (let ((r (substring x l))
12175 (f (if (string-match " ([^)]*)$" x)
12176 (match-string 0 x)
12177 "")))
12178 (if (string-match "/" r)
12179 (concat string (substring r 0 (match-end 0)) f)
12180 x)))
12181 (all-completions string thetable predicate))))
12182 ;; Exact match?
12183 ((eq flag 'lambda) (assoc string thetable))))
12184 args)))
12186 ;;;; Dynamic blocks
12188 (defun org-find-dblock (name)
12189 "Find the first dynamic block with name NAME in the buffer.
12190 If not found, stay at current position and return nil."
12191 (let ((case-fold-search t) pos)
12192 (save-excursion
12193 (goto-char (point-min))
12194 (setq pos (and (re-search-forward
12195 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12196 (match-beginning 0))))
12197 (when pos (goto-char pos))
12198 pos))
12200 (defun org-create-dblock (plist)
12201 "Create a dynamic block section, with parameters taken from PLIST.
12202 PLIST must contain a :name entry which is used as the name of the block."
12203 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12204 (end-of-line 1)
12205 (newline))
12206 (let ((col (current-column))
12207 (name (plist-get plist :name)))
12208 (insert "#+BEGIN: " name)
12209 (while plist
12210 (if (eq (car plist) :name)
12211 (setq plist (cddr plist))
12212 (insert " " (prin1-to-string (pop plist)))))
12213 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12214 (beginning-of-line -2)))
12216 (defun org-prepare-dblock ()
12217 "Prepare dynamic block for refresh.
12218 This empties the block, puts the cursor at the insert position and returns
12219 the property list including an extra property :name with the block name."
12220 (unless (looking-at org-dblock-start-re)
12221 (user-error "Not at a dynamic block"))
12222 (let* ((begdel (1+ (match-end 0)))
12223 (name (org-no-properties (match-string 1)))
12224 (params (append (list :name name)
12225 (read (concat "(" (match-string 3) ")")))))
12226 (save-excursion
12227 (beginning-of-line 1)
12228 (skip-chars-forward " \t")
12229 (setq params (plist-put params :indentation-column (current-column))))
12230 (unless (re-search-forward org-dblock-end-re nil t)
12231 (error "Dynamic block not terminated"))
12232 (setq params
12233 (append params
12234 (list :content (buffer-substring
12235 begdel (match-beginning 0)))))
12236 (delete-region begdel (match-beginning 0))
12237 (goto-char begdel)
12238 (open-line 1)
12239 params))
12241 (defun org-map-dblocks (&optional command)
12242 "Apply COMMAND to all dynamic blocks in the current buffer.
12243 If COMMAND is not given, use `org-update-dblock'."
12244 (let ((cmd (or command 'org-update-dblock)))
12245 (save-excursion
12246 (goto-char (point-min))
12247 (while (re-search-forward org-dblock-start-re nil t)
12248 (goto-char (match-beginning 0))
12249 (save-excursion
12250 (condition-case nil
12251 (funcall cmd)
12252 (error (message "Error during update of dynamic block"))))
12253 (unless (re-search-forward org-dblock-end-re nil t)
12254 (error "Dynamic block not terminated"))))))
12256 (defun org-dblock-update (&optional arg)
12257 "User command for updating dynamic blocks.
12258 Update the dynamic block at point. With prefix ARG, update all dynamic
12259 blocks in the buffer."
12260 (interactive "P")
12261 (if arg
12262 (org-update-all-dblocks)
12263 (or (looking-at org-dblock-start-re)
12264 (org-beginning-of-dblock))
12265 (org-update-dblock)))
12267 (defun org-update-dblock ()
12268 "Update the dynamic block at point.
12269 This means to empty the block, parse for parameters and then call
12270 the correct writing function."
12271 (interactive)
12272 (save-excursion
12273 (let* ((win (selected-window))
12274 (pos (point))
12275 (line (org-current-line))
12276 (params (org-prepare-dblock))
12277 (name (plist-get params :name))
12278 (indent (plist-get params :indentation-column))
12279 (cmd (intern (concat "org-dblock-write:" name))))
12280 (message "Updating dynamic block `%s' at line %d..." name line)
12281 (funcall cmd params)
12282 (message "Updating dynamic block `%s' at line %d...done" name line)
12283 (goto-char pos)
12284 (when (and indent (> indent 0))
12285 (setq indent (make-string indent ?\ ))
12286 (save-excursion
12287 (select-window win)
12288 (org-beginning-of-dblock)
12289 (forward-line 1)
12290 (while (not (looking-at org-dblock-end-re))
12291 (insert indent)
12292 (beginning-of-line 2))
12293 (when (looking-at org-dblock-end-re)
12294 (and (looking-at "[ \t]+")
12295 (replace-match ""))
12296 (insert indent)))))))
12298 (defun org-beginning-of-dblock ()
12299 "Find the beginning of the dynamic block at point.
12300 Error if there is no such block at point."
12301 (let ((pos (point))
12302 beg)
12303 (end-of-line 1)
12304 (if (and (re-search-backward org-dblock-start-re nil t)
12305 (setq beg (match-beginning 0))
12306 (re-search-forward org-dblock-end-re nil t)
12307 (> (match-end 0) pos))
12308 (goto-char beg)
12309 (goto-char pos)
12310 (error "Not in a dynamic block"))))
12312 (defun org-update-all-dblocks ()
12313 "Update all dynamic blocks in the buffer.
12314 This function can be used in a hook."
12315 (interactive)
12316 (when (derived-mode-p 'org-mode)
12317 (org-map-dblocks 'org-update-dblock)))
12320 ;;;; Completion
12322 (declare-function org-export-backend-options "ox" (cl-x) t)
12323 (defun org-get-export-keywords ()
12324 "Return a list of all currently understood export keywords.
12325 Export keywords include options, block names, attributes and
12326 keywords relative to each registered export back-end."
12327 (let (keywords)
12328 (dolist (backend
12329 (org-bound-and-true-p org-export-registered-backends)
12330 (delq nil keywords))
12331 ;; Back-end name (for keywords, like #+LATEX:)
12332 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12333 (dolist (option-entry (org-export-backend-options backend))
12334 ;; Back-end options.
12335 (push (nth 1 option-entry) keywords)))))
12337 (defconst org-options-keywords
12338 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12339 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12340 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12341 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12342 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12344 (defcustom org-structure-template-alist
12345 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12346 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12347 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12348 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12349 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12350 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12351 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12352 ("L" "#+LaTeX: ")
12353 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12354 ("H" "#+HTML: ")
12355 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12356 ("A" "#+ASCII: ")
12357 ("i" "#+INDEX: ?")
12358 ("I" "#+INCLUDE: %file ?"))
12359 "Structure completion elements.
12360 This is a list of abbreviation keys and values. The value gets inserted
12361 if you type `<' followed by the key and then press the completion key,
12362 usually `TAB'. %file will be replaced by a file name after prompting
12363 for the file using completion. The cursor will be placed at the position
12364 of the `?' in the template.
12365 There are two templates for each key, the first uses the original Org syntax,
12366 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12367 the default when the /org-mtags.el/ module has been loaded. See also the
12368 variable `org-mtags-prefer-muse-templates'."
12369 :group 'org-completion
12370 :type '(repeat
12371 (list
12372 (string :tag "Key")
12373 (string :tag "Template")))
12374 :version "25.1"
12375 :package-version '(Org . "8.3"))
12377 (defun org-try-structure-completion ()
12378 "Try to complete a structure template before point.
12379 This looks for strings like \"<e\" on an otherwise empty line and
12380 expands them."
12381 (let ((l (buffer-substring (point-at-bol) (point)))
12383 (when (and (looking-at "[ \t]*$")
12384 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12385 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12386 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12387 (match-beginning 1)) a)
12388 t)))
12390 (defun org-complete-expand-structure-template (start cell)
12391 "Expand a structure template."
12392 (let ((rpl (nth 1 cell))
12393 (ind ""))
12394 (delete-region start (point))
12395 (when (string-match "\\`[ \t]*#\\+" rpl)
12396 (cond
12397 ((bolp))
12398 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12399 (setq ind (buffer-substring (point-at-bol) (point))))
12400 (t (newline))))
12401 (setq start (point))
12402 (when (string-match "%file" rpl)
12403 (setq rpl (replace-match
12404 (concat
12405 "\""
12406 (save-match-data
12407 (abbreviate-file-name (read-file-name "Include file: ")))
12408 "\"")
12409 t t rpl)))
12410 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12411 (concat "\n" ind)))
12412 (insert rpl)
12413 (when (re-search-backward "\\?" start t) (delete-char 1))))
12415 ;;;; TODO, DEADLINE, Comments
12417 (defun org-toggle-comment ()
12418 "Change the COMMENT state of an entry."
12419 (interactive)
12420 (save-excursion
12421 (org-back-to-heading)
12422 (looking-at org-complex-heading-regexp)
12423 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12424 (skip-chars-forward " \t")
12425 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12426 (if (org-in-commented-heading-p t)
12427 (delete-region (point)
12428 (progn (search-forward " " (line-end-position) 'move)
12429 (skip-chars-forward " \t")
12430 (point)))
12431 (insert org-comment-string)
12432 (unless (eolp) (insert " ")))))
12434 (defvar org-last-todo-state-is-todo nil
12435 "This is non-nil when the last TODO state change led to a TODO state.
12436 If the last change removed the TODO tag or switched to DONE, then
12437 this is nil.")
12439 (defvar org-setting-tags nil) ; dynamically skipped
12441 (defvar org-todo-setup-filter-hook nil
12442 "Hook for functions that pre-filter todo specs.
12443 Each function takes a todo spec and returns either nil or the spec
12444 transformed into canonical form." )
12446 (defvar org-todo-get-default-hook nil
12447 "Hook for functions that get a default item for todo.
12448 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12449 nil or a string to be used for the todo mark." )
12451 (defvar org-agenda-headline-snapshot-before-repeat)
12453 (defun org-current-effective-time ()
12454 "Return current time adjusted for `org-extend-today-until' variable."
12455 (let* ((ct (org-current-time))
12456 (dct (decode-time ct))
12457 (ct1
12458 (cond
12459 (org-use-last-clock-out-time-as-effective-time
12460 (or (org-clock-get-last-clock-out-time) ct))
12461 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12462 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12463 (t ct))))
12464 ct1))
12466 (defun org-todo-yesterday (&optional arg)
12467 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12468 (interactive "P")
12469 (if (eq major-mode 'org-agenda-mode)
12470 (apply 'org-agenda-todo-yesterday arg)
12471 (let* ((org-use-effective-time t)
12472 (hour (nth 2 (decode-time (org-current-time))))
12473 (org-extend-today-until (1+ hour)))
12474 (org-todo arg))))
12476 (defvar org-block-entry-blocking ""
12477 "First entry preventing the TODO state change.")
12479 (defun org-cancel-repeater ()
12480 "Cancel a repeater by setting its numeric value to zero."
12481 (interactive)
12482 (save-excursion
12483 (org-back-to-heading t)
12484 (let ((bound1 (point))
12485 (bound0 (save-excursion (outline-next-heading) (point))))
12486 (when (and (re-search-forward
12487 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12488 org-deadline-time-regexp "\\)\\|\\("
12489 org-ts-regexp "\\)")
12490 bound0 t)
12491 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12492 bound1 t))
12493 (replace-match "0" t nil nil 1)))))
12495 (defvar org-state) ;; dynamically scoped into this function
12496 (defun org-todo (&optional arg)
12497 "Change the TODO state of an item.
12498 The state of an item is given by a keyword at the start of the heading,
12499 like
12500 *** TODO Write paper
12501 *** DONE Call mom
12503 The different keywords are specified in the variable `org-todo-keywords'.
12504 By default the available states are \"TODO\" and \"DONE\".
12505 So for this example: when the item starts with TODO, it is changed to DONE.
12506 When it starts with DONE, the DONE is removed. And when neither TODO nor
12507 DONE are present, add TODO at the beginning of the heading.
12509 With \\[universal-argument] prefix arg, use completion to determine the new \
12510 state.
12511 With numeric prefix arg, switch to that state.
12512 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12513 keywords (nextset).
12514 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12515 With a numeric prefix arg of 0, inhibit note taking for the change.
12516 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12518 When called through ELisp, arg is also interpreted in the following way:
12519 `none' -> empty state
12520 \"\"(empty string) -> switch to empty state
12521 `done' -> switch to DONE
12522 `nextset' -> switch to the next set of keywords
12523 `previousset' -> switch to the previous set of keywords
12524 \"WAITING\" -> switch to the specified keyword, but only if it
12525 really is a member of `org-todo-keywords'."
12526 (interactive "P")
12527 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12528 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12529 'region-start-level 'region))
12530 org-loop-over-headlines-in-active-region)
12531 (org-map-entries
12532 `(org-todo ,arg)
12533 org-loop-over-headlines-in-active-region
12534 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12535 (when (equal arg '(16)) (setq arg 'nextset))
12536 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12537 (let ((org-blocker-hook org-blocker-hook)
12538 commentp
12539 case-fold-search)
12540 (when (equal arg '(64))
12541 (setq arg nil org-blocker-hook nil))
12542 (when (and org-blocker-hook
12543 (or org-inhibit-blocking
12544 (org-entry-get nil "NOBLOCKING")))
12545 (setq org-blocker-hook nil))
12546 (save-excursion
12547 (catch 'exit
12548 (org-back-to-heading t)
12549 (when (org-in-commented-heading-p t)
12550 (org-toggle-comment)
12551 (setq commentp t))
12552 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12553 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12554 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12555 (let* ((match-data (match-data))
12556 (startpos (point-at-bol))
12557 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12558 (org-log-done org-log-done)
12559 (org-log-repeat org-log-repeat)
12560 (org-todo-log-states org-todo-log-states)
12561 (org-inhibit-logging
12562 (if (equal arg 0)
12563 (progn (setq arg nil) 'note) org-inhibit-logging))
12564 (this (match-string 1))
12565 (hl-pos (match-beginning 0))
12566 (head (org-get-todo-sequence-head this))
12567 (ass (assoc head org-todo-kwd-alist))
12568 (interpret (nth 1 ass))
12569 (done-word (nth 3 ass))
12570 (final-done-word (nth 4 ass))
12571 (org-last-state (or this ""))
12572 (completion-ignore-case t)
12573 (member (member this org-todo-keywords-1))
12574 (tail (cdr member))
12575 (org-state (cond
12576 ((and org-todo-key-trigger
12577 (or (and (equal arg '(4))
12578 (eq org-use-fast-todo-selection 'prefix))
12579 (and (not arg) org-use-fast-todo-selection
12580 (not (eq org-use-fast-todo-selection
12581 'prefix)))))
12582 ;; Use fast selection
12583 (org-fast-todo-selection))
12584 ((and (equal arg '(4))
12585 (or (not org-use-fast-todo-selection)
12586 (not org-todo-key-trigger)))
12587 ;; Read a state with completion
12588 (completing-read
12589 "State: " (mapcar #'list org-todo-keywords-1)
12590 nil t))
12591 ((eq arg 'right)
12592 (if this
12593 (if tail (car tail) nil)
12594 (car org-todo-keywords-1)))
12595 ((eq arg 'left)
12596 (unless (equal member org-todo-keywords-1)
12597 (if this
12598 (nth (- (length org-todo-keywords-1)
12599 (length tail) 2)
12600 org-todo-keywords-1)
12601 (org-last org-todo-keywords-1))))
12602 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12603 (setq arg nil))) ; hack to fall back to cycling
12604 (arg
12605 ;; user or caller requests a specific state
12606 (cond
12607 ((equal arg "") nil)
12608 ((eq arg 'none) nil)
12609 ((eq arg 'done) (or done-word (car org-done-keywords)))
12610 ((eq arg 'nextset)
12611 (or (car (cdr (member head org-todo-heads)))
12612 (car org-todo-heads)))
12613 ((eq arg 'previousset)
12614 (let ((org-todo-heads (reverse org-todo-heads)))
12615 (or (car (cdr (member head org-todo-heads)))
12616 (car org-todo-heads))))
12617 ((car (member arg org-todo-keywords-1)))
12618 ((stringp arg)
12619 (user-error "State `%s' not valid in this file" arg))
12620 ((nth (1- (prefix-numeric-value arg))
12621 org-todo-keywords-1))))
12622 ((null member) (or head (car org-todo-keywords-1)))
12623 ((equal this final-done-word) nil) ;; -> make empty
12624 ((null tail) nil) ;; -> first entry
12625 ((memq interpret '(type priority))
12626 (if (eq this-command last-command)
12627 (car tail)
12628 (if (> (length tail) 0)
12629 (or done-word (car org-done-keywords))
12630 nil)))
12632 (car tail))))
12633 (org-state (or
12634 (run-hook-with-args-until-success
12635 'org-todo-get-default-hook org-state org-last-state)
12636 org-state))
12637 (next (if org-state (concat " " org-state " ") " "))
12638 (change-plist (list :type 'todo-state-change :from this :to org-state
12639 :position startpos))
12640 dolog now-done-p)
12641 (when org-blocker-hook
12642 (setq org-last-todo-state-is-todo
12643 (not (member this org-done-keywords)))
12644 (unless (save-excursion
12645 (save-match-data
12646 (org-with-wide-buffer
12647 (run-hook-with-args-until-failure
12648 'org-blocker-hook change-plist))))
12649 (if (org-called-interactively-p 'interactive)
12650 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12651 this org-state org-block-entry-blocking)
12652 ;; fail silently
12653 (message "TODO state change from %s to %s blocked (by \"%s\")"
12654 this org-state org-block-entry-blocking)
12655 (throw 'exit nil))))
12656 (store-match-data match-data)
12657 (replace-match next t t)
12658 (cond ((equal this org-state)
12659 (message "TODO state was already %s" (org-trim next)))
12660 ((pos-visible-in-window-p hl-pos)
12661 (message "TODO state changed to %s" (org-trim next))))
12662 (unless head
12663 (setq head (org-get-todo-sequence-head org-state)
12664 ass (assoc head org-todo-kwd-alist)
12665 interpret (nth 1 ass)
12666 done-word (nth 3 ass)
12667 final-done-word (nth 4 ass)))
12668 (when (memq arg '(nextset previousset))
12669 (message "Keyword-Set %d/%d: %s"
12670 (- (length org-todo-sets) -1
12671 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12672 (length org-todo-sets)
12673 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12674 (setq org-last-todo-state-is-todo
12675 (not (member org-state org-done-keywords)))
12676 (setq now-done-p (and (member org-state org-done-keywords)
12677 (not (member this org-done-keywords))))
12678 (and logging (org-local-logging logging))
12679 (when (and (or org-todo-log-states org-log-done)
12680 (not (eq org-inhibit-logging t))
12681 (not (memq arg '(nextset previousset))))
12682 ;; we need to look at recording a time and note
12683 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12684 (nth 2 (assoc this org-todo-log-states))))
12685 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12686 (setq dolog 'time))
12687 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12688 (and org-state
12689 (member org-state org-not-done-keywords)
12690 (not (member this org-not-done-keywords))))
12691 ;; This is now a todo state and was not one before
12692 ;; If there was a CLOSED time stamp, get rid of it.
12693 (org-add-planning-info nil nil 'closed))
12694 (when (and now-done-p org-log-done)
12695 ;; It is now done, and it was not done before
12696 (org-add-planning-info 'closed (org-current-effective-time))
12697 (when (and (not dolog) (eq 'note org-log-done))
12698 (org-add-log-setup 'done org-state this 'note)))
12699 (when (and org-state dolog)
12700 ;; This is a non-nil state, and we need to log it
12701 (org-add-log-setup 'state org-state this dolog)))
12702 ;; Fixup tag positioning
12703 (org-todo-trigger-tag-changes org-state)
12704 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12705 (when org-provide-todo-statistics
12706 (org-update-parent-todo-statistics))
12707 (run-hooks 'org-after-todo-state-change-hook)
12708 (when (and arg (not (member org-state org-done-keywords)))
12709 (setq head (org-get-todo-sequence-head org-state)))
12710 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12711 ;; Do we need to trigger a repeat?
12712 (when now-done-p
12713 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12714 ;; This is for the agenda, take a snapshot of the headline.
12715 (save-match-data
12716 (setq org-agenda-headline-snapshot-before-repeat
12717 (org-get-heading))))
12718 (org-auto-repeat-maybe org-state))
12719 ;; Fixup cursor location if close to the keyword
12720 (when (and (outline-on-heading-p)
12721 (not (bolp))
12722 (save-excursion (beginning-of-line 1)
12723 (looking-at org-todo-line-regexp))
12724 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12725 (goto-char (or (match-end 2) (match-end 1)))
12726 (and (looking-at " ") (just-one-space)))
12727 (when org-trigger-hook
12728 (save-excursion
12729 (run-hook-with-args 'org-trigger-hook change-plist)))
12730 (when commentp (org-toggle-comment))))))))
12732 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12733 "Block turning an entry into a TODO, using the hierarchy.
12734 This checks whether the current task should be blocked from state
12735 changes. Such blocking occurs when:
12737 1. The task has children which are not all in a completed state.
12739 2. A task has a parent with the property :ORDERED:, and there
12740 are siblings prior to the current task with incomplete
12741 status.
12743 3. The parent of the task is blocked because it has siblings that should
12744 be done first, or is child of a block grandparent TODO entry."
12746 (if (not org-enforce-todo-dependencies)
12747 t ; if locally turned off don't block
12748 (catch 'dont-block
12749 ;; If this is not a todo state change, or if this entry is already DONE,
12750 ;; do not block
12751 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12752 (member (plist-get change-plist :from)
12753 (cons 'done org-done-keywords))
12754 (member (plist-get change-plist :to)
12755 (cons 'todo org-not-done-keywords))
12756 (not (plist-get change-plist :to)))
12757 (throw 'dont-block t))
12758 ;; If this task has children, and any are undone, it's blocked
12759 (save-excursion
12760 (org-back-to-heading t)
12761 (let ((this-level (funcall outline-level)))
12762 (outline-next-heading)
12763 (let ((child-level (funcall outline-level)))
12764 (while (and (not (eobp))
12765 (> child-level this-level))
12766 ;; this todo has children, check whether they are all
12767 ;; completed
12768 (when (and (not (org-entry-is-done-p))
12769 (org-entry-is-todo-p))
12770 (setq org-block-entry-blocking (org-get-heading))
12771 (throw 'dont-block nil))
12772 (outline-next-heading)
12773 (setq child-level (funcall outline-level))))))
12774 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12775 ;; any previous siblings are undone, it's blocked
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (let* ((pos (point))
12779 (parent-pos (and (org-up-heading-safe) (point))))
12780 (unless parent-pos (throw 'dont-block t)) ; no parent
12781 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12782 (forward-line 1)
12783 (re-search-forward org-not-done-heading-regexp pos t))
12784 (setq org-block-entry-blocking (match-string 0))
12785 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12786 ;; Search further up the hierarchy, to see if an ancestor is blocked
12787 (while t
12788 (goto-char parent-pos)
12789 (unless (looking-at org-not-done-heading-regexp)
12790 (throw 'dont-block t)) ; do not block, parent is not a TODO
12791 (setq pos (point))
12792 (setq parent-pos (and (org-up-heading-safe) (point)))
12793 (unless parent-pos (throw 'dont-block t)) ; no parent
12794 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12795 (forward-line 1)
12796 (re-search-forward org-not-done-heading-regexp pos t)
12797 (setq org-block-entry-blocking (org-get-heading)))
12798 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12800 (defcustom org-track-ordered-property-with-tag nil
12801 "Should the ORDERED property also be shown as a tag?
12802 The ORDERED property decides if an entry should require subtasks to be
12803 completed in sequence. Since a property is not very visible, setting
12804 this option means that toggling the ORDERED property with the command
12805 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12806 not relevant for the behavior, but it makes things more visible.
12808 Note that toggling the tag with tags commands will not change the property
12809 and therefore not influence behavior!
12811 This can be t, meaning the tag ORDERED should be used, It can also be a
12812 string to select a different tag for this task."
12813 :group 'org-todo
12814 :type '(choice
12815 (const :tag "No tracking" nil)
12816 (const :tag "Track with ORDERED tag" t)
12817 (string :tag "Use other tag")))
12819 (defun org-toggle-ordered-property ()
12820 "Toggle the ORDERED property of the current entry.
12821 For better visibility, you can track the value of this property with a tag.
12822 See variable `org-track-ordered-property-with-tag'."
12823 (interactive)
12824 (let* ((t1 org-track-ordered-property-with-tag)
12825 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12826 (save-excursion
12827 (org-back-to-heading)
12828 (if (org-entry-get nil "ORDERED")
12829 (progn
12830 (org-delete-property "ORDERED")
12831 (and tag (org-toggle-tag tag 'off))
12832 (message "Subtasks can be completed in arbitrary order"))
12833 (org-entry-put nil "ORDERED" "t")
12834 (and tag (org-toggle-tag tag 'on))
12835 (message "Subtasks must be completed in sequence")))))
12837 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12838 (defun org-block-todo-from-checkboxes (change-plist)
12839 "Block turning an entry into a TODO, using checkboxes.
12840 This checks whether the current task should be blocked from state
12841 changes because there are unchecked boxes in this entry."
12842 (if (not org-enforce-todo-checkbox-dependencies)
12843 t ; if locally turned off don't block
12844 (catch 'dont-block
12845 ;; If this is not a todo state change, or if this entry is already DONE,
12846 ;; do not block
12847 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12848 (member (plist-get change-plist :from)
12849 (cons 'done org-done-keywords))
12850 (member (plist-get change-plist :to)
12851 (cons 'todo org-not-done-keywords))
12852 (not (plist-get change-plist :to)))
12853 (throw 'dont-block t))
12854 ;; If this task has checkboxes that are not checked, it's blocked
12855 (save-excursion
12856 (org-back-to-heading t)
12857 (let ((beg (point)) end)
12858 (outline-next-heading)
12859 (setq end (point))
12860 (goto-char beg)
12861 (when (org-list-search-forward
12862 (concat (org-item-beginning-re)
12863 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12864 "\\[[- ]\\]")
12865 end t)
12866 (when (boundp 'org-blocked-by-checkboxes)
12867 (setq org-blocked-by-checkboxes t))
12868 (throw 'dont-block nil))))
12869 t))) ; do not block
12871 (defun org-entry-blocked-p ()
12872 "Non-nil if entry at point is blocked."
12873 (and (not (org-entry-get nil "NOBLOCKING"))
12874 (member (org-entry-get nil "TODO") org-not-done-keywords)
12875 (not (run-hook-with-args-until-failure
12876 'org-blocker-hook
12877 (list :type 'todo-state-change
12878 :position (point)
12879 :from 'todo
12880 :to 'done)))))
12882 (defun org-update-statistics-cookies (all)
12883 "Update the statistics cookie, either from TODO or from checkboxes.
12884 This should be called with the cursor in a line with a statistics cookie."
12885 (interactive "P")
12886 (if all
12887 (progn
12888 (org-update-checkbox-count 'all)
12889 (org-map-entries 'org-update-parent-todo-statistics))
12890 (if (not (org-at-heading-p))
12891 (org-update-checkbox-count)
12892 (let ((pos (point-marker))
12893 end l1 l2)
12894 (ignore-errors (org-back-to-heading t))
12895 (if (not (org-at-heading-p))
12896 (org-update-checkbox-count)
12897 (setq l1 (org-outline-level))
12898 (setq end (save-excursion
12899 (outline-next-heading)
12900 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12901 (point)))
12902 (if (and (save-excursion
12903 (re-search-forward
12904 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12905 (not (save-excursion (re-search-forward
12906 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12907 (org-update-checkbox-count)
12908 (if (and l2 (> l2 l1))
12909 (progn
12910 (goto-char end)
12911 (org-update-parent-todo-statistics))
12912 (goto-char pos)
12913 (beginning-of-line 1)
12914 (while (re-search-forward
12915 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12916 (point-at-eol) t)
12917 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12918 (goto-char pos)
12919 (move-marker pos nil)))))
12921 (defvar org-entry-property-inherited-from) ;; defined below
12922 (defun org-update-parent-todo-statistics ()
12923 "Update any statistics cookie in the parent of the current headline.
12924 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12925 the entire subtree and this will travel up the hierarchy and update
12926 statistics everywhere."
12927 (let* ((prop (save-excursion (org-up-heading-safe)
12928 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12929 (recursive (or (not org-hierarchical-todo-statistics)
12930 (and prop (string-match "\\<recursive\\>" prop))))
12931 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12933 (first t)
12934 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12935 level ltoggle l1 new ndel
12936 (cnt-all 0) (cnt-done 0) is-percent kwd
12937 checkbox-beg ov ovs ove cookie-present)
12938 (catch 'exit
12939 (save-excursion
12940 (beginning-of-line 1)
12941 (setq ltoggle (funcall outline-level))
12942 ;; Three situations are to consider:
12944 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12945 ;; to the top-level ancestor on the headline;
12947 ;; 2. If parent has "recursive" property, repeat up to the
12948 ;; headline setting that property, taking inheritance into
12949 ;; account;
12951 ;; 3. Else, move up to direct parent and proceed only once.
12952 (while (and (setq level (org-up-heading-safe))
12953 (or recursive first)
12954 (>= (point) lim))
12955 (setq first nil cookie-present nil)
12956 (unless (and level
12957 (not (string-match
12958 "\\<checkbox\\>"
12959 (downcase (or (org-entry-get nil "COOKIE_DATA")
12960 "")))))
12961 (throw 'exit nil))
12962 (while (re-search-forward box-re (point-at-eol) t)
12963 (setq cnt-all 0 cnt-done 0 cookie-present t)
12964 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12965 (save-match-data
12966 (unless (outline-next-heading) (throw 'exit nil))
12967 (while (and (looking-at org-complex-heading-regexp)
12968 (> (setq l1 (length (match-string 1))) level))
12969 (setq kwd (and (or recursive (= l1 ltoggle))
12970 (match-string 2)))
12971 (if (or (eq org-provide-todo-statistics 'all-headlines)
12972 (and (eq org-provide-todo-statistics t)
12973 (or (member kwd org-done-keywords)))
12974 (and (listp org-provide-todo-statistics)
12975 (stringp (car org-provide-todo-statistics))
12976 (or (member kwd org-provide-todo-statistics)
12977 (member kwd org-done-keywords)))
12978 (and (listp org-provide-todo-statistics)
12979 (listp (car org-provide-todo-statistics))
12980 (or (member kwd (car org-provide-todo-statistics))
12981 (and (member kwd org-done-keywords)
12982 (member kwd (cadr org-provide-todo-statistics))))))
12983 (setq cnt-all (1+ cnt-all))
12984 (and (eq org-provide-todo-statistics t)
12986 (setq cnt-all (1+ cnt-all))))
12987 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12988 (member kwd org-done-keywords))
12989 (and (listp org-provide-todo-statistics)
12990 (listp (car org-provide-todo-statistics))
12991 (member kwd org-done-keywords)
12992 (member kwd (cadr org-provide-todo-statistics)))
12993 (and (listp org-provide-todo-statistics)
12994 (stringp (car org-provide-todo-statistics))
12995 (member kwd org-done-keywords)))
12996 (setq cnt-done (1+ cnt-done)))
12997 (outline-next-heading)))
12998 (setq new
12999 (if is-percent
13000 (format "[%d%%]" (floor (* 100.0 cnt-done)
13001 (max 1 cnt-all)))
13002 (format "[%d/%d]" cnt-done cnt-all))
13003 ndel (- (match-end 0) checkbox-beg))
13004 ;; handle overlays when updating cookie from column view
13005 (when (setq ov (car (overlays-at checkbox-beg)))
13006 (setq ovs (overlay-start ov) ove (overlay-end ov))
13007 (delete-overlay ov))
13008 (goto-char checkbox-beg)
13009 (insert new)
13010 (delete-region (point) (+ (point) ndel))
13011 (when org-auto-align-tags (org-fix-tags-on-the-fly))
13012 (when ov (move-overlay ov ovs ove)))
13013 (when cookie-present
13014 (run-hook-with-args 'org-after-todo-statistics-hook
13015 cnt-done (- cnt-all cnt-done))))))
13016 (run-hooks 'org-todo-statistics-hook)))
13018 (defvar org-after-todo-statistics-hook nil
13019 "Hook that is called after a TODO statistics cookie has been updated.
13020 Each function is called with two arguments: the number of not-done entries
13021 and the number of done entries.
13023 For example, the following function, when added to this hook, will switch
13024 an entry to DONE when all children are done, and back to TODO when new
13025 entries are set to a TODO status. Note that this hook is only called
13026 when there is a statistics cookie in the headline!
13028 \(defun org-summary-todo (n-done n-not-done)
13029 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13030 \(let (org-log-done org-log-states) ; turn off logging
13031 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13034 (defvar org-todo-statistics-hook nil
13035 "Hook that is run whenever Org thinks TODO statistics should be updated.
13036 This hook runs even if there is no statistics cookie present, in which case
13037 `org-after-todo-statistics-hook' would not run.")
13039 (defun org-todo-trigger-tag-changes (state)
13040 "Apply the changes defined in `org-todo-state-tags-triggers'."
13041 (let ((l org-todo-state-tags-triggers)
13042 changes)
13043 (when (or (not state) (equal state ""))
13044 (setq changes (append changes (cdr (assoc "" l)))))
13045 (when (and (stringp state) (> (length state) 0))
13046 (setq changes (append changes (cdr (assoc state l)))))
13047 (when (member state org-not-done-keywords)
13048 (setq changes (append changes (cdr (assoc 'todo l)))))
13049 (when (member state org-done-keywords)
13050 (setq changes (append changes (cdr (assoc 'done l)))))
13051 (dolist (c changes)
13052 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13054 (defun org-local-logging (value)
13055 "Get logging settings from a property VALUE."
13056 ;; Directly set the variables, they are already local.
13057 (setq org-log-done nil
13058 org-log-repeat nil
13059 org-todo-log-states nil)
13060 (dolist (w (org-split-string value))
13061 (let (a)
13062 (cond
13063 ((setq a (assoc w org-startup-options))
13064 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13065 (set (nth 1 a) (nth 2 a))))
13066 ((setq a (org-extract-log-state-settings w))
13067 (and (member (car a) org-todo-keywords-1)
13068 (push a org-todo-log-states)))))))
13070 (defun org-get-todo-sequence-head (kwd)
13071 "Return the head of the TODO sequence to which KWD belongs.
13072 If KWD is not set, check if there is a text property remembering the
13073 right sequence."
13074 (let (p)
13075 (cond
13076 ((not kwd)
13077 (or (get-text-property (point-at-bol) 'org-todo-head)
13078 (progn
13079 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13080 nil (point-at-eol)))
13081 (get-text-property p 'org-todo-head))))
13082 ((not (member kwd org-todo-keywords-1))
13083 (car org-todo-keywords-1))
13084 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13086 (defun org-fast-todo-selection ()
13087 "Fast TODO keyword selection with single keys.
13088 Returns the new TODO keyword, or nil if no state change should occur."
13089 (let* ((fulltable org-todo-key-alist)
13090 (done-keywords org-done-keywords) ;; needed for the faces.
13091 (maxlen (apply 'max (mapcar
13092 (lambda (x)
13093 (if (stringp (car x)) (string-width (car x)) 0))
13094 fulltable)))
13095 (expert nil)
13096 (fwidth (+ maxlen 3 1 3))
13097 (ncol (/ (- (window-width) 4) fwidth))
13098 tg cnt e c tbl
13099 groups ingroup)
13100 (save-excursion
13101 (save-window-excursion
13102 (if expert
13103 (set-buffer (get-buffer-create " *Org todo*"))
13104 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13105 (erase-buffer)
13106 (setq-local org-done-keywords done-keywords)
13107 (setq tbl fulltable cnt 0)
13108 (while (setq e (pop tbl))
13109 (cond
13110 ((equal e '(:startgroup))
13111 (push '() groups) (setq ingroup t)
13112 (unless (= cnt 0)
13113 (setq cnt 0)
13114 (insert "\n"))
13115 (insert "{ "))
13116 ((equal e '(:endgroup))
13117 (setq ingroup nil cnt 0)
13118 (insert "}\n"))
13119 ((equal e '(:newline))
13120 (unless (= cnt 0)
13121 (setq cnt 0)
13122 (insert "\n")
13123 (setq e (car tbl))
13124 (while (equal (car tbl) '(:newline))
13125 (insert "\n")
13126 (setq tbl (cdr tbl)))))
13128 (setq tg (car e) c (cdr e))
13129 (when ingroup (push tg (car groups)))
13130 (setq tg (org-add-props tg nil 'face
13131 (org-get-todo-face tg)))
13132 (when (and (= cnt 0) (not ingroup)) (insert " "))
13133 (insert "[" c "] " tg (make-string
13134 (- fwidth 4 (length tg)) ?\ ))
13135 (when (= (setq cnt (1+ cnt)) ncol)
13136 (insert "\n")
13137 (when ingroup (insert " "))
13138 (setq cnt 0)))))
13139 (insert "\n")
13140 (goto-char (point-min))
13141 (unless expert (org-fit-window-to-buffer))
13142 (message "[a-z..]:Set [SPC]:clear")
13143 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13144 (cond
13145 ((or (= c ?\C-g)
13146 (and (= c ?q) (not (rassoc c fulltable))))
13147 (setq quit-flag t))
13148 ((= c ?\ ) nil)
13149 ((setq e (rassoc c fulltable) tg (car e))
13151 (t (setq quit-flag t)))))))
13153 (defun org-entry-is-todo-p ()
13154 (member (org-get-todo-state) org-not-done-keywords))
13156 (defun org-entry-is-done-p ()
13157 (member (org-get-todo-state) org-done-keywords))
13159 (defun org-get-todo-state ()
13160 "Return the TODO keyword of the current subtree."
13161 (save-excursion
13162 (org-back-to-heading t)
13163 (and (looking-at org-todo-line-regexp)
13164 (match-end 2)
13165 (match-string 2))))
13167 (defun org-at-date-range-p (&optional inactive-ok)
13168 "Non-nil if point is inside a date range.
13170 When optional argument INACTIVE-OK is non-nil, also consider
13171 inactive time ranges.
13173 When this function returns a non-nil value, match data is set
13174 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13175 on INACTIVE-OK."
13176 (interactive)
13177 (save-excursion
13178 (catch 'exit
13179 (let ((pos (point)))
13180 (skip-chars-backward "^[<\r\n")
13181 (skip-chars-backward "<[")
13182 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13183 (>= (match-end 0) pos)
13184 (throw 'exit t))
13185 (skip-chars-backward "^<[\r\n")
13186 (skip-chars-backward "<[")
13187 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13188 (>= (match-end 0) pos)
13189 (throw 'exit t)))
13190 nil)))
13192 (defun org-get-repeat (&optional tagline)
13193 "Check if there is a deadline/schedule with repeater in this entry."
13194 (save-match-data
13195 (save-excursion
13196 (org-back-to-heading t)
13197 (and (re-search-forward (if tagline
13198 (concat tagline "\\s-*" org-repeat-re)
13199 org-repeat-re)
13200 (org-entry-end-position) t)
13201 (match-string-no-properties 1)))))
13203 (defvar org-last-changed-timestamp)
13204 (defvar org-last-inserted-timestamp)
13205 (defvar org-log-post-message)
13206 (defvar org-log-note-purpose)
13207 (defvar org-log-note-how nil)
13208 (defvar org-log-note-extra)
13209 (defun org-auto-repeat-maybe (done-word)
13210 "Check if the current headline contains a repeated time-stamp.
13212 If yes, set TODO state back to what it was and change the base date
13213 of repeating deadline/scheduled time stamps to new date.
13215 This function is run automatically after each state change to a DONE state."
13216 (let* ((repeat (org-get-repeat))
13217 (aa (assoc org-last-state org-todo-kwd-alist))
13218 (interpret (nth 1 aa))
13219 (head (nth 2 aa))
13220 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13221 (msg "Entry repeats: ")
13222 (org-log-done nil)
13223 (org-todo-log-states nil))
13224 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13225 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13226 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13227 org-todo-repeat-to-state)))
13228 (unless (and to-state (member to-state org-todo-keywords-1))
13229 (setq to-state (if (eq interpret 'type) org-last-state head)))
13230 (org-todo to-state))
13231 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13232 (org-entry-put nil "LAST_REPEAT" (format-time-string
13233 (org-time-stamp-format t t))))
13234 (when org-log-repeat
13235 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13236 (memq 'org-add-log-note post-command-hook))
13237 ;; We are already setup for some record.
13238 (when (eq org-log-repeat 'note)
13239 ;; Make sure we take a note, not only a time stamp.
13240 (setq org-log-note-how 'note))
13241 ;; Set up for taking a record.
13242 (org-add-log-setup 'state
13243 (or done-word (car org-done-keywords))
13244 org-last-state
13245 org-log-repeat)))
13246 (org-back-to-heading t)
13247 (org-add-planning-info nil nil 'closed)
13248 (let ((end (save-excursion (outline-next-heading) (point))))
13249 (while (re-search-forward org-ts-regexp end t)
13250 (when (save-match-data
13251 (or (org-at-planning-p)
13252 (org-at-property-p)
13253 (eq (org-element-type (save-excursion
13254 (backward-char)
13255 (org-element-context)))
13256 'timestamp)))
13257 (let ((type (cond ((match-end 1) org-scheduled-string)
13258 ((match-end 3) org-deadline-string)
13259 (t "Plain:")))
13260 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13261 (cond
13262 ((not
13263 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13264 ;; Time-stamps without a repeater are usually skipped.
13265 ;; However, a SCHEDULED time-stamp without one is
13266 ;; removed, as it is considered as no longer relevant.
13267 (when (equal type org-scheduled-string)
13268 (org-remove-timestamp-with-keyword type)))
13270 (let ((n (string-to-number (match-string 2 ts)))
13271 (what (match-string 3 ts)))
13272 (when (equal what "w") (setq n (* n 7) what "d"))
13273 (when (and (equal what "h")
13274 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13275 ts)))
13276 (user-error
13277 "Cannot repeat in Repeat in %d hour(s) because no hour \
13278 has been set"
13280 ;; Preparation, see if we need to modify the start
13281 ;; date for the change.
13282 (when (match-end 1)
13283 (let ((time (save-match-data (org-time-string-to-time ts))))
13284 (cond
13285 ((equal (match-string 1 ts) ".")
13286 ;; Shift starting date to today
13287 (org-timestamp-change
13288 (- (org-today) (time-to-days time))
13289 'day))
13290 ((equal (match-string 1 ts) "+")
13291 (let ((nshiftmax 10)
13292 (nshift 0))
13293 (while (or (= nshift 0)
13294 (<= (time-to-days time)
13295 (time-to-days (current-time))))
13296 (when (= (cl-incf nshift) nshiftmax)
13297 (or (y-or-n-p
13298 (format "%d repeater intervals were not \
13299 enough to shift date past today. Continue? "
13300 nshift))
13301 (user-error "Abort")))
13302 (org-timestamp-change n (cdr (assoc what whata)))
13303 (org-at-timestamp-p t)
13304 (setq ts (match-string 1))
13305 (setq time
13306 (save-match-data
13307 (org-time-string-to-time ts)))))
13308 (org-timestamp-change (- n) (cdr (assoc what whata)))
13309 ;; Rematch, so that we have everything in
13310 ;; place for the real shift.
13311 (org-at-timestamp-p t)
13312 (setq ts (match-string 1))
13313 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13314 ts)))))
13315 (save-excursion
13316 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13317 (setq msg
13318 (concat
13319 msg type " " org-last-changed-timestamp " ")))))))))
13320 (setq org-log-post-message msg)
13321 (message "%s" msg))))
13323 (defun org-show-todo-tree (arg)
13324 "Make a compact tree which shows all headlines marked with TODO.
13325 The tree will show the lines where the regexp matches, and all higher
13326 headlines above the match.
13327 With a \\[universal-argument] prefix, prompt for a regexp to match.
13328 With a numeric prefix N, construct a sparse tree for the Nth element
13329 of `org-todo-keywords-1'."
13330 (interactive "P")
13331 (let ((case-fold-search nil)
13332 (kwd-re
13333 (cond ((null arg) org-not-done-regexp)
13334 ((equal arg '(4))
13335 (let ((kwd
13336 (completing-read "Keyword (or KWD1|KWD2|...): "
13337 (mapcar #'list org-todo-keywords-1))))
13338 (concat "\\("
13339 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13340 "\\)\\>")))
13341 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13342 (regexp-quote (nth (1- (prefix-numeric-value arg))
13343 org-todo-keywords-1)))
13344 (t (user-error "Invalid prefix argument: %s" arg)))))
13345 (message "%d TODO entries found"
13346 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13348 (defun org-deadline (arg &optional time)
13349 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13350 With one universal prefix argument, remove any deadline from the item.
13351 With two universal prefix arguments, prompt for a warning delay.
13352 With argument TIME, set the deadline at the corresponding date. TIME
13353 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13354 (interactive "P")
13355 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13356 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13357 'region-start-level 'region))
13358 org-loop-over-headlines-in-active-region)
13359 (org-map-entries
13360 `(org-deadline ',arg ,time)
13361 org-loop-over-headlines-in-active-region
13362 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13363 (let* ((old-date (org-entry-get nil "DEADLINE"))
13364 (old-date-time (when old-date (org-time-string-to-time old-date)))
13365 (repeater (and old-date
13366 (string-match
13367 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13368 old-date)
13369 (match-string 1 old-date))))
13370 (cond
13371 ((equal arg '(4))
13372 (when (and old-date org-log-redeadline)
13373 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13374 (org-remove-timestamp-with-keyword org-deadline-string)
13375 (message "Item no longer has a deadline."))
13376 ((equal arg '(16))
13377 (save-excursion
13378 (org-back-to-heading t)
13379 (if (re-search-forward
13380 org-deadline-time-regexp
13381 (save-excursion (outline-next-heading) (point)) t)
13382 (let* ((rpl0 (match-string 1))
13383 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13384 (replace-match
13385 (concat org-deadline-string
13386 " <" rpl
13387 (format " -%dd"
13388 (abs
13389 (- (time-to-days
13390 (save-match-data
13391 (org-read-date nil t nil "Warn starting from" old-date-time)))
13392 (time-to-days old-date-time))))
13393 ">") t t))
13394 (user-error "No deadline information to update"))))
13396 (org-add-planning-info 'deadline time 'closed)
13397 (when (and old-date
13398 org-log-redeadline
13399 (not (equal old-date org-last-inserted-timestamp)))
13400 (org-add-log-setup
13401 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13402 (when repeater
13403 (save-excursion
13404 (org-back-to-heading t)
13405 (when (re-search-forward (concat org-deadline-string " "
13406 org-last-inserted-timestamp)
13407 (save-excursion
13408 (outline-next-heading) (point)) t)
13409 (goto-char (1- (match-end 0)))
13410 (insert " " repeater)
13411 (setq org-last-inserted-timestamp
13412 (concat (substring org-last-inserted-timestamp 0 -1)
13413 " " repeater
13414 (substring org-last-inserted-timestamp -1))))))
13415 (message "Deadline on %s" org-last-inserted-timestamp))))))
13417 (defun org-schedule (arg &optional time)
13418 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13419 With one universal prefix argument, remove any scheduling date from the item.
13420 With two universal prefix arguments, prompt for a delay cookie.
13421 With argument TIME, scheduled at the corresponding date. TIME can
13422 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13423 (interactive "P")
13424 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13425 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13426 'region-start-level 'region))
13427 org-loop-over-headlines-in-active-region)
13428 (org-map-entries
13429 `(org-schedule ',arg ,time)
13430 org-loop-over-headlines-in-active-region
13431 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13432 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13433 (old-date-time (when old-date (org-time-string-to-time old-date)))
13434 (repeater (and old-date
13435 (string-match
13436 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13437 old-date)
13438 (match-string 1 old-date))))
13439 (cond
13440 ((equal arg '(4))
13441 (progn
13442 (when (and old-date org-log-reschedule)
13443 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13444 (org-remove-timestamp-with-keyword org-scheduled-string)
13445 (message "Item is no longer scheduled.")))
13446 ((equal arg '(16))
13447 (save-excursion
13448 (org-back-to-heading t)
13449 (if (re-search-forward
13450 org-scheduled-time-regexp
13451 (save-excursion (outline-next-heading) (point)) t)
13452 (let* ((rpl0 (match-string 1))
13453 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13454 (replace-match
13455 (concat org-scheduled-string
13456 " <" rpl
13457 (format " -%dd"
13458 (abs
13459 (- (time-to-days
13460 (save-match-data
13461 (org-read-date nil t nil "Delay until" old-date-time)))
13462 (time-to-days old-date-time))))
13463 ">") t t))
13464 (user-error "No scheduled information to update"))))
13466 (org-add-planning-info 'scheduled time 'closed)
13467 (when (and old-date
13468 org-log-reschedule
13469 (not (equal old-date org-last-inserted-timestamp)))
13470 (org-add-log-setup
13471 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13472 (when repeater
13473 (save-excursion
13474 (org-back-to-heading t)
13475 (when (re-search-forward (concat org-scheduled-string " "
13476 org-last-inserted-timestamp)
13477 (save-excursion
13478 (outline-next-heading) (point)) t)
13479 (goto-char (1- (match-end 0)))
13480 (insert " " repeater)
13481 (setq org-last-inserted-timestamp
13482 (concat (substring org-last-inserted-timestamp 0 -1)
13483 " " repeater
13484 (substring org-last-inserted-timestamp -1))))))
13485 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13487 (defun org-get-scheduled-time (pom &optional inherit)
13488 "Get the scheduled time as a time tuple, of a format suitable
13489 for calling org-schedule with, or if there is no scheduling,
13490 returns nil."
13491 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13492 (when time
13493 (apply 'encode-time (org-parse-time-string time)))))
13495 (defun org-get-deadline-time (pom &optional inherit)
13496 "Get the deadline as a time tuple, of a format suitable for
13497 calling org-deadline with, or if there is no scheduling, returns
13498 nil."
13499 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13500 (when time
13501 (apply 'encode-time (org-parse-time-string time)))))
13503 (defun org-remove-timestamp-with-keyword (keyword)
13504 "Remove all time stamps with KEYWORD in the current entry."
13505 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13506 beg)
13507 (save-excursion
13508 (org-back-to-heading t)
13509 (setq beg (point))
13510 (outline-next-heading)
13511 (while (re-search-backward re beg t)
13512 (replace-match "")
13513 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13514 (equal (char-before) ?\ ))
13515 (backward-delete-char 1)
13516 (when (string-match "^[ \t]*$" (buffer-substring
13517 (point-at-bol) (point-at-eol)))
13518 (delete-region (point-at-bol)
13519 (min (point-max) (1+ (point-at-eol))))))))))
13521 (defvar org-time-was-given) ; dynamically scoped parameter
13522 (defvar org-end-time-was-given) ; dynamically scoped parameter
13524 (defun org-at-planning-p ()
13525 "Non-nil when point is on a planning info line."
13526 ;; This is as accurate and faster than `org-element-at-point' since
13527 ;; planning info location is fixed in the section.
13528 (org-with-wide-buffer
13529 (beginning-of-line)
13530 (and (looking-at-p org-planning-line-re)
13531 (eq (point)
13532 (ignore-errors
13533 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13534 (org-back-to-heading t)
13535 (org-with-limited-levels (org-back-to-heading t)))
13536 (line-beginning-position 2))))))
13538 (defun org-add-planning-info (what &optional time &rest remove)
13539 "Insert new timestamp with keyword in the planning line.
13540 WHAT indicates what kind of time stamp to add. It is a symbol
13541 among `closed', `deadline', `scheduled' and nil. TIME indicates
13542 the time to use. If none is given, the user is prompted for
13543 a date. REMOVE indicates what kind of entries to remove. An old
13544 WHAT entry will also be removed."
13545 (let (org-time-was-given org-end-time-was-given default-time default-input)
13546 (catch 'exit
13547 (when (and (memq what '(scheduled deadline))
13548 (or (not time)
13549 (and (stringp time)
13550 (string-match "^[-+]+[0-9]" time))))
13551 ;; Try to get a default date/time from existing timestamp
13552 (save-excursion
13553 (org-back-to-heading t)
13554 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13555 (when (re-search-forward (if (eq what 'scheduled)
13556 org-scheduled-time-regexp
13557 org-deadline-time-regexp)
13558 end t)
13559 (setq ts (match-string 1)
13560 default-time (apply 'encode-time (org-parse-time-string ts))
13561 default-input (and ts (org-get-compact-tod ts)))))))
13562 (when what
13563 (setq time
13564 (if (stringp time)
13565 ;; This is a string (relative or absolute), set
13566 ;; proper date.
13567 (apply #'encode-time
13568 (org-read-date-analyze
13569 time default-time (decode-time default-time)))
13570 ;; If necessary, get the time from the user
13571 (or time (org-read-date nil 'to-time nil nil
13572 default-time default-input)))))
13574 (org-with-wide-buffer
13575 (org-back-to-heading t)
13576 (forward-line)
13577 (unless (bolp) (insert "\n"))
13578 (cond ((looking-at-p org-planning-line-re)
13579 ;; Move to current indentation.
13580 (skip-chars-forward " \t")
13581 ;; Check if we have to remove something.
13582 (dolist (type (if what (cons what remove) remove))
13583 (save-excursion
13584 (when (re-search-forward
13585 (cl-case type
13586 (closed org-closed-time-regexp)
13587 (deadline org-deadline-time-regexp)
13588 (scheduled org-scheduled-time-regexp)
13589 (otherwise
13590 (error "Invalid planning type: %s" type)))
13591 (line-end-position) t)
13592 ;; Delete until next keyword or end of line.
13593 (delete-region
13594 (match-beginning 0)
13595 (if (re-search-forward org-keyword-time-not-clock-regexp
13596 (line-end-position)
13598 (match-beginning 0)
13599 (line-end-position))))))
13600 ;; If there is nothing more to add and no more keyword
13601 ;; is left, remove the line completely.
13602 (if (and (looking-at-p "[ \t]*$") (not what))
13603 (delete-region (line-beginning-position)
13604 (line-beginning-position 2))
13605 ;; If we removed last keyword, do not leave trailing
13606 ;; white space at the end of line.
13607 (let ((p (point)))
13608 (save-excursion
13609 (end-of-line)
13610 (unless (= (skip-chars-backward " \t" p) 0)
13611 (delete-region (point) (line-end-position)))))))
13612 ((not what) (throw 'exit nil)) ; Nothing to do.
13613 (t (insert-before-markers "\n")
13614 (backward-char 1)
13615 (when org-adapt-indentation
13616 (indent-to-column (1+ (org-outline-level))))))
13617 (when what
13618 ;; Insert planning keyword.
13619 (insert (cl-case what
13620 (closed org-closed-string)
13621 (deadline org-deadline-string)
13622 (scheduled org-scheduled-string)
13623 (otherwise (error "Invalid planning type: %s" what)))
13624 " ")
13625 ;; Insert associated timestamp.
13626 (let ((ts (org-insert-time-stamp
13627 time
13628 (or org-time-was-given
13629 (and (eq what 'closed) org-log-done-with-time))
13630 (eq what 'closed)
13631 nil nil (list org-end-time-was-given))))
13632 (unless (eolp) (insert " "))
13633 ts))))))
13635 (defvar org-log-note-marker (make-marker)
13636 "Marker pointing at the entry where the note is to be inserted.")
13637 (defvar org-log-note-purpose nil)
13638 (defvar org-log-note-state nil)
13639 (defvar org-log-note-previous-state nil)
13640 (defvar org-log-note-extra nil)
13641 (defvar org-log-note-window-configuration nil)
13642 (defvar org-log-note-return-to (make-marker))
13643 (defvar org-log-note-effective-time nil
13644 "Remembered current time so that dynamically scoped
13645 `org-extend-today-until' affects timestamps in state change log")
13647 (defvar org-log-post-message nil
13648 "Message to be displayed after a log note has been stored.
13649 The auto-repeater uses this.")
13651 (defun org-add-note ()
13652 "Add a note to the current entry.
13653 This is done in the same way as adding a state change note."
13654 (interactive)
13655 (org-add-log-setup 'note))
13657 (defun org-log-beginning (&optional create)
13658 "Return expected start of log notes in current entry.
13659 When optional argument CREATE is non-nil, the function creates
13660 a drawer to store notes, if necessary. Returned position ignores
13661 narrowing."
13662 (org-with-wide-buffer
13663 (let ((drawer (org-log-into-drawer)))
13664 (cond
13665 (drawer
13666 (org-end-of-meta-data)
13667 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13668 (end (if (org-at-heading-p) (point)
13669 (save-excursion (outline-next-heading) (point))))
13670 (case-fold-search t))
13671 (catch 'exit
13672 ;; Try to find existing drawer.
13673 (while (re-search-forward regexp end t)
13674 (let ((element (org-element-at-point)))
13675 (when (eq (org-element-type element) 'drawer)
13676 (let ((cend (org-element-property :contents-end element)))
13677 (when (and (not org-log-states-order-reversed) cend)
13678 (goto-char cend)))
13679 (throw 'exit nil))))
13680 ;; No drawer found. Create one, if permitted.
13681 (when create
13682 (unless (bolp) (insert "\n"))
13683 (let ((beg (point)))
13684 (insert ":" drawer ":\n:END:\n")
13685 (org-indent-region beg (point)))
13686 (end-of-line -1)))))
13688 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13689 (skip-chars-forward " \t\n")
13690 (beginning-of-line)
13691 (unless org-log-states-order-reversed
13692 (org-skip-over-state-notes)
13693 (skip-chars-backward " \t\n")
13694 (forward-line)))))
13695 (if (bolp) (point) (line-beginning-position 2))))
13697 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13698 "Set up the post command hook to take a note.
13699 If this is about to TODO state change, the new state is expected in STATE.
13700 HOW is an indicator what kind of note should be created.
13701 EXTRA is additional text that will be inserted into the notes buffer."
13702 (move-marker org-log-note-marker (point))
13703 (setq org-log-note-purpose purpose
13704 org-log-note-state state
13705 org-log-note-previous-state prev-state
13706 org-log-note-how how
13707 org-log-note-extra extra
13708 org-log-note-effective-time (org-current-effective-time))
13709 (add-hook 'post-command-hook 'org-add-log-note 'append))
13711 (defun org-skip-over-state-notes ()
13712 "Skip past the list of State notes in an entry."
13713 (when (ignore-errors (goto-char (org-in-item-p)))
13714 (let* ((struct (org-list-struct))
13715 (prevs (org-list-prevs-alist struct))
13716 (regexp
13717 (concat "[ \t]*- +"
13718 (replace-regexp-in-string
13719 " +" " +"
13720 (org-replace-escapes
13721 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13722 `(("%d" . ,org-ts-regexp-inactive)
13723 ("%D" . ,org-ts-regexp)
13724 ("%s" . "\"\\S-+\"")
13725 ("%S" . "\"\\S-+\"")
13726 ("%t" . ,org-ts-regexp-inactive)
13727 ("%T" . ,org-ts-regexp)
13728 ("%u" . ".*?")
13729 ("%U" . ".*?")))))))
13730 (while (looking-at-p regexp)
13731 (goto-char (or (org-list-get-next-item (point) struct prevs)
13732 (org-list-get-item-end (point) struct)))))))
13734 (defun org-add-log-note (&optional _purpose)
13735 "Pop up a window for taking a note, and add this note later."
13736 (remove-hook 'post-command-hook 'org-add-log-note)
13737 (setq org-log-note-window-configuration (current-window-configuration))
13738 (delete-other-windows)
13739 (move-marker org-log-note-return-to (point))
13740 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13741 (goto-char org-log-note-marker)
13742 (org-switch-to-buffer-other-window "*Org Note*")
13743 (erase-buffer)
13744 (if (memq org-log-note-how '(time state))
13745 (let (current-prefix-arg) (org-store-log-note))
13746 (let ((org-inhibit-startup t)) (org-mode))
13747 (insert (format "# Insert note for %s.
13748 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13749 (cond
13750 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13751 ((eq org-log-note-purpose 'done) "closed todo item")
13752 ((eq org-log-note-purpose 'state)
13753 (format "state change from \"%s\" to \"%s\""
13754 (or org-log-note-previous-state "")
13755 (or org-log-note-state "")))
13756 ((eq org-log-note-purpose 'reschedule)
13757 "rescheduling")
13758 ((eq org-log-note-purpose 'delschedule)
13759 "no longer scheduled")
13760 ((eq org-log-note-purpose 'redeadline)
13761 "changing deadline")
13762 ((eq org-log-note-purpose 'deldeadline)
13763 "removing deadline")
13764 ((eq org-log-note-purpose 'refile)
13765 "refiling")
13766 ((eq org-log-note-purpose 'note)
13767 "this entry")
13768 (t (error "This should not happen")))))
13769 (when org-log-note-extra (insert org-log-note-extra))
13770 (setq-local org-finish-function 'org-store-log-note)
13771 (run-hooks 'org-log-buffer-setup-hook)))
13773 (defvar org-note-abort nil) ; dynamically scoped
13774 (defun org-store-log-note ()
13775 "Finish taking a log note, and insert it to where it belongs."
13776 (let ((txt (prog1 (buffer-string)
13777 (kill-buffer)))
13778 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13779 lines)
13780 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13781 (setq txt (replace-match "" t t txt)))
13782 (when (string-match "\\s-+\\'" txt)
13783 (setq txt (replace-match "" t t txt)))
13784 (setq lines (org-split-string txt "\n"))
13785 (when (org-string-nw-p note)
13786 (setq note
13787 (org-replace-escapes
13788 note
13789 (list (cons "%u" (user-login-name))
13790 (cons "%U" user-full-name)
13791 (cons "%t" (format-time-string
13792 (org-time-stamp-format 'long 'inactive)
13793 org-log-note-effective-time))
13794 (cons "%T" (format-time-string
13795 (org-time-stamp-format 'long nil)
13796 org-log-note-effective-time))
13797 (cons "%d" (format-time-string
13798 (org-time-stamp-format nil 'inactive)
13799 org-log-note-effective-time))
13800 (cons "%D" (format-time-string
13801 (org-time-stamp-format nil nil)
13802 org-log-note-effective-time))
13803 (cons "%s" (cond
13804 ((not org-log-note-state) "")
13805 ((org-string-match-p org-ts-regexp
13806 org-log-note-state)
13807 (format "\"[%s]\""
13808 (substring org-log-note-state 1 -1)))
13809 (t (format "\"%s\"" org-log-note-state))))
13810 (cons "%S"
13811 (cond
13812 ((not org-log-note-previous-state) "")
13813 ((org-string-match-p org-ts-regexp
13814 org-log-note-previous-state)
13815 (format "\"[%s]\""
13816 (substring
13817 org-log-note-previous-state 1 -1)))
13818 (t (format "\"%s\""
13819 org-log-note-previous-state)))))))
13820 (when lines (setq note (concat note " \\\\")))
13821 (push note lines))
13822 (when (and lines (not (or current-prefix-arg org-note-abort)))
13823 (with-current-buffer (marker-buffer org-log-note-marker)
13824 (org-with-wide-buffer
13825 ;; Find location for the new note.
13826 (goto-char org-log-note-marker)
13827 (set-marker org-log-note-marker nil)
13828 (goto-char (org-log-beginning t))
13829 ;; Make sure point is at the beginning of an empty line.
13830 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13831 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13832 ;; In an existing list, add a new item at the top level.
13833 ;; Otherwise, indent line like a regular one.
13834 (let ((itemp (org-in-item-p)))
13835 (if itemp
13836 (indent-line-to
13837 (let ((struct (save-excursion
13838 (goto-char itemp) (org-list-struct))))
13839 (org-list-get-ind (org-list-get-top-point struct) struct)))
13840 (org-indent-line)))
13841 (insert (org-list-bullet-string "-") (pop lines))
13842 (let ((ind (org-list-item-body-column (line-beginning-position))))
13843 (dolist (line lines)
13844 (insert "\n")
13845 (indent-line-to ind)
13846 (insert line)))
13847 (message "Note stored")
13848 (org-back-to-heading t)
13849 (org-cycle-hide-drawers 'children))
13850 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13851 ;; from within `org-add-log-note' because `buffer-undo-list'
13852 ;; is then modified outside of `org-with-remote-undo'.
13853 (when (eq this-command 'org-agenda-todo)
13854 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13855 ;; Don't add undo information when called from `org-agenda-todo'.
13856 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13857 (set-window-configuration org-log-note-window-configuration)
13858 (with-current-buffer (marker-buffer org-log-note-return-to)
13859 (goto-char org-log-note-return-to))
13860 (move-marker org-log-note-return-to nil)
13861 (when org-log-post-message (message "%s" org-log-post-message))))
13863 (defun org-remove-empty-drawer-at (pos)
13864 "Remove an empty drawer at position POS.
13865 POS may also be a marker."
13866 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13867 (org-with-wide-buffer
13868 (goto-char pos)
13869 (let ((drawer (org-element-at-point)))
13870 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13871 (not (org-element-property :contents-begin drawer)))
13872 (delete-region (org-element-property :begin drawer)
13873 (progn (goto-char (org-element-property :end drawer))
13874 (skip-chars-backward " \r\t\n")
13875 (forward-line)
13876 (point))))))))
13878 (defvar org-ts-type nil)
13879 (defun org-sparse-tree (&optional arg type)
13880 "Create a sparse tree, prompt for the details.
13881 This command can create sparse trees. You first need to select the type
13882 of match used to create the tree:
13884 t Show all TODO entries.
13885 T Show entries with a specific TODO keyword.
13886 m Show entries selected by a tags/property match.
13887 p Enter a property name and its value (both with completion on existing
13888 names/values) and show entries with that property.
13889 r Show entries matching a regular expression (`/' can be used as well).
13890 b Show deadlines and scheduled items before a date.
13891 a Show deadlines and scheduled items after a date.
13892 d Show deadlines due within `org-deadline-warning-days'.
13893 D Show deadlines and scheduled items between a date range."
13894 (interactive "P")
13895 (setq type (or type org-sparse-tree-default-date-type))
13896 (setq org-ts-type type)
13897 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13898 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13899 \[c]ycle through date types: %s"
13900 (cl-case type
13901 (all "all timestamps")
13902 (scheduled "only scheduled")
13903 (deadline "only deadline")
13904 (active "only active timestamps")
13905 (inactive "only inactive timestamps")
13906 (closed "with a closed time-stamp")
13907 (otherwise "scheduled/deadline")))
13908 (let ((answer (read-char-exclusive)))
13909 (cl-case answer
13911 (org-sparse-tree
13913 (cadr
13914 (memq type '(nil all scheduled deadline active inactive closed)))))
13915 (?d (call-interactively 'org-check-deadlines))
13916 (?b (call-interactively 'org-check-before-date))
13917 (?a (call-interactively 'org-check-after-date))
13918 (?D (call-interactively 'org-check-dates-range))
13919 (?t (call-interactively 'org-show-todo-tree))
13920 (?T (org-show-todo-tree '(4)))
13921 (?m (call-interactively 'org-match-sparse-tree))
13922 ((?p ?P)
13923 (let* ((kwd (completing-read
13924 "Property: " (mapcar #'list (org-buffer-property-keys))))
13925 (value (completing-read
13926 "Value: " (mapcar #'list (org-property-values kwd)))))
13927 (unless (string-match "\\`{.*}\\'" value)
13928 (setq value (concat "\"" value "\"")))
13929 (org-match-sparse-tree arg (concat kwd "=" value))))
13930 ((?r ?R ?/) (call-interactively 'org-occur))
13931 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13933 (defvar-local org-occur-highlights nil
13934 "List of overlays used for occur matches.")
13935 (defvar-local org-occur-parameters nil
13936 "Parameters of the active org-occur calls.
13937 This is a list, each call to org-occur pushes as cons cell,
13938 containing the regular expression and the callback, onto the list.
13939 The list can contain several entries if `org-occur' has been called
13940 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13941 will only contain one set of parameters. When the highlights are
13942 removed (for example with `C-c C-c', or with the next edit (depending
13943 on `org-remove-highlights-with-change'), this variable is emptied
13944 as well.")
13946 (defun org-occur (regexp &optional keep-previous callback)
13947 "Make a compact tree which shows all matches of REGEXP.
13949 The tree will show the lines where the regexp matches, and any other context
13950 defined in `org-show-context-detail', which see.
13952 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13953 done by a previous call to `org-occur' will be kept, to allow stacking of
13954 calls to this command.
13956 Optional argument CALLBACK can be a function of no argument. In this case,
13957 it is called with point at the end of the match, match data being set
13958 accordingly. Current match is shown only if the return value is non-nil.
13959 The function must neither move point nor alter narrowing."
13960 (interactive "sRegexp: \nP")
13961 (when (equal regexp "")
13962 (user-error "Regexp cannot be empty"))
13963 (unless keep-previous
13964 (org-remove-occur-highlights nil nil t))
13965 (push (cons regexp callback) org-occur-parameters)
13966 (let ((cnt 0))
13967 (save-excursion
13968 (goto-char (point-min))
13969 (when (or (not keep-previous) ; do not want to keep
13970 (not org-occur-highlights)) ; no previous matches
13971 ;; hide everything
13972 (org-overview))
13973 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13974 (isearch-no-upper-case-p regexp t)
13975 org-occur-case-fold-search)))
13976 (while (re-search-forward regexp nil t)
13977 (when (or (not callback)
13978 (save-match-data (funcall callback)))
13979 (setq cnt (1+ cnt))
13980 (when org-highlight-sparse-tree-matches
13981 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13982 (org-show-context 'occur-tree)))))
13983 (when org-remove-highlights-with-change
13984 (add-hook 'before-change-functions 'org-remove-occur-highlights
13985 nil 'local))
13986 (unless org-sparse-tree-open-archived-trees
13987 (org-hide-archived-subtrees (point-min) (point-max)))
13988 (run-hooks 'org-occur-hook)
13989 (when (org-called-interactively-p 'interactive)
13990 (message "%d match(es) for regexp %s" cnt regexp))
13991 cnt))
13993 (defun org-occur-next-match (&optional n _reset)
13994 "Function for `next-error-function' to find sparse tree matches.
13995 N is the number of matches to move, when negative move backwards.
13996 This function always goes back to the starting point when no
13997 match is found."
13998 (let* ((limit (if (< n 0) (point-min) (point-max)))
13999 (search-func (if (< n 0)
14000 'previous-single-char-property-change
14001 'next-single-char-property-change))
14002 (n (abs n))
14003 (pos (point))
14005 (catch 'exit
14006 (while (setq p1 (funcall search-func (point) 'org-type))
14007 (when (equal p1 limit)
14008 (goto-char pos)
14009 (user-error "No more matches"))
14010 (when (equal (get-char-property p1 'org-type) 'org-occur)
14011 (setq n (1- n))
14012 (when (= n 0)
14013 (goto-char p1)
14014 (throw 'exit (point))))
14015 (goto-char p1))
14016 (goto-char p1)
14017 (user-error "No more matches"))))
14019 (defun org-show-context (&optional key)
14020 "Make sure point and context are visible.
14021 Optional argument KEY, when non-nil, is a symbol. See
14022 `org-show-context-detail' for allowed values and how much is to
14023 be shown."
14024 (org-show-set-visibility
14025 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14026 ((cdr (assq key org-show-context-detail)))
14027 (t (cdr (assq 'default org-show-context-detail))))))
14029 (defun org-show-set-visibility (detail)
14030 "Set visibility around point according to DETAIL.
14031 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14032 `tree', `canonical' or t. See `org-show-context-detail' for more
14033 information."
14034 ;; Show current heading and possibly its entry, following headline
14035 ;; or all children.
14036 (if (and (org-at-heading-p) (not (eq detail 'local)))
14037 (org-flag-heading nil)
14038 (org-show-entry)
14039 ;; If point is hidden within a drawer or a block, make sure to
14040 ;; expose it.
14041 (dolist (o (overlays-at (point)))
14042 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14043 (delete-overlay o)))
14044 (unless (org-before-first-heading-p)
14045 (org-with-limited-levels
14046 (cl-case detail
14047 ((tree canonical t) (org-show-children))
14048 ((nil minimal ancestors))
14049 (t (save-excursion
14050 (outline-next-heading)
14051 (org-flag-heading nil)))))))
14052 ;; Show all siblings.
14053 (when (eq detail 'lineage) (org-show-siblings))
14054 ;; Show ancestors, possibly with their children.
14055 (when (memq detail '(ancestors lineage tree canonical t))
14056 (save-excursion
14057 (while (org-up-heading-safe)
14058 (org-flag-heading nil)
14059 (when (memq detail '(canonical t)) (org-show-entry))
14060 (when (memq detail '(tree canonical t)) (org-show-children))))))
14062 (defvar org-reveal-start-hook nil
14063 "Hook run before revealing a location.")
14065 (defun org-reveal (&optional siblings)
14066 "Show current entry, hierarchy above it, and the following headline.
14068 This can be used to show a consistent set of context around
14069 locations exposed with `org-show-context'.
14071 With optional argument SIBLINGS, on each level of the hierarchy all
14072 siblings are shown. This repairs the tree structure to what it would
14073 look like when opened with hierarchical calls to `org-cycle'.
14075 With double optional argument \\[universal-argument] \\[universal-argument], \
14076 go to the parent and show the
14077 entire tree."
14078 (interactive "P")
14079 (run-hooks 'org-reveal-start-hook)
14080 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14081 ((equal siblings '(16))
14082 (save-excursion
14083 (when (org-up-heading-safe)
14084 (org-show-subtree)
14085 (run-hook-with-args 'org-cycle-hook 'subtree))))
14086 (t (org-show-set-visibility 'lineage))))
14088 (defun org-highlight-new-match (beg end)
14089 "Highlight from BEG to END and mark the highlight is an occur headline."
14090 (let ((ov (make-overlay beg end)))
14091 (overlay-put ov 'face 'secondary-selection)
14092 (overlay-put ov 'org-type 'org-occur)
14093 (push ov org-occur-highlights)))
14095 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14096 "Remove the occur highlights from the buffer.
14097 BEG and END are ignored. If NOREMOVE is nil, remove this function
14098 from the `before-change-functions' in the current buffer."
14099 (interactive)
14100 (unless org-inhibit-highlight-removal
14101 (mapc #'delete-overlay org-occur-highlights)
14102 (setq org-occur-highlights nil)
14103 (setq org-occur-parameters nil)
14104 (unless noremove
14105 (remove-hook 'before-change-functions
14106 'org-remove-occur-highlights 'local))))
14108 ;;;; Priorities
14110 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14111 "Regular expression matching the priority indicator.")
14113 (defvar org-remove-priority-next-time nil)
14115 (defun org-priority-up ()
14116 "Increase the priority of the current item."
14117 (interactive)
14118 (org-priority 'up))
14120 (defun org-priority-down ()
14121 "Decrease the priority of the current item."
14122 (interactive)
14123 (org-priority 'down))
14125 (defun org-priority (&optional action _show)
14126 "Change the priority of an item.
14127 ACTION can be `set', `up', `down', or a character."
14128 (interactive "P")
14129 (if (equal action '(4))
14130 (org-show-priority)
14131 (unless org-enable-priority-commands
14132 (user-error "Priority commands are disabled"))
14133 (setq action (or action 'set))
14134 (let (current new news have remove)
14135 (save-excursion
14136 (org-back-to-heading t)
14137 (when (looking-at org-priority-regexp)
14138 (setq current (string-to-char (match-string 2))
14139 have t))
14140 (cond
14141 ((eq action 'remove)
14142 (setq remove t new ?\ ))
14143 ((or (eq action 'set)
14144 (integerp action))
14145 (if (not (eq action 'set))
14146 (setq new action)
14147 (message "Priority %c-%c, SPC to remove: "
14148 org-highest-priority org-lowest-priority)
14149 (save-match-data
14150 (setq new (read-char-exclusive))))
14151 (when (and (= (upcase org-highest-priority) org-highest-priority)
14152 (= (upcase org-lowest-priority) org-lowest-priority))
14153 (setq new (upcase new)))
14154 (cond ((equal new ?\ ) (setq remove t))
14155 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14156 (user-error "Priority must be between `%c' and `%c'"
14157 org-highest-priority org-lowest-priority))))
14158 ((eq action 'up)
14159 (setq new (if have
14160 (1- current) ; normal cycling
14161 ;; last priority was empty
14162 (if (eq last-command this-command)
14163 org-lowest-priority ; wrap around empty to lowest
14164 ;; default
14165 (if org-priority-start-cycle-with-default
14166 org-default-priority
14167 (1- org-default-priority))))))
14168 ((eq action 'down)
14169 (setq new (if have
14170 (1+ current) ; normal cycling
14171 ;; last priority was empty
14172 (if (eq last-command this-command)
14173 org-highest-priority ; wrap around empty to highest
14174 ;; default
14175 (if org-priority-start-cycle-with-default
14176 org-default-priority
14177 (1+ org-default-priority))))))
14178 (t (user-error "Invalid action")))
14179 (when (or (< (upcase new) org-highest-priority)
14180 (> (upcase new) org-lowest-priority))
14181 (if (and (memq action '(up down))
14182 (not have) (not (eq last-command this-command)))
14183 ;; `new' is from default priority
14184 (error
14185 "The default can not be set, see `org-default-priority' why")
14186 ;; normal cycling: `new' is beyond highest/lowest priority
14187 ;; and is wrapped around to the empty priority
14188 (setq remove t)))
14189 (setq news (format "%c" new))
14190 (if have
14191 (if remove
14192 (replace-match "" t t nil 1)
14193 (replace-match news t t nil 2))
14194 (if remove
14195 (user-error "No priority cookie found in line")
14196 (let ((case-fold-search nil))
14197 (looking-at org-todo-line-regexp))
14198 (if (match-end 2)
14199 (progn
14200 (goto-char (match-end 2))
14201 (insert " [#" news "]"))
14202 (goto-char (match-beginning 3))
14203 (insert "[#" news "] "))))
14204 (org-set-tags nil 'align))
14205 (if remove
14206 (message "Priority removed")
14207 (message "Priority of current item set to %s" news)))))
14209 (defun org-show-priority ()
14210 "Show the priority of the current item.
14211 This priority is composed of the main priority given with the [#A] cookies,
14212 and by additional input from the age of a schedules or deadline entry."
14213 (interactive)
14214 (let ((pri (if (eq major-mode 'org-agenda-mode)
14215 (org-get-at-bol 'priority)
14216 (save-excursion
14217 (save-match-data
14218 (beginning-of-line)
14219 (and (looking-at org-heading-regexp)
14220 (org-get-priority (match-string 0))))))))
14221 (message "Priority is %d" (if pri pri -1000))))
14223 (defun org-get-priority (s)
14224 "Find priority cookie and return priority."
14225 (save-match-data
14226 (if (functionp org-get-priority-function)
14227 (funcall org-get-priority-function)
14228 (if (not (string-match org-priority-regexp s))
14229 (* 1000 (- org-lowest-priority org-default-priority))
14230 (* 1000 (- org-lowest-priority
14231 (string-to-char (match-string 2 s))))))))
14233 ;;;; Tags
14235 (defvar org-agenda-archives-mode)
14236 (defvar org-map-continue-from nil
14237 "Position from where mapping should continue.
14238 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14240 (defvar org-scanner-tags nil
14241 "The current tag list while the tags scanner is running.")
14243 (defvar org-trust-scanner-tags nil
14244 "Should `org-get-tags-at' use the tags for the scanner.
14245 This is for internal dynamical scoping only.
14246 When this is non-nil, the function `org-get-tags-at' will return the value
14247 of `org-scanner-tags' instead of building the list by itself. This
14248 can lead to large speed-ups when the tags scanner is used in a file with
14249 many entries, and when the list of tags is retrieved, for example to
14250 obtain a list of properties. Building the tags list for each entry in such
14251 a file becomes an N^2 operation - but with this variable set, it scales
14252 as N.")
14254 (defvar org--matcher-tags-todo-only nil)
14256 (defun org-scan-tags (action matcher todo-only &optional start-level)
14257 "Scan headline tags with inheritance and produce output ACTION.
14259 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14260 or `agenda' to produce an entry list for an agenda view. It can also be
14261 a Lisp form or a function that should be called at each matched headline, in
14262 this case the return value is a list of all return values from these calls.
14264 MATCHER is a function accepting three arguments, returning
14265 a non-nil value whenever a given set of tags qualifies a headline
14266 for inclusion. See `org-make-tags-matcher' for more information.
14267 As a special case, it can also be set to t (respectively nil) in
14268 order to match all (respectively none) headline.
14270 When TODO-ONLY is non-nil, only lines with a not-done TODO
14271 keyword are included in the output.
14273 START-LEVEL can be a string with asterisks, reducing the scope to
14274 headlines matching this string."
14275 (require 'org-agenda)
14276 (let* ((re (concat "^"
14277 (if start-level
14278 ;; Get the correct level to match
14279 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14280 org-outline-regexp)
14281 " *\\(\\<\\("
14282 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14283 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14284 (props (list 'face 'default
14285 'done-face 'org-agenda-done
14286 'undone-face 'default
14287 'mouse-face 'highlight
14288 'org-not-done-regexp org-not-done-regexp
14289 'org-todo-regexp org-todo-regexp
14290 'org-complex-heading-regexp org-complex-heading-regexp
14291 'help-echo
14292 (format "mouse-2 or RET jump to org file %s"
14293 (abbreviate-file-name
14294 (or (buffer-file-name (buffer-base-buffer))
14295 (buffer-name (buffer-base-buffer)))))))
14296 (org-map-continue-from nil)
14297 lspos tags tags-list
14298 (tags-alist (list (cons 0 org-file-tags)))
14299 (llast 0) rtn rtn1 level category i txt
14300 todo marker entry priority
14301 ts-date ts-date-type ts-date-pair)
14302 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14303 (setq action (list 'lambda nil action)))
14304 (save-excursion
14305 (goto-char (point-min))
14306 (when (eq action 'sparse-tree)
14307 (org-overview)
14308 (org-remove-occur-highlights))
14309 (while (let (case-fold-search)
14310 (re-search-forward re nil t))
14311 (setq org-map-continue-from nil)
14312 (catch :skip
14313 (setq todo
14314 ;; TODO: is the 1-2 difference a bug?
14315 (when (match-end 1) (match-string-no-properties 2))
14316 tags (when (match-end 4) (match-string-no-properties 4)))
14317 (goto-char (setq lspos (match-beginning 0)))
14318 (setq level (org-reduced-level (org-outline-level))
14319 category (org-get-category))
14320 (when (eq action 'agenda)
14321 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14322 ts-date (car ts-date-pair)
14323 ts-date-type (cdr ts-date-pair)))
14324 (setq i llast llast level)
14325 ;; remove tag lists from same and sublevels
14326 (while (>= i level)
14327 (when (setq entry (assoc i tags-alist))
14328 (setq tags-alist (delete entry tags-alist)))
14329 (setq i (1- i)))
14330 ;; add the next tags
14331 (when tags
14332 (setq tags (org-split-string tags ":")
14333 tags-alist
14334 (cons (cons level tags) tags-alist)))
14335 ;; compile tags for current headline
14336 (setq tags-list
14337 (if org-use-tag-inheritance
14338 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14339 tags)
14340 org-scanner-tags tags-list)
14341 (when org-use-tag-inheritance
14342 (setcdr (car tags-alist)
14343 (mapcar (lambda (x)
14344 (setq x (copy-sequence x))
14345 (org-add-prop-inherited x))
14346 (cdar tags-alist))))
14347 (when (and tags org-use-tag-inheritance
14348 (or (not (eq t org-use-tag-inheritance))
14349 org-tags-exclude-from-inheritance))
14350 ;; Selective inheritance, remove uninherited ones.
14351 (setcdr (car tags-alist)
14352 (org-remove-uninherited-tags (cdar tags-alist))))
14353 (when (and
14355 ;; eval matcher only when the todo condition is OK
14356 (and (or (not todo-only) (member todo org-not-done-keywords))
14357 (if (functionp matcher)
14358 (let ((case-fold-search t) (org-trust-scanner-tags t))
14359 (funcall matcher todo tags-list level))
14360 matcher))
14362 ;; Call the skipper, but return t if it does not
14363 ;; skip, so that the `and' form continues evaluating.
14364 (progn
14365 (unless (eq action 'sparse-tree) (org-agenda-skip))
14368 ;; Check if timestamps are deselecting this entry
14369 (or (not todo-only)
14370 (and (member todo org-not-done-keywords)
14371 (or (not org-agenda-tags-todo-honor-ignore-options)
14372 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14374 ;; select this headline
14375 (cond
14376 ((eq action 'sparse-tree)
14377 (and org-highlight-sparse-tree-matches
14378 (org-get-heading) (match-end 0)
14379 (org-highlight-new-match
14380 (match-beginning 1) (match-end 1)))
14381 (org-show-context 'tags-tree))
14382 ((eq action 'agenda)
14383 (setq txt (org-agenda-format-item
14385 (concat
14386 (if (eq org-tags-match-list-sublevels 'indented)
14387 (make-string (1- level) ?.) "")
14388 (org-get-heading))
14389 (make-string level ?\s)
14390 category
14391 tags-list)
14392 priority (org-get-priority txt))
14393 (goto-char lspos)
14394 (setq marker (org-agenda-new-marker))
14395 (org-add-props txt props
14396 'org-marker marker 'org-hd-marker marker 'org-category category
14397 'todo-state todo
14398 'ts-date ts-date
14399 'priority priority
14400 'type (concat "tagsmatch" ts-date-type))
14401 (push txt rtn))
14402 ((functionp action)
14403 (setq org-map-continue-from nil)
14404 (save-excursion
14405 (setq rtn1 (funcall action))
14406 (push rtn1 rtn)))
14407 (t (user-error "Invalid action")))
14409 ;; if we are to skip sublevels, jump to end of subtree
14410 (unless org-tags-match-list-sublevels
14411 (org-end-of-subtree t)
14412 (backward-char 1))))
14413 ;; Get the correct position from where to continue
14414 (if org-map-continue-from
14415 (goto-char org-map-continue-from)
14416 (and (= (point) lspos) (end-of-line 1)))))
14417 (when (and (eq action 'sparse-tree)
14418 (not org-sparse-tree-open-archived-trees))
14419 (org-hide-archived-subtrees (point-min) (point-max)))
14420 (nreverse rtn)))
14422 (defun org-remove-uninherited-tags (tags)
14423 "Remove all tags that are not inherited from the list TAGS."
14424 (cond
14425 ((eq org-use-tag-inheritance t)
14426 (if org-tags-exclude-from-inheritance
14427 (org-delete-all org-tags-exclude-from-inheritance tags)
14428 tags))
14429 ((not org-use-tag-inheritance) nil)
14430 ((stringp org-use-tag-inheritance)
14431 (delq nil (mapcar
14432 (lambda (x)
14433 (if (and (string-match org-use-tag-inheritance x)
14434 (not (member x org-tags-exclude-from-inheritance)))
14435 x nil))
14436 tags)))
14437 ((listp org-use-tag-inheritance)
14438 (delq nil (mapcar
14439 (lambda (x)
14440 (if (member x org-use-tag-inheritance) x nil))
14441 tags)))))
14443 (defun org-match-sparse-tree (&optional todo-only match)
14444 "Create a sparse tree according to tags string MATCH.
14445 MATCH can contain positive and negative selection of tags, like
14446 \"+WORK+URGENT-WITHBOSS\".
14447 If optional argument TODO-ONLY is non-nil, only select lines that are
14448 also TODO lines."
14449 (interactive "P")
14450 (org-agenda-prepare-buffers (list (current-buffer)))
14451 (let ((org--matcher-tags-todo-only todo-only))
14452 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14453 org--matcher-tags-todo-only)))
14455 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14457 (defvar org-cached-props nil)
14458 (defun org-cached-entry-get (pom property)
14459 (if (or (eq t org-use-property-inheritance)
14460 (and (stringp org-use-property-inheritance)
14461 (let ((case-fold-search t))
14462 (org-string-match-p org-use-property-inheritance property)))
14463 (and (listp org-use-property-inheritance)
14464 (member-ignore-case property org-use-property-inheritance)))
14465 ;; Caching is not possible, check it directly.
14466 (org-entry-get pom property 'inherit)
14467 ;; Get all properties, so we can do complicated checks easily.
14468 (cdr (assoc-string property
14469 (or org-cached-props
14470 (setq org-cached-props (org-entry-properties pom)))
14471 t))))
14473 (defun org-global-tags-completion-table (&optional files)
14474 "Return the list of all tags in all agenda buffer/files.
14475 Optional FILES argument is a list of files which can be used
14476 instead of the agenda files."
14477 (save-excursion
14478 (org-uniquify
14479 (delq nil
14480 (apply #'append
14481 (mapcar
14482 (lambda (file)
14483 (set-buffer (find-file-noselect file))
14484 (mapcar (lambda (x)
14485 (and (stringp (car-safe x))
14486 (list (car-safe x))))
14487 (or org-current-tag-alist (org-get-buffer-tags))))
14488 (if (car-safe files) files
14489 (org-agenda-files))))))))
14491 (defun org-make-tags-matcher (match)
14492 "Create the TAGS/TODO matcher form for the selection string MATCH.
14494 Returns a cons of the selection string MATCH and a function
14495 implementing the matcher.
14497 The matcher is to be called at an Org entry, with point on the
14498 headline, and returns non-nil if the entry matches the selection
14499 string MATCH. It must be called with three arguments: the TODO
14500 keyword at the entry (or nil if none), the list of all tags at
14501 the entry including inherited ones and the reduced level of the
14502 headline. Additionally, the category of the entry, if any, must
14503 be specified as the text property `org-category' on the headline.
14505 This function sets the variable `org--matcher-tags-todo-only' to
14506 a non-nil value if the matcher restricts matching to TODO
14507 entries, otherwise it is not touched.
14509 See also `org-scan-tags'."
14510 (unless match
14511 ;; Get a new match request, with completion against the global
14512 ;; tags table and the local tags in current buffer.
14513 (let ((org-last-tags-completion-table
14514 (org-uniquify
14515 (delq nil (append (org-get-buffer-tags)
14516 (org-global-tags-completion-table))))))
14517 (setq match
14518 (completing-read
14519 "Match: "
14520 'org-tags-completion-function nil nil nil 'org-tags-history))))
14522 (let ((match0 match)
14523 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14524 (start 0)
14525 tagsmatch todomatch tagsmatcher todomatcher)
14527 ;; Expand group tags.
14528 (setq match (org-tags-expand match))
14530 ;; Check if there is a TODO part of this match, which would be the
14531 ;; part after a "/". To make sure that this slash is not part of
14532 ;; a property value to be matched against, we also check that
14533 ;; there is no / after that slash. First, find the last slash.
14534 (let ((s 0))
14535 (while (string-match "/+" match s)
14536 (setq start (match-beginning 0))
14537 (setq s (match-end 0))))
14538 (if (and (string-match "/+" match start)
14539 (not (string-match-p "\"" match start)))
14540 ;; Match contains also a TODO-matching request.
14541 (progn
14542 (setq tagsmatch (substring match 0 (match-beginning 0)))
14543 (setq todomatch (substring match (match-end 0)))
14544 (when (string-match "\\`!" todomatch)
14545 (setq org--matcher-tags-todo-only t)
14546 (setq todomatch (substring todomatch 1)))
14547 (when (string-match "\\`\\s-*\\'" todomatch)
14548 (setq todomatch nil)))
14549 ;; Only matching tags.
14550 (setq tagsmatch match)
14551 (setq todomatch nil))
14553 ;; Make the tags matcher.
14554 (when (org-string-nw-p tagsmatch)
14555 (let ((orlist nil)
14556 (orterms (org-split-string tagsmatch "|"))
14557 term)
14558 (while (setq term (pop orterms))
14559 (while (and (equal (substring term -1) "\\") orterms)
14560 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14561 (while (string-match re term)
14562 (let* ((rest (substring term (match-end 0)))
14563 (minus (and (match-end 1)
14564 (equal (match-string 1 term) "-")))
14565 (tag (save-match-data
14566 (replace-regexp-in-string
14567 "\\\\-" "-" (match-string 2 term))))
14568 (regexp (eq (string-to-char tag) ?{))
14569 (levelp (match-end 4))
14570 (propp (match-end 5))
14572 (cond
14573 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14574 (levelp
14575 `(,(org-op-to-function (match-string 3 term))
14576 level
14577 ,(string-to-number (match-string 4 term))))
14578 (propp
14579 (let* ((gv (pcase (upcase (match-string 5 term))
14580 ("CATEGORY"
14581 '(get-text-property (point) 'org-category))
14582 ("TODO" 'todo)
14583 (p `(org-cached-entry-get nil ,p))))
14584 (pv (match-string 7 term))
14585 (regexp (eq (string-to-char pv) ?{))
14586 (strp (eq (string-to-char pv) ?\"))
14587 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14588 (po (org-op-to-function (match-string 6 term)
14589 (if timep 'time strp))))
14590 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14591 (when timep (setq pv (org-matcher-time pv)))
14592 (cond ((and regexp (eq po 'org<>))
14593 `(not (string-match ,pv (or ,gv ""))))
14594 (regexp `(string-match ,pv (or ,gv "")))
14595 (strp `(,po (or ,gv "") ,pv))
14597 `(,po
14598 (string-to-number (or ,gv ""))
14599 ,(string-to-number pv))))))
14600 (t `(member ,tag tags-list)))))
14601 (push (if minus `(not ,mm) mm) tagsmatcher)
14602 (setq term rest)))
14603 (push `(and ,@tagsmatcher) orlist)
14604 (setq tagsmatcher nil))
14605 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14607 ;; Make the TODO matcher.
14608 (when (org-string-nw-p todomatch)
14609 (let ((orlist nil))
14610 (dolist (term (org-split-string todomatch "|"))
14611 (while (string-match re term)
14612 (let* ((minus (and (match-end 1)
14613 (equal (match-string 1 term) "-")))
14614 (kwd (match-string 2 term))
14615 (regexp (eq (string-to-char kwd) ?{))
14616 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14617 `(equal todo ,kwd))))
14618 (push (if minus `(not ,mm) mm) todomatcher))
14619 (setq term (substring term (match-end 0))))
14620 (push (if (> (length todomatcher) 1)
14621 (cons 'and todomatcher)
14622 (car todomatcher))
14623 orlist)
14624 (setq todomatcher nil))
14625 (setq todomatcher (cons 'or orlist))))
14627 ;; Return the string and function of the matcher. If no
14628 ;; tags-specific or todo-specific matcher exists, match
14629 ;; everything.
14630 (let ((matcher (if (and tagsmatcher todomatcher)
14631 `(and ,tagsmatcher ,todomatcher)
14632 (or tagsmatcher todomatcher t))))
14633 (when org--matcher-tags-todo-only
14634 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14635 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14637 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14638 "Expand group tags in MATCH.
14640 This replaces every group tag in MATCH with a regexp tag search.
14641 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14642 will be replaced like this:
14644 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14645 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14646 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14648 Replacing by a regexp preserves the structure of the match.
14649 E.g., this expansion
14651 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14653 will match anything tagged with \"Lab\" and \"Home\", or tagged
14654 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14656 A group tag in MATCH can contain regular expressions of its own.
14657 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14658 will be replaced like this:
14660 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14662 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14663 assumed to be a single group tag, and the function will return
14664 the list of tags in this group.
14666 When DOWNCASE is non-nil, expand downcased TAGS."
14667 (if org-group-tags
14668 (let* ((case-fold-search t)
14669 (stable org-mode-syntax-table)
14670 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14671 (taggroups (if downcased
14672 (mapcar (lambda (tg) (mapcar #'downcase tg))
14673 taggroups)
14674 taggroups))
14675 (taggroups-keys (mapcar #'car taggroups))
14676 (return-match (if downcased (downcase match) match))
14677 (count 0)
14678 (work-already-expanded tags-already-expanded)
14679 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14680 ;; @ and _ are allowed as word-components in tags.
14681 (modify-syntax-entry ?@ "w" stable)
14682 (modify-syntax-entry ?_ "w" stable)
14683 ;; Temporarily replace regexp-expressions in the match-expression.
14684 (while (string-match "{.+?}" return-match)
14685 (cl-incf count)
14686 (push (match-string 0 return-match) regexps-in-match)
14687 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14688 (while (and taggroups-keys
14689 (with-syntax-table stable
14690 (string-match
14691 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14692 (regexp-opt taggroups-keys) "\\>\\)")
14693 return-match)))
14694 (let* ((dir (match-string 1 return-match))
14695 (tag (match-string 2 return-match))
14696 (tag (if downcased (downcase tag) tag)))
14697 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14698 (member tag work-already-expanded))
14699 (setq tags-in-group (assoc tag taggroups))
14700 (push tag work-already-expanded)
14701 ;; Recursively expand each tag in the group, if the tag hasn't
14702 ;; already been expanded. Restore the match-data after all recursive calls.
14703 (save-match-data
14704 (let (tags-expanded)
14705 (dolist (x (cdr tags-in-group))
14706 (if (and (member x taggroups-keys)
14707 (not (member x work-already-expanded)))
14708 (setq tags-expanded
14709 (delete-dups
14710 (append
14711 (org-tags-expand x t downcased
14712 work-already-expanded)
14713 tags-expanded)))
14714 (setq tags-expanded
14715 (append (list x) tags-expanded)))
14716 (setq work-already-expanded
14717 (delete-dups
14718 (append tags-expanded
14719 work-already-expanded))))
14720 (setq tags-in-group
14721 (delete-dups (cons (car tags-in-group)
14722 tags-expanded)))))
14723 ;; Filter tag-regexps from tags.
14724 (setq regexp-in-group-escaped
14725 (delq nil (mapcar (lambda (x)
14726 (if (stringp x)
14727 (and (equal "{" (substring x 0 1))
14728 (equal "}" (substring x -1))
14731 tags-in-group))
14732 regexp-in-group
14733 (mapcar (lambda (x)
14734 (substring x 1 -1))
14735 regexp-in-group-escaped)
14736 tags-in-group
14737 (delq nil (mapcar (lambda (x)
14738 (if (stringp x)
14739 (and (not (equal "{" (substring x 0 1)))
14740 (not (equal "}" (substring x -1)))
14743 tags-in-group)))
14744 ;; If single-as-list, do no more in the while-loop.
14745 (if (not single-as-list)
14746 (progn
14747 (when regexp-in-group
14748 (setq regexp-in-group
14749 (concat "\\|"
14750 (mapconcat 'identity regexp-in-group
14751 "\\|"))))
14752 (setq tags-in-group
14753 (concat dir
14754 "{\\<"
14755 (regexp-opt tags-in-group)
14756 "\\>"
14757 regexp-in-group
14758 "}"))
14759 (when (stringp tags-in-group)
14760 (org-add-props tags-in-group '(grouptag t)))
14761 (setq return-match
14762 (replace-match tags-in-group t t return-match)))
14763 (setq tags-in-group
14764 (append regexp-in-group-escaped tags-in-group))))
14765 (setq taggroups-keys (delete tag taggroups-keys))))
14766 ;; Add the regular expressions back into the match-expression again.
14767 (while regexps-in-match
14768 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14769 (pop regexps-in-match)
14770 return-match t t))
14771 (cl-decf count))
14772 (if single-as-list
14773 (if tags-in-group tags-in-group (list return-match))
14774 return-match))
14775 (if single-as-list
14776 (list (if downcased (downcase match) match))
14777 match)))
14779 (defun org-op-to-function (op &optional stringp)
14780 "Turn an operator into the appropriate function."
14781 (setq op
14782 (cond
14783 ((equal op "<" ) '(< string< org-time<))
14784 ((equal op ">" ) '(> org-string> org-time>))
14785 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14786 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14787 ((member op '("=" "==")) '(= string= org-time=))
14788 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14789 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14791 (defun org<> (a b) (not (= a b)))
14792 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14793 (defun org-string>= (a b) (not (string< a b)))
14794 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14795 (defun org-string<> (a b) (not (string= a b)))
14796 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14797 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14798 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14799 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14800 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14801 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14802 (defun org-2ft (s)
14803 "Convert S to a floating point time.
14804 If S is already a number, just return it. If it is a string, parse
14805 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14806 (cond
14807 ((numberp s) s)
14808 ((stringp s)
14809 (condition-case nil
14810 (float-time (apply 'encode-time (org-parse-time-string s)))
14811 (error 0.)))
14812 (t 0.)))
14814 (defun org-time-today ()
14815 "Time in seconds today at 0:00.
14816 Returns the float number of seconds since the beginning of the
14817 epoch to the beginning of today (00:00)."
14818 (float-time (apply 'encode-time
14819 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14821 (defun org-matcher-time (s)
14822 "Interpret a time comparison value."
14823 (save-match-data
14824 (cond
14825 ((string= s "<now>") (float-time))
14826 ((string= s "<today>") (org-time-today))
14827 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14828 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14829 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14830 (+ (org-time-today)
14831 (* (string-to-number (match-string 1 s))
14832 (cdr (assoc (match-string 2 s)
14833 '(("d" . 86400.0) ("w" . 604800.0)
14834 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14835 (t (org-2ft s)))))
14837 (defun org-match-any-p (re list)
14838 "Does re match any element of list?"
14839 (setq list (mapcar (lambda (x) (string-match re x)) list))
14840 (delq nil list))
14842 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14843 (defvar org-tags-overlay (make-overlay 1 1))
14844 (delete-overlay org-tags-overlay)
14846 (defun org-get-local-tags-at (&optional pos)
14847 "Get a list of tags defined in the current headline."
14848 (org-get-tags-at pos 'local))
14850 (defun org-get-local-tags ()
14851 "Get a list of tags defined in the current headline."
14852 (org-get-tags-at nil 'local))
14854 (defun org-get-tags-at (&optional pos local)
14855 "Get a list of all headline tags applicable at POS.
14856 POS defaults to point. If tags are inherited, the list contains
14857 the targets in the same sequence as the headlines appear, i.e.
14858 the tags of the current headline come last.
14859 When LOCAL is non-nil, only return tags from the current headline,
14860 ignore inherited ones."
14861 (interactive)
14862 (if (and org-trust-scanner-tags
14863 (or (not pos) (equal pos (point)))
14864 (not local))
14865 org-scanner-tags
14866 (let (tags ltags lastpos parent)
14867 (save-excursion
14868 (save-restriction
14869 (widen)
14870 (goto-char (or pos (point)))
14871 (save-match-data
14872 (catch 'done
14873 (condition-case nil
14874 (progn
14875 (org-back-to-heading t)
14876 (while (not (equal lastpos (point)))
14877 (setq lastpos (point))
14878 (when (looking-at ".+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14879 (setq ltags (org-split-string
14880 (match-string-no-properties 1) ":"))
14881 (when parent
14882 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14883 (setq tags (append
14884 (if parent
14885 (org-remove-uninherited-tags ltags)
14886 ltags)
14887 tags)))
14888 (or org-use-tag-inheritance (throw 'done t))
14889 (when local (throw 'done t))
14890 (or (org-up-heading-safe) (error nil))
14891 (setq parent t)))
14892 (error nil)))))
14893 (if local
14894 tags
14895 (reverse (delete-dups
14896 (reverse (append
14897 (org-remove-uninherited-tags
14898 org-file-tags)
14899 tags)))))))))
14901 (defun org-add-prop-inherited (s)
14902 (add-text-properties 0 (length s) '(inherited t) s)
14905 (defun org-toggle-tag (tag &optional onoff)
14906 "Toggle the tag TAG for the current line.
14907 If ONOFF is `on' or `off', don't toggle but set to this state."
14908 (let (res current)
14909 (save-excursion
14910 (org-back-to-heading t)
14911 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14912 (point-at-eol) t)
14913 (progn
14914 (setq current (match-string 1))
14915 (replace-match ""))
14916 (setq current ""))
14917 (setq current (nreverse (org-split-string current ":")))
14918 (cond
14919 ((eq onoff 'on)
14920 (setq res t)
14921 (or (member tag current) (push tag current)))
14922 ((eq onoff 'off)
14923 (or (not (member tag current)) (setq current (delete tag current))))
14924 (t (if (member tag current)
14925 (setq current (delete tag current))
14926 (setq res t)
14927 (push tag current))))
14928 (end-of-line 1)
14929 (if current
14930 (progn
14931 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14932 (org-set-tags nil t))
14933 (delete-horizontal-space))
14934 (run-hooks 'org-after-tags-change-hook))
14935 res))
14937 (defun org-align-tags-here (to-col)
14938 ;; Assumes that this is a headline
14939 "Align tags on the current headline to TO-COL."
14940 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14941 (beginning-of-line 1)
14942 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14943 (< pos (match-beginning 2)))
14944 (progn
14945 (setq tags-l (string-width (match-string 2)))
14946 (goto-char (match-beginning 1))
14947 (insert " ")
14948 (delete-region (point) (1+ (match-beginning 2)))
14949 (setq ncol (max (current-column)
14950 (1+ col)
14951 (if (> to-col 0)
14952 to-col
14953 (- (abs to-col) tags-l))))
14954 (setq p (point))
14955 (insert (make-string (- ncol (current-column)) ?\ ))
14956 (setq ncol (current-column))
14957 (when indent-tabs-mode (tabify p (point-at-eol)))
14958 (org-move-to-column (min ncol col)))
14959 (goto-char pos))))
14961 (defun org-set-tags-command (&optional arg just-align)
14962 "Call the set-tags command for the current entry."
14963 (interactive "P")
14964 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14965 (org-set-tags arg just-align)
14966 (save-excursion
14967 (unless (and (org-region-active-p)
14968 org-loop-over-headlines-in-active-region)
14969 (org-back-to-heading t))
14970 (org-set-tags arg just-align))))
14972 (defun org-set-tags-to (data)
14973 "Set the tags of the current entry to DATA, replacing the current tags.
14974 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14975 If DATA is nil or the empty string, any tags will be removed."
14976 (interactive "sTags: ")
14977 (setq data
14978 (cond
14979 ((eq data nil) "")
14980 ((equal data "") "")
14981 ((stringp data)
14982 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14983 ":"))
14984 ((listp data)
14985 (concat ":" (mapconcat 'identity data ":") ":"))))
14986 (when data
14987 (save-excursion
14988 (org-back-to-heading t)
14989 (when (looking-at org-complex-heading-regexp)
14990 (if (match-end 5)
14991 (progn
14992 (goto-char (match-beginning 5))
14993 (insert data)
14994 (delete-region (point) (point-at-eol))
14995 (org-set-tags nil 'align))
14996 (goto-char (point-at-eol))
14997 (insert " " data)
14998 (org-set-tags nil 'align)))
14999 (beginning-of-line 1)
15000 (when (looking-at ".*?\\([ \t]+\\)$")
15001 (delete-region (match-beginning 1) (match-end 1))))))
15003 (defun org-align-all-tags ()
15004 "Align the tags in all headings."
15005 (interactive)
15006 (save-excursion
15007 (or (ignore-errors (org-back-to-heading t))
15008 (outline-next-heading))
15009 (if (org-at-heading-p)
15010 (org-set-tags t)
15011 (message "No headings"))))
15013 (defvar org-indent-indentation-per-level)
15014 (defun org-set-tags (&optional arg just-align)
15015 "Set the tags for the current headline.
15016 With prefix ARG, realign all tags in headings in the current buffer.
15017 When JUST-ALIGN is non-nil, only align tags."
15018 (interactive "P")
15019 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15020 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15021 'region-start-level
15022 'region))
15023 org-loop-over-headlines-in-active-region)
15024 (org-map-entries
15025 ;; We don't use ARG and JUST-ALIGN here because these args
15026 ;; are not useful when looping over headlines.
15027 #'org-set-tags
15028 org-loop-over-headlines-in-active-region
15030 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15031 (let ((org-setting-tags t))
15032 (if arg
15033 (save-excursion
15034 (goto-char (point-min))
15035 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15036 (while (re-search-forward org-outline-regexp-bol nil t)
15037 (org-set-tags nil t)
15038 (end-of-line)))
15039 (message "All tags realigned to column %d" org-tags-column))
15040 (let* ((current (org-get-tags-string))
15041 (col (current-column))
15042 (tags
15043 (if just-align current
15044 ;; Get a new set of tags from the user.
15045 (save-excursion
15046 (let* ((seen)
15047 (table
15048 (setq
15049 org-last-tags-completion-table
15050 ;; Uniquify tags in alists, yet preserve
15051 ;; structure (i.e., keywords).
15052 (delq nil
15053 (mapcar
15054 (lambda (pair)
15055 (let ((head (car pair)))
15056 (cond ((symbolp head) pair)
15057 ((member head seen) nil)
15058 (t (push head seen)
15059 pair))))
15060 (append
15061 (or org-current-tag-alist
15062 (org-get-buffer-tags))
15063 (and
15064 org-complete-tags-always-offer-all-agenda-tags
15065 (org-global-tags-completion-table
15066 (org-agenda-files))))))))
15067 (current-tags (org-split-string current ":"))
15068 (inherited-tags
15069 (nreverse (nthcdr (length current-tags)
15070 (nreverse (org-get-tags-at))))))
15071 (replace-regexp-in-string
15072 "\\([-+&]+\\|,\\)"
15074 (if (or (eq t org-use-fast-tag-selection)
15075 (and org-use-fast-tag-selection
15076 (delq nil (mapcar #'cdr table))))
15077 (org-fast-tag-selection
15078 current-tags inherited-tags table
15079 (and org-fast-tag-selection-include-todo
15080 org-todo-key-alist))
15081 (let ((org-add-colon-after-tag-completion
15082 (< 1 (length table))))
15083 (org-trim
15084 (completing-read
15085 "Tags: "
15086 #'org-tags-completion-function
15087 nil nil current 'org-tags-history))))))))))
15089 (when org-tags-sort-function
15090 (setq tags
15091 (mapconcat
15092 #'identity
15093 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15094 org-tags-sort-function)
15095 ":")))
15097 (if (not (org-string-nw-p tags)) (setq tags "")
15098 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15099 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15101 ;; Insert new tags at the correct column
15102 (beginning-of-line)
15103 (let ((level (if (looking-at org-outline-regexp)
15104 (- (match-end 0) (point) 1)
15105 1)))
15106 (cond
15107 ((and (equal current "") (equal tags "")))
15108 ((re-search-forward
15109 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15110 (line-end-position)
15112 (if (equal tags "") (replace-match "" t t)
15113 (goto-char (match-beginning 0))
15114 (let* ((c0 (current-column))
15115 ;; Compute offset for the case of org-indent-mode
15116 ;; active.
15117 (di (if (org-bound-and-true-p org-indent-mode)
15118 (* (1- org-indent-indentation-per-level)
15119 (1- level))
15121 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15122 (tc (+ org-tags-column
15123 (if (> org-tags-column 0) (- di) di)))
15124 (c1 (max (1+ c0)
15125 (if (> tc 0) tc
15126 (- (- tc) (string-width tags)))))
15127 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15128 (replace-match rpl t t)
15129 (when indent-tabs-mode (tabify p0 (point))))))
15130 (t (error "Tags alignment failed"))))
15131 (org-move-to-column col))
15132 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15134 (defun org-change-tag-in-region (beg end tag off)
15135 "Add or remove TAG for each entry in the region.
15136 This works in the agenda, and also in an org-mode buffer."
15137 (interactive
15138 (list (region-beginning) (region-end)
15139 (let ((org-last-tags-completion-table
15140 (if (derived-mode-p 'org-mode)
15141 (org-uniquify
15142 (delq nil (append (org-get-buffer-tags)
15143 (org-global-tags-completion-table))))
15144 (org-global-tags-completion-table))))
15145 (completing-read
15146 "Tag: " 'org-tags-completion-function nil nil nil
15147 'org-tags-history))
15148 (progn
15149 (message "[s]et or [r]emove? ")
15150 (equal (read-char-exclusive) ?r))))
15151 (when (fboundp 'deactivate-mark) (deactivate-mark))
15152 (let ((agendap (equal major-mode 'org-agenda-mode))
15153 l1 l2 m buf pos newhead (cnt 0))
15154 (goto-char end)
15155 (setq l2 (1- (org-current-line)))
15156 (goto-char beg)
15157 (setq l1 (org-current-line))
15158 (cl-loop for l from l1 to l2 do
15159 (org-goto-line l)
15160 (setq m (get-text-property (point) 'org-hd-marker))
15161 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15162 (and agendap m))
15163 (setq buf (if agendap (marker-buffer m) (current-buffer))
15164 pos (if agendap m (point)))
15165 (with-current-buffer buf
15166 (save-excursion
15167 (save-restriction
15168 (goto-char pos)
15169 (setq cnt (1+ cnt))
15170 (org-toggle-tag tag (if off 'off 'on))
15171 (setq newhead (org-get-heading)))))
15172 (and agendap (org-agenda-change-all-lines newhead m))))
15173 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15175 (defun org-tags-completion-function (string _predicate &optional flag)
15176 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15177 (confirm (lambda (x) (stringp (car x)))))
15178 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15179 (setq s1 (match-string 1 string)
15180 s2 (match-string 2 string))
15181 (setq s1 "" s2 string))
15182 (cond
15183 ((eq flag nil)
15184 ;; try completion
15185 (setq rtn (try-completion s2 ctable confirm))
15186 (when (stringp rtn)
15187 (setq rtn
15188 (concat s1 s2 (substring rtn (length s2))
15189 (if (and org-add-colon-after-tag-completion
15190 (assoc rtn ctable))
15191 ":" ""))))
15192 rtn)
15193 ((eq flag t)
15194 ;; all-completions
15195 (all-completions s2 ctable confirm))
15196 ((eq flag 'lambda)
15197 ;; exact match?
15198 (assoc s2 ctable)))))
15200 (defun org-fast-tag-insert (kwd tags face &optional end)
15201 "Insert KDW, and the TAGS, the latter with face FACE.
15202 Also insert END."
15203 (insert (format "%-12s" (concat kwd ":"))
15204 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15205 (or end "")))
15207 (defun org-fast-tag-show-exit (flag)
15208 (save-excursion
15209 (org-goto-line 3)
15210 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15211 (replace-match ""))
15212 (when flag
15213 (end-of-line 1)
15214 (org-move-to-column (- (window-width) 19) t)
15215 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15217 (defun org-set-current-tags-overlay (current prefix)
15218 "Add an overlay to CURRENT tag with PREFIX."
15219 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15220 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15221 (org-overlay-display org-tags-overlay (concat prefix s))))
15223 (defvar org-last-tag-selection-key nil)
15224 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15225 "Fast tag selection with single keys.
15226 CURRENT is the current list of tags in the headline, INHERITED is the
15227 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15228 possibly with grouping information. TODO-TABLE is a similar table with
15229 TODO keywords, should these have keys assigned to them.
15230 If the keys are nil, a-z are automatically assigned.
15231 Returns the new tags string, or nil to not change the current settings."
15232 (let* ((fulltable (append table todo-table))
15233 (maxlen (apply 'max (mapcar
15234 (lambda (x)
15235 (if (stringp (car x)) (string-width (car x)) 0))
15236 fulltable)))
15237 (buf (current-buffer))
15238 (expert (eq org-fast-tag-selection-single-key 'expert))
15239 (buffer-tags nil)
15240 (fwidth (+ maxlen 3 1 3))
15241 (ncol (/ (- (window-width) 4) fwidth))
15242 (i-face 'org-done)
15243 (c-face 'org-todo)
15244 tg cnt e c char c1 c2 ntable tbl rtn
15245 ov-start ov-end ov-prefix
15246 (exit-after-next org-fast-tag-selection-single-key)
15247 (done-keywords org-done-keywords)
15248 groups ingroup intaggroup)
15249 (save-excursion
15250 (beginning-of-line 1)
15251 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15252 (setq ov-start (match-beginning 1)
15253 ov-end (match-end 1)
15254 ov-prefix "")
15255 (setq ov-start (1- (point-at-eol))
15256 ov-end (1+ ov-start))
15257 (skip-chars-forward "^\n\r")
15258 (setq ov-prefix
15259 (concat
15260 (buffer-substring (1- (point)) (point))
15261 (if (> (current-column) org-tags-column)
15263 (make-string (- org-tags-column (current-column)) ?\ ))))))
15264 (move-overlay org-tags-overlay ov-start ov-end)
15265 (save-window-excursion
15266 (if expert
15267 (set-buffer (get-buffer-create " *Org tags*"))
15268 (delete-other-windows)
15269 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15270 (org-switch-to-buffer-other-window " *Org tags*"))
15271 (erase-buffer)
15272 (setq-local org-done-keywords done-keywords)
15273 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15274 (org-fast-tag-insert "Current" current c-face "\n\n")
15275 (org-fast-tag-show-exit exit-after-next)
15276 (org-set-current-tags-overlay current ov-prefix)
15277 (setq tbl fulltable char ?a cnt 0)
15278 (while (setq e (pop tbl))
15279 (cond
15280 ((eq (car e) :startgroup)
15281 (push '() groups) (setq ingroup t)
15282 (unless (zerop cnt)
15283 (setq cnt 0)
15284 (insert "\n"))
15285 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15286 ((eq (car e) :endgroup)
15287 (setq ingroup nil cnt 0)
15288 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15289 ((eq (car e) :startgrouptag)
15290 (setq intaggroup t)
15291 (unless (zerop cnt)
15292 (setq cnt 0)
15293 (insert "\n"))
15294 (insert "[ "))
15295 ((eq (car e) :endgrouptag)
15296 (setq intaggroup nil cnt 0)
15297 (insert "]\n"))
15298 ((equal e '(:newline))
15299 (unless (zerop cnt)
15300 (setq cnt 0)
15301 (insert "\n")
15302 (setq e (car tbl))
15303 (while (equal (car tbl) '(:newline))
15304 (insert "\n")
15305 (setq tbl (cdr tbl)))))
15306 ((equal e '(:grouptags)) (insert " : "))
15308 (setq tg (copy-sequence (car e)) c2 nil)
15309 (if (cdr e)
15310 (setq c (cdr e))
15311 ;; automatically assign a character.
15312 (setq c1 (string-to-char
15313 (downcase (substring
15314 tg (if (= (string-to-char tg) ?@) 1 0)))))
15315 (if (or (rassoc c1 ntable) (rassoc c1 table))
15316 (while (or (rassoc char ntable) (rassoc char table))
15317 (setq char (1+ char)))
15318 (setq c2 c1))
15319 (setq c (or c2 char)))
15320 (when ingroup (push tg (car groups)))
15321 (setq tg (org-add-props tg nil 'face
15322 (cond
15323 ((not (assoc tg table))
15324 (org-get-todo-face tg))
15325 ((member tg current) c-face)
15326 ((member tg inherited) i-face))))
15327 (when (equal (caar tbl) :grouptags)
15328 (org-add-props tg nil 'face 'org-tag-group))
15329 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15330 (insert "[" c "] " tg (make-string
15331 (- fwidth 4 (length tg)) ?\ ))
15332 (push (cons tg c) ntable)
15333 (when (= (cl-incf cnt) ncol)
15334 (insert "\n")
15335 (when (or ingroup intaggroup) (insert " "))
15336 (setq cnt 0)))))
15337 (setq ntable (nreverse ntable))
15338 (insert "\n")
15339 (goto-char (point-min))
15340 (unless expert (org-fit-window-to-buffer))
15341 (setq rtn
15342 (catch 'exit
15343 (while t
15344 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15345 (if (not groups) "no " "")
15346 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15347 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15348 (setq org-last-tag-selection-key c)
15349 (cond
15350 ((= c ?\r) (throw 'exit t))
15351 ((= c ?!)
15352 (setq groups (not groups))
15353 (goto-char (point-min))
15354 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15355 ((= c ?\C-c)
15356 (if (not expert)
15357 (org-fast-tag-show-exit
15358 (setq exit-after-next (not exit-after-next)))
15359 (setq expert nil)
15360 (delete-other-windows)
15361 (set-window-buffer (split-window-vertically) " *Org tags*")
15362 (org-switch-to-buffer-other-window " *Org tags*")
15363 (org-fit-window-to-buffer)))
15364 ((or (= c ?\C-g)
15365 (and (= c ?q) (not (rassoc c ntable))))
15366 (delete-overlay org-tags-overlay)
15367 (setq quit-flag t))
15368 ((= c ?\ )
15369 (setq current nil)
15370 (when exit-after-next (setq exit-after-next 'now)))
15371 ((= c ?\t)
15372 (condition-case nil
15373 (setq tg (completing-read
15374 "Tag: "
15375 (or buffer-tags
15376 (with-current-buffer buf
15377 (setq buffer-tags
15378 (org-get-buffer-tags))))))
15379 (quit (setq tg "")))
15380 (when (string-match "\\S-" tg)
15381 (cl-pushnew (list tg) buffer-tags :test #'equal)
15382 (if (member tg current)
15383 (setq current (delete tg current))
15384 (push tg current)))
15385 (when exit-after-next (setq exit-after-next 'now)))
15386 ((setq e (rassoc c todo-table) tg (car e))
15387 (with-current-buffer buf
15388 (save-excursion (org-todo tg)))
15389 (when exit-after-next (setq exit-after-next 'now)))
15390 ((setq e (rassoc c ntable) tg (car e))
15391 (if (member tg current)
15392 (setq current (delete tg current))
15393 (cl-loop for g in groups do
15394 (when (member tg g)
15395 (dolist (x g) (setq current (delete x current)))))
15396 (push tg current))
15397 (when exit-after-next (setq exit-after-next 'now))))
15399 ;; Create a sorted list
15400 (setq current
15401 (sort current
15402 (lambda (a b)
15403 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15404 (when (eq exit-after-next 'now) (throw 'exit t))
15405 (goto-char (point-min))
15406 (beginning-of-line 2)
15407 (delete-region (point) (point-at-eol))
15408 (org-fast-tag-insert "Current" current c-face)
15409 (org-set-current-tags-overlay current ov-prefix)
15410 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15411 (setq tg (match-string 1))
15412 (add-text-properties
15413 (match-beginning 1) (match-end 1)
15414 (list 'face
15415 (cond
15416 ((member tg current) c-face)
15417 ((member tg inherited) i-face)
15418 (t (get-text-property (match-beginning 1) 'face))))))
15419 (goto-char (point-min)))))
15420 (delete-overlay org-tags-overlay)
15421 (if rtn
15422 (mapconcat 'identity current ":")
15423 nil))))
15425 (defun org-get-tags-string ()
15426 "Get the TAGS string in the current headline."
15427 (unless (org-at-heading-p t)
15428 (user-error "Not on a heading"))
15429 (save-excursion
15430 (beginning-of-line 1)
15431 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15432 (match-string-no-properties 1)
15433 "")))
15435 (defun org-get-tags ()
15436 "Get the list of tags specified in the current headline."
15437 (org-split-string (org-get-tags-string) ":"))
15439 (defun org-get-buffer-tags ()
15440 "Get a table of all tags used in the buffer, for completion."
15441 (org-with-wide-buffer
15442 (goto-char (point-min))
15443 (let ((tag-re (concat org-outline-regexp-bol
15444 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15445 tags)
15446 (while (re-search-forward tag-re nil t)
15447 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15448 (push tag tags)))
15449 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15451 ;;;; The mapping API
15453 (defvar org-agenda-skip-comment-trees)
15454 (defvar org-agenda-skip-function)
15455 (defun org-map-entries (func &optional match scope &rest skip)
15456 "Call FUNC at each headline selected by MATCH in SCOPE.
15458 FUNC is a function or a lisp form. The function will be called without
15459 arguments, with the cursor positioned at the beginning of the headline.
15460 The return values of all calls to the function will be collected and
15461 returned as a list.
15463 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15464 does not need to preserve point. After evaluation, the cursor will be
15465 moved to the end of the line (presumably of the headline of the
15466 processed entry) and search continues from there. Under some
15467 circumstances, this may not produce the wanted results. For example,
15468 if you have removed (e.g. archived) the current (sub)tree it could
15469 mean that the next entry will be skipped entirely. In such cases, you
15470 can specify the position from where search should continue by making
15471 FUNC set the variable `org-map-continue-from' to the desired buffer
15472 position.
15474 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15475 Only headlines that are matched by this query will be considered during
15476 the iteration. When MATCH is nil or t, all headlines will be
15477 visited by the iteration.
15479 SCOPE determines the scope of this command. It can be any of:
15481 nil The current buffer, respecting the restriction if any
15482 tree The subtree started with the entry at point
15483 region The entries within the active region, if any
15484 region-start-level
15485 The entries within the active region, but only those at
15486 the same level than the first one.
15487 file The current buffer, without restriction
15488 file-with-archives
15489 The current buffer, and any archives associated with it
15490 agenda All agenda files
15491 agenda-with-archives
15492 All agenda files with any archive files associated with them
15493 \(file1 file2 ...)
15494 If this is a list, all files in the list will be scanned
15496 The remaining args are treated as settings for the skipping facilities of
15497 the scanner. The following items can be given here:
15499 archive skip trees with the archive tag
15500 comment skip trees with the COMMENT keyword
15501 function or Emacs Lisp form:
15502 will be used as value for `org-agenda-skip-function', so
15503 whenever the function returns a position, FUNC will not be
15504 called for that entry and search will continue from the
15505 position returned
15507 If your function needs to retrieve the tags including inherited tags
15508 at the *current* entry, you can use the value of the variable
15509 `org-scanner-tags' which will be much faster than getting the value
15510 with `org-get-tags-at'. If your function gets properties with
15511 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15512 to t around the call to `org-entry-properties' to get the same speedup.
15513 Note that if your function moves around to retrieve tags and properties at
15514 a *different* entry, you cannot use these techniques."
15515 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15516 (not (org-region-active-p)))
15517 (let* ((org-agenda-archives-mode nil) ; just to make sure
15518 (org-agenda-skip-archived-trees (memq 'archive skip))
15519 (org-agenda-skip-comment-trees (memq 'comment skip))
15520 (org-agenda-skip-function
15521 (car (org-delete-all '(comment archive) skip)))
15522 (org-tags-match-list-sublevels t)
15523 (start-level (eq scope 'region-start-level))
15524 matcher res
15525 org-todo-keywords-for-agenda
15526 org-done-keywords-for-agenda
15527 org-todo-keyword-alist-for-agenda
15528 org-tag-alist-for-agenda
15529 org--matcher-tags-todo-only)
15531 (cond
15532 ((eq match t) (setq matcher t))
15533 ((eq match nil) (setq matcher t))
15534 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15536 (save-excursion
15537 (save-restriction
15538 (cond ((eq scope 'tree)
15539 (org-back-to-heading t)
15540 (org-narrow-to-subtree)
15541 (setq scope nil))
15542 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15543 (org-region-active-p))
15544 ;; If needed, set start-level to a string like "2"
15545 (when start-level
15546 (save-excursion
15547 (goto-char (region-beginning))
15548 (unless (org-at-heading-p) (outline-next-heading))
15549 (setq start-level (org-current-level))))
15550 (narrow-to-region (region-beginning)
15551 (save-excursion
15552 (goto-char (region-end))
15553 (unless (and (bolp) (org-at-heading-p))
15554 (outline-next-heading))
15555 (point)))
15556 (setq scope nil)))
15558 (if (not scope)
15559 (progn
15560 (org-agenda-prepare-buffers
15561 (and buffer-file-name (list buffer-file-name)))
15562 (setq res
15563 (org-scan-tags
15564 func matcher org--matcher-tags-todo-only start-level)))
15565 ;; Get the right scope
15566 (cond
15567 ((and scope (listp scope) (symbolp (car scope)))
15568 (setq scope (eval scope)))
15569 ((eq scope 'agenda)
15570 (setq scope (org-agenda-files t)))
15571 ((eq scope 'agenda-with-archives)
15572 (setq scope (org-agenda-files t))
15573 (setq scope (org-add-archive-files scope)))
15574 ((eq scope 'file)
15575 (setq scope (and buffer-file-name (list buffer-file-name))))
15576 ((eq scope 'file-with-archives)
15577 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15578 (org-agenda-prepare-buffers scope)
15579 (dolist (file scope)
15580 (with-current-buffer (org-find-base-buffer-visiting file)
15581 (save-excursion
15582 (save-restriction
15583 (widen)
15584 (goto-char (point-min))
15585 (setq res
15586 (append
15588 (org-scan-tags
15589 func matcher org--matcher-tags-todo-only))))))))))
15590 res)))
15592 ;;; Properties API
15594 (defconst org-special-properties
15595 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15596 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15597 "The special properties valid in Org mode.
15598 These are properties that are not defined in the property drawer,
15599 but in some other way.")
15601 (defconst org-default-properties
15602 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15603 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15604 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15605 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15606 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15607 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15608 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15609 "Some properties that are used by Org mode for various purposes.
15610 Being in this list makes sure that they are offered for completion.")
15612 (defun org--valid-property-p (property)
15613 "Non nil when string PROPERTY is a valid property name."
15614 (not
15615 (or (equal property "")
15616 (org-string-match-p "\\s-" property))))
15618 (defun org--update-property-plist (key val props)
15619 "Associate KEY to VAL in alist PROPS.
15620 Modifications are made by side-effect. Return new alist."
15621 (let* ((appending (string= (substring key -1) "+"))
15622 (key (if appending (substring key 0 -1) key))
15623 (old (assoc-string key props t)))
15624 (if (not old) (cons (cons key val) props)
15625 (setcdr old (if appending (concat (cdr old) " " val) val))
15626 props)))
15628 (defun org-get-property-block (&optional beg force)
15629 "Return the (beg . end) range of the body of the property drawer.
15630 BEG is the beginning of the current subtree, or of the part
15631 before the first headline. If it is not given, it will be found.
15632 If the drawer does not exist, create it if FORCE is non-nil, or
15633 return nil."
15634 (org-with-wide-buffer
15635 (when beg (goto-char beg))
15636 (unless (org-before-first-heading-p)
15637 (let ((beg (cond (beg)
15638 ((or (not (featurep 'org-inlinetask))
15639 (org-inlinetask-in-task-p))
15640 (org-back-to-heading t))
15641 (t (org-with-limited-levels (org-back-to-heading t))))))
15642 (forward-line)
15643 (when (looking-at-p org-planning-line-re) (forward-line))
15644 (cond ((looking-at org-property-drawer-re)
15645 (forward-line)
15646 (cons (point) (progn (goto-char (match-end 0))
15647 (line-beginning-position))))
15648 (force
15649 (goto-char beg)
15650 (org-insert-property-drawer)
15651 (let ((pos (save-excursion (search-forward ":END:")
15652 (line-beginning-position))))
15653 (cons pos pos))))))))
15655 (defun org-at-property-p ()
15656 "Non-nil when point is inside a property drawer.
15657 See `org-property-re' for match data, if applicable."
15658 (save-excursion
15659 (beginning-of-line)
15660 (and (looking-at org-property-re)
15661 (let ((property-drawer (save-match-data (org-get-property-block))))
15662 (and property-drawer
15663 (>= (point) (car property-drawer))
15664 (< (point) (cdr property-drawer)))))))
15666 (defun org-property-action ()
15667 "Do an action on properties."
15668 (interactive)
15669 (unless (org-at-property-p) (user-error "Not at a property"))
15670 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15671 (let ((c (read-char-exclusive)))
15672 (cl-case c
15673 (?s (call-interactively #'org-set-property))
15674 (?d (call-interactively #'org-delete-property))
15675 (?D (call-interactively #'org-delete-property-globally))
15676 (?c (call-interactively #'org-compute-property-at-point))
15677 (otherwise (user-error "No such property action %c" c)))))
15679 (defun org-inc-effort ()
15680 "Increment the value of the effort property in the current entry."
15681 (interactive)
15682 (org-set-effort nil t))
15684 (defvar org-clock-effort) ; Defined in org-clock.el.
15685 (defvar org-clock-current-task) ; Defined in org-clock.el.
15686 (defun org-set-effort (&optional value increment)
15687 "Set the effort property of the current entry.
15688 With numerical prefix arg, use the nth allowed value, 0 stands for the
15689 10th allowed value.
15691 When INCREMENT is non-nil, set the property to the next allowed value."
15692 (interactive "P")
15693 (when (equal value 0) (setq value 10))
15694 (let* ((completion-ignore-case t)
15695 (prop org-effort-property)
15696 (cur (org-entry-get nil prop))
15697 (allowed (org-property-get-allowed-values nil prop 'table))
15698 (existing (mapcar 'list (org-property-values prop)))
15699 (heading (nth 4 (org-heading-components)))
15701 (val (cond
15702 ((stringp value) value)
15703 ((and allowed (integerp value))
15704 (or (car (nth (1- value) allowed))
15705 (car (org-last allowed))))
15706 ((and allowed increment)
15707 (or (cl-caadr (member (list cur) allowed))
15708 (user-error "Allowed effort values are not set")))
15709 (allowed
15710 (message "Select 1-9,0, [RET%s]: %s"
15711 (if cur (concat "=" cur) "")
15712 (mapconcat 'car allowed " "))
15713 (setq rpl (read-char-exclusive))
15714 (if (equal rpl ?\r)
15716 (setq rpl (- rpl ?0))
15717 (when (equal rpl 0) (setq rpl 10))
15718 (if (and (> rpl 0) (<= rpl (length allowed)))
15719 (car (nth (1- rpl) allowed))
15720 (org-completing-read "Effort: " allowed nil))))
15722 (org-completing-read
15723 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15724 (concat "[" cur "]") "")
15725 ": ")
15726 existing nil nil "" nil cur)))))
15727 (unless (equal (org-entry-get nil prop) val)
15728 (org-entry-put nil prop val))
15729 (org-refresh-property
15730 '((effort . identity)
15731 (effort-minutes . org-duration-string-to-minutes))
15732 val)
15733 (when (string= heading org-clock-current-task)
15734 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15735 (org-clock-update-mode-line))
15736 (message "%s is now %s" prop val)))
15738 (defun org-entry-properties (&optional pom which)
15739 "Get all properties of the current entry.
15741 When POM is a buffer position, get all properties from the entry
15742 there instead.
15744 This includes the TODO keyword, the tags, time strings for
15745 deadline, scheduled, and clocking, and any additional properties
15746 defined in the entry.
15748 If WHICH is nil or `all', get all properties. If WHICH is
15749 `special' or `standard', only get that subclass. If WHICH is
15750 a string, only get that property.
15752 Return value is an alist. Keys are properties, as upcased
15753 strings."
15754 (org-with-point-at pom
15755 (when (and (derived-mode-p 'org-mode)
15756 (ignore-errors (org-back-to-heading t)))
15757 (catch 'exit
15758 (let* ((beg (point))
15759 (specific (and (stringp which) (upcase which)))
15760 (which (cond ((not specific) which)
15761 ((member specific org-special-properties) 'special)
15762 (t 'standard)))
15763 props)
15764 ;; Get the special properties, like TODO and TAGS.
15765 (when (memq which '(nil all special))
15766 (when (or (not specific) (string= specific "CLOCKSUM"))
15767 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15768 (when clocksum
15769 (push (cons "CLOCKSUM"
15770 (org-minutes-to-clocksum-string clocksum))
15771 props)))
15772 (when specific (throw 'exit props)))
15773 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15774 (let ((clocksumt (get-text-property (point)
15775 :org-clock-minutes-today)))
15776 (when clocksumt
15777 (push (cons "CLOCKSUM_T"
15778 (org-minutes-to-clocksum-string clocksumt))
15779 props)))
15780 (when specific (throw 'exit props)))
15781 (when (or (not specific) (string= specific "ITEM"))
15782 (when (looking-at org-complex-heading-regexp)
15783 (push (cons "ITEM"
15784 (let ((title (match-string-no-properties 4)))
15785 (if (org-string-nw-p title)
15786 (org-remove-tabs title)
15787 "")))
15788 props))
15789 (when specific (throw 'exit props)))
15790 (when (or (not specific) (string= specific "TODO"))
15791 (let ((case-fold-search nil))
15792 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15793 (push (cons "TODO" (match-string-no-properties 2)) props)))
15794 (when specific (throw 'exit props)))
15795 (when (or (not specific) (string= specific "PRIORITY"))
15796 (push (cons "PRIORITY"
15797 (if (looking-at org-priority-regexp)
15798 (match-string-no-properties 2)
15799 (char-to-string org-default-priority)))
15800 props)
15801 (when specific (throw 'exit props)))
15802 (when (or (not specific) (string= specific "FILE"))
15803 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15804 props)
15805 (when specific (throw 'exit props)))
15806 (when (or (not specific) (string= specific "TAGS"))
15807 (let ((value (org-string-nw-p (org-get-tags-string))))
15808 (when value (push (cons "TAGS" value) props)))
15809 (when specific (throw 'exit props)))
15810 (when (or (not specific) (string= specific "ALLTAGS"))
15811 (let ((value (org-get-tags-at)))
15812 (when value
15813 (push (cons "ALLTAGS"
15814 (format ":%s:" (mapconcat #'identity value ":")))
15815 props)))
15816 (when specific (throw 'exit props)))
15817 (when (or (not specific) (string= specific "BLOCKED"))
15818 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15819 (when specific (throw 'exit props)))
15820 (when (or (not specific)
15821 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15822 (forward-line)
15823 (when (looking-at-p org-planning-line-re)
15824 (end-of-line)
15825 (let ((bol (line-beginning-position))
15826 ;; Backward compatibility: time keywords used to
15827 ;; be configurable (before 8.3). Make sure we
15828 ;; get the correct keyword.
15829 (key-assoc `(("CLOSED" . ,org-closed-string)
15830 ("DEADLINE" . ,org-deadline-string)
15831 ("SCHEDULED" . ,org-scheduled-string))))
15832 (dolist (pair (if specific (list (assoc specific key-assoc))
15833 key-assoc))
15834 (save-excursion
15835 (when (search-backward (cdr pair) bol t)
15836 (goto-char (match-end 0))
15837 (skip-chars-forward " \t")
15838 (and (looking-at org-ts-regexp-both)
15839 (push (cons (car pair)
15840 (match-string-no-properties 0))
15841 props)))))))
15842 (when specific (throw 'exit props)))
15843 (when (or (not specific)
15844 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15845 (let ((find-ts
15846 (lambda (end ts)
15847 ;; Fix next time-stamp before END. TS is the
15848 ;; list of time-stamps found so far.
15849 (let ((ts ts)
15850 (regexp (cond
15851 ((string= specific "TIMESTAMP")
15852 org-ts-regexp)
15853 ((string= specific "TIMESTAMP_IA")
15854 org-ts-regexp-inactive)
15855 ((assoc "TIMESTAMP_IA" ts)
15856 org-ts-regexp)
15857 ((assoc "TIMESTAMP" ts)
15858 org-ts-regexp-inactive)
15859 (t org-ts-regexp-both))))
15860 (catch 'next
15861 (while (re-search-forward regexp end t)
15862 (backward-char)
15863 (let ((object (org-element-context)))
15864 ;; Accept to match timestamps in node
15865 ;; properties, too.
15866 (when (memq (org-element-type object)
15867 '(node-property timestamp))
15868 (let ((type
15869 (org-element-property :type object)))
15870 (cond
15871 ((and (memq type '(active active-range))
15872 (not (equal specific "TIMESTAMP_IA")))
15873 (unless (assoc "TIMESTAMP" ts)
15874 (push (cons "TIMESTAMP"
15875 (org-element-property
15876 :raw-value object))
15878 (when specific (throw 'exit ts))))
15879 ((and (memq type '(inactive inactive-range))
15880 (not (string= specific "TIMESTAMP")))
15881 (unless (assoc "TIMESTAMP_IA" ts)
15882 (push (cons "TIMESTAMP_IA"
15883 (org-element-property
15884 :raw-value object))
15886 (when specific (throw 'exit ts))))))
15887 ;; Both timestamp types are found,
15888 ;; move to next part.
15889 (when (= (length ts) 2) (throw 'next ts)))))
15890 ts)))))
15891 (goto-char beg)
15892 ;; First look for timestamps within headline.
15893 (let ((ts (funcall find-ts (line-end-position) nil)))
15894 (if (= (length ts) 2) (setq props (nconc ts props))
15895 (forward-line)
15896 ;; Then find timestamps in the section, skipping
15897 ;; planning line.
15898 (when (looking-at-p org-planning-line-re)
15899 (forward-line))
15900 (let ((end (save-excursion (outline-next-heading))))
15901 (setq props (nconc (funcall find-ts end ts) props))))))))
15902 ;; Get the standard properties, like :PROP:.
15903 (when (memq which '(nil all standard))
15904 ;; If we are looking after a specific property, delegate
15905 ;; to `org-entry-get', which is faster. However, make an
15906 ;; exception for "CATEGORY", since it can be also set
15907 ;; through keywords (i.e. #+CATEGORY).
15908 (if (and specific (not (equal specific "CATEGORY")))
15909 (let ((value (org-entry-get beg specific nil t)))
15910 (throw 'exit (and value (list (cons specific value)))))
15911 (let ((range (org-get-property-block beg)))
15912 (when range
15913 (let ((end (cdr range)) seen-base)
15914 (goto-char (car range))
15915 ;; Unlike to `org--update-property-plist', we
15916 ;; handle the case where base values is found
15917 ;; after its extension. We also forbid standard
15918 ;; properties to be named as special properties.
15919 (while (re-search-forward org-property-re end t)
15920 (let* ((key (upcase (match-string-no-properties 2)))
15921 (extendp (org-string-match-p "\\+\\'" key))
15922 (key-base (if extendp (substring key 0 -1) key))
15923 (value (match-string-no-properties 3)))
15924 (cond
15925 ((member-ignore-case key-base org-special-properties))
15926 (extendp
15927 (setq props
15928 (org--update-property-plist key value props)))
15929 ((member key seen-base))
15930 (t (push key seen-base)
15931 (let ((p (assoc-string key props t)))
15932 (if p (setcdr p (concat value " " (cdr p)))
15933 (push (cons key value) props))))))))))))
15934 (unless (assoc "CATEGORY" props)
15935 (push (cons "CATEGORY" (org-get-category beg)) props)
15936 (when (string= specific "CATEGORY") (throw 'exit props)))
15937 ;; Return value.
15938 props)))))
15940 (defun org-property--local-values (property literal-nil)
15941 "Return value for PROPERTY in current entry.
15942 Value is a list whose car is the base value for PROPERTY and cdr
15943 a list of accumulated values. Return nil if neither is found in
15944 the entry. Also return nil when PROPERTY is set to \"nil\",
15945 unless LITERAL-NIL is non-nil."
15946 (let ((range (org-get-property-block)))
15947 (when range
15948 (goto-char (car range))
15949 (let* ((case-fold-search t)
15950 (end (cdr range))
15951 (value
15952 ;; Base value.
15953 (save-excursion
15954 (let ((v (and (re-search-forward
15955 (org-re-property property nil t) end t)
15956 (match-string-no-properties 3))))
15957 (list (if literal-nil v (org-not-nil v)))))))
15958 ;; Find additional values.
15959 (let* ((property+ (org-re-property (concat property "+") nil t)))
15960 (while (re-search-forward property+ end t)
15961 (push (match-string-no-properties 3) value)))
15962 ;; Return final values.
15963 (and (not (equal value '(nil))) (nreverse value))))))
15965 (defun org-entry-get (pom property &optional inherit literal-nil)
15966 "Get value of PROPERTY for entry or content at point-or-marker POM.
15968 If INHERIT is non-nil and the entry does not have the property,
15969 then also check higher levels of the hierarchy. If INHERIT is
15970 the symbol `selective', use inheritance only if the setting in
15971 `org-use-property-inheritance' selects PROPERTY for inheritance.
15973 If the property is present but empty, the return value is the
15974 empty string. If the property is not present at all, nil is
15975 returned. In any other case, return the value as a string.
15976 Search is case-insensitive.
15978 If LITERAL-NIL is set, return the string value \"nil\" as
15979 a string, do not interpret it as the list atom nil. This is used
15980 for inheritance when a \"nil\" value can supersede a non-nil
15981 value higher up the hierarchy."
15982 (org-with-point-at pom
15983 (cond
15984 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15985 ;; We need a special property. Use `org-entry-properties' to
15986 ;; retrieve it, but specify the wanted property.
15987 (cdr (assoc-string property (org-entry-properties nil property))))
15988 ((and inherit
15989 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15990 (org-entry-get-with-inheritance property literal-nil))
15992 (let* ((local (org-property--local-values property literal-nil))
15993 (value (and local (mapconcat #'identity (delq nil local) " "))))
15994 (if literal-nil value (org-not-nil value)))))))
15996 (defun org-property-or-variable-value (var &optional inherit)
15997 "Check if there is a property fixing the value of VAR.
15998 If yes, return this value. If not, return the current value of the variable."
15999 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
16000 (if (and prop (stringp prop) (string-match "\\S-" prop))
16001 (read prop)
16002 (symbol-value var))))
16004 (defun org-entry-delete (pom property)
16005 "Delete PROPERTY from entry at point-or-marker POM.
16006 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16007 non-nil when a property was removed."
16008 (unless (member property org-special-properties)
16009 (org-with-point-at pom
16010 (let ((range (org-get-property-block)))
16011 (when range
16012 (let* ((begin (car range))
16013 (origin (cdr range))
16014 (end (copy-marker origin))
16015 (re (org-re-property
16016 (concat (regexp-quote property) "\\+?") t t)))
16017 (goto-char begin)
16018 (while (re-search-forward re end t)
16019 (delete-region (match-beginning 0) (line-beginning-position 2)))
16020 ;; If drawer is empty, remove it altogether.
16021 (when (= begin end)
16022 (delete-region (line-beginning-position 0)
16023 (line-beginning-position 2)))
16024 ;; Return non-nil if some property was removed.
16025 (prog1 (/= end origin) (set-marker end nil))))))))
16027 ;; Multi-values properties are properties that contain multiple values
16028 ;; These values are assumed to be single words, separated by whitespace.
16029 (defun org-entry-add-to-multivalued-property (pom property value)
16030 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16031 (let* ((old (org-entry-get pom property))
16032 (values (and old (org-split-string old "[ \t]"))))
16033 (setq value (org-entry-protect-space value))
16034 (unless (member value values)
16035 (setq values (append values (list value)))
16036 (org-entry-put pom property
16037 (mapconcat 'identity values " ")))))
16039 (defun org-entry-remove-from-multivalued-property (pom property value)
16040 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16041 (let* ((old (org-entry-get pom property))
16042 (values (and old (org-split-string old "[ \t]"))))
16043 (setq value (org-entry-protect-space value))
16044 (when (member value values)
16045 (setq values (delete value values))
16046 (org-entry-put pom property
16047 (mapconcat 'identity values " ")))))
16049 (defun org-entry-member-in-multivalued-property (pom property value)
16050 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16051 (let* ((old (org-entry-get pom property))
16052 (values (and old (org-split-string old "[ \t]"))))
16053 (setq value (org-entry-protect-space value))
16054 (member value values)))
16056 (defun org-entry-get-multivalued-property (pom property)
16057 "Return a list of values in a multivalued property."
16058 (let* ((value (org-entry-get pom property))
16059 (values (and value (org-split-string value "[ \t]"))))
16060 (mapcar 'org-entry-restore-space values)))
16062 (defun org-entry-put-multivalued-property (pom property &rest values)
16063 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16064 VALUES should be a list of strings. Spaces will be protected."
16065 (org-entry-put pom property
16066 (mapconcat 'org-entry-protect-space values " "))
16067 (let* ((value (org-entry-get pom property))
16068 (values (and value (org-split-string value "[ \t]"))))
16069 (mapcar 'org-entry-restore-space values)))
16071 (defun org-entry-protect-space (s)
16072 "Protect spaces and newline in string S."
16073 (while (string-match " " s)
16074 (setq s (replace-match "%20" t t s)))
16075 (while (string-match "\n" s)
16076 (setq s (replace-match "%0A" t t s)))
16079 (defun org-entry-restore-space (s)
16080 "Restore spaces and newline in string S."
16081 (while (string-match "%20" s)
16082 (setq s (replace-match " " t t s)))
16083 (while (string-match "%0A" s)
16084 (setq s (replace-match "\n" t t s)))
16087 (defvar org-entry-property-inherited-from (make-marker)
16088 "Marker pointing to the entry from where a property was inherited.
16089 Each call to `org-entry-get-with-inheritance' will set this marker to the
16090 location of the entry where the inheritance search matched. If there was
16091 no match, the marker will point nowhere.
16092 Note that also `org-entry-get' calls this function, if the INHERIT flag
16093 is set.")
16095 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16096 "Get PROPERTY of entry or content at point, search higher levels if needed.
16097 The search will stop at the first ancestor which has the property defined.
16098 If the value found is \"nil\", return nil to show that the property
16099 should be considered as undefined (this is the meaning of nil here).
16100 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16101 (move-marker org-entry-property-inherited-from nil)
16102 (org-with-wide-buffer
16103 (let (value)
16104 (catch 'exit
16105 (while t
16106 (let ((v (org-property--local-values property literal-nil)))
16107 (when v
16108 (setq value
16109 (concat (mapconcat #'identity (delq nil v) " ")
16110 (and value " ")
16111 value)))
16112 (cond
16113 ((car v)
16114 (org-back-to-heading t)
16115 (move-marker org-entry-property-inherited-from (point))
16116 (throw 'exit nil))
16117 ((org-up-heading-safe))
16119 (let ((global
16120 (cdr (or (assoc-string property org-file-properties t)
16121 (assoc-string property org-global-properties t)
16122 (assoc-string property org-global-properties-fixed t)))))
16123 (cond ((not global))
16124 (value (setq value (concat global " " value)))
16125 (t (setq value global))))
16126 (throw 'exit nil))))))
16127 (if literal-nil value (org-not-nil value)))))
16129 (defvar org-property-changed-functions nil
16130 "Hook called when the value of a property has changed.
16131 Each hook function should accept two arguments, the name of the property
16132 and the new value.")
16134 (defun org-entry-put (pom property value)
16135 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16137 If the value is nil, it is converted to the empty string. If it
16138 is not a string, an error is raised. Also raise an error on
16139 invalid property names.
16141 PROPERTY can be any regular property (see
16142 `org-special-properties'). It can also be \"TODO\",
16143 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16145 For the last two properties, VALUE may have any of the special
16146 values \"earlier\" and \"later\". The function then increases or
16147 decreases scheduled or deadline date by one day."
16148 (cond ((null value) (setq value ""))
16149 ((not (stringp value)) (error "Properties values should be strings"))
16150 ((not (org--valid-property-p property))
16151 (user-error "Invalid property name: \"%s\"" property)))
16152 (org-with-point-at pom
16153 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16154 (org-back-to-heading t)
16155 (org-with-limited-levels (org-back-to-heading t)))
16156 (let ((beg (point)))
16157 (cond
16158 ((equal property "TODO")
16159 (cond ((not (org-string-nw-p value)) (setq value 'none))
16160 ((not (member value org-todo-keywords-1))
16161 (user-error "\"%s\" is not a valid TODO state" value)))
16162 (org-todo value)
16163 (org-set-tags nil 'align))
16164 ((equal property "PRIORITY")
16165 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16166 (org-set-tags nil 'align))
16167 ((equal property "SCHEDULED")
16168 (forward-line)
16169 (if (and (looking-at-p org-planning-line-re)
16170 (re-search-forward
16171 org-scheduled-time-regexp (line-end-position) t))
16172 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16173 ((string= value "later") (org-timestamp-change 1 'day))
16174 ((string= value "") (org-schedule '(4)))
16175 (t (org-schedule nil value)))
16176 (if (member value '("earlier" "later" ""))
16177 (call-interactively #'org-schedule)
16178 (org-schedule nil value))))
16179 ((equal property "DEADLINE")
16180 (forward-line)
16181 (if (and (looking-at-p org-planning-line-re)
16182 (re-search-forward
16183 org-deadline-time-regexp (line-end-position) t))
16184 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16185 ((string= value "later") (org-timestamp-change 1 'day))
16186 ((string= value "") (org-deadline '(4)))
16187 (t (org-deadline nil value)))
16188 (if (member value '("earlier" "later" ""))
16189 (call-interactively #'org-deadline)
16190 (org-deadline nil value))))
16191 ((member property org-special-properties)
16192 (error "The %s property cannot be set with `org-entry-put'" property))
16194 (let* ((range (org-get-property-block beg 'force))
16195 (end (cdr range))
16196 (case-fold-search t))
16197 (goto-char (car range))
16198 (if (re-search-forward (org-re-property property nil t) end t)
16199 (progn (delete-region (match-beginning 0) (match-end 0))
16200 (goto-char (match-beginning 0)))
16201 (goto-char end)
16202 (insert "\n")
16203 (backward-char))
16204 (insert ":" property ":")
16205 (when value (insert " " value))
16206 (org-indent-line)))))
16207 (run-hook-with-args 'org-property-changed-functions property value)))
16209 (defun org-buffer-property-keys
16210 (&optional specials defaults columns ignore-malformed)
16211 "Get all property keys in the current buffer.
16213 When SPECIALS is non-nil, also list the special properties that
16214 reflect things like tags and TODO state.
16216 When DEFAULTS is non-nil, also include properties that has
16217 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16218 DESCRIPTION, LOCATION, and LOGGING and others.
16220 When COLUMNS in non-nil, also include property names given in
16221 COLUMN formats in the current buffer.
16223 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16224 automatically performed, such drawers will be silently ignored."
16225 (let ((case-fold-search t)
16226 (props (append
16227 (and specials org-special-properties)
16228 (and defaults (cons org-effort-property org-default-properties))
16229 nil)))
16230 (org-with-wide-buffer
16231 (goto-char (point-min))
16232 (while (re-search-forward org-property-start-re nil t)
16233 (let ((range (org-get-property-block)))
16234 (catch 'skip
16235 (unless range
16236 (when (and (not ignore-malformed)
16237 (not (org-before-first-heading-p))
16238 (y-or-n-p (format "Malformed drawer at %d, repair?"
16239 (line-beginning-position))))
16240 (org-get-property-block nil t))
16241 (throw 'skip nil))
16242 (goto-char (car range))
16243 (let ((begin (car range))
16244 (end (cdr range)))
16245 ;; Make sure that found property block is not located
16246 ;; before current point, as it would generate an infloop.
16247 ;; It can happen, for example, in the following
16248 ;; situation:
16250 ;; * Headline
16251 ;; :PROPERTIES:
16252 ;; ...
16253 ;; :END:
16254 ;; *************** Inlinetask
16255 ;; #+BEGIN_EXAMPLE
16256 ;; :PROPERTIES:
16257 ;; #+END_EXAMPLE
16259 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16260 (while (< (point) end)
16261 (let ((p (progn (looking-at org-property-re)
16262 (match-string-no-properties 2))))
16263 ;; Only add true property name, not extension symbol.
16264 (push (if (not (org-string-match-p "\\+\\'" p)) p
16265 (substring p 0 -1))
16266 props))
16267 (forward-line))))
16268 (outline-next-heading)))
16269 (when columns
16270 (goto-char (point-min))
16271 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16272 (let ((element (org-element-at-point)))
16273 (when (memq (org-element-type element) '(keyword node-property))
16274 (let ((value (org-element-property :value element))
16275 (start 0))
16276 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16277 (setq start (match-end 0))
16278 (let ((p (match-string-no-properties 1 value)))
16279 (unless (member-ignore-case p org-special-properties)
16280 (push p props))))))))))
16281 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16283 (defun org-property-values (key)
16284 "List all non-nil values of property KEY in current buffer."
16285 (org-with-wide-buffer
16286 (goto-char (point-min))
16287 (let ((case-fold-search t)
16288 (re (org-re-property key))
16289 values)
16290 (while (re-search-forward re nil t)
16291 (push (org-entry-get (point) key) values))
16292 (delete-dups values))))
16294 (defun org-insert-property-drawer ()
16295 "Insert a property drawer into the current entry."
16296 (org-with-wide-buffer
16297 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16298 (org-back-to-heading t)
16299 (org-with-limited-levels (org-back-to-heading t)))
16300 (forward-line)
16301 (when (looking-at-p org-planning-line-re) (forward-line))
16302 (unless (looking-at-p org-property-drawer-re)
16303 ;; Make sure we start editing a line from current entry, not from
16304 ;; next one. It prevents extending text properties or overlays
16305 ;; belonging to the latter.
16306 (when (bolp) (backward-char))
16307 (let ((begin (1+ (point)))
16308 (inhibit-read-only t))
16309 (insert "\n:PROPERTIES:\n:END:")
16310 (when (eobp) (insert "\n"))
16311 (org-indent-region begin (point))))))
16313 (defun org-insert-drawer (&optional arg drawer)
16314 "Insert a drawer at point.
16316 When optional argument ARG is non-nil, insert a property drawer.
16318 Optional argument DRAWER, when non-nil, is a string representing
16319 drawer's name. Otherwise, the user is prompted for a name.
16321 If a region is active, insert the drawer around that region
16322 instead.
16324 Point is left between drawer's boundaries."
16325 (interactive "P")
16326 (let* ((drawer (if arg "PROPERTIES"
16327 (or drawer (read-from-minibuffer "Drawer: ")))))
16328 (cond
16329 ;; With C-u, fall back on `org-insert-property-drawer'
16330 (arg (org-insert-property-drawer))
16331 ;; Check validity of suggested drawer's name.
16332 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16333 (user-error "Invalid drawer name"))
16334 ;; With an active region, insert a drawer at point.
16335 ((not (org-region-active-p))
16336 (progn
16337 (unless (bolp) (insert "\n"))
16338 (insert (format ":%s:\n\n:END:\n" drawer))
16339 (forward-line -2)))
16340 ;; Otherwise, insert the drawer at point
16342 (let ((rbeg (region-beginning))
16343 (rend (copy-marker (region-end))))
16344 (unwind-protect
16345 (progn
16346 (goto-char rbeg)
16347 (beginning-of-line)
16348 (when (save-excursion
16349 (re-search-forward org-outline-regexp-bol rend t))
16350 (user-error "Drawers cannot contain headlines"))
16351 ;; Position point at the beginning of the first
16352 ;; non-blank line in region. Insert drawer's opening
16353 ;; there, then indent it.
16354 (org-skip-whitespace)
16355 (beginning-of-line)
16356 (insert ":" drawer ":\n")
16357 (forward-line -1)
16358 (indent-for-tab-command)
16359 ;; Move point to the beginning of the first blank line
16360 ;; after the last non-blank line in region. Insert
16361 ;; drawer's closing, then indent it.
16362 (goto-char rend)
16363 (skip-chars-backward " \r\t\n")
16364 (insert "\n:END:")
16365 (deactivate-mark t)
16366 (indent-for-tab-command)
16367 (unless (eolp) (insert "\n")))
16368 ;; Clear marker, whatever the outcome of insertion is.
16369 (set-marker rend nil)))))))
16371 (defvar org-property-set-functions-alist nil
16372 "Property set function alist.
16373 Each entry should have the following format:
16375 (PROPERTY . READ-FUNCTION)
16377 The read function will be called with the same argument as
16378 `org-completing-read'.")
16380 (defun org-set-property-function (property)
16381 "Get the function that should be used to set PROPERTY.
16382 This is computed according to `org-property-set-functions-alist'."
16383 (or (cdr (assoc property org-property-set-functions-alist))
16384 'org-completing-read))
16386 (defun org-read-property-value (property)
16387 "Read PROPERTY value from user."
16388 (let* ((completion-ignore-case t)
16389 (allowed (org-property-get-allowed-values nil property 'table))
16390 (cur (org-entry-get nil property))
16391 (prompt (concat property " value"
16392 (if (and cur (string-match "\\S-" cur))
16393 (concat " [" cur "]") "") ": "))
16394 (set-function (org-set-property-function property))
16395 (val (if allowed
16396 (funcall set-function prompt allowed nil
16397 (not (get-text-property 0 'org-unrestricted
16398 (caar allowed))))
16399 (funcall set-function prompt
16400 (mapcar 'list (org-property-values property))
16401 nil nil "" nil cur))))
16402 (org-trim val)))
16404 (defvar org-last-set-property nil)
16405 (defvar org-last-set-property-value nil)
16406 (defun org-read-property-name ()
16407 "Read a property name."
16408 (let ((completion-ignore-case t)
16409 (default-prop (or (and (org-at-property-p)
16410 (match-string-no-properties 2))
16411 org-last-set-property)))
16412 (org-completing-read
16413 (concat "Property"
16414 (if default-prop (concat " [" default-prop "]") "")
16415 ": ")
16416 (mapcar #'list (org-buffer-property-keys nil t t))
16417 nil nil nil nil default-prop)))
16419 (defun org-set-property-and-value (use-last)
16420 "Allow to set [PROPERTY]: [value] direction from prompt.
16421 When use-default, don't even ask, just use the last
16422 \"[PROPERTY]: [value]\" string from the history."
16423 (interactive "P")
16424 (let* ((completion-ignore-case t)
16425 (pv (or (and use-last org-last-set-property-value)
16426 (org-completing-read
16427 "Enter a \"[Property]: [value]\" pair: "
16428 nil nil nil nil nil
16429 org-last-set-property-value)))
16430 prop val)
16431 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16432 (setq prop (match-string 1 pv)
16433 val (match-string 2 pv))
16434 (org-set-property prop val))))
16436 (defun org-set-property (property value)
16437 "In the current entry, set PROPERTY to VALUE.
16439 When called interactively, this will prompt for a property name, offering
16440 completion on existing and default properties. And then it will prompt
16441 for a value, offering completion either on allowed values (via an inherited
16442 xxx_ALL property) or on existing values in other instances of this property
16443 in the current file.
16445 Throw an error when trying to set a property with an invalid name."
16446 (interactive (list nil nil))
16447 (let ((property (or property (org-read-property-name))))
16448 ;; `org-entry-put' also makes the following check, but this one
16449 ;; avoids polluting `org-last-set-property' and
16450 ;; `org-last-set-property-value' needlessly.
16451 (unless (org--valid-property-p property)
16452 (user-error "Invalid property name: \"%s\"" property))
16453 (let ((value (or value (org-read-property-value property)))
16454 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16455 (setq org-last-set-property property)
16456 (setq org-last-set-property-value (concat property ": " value))
16457 ;; Possibly postprocess the inserted value:
16458 (when fn (setq value (funcall fn value)))
16459 (unless (equal (org-entry-get nil property) value)
16460 (org-entry-put nil property value)))))
16462 (defun org-find-property (property &optional value)
16463 "Find first entry in buffer that sets PROPERTY.
16465 When optional argument VALUE is non-nil, only consider an entry
16466 if it contains PROPERTY set to this value. If PROPERTY should be
16467 explicitly set to nil, use string \"nil\" for VALUE.
16469 Return position where the entry begins, or nil if there is no
16470 such entry. If narrowing is in effect, only search the visible
16471 part of the buffer."
16472 (save-excursion
16473 (goto-char (point-min))
16474 (let ((case-fold-search t)
16475 (re (org-re-property property nil (not value) value)))
16476 (catch 'exit
16477 (while (re-search-forward re nil t)
16478 (when (if value (org-at-property-p)
16479 (org-entry-get (point) property nil t))
16480 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16482 (defun org-delete-property (property)
16483 "In the current entry, delete PROPERTY."
16484 (interactive
16485 (let* ((completion-ignore-case t)
16486 (cat (org-entry-get (point) "CATEGORY"))
16487 (props0 (org-entry-properties nil 'standard))
16488 (props (if cat props0
16489 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16490 (prop (if (< 1 (length props))
16491 (completing-read "Property: " props nil t)
16492 (caar props))))
16493 (list prop)))
16494 (if (not property)
16495 (message "No property to delete in this entry")
16496 (org-entry-delete nil property)
16497 (message "Property \"%s\" deleted" property)))
16499 (defun org-delete-property-globally (property)
16500 "Remove PROPERTY globally, from all entries.
16501 This function ignores narrowing, if any."
16502 (interactive
16503 (let* ((completion-ignore-case t)
16504 (prop (completing-read
16505 "Globally remove property: "
16506 (mapcar #'list (org-buffer-property-keys)))))
16507 (list prop)))
16508 (org-with-wide-buffer
16509 (goto-char (point-min))
16510 (let ((count 0)
16511 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16512 (while (re-search-forward re nil t)
16513 (when (org-entry-delete (point) property) (cl-incf count)))
16514 (message "Property \"%s\" removed from %d entries" property count))))
16516 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16518 (defun org-compute-property-at-point ()
16519 "Compute the property at point.
16520 This looks for an enclosing column format, extracts the operator and
16521 then applies it to the property in the column format's scope."
16522 (interactive)
16523 (unless (org-at-property-p)
16524 (user-error "Not at a property"))
16525 (let ((prop (match-string-no-properties 2)))
16526 (org-columns-get-format-and-top-level)
16527 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16528 (user-error "No operator defined for property %s" prop))
16529 (org-columns-compute prop)))
16531 (defvar org-property-allowed-value-functions nil
16532 "Hook for functions supplying allowed values for a specific property.
16533 The functions must take a single argument, the name of the property, and
16534 return a flat list of allowed values. If \":ETC\" is one of
16535 the values, this means that these values are intended as defaults for
16536 completion, but that other values should be allowed too.
16537 The functions must return nil if they are not responsible for this
16538 property.")
16540 (defun org-property-get-allowed-values (pom property &optional table)
16541 "Get allowed values for the property PROPERTY.
16542 When TABLE is non-nil, return an alist that can directly be used for
16543 completion."
16544 (let (vals)
16545 (cond
16546 ((equal property "TODO")
16547 (setq vals (org-with-point-at pom
16548 (append org-todo-keywords-1 '("")))))
16549 ((equal property "PRIORITY")
16550 (let ((n org-lowest-priority))
16551 (while (>= n org-highest-priority)
16552 (push (char-to-string n) vals)
16553 (setq n (1- n)))))
16554 ((equal property "CATEGORY"))
16555 ((member property org-special-properties))
16556 ((setq vals (run-hook-with-args-until-success
16557 'org-property-allowed-value-functions property)))
16559 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16560 (when (and vals (string-match "\\S-" vals))
16561 (setq vals (car (read-from-string (concat "(" vals ")"))))
16562 (setq vals (mapcar (lambda (x)
16563 (cond ((stringp x) x)
16564 ((numberp x) (number-to-string x))
16565 ((symbolp x) (symbol-name x))
16566 (t "???")))
16567 vals)))))
16568 (when (member ":ETC" vals)
16569 (setq vals (remove ":ETC" vals))
16570 (org-add-props (car vals) '(org-unrestricted t)))
16571 (if table (mapcar 'list vals) vals)))
16573 (defun org-property-previous-allowed-value (&optional _previous)
16574 "Switch to the next allowed value for this property."
16575 (interactive)
16576 (org-property-next-allowed-value t))
16578 (defun org-property-next-allowed-value (&optional previous)
16579 "Switch to the next allowed value for this property."
16580 (interactive)
16581 (unless (org-at-property-p)
16582 (user-error "Not at a property"))
16583 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16584 (key (match-string 2))
16585 (value (match-string 3))
16586 (allowed (or (org-property-get-allowed-values (point) key)
16587 (and (member value '("[ ]" "[-]" "[X]"))
16588 '("[ ]" "[X]"))))
16589 (heading (save-match-data (nth 4 (org-heading-components))))
16590 nval)
16591 (unless allowed
16592 (user-error "Allowed values for this property have not been defined"))
16593 (when previous (setq allowed (reverse allowed)))
16594 (when (member value allowed)
16595 (setq nval (car (cdr (member value allowed)))))
16596 (setq nval (or nval (car allowed)))
16597 (when (equal nval value)
16598 (user-error "Only one allowed value for this property"))
16599 (org-at-property-p)
16600 (replace-match (concat " :" key ": " nval) t t)
16601 (org-indent-line)
16602 (beginning-of-line 1)
16603 (skip-chars-forward " \t")
16604 (when (equal prop org-effort-property)
16605 (org-refresh-property
16606 '((effort . identity)
16607 (effort-minutes . org-duration-string-to-minutes))
16608 nval)
16609 (when (string= org-clock-current-task heading)
16610 (setq org-clock-effort nval)
16611 (org-clock-update-mode-line)))
16612 (run-hook-with-args 'org-property-changed-functions key nval)))
16614 (defun org-find-olp (path &optional this-buffer)
16615 "Return a marker pointing to the entry at outline path OLP.
16616 If anything goes wrong, throw an error.
16617 You can wrap this call to catch the error like this:
16619 \(condition-case msg
16620 \(org-mobile-locate-entry (match-string 4))
16621 \(error (nth 1 msg)))
16623 The return value will then be either a string with the error message,
16624 or a marker if everything is OK.
16626 If THIS-BUFFER is set, the outline path does not contain a file,
16627 only headings."
16628 (let* ((file (if this-buffer buffer-file-name (pop path)))
16629 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16630 (level 1)
16631 (lmin 1)
16632 (lmax 1)
16633 end found flevel)
16634 (unless buffer (error "File not found :%s" file))
16635 (with-current-buffer buffer
16636 (org-with-wide-buffer
16637 (goto-char (point-min))
16638 (dolist (heading path)
16639 (let ((re (format org-complex-heading-regexp-format
16640 (regexp-quote heading)))
16641 (cnt 0))
16642 (while (re-search-forward re end t)
16643 (setq level (- (match-end 1) (match-beginning 1)))
16644 (when (and (>= level lmin) (<= level lmax))
16645 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16646 (when (= cnt 0)
16647 (error "Heading not found on level %d: %s" lmax heading))
16648 (when (> cnt 1)
16649 (error "Heading not unique on level %d: %s" lmax heading))
16650 (goto-char found)
16651 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16652 (setq end (save-excursion (org-end-of-subtree t t)))))
16653 (when (org-at-heading-p)
16654 (point-marker))))))
16656 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16657 "Find node HEADING in BUFFER.
16658 Return a marker to the heading if it was found, or nil if not.
16659 If POS-ONLY is set, return just the position instead of a marker.
16661 The heading text must match exact, but it may have a TODO keyword,
16662 a priority cookie and tags in the standard locations."
16663 (with-current-buffer (or buffer (current-buffer))
16664 (save-excursion
16665 (save-restriction
16666 (widen)
16667 (goto-char (point-min))
16668 (let (case-fold-search)
16669 (when (re-search-forward
16670 (format org-complex-heading-regexp-format
16671 (regexp-quote heading)) nil t)
16672 (if pos-only
16673 (match-beginning 0)
16674 (move-marker (make-marker) (match-beginning 0)))))))))
16676 (defun org-find-exact-heading-in-directory (heading &optional dir)
16677 "Find Org node headline HEADING in all .org files in directory DIR.
16678 When the target headline is found, return a marker to this location."
16679 (let ((files (directory-files (or dir default-directory)
16680 t "\\`[^.#].*\\.org\\'"))
16681 visiting m buffer)
16682 (catch 'found
16683 (dolist (file files)
16684 (message "trying %s" file)
16685 (setq visiting (org-find-base-buffer-visiting file))
16686 (setq buffer (or visiting (find-file-noselect file)))
16687 (setq m (org-find-exact-headline-in-buffer
16688 heading buffer))
16689 (when (and (not m) (not visiting)) (kill-buffer buffer))
16690 (and m (throw 'found m))))))
16692 (defun org-find-entry-with-id (ident)
16693 "Locate the entry that contains the ID property with exact value IDENT.
16694 IDENT can be a string, a symbol or a number, this function will search for
16695 the string representation of it.
16696 Return the position where this entry starts, or nil if there is no such entry."
16697 (interactive "sID: ")
16698 (let ((id (cond
16699 ((stringp ident) ident)
16700 ((symbolp ident) (symbol-name ident))
16701 ((numberp ident) (number-to-string ident))
16702 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16703 (org-with-wide-buffer (org-find-property "ID" id))))
16705 ;;;; Timestamps
16707 (defvar org-last-changed-timestamp nil)
16708 (defvar org-last-inserted-timestamp nil
16709 "The last time stamp inserted with `org-insert-time-stamp'.")
16710 (defvar org-ts-what) ; dynamically scoped parameter
16712 (defun org-time-stamp (arg &optional inactive)
16713 "Prompt for a date/time and insert a time stamp.
16715 If the user specifies a time like HH:MM or if this command is
16716 called with at least one prefix argument, the time stamp contains
16717 the date and the time. Otherwise, only the date is included.
16719 All parts of a date not specified by the user are filled in from
16720 the timestamp at point, if any, or the current date/time
16721 otherwise.
16723 If there is already a timestamp at the cursor, it is replaced.
16725 With two universal prefix arguments, insert an active timestamp
16726 with the current time without prompting the user.
16728 When called from lisp, the timestamp is inactive if INACTIVE is
16729 non-nil."
16730 (interactive "P")
16731 (let* ((ts (cond
16732 ((org-at-date-range-p t)
16733 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16734 ((org-at-timestamp-p t) (match-string 0))))
16735 ;; Default time is either the timestamp at point or today.
16736 ;; When entering a range, only the range start is considered.
16737 (default-time (if (not ts) (current-time)
16738 (apply #'encode-time (org-parse-time-string ts))))
16739 (default-input (and ts (org-get-compact-tod ts)))
16740 (repeater (and ts
16741 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16742 (match-string 0 ts)))
16743 org-time-was-given
16744 org-end-time-was-given
16745 (time
16746 (and (if (equal arg '(16)) (current-time)
16747 ;; Preserve `this-command' and `last-command'.
16748 (let ((this-command this-command)
16749 (last-command last-command))
16750 (org-read-date
16751 arg 'totime nil nil default-time default-input
16752 inactive))))))
16753 (cond
16754 ((and ts
16755 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16756 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16757 (insert "--")
16758 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16760 ;; Make sure we're on a timestamp. When in the middle of a date
16761 ;; range, move arbitrarily to range end.
16762 (unless (org-at-timestamp-p t)
16763 (skip-chars-forward "-")
16764 (org-at-timestamp-p t))
16765 (replace-match "")
16766 (setq org-last-changed-timestamp
16767 (org-insert-time-stamp
16768 time (or org-time-was-given arg)
16769 inactive nil nil (list org-end-time-was-given)))
16770 (when repeater
16771 (backward-char)
16772 (insert " " repeater)
16773 (setq org-last-changed-timestamp
16774 (concat (substring org-last-inserted-timestamp 0 -1)
16775 " " repeater ">")))
16776 (message "Timestamp updated"))
16777 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16778 (t (org-insert-time-stamp
16779 time (or org-time-was-given arg) inactive nil nil
16780 (list org-end-time-was-given))))))
16782 ;; FIXME: can we use this for something else, like computing time differences?
16783 (defun org-get-compact-tod (s)
16784 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16785 (let* ((t1 (match-string 1 s))
16786 (h1 (string-to-number (match-string 2 s)))
16787 (m1 (string-to-number (match-string 3 s)))
16788 (t2 (and (match-end 4) (match-string 5 s)))
16789 (h2 (and t2 (string-to-number (match-string 6 s))))
16790 (m2 (and t2 (string-to-number (match-string 7 s))))
16791 dh dm)
16792 (if (not t2)
16794 (setq dh (- h2 h1) dm (- m2 m1))
16795 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16796 (concat t1 "+" (number-to-string dh)
16797 (and (/= 0 dm) (format ":%02d" dm)))))))
16799 (defun org-time-stamp-inactive (&optional arg)
16800 "Insert an inactive time stamp.
16801 An inactive time stamp is enclosed in square brackets instead of angle
16802 brackets. It is inactive in the sense that it does not trigger agenda entries,
16803 does not link to the calendar and cannot be changed with the S-cursor keys.
16804 So these are more for recording a certain time/date."
16805 (interactive "P")
16806 (org-time-stamp arg 'inactive))
16808 (defvar org-date-ovl (make-overlay 1 1))
16809 (overlay-put org-date-ovl 'face 'org-date-selected)
16810 (delete-overlay org-date-ovl)
16812 (defvar org-ans1) ; dynamically scoped parameter
16813 (defvar org-ans2) ; dynamically scoped parameter
16815 (defvar org-plain-time-of-day-regexp) ; defined below
16817 (defvar org-overriding-default-time nil) ; dynamically scoped
16818 (defvar org-read-date-overlay nil)
16819 (defvar org-dcst nil) ; dynamically scoped
16820 (defvar org-read-date-history nil)
16821 (defvar org-read-date-final-answer nil)
16822 (defvar org-read-date-analyze-futurep nil)
16823 (defvar org-read-date-analyze-forced-year nil)
16824 (defvar org-read-date-inactive)
16826 (defvar org-read-date-minibuffer-local-map
16827 (let* ((map (make-sparse-keymap)))
16828 (set-keymap-parent map minibuffer-local-map)
16829 (org-defkey map (kbd ".")
16830 (lambda () (interactive)
16831 ;; Are we at the beginning of the prompt?
16832 (if (looking-back "^[^:]+: "
16833 (let ((inhibit-field-text-motion t))
16834 (line-beginning-position)))
16835 (org-eval-in-calendar '(calendar-goto-today))
16836 (insert "."))))
16837 (org-defkey map (kbd "C-.")
16838 (lambda () (interactive)
16839 (org-eval-in-calendar '(calendar-goto-today))))
16840 (org-defkey map [(meta shift left)]
16841 (lambda () (interactive)
16842 (org-eval-in-calendar '(calendar-backward-month 1))))
16843 (org-defkey map [(meta shift right)]
16844 (lambda () (interactive)
16845 (org-eval-in-calendar '(calendar-forward-month 1))))
16846 (org-defkey map [(meta shift up)]
16847 (lambda () (interactive)
16848 (org-eval-in-calendar '(calendar-backward-year 1))))
16849 (org-defkey map [(meta shift down)]
16850 (lambda () (interactive)
16851 (org-eval-in-calendar '(calendar-forward-year 1))))
16852 (org-defkey map [?\e (shift left)]
16853 (lambda () (interactive)
16854 (org-eval-in-calendar '(calendar-backward-month 1))))
16855 (org-defkey map [?\e (shift right)]
16856 (lambda () (interactive)
16857 (org-eval-in-calendar '(calendar-forward-month 1))))
16858 (org-defkey map [?\e (shift up)]
16859 (lambda () (interactive)
16860 (org-eval-in-calendar '(calendar-backward-year 1))))
16861 (org-defkey map [?\e (shift down)]
16862 (lambda () (interactive)
16863 (org-eval-in-calendar '(calendar-forward-year 1))))
16864 (org-defkey map [(shift up)]
16865 (lambda () (interactive)
16866 (org-eval-in-calendar '(calendar-backward-week 1))))
16867 (org-defkey map [(shift down)]
16868 (lambda () (interactive)
16869 (org-eval-in-calendar '(calendar-forward-week 1))))
16870 (org-defkey map [(shift left)]
16871 (lambda () (interactive)
16872 (org-eval-in-calendar '(calendar-backward-day 1))))
16873 (org-defkey map [(shift right)]
16874 (lambda () (interactive)
16875 (org-eval-in-calendar '(calendar-forward-day 1))))
16876 (org-defkey map "!"
16877 (lambda () (interactive)
16878 (org-eval-in-calendar '(diary-view-entries))
16879 (message "")))
16880 (org-defkey map ">"
16881 (lambda () (interactive)
16882 (org-eval-in-calendar '(calendar-scroll-left 1))))
16883 (org-defkey map "<"
16884 (lambda () (interactive)
16885 (org-eval-in-calendar '(calendar-scroll-right 1))))
16886 (org-defkey map "\C-v"
16887 (lambda () (interactive)
16888 (org-eval-in-calendar
16889 '(calendar-scroll-left-three-months 1))))
16890 (org-defkey map "\M-v"
16891 (lambda () (interactive)
16892 (org-eval-in-calendar
16893 '(calendar-scroll-right-three-months 1))))
16894 map)
16895 "Keymap for minibuffer commands when using `org-read-date'.")
16897 (defvar org-def)
16898 (defvar org-defdecode)
16899 (defvar org-with-time)
16901 (defvar calendar-setup) ; Dynamically scoped.
16902 (defun org-read-date (&optional with-time to-time from-string prompt
16903 default-time default-input inactive)
16904 "Read a date, possibly a time, and make things smooth for the user.
16905 The prompt will suggest to enter an ISO date, but you can also enter anything
16906 which will at least partially be understood by `parse-time-string'.
16907 Unrecognized parts of the date will default to the current day, month, year,
16908 hour and minute. If this command is called to replace a timestamp at point,
16909 or to enter the second timestamp of a range, the default time is taken
16910 from the existing stamp. Furthermore, the command prefers the future,
16911 so if you are giving a date where the year is not given, and the day-month
16912 combination is already past in the current year, it will assume you
16913 mean next year. For details, see the manual. A few examples:
16915 3-2-5 --> 2003-02-05
16916 feb 15 --> currentyear-02-15
16917 2/15 --> currentyear-02-15
16918 sep 12 9 --> 2009-09-12
16919 12:45 --> today 12:45
16920 22 sept 0:34 --> currentyear-09-22 0:34
16921 12 --> currentyear-currentmonth-12
16922 Fri --> nearest Friday after today
16923 -Tue --> last Tuesday
16924 etc.
16926 Furthermore you can specify a relative date by giving, as the *first* thing
16927 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16928 change in days weeks, months, years.
16929 With a single plus or minus, the date is relative to today. With a double
16930 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16931 +4d --> four days from today
16932 +4 --> same as above
16933 +2w --> two weeks from today
16934 ++5 --> five days from default date
16936 The function understands only English month and weekday abbreviations.
16938 While prompting, a calendar is popped up - you can also select the
16939 date with the mouse (button 1). The calendar shows a period of three
16940 months. To scroll it to other months, use the keys `>' and `<'.
16941 If you don't like the calendar, turn it off with
16942 (setq org-read-date-popup-calendar nil)
16944 With optional argument TO-TIME, the date will immediately be converted
16945 to an internal time.
16946 With an optional argument WITH-TIME, the prompt will suggest to
16947 also insert a time. Note that when WITH-TIME is not set, you can
16948 still enter a time, and this function will inform the calling routine
16949 about this change. The calling routine may then choose to change the
16950 format used to insert the time stamp into the buffer to include the time.
16951 With optional argument FROM-STRING, read from this string instead from
16952 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16953 the time/date that is used for everything that is not specified by the
16954 user."
16955 (require 'parse-time)
16956 (let* ((org-with-time with-time)
16957 (org-time-stamp-rounding-minutes
16958 (if (equal org-with-time '(16))
16959 '(0 0)
16960 org-time-stamp-rounding-minutes))
16961 (org-dcst org-display-custom-times)
16962 (ct (org-current-time))
16963 (org-def (or org-overriding-default-time default-time ct))
16964 (org-defdecode (decode-time org-def))
16965 (cur-frame (selected-frame))
16966 (mouse-autoselect-window nil) ; Don't let the mouse jump
16967 (calendar-setup
16968 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16969 (calendar-move-hook nil)
16970 (calendar-view-diary-initially-flag nil)
16971 (calendar-view-holidays-initially-flag nil)
16972 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16973 ;; Rationalize `org-def' and `org-defdecode', if required.
16974 (when (< (nth 2 org-defdecode) org-extend-today-until)
16975 (setf (nth 2 org-defdecode) -1)
16976 (setf (nth 1 org-defdecode) 59)
16977 (setq org-def (apply #'encode-time org-defdecode))
16978 (setq org-defdecode (decode-time org-def)))
16979 (let* ((timestr (format-time-string
16980 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16981 org-def))
16982 (prompt (concat (if prompt (concat prompt " ") "")
16983 (format "Date+time [%s]: " timestr))))
16984 (cond
16985 (from-string (setq ans from-string))
16986 (org-read-date-popup-calendar
16987 (save-excursion
16988 (save-window-excursion
16989 (calendar)
16990 (when (eq calendar-setup 'calendar-only)
16991 (setq cal-frame
16992 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16993 (select-frame cal-frame))
16994 (org-eval-in-calendar '(setq cursor-type nil) t)
16995 (unwind-protect
16996 (progn
16997 (calendar-forward-day (- (time-to-days org-def)
16998 (calendar-absolute-from-gregorian
16999 (calendar-current-date))))
17000 (org-eval-in-calendar nil t)
17001 (let* ((old-map (current-local-map))
17002 (map (copy-keymap calendar-mode-map))
17003 (minibuffer-local-map
17004 (copy-keymap org-read-date-minibuffer-local-map)))
17005 (org-defkey map (kbd "RET") 'org-calendar-select)
17006 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17007 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17008 (unwind-protect
17009 (progn
17010 (use-local-map map)
17011 (setq org-read-date-inactive inactive)
17012 (add-hook 'post-command-hook 'org-read-date-display)
17013 (setq org-ans0
17014 (read-string prompt
17015 default-input
17016 'org-read-date-history
17017 nil))
17018 ;; org-ans0: from prompt
17019 ;; org-ans1: from mouse click
17020 ;; org-ans2: from calendar motion
17021 (setq ans
17022 (concat org-ans0 " " (or org-ans1 org-ans2))))
17023 (remove-hook 'post-command-hook 'org-read-date-display)
17024 (use-local-map old-map)
17025 (when org-read-date-overlay
17026 (delete-overlay org-read-date-overlay)
17027 (setq org-read-date-overlay nil)))))
17028 (bury-buffer "*Calendar*")
17029 (when cal-frame
17030 (delete-frame cal-frame)
17031 (select-frame-set-input-focus cur-frame))))))
17033 (t ; Naked prompt only
17034 (unwind-protect
17035 (setq ans (read-string prompt default-input
17036 'org-read-date-history timestr))
17037 (when org-read-date-overlay
17038 (delete-overlay org-read-date-overlay)
17039 (setq org-read-date-overlay nil))))))
17041 (setq final (org-read-date-analyze ans org-def org-defdecode))
17043 (when org-read-date-analyze-forced-year
17044 (message "Year was forced into %s"
17045 (if org-read-date-force-compatible-dates
17046 "compatible range (1970-2037)"
17047 "range representable on this machine"))
17048 (ding))
17050 ;; One round trip to get rid of 34th of August and stuff like that....
17051 (setq final (decode-time (apply 'encode-time final)))
17053 (setq org-read-date-final-answer ans)
17055 (if to-time
17056 (apply 'encode-time final)
17057 (if (and (boundp 'org-time-was-given) org-time-was-given)
17058 (format "%04d-%02d-%02d %02d:%02d"
17059 (nth 5 final) (nth 4 final) (nth 3 final)
17060 (nth 2 final) (nth 1 final))
17061 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17063 (defun org-read-date-display ()
17064 "Display the current date prompt interpretation in the minibuffer."
17065 (when org-read-date-display-live
17066 (when org-read-date-overlay
17067 (delete-overlay org-read-date-overlay))
17068 (when (minibufferp (current-buffer))
17069 (save-excursion
17070 (end-of-line 1)
17071 (while (not (equal (buffer-substring
17072 (max (point-min) (- (point) 4)) (point))
17073 " "))
17074 (insert " ")))
17075 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17076 " " (or org-ans1 org-ans2)))
17077 (org-end-time-was-given nil)
17078 (f (org-read-date-analyze ans org-def org-defdecode))
17079 (fmts (if org-dcst
17080 org-time-stamp-custom-formats
17081 org-time-stamp-formats))
17082 (fmt (if (or org-with-time
17083 (and (boundp 'org-time-was-given) org-time-was-given))
17084 (cdr fmts)
17085 (car fmts)))
17086 (txt (format-time-string fmt (apply 'encode-time f)))
17087 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17088 (txt (concat "=> " txt)))
17089 (when (and org-end-time-was-given
17090 (string-match org-plain-time-of-day-regexp txt))
17091 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17092 org-end-time-was-given
17093 (substring txt (match-end 0)))))
17094 (when org-read-date-analyze-futurep
17095 (setq txt (concat txt " (=>F)")))
17096 (setq org-read-date-overlay
17097 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17098 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17100 (defun org-read-date-analyze (ans def defdecode)
17101 "Analyze the combined answer of the date prompt."
17102 ;; FIXME: cleanup and comment
17103 ;; Pass `current-time' result to `decode-time' (instead of calling
17104 ;; without arguments) so that only `current-time' has to be
17105 ;; overriden in tests.
17106 (let ((org-def def)
17107 (org-defdecode defdecode)
17108 (nowdecode (decode-time (current-time)))
17109 delta deltan deltaw deltadef year month day
17110 hour minute second wday pm h2 m2 tl wday1
17111 iso-year iso-weekday iso-week iso-date futurep kill-year)
17112 (setq org-read-date-analyze-futurep nil
17113 org-read-date-analyze-forced-year nil)
17114 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17115 (setq ans "+0"))
17117 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17118 (setq ans (replace-match "" t t ans)
17119 deltan (car delta)
17120 deltaw (nth 1 delta)
17121 deltadef (nth 2 delta)))
17123 ;; Check if there is an iso week date in there. If yes, store the
17124 ;; info and postpone interpreting it until the rest of the parsing
17125 ;; is done.
17126 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17127 (setq iso-year (when (match-end 1)
17128 (org-small-year-to-year
17129 (string-to-number (match-string 1 ans))))
17130 iso-weekday (when (match-end 3)
17131 (string-to-number (match-string 3 ans)))
17132 iso-week (string-to-number (match-string 2 ans)))
17133 (setq ans (replace-match "" t t ans)))
17135 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17136 (when (string-match
17137 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17138 (setq year (if (match-end 2)
17139 (string-to-number (match-string 2 ans))
17140 (progn (setq kill-year t)
17141 (string-to-number (format-time-string "%Y"))))
17142 month (string-to-number (match-string 3 ans))
17143 day (string-to-number (match-string 4 ans)))
17144 (setq year (org-small-year-to-year year))
17145 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17146 t nil ans)))
17148 ;; Help matching dotted european dates
17149 (when (string-match
17150 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17151 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17152 (setq kill-year t)
17153 (string-to-number (format-time-string "%Y")))
17154 day (string-to-number (match-string 1 ans))
17155 month (string-to-number (match-string 2 ans))
17156 ans (replace-match (format "%04d-%02d-%02d" year month day)
17157 t nil ans)))
17159 ;; Help matching american dates, like 5/30 or 5/30/7
17160 (when (string-match
17161 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17162 (setq year (if (match-end 4)
17163 (string-to-number (match-string 4 ans))
17164 (progn (setq kill-year t)
17165 (string-to-number (format-time-string "%Y"))))
17166 month (string-to-number (match-string 1 ans))
17167 day (string-to-number (match-string 2 ans)))
17168 (setq year (org-small-year-to-year year))
17169 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17170 t nil ans)))
17171 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17172 ;; If there is a time with am/pm, and *no* time without it, we convert
17173 ;; so that matching will be successful.
17174 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17175 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17176 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17177 (setq hour (string-to-number (match-string 1 ans))
17178 minute (if (match-end 3)
17179 (string-to-number (match-string 3 ans))
17181 pm (equal ?p
17182 (string-to-char (downcase (match-string 4 ans)))))
17183 (if (and (= hour 12) (not pm))
17184 (setq hour 0)
17185 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17186 (setq ans (replace-match (format "%02d:%02d" hour minute)
17187 t t ans))))
17189 ;; Check if a time range is given as a duration
17190 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17191 (setq hour (string-to-number (match-string 1 ans))
17192 h2 (+ hour (string-to-number (match-string 3 ans)))
17193 minute (string-to-number (match-string 2 ans))
17194 m2 (+ minute (if (match-end 5) (string-to-number
17195 (match-string 5 ans))0)))
17196 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17197 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17198 t t ans)))
17200 ;; Check if there is a time range
17201 (when (boundp 'org-end-time-was-given)
17202 (setq org-time-was-given nil)
17203 (when (and (string-match org-plain-time-of-day-regexp ans)
17204 (match-end 8))
17205 (setq org-end-time-was-given (match-string 8 ans))
17206 (setq ans (concat (substring ans 0 (match-beginning 7))
17207 (substring ans (match-end 7))))))
17209 (setq tl (parse-time-string ans)
17210 day (or (nth 3 tl) (nth 3 org-defdecode))
17211 month
17212 (cond ((nth 4 tl))
17213 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17214 ;; Day was specified. Make sure DAY+MONTH
17215 ;; combination happens in the future.
17216 ((nth 3 tl)
17217 (setq futurep t)
17218 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17219 (nth 4 nowdecode)))
17220 (t (nth 4 org-defdecode)))
17221 year
17222 (cond ((and (not kill-year) (nth 5 tl)))
17223 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17224 ;; Month was guessed in the future and is at least
17225 ;; equal to NOWDECODE's. Fix year accordingly.
17226 (futurep
17227 (if (or (> month (nth 4 nowdecode))
17228 (>= day (nth 3 nowdecode)))
17229 (nth 5 nowdecode)
17230 (1+ (nth 5 nowdecode))))
17231 ;; Month was specified. Make sure MONTH+YEAR
17232 ;; combination happens in the future.
17233 ((nth 4 tl)
17234 (setq futurep t)
17235 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17236 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17237 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17238 (t (nth 5 nowdecode))))
17239 (t (nth 5 org-defdecode)))
17240 hour (or (nth 2 tl) (nth 2 org-defdecode))
17241 minute (or (nth 1 tl) (nth 1 org-defdecode))
17242 second (or (nth 0 tl) 0)
17243 wday (nth 6 tl))
17245 (when (and (eq org-read-date-prefer-future 'time)
17246 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17247 (equal day (nth 3 nowdecode))
17248 (equal month (nth 4 nowdecode))
17249 (equal year (nth 5 nowdecode))
17250 (nth 2 tl)
17251 (or (< (nth 2 tl) (nth 2 nowdecode))
17252 (and (= (nth 2 tl) (nth 2 nowdecode))
17253 (nth 1 tl)
17254 (< (nth 1 tl) (nth 1 nowdecode)))))
17255 (setq day (1+ day)
17256 futurep t))
17258 ;; Special date definitions below
17259 (cond
17260 (iso-week
17261 ;; There was an iso week
17262 (require 'cal-iso)
17263 (setq futurep nil)
17264 (setq year (or iso-year year)
17265 day (or iso-weekday wday 1)
17266 wday nil ; to make sure that the trigger below does not match
17267 iso-date (calendar-gregorian-from-absolute
17268 (calendar-iso-to-absolute
17269 (list iso-week day year))))
17270 ; FIXME: Should we also push ISO weeks into the future?
17271 ; (when (and org-read-date-prefer-future
17272 ; (not iso-year)
17273 ; (< (calendar-absolute-from-gregorian iso-date)
17274 ; (time-to-days (current-time))))
17275 ; (setq year (1+ year)
17276 ; iso-date (calendar-gregorian-from-absolute
17277 ; (calendar-iso-to-absolute
17278 ; (list iso-week day year)))))
17279 (setq month (car iso-date)
17280 year (nth 2 iso-date)
17281 day (nth 1 iso-date)))
17282 (deltan
17283 (setq futurep nil)
17284 (unless deltadef
17285 ;; Pass `current-time' result to `decode-time' (instead of
17286 ;; calling without arguments) so that only `current-time' has
17287 ;; to be overriden in tests.
17288 (let ((now (decode-time (current-time))))
17289 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17290 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17291 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17292 ((equal deltaw "m") (setq month (+ month deltan)))
17293 ((equal deltaw "y") (setq year (+ year deltan)))))
17294 ((and wday (not (nth 3 tl)))
17295 ;; Weekday was given, but no day, so pick that day in the week
17296 ;; on or after the derived date.
17297 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17298 (unless (equal wday wday1)
17299 (setq day (+ day (% (- wday wday1 -7) 7))))))
17300 (when (and (boundp 'org-time-was-given)
17301 (nth 2 tl))
17302 (setq org-time-was-given t))
17303 (when (< year 100) (setq year (+ 2000 year)))
17304 ;; Check of the date is representable
17305 (if org-read-date-force-compatible-dates
17306 (progn
17307 (when (< year 1970)
17308 (setq year 1970 org-read-date-analyze-forced-year t))
17309 (when (> year 2037)
17310 (setq year 2037 org-read-date-analyze-forced-year t)))
17311 (condition-case nil
17312 (ignore (encode-time second minute hour day month year))
17313 (error
17314 (setq year (nth 5 org-defdecode))
17315 (setq org-read-date-analyze-forced-year t))))
17316 (setq org-read-date-analyze-futurep futurep)
17317 (list second minute hour day month year)))
17319 (defvar parse-time-weekdays)
17320 (defun org-read-date-get-relative (s today default)
17321 "Check string S for special relative date string.
17322 TODAY and DEFAULT are internal times, for today and for a default.
17323 Return shift list (N what def-flag)
17324 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17325 N is the number of WHATs to shift.
17326 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17327 the DEFAULT date rather than TODAY."
17328 (require 'parse-time)
17329 (when (and
17330 (string-match
17331 (concat
17332 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17333 "\\([0-9]+\\)?"
17334 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17335 "\\([ \t]\\|$\\)") s)
17336 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17337 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17338 (string-to-char (substring (match-string 1 s) -1))
17339 ?+))
17340 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17341 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17342 (what (if (match-end 3) (match-string 3 s) "d"))
17343 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17344 (date (if rel default today))
17345 (wday (nth 6 (decode-time date)))
17346 delta)
17347 (if wday1
17348 (progn
17349 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17350 (when (= delta 0) (setq delta 7))
17351 (when (= dir ?-)
17352 (setq delta (- delta 7))
17353 (when (= delta 0) (setq delta -7)))
17354 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17355 (list delta "d" rel))
17356 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17358 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17359 "Turn a user-specified date into the internal representation.
17360 The internal representation needed by the calendar is (month day year).
17361 This is a wrapper to handle the brain-dead convention in calendar that
17362 user function argument order change dependent on argument order."
17363 (if (boundp 'calendar-date-style)
17364 (cond
17365 ((eq calendar-date-style 'american)
17366 (list arg1 arg2 arg3))
17367 ((eq calendar-date-style 'european)
17368 (list arg2 arg1 arg3))
17369 ((eq calendar-date-style 'iso)
17370 (list arg2 arg3 arg1)))
17371 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17372 (if (org-bound-and-true-p european-calendar-style)
17373 (list arg2 arg1 arg3)
17374 (list arg1 arg2 arg3)))))
17376 (defun org-eval-in-calendar (form &optional keepdate)
17377 "Eval FORM in the calendar window and return to current window.
17378 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17379 (let ((sf (selected-frame))
17380 (sw (selected-window)))
17381 (select-window (get-buffer-window "*Calendar*" t))
17382 (eval form)
17383 (when (and (not keepdate) (calendar-cursor-to-date))
17384 (let* ((date (calendar-cursor-to-date))
17385 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17386 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17387 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17388 (select-window sw)
17389 (select-frame-set-input-focus sf)))
17391 (defun org-calendar-select ()
17392 "Return to `org-read-date' with the date currently selected.
17393 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17394 (interactive)
17395 (when (calendar-cursor-to-date)
17396 (let* ((date (calendar-cursor-to-date))
17397 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17398 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17399 (when (active-minibuffer-window) (exit-minibuffer))))
17401 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17402 "Insert a date stamp for the date given by the internal TIME.
17403 See `format-time-string' for the format of TIME.
17404 WITH-HM means use the stamp format that includes the time of the day.
17405 INACTIVE means use square brackets instead of angular ones, so that the
17406 stamp will not contribute to the agenda.
17407 PRE and POST are optional strings to be inserted before and after the
17408 stamp.
17409 The command returns the inserted time stamp."
17410 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17411 stamp)
17412 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17413 (insert-before-markers (or pre ""))
17414 (when (listp extra)
17415 (setq extra (car extra))
17416 (if (and (stringp extra)
17417 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17418 (setq extra (format "-%02d:%02d"
17419 (string-to-number (match-string 1 extra))
17420 (string-to-number (match-string 2 extra))))
17421 (setq extra nil)))
17422 (when extra
17423 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17424 (insert-before-markers (setq stamp (format-time-string fmt time)))
17425 (insert-before-markers (or post ""))
17426 (setq org-last-inserted-timestamp stamp)))
17428 (defun org-toggle-time-stamp-overlays ()
17429 "Toggle the use of custom time stamp formats."
17430 (interactive)
17431 (setq org-display-custom-times (not org-display-custom-times))
17432 (unless org-display-custom-times
17433 (let ((p (point-min)) (bmp (buffer-modified-p)))
17434 (while (setq p (next-single-property-change p 'display))
17435 (when (and (get-text-property p 'display)
17436 (eq (get-text-property p 'face) 'org-date))
17437 (remove-text-properties
17438 p (setq p (next-single-property-change p 'display))
17439 '(display t))))
17440 (set-buffer-modified-p bmp)))
17441 (org-restart-font-lock)
17442 (setq org-table-may-need-update t)
17443 (if org-display-custom-times
17444 (message "Time stamps are overlaid with custom format")
17445 (message "Time stamp overlays removed")))
17447 (defun org-display-custom-time (beg end)
17448 "Overlay modified time stamp format over timestamp between BEG and END."
17449 (let* ((ts (buffer-substring beg end))
17450 t1 w1 with-hm tf time str w2 (off 0))
17451 (save-match-data
17452 (setq t1 (org-parse-time-string ts t))
17453 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17454 (setq off (- (match-end 0) (match-beginning 0)))))
17455 (setq end (- end off))
17456 (setq w1 (- end beg)
17457 with-hm (and (nth 1 t1) (nth 2 t1))
17458 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17459 time (org-fix-decoded-time t1)
17460 str (org-add-props
17461 (format-time-string
17462 (substring tf 1 -1) (apply 'encode-time time))
17463 nil 'mouse-face 'highlight)
17464 w2 (length str))
17465 (unless (= w2 w1)
17466 (add-text-properties (1+ beg) (+ 2 beg)
17467 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17468 (put-text-property beg end 'display str)))
17470 (defun org-fix-decoded-time (time)
17471 "Set 0 instead of nil for the first 6 elements of time.
17472 Don't touch the rest."
17473 (let ((n 0))
17474 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17476 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17478 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17479 "Difference between TIMESTAMP-STRING and now in days.
17480 If SECONDS is non-nil, return the difference in seconds."
17481 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17482 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17483 (funcall fdiff (current-time)))))
17485 (defun org-deadline-close-p (timestamp-string &optional ndays)
17486 "Is the time in TIMESTAMP-STRING close to the current date?"
17487 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17488 (and (<= (org-time-stamp-to-now timestamp-string) ndays)
17489 (not (org-entry-is-done-p))))
17491 (defun org-get-wdays (ts &optional delay zero-delay)
17492 "Get the deadline lead time appropriate for timestring TS.
17493 When DELAY is non-nil, get the delay time for scheduled items
17494 instead of the deadline lead time. When ZERO-DELAY is non-nil
17495 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17496 don't try to find the delay cookie in the scheduled timestamp."
17497 (let ((tv (if delay org-scheduled-delay-days
17498 org-deadline-warning-days)))
17499 (cond
17500 ((or (and delay (< tv 0))
17501 (and delay zero-delay (<= tv 0))
17502 (and (not delay) (<= tv 0)))
17503 ;; Enforce this value no matter what
17504 (- tv))
17505 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17506 ;; lead time is specified.
17507 (floor (* (string-to-number (match-string 1 ts))
17508 (cdr (assoc (match-string 2 ts)
17509 '(("d" . 1) ("w" . 7)
17510 ("m" . 30.4) ("y" . 365.25)
17511 ("h" . 0.041667)))))))
17512 ;; go for the default.
17513 (t tv))))
17515 (defun org-calendar-select-mouse (ev)
17516 "Return to `org-read-date' with the date currently selected.
17517 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17518 (interactive "e")
17519 (mouse-set-point ev)
17520 (when (calendar-cursor-to-date)
17521 (let* ((date (calendar-cursor-to-date))
17522 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17523 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17524 (when (active-minibuffer-window) (exit-minibuffer))))
17526 (defun org-check-deadlines (ndays)
17527 "Check if there are any deadlines due or past due.
17528 A deadline is considered due if it happens within `org-deadline-warning-days'
17529 days from today's date. If the deadline appears in an entry marked DONE,
17530 it is not shown. The prefix arg NDAYS can be used to test that many
17531 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17532 (interactive "P")
17533 (let* ((org-warn-days
17534 (cond
17535 ((equal ndays '(4)) 100000)
17536 (ndays (prefix-numeric-value ndays))
17537 (t (abs org-deadline-warning-days))))
17538 (case-fold-search nil)
17539 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17540 (callback
17541 (lambda () (org-deadline-close-p (match-string 1) org-warn-days))))
17542 (message "%d deadlines past-due or due within %d days"
17543 (org-occur regexp nil callback)
17544 org-warn-days)))
17546 (defsubst org-re-timestamp (type)
17547 "Return a regexp for timestamp TYPE.
17548 Allowed values for TYPE are:
17550 all: all timestamps
17551 active: only active timestamps (<...>)
17552 inactive: only inactive timestamps ([...])
17553 scheduled: only scheduled timestamps
17554 deadline: only deadline timestamps
17555 closed: only closed time-stamps
17557 When TYPE is nil, fall back on returning a regexp that matches
17558 both scheduled and deadline timestamps."
17559 (cl-case type
17560 (all org-ts-regexp-both)
17561 (active org-ts-regexp)
17562 (inactive org-ts-regexp-inactive)
17563 (scheduled org-scheduled-time-regexp)
17564 (deadline org-deadline-time-regexp)
17565 (closed org-closed-time-regexp)
17566 (otherwise
17567 (concat "\\<"
17568 (regexp-opt (list org-deadline-string org-scheduled-string))
17569 " *<\\([^>]+\\)>"))))
17571 (defun org-check-before-date (d)
17572 "Check if there are deadlines or scheduled entries before date D."
17573 (interactive (list (org-read-date)))
17574 (let* ((case-fold-search nil)
17575 (regexp (org-re-timestamp org-ts-type))
17576 (ts-type org-ts-type)
17577 (callback
17578 (lambda ()
17579 (let ((match (match-string 1)))
17580 (and (if (memq ts-type '(active inactive all))
17581 (eq (org-element-type (save-excursion
17582 (backward-char)
17583 (org-element-context)))
17584 'timestamp)
17585 (org-at-planning-p))
17586 (time-less-p
17587 (org-time-string-to-time match)
17588 (org-time-string-to-time d)))))))
17589 (message "%d entries before %s"
17590 (org-occur regexp nil callback)
17591 d)))
17593 (defun org-check-after-date (d)
17594 "Check if there are deadlines or scheduled entries after date D."
17595 (interactive (list (org-read-date)))
17596 (let* ((case-fold-search nil)
17597 (regexp (org-re-timestamp org-ts-type))
17598 (ts-type org-ts-type)
17599 (callback
17600 (lambda ()
17601 (let ((match (match-string 1)))
17602 (and (if (memq ts-type '(active inactive all))
17603 (eq (org-element-type (save-excursion
17604 (backward-char)
17605 (org-element-context)))
17606 'timestamp)
17607 (org-at-planning-p))
17608 (not (time-less-p
17609 (org-time-string-to-time match)
17610 (org-time-string-to-time d))))))))
17611 (message "%d entries after %s"
17612 (org-occur regexp nil callback)
17613 d)))
17615 (defun org-check-dates-range (start-date end-date)
17616 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17617 (interactive (list (org-read-date nil nil nil "Range starts")
17618 (org-read-date nil nil nil "Range end")))
17619 (let ((case-fold-search nil)
17620 (regexp (org-re-timestamp org-ts-type))
17621 (callback
17622 (let ((type org-ts-type))
17623 (lambda ()
17624 (let ((match (match-string 1)))
17625 (and
17626 (if (memq type '(active inactive all))
17627 (eq (org-element-type (save-excursion
17628 (backward-char)
17629 (org-element-context)))
17630 'timestamp)
17631 (org-at-planning-p))
17632 (not (time-less-p
17633 (org-time-string-to-time match)
17634 (org-time-string-to-time start-date)))
17635 (time-less-p
17636 (org-time-string-to-time match)
17637 (org-time-string-to-time end-date))))))))
17638 (message "%d entries between %s and %s"
17639 (org-occur regexp nil callback) start-date end-date)))
17641 (defun org-evaluate-time-range (&optional to-buffer)
17642 "Evaluate a time range by computing the difference between start and end.
17643 Normally the result is just printed in the echo area, but with prefix arg
17644 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17645 If the time range is actually in a table, the result is inserted into the
17646 next column.
17647 For time difference computation, a year is assumed to be exactly 365
17648 days in order to avoid rounding problems."
17649 (interactive "P")
17651 (org-clock-update-time-maybe)
17652 (save-excursion
17653 (unless (org-at-date-range-p t)
17654 (goto-char (point-at-bol))
17655 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17656 (unless (org-at-date-range-p t)
17657 (user-error "Not at a time-stamp range, and none found in current line")))
17658 (let* ((ts1 (match-string 1))
17659 (ts2 (match-string 2))
17660 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17661 (match-end (match-end 0))
17662 (time1 (org-time-string-to-time ts1))
17663 (time2 (org-time-string-to-time ts2))
17664 (t1 (float-time time1))
17665 (t2 (float-time time2))
17666 (diff (abs (- t2 t1)))
17667 (negative (< (- t2 t1) 0))
17668 ;; (ys (floor (* 365 24 60 60)))
17669 (ds (* 24 60 60))
17670 (hs (* 60 60))
17671 (fy "%dy %dd %02d:%02d")
17672 (fy1 "%dy %dd")
17673 (fd "%dd %02d:%02d")
17674 (fd1 "%dd")
17675 (fh "%02d:%02d")
17676 y d h m align)
17677 (if havetime
17678 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17680 d (floor (/ diff ds)) diff (mod diff ds)
17681 h (floor (/ diff hs)) diff (mod diff hs)
17682 m (floor (/ diff 60)))
17683 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17685 d (floor (+ (/ diff ds) 0.5))
17686 h 0 m 0))
17687 (if (not to-buffer)
17688 (message "%s" (org-make-tdiff-string y d h m))
17689 (if (org-at-table-p)
17690 (progn
17691 (goto-char match-end)
17692 (setq align t)
17693 (and (looking-at " *|") (goto-char (match-end 0))))
17694 (goto-char match-end))
17695 (when (looking-at
17696 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17697 (replace-match ""))
17698 (when negative (insert " -"))
17699 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17700 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17701 (insert " " (format fh h m))))
17702 (when align (org-table-align))
17703 (message "Time difference inserted")))))
17705 (defun org-make-tdiff-string (y d h m)
17706 (let ((fmt "")
17707 (l nil))
17708 (when (> y 0)
17709 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17710 (push y l))
17711 (when (> d 0)
17712 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17713 (push d l))
17714 (when (> h 0)
17715 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17716 (push h l))
17717 (when (> m 0)
17718 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17719 (push m l))
17720 (apply 'format fmt (nreverse l))))
17722 (defun org-time-string-to-time (s &optional buffer pos)
17723 "Convert a timestamp string into internal time."
17724 (condition-case errdata
17725 (apply 'encode-time (org-parse-time-string s))
17726 (error (error "Bad timestamp `%s'%s\nError was: %s"
17727 s (if (not (and buffer pos))
17729 (format-message " at %d in buffer `%s'" pos buffer))
17730 (cdr errdata)))))
17732 (defun org-time-string-to-seconds (s)
17733 "Convert a timestamp string to a number of seconds."
17734 (float-time (org-time-string-to-time s)))
17736 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17738 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17739 "Convert time stamp S to an absolute day number.
17741 If DAYNR in non-nil, and there is a specifier for a cyclic time
17742 stamp, get the closest date to DAYNR. If PREFER is
17743 `past' (respectively `future') return a date past (respectively
17744 after) or equal to DAYNR.
17746 POS is the location of time stamp S, as a buffer position in
17747 BUFFER.
17749 Diary sexp timestamps are matched against DAYNR, when non-nil.
17750 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17751 signalled."
17752 (cond
17753 ((string-match "\\`%%\\((.*)\\)" s)
17754 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17755 ;; only able to match individual dates. If it fails, raise an
17756 ;; error.
17757 (if (and daynr
17758 (org-diary-sexp-entry
17759 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17760 daynr
17761 (signal 'org-diary-sexp-no-match (list s))))
17762 ((and daynr show-all) (org-closest-date s daynr prefer))
17763 (t (time-to-days
17764 (condition-case errdata
17765 (apply #'encode-time (org-parse-time-string s))
17766 (error (error "Bad timestamp `%s'%s\nError was: %s"
17768 (if (not (and buffer pos)) ""
17769 (format-message " at %d in buffer `%s'" pos buffer))
17770 (cdr errdata))))))))
17772 (defun org-days-to-iso-week (days)
17773 "Return the iso week number."
17774 (require 'cal-iso)
17775 (car (calendar-iso-from-absolute days)))
17777 (defun org-small-year-to-year (year)
17778 "Convert 2-digit years into 4-digit years.
17779 YEAR is expanded into one of the 30 next years, if possible, or
17780 into a past one. Any year larger than 99 is returned unchanged."
17781 (if (>= year 100) year
17782 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17783 (century (/ current 100))
17784 (offset (- year (% current 100))))
17785 (cond ((> offset 30) (+ (* (1- century) 100) year))
17786 ((> offset -70) (+ (* century 100) year))
17787 (t (+ (* (1+ century) 100) year))))))
17789 (defun org-time-from-absolute (d)
17790 "Return the time corresponding to date D.
17791 D may be an absolute day number, or a calendar-type list (month day year)."
17792 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17793 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17795 (defvar org-agenda-current-date)
17796 (defun org-calendar-holiday ()
17797 "List of holidays, for Diary display in Org mode."
17798 (require 'holidays)
17799 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17800 (and hl (mapconcat #'identity hl "; "))))
17802 (defun org-diary-sexp-entry (sexp entry d)
17803 "Process a SEXP diary ENTRY for date D."
17804 (require 'diary-lib)
17805 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17806 ;; dynamically.
17807 (let* ((sexp `(let ((entry ,entry)
17808 (date ',d))
17809 ,(car (read-from-string sexp))))
17810 (result (if calendar-debug-sexp (eval sexp)
17811 (condition-case nil
17812 (eval sexp)
17813 (error
17814 (beep)
17815 (message "Bad sexp at line %d in %s: %s"
17816 (org-current-line)
17817 (buffer-file-name) sexp)
17818 (sleep-for 2))))))
17819 (cond ((stringp result) (split-string result "; "))
17820 ((and (consp result)
17821 (not (consp (cdr result)))
17822 (stringp (cdr result))) (cdr result))
17823 ((and (consp result)
17824 (stringp (car result))) result)
17825 (result entry))))
17827 (defun org-diary-to-ical-string (frombuf)
17828 "Get iCalendar entries from diary entries in buffer FROMBUF.
17829 This uses the icalendar.el library."
17830 (let* ((tmpdir temporary-file-directory)
17831 (tmpfile (make-temp-name
17832 (expand-file-name "orgics" tmpdir)))
17833 buf rtn b e)
17834 (with-current-buffer frombuf
17835 (icalendar-export-region (point-min) (point-max) tmpfile)
17836 (setq buf (find-buffer-visiting tmpfile))
17837 (set-buffer buf)
17838 (goto-char (point-min))
17839 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17840 (setq b (match-beginning 0)))
17841 (goto-char (point-max))
17842 (when (re-search-backward "^END:VEVENT" nil t)
17843 (setq e (match-end 0)))
17844 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17845 (kill-buffer buf)
17846 (delete-file tmpfile)
17847 rtn))
17849 (defun org-closest-date (start current prefer)
17850 "Return closest date to CURRENT starting from START.
17852 CURRENT and START are both time stamps.
17854 When PREFER is `past', return a date that is either CURRENT or
17855 past. When PREFER is `future', return a date that is either
17856 CURRENT or future.
17858 Only time stamps with a repeater are modified. Any other time
17859 stamp stay unchanged. In any case, return value is an absolute
17860 day number."
17861 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17862 ;; No repeater. Do not shift time stamp.
17863 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17864 (let ((value (string-to-number (match-string 1 start)))
17865 (type (match-string 2 start)))
17866 (if (= 0 value)
17867 ;; Repeater with a 0-value is considered as void.
17868 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17869 (let* ((base (org-date-to-gregorian start))
17870 (target (org-date-to-gregorian current))
17871 (sday (calendar-absolute-from-gregorian base))
17872 (cday (calendar-absolute-from-gregorian target))
17873 n1 n2)
17874 ;; If START is already past CURRENT, just return START.
17875 (if (<= cday sday) sday
17876 ;; Compute closest date before (N1) and closest date past
17877 ;; (N2) CURRENT.
17878 (pcase type
17879 ("h"
17880 (let ((missing-hours
17881 (mod (+ (- (* 24 (- cday sday))
17882 (nth 2 (org-parse-time-string start)))
17883 org-extend-today-until)
17884 value)))
17885 (setf n1 (if (= missing-hours 0) cday
17886 (- cday (1+ (/ missing-hours 24)))))
17887 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17888 ((or "d" "w")
17889 (let ((value (if (equal type "w") (* 7 value) value)))
17890 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17891 (setf n2 (+ n1 value))))
17892 ("m"
17893 (let* ((add-months
17894 (lambda (d n)
17895 ;; Add N months to gregorian date D, i.e.,
17896 ;; a list (MONTH DAY YEAR). Return a valid
17897 ;; gregorian date.
17898 (let ((m (+ (nth 0 d) n)))
17899 (list (mod m 12)
17900 (nth 1 d)
17901 (+ (/ m 12) (nth 2 d))))))
17902 (months ; Complete months to TARGET.
17903 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17904 (- (nth 0 target) (nth 0 base))
17905 ;; If START's day is greater than
17906 ;; TARGET's, remove incomplete month.
17907 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17908 value)
17909 value))
17910 (before (funcall add-months base months)))
17911 (setf n1 (calendar-absolute-from-gregorian before))
17912 (setf n2
17913 (calendar-absolute-from-gregorian
17914 (funcall add-months before value)))))
17916 (let* ((d (nth 1 base))
17917 (m (nth 0 base))
17918 (y (nth 2 base))
17919 (years ; Complete years to TARGET.
17920 (* (/ (- (nth 2 target)
17922 ;; If START's month and day are
17923 ;; greater than TARGET's, remove
17924 ;; incomplete year.
17925 (if (or (> (nth 0 target) m)
17926 (and (= (nth 0 target) m)
17927 (> (nth 1 target) d)))
17930 value)
17931 value))
17932 (before (list m d (+ y years))))
17933 (setf n1 (calendar-absolute-from-gregorian before))
17934 (setf n2 (calendar-absolute-from-gregorian
17935 (list m d (+ (nth 2 before) value)))))))
17936 ;; Handle PREFER parameter, if any.
17937 (cond
17938 ((eq prefer 'past) (if (= cday n2) n2 n1))
17939 ((eq prefer 'future) (if (= cday n1) n1 n2))
17940 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17942 (defun org-date-to-gregorian (d)
17943 "Turn any specification of date D into a Gregorian date for the calendar."
17944 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17945 ((and (listp d) (= (length d) 3)) d)
17946 ((stringp d)
17947 (let ((d (org-parse-time-string d)))
17948 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17949 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17951 (defun org-parse-time-string (s &optional nodefault)
17952 "Parse the standard Org-mode time string.
17953 This should be a lot faster than the normal `parse-time-string'.
17954 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17955 hour and minute fields will be nil if not given."
17956 (cond ((string-match org-ts-regexp0 s)
17957 (list 0
17958 (when (or (match-beginning 8) (not nodefault))
17959 (string-to-number (or (match-string 8 s) "0")))
17960 (when (or (match-beginning 7) (not nodefault))
17961 (string-to-number (or (match-string 7 s) "0")))
17962 (string-to-number (match-string 4 s))
17963 (string-to-number (match-string 3 s))
17964 (string-to-number (match-string 2 s))
17965 nil nil nil))
17966 ((string-match "^<[^>]+>$" s)
17967 (decode-time (seconds-to-time (org-matcher-time s))))
17968 (t (error "Not a standard Org-mode time string: %s" s))))
17970 (defun org-timestamp-up (&optional arg)
17971 "Increase the date item at the cursor by one.
17972 If the cursor is on the year, change the year. If it is on the month,
17973 the day or the time, change that.
17974 With prefix ARG, change by that many units."
17975 (interactive "p")
17976 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17978 (defun org-timestamp-down (&optional arg)
17979 "Decrease the date item at the cursor by one.
17980 If the cursor is on the year, change the year. If it is on the month,
17981 the day or the time, change that.
17982 With prefix ARG, change by that many units."
17983 (interactive "p")
17984 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17986 (defun org-timestamp-up-day (&optional arg)
17987 "Increase the date in the time stamp by one day.
17988 With prefix ARG, change that many days."
17989 (interactive "p")
17990 (if (and (not (org-at-timestamp-p t))
17991 (org-at-heading-p))
17992 (org-todo 'up)
17993 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17995 (defun org-timestamp-down-day (&optional arg)
17996 "Decrease the date in the time stamp by one day.
17997 With prefix ARG, change that many days."
17998 (interactive "p")
17999 (if (and (not (org-at-timestamp-p t))
18000 (org-at-heading-p))
18001 (org-todo 'down)
18002 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
18004 (defun org-at-timestamp-p (&optional inactive-ok)
18005 "Non-nil if point is inside a timestamp.
18007 When optional argument INACTIVE-OK is non-nil, also consider
18008 inactive timestamps.
18010 When this function returns a non-nil value, match data is set
18011 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18012 INACTIVE-OK."
18013 (interactive)
18014 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18015 (pos (point))
18016 (ans (or (looking-at tsr)
18017 (save-excursion
18018 (skip-chars-backward "^[<\n\r\t")
18019 (when (> (point) (point-min)) (backward-char 1))
18020 (and (looking-at tsr)
18021 (> (- (match-end 0) pos) -1))))))
18022 (and ans
18023 (boundp 'org-ts-what)
18024 (setq org-ts-what
18025 (cond
18026 ((= pos (match-beginning 0)) 'bracket)
18027 ;; Point is considered to be "on the bracket" whether
18028 ;; it's really on it or right after it.
18029 ((= pos (1- (match-end 0))) 'bracket)
18030 ((= pos (match-end 0)) 'after)
18031 ((org-pos-in-match-range pos 2) 'year)
18032 ((org-pos-in-match-range pos 3) 'month)
18033 ((org-pos-in-match-range pos 7) 'hour)
18034 ((org-pos-in-match-range pos 8) 'minute)
18035 ((or (org-pos-in-match-range pos 4)
18036 (org-pos-in-match-range pos 5)) 'day)
18037 ((and (> pos (or (match-end 8) (match-end 5)))
18038 (< pos (match-end 0)))
18039 (- pos (or (match-end 8) (match-end 5))))
18040 (t 'day))))
18041 ans))
18043 (defun org-toggle-timestamp-type ()
18044 "Toggle the type (<active> or [inactive]) of a time stamp."
18045 (interactive)
18046 (when (org-at-timestamp-p t)
18047 (let ((beg (match-beginning 0)) (end (match-end 0))
18048 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18049 (save-excursion
18050 (goto-char beg)
18051 (while (re-search-forward "[][<>]" end t)
18052 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18053 t t)))
18054 (message "Timestamp is now %sactive"
18055 (if (equal (char-after beg) ?<) "" "in")))))
18057 (defun org-at-clock-log-p nil
18058 "Is the cursor on the clock log line?"
18059 (save-excursion
18060 (move-beginning-of-line 1)
18061 (looking-at org-clock-line-re)))
18063 (defvar org-clock-history) ; defined in org-clock.el
18064 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18065 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18066 "Change the date in the time stamp at point.
18067 The date will be changed by N times WHAT. WHAT can be `day', `month',
18068 `year', `minute', `second'. If WHAT is not given, the cursor position
18069 in the timestamp determines what will be changed.
18070 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18071 (let ((origin (point)) origin-cat
18072 with-hm inactive
18073 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18074 org-ts-what
18075 extra rem
18076 ts time time0 fixnext clrgx)
18077 (unless (org-at-timestamp-p t)
18078 (user-error "Not at a timestamp"))
18079 (if (and (not what) (eq org-ts-what 'bracket))
18080 (org-toggle-timestamp-type)
18081 ;; Point isn't on brackets. Remember the part of the time-stamp
18082 ;; the point was in. Indeed, size of time-stamps may change,
18083 ;; but point must be kept in the same category nonetheless.
18084 (setq origin-cat org-ts-what)
18085 (when (and (not what) (not (eq org-ts-what 'day))
18086 org-display-custom-times
18087 (get-text-property (point) 'display)
18088 (not (get-text-property (1- (point)) 'display)))
18089 (setq org-ts-what 'day))
18090 (setq org-ts-what (or what org-ts-what)
18091 inactive (= (char-after (match-beginning 0)) ?\[)
18092 ts (match-string 0))
18093 (replace-match "")
18094 (when (string-match
18095 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18097 (setq extra (match-string 1 ts))
18098 (when suppress-tmp-delay
18099 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18100 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18101 (setq with-hm t))
18102 (setq time0 (org-parse-time-string ts))
18103 (when (and updown
18104 (eq org-ts-what 'minute)
18105 (not current-prefix-arg))
18106 ;; This looks like s-up and s-down. Change by one rounding step.
18107 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18108 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18109 (setcar (cdr time0) (+ (nth 1 time0)
18110 (if (> n 0) (- rem) (- dm rem))))))
18111 (setq time
18112 (apply #'encode-time
18113 (or (car time0) 0)
18114 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18115 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18116 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18117 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18118 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18119 (nthcdr 6 time0)))
18120 (when (and (member org-ts-what '(hour minute))
18121 extra
18122 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18123 (setq extra (org-modify-ts-extra
18124 extra
18125 (if (eq org-ts-what 'hour) 2 5)
18126 n dm)))
18127 (when (integerp org-ts-what)
18128 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18129 (when (eq what 'calendar)
18130 (let ((cal-date (org-get-date-from-calendar)))
18131 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18132 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18133 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18134 (setcar time0 (or (car time0) 0))
18135 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18136 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18137 (setq time (apply 'encode-time time0))))
18138 ;; Insert the new time-stamp, and ensure point stays in the same
18139 ;; category as before (i.e. not after the last position in that
18140 ;; category).
18141 (let ((pos (point)))
18142 ;; Stay before inserted string. `save-excursion' is of no use.
18143 (setq org-last-changed-timestamp
18144 (org-insert-time-stamp time with-hm inactive nil nil extra))
18145 (goto-char pos))
18146 (save-match-data
18147 (looking-at org-ts-regexp3)
18148 (goto-char (cond
18149 ;; `day' category ends before `hour' if any, or at
18150 ;; the end of the day name.
18151 ((eq origin-cat 'day)
18152 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18153 ((eq origin-cat 'hour) (min (match-end 7) origin))
18154 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18155 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18156 ;; `year' and `month' have both fixed size: point
18157 ;; couldn't have moved into another part.
18158 (t origin))))
18159 ;; Update clock if on a CLOCK line.
18160 (org-clock-update-time-maybe)
18161 ;; Maybe adjust the closest clock in `org-clock-history'
18162 (when org-clock-adjust-closest
18163 (if (not (and (org-at-clock-log-p)
18164 (< 1 (length (delq nil (mapcar 'marker-position
18165 org-clock-history))))))
18166 (message "No clock to adjust")
18167 (cond ((save-excursion ; fix previous clock?
18168 (re-search-backward org-ts-regexp0 nil t)
18169 (looking-back (concat org-clock-string " \\[")
18170 (line-beginning-position)))
18171 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18172 ((save-excursion ; fix next clock?
18173 (re-search-backward org-ts-regexp0 nil t)
18174 (looking-at (concat org-ts-regexp0 "\\] =>")))
18175 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18176 (save-window-excursion
18177 ;; Find closest clock to point, adjust the previous/next one in history
18178 (let* ((p (save-excursion (org-back-to-heading t)))
18179 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18180 (clfixnth
18181 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18182 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18183 (if (not clfixpos)
18184 (message "No clock to adjust")
18185 (save-excursion
18186 (org-goto-marker-or-bmk clfixpos)
18187 (org-show-subtree)
18188 (when (re-search-forward clrgx nil t)
18189 (goto-char (match-beginning 1))
18190 (let (org-clock-adjust-closest)
18191 (org-timestamp-change n org-ts-what updown))
18192 (message "Clock adjusted in %s for heading: %s"
18193 (file-name-nondirectory (buffer-file-name))
18194 (org-get-heading t t)))))))))
18195 ;; Try to recenter the calendar window, if any.
18196 (when (and org-calendar-follow-timestamp-change
18197 (get-buffer-window "*Calendar*" t)
18198 (memq org-ts-what '(day month year)))
18199 (org-recenter-calendar (time-to-days time))))))
18201 (defun org-modify-ts-extra (s pos n dm)
18202 "Change the different parts of the lead-time and repeat fields in timestamp."
18203 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18204 ng h m new rem)
18205 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18206 (cond
18207 ((or (org-pos-in-match-range pos 2)
18208 (org-pos-in-match-range pos 3))
18209 (setq m (string-to-number (match-string 3 s))
18210 h (string-to-number (match-string 2 s)))
18211 (if (org-pos-in-match-range pos 2)
18212 (setq h (+ h n))
18213 (setq n (* dm (org-no-warnings (signum n))))
18214 (unless (= 0 (setq rem (% m dm)))
18215 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18216 (setq m (+ m n)))
18217 (when (< m 0) (setq m (+ m 60) h (1- h)))
18218 (when (> m 59) (setq m (- m 60) h (1+ h)))
18219 (setq h (mod h 24))
18220 (setq ng 1 new (format "-%02d:%02d" h m)))
18221 ((org-pos-in-match-range pos 6)
18222 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18223 ((org-pos-in-match-range pos 5)
18224 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18226 ((org-pos-in-match-range pos 9)
18227 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18228 ((org-pos-in-match-range pos 8)
18229 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18231 (when ng
18232 (setq s (concat
18233 (substring s 0 (match-beginning ng))
18235 (substring s (match-end ng))))))
18238 (defun org-recenter-calendar (d)
18239 "If the calendar is visible, recenter it to date D."
18240 (let ((cwin (get-buffer-window "*Calendar*" t)))
18241 (when cwin
18242 (let ((calendar-move-hook nil))
18243 (with-selected-window cwin
18244 (calendar-goto-date
18245 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18247 (defun org-goto-calendar (&optional arg)
18248 "Go to the Emacs calendar at the current date.
18249 If there is a time stamp in the current line, go to that date.
18250 A prefix ARG can be used to force the current date."
18251 (interactive "P")
18252 (let ((tsr org-ts-regexp) diff
18253 (calendar-move-hook nil)
18254 (calendar-view-holidays-initially-flag nil)
18255 (calendar-view-diary-initially-flag nil))
18256 (when (or (org-at-timestamp-p)
18257 (save-excursion
18258 (beginning-of-line 1)
18259 (looking-at (concat ".*" tsr))))
18260 (let ((d1 (time-to-days (current-time)))
18261 (d2 (time-to-days
18262 (org-time-string-to-time (match-string 1)))))
18263 (setq diff (- d2 d1))))
18264 (calendar)
18265 (calendar-goto-today)
18266 (when (and diff (not arg)) (calendar-forward-day diff))))
18268 (defun org-get-date-from-calendar ()
18269 "Return a list (month day year) of date at point in calendar."
18270 (with-current-buffer "*Calendar*"
18271 (save-match-data
18272 (calendar-cursor-to-date))))
18274 (defun org-date-from-calendar ()
18275 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18276 If there is already a time stamp at the cursor position, update it."
18277 (interactive)
18278 (if (org-at-timestamp-p t)
18279 (org-timestamp-change 0 'calendar)
18280 (let ((cal-date (org-get-date-from-calendar)))
18281 (org-insert-time-stamp
18282 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18284 (defcustom org-effort-durations
18285 `(("min" . 1)
18286 ("h" . 60)
18287 ("d" . ,(* 60 8))
18288 ("w" . ,(* 60 8 5))
18289 ("m" . ,(* 60 8 5 4))
18290 ("y" . ,(* 60 8 5 40)))
18291 "Conversion factor to minutes for an effort modifier.
18293 Each entry has the form (MODIFIER . MINUTES).
18295 In an effort string, a number followed by MODIFIER is multiplied
18296 by the specified number of MINUTES to obtain an effort in
18297 minutes.
18299 For example, if the value of this variable is ((\"hours\" . 60)), then an
18300 effort string \"2hours\" is equivalent to 120 minutes."
18301 :group 'org-agenda
18302 :version "25.1"
18303 :package-version '(Org . "8.3")
18304 :type '(alist :key-type (string :tag "Modifier")
18305 :value-type (number :tag "Minutes")))
18307 (defun org-minutes-to-clocksum-string (m)
18308 "Format number of minutes as a clocksum string.
18309 The format is determined by `org-time-clocksum-format',
18310 `org-time-clocksum-use-fractional' and
18311 `org-time-clocksum-fractional-format' and
18312 `org-time-clocksum-use-effort-durations'."
18313 (let ((clocksum "")
18314 (m (round m)) ; Don't allow fractions of minutes
18315 h d w mo y fmt n)
18316 (setq h (if org-time-clocksum-use-effort-durations
18317 (cdr (assoc "h" org-effort-durations)) 60)
18318 d (if org-time-clocksum-use-effort-durations
18319 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18320 w (if org-time-clocksum-use-effort-durations
18321 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18322 mo (if org-time-clocksum-use-effort-durations
18323 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18324 y (if org-time-clocksum-use-effort-durations
18325 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18326 ;; fractional format
18327 (if org-time-clocksum-use-fractional
18328 (cond
18329 ;; single format string
18330 ((stringp org-time-clocksum-fractional-format)
18331 (format org-time-clocksum-fractional-format (/ m (float h))))
18332 ;; choice of fractional formats for different time units
18333 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18334 (> (/ (truncate m) (* y d h)) 0))
18335 (format fmt (/ m (* y d (float h)))))
18336 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18337 (> (/ (truncate m) (* mo d h)) 0))
18338 (format fmt (/ m (* mo d (float h)))))
18339 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18340 (> (/ (truncate m) (* w d h)) 0))
18341 (format fmt (/ m (* w d (float h)))))
18342 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18343 (> (/ (truncate m) (* d h)) 0))
18344 (format fmt (/ m (* d (float h)))))
18345 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18346 (> (/ (truncate m) h) 0))
18347 (format fmt (/ m (float h))))
18348 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18349 (format fmt m))
18350 ;; fall back to smallest time unit with a format
18351 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18352 (format fmt (/ m (float h))))
18353 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18354 (format fmt (/ m (* d (float h)))))
18355 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18356 (format fmt (/ m (* w d (float h)))))
18357 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18358 (format fmt (/ m (* mo d (float h)))))
18359 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18360 (format fmt (/ m (* y d (float h))))))
18361 ;; standard (non-fractional) format, with single format string
18362 (if (stringp org-time-clocksum-format)
18363 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18364 ;; separate formats components
18365 (and (setq fmt (plist-get org-time-clocksum-format :years))
18366 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18367 (plist-get org-time-clocksum-format :require-years))
18368 (setq clocksum (concat clocksum (format fmt n))
18369 m (- m (* n y d h))))
18370 (and (setq fmt (plist-get org-time-clocksum-format :months))
18371 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18372 (plist-get org-time-clocksum-format :require-months))
18373 (setq clocksum (concat clocksum (format fmt n))
18374 m (- m (* n mo d h))))
18375 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18376 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18377 (plist-get org-time-clocksum-format :require-weeks))
18378 (setq clocksum (concat clocksum (format fmt n))
18379 m (- m (* n w d h))))
18380 (and (setq fmt (plist-get org-time-clocksum-format :days))
18381 (or (> (setq n (/ (truncate m) (* d h))) 0)
18382 (plist-get org-time-clocksum-format :require-days))
18383 (setq clocksum (concat clocksum (format fmt n))
18384 m (- m (* n d h))))
18385 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18386 (or (> (setq n (/ (truncate m) h)) 0)
18387 (plist-get org-time-clocksum-format :require-hours))
18388 (setq clocksum (concat clocksum (format fmt n))
18389 m (- m (* n h))))
18390 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18391 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18392 (setq clocksum (concat clocksum (format fmt m))))
18393 ;; return formatted time duration
18394 clocksum))))
18396 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18397 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18398 "Org mode version 8.0")
18400 (defun org-hours-to-clocksum-string (n)
18401 (org-minutes-to-clocksum-string (* n 60)))
18403 (defun org-hh:mm-string-to-minutes (s)
18404 "Convert a string H:MM to a number of minutes.
18405 If the string is just a number, interpret it as minutes.
18406 In fact, the first hh:mm or number in the string will be taken,
18407 there can be extra stuff in the string.
18408 If no number is found, the return value is 0."
18409 (cond
18410 ((integerp s) s)
18411 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18412 (+ (* (string-to-number (match-string 1 s)) 60)
18413 (string-to-number (match-string 2 s))))
18414 ((string-match "\\([0-9]+\\)" s)
18415 (string-to-number (match-string 1 s)))
18416 (t 0)))
18418 (defcustom org-image-actual-width t
18419 "Should we use the actual width of images when inlining them?
18421 When set to t, always use the image width.
18423 When set to a number, use imagemagick (when available) to set
18424 the image's width to this value.
18426 When set to a number in a list, try to get the width from any
18427 #+ATTR.* keyword if it matches a width specification like
18429 #+ATTR_HTML: :width 300px
18431 and fall back on that number if none is found.
18433 When set to nil, try to get the width from an #+ATTR.* keyword
18434 and fall back on the original width if none is found.
18436 This requires Emacs >= 24.1, build with imagemagick support."
18437 :group 'org-appearance
18438 :version "24.4"
18439 :package-version '(Org . "8.0")
18440 :type '(choice
18441 (const :tag "Use the image width" t)
18442 (integer :tag "Use a number of pixels")
18443 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18444 (const :tag "Use #+ATTR* or don't resize" nil)))
18446 (defcustom org-agenda-inhibit-startup nil
18447 "Inhibit startup when preparing agenda buffers.
18448 When this variable is t, the initialization of the Org agenda
18449 buffers is inhibited: e.g. the visibility state is not set, the
18450 tables are not re-aligned, etc."
18451 :type 'boolean
18452 :version "24.3"
18453 :group 'org-agenda)
18455 (define-obsolete-variable-alias
18456 'org-agenda-ignore-drawer-properties
18457 'org-agenda-ignore-properties "25.1")
18459 (defcustom org-agenda-ignore-properties nil
18460 "Avoid updating text properties when building the agenda.
18461 Properties are used to prepare buffers for effort estimates,
18462 appointments, statistics and subtree-local categories.
18463 If you don't use these in the agenda, you can add them to this
18464 list and agenda building will be a bit faster.
18465 The value is a list, with zero or more of the symbols `effort', `appt',
18466 `stats' or `category'."
18467 :type '(set :greedy t
18468 (const effort)
18469 (const appt)
18470 (const stats)
18471 (const category))
18472 :version "25.1"
18473 :package-version '(Org . "8.3")
18474 :group 'org-agenda)
18476 (defun org-duration-string-to-minutes (s &optional output-to-string)
18477 "Convert a duration string S to minutes.
18479 A bare number is interpreted as minutes, modifiers can be set by
18480 customizing `org-effort-durations' (which see).
18482 Entries containing a colon are interpreted as H:MM by
18483 `org-hh:mm-string-to-minutes'."
18484 (let ((result 0)
18485 (re (concat "\\([0-9.]+\\) *\\("
18486 (regexp-opt (mapcar 'car org-effort-durations))
18487 "\\)")))
18488 (while (string-match re s)
18489 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18490 (string-to-number (match-string 1 s))))
18491 (setq s (replace-match "" nil t s)))
18492 (setq result (floor result))
18493 (cl-incf result (org-hh:mm-string-to-minutes s))
18494 (if output-to-string (number-to-string result) result)))
18496 ;;;; Files
18498 (defun org-save-all-org-buffers ()
18499 "Save all Org-mode buffers without user confirmation."
18500 (interactive)
18501 (message "Saving all Org-mode buffers...")
18502 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18503 (when (featurep 'org-id) (org-id-locations-save))
18504 (message "Saving all Org-mode buffers... done"))
18506 (defun org-revert-all-org-buffers ()
18507 "Revert all Org-mode buffers.
18508 Prompt for confirmation when there are unsaved changes.
18509 Be sure you know what you are doing before letting this function
18510 overwrite your changes.
18512 This function is useful in a setup where one tracks org files
18513 with a version control system, to revert on one machine after pulling
18514 changes from another. I believe the procedure must be like this:
18516 1. M-x org-save-all-org-buffers
18517 2. Pull changes from the other machine, resolve conflicts
18518 3. M-x org-revert-all-org-buffers"
18519 (interactive)
18520 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18521 (user-error "Abort"))
18522 (save-excursion
18523 (save-window-excursion
18524 (dolist (b (buffer-list))
18525 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18526 (with-current-buffer b buffer-file-name))
18527 (org-pop-to-buffer-same-window b)
18528 (revert-buffer t 'no-confirm)))
18529 (when (and (featurep 'org-id) org-id-track-globally)
18530 (org-id-locations-load)))))
18532 ;;;; Agenda files
18534 ;;;###autoload
18535 (defun org-switchb (&optional arg)
18536 "Switch between Org buffers.
18538 With \\[universal-argument] prefix, restrict available buffers to files.
18540 With \\[universal-argument] \\[universal-argument] \
18541 prefix, restrict available buffers to agenda files."
18542 (interactive "P")
18543 (let ((blist (org-buffer-list
18544 (cond ((equal arg '(4)) 'files)
18545 ((equal arg '(16)) 'agenda)))))
18546 (org-pop-to-buffer-same-window
18547 (completing-read "Org buffer: "
18548 (mapcar #'list (mapcar #'buffer-name blist))
18549 nil t))))
18551 (defun org-buffer-list (&optional predicate exclude-tmp)
18552 "Return a list of Org buffers.
18553 PREDICATE can be `export', `files' or `agenda'.
18555 export restrict the list to Export buffers.
18556 files restrict the list to buffers visiting Org files.
18557 agenda restrict the list to buffers visiting agenda files.
18559 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18560 (let* ((bfn nil)
18561 (agenda-files (and (eq predicate 'agenda)
18562 (mapcar 'file-truename (org-agenda-files t))))
18563 (filter
18564 (cond
18565 ((eq predicate 'files)
18566 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18567 ((eq predicate 'export)
18568 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18569 ((eq predicate 'agenda)
18570 (lambda (b)
18571 (with-current-buffer b
18572 (and (derived-mode-p 'org-mode)
18573 (setq bfn (buffer-file-name b))
18574 (member (file-truename bfn) agenda-files)))))
18575 (t (lambda (b) (with-current-buffer b
18576 (or (derived-mode-p 'org-mode)
18577 (string-match "\\*Org .*Export"
18578 (buffer-name b)))))))))
18579 (delq nil
18580 (mapcar
18581 (lambda(b)
18582 (if (and (funcall filter b)
18583 (or (not exclude-tmp)
18584 (not (string-match "tmp" (buffer-name b)))))
18586 nil))
18587 (buffer-list)))))
18589 (defun org-agenda-files (&optional unrestricted archives)
18590 "Get the list of agenda files.
18591 Optional UNRESTRICTED means return the full list even if a restriction
18592 is currently in place.
18593 When ARCHIVES is t, include all archive files that are really being
18594 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18595 `org-agenda-archives-mode' is t."
18596 (let ((files
18597 (cond
18598 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18599 ((stringp org-agenda-files) (org-read-agenda-file-list))
18600 ((listp org-agenda-files) org-agenda-files)
18601 (t (error "Invalid value of `org-agenda-files'")))))
18602 (setq files (apply 'append
18603 (mapcar (lambda (f)
18604 (if (file-directory-p f)
18605 (directory-files
18606 f t org-agenda-file-regexp)
18607 (list f)))
18608 files)))
18609 (when org-agenda-skip-unavailable-files
18610 (setq files (delq nil
18611 (mapcar (function
18612 (lambda (file)
18613 (and (file-readable-p file) file)))
18614 files))))
18615 (when (or (eq archives t)
18616 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18617 (setq files (org-add-archive-files files)))
18618 files))
18620 (defun org-agenda-file-p (&optional file)
18621 "Return non-nil, if FILE is an agenda file.
18622 If FILE is omitted, use the file associated with the current
18623 buffer."
18624 (let ((fname (or file (buffer-file-name))))
18625 (and fname
18626 (member (file-truename fname)
18627 (mapcar #'file-truename (org-agenda-files t))))))
18629 (defun org-edit-agenda-file-list ()
18630 "Edit the list of agenda files.
18631 Depending on setup, this either uses customize to edit the variable
18632 `org-agenda-files', or it visits the file that is holding the list. In the
18633 latter case, the buffer is set up in a way that saving it automatically kills
18634 the buffer and restores the previous window configuration."
18635 (interactive)
18636 (if (stringp org-agenda-files)
18637 (let ((cw (current-window-configuration)))
18638 (find-file org-agenda-files)
18639 (setq-local org-window-configuration cw)
18640 (add-hook 'after-save-hook
18641 (lambda ()
18642 (set-window-configuration
18643 (prog1 org-window-configuration
18644 (kill-buffer (current-buffer))))
18645 (org-install-agenda-files-menu)
18646 (message "New agenda file list installed"))
18647 nil 'local)
18648 (message "%s" (substitute-command-keys
18649 "Edit list and finish with \\[save-buffer]")))
18650 (customize-variable 'org-agenda-files)))
18652 (defun org-store-new-agenda-file-list (list)
18653 "Set new value for the agenda file list and save it correctly."
18654 (if (stringp org-agenda-files)
18655 (let ((fe (org-read-agenda-file-list t)) b u)
18656 (while (setq b (find-buffer-visiting org-agenda-files))
18657 (kill-buffer b))
18658 (with-temp-file org-agenda-files
18659 (insert
18660 (mapconcat
18661 (lambda (f) ;; Keep un-expanded entries.
18662 (if (setq u (assoc f fe))
18663 (cdr u)
18665 list "\n")
18666 "\n")))
18667 (let ((org-mode-hook nil) (org-inhibit-startup t)
18668 (org-insert-mode-line-in-empty-file nil))
18669 (setq org-agenda-files list)
18670 (customize-save-variable 'org-agenda-files org-agenda-files))))
18672 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18673 "Read the list of agenda files from a file.
18674 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18675 filenames, used by `org-store-new-agenda-file-list' to write back
18676 un-expanded file names."
18677 (when (file-directory-p org-agenda-files)
18678 (error "`org-agenda-files' cannot be a single directory"))
18679 (when (stringp org-agenda-files)
18680 (with-temp-buffer
18681 (insert-file-contents org-agenda-files)
18682 (mapcar
18683 (lambda (f)
18684 (let ((e (expand-file-name (substitute-in-file-name f)
18685 org-directory)))
18686 (if pair-with-expansion
18687 (cons e f)
18688 e)))
18689 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18691 ;;;###autoload
18692 (defun org-cycle-agenda-files ()
18693 "Cycle through the files in `org-agenda-files'.
18694 If the current buffer visits an agenda file, find the next one in the list.
18695 If the current buffer does not, find the first agenda file."
18696 (interactive)
18697 (let* ((fs (or (org-agenda-files t)
18698 (user-error "No agenda files")))
18699 (files (copy-sequence fs))
18700 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18701 file)
18702 (when tcf
18703 (while (and (setq file (pop files))
18704 (not (equal (file-truename file) tcf)))))
18705 (find-file (car (or files fs)))
18706 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18708 (defun org-agenda-file-to-front (&optional to-end)
18709 "Move/add the current file to the top of the agenda file list.
18710 If the file is not present in the list, it is added to the front. If it is
18711 present, it is moved there. With optional argument TO-END, add/move to the
18712 end of the list."
18713 (interactive "P")
18714 (let ((org-agenda-skip-unavailable-files nil)
18715 (file-alist (mapcar (lambda (x)
18716 (cons (file-truename x) x))
18717 (org-agenda-files t)))
18718 (ctf (file-truename
18719 (or buffer-file-name
18720 (user-error "Please save the current buffer to a file"))))
18721 x had)
18722 (setq x (assoc ctf file-alist) had x)
18724 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18725 (if to-end
18726 (setq file-alist (append (delq x file-alist) (list x)))
18727 (setq file-alist (cons x (delq x file-alist))))
18728 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18729 (org-install-agenda-files-menu)
18730 (message "File %s to %s of agenda file list"
18731 (if had "moved" "added") (if to-end "end" "front"))))
18733 (defun org-remove-file (&optional file)
18734 "Remove current file from the list of files in variable `org-agenda-files'.
18735 These are the files which are being checked for agenda entries.
18736 Optional argument FILE means use this file instead of the current."
18737 (interactive)
18738 (let* ((org-agenda-skip-unavailable-files nil)
18739 (file (or file buffer-file-name
18740 (user-error "Current buffer does not visit a file")))
18741 (true-file (file-truename file))
18742 (afile (abbreviate-file-name file))
18743 (files (delq nil (mapcar
18744 (lambda (x)
18745 (unless (equal true-file
18746 (file-truename x))
18748 (org-agenda-files t)))))
18749 (if (not (= (length files) (length (org-agenda-files t))))
18750 (progn
18751 (org-store-new-agenda-file-list files)
18752 (org-install-agenda-files-menu)
18753 (message "Removed from Org Agenda list: %s" afile))
18754 (message "File was not in list: %s (not removed)" afile))))
18756 (defun org-file-menu-entry (file)
18757 (vector file (list 'find-file file) t))
18759 (defun org-check-agenda-file (file)
18760 "Make sure FILE exists. If not, ask user what to do."
18761 (unless (file-exists-p file)
18762 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18763 (abbreviate-file-name file))
18764 (let ((r (downcase (read-char-exclusive))))
18765 (cond
18766 ((equal r ?r)
18767 (org-remove-file file)
18768 (throw 'nextfile t))
18769 (t (user-error "Abort"))))))
18771 (defun org-get-agenda-file-buffer (file)
18772 "Get an agenda buffer visiting FILE.
18773 If the buffer needs to be created, add it to the list of buffers
18774 which might be released later."
18775 (let ((buf (org-find-base-buffer-visiting file)))
18776 (if buf
18777 buf ; just return it
18778 ;; Make a new buffer and remember it
18779 (setq buf (find-file-noselect file))
18780 (when buf (push buf org-agenda-new-buffers))
18781 buf)))
18783 (defun org-release-buffers (blist)
18784 "Release all buffers in list, asking the user for confirmation when needed.
18785 When a buffer is unmodified, it is just killed. When modified, it is saved
18786 \(if the user agrees) and then killed."
18787 (let (file)
18788 (dolist (buf blist)
18789 (setq file (buffer-file-name buf))
18790 (when (and (buffer-modified-p buf)
18791 file
18792 (y-or-n-p (format "Save file %s? " file)))
18793 (with-current-buffer buf (save-buffer)))
18794 (kill-buffer buf))))
18796 (defun org-agenda-prepare-buffers (files)
18797 "Create buffers for all agenda files, protect archived trees and comments."
18798 (interactive)
18799 (let ((pa '(:org-archived t))
18800 (pc '(:org-comment t))
18801 (pall '(:org-archived t :org-comment t))
18802 (inhibit-read-only t)
18803 (org-inhibit-startup org-agenda-inhibit-startup)
18804 (rea (concat ":" org-archive-tag ":"))
18805 re pos)
18806 (setq org-tag-alist-for-agenda nil
18807 org-tag-groups-alist-for-agenda nil)
18808 (save-excursion
18809 (save-restriction
18810 (dolist (file files)
18811 (catch 'nextfile
18812 (if (bufferp file)
18813 (set-buffer file)
18814 (org-check-agenda-file file)
18815 (set-buffer (org-get-agenda-file-buffer file)))
18816 (widen)
18817 (org-set-regexps-and-options 'tags-only)
18818 (setq pos (point))
18819 (or (memq 'category org-agenda-ignore-properties)
18820 (org-refresh-category-properties))
18821 (or (memq 'stats org-agenda-ignore-properties)
18822 (org-refresh-stats-properties))
18823 (or (memq 'effort org-agenda-ignore-properties)
18824 (org-refresh-effort-properties))
18825 (or (memq 'appt org-agenda-ignore-properties)
18826 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18827 (setq org-todo-keywords-for-agenda
18828 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18829 (setq org-done-keywords-for-agenda
18830 (append org-done-keywords-for-agenda org-done-keywords))
18831 (setq org-todo-keyword-alist-for-agenda
18832 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18833 (setq org-tag-alist-for-agenda
18834 (org-uniquify
18835 (append org-tag-alist-for-agenda
18836 org-current-tag-alist)))
18837 ;; Merge current file's tag groups into global
18838 ;; `org-tag-groups-alist-for-agenda'.
18839 (when org-group-tags
18840 (dolist (alist org-tag-groups-alist)
18841 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18842 (if old
18843 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18844 (push alist org-tag-groups-alist-for-agenda)))))
18845 (org-with-silent-modifications
18846 (save-excursion
18847 (remove-text-properties (point-min) (point-max) pall)
18848 (when org-agenda-skip-archived-trees
18849 (goto-char (point-min))
18850 (while (re-search-forward rea nil t)
18851 (when (org-at-heading-p t)
18852 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18853 (goto-char (point-min))
18854 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18855 (while (re-search-forward re nil t)
18856 (when (save-match-data (org-in-commented-heading-p t))
18857 (add-text-properties
18858 (match-beginning 0) (org-end-of-subtree t) pc)))))
18859 (goto-char pos)))))
18860 (setq org-todo-keywords-for-agenda
18861 (org-uniquify org-todo-keywords-for-agenda))
18862 (setq org-todo-keyword-alist-for-agenda
18863 (org-uniquify org-todo-keyword-alist-for-agenda))))
18866 ;;;; CDLaTeX minor mode
18868 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18869 "Keymap for the minor `org-cdlatex-mode'.")
18871 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18872 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18873 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18874 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18875 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18877 (defvar org-cdlatex-texmathp-advice-is-done nil
18878 "Flag remembering if we have applied the advice to texmathp already.")
18880 (define-minor-mode org-cdlatex-mode
18881 "Toggle the minor `org-cdlatex-mode'.
18882 This mode supports entering LaTeX environment and math in LaTeX fragments
18883 in Org-mode.
18884 \\{org-cdlatex-mode-map}"
18885 nil " OCDL" nil
18886 (when org-cdlatex-mode
18887 (require 'cdlatex)
18888 (run-hooks 'cdlatex-mode-hook)
18889 (cdlatex-compute-tables))
18890 (unless org-cdlatex-texmathp-advice-is-done
18891 (setq org-cdlatex-texmathp-advice-is-done t)
18892 (defadvice texmathp (around org-math-always-on activate)
18893 "Always return t in org-mode buffers.
18894 This is because we want to insert math symbols without dollars even outside
18895 the LaTeX math segments. If Orgmode thinks that point is actually inside
18896 an embedded LaTeX fragment, let texmathp do its job.
18897 \\[org-cdlatex-mode-map]"
18898 (interactive)
18899 (let (p)
18900 (cond
18901 ((not (derived-mode-p 'org-mode)) ad-do-it)
18902 ((eq this-command 'cdlatex-math-symbol)
18903 (setq ad-return-value t
18904 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18906 (let ((p (org-inside-LaTeX-fragment-p)))
18907 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18908 (setq ad-return-value t
18909 texmathp-why '("Org-mode embedded math" . 0))
18910 (when p ad-do-it)))))))))
18912 (defun turn-on-org-cdlatex ()
18913 "Unconditionally turn on `org-cdlatex-mode'."
18914 (org-cdlatex-mode 1))
18916 (defun org-try-cdlatex-tab ()
18917 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18918 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18919 - inside a LaTeX fragment, or
18920 - after the first word in a line, where an abbreviation expansion could
18921 insert a LaTeX environment."
18922 (when org-cdlatex-mode
18923 (cond
18924 ;; Before any word on the line: No expansion possible.
18925 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18926 ;; Just after first word on the line: Expand it. Make sure it
18927 ;; cannot happen on headlines, though.
18928 ((save-excursion
18929 (skip-chars-backward "a-zA-Z0-9*")
18930 (skip-chars-backward " \t")
18931 (and (bolp) (not (org-at-heading-p))))
18932 (cdlatex-tab) t)
18933 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18935 (defun org-cdlatex-underscore-caret (&optional _arg)
18936 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18937 Revert to the normal definition outside of these fragments."
18938 (interactive "P")
18939 (if (org-inside-LaTeX-fragment-p)
18940 (call-interactively 'cdlatex-sub-superscript)
18941 (let (org-cdlatex-mode)
18942 (call-interactively (key-binding (vector last-input-event))))))
18944 (defun org-cdlatex-math-modify (&optional _arg)
18945 "Execute `cdlatex-math-modify' in LaTeX fragments.
18946 Revert to the normal definition outside of these fragments."
18947 (interactive "P")
18948 (if (org-inside-LaTeX-fragment-p)
18949 (call-interactively 'cdlatex-math-modify)
18950 (let (org-cdlatex-mode)
18951 (call-interactively (key-binding (vector last-input-event))))))
18953 (defun org-cdlatex-environment-indent (&optional environment item)
18954 "Execute `cdlatex-environment' and indent the inserted environment.
18956 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18958 The inserted environment is indented to current indentation
18959 unless point is at the beginning of the line, in which the
18960 environment remains unintended."
18961 (interactive)
18962 ;; cdlatex-environment always return nil. Therefore, capture output
18963 ;; first and determine if an environment was selected.
18964 (let* ((beg (point-marker))
18965 (end (copy-marker (point) t))
18966 (inserted (progn
18967 (ignore-errors (cdlatex-environment environment item))
18968 (< beg end)))
18969 ;; Figure out how many lines to move forward after the
18970 ;; environment has been inserted.
18971 (lines (when inserted
18972 (save-excursion
18973 (- (cl-loop while (< beg (point))
18974 with x = 0
18975 do (forward-line -1)
18976 (cl-incf x)
18977 finally return x)
18978 (if (progn (goto-char beg)
18979 (and (progn (skip-chars-forward " \t") (eolp))
18980 (progn (skip-chars-backward " \t") (bolp))))
18981 1 0)))))
18982 (env (org-trim (delete-and-extract-region beg end))))
18983 (when inserted
18984 ;; Get indentation of next line unless at column 0.
18985 (let ((ind (if (bolp) 0
18986 (save-excursion
18987 (org-return-indent)
18988 (prog1 (org-get-indentation)
18989 (when (progn (skip-chars-forward " \t") (eolp))
18990 (delete-region beg (point)))))))
18991 (bol (progn (skip-chars-backward " \t") (bolp))))
18992 ;; Insert a newline before environment unless at column zero
18993 ;; to "escape" the current line. Insert a newline if
18994 ;; something is one the same line as \end{ENVIRONMENT}.
18995 (insert
18996 (concat (unless bol "\n") env
18997 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18998 (unless (zerop ind)
18999 (save-excursion
19000 (goto-char beg)
19001 (while (< (point) end)
19002 (unless (eolp) (indent-line-to ind))
19003 (forward-line))))
19004 (goto-char beg)
19005 (forward-line lines)
19006 (indent-line-to ind)))
19007 (set-marker beg nil)
19008 (set-marker end nil)))
19011 ;;;; LaTeX fragments
19013 (defun org-inside-LaTeX-fragment-p ()
19014 "Test if point is inside a LaTeX fragment.
19015 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19016 sequence appearing also before point.
19017 Even though the matchers for math are configurable, this function assumes
19018 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19019 delimiters are skipped when they have been removed by customization.
19020 The return value is nil, or a cons cell with the delimiter and the
19021 position of this delimiter.
19023 This function does a reasonably good job, but can locally be fooled by
19024 for example currency specifications. For example it will assume being in
19025 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19026 fragments that are properly closed, but during editing, we have to live
19027 with the uncertainty caused by missing closing delimiters. This function
19028 looks only before point, not after."
19029 (catch 'exit
19030 (let ((pos (point))
19031 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19032 (lim (progn
19033 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19034 (point)))
19035 dd-on str (start 0) m re)
19036 (goto-char pos)
19037 (when dodollar
19038 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19039 re (nth 1 (assoc "$" org-latex-regexps)))
19040 (while (string-match re str start)
19041 (cond
19042 ((= (match-end 0) (length str))
19043 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19044 ((= (match-end 0) (- (length str) 5))
19045 (throw 'exit nil))
19046 (t (setq start (match-end 0))))))
19047 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19048 (goto-char pos)
19049 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19050 (and (match-beginning 2) (throw 'exit nil))
19051 ;; count $$
19052 (while (re-search-backward "\\$\\$" lim t)
19053 (setq dd-on (not dd-on)))
19054 (goto-char pos)
19055 (when dd-on (cons "$$" m))))))
19057 (defun org-inside-latex-macro-p ()
19058 "Is point inside a LaTeX macro or its arguments?"
19059 (save-match-data
19060 (org-in-regexp
19061 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19063 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19064 "Build an overlay between BEG and END using IMAGE file.
19065 Argument IMAGETYPE is the extension of the displayed image,
19066 as a string. It defaults to \"png\"."
19067 (let ((ov (make-overlay beg end))
19068 (imagetype (or (intern imagetype) 'png)))
19069 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19070 (overlay-put ov 'evaporate t)
19071 (overlay-put ov
19072 'modification-hooks
19073 (list (lambda (o _flag _beg _end &optional _l)
19074 (delete-overlay o))))
19075 (overlay-put ov
19076 'display
19077 (list 'image :type imagetype :file image :ascent 'center))))
19079 (defun org--list-latex-overlays (&optional beg end)
19080 "List all Org LaTeX overlays in current buffer.
19081 Limit to overlays between BEG and END when those are provided."
19082 (cl-remove-if-not
19083 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19084 (overlays-in (or beg (point-min)) (or end (point-max)))))
19086 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19087 "Remove all overlays with LaTeX fragment images in current buffer.
19088 When optional arguments BEG and END are non-nil, remove all
19089 overlays between them instead. Return a non-nil value when some
19090 overlays were removed, nil otherwise."
19091 (let ((overlays (org--list-latex-overlays beg end)))
19092 (mapc #'delete-overlay overlays)
19093 overlays))
19095 (define-obsolete-function-alias
19096 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
19097 (defun org-toggle-latex-fragment (&optional arg)
19098 "Preview the LaTeX fragment at point, or all locally or globally.
19100 If the cursor is on a LaTeX fragment, create the image and overlay
19101 it over the source code, if there is none. Remove it otherwise.
19102 If there is no fragment at point, display all fragments in the
19103 current section.
19105 With prefix ARG, preview or clear image for all fragments in the
19106 current subtree or in the whole buffer when used before the first
19107 headline. With a double prefix ARG \\[universal-argument] \
19108 \\[universal-argument] preview or clear images
19109 for all fragments in the buffer."
19110 (interactive "P")
19111 (when (display-graphic-p)
19112 (catch 'exit
19113 (save-excursion
19114 (let ((window-start (window-start)) msg)
19115 (save-restriction
19116 (cond
19117 ((or (equal arg '(16))
19118 (and (equal arg '(4))
19119 (org-with-limited-levels (org-before-first-heading-p))))
19120 (if (org-remove-latex-fragment-image-overlays)
19121 (progn (message "LaTeX fragments images removed from buffer")
19122 (throw 'exit nil))
19123 (setq msg "Creating images for buffer...")))
19124 ((equal arg '(4))
19125 (org-with-limited-levels (org-back-to-heading t))
19126 (let ((beg (point))
19127 (end (progn (org-end-of-subtree t) (point))))
19128 (if (org-remove-latex-fragment-image-overlays beg end)
19129 (progn
19130 (message "LaTeX fragment images removed from subtree")
19131 (throw 'exit nil))
19132 (setq msg "Creating images for subtree...")
19133 (narrow-to-region beg end))))
19134 ((let ((datum (org-element-context)))
19135 (when (memq (org-element-type datum)
19136 '(latex-environment latex-fragment))
19137 (let* ((beg (org-element-property :begin datum))
19138 (end (org-element-property :end datum)))
19139 (if (org-remove-latex-fragment-image-overlays beg end)
19140 (progn (message "LaTeX fragment image removed")
19141 (throw 'exit nil))
19142 (narrow-to-region beg end)
19143 (setq msg "Creating image..."))))))
19145 (org-with-limited-levels
19146 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19147 (outline-previous-heading)
19148 (point)))
19149 (end (progn (outline-next-heading) (point))))
19150 (if (org-remove-latex-fragment-image-overlays beg end)
19151 (progn
19152 (message "LaTeX fragment images removed from section")
19153 (throw 'exit nil))
19154 (setq msg "Creating images for section...")
19155 (narrow-to-region beg end))))))
19156 (let ((file (buffer-file-name (buffer-base-buffer))))
19157 (org-format-latex
19158 (concat org-preview-latex-image-directory "org-ltximg")
19159 ;; Emacs cannot overlay images from remote hosts.
19160 ;; Create it in `temporary-file-directory' instead.
19161 (if (or (not file) (file-remote-p file))
19162 temporary-file-directory
19163 default-directory)
19164 'overlays msg 'forbuffer org-preview-latex-default-process)))
19165 ;; Work around a bug that doesn't restore window's start
19166 ;; when widening back the buffer.
19167 (set-window-start nil window-start)
19168 (message (concat msg "done")))))))
19170 (defun org-format-latex
19171 (prefix &optional dir overlays msg forbuffer processing-type)
19172 "Replace LaTeX fragments with links to an image, and produce images.
19174 When optional argument OVERLAYS is non-nil, display the image on
19175 top of the fragment instead of replacing it.
19177 PROCESSING-TYPE is the conversion method to use, as a symbol.
19179 Some of the options can be changed using the variable
19180 `org-format-latex-options', which see."
19181 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19182 (unless (eq processing-type 'verbatim)
19183 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19184 (cnt 0)
19185 checkdir-flag)
19186 (goto-char (point-min))
19187 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19188 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19189 (overlay-recenter (point-max)))
19190 (while (re-search-forward math-regexp nil t)
19191 (unless (and overlays
19192 (eq (get-char-property (point) 'org-overlay-type)
19193 'org-latex-overlay))
19194 (let* ((context (org-element-context))
19195 (type (org-element-type context)))
19196 (when (memq type '(latex-environment latex-fragment))
19197 (let ((block-type (eq type 'latex-environment))
19198 (value (org-element-property :value context))
19199 (beg (org-element-property :begin context))
19200 (end (save-excursion
19201 (goto-char (org-element-property :end context))
19202 (skip-chars-backward " \r\t\n")
19203 (point))))
19204 (cond
19205 ((eq processing-type 'mathjax)
19206 ;; Prepare for MathJax processing.
19207 (if (not (string-match "\\`\\$\\$?" value))
19208 (goto-char end)
19209 (delete-region beg end)
19210 (if (string= (match-string 0 value) "$$")
19211 (insert "\\[" (substring value 2 -2) "\\]")
19212 (insert "\\(" (substring value 1 -1) "\\)"))))
19213 ((assq processing-type org-preview-latex-process-alist)
19214 ;; Process to an image.
19215 (cl-incf cnt)
19216 (goto-char beg)
19217 (let* ((processing-info
19218 (cdr (assq processing-type org-preview-latex-process-alist)))
19219 (face (face-at-point))
19220 ;; Get the colors from the face at point.
19222 (let ((color (plist-get org-format-latex-options
19223 :foreground)))
19224 (if (and forbuffer (eq color 'auto))
19225 (face-attribute face :foreground nil 'default)
19226 color)))
19228 (let ((color (plist-get org-format-latex-options
19229 :background)))
19230 (if (and forbuffer (eq color 'auto))
19231 (face-attribute face :background nil 'default)
19232 color)))
19233 (hash (sha1 (prin1-to-string
19234 (list org-format-latex-header
19235 org-latex-default-packages-alist
19236 org-latex-packages-alist
19237 org-format-latex-options
19238 forbuffer value fg bg))))
19239 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19240 (absprefix (expand-file-name prefix dir))
19241 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19242 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19243 (sep (and block-type "\n\n"))
19244 (link (concat sep "[[file:" linkfile "]]" sep))
19245 (options
19246 (org-combine-plists
19247 org-format-latex-options
19248 `(:foreground ,fg :background ,bg))))
19249 (when msg (message msg cnt))
19250 (unless checkdir-flag ; Ensure the directory exists.
19251 (setq checkdir-flag t)
19252 (let ((todir (file-name-directory absprefix)))
19253 (unless (file-directory-p todir)
19254 (make-directory todir t))))
19255 (unless (file-exists-p movefile)
19256 (org-create-formula-image
19257 value movefile options forbuffer processing-type))
19258 (if overlays
19259 (progn
19260 (dolist (o (overlays-in beg end))
19261 (when (eq (overlay-get o 'org-overlay-type)
19262 'org-latex-overlay)
19263 (delete-overlay o)))
19264 (org--format-latex-make-overlay beg end movefile imagetype)
19265 (goto-char end))
19266 (delete-region beg end)
19267 (insert
19268 (org-add-props link
19269 (list 'org-latex-src
19270 (replace-regexp-in-string "\"" "" value)
19271 'org-latex-src-embed-type
19272 (if block-type 'paragraph 'character)))))))
19273 ((eq processing-type 'mathml)
19274 ;; Process to MathML.
19275 (unless (org-format-latex-mathml-available-p)
19276 (user-error "LaTeX to MathML converter not configured"))
19277 (cl-incf cnt)
19278 (when msg (message msg cnt))
19279 (goto-char beg)
19280 (delete-region beg end)
19281 (insert (org-format-latex-as-mathml
19282 value block-type prefix dir)))
19284 (error "Unknown conversion process %s for LaTeX fragments"
19285 processing-type)))))))))))
19287 (defun org-create-math-formula (latex-frag &optional mathml-file)
19288 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19289 Use `org-latex-to-mathml-convert-command'. If the conversion is
19290 sucessful, return the portion between \"<math...> </math>\"
19291 elements otherwise return nil. When MATHML-FILE is specified,
19292 write the results in to that file. When invoked as an
19293 interactive command, prompt for LATEX-FRAG, with initial value
19294 set to the current active region and echo the results for user
19295 inspection."
19296 (interactive (list (let ((frag (when (org-region-active-p)
19297 (buffer-substring-no-properties
19298 (region-beginning) (region-end)))))
19299 (read-string "LaTeX Fragment: " frag nil frag))))
19300 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19301 (let* ((tmp-in-file
19302 (let ((file (file-relative-name
19303 (make-temp-name (expand-file-name "ltxmathml-in")))))
19304 (write-region latex-frag nil file)
19305 file))
19306 (tmp-out-file (file-relative-name
19307 (make-temp-name (expand-file-name "ltxmathml-out"))))
19308 (cmd (format-spec
19309 org-latex-to-mathml-convert-command
19310 `((?j . ,(and org-latex-to-mathml-jar-file
19311 (shell-quote-argument
19312 (expand-file-name
19313 org-latex-to-mathml-jar-file))))
19314 (?I . ,(shell-quote-argument tmp-in-file))
19315 (?i . ,latex-frag)
19316 (?o . ,(shell-quote-argument tmp-out-file)))))
19317 mathml shell-command-output)
19318 (when (org-called-interactively-p 'any)
19319 (unless (org-format-latex-mathml-available-p)
19320 (user-error "LaTeX to MathML converter not configured")))
19321 (message "Running %s" cmd)
19322 (setq shell-command-output (shell-command-to-string cmd))
19323 (setq mathml
19324 (when (file-readable-p tmp-out-file)
19325 (with-current-buffer (find-file-noselect tmp-out-file t)
19326 (goto-char (point-min))
19327 (when (re-search-forward
19328 (concat
19329 (regexp-quote
19330 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19331 "[^>]*?>"
19332 "\\(.\\|\n\\)*"
19333 "</math>")
19334 nil t)
19335 (prog1 (match-string 0) (kill-buffer))))))
19336 (cond
19337 (mathml
19338 (setq mathml
19339 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19340 (when mathml-file
19341 (write-region mathml nil mathml-file))
19342 (when (org-called-interactively-p 'any)
19343 (message mathml)))
19344 ((message "LaTeX to MathML conversion failed")
19345 (message shell-command-output)))
19346 (delete-file tmp-in-file)
19347 (when (file-exists-p tmp-out-file)
19348 (delete-file tmp-out-file))
19349 mathml))
19351 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19352 prefix &optional dir)
19353 "Use `org-create-math-formula' but check local cache first."
19354 (let* ((absprefix (expand-file-name prefix dir))
19355 (print-length nil) (print-level nil)
19356 (formula-id (concat
19357 "formula-"
19358 (sha1
19359 (prin1-to-string
19360 (list latex-frag
19361 org-latex-to-mathml-convert-command)))))
19362 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19363 (formula-cache-dir (file-name-directory formula-cache)))
19365 (unless (file-directory-p formula-cache-dir)
19366 (make-directory formula-cache-dir t))
19368 (unless (file-exists-p formula-cache)
19369 (org-create-math-formula latex-frag formula-cache))
19371 (if (file-exists-p formula-cache)
19372 ;; Successful conversion. Return the link to MathML file.
19373 (org-add-props
19374 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19375 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19376 'org-latex-src-embed-type (if latex-frag-type
19377 'paragraph 'character)))
19378 ;; Failed conversion. Return the LaTeX fragment verbatim
19379 latex-frag)))
19381 (declare-function org-export-get-backend "ox" (name))
19382 (declare-function org-export--get-global-options "ox" (&optional backend))
19383 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19384 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19385 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19386 (defun org-create-formula--latex-header ()
19387 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19388 (let ((info (org-combine-plists (org-export--get-global-options
19389 (org-export-get-backend 'latex))
19390 (org-export--get-inbuffer-options
19391 (org-export-get-backend 'latex)))))
19392 (org-latex-guess-babel-language
19393 (org-latex-guess-inputenc
19394 (org-splice-latex-header
19395 org-format-latex-header
19396 org-latex-default-packages-alist
19397 org-latex-packages-alist t
19398 (plist-get info :latex-header)))
19399 info)))
19401 (defun org--get-display-dpi ()
19402 "Get the DPI of the display.
19404 Assumes that the display has the same pixel width in the
19405 horizontal and vertical directions."
19406 (if (display-graphic-p)
19407 (round (/ (display-pixel-height)
19408 (/ (display-mm-height) 25.4)))
19409 (error "Attempt to calculate the dpi of a non-graphic display")))
19411 (defun org-create-formula-image
19412 (string tofile options buffer &optional processing-type)
19413 "Create an image from LaTeX source using external processes.
19415 The LaTeX STRING is saved to a temporary LaTeX file, then
19416 converted to an image file by process PROCESSING-TYPE defined in
19417 `org-preview-latex-process-alist'. A nil value defaults to
19418 `org-preview-latex-default-process'.
19420 The generated image file is eventually moved to TOFILE.
19422 The OPTIONS argument controls the size, foreground color and
19423 background color of the generated image.
19425 When BUFFER non-nil, this function is used for LaTeX previewing.
19426 Otherwise, it is used to deal with LaTeX snippets showed in
19427 a HTML file."
19428 (let* ((processing-type (or processing-type
19429 org-preview-latex-default-process))
19430 (processing-info
19431 (cdr (assq processing-type org-preview-latex-process-alist)))
19432 (programs (plist-get processing-info :programs))
19433 (error-message (or (plist-get processing-info :message) ""))
19434 (use-xcolor (plist-get processing-info :use-xcolor))
19435 (image-input-type (plist-get processing-info :image-input-type))
19436 (image-output-type (plist-get processing-info :image-output-type))
19437 (post-clean (or (plist-get processing-info :post-clean)
19438 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19439 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19440 (latex-header (or (plist-get processing-info :latex-header)
19441 (org-create-formula--latex-header)))
19442 (latex-compiler (plist-get processing-info :latex-compiler))
19443 (image-converter (plist-get processing-info :image-converter))
19444 (tmpdir temporary-file-directory)
19445 (texfilebase (make-temp-name
19446 (expand-file-name "orgtex" tmpdir)))
19447 (texfile (concat texfilebase ".tex"))
19448 (font-height (face-attribute 'default :height nil))
19449 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19450 '(1.0 . 1.0)))
19451 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19452 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19453 (dpi (* scale (floor (if buffer font-height 140.0))))
19454 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19455 "Black"))
19456 (bg (or (plist-get options (if buffer :background :html-background))
19457 "Transparent"))
19458 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19459 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19460 (dolist (program programs)
19461 (org-check-external-command program error-message))
19462 (if use-xcolor
19463 (progn (if (eq fg 'default)
19464 (setq fg (org-latex-color :foreground))
19465 (setq fg (org-latex-color-format fg)))
19466 (if (eq bg 'default)
19467 (setq bg (org-latex-color :background))
19468 (setq bg (org-latex-color-format
19469 (if (string= bg "Transparent") "white" bg))))
19470 (with-temp-file texfile
19471 (insert latex-header)
19472 (insert "\n\\begin{document}\n"
19473 "\\definecolor{fg}{rgb}{" fg "}\n"
19474 "\\definecolor{bg}{rgb}{" bg "}\n"
19475 "\n\\pagecolor{bg}\n"
19476 "\n{\\color{fg}\n"
19477 string
19478 "\n}\n"
19479 "\n\\end{document}\n")))
19480 (if (eq fg 'default)
19481 (setq fg (org-dvipng-color :foreground))
19482 (unless (string= fg "Transparent")
19483 (setq fg (org-dvipng-color-format fg))))
19484 (if (eq bg 'default)
19485 (setq bg (org-dvipng-color :background))
19486 (unless (string= bg "Transparent")
19487 (setq bg (org-dvipng-color-format bg))))
19488 (with-temp-file texfile
19489 (insert latex-header)
19490 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19492 (let* ((err-msg (format "Please adjust '%s' part of \
19493 `org-preview-latex-process-alist'."
19494 processing-type))
19495 (image-input-file
19496 (org-compile-file
19497 texfile latex-compiler image-input-type err-msg log-buf))
19498 (image-output-file
19499 (org-compile-file
19500 image-input-file image-converter image-output-type err-msg log-buf
19501 `((?F . ,(shell-quote-argument fg))
19502 (?B . ,(shell-quote-argument bg))
19503 (?D . ,(shell-quote-argument (format "%s" dpi)))
19504 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19505 (copy-file image-output-file tofile 'replace)
19506 (dolist (e post-clean)
19507 (when (file-exists-p (concat texfilebase e))
19508 (delete-file (concat texfilebase e))))
19509 image-output-file)))
19511 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19512 "Fill a LaTeX header template TPL.
19513 In the template, the following place holders will be recognized:
19515 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19516 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19517 [PACKAGES] \\usepackage statements for PKG
19518 [NO-PACKAGES] do not include PKG
19519 [EXTRA] the string EXTRA
19520 [NO-EXTRA] do not include EXTRA
19522 For backward compatibility, if both the positive and the negative place
19523 holder is missing, the positive one (without the \"NO-\") will be
19524 assumed to be present at the end of the template.
19525 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19526 EXTRA is a string.
19527 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19528 (let (rpl (end ""))
19529 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19530 (setq rpl (if (or (match-end 1) (not def-pkg))
19531 "" (org-latex-packages-to-string def-pkg snippets-p t))
19532 tpl (replace-match rpl t t tpl))
19533 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19535 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19536 (setq rpl (if (or (match-end 1) (not pkg))
19537 "" (org-latex-packages-to-string pkg snippets-p t))
19538 tpl (replace-match rpl t t tpl))
19539 (when pkg (setq end
19540 (concat end "\n"
19541 (org-latex-packages-to-string pkg snippets-p)))))
19543 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19544 (setq rpl (if (or (match-end 1) (not extra))
19545 "" (concat extra "\n"))
19546 tpl (replace-match rpl t t tpl))
19547 (when (and extra (string-match "\\S-" extra))
19548 (setq end (concat end "\n" extra))))
19550 (if (string-match "\\S-" end)
19551 (concat tpl "\n" end)
19552 tpl)))
19554 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19555 "Turn an alist of packages into a string with the \\usepackage macros."
19556 (setq pkg (mapconcat (lambda(p)
19557 (cond
19558 ((stringp p) p)
19559 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19560 (format "%% Package %s omitted" (cadr p)))
19561 ((equal "" (car p))
19562 (format "\\usepackage{%s}" (cadr p)))
19564 (format "\\usepackage[%s]{%s}"
19565 (car p) (cadr p)))))
19567 "\n"))
19568 (if newline (concat pkg "\n") pkg))
19570 (defun org-dvipng-color (attr)
19571 "Return a RGB color specification for dvipng."
19572 (apply #'format "rgb %s %s %s"
19573 (mapcar #'org-normalize-color
19574 (color-values (face-attribute 'default attr nil)))))
19576 (defun org-dvipng-color-format (color-name)
19577 "Convert COLOR-NAME to a RGB color value for dvipng."
19578 (apply 'format "rgb %s %s %s"
19579 (mapcar 'org-normalize-color
19580 (color-values color-name))))
19582 (defun org-latex-color (attr)
19583 "Return a RGB color for the LaTeX color package."
19584 (apply #'format "%s,%s,%s"
19585 (mapcar #'org-normalize-color
19586 (color-values (face-attribute 'default attr nil)))))
19588 (defun org-latex-color-format (color-name)
19589 "Convert COLOR-NAME to a RGB color value."
19590 (apply 'format "%s,%s,%s"
19591 (mapcar 'org-normalize-color
19592 (color-values color-name))))
19594 (defun org-normalize-color (value)
19595 "Return string to be used as color value for an RGB component."
19596 (format "%g" (/ value 65535.0)))
19600 ;; Image display
19602 (defvar-local org-inline-image-overlays nil)
19604 (defun org-toggle-inline-images (&optional include-linked)
19605 "Toggle the display of inline images.
19606 INCLUDE-LINKED is passed to `org-display-inline-images'."
19607 (interactive "P")
19608 (if org-inline-image-overlays
19609 (progn
19610 (org-remove-inline-images)
19611 (when (org-called-interactively-p 'interactive)
19612 (message "Inline image display turned off")))
19613 (org-display-inline-images include-linked)
19614 (when (org-called-interactively-p 'interactive)
19615 (message (if org-inline-image-overlays
19616 (format "%d images displayed inline"
19617 (length org-inline-image-overlays))
19618 "No images to display inline")))))
19620 (defun org-redisplay-inline-images ()
19621 "Refresh the display of inline images."
19622 (interactive)
19623 (if (not org-inline-image-overlays)
19624 (org-toggle-inline-images)
19625 (org-toggle-inline-images)
19626 (org-toggle-inline-images)))
19628 (defun org-display-inline-images (&optional include-linked refresh beg end)
19629 "Display inline images.
19631 An inline image is a link which follows either of these
19632 conventions:
19634 1. Its path is a file with an extension matching return value
19635 from `image-file-name-regexp' and it has no contents.
19637 2. Its description consists in a single link of the previous
19638 type.
19640 When optional argument INCLUDE-LINKED is non-nil, also links with
19641 a text description part will be inlined. This can be nice for
19642 a quick look at those images, but it does not reflect what
19643 exported files will look like.
19645 When optional argument REFRESH is non-nil, refresh existing
19646 images between BEG and END. This will create new image displays
19647 only if necessary. BEG and END default to the buffer
19648 boundaries."
19649 (interactive "P")
19650 (when (display-graphic-p)
19651 (unless refresh
19652 (org-remove-inline-images)
19653 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19654 (org-with-wide-buffer
19655 (goto-char (or beg (point-min)))
19656 (let ((case-fold-search t)
19657 (file-extension-re (image-file-name-regexp)))
19658 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19659 (let ((link (save-match-data (org-element-context))))
19660 ;; Check if we're at an inline image.
19661 (when (and (equal (org-element-property :type link) "file")
19662 (or include-linked
19663 (not (org-element-property :contents-begin link)))
19664 (let ((parent (org-element-property :parent link)))
19665 (or (not (eq (org-element-type parent) 'link))
19666 (not (cdr (org-element-contents parent)))))
19667 (org-string-match-p file-extension-re
19668 (org-element-property :path link)))
19669 (let ((file (expand-file-name
19670 (org-link-unescape
19671 (org-element-property :path link)))))
19672 (when (file-exists-p file)
19673 (let ((width
19674 ;; Apply `org-image-actual-width' specifications.
19675 (cond
19676 ((not (image-type-available-p 'imagemagick)) nil)
19677 ((eq org-image-actual-width t) nil)
19678 ((listp org-image-actual-width)
19680 ;; First try to find a width among
19681 ;; attributes associated to the paragraph
19682 ;; containing link.
19683 (let ((paragraph
19684 (let ((e link))
19685 (while (and (setq e (org-element-property
19686 :parent e))
19687 (not (eq (org-element-type e)
19688 'paragraph))))
19689 e)))
19690 (when paragraph
19691 (save-excursion
19692 (goto-char (org-element-property :begin paragraph))
19693 (when
19694 (re-search-forward
19695 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19696 (org-element-property
19697 :post-affiliated paragraph)
19699 (string-to-number (match-string 1))))))
19700 ;; Otherwise, fall-back to provided number.
19701 (car org-image-actual-width)))
19702 ((numberp org-image-actual-width)
19703 org-image-actual-width)))
19704 (old (get-char-property-and-overlay
19705 (org-element-property :begin link)
19706 'org-image-overlay)))
19707 (if (and (car-safe old) refresh)
19708 (image-refresh (overlay-get (cdr old) 'display))
19709 (let ((image (create-image file
19710 (and width 'imagemagick)
19712 :width width)))
19713 (when image
19714 (let* ((link
19715 ;; If inline image is the description
19716 ;; of another link, be sure to
19717 ;; consider the latter as the one to
19718 ;; apply the overlay on.
19719 (let ((parent
19720 (org-element-property :parent link)))
19721 (if (eq (org-element-type parent) 'link)
19722 parent
19723 link)))
19724 (ov (make-overlay
19725 (org-element-property :begin link)
19726 (progn
19727 (goto-char
19728 (org-element-property :end link))
19729 (skip-chars-backward " \t")
19730 (point)))))
19731 (overlay-put ov 'display image)
19732 (overlay-put ov 'face 'default)
19733 (overlay-put ov 'org-image-overlay t)
19734 (overlay-put
19735 ov 'modification-hooks
19736 (list 'org-display-inline-remove-overlay))
19737 (push ov org-inline-image-overlays)))))))))))))))
19739 (define-obsolete-function-alias
19740 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19742 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19743 "Remove inline-display overlay if a corresponding region is modified."
19744 (let ((inhibit-modification-hooks t))
19745 (when (and ov after)
19746 (delete ov org-inline-image-overlays)
19747 (delete-overlay ov))))
19749 (defun org-remove-inline-images ()
19750 "Remove inline display of images."
19751 (interactive)
19752 (mapc #'delete-overlay org-inline-image-overlays)
19753 (setq org-inline-image-overlays nil))
19755 ;;;; Key bindings
19757 ;; Outline functions from `outline-mode-prefix-map'
19758 ;; that can be remapped in Org:
19759 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19760 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19761 (define-key org-mode-map [remap outline-forward-same-level]
19762 'org-forward-heading-same-level)
19763 (define-key org-mode-map [remap outline-backward-same-level]
19764 'org-backward-heading-same-level)
19765 (define-key org-mode-map [remap outline-show-branches]
19766 'org-kill-note-or-show-branches)
19767 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19768 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19769 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19770 (define-key org-mode-map [remap outline-next-visible-heading]
19771 'org-next-visible-heading)
19772 (define-key org-mode-map [remap outline-previous-visible-heading]
19773 'org-previous-visible-heading)
19774 (define-key org-mode-map [remap show-children] 'org-show-children)
19776 ;; Outline functions from `outline-mode-prefix-map' that can not
19777 ;; be remapped in Org:
19779 ;; - the column "key binding" shows whether the Outline function is still
19780 ;; available in Org mode on the same key that it has been bound to in
19781 ;; Outline mode:
19782 ;; - "overridden": key used for a different functionality in Org mode
19783 ;; - else: key still bound to the same Outline function in Org mode
19785 ;; | Outline function | key binding | Org replacement |
19786 ;; |------------------------------------+-------------+--------------------------|
19787 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19788 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19789 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19790 ;; | `show-entry' | overridden | no replacement |
19791 ;; | `show-branches' | `C-c C-k' | still same function |
19792 ;; | `show-subtree' | overridden | visibility cycling |
19793 ;; | `show-all' | overridden | no replacement |
19794 ;; | `hide-subtree' | overridden | visibility cycling |
19795 ;; | `hide-body' | overridden | no replacement |
19796 ;; | `hide-entry' | overridden | visibility cycling |
19797 ;; | `hide-leaves' | overridden | no replacement |
19798 ;; | `hide-sublevels' | overridden | no replacement |
19799 ;; | `hide-other' | overridden | no replacement |
19801 ;; Make `C-c C-x' a prefix key
19802 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19804 ;; TAB key with modifiers
19805 (org-defkey org-mode-map "\C-i" 'org-cycle)
19806 (org-defkey org-mode-map [(tab)] 'org-cycle)
19807 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19808 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19809 ;; The following line is necessary under Suse GNU/Linux
19810 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19811 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19812 (define-key org-mode-map [backtab] 'org-shifttab)
19814 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19815 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19816 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19818 ;; Cursor keys with modifiers
19819 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19820 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19821 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19822 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19824 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19825 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19826 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19827 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19828 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19829 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19831 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19832 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19833 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19834 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19836 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19837 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19838 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19839 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19841 ;; Babel keys
19842 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19843 (dolist (pair org-babel-key-bindings)
19844 (define-key org-babel-map (car pair) (cdr pair)))
19846 ;;; Extra keys for tty access.
19847 ;; We only set them when really needed because otherwise the
19848 ;; menus don't show the simple keys
19850 (when (or org-use-extra-keys (not window-system))
19851 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19852 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19853 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19854 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19855 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19856 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19857 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19858 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19859 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19860 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19861 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19862 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19863 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19864 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19865 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19866 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19867 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19868 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19869 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19870 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19871 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19872 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19873 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19874 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19875 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19876 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19877 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19878 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19880 ;; All the other keys
19882 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19883 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19884 (if (boundp 'narrow-map)
19885 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19886 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19887 (if (boundp 'narrow-map)
19888 (org-defkey narrow-map "b" 'org-narrow-to-block)
19889 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19890 (if (boundp 'narrow-map)
19891 (org-defkey narrow-map "e" 'org-narrow-to-element)
19892 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19893 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19894 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19895 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19896 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19897 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19898 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19899 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19900 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19901 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19902 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19903 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19904 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19905 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19906 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19907 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19908 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19909 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19910 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19911 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19912 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19913 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19914 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19915 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19916 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19917 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19918 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19919 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19920 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19921 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19922 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19923 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19924 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19925 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19926 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19927 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19928 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19929 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19930 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19931 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19932 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19933 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19934 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19935 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19936 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19937 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19938 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19939 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19940 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19941 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19942 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19943 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19944 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19945 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19946 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19947 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19948 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19949 (org-defkey org-mode-map "\C-c^" 'org-sort)
19950 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19951 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19952 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19953 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19954 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19955 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19956 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19957 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19958 (org-defkey org-mode-map "\C-m" 'org-return)
19959 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19960 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19961 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19962 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19963 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19964 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19965 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19966 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19967 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19968 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19969 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19970 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19971 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19972 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19973 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19974 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19975 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19976 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19977 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19978 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19979 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19980 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19981 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19982 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19983 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19985 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19986 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19987 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19989 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19990 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19991 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19992 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19993 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19994 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19995 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19996 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19997 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19998 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19999 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
20000 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
20001 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
20002 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
20003 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
20004 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20005 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20006 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20007 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20008 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20009 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20010 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20012 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20013 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20014 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20015 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20016 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20018 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20020 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20022 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20023 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20025 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20028 (defconst org-speed-commands-default
20030 ("Outline Navigation")
20031 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20032 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20033 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20034 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20035 ("F" . org-next-block)
20036 ("B" . org-previous-block)
20037 ("u" . (org-speed-move-safe 'outline-up-heading))
20038 ("j" . org-goto)
20039 ("g" . (org-refile t))
20040 ("Outline Visibility")
20041 ("c" . org-cycle)
20042 ("C" . org-shifttab)
20043 (" " . org-display-outline-path)
20044 ("s" . org-narrow-to-subtree)
20045 ("=" . org-columns)
20046 ("Outline Structure Editing")
20047 ("U" . org-metaup)
20048 ("D" . org-metadown)
20049 ("r" . org-metaright)
20050 ("l" . org-metaleft)
20051 ("R" . org-shiftmetaright)
20052 ("L" . org-shiftmetaleft)
20053 ("i" . (progn (forward-char 1) (call-interactively
20054 'org-insert-heading-respect-content)))
20055 ("^" . org-sort)
20056 ("w" . org-refile)
20057 ("a" . org-archive-subtree-default-with-confirmation)
20058 ("@" . org-mark-subtree)
20059 ("#" . org-toggle-comment)
20060 ("Clock Commands")
20061 ("I" . org-clock-in)
20062 ("O" . org-clock-out)
20063 ("Meta Data Editing")
20064 ("t" . org-todo)
20065 ("," . (org-priority))
20066 ("0" . (org-priority ?\ ))
20067 ("1" . (org-priority ?A))
20068 ("2" . (org-priority ?B))
20069 ("3" . (org-priority ?C))
20070 (":" . org-set-tags-command)
20071 ("e" . org-set-effort)
20072 ("E" . org-inc-effort)
20073 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20074 (org-entry-put (point) "APPT_WARNTIME" m)))
20075 ("Agenda Views etc")
20076 ("v" . org-agenda)
20077 ("/" . org-sparse-tree)
20078 ("Misc")
20079 ("o" . org-open-at-point)
20080 ("?" . org-speed-command-help)
20081 ("<" . (org-agenda-set-restriction-lock 'subtree))
20082 (">" . (org-agenda-remove-restriction-lock))
20084 "The default speed commands.")
20086 (defun org-print-speed-command (e)
20087 (if (> (length (car e)) 1)
20088 (progn
20089 (princ "\n")
20090 (princ (car e))
20091 (princ "\n")
20092 (princ (make-string (length (car e)) ?-))
20093 (princ "\n"))
20094 (princ (car e))
20095 (princ " ")
20096 (if (symbolp (cdr e))
20097 (princ (symbol-name (cdr e)))
20098 (prin1 (cdr e)))
20099 (princ "\n")))
20101 (defun org-speed-command-help ()
20102 "Show the available speed commands."
20103 (interactive)
20104 (if (not org-use-speed-commands)
20105 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20106 (with-output-to-temp-buffer "*Help*"
20107 (princ "User-defined Speed commands\n===========================\n")
20108 (mapc #'org-print-speed-command org-speed-commands-user)
20109 (princ "\n")
20110 (princ "Built-in Speed commands\n=======================\n")
20111 (mapc #'org-print-speed-command org-speed-commands-default))
20112 (with-current-buffer "*Help*"
20113 (setq truncate-lines t))))
20115 (defun org-speed-move-safe (cmd)
20116 "Execute CMD, but make sure that the cursor always ends up in a headline.
20117 If not, return to the original position and throw an error."
20118 (interactive)
20119 (let ((pos (point)))
20120 (call-interactively cmd)
20121 (unless (and (bolp) (org-at-heading-p))
20122 (goto-char pos)
20123 (error "Boundary reached while executing %s" cmd))))
20125 (defvar org-self-insert-command-undo-counter 0)
20127 (defvar org-table-auto-blank-field) ; defined in org-table.el
20128 (defvar org-speed-command nil)
20130 (define-obsolete-function-alias
20131 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20133 (defun org-speed-command-activate (keys)
20134 "Hook for activating single-letter speed commands.
20135 `org-speed-commands-default' specifies a minimal command set.
20136 Use `org-speed-commands-user' for further customization."
20137 (when (or (and (bolp) (looking-at org-outline-regexp))
20138 (and (functionp org-use-speed-commands)
20139 (funcall org-use-speed-commands)))
20140 (cdr (assoc keys (append org-speed-commands-user
20141 org-speed-commands-default)))))
20143 (define-obsolete-function-alias
20144 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20146 (defun org-babel-speed-command-activate (keys)
20147 "Hook for activating single-letter code block commands."
20148 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20149 (cdr (assoc keys org-babel-key-bindings))))
20151 (defcustom org-speed-command-hook
20152 '(org-speed-command-default-hook org-babel-speed-command-hook)
20153 "Hook for activating speed commands at strategic locations.
20154 Hook functions are called in sequence until a valid handler is
20155 found.
20157 Each hook takes a single argument, a user-pressed command key
20158 which is also a `self-insert-command' from the global map.
20160 Within the hook, examine the cursor position and the command key
20161 and return nil or a valid handler as appropriate. Handler could
20162 be one of an interactive command, a function, or a form.
20164 Set `org-use-speed-commands' to non-nil value to enable this
20165 hook. The default setting is `org-speed-command-activate'."
20166 :group 'org-structure
20167 :version "24.1"
20168 :type 'hook)
20170 (defun org-self-insert-command (N)
20171 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20172 If the cursor is in a table looking at whitespace, the whitespace is
20173 overwritten, and the table is not marked as requiring realignment."
20174 (interactive "p")
20175 (org-check-before-invisible-edit 'insert)
20176 (cond
20177 ((and org-use-speed-commands
20178 (let ((kv (this-command-keys-vector)))
20179 (setq org-speed-command
20180 (run-hook-with-args-until-success
20181 'org-speed-command-hook
20182 (make-string 1 (aref kv (1- (length kv))))))))
20183 (cond
20184 ((commandp org-speed-command)
20185 (setq this-command org-speed-command)
20186 (call-interactively org-speed-command))
20187 ((functionp org-speed-command)
20188 (funcall org-speed-command))
20189 ((and org-speed-command (listp org-speed-command))
20190 (eval org-speed-command))
20191 (t (let (org-use-speed-commands)
20192 (call-interactively 'org-self-insert-command)))))
20193 ((and
20194 (org-at-table-p)
20195 (progn
20196 ;; Check if we blank the field, and if that triggers align.
20197 (and (featurep 'org-table) org-table-auto-blank-field
20198 (memq last-command
20199 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20200 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20201 ;; Got extra space, this field does not determine
20202 ;; column width.
20203 (let (org-table-may-need-update) (org-table-blank-field))
20204 ;; No extra space, this field may determine column
20205 ;; width.
20206 (org-table-blank-field)))
20208 (eq N 1)
20209 (looking-at "[^|\n]* \\( \\)|"))
20210 ;; There is room for insertion without re-aligning the table.
20211 (delete-region (match-beginning 1) (match-end 1))
20212 (self-insert-command N))
20214 (setq org-table-may-need-update t)
20215 (self-insert-command N)
20216 (org-fix-tags-on-the-fly)
20217 (when org-self-insert-cluster-for-undo
20218 (if (not (eq last-command 'org-self-insert-command))
20219 (setq org-self-insert-command-undo-counter 1)
20220 (if (>= org-self-insert-command-undo-counter 20)
20221 (setq org-self-insert-command-undo-counter 1)
20222 (and (> org-self-insert-command-undo-counter 0)
20223 buffer-undo-list (listp buffer-undo-list)
20224 (not (cadr buffer-undo-list)) ; remove nil entry
20225 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20226 (setq org-self-insert-command-undo-counter
20227 (1+ org-self-insert-command-undo-counter))))))))
20229 (defun org-check-before-invisible-edit (kind)
20230 "Check is editing if kind KIND would be dangerous with invisible text around.
20231 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20232 ;; First, try to get out of here as quickly as possible, to reduce overhead
20233 (when (and org-catch-invisible-edits
20234 (or (not (boundp 'visible-mode)) (not visible-mode))
20235 (or (get-char-property (point) 'invisible)
20236 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20237 ;; OK, we need to take a closer look
20238 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20239 (invisible-before-point (unless (bobp) (get-char-property
20240 (1- (point)) 'invisible)))
20241 (border-and-ok-direction
20243 ;; Check if we are acting predictably before invisible text
20244 (and invisible-at-point (not invisible-before-point)
20245 (memq kind '(insert delete-backward)))
20246 ;; Check if we are acting predictably after invisible text
20247 ;; This works not well, and I have turned it off. It seems
20248 ;; better to always show and stop after invisible text.
20249 ;; (and (not invisible-at-point) invisible-before-point
20250 ;; (memq kind '(insert delete)))
20252 (when (or (memq invisible-at-point '(outline org-hide-block t))
20253 (memq invisible-before-point '(outline org-hide-block t)))
20254 (when (eq org-catch-invisible-edits 'error)
20255 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20256 (if (and org-custom-properties-overlays
20257 (y-or-n-p "Display invisible properties in this buffer? "))
20258 (org-toggle-custom-properties-visibility)
20259 ;; Make the area visible
20260 (save-excursion
20261 (when invisible-before-point
20262 (goto-char (previous-single-char-property-change
20263 (point) 'invisible)))
20264 (outline-show-subtree))
20265 (cond
20266 ((eq org-catch-invisible-edits 'show)
20267 ;; That's it, we do the edit after showing
20268 (message
20269 "Unfolding invisible region around point before editing")
20270 (sit-for 1))
20271 ((and (eq org-catch-invisible-edits 'smart)
20272 border-and-ok-direction)
20273 (message "Unfolding invisible region around point before editing"))
20275 ;; Don't do the edit, make the user repeat it in full visibility
20276 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20278 (defun org-fix-tags-on-the-fly ()
20279 (when (and (equal (char-after (point-at-bol)) ?*)
20280 (org-at-heading-p))
20281 (org-align-tags-here org-tags-column)))
20283 (defun org-delete-backward-char (N)
20284 "Like `delete-backward-char', insert whitespace at field end in tables.
20285 When deleting backwards, in tables this function will insert whitespace in
20286 front of the next \"|\" separator, to keep the table aligned. The table will
20287 still be marked for re-alignment if the field did fill the entire column,
20288 because, in this case the deletion might narrow the column."
20289 (interactive "p")
20290 (save-match-data
20291 (org-check-before-invisible-edit 'delete-backward)
20292 (if (and (org-at-table-p)
20293 (eq N 1)
20294 (string-match "|" (buffer-substring (point-at-bol) (point)))
20295 (looking-at ".*?|"))
20296 (let ((pos (point))
20297 (noalign (looking-at "[^|\n\r]* |"))
20298 (c org-table-may-need-update))
20299 (backward-delete-char N)
20300 (unless overwrite-mode
20301 (skip-chars-forward "^|")
20302 (insert " ")
20303 (goto-char (1- pos)))
20304 ;; noalign: if there were two spaces at the end, this field
20305 ;; does not determine the width of the column.
20306 (when noalign (setq org-table-may-need-update c)))
20307 (backward-delete-char N)
20308 (org-fix-tags-on-the-fly))))
20310 (defun org-delete-char (N)
20311 "Like `delete-char', but insert whitespace at field end in tables.
20312 When deleting characters, in tables this function will insert whitespace in
20313 front of the next \"|\" separator, to keep the table aligned. The table will
20314 still be marked for re-alignment if the field did fill the entire column,
20315 because, in this case the deletion might narrow the column."
20316 (interactive "p")
20317 (save-match-data
20318 (org-check-before-invisible-edit 'delete)
20319 (if (and (org-at-table-p)
20320 (not (bolp))
20321 (not (= (char-after) ?|))
20322 (eq N 1))
20323 (if (looking-at ".*?|")
20324 (let ((pos (point))
20325 (noalign (looking-at "[^|\n\r]* |"))
20326 (c org-table-may-need-update))
20327 (replace-match
20328 (concat (substring (match-string 0) 1 -1) " |") nil t)
20329 (goto-char pos)
20330 ;; noalign: if there were two spaces at the end, this field
20331 ;; does not determine the width of the column.
20332 (when noalign (setq org-table-may-need-update c)))
20333 (delete-char N))
20334 (delete-char N)
20335 (org-fix-tags-on-the-fly))))
20337 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20338 (put 'org-self-insert-command 'delete-selection
20339 (lambda ()
20340 (not (run-hook-with-args-until-success
20341 'self-insert-uses-region-functions))))
20342 (put 'orgtbl-self-insert-command 'delete-selection
20343 (lambda ()
20344 (not (run-hook-with-args-until-success
20345 'self-insert-uses-region-functions))))
20346 (put 'org-delete-char 'delete-selection 'supersede)
20347 (put 'org-delete-backward-char 'delete-selection 'supersede)
20348 (put 'org-yank 'delete-selection 'yank)
20350 ;; Make `flyspell-mode' delay after some commands
20351 (put 'org-self-insert-command 'flyspell-delayed t)
20352 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20353 (put 'org-delete-char 'flyspell-delayed t)
20354 (put 'org-delete-backward-char 'flyspell-delayed t)
20356 ;; Make pabbrev-mode expand after org-mode commands
20357 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20358 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20360 (defun org-remap (map &rest commands)
20361 "In MAP, remap the functions given in COMMANDS.
20362 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20363 (let (new old)
20364 (while commands
20365 (setq old (pop commands) new (pop commands))
20366 (if (fboundp 'command-remapping)
20367 (org-defkey map (vector 'remap old) new)
20368 (substitute-key-definition old new map global-map)))))
20370 (defun org-transpose-words ()
20371 "Transpose words for Org.
20372 This uses the `org-mode-transpose-word-syntax-table' syntax
20373 table, which interprets characters in `org-emphasis-alist' as
20374 word constituents."
20375 (interactive)
20376 (with-syntax-table org-mode-transpose-word-syntax-table
20377 (call-interactively 'transpose-words)))
20378 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20380 (when (eq org-enable-table-editor 'optimized)
20381 ;; If the user wants maximum table support, we need to hijack
20382 ;; some standard editing functions
20383 (org-remap org-mode-map
20384 'self-insert-command 'org-self-insert-command
20385 'delete-char 'org-delete-char
20386 'delete-backward-char 'org-delete-backward-char)
20387 (org-defkey org-mode-map "|" 'org-force-self-insert))
20389 (defvar org-ctrl-c-ctrl-c-hook nil
20390 "Hook for functions attaching themselves to `C-c C-c'.
20392 This can be used to add additional functionality to the C-c C-c
20393 key which executes context-dependent commands. This hook is run
20394 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20395 run after the last test.
20397 Each function will be called with no arguments. The function
20398 must check if the context is appropriate for it to act. If yes,
20399 it should do its thing and then return a non-nil value. If the
20400 context is wrong, just do nothing and return nil.")
20402 (defvar org-ctrl-c-ctrl-c-final-hook nil
20403 "Hook for functions attaching themselves to `C-c C-c'.
20405 This can be used to add additional functionality to the C-c C-c
20406 key which executes context-dependent commands. This hook is run
20407 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20408 before the first test.
20410 Each function will be called with no arguments. The function
20411 must check if the context is appropriate for it to act. If yes,
20412 it should do its thing and then return a non-nil value. If the
20413 context is wrong, just do nothing and return nil.")
20415 (defvar org-tab-first-hook nil
20416 "Hook for functions to attach themselves to TAB.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.
20418 This hook runs as the first action when TAB is pressed, even before
20419 `org-cycle' messes around with the `outline-regexp' to cater for
20420 inline tasks and plain list item folding.
20421 If any function in this hook returns t, any other actions that
20422 would have been caused by TAB (such as table field motion or visibility
20423 cycling) will not occur.")
20425 (defvar org-tab-after-check-for-table-hook nil
20426 "Hook for functions to attach themselves to TAB.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.
20428 This hook runs after it has been established that the cursor is not in a
20429 table, but before checking if the cursor is in a headline or if global cycling
20430 should be done.
20431 If any function in this hook returns t, not other actions like visibility
20432 cycling will be done.")
20434 (defvar org-tab-after-check-for-cycling-hook nil
20435 "Hook for functions to attach themselves to TAB.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.
20437 This hook runs after it has been established that not table field motion and
20438 not visibility should be done because of current context. This is probably
20439 the place where a package like yasnippets can hook in.")
20441 (defvar org-tab-before-tab-emulation-hook nil
20442 "Hook for functions to attach themselves to TAB.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.
20444 This hook runs after every other options for TAB have been exhausted, but
20445 before indentation and \t insertion takes place.")
20447 (defvar org-metaleft-hook nil
20448 "Hook for functions attaching themselves to `M-left'.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-metaright-hook nil
20451 "Hook for functions attaching themselves to `M-right'.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-metaup-hook nil
20454 "Hook for functions attaching themselves to `M-up'.
20455 See `org-ctrl-c-ctrl-c-hook' for more information.")
20456 (defvar org-metadown-hook nil
20457 "Hook for functions attaching themselves to `M-down'.
20458 See `org-ctrl-c-ctrl-c-hook' for more information.")
20459 (defvar org-shiftmetaleft-hook nil
20460 "Hook for functions attaching themselves to `M-S-left'.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.")
20462 (defvar org-shiftmetaright-hook nil
20463 "Hook for functions attaching themselves to `M-S-right'.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-shiftmetaup-hook nil
20466 "Hook for functions attaching themselves to `M-S-up'.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-shiftmetadown-hook nil
20469 "Hook for functions attaching themselves to `M-S-down'.
20470 See `org-ctrl-c-ctrl-c-hook' for more information.")
20471 (defvar org-metareturn-hook nil
20472 "Hook for functions attaching themselves to `M-RET'.
20473 See `org-ctrl-c-ctrl-c-hook' for more information.")
20474 (defvar org-shiftup-hook nil
20475 "Hook for functions attaching themselves to `S-up'.
20476 See `org-ctrl-c-ctrl-c-hook' for more information.")
20477 (defvar org-shiftup-final-hook nil
20478 "Hook for functions attaching themselves to `S-up'.
20479 This one runs after all other options except shift-select have been excluded.
20480 See `org-ctrl-c-ctrl-c-hook' for more information.")
20481 (defvar org-shiftdown-hook nil
20482 "Hook for functions attaching themselves to `S-down'.
20483 See `org-ctrl-c-ctrl-c-hook' for more information.")
20484 (defvar org-shiftdown-final-hook nil
20485 "Hook for functions attaching themselves to `S-down'.
20486 This one runs after all other options except shift-select have been excluded.
20487 See `org-ctrl-c-ctrl-c-hook' for more information.")
20488 (defvar org-shiftleft-hook nil
20489 "Hook for functions attaching themselves to `S-left'.
20490 See `org-ctrl-c-ctrl-c-hook' for more information.")
20491 (defvar org-shiftleft-final-hook nil
20492 "Hook for functions attaching themselves to `S-left'.
20493 This one runs after all other options except shift-select have been excluded.
20494 See `org-ctrl-c-ctrl-c-hook' for more information.")
20495 (defvar org-shiftright-hook nil
20496 "Hook for functions attaching themselves to `S-right'.
20497 See `org-ctrl-c-ctrl-c-hook' for more information.")
20498 (defvar org-shiftright-final-hook nil
20499 "Hook for functions attaching themselves to `S-right'.
20500 This one runs after all other options except shift-select have been excluded.
20501 See `org-ctrl-c-ctrl-c-hook' for more information.")
20503 (defun org-modifier-cursor-error ()
20504 "Throw an error, a modified cursor command was applied in wrong context."
20505 (user-error "This command is active in special context like tables, headlines or items"))
20507 (defun org-shiftselect-error ()
20508 "Throw an error because Shift-Cursor command was applied in wrong context."
20509 (if (and (boundp 'shift-select-mode) shift-select-mode)
20510 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20511 (user-error "This command works only in special context like headlines or timestamps")))
20513 (defun org-call-for-shift-select (cmd)
20514 (let ((this-command-keys-shift-translated t))
20515 (call-interactively cmd)))
20517 (defun org-shifttab (&optional arg)
20518 "Global visibility cycling or move to previous table field.
20519 Call `org-table-previous-field' within a table.
20520 When ARG is nil, cycle globally through visibility states.
20521 When ARG is a numeric prefix, show contents of this level."
20522 (interactive "P")
20523 (cond
20524 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20525 ((integerp arg)
20526 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20527 (message "Content view to level: %d" arg)
20528 (org-content (prefix-numeric-value arg2))
20529 (org-cycle-show-empty-lines t)
20530 (setq org-cycle-global-status 'overview)))
20531 (t (call-interactively 'org-global-cycle))))
20533 (defun org-shiftmetaleft ()
20534 "Promote subtree or delete table column.
20535 Calls `org-promote-subtree', `org-outdent-item-tree', or
20536 `org-table-delete-column', depending on context. See the
20537 individual commands for more information."
20538 (interactive)
20539 (cond
20540 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20541 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20542 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20543 ((if (not (org-region-active-p)) (org-at-item-p)
20544 (save-excursion (goto-char (region-beginning))
20545 (org-at-item-p)))
20546 (call-interactively 'org-outdent-item-tree))
20547 (t (org-modifier-cursor-error))))
20549 (defun org-shiftmetaright ()
20550 "Demote subtree or insert table column.
20551 Calls `org-demote-subtree', `org-indent-item-tree', or
20552 `org-table-insert-column', depending on context. See the
20553 individual commands for more information."
20554 (interactive)
20555 (cond
20556 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20557 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20558 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20559 ((if (not (org-region-active-p)) (org-at-item-p)
20560 (save-excursion (goto-char (region-beginning))
20561 (org-at-item-p)))
20562 (call-interactively 'org-indent-item-tree))
20563 (t (org-modifier-cursor-error))))
20565 (defun org-shiftmetaup (&optional _arg)
20566 "Drag the line at point up.
20567 In a table, kill the current row.
20568 On a clock timestamp, update the value of the timestamp like `S-<up>'
20569 but also adjust the previous clocked item in the clock history.
20570 Everywhere else, drag the line at point up."
20571 (interactive "P")
20572 (cond
20573 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20574 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20575 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20576 (call-interactively 'org-timestamp-up)))
20577 (t (call-interactively 'org-drag-line-backward))))
20579 (defun org-shiftmetadown (&optional _arg)
20580 "Drag the line at point down.
20581 In a table, insert an empty row at the current line.
20582 On a clock timestamp, update the value of the timestamp like `S-<down>'
20583 but also adjust the previous clocked item in the clock history.
20584 Everywhere else, drag the line at point down."
20585 (interactive "P")
20586 (cond
20587 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20588 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20589 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20590 (call-interactively 'org-timestamp-down)))
20591 (t (call-interactively 'org-drag-line-forward))))
20593 (defsubst org-hidden-tree-error ()
20594 (user-error
20595 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20597 (defun org-metaleft (&optional _arg)
20598 "Promote heading, list item at point or move table column left.
20600 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20601 depending on context. With no specific context, calls the Emacs
20602 default `backward-word'. See the individual commands for more
20603 information.
20605 This function runs the hook `org-metaleft-hook' as a first step,
20606 and returns at first non-nil value."
20607 (interactive "P")
20608 (cond
20609 ((run-hook-with-args-until-success 'org-metaleft-hook))
20610 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20611 ((org-with-limited-levels
20612 (or (org-at-heading-p)
20613 (and (org-region-active-p)
20614 (save-excursion
20615 (goto-char (region-beginning))
20616 (org-at-heading-p)))))
20617 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20618 (call-interactively 'org-do-promote))
20619 ;; At an inline task.
20620 ((org-at-heading-p)
20621 (call-interactively 'org-inlinetask-promote))
20622 ((or (org-at-item-p)
20623 (and (org-region-active-p)
20624 (save-excursion
20625 (goto-char (region-beginning))
20626 (org-at-item-p))))
20627 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20628 (call-interactively 'org-outdent-item))
20629 (t (call-interactively 'backward-word))))
20631 (defun org-metaright (&optional _arg)
20632 "Demote heading, list item at point or move table column right.
20634 In front of a drawer or a block keyword, indent it correctly.
20636 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20637 `org-indnet-drawer' or `org-indent-block' depending on context.
20638 With no specific context, calls the Emacs default `forward-word'.
20639 See the individual commands for more information.
20641 This function runs the hook `org-metaright-hook' as a first step,
20642 and returns at first non-nil value."
20643 (interactive "P")
20644 (cond
20645 ((run-hook-with-args-until-success 'org-metaright-hook))
20646 ((org-at-table-p) (call-interactively 'org-table-move-column))
20647 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20648 ((org-at-block-p) (call-interactively 'org-indent-block))
20649 ((org-with-limited-levels
20650 (or (org-at-heading-p)
20651 (and (org-region-active-p)
20652 (save-excursion
20653 (goto-char (region-beginning))
20654 (org-at-heading-p)))))
20655 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20656 (call-interactively 'org-do-demote))
20657 ;; At an inline task.
20658 ((org-at-heading-p)
20659 (call-interactively 'org-inlinetask-demote))
20660 ((or (org-at-item-p)
20661 (and (org-region-active-p)
20662 (save-excursion
20663 (goto-char (region-beginning))
20664 (org-at-item-p))))
20665 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20666 (call-interactively 'org-indent-item))
20667 (t (call-interactively 'forward-word))))
20669 (defun org-check-for-hidden (what)
20670 "Check if there are hidden headlines/items in the current visual line.
20671 WHAT can be either `headlines' or `items'. If the current line is
20672 an outline or item heading and it has a folded subtree below it,
20673 this function returns t, nil otherwise."
20674 (let ((re (cond
20675 ((eq what 'headlines) org-outline-regexp-bol)
20676 ((eq what 'items) (org-item-beginning-re))
20677 (t (error "This should not happen"))))
20678 beg end)
20679 (save-excursion
20680 (catch 'exit
20681 (unless (org-region-active-p)
20682 (setq beg (point-at-bol))
20683 (beginning-of-line 2)
20684 (while (and (not (eobp)) ;; this is like `next-line'
20685 (get-char-property (1- (point)) 'invisible))
20686 (beginning-of-line 2))
20687 (setq end (point))
20688 (goto-char beg)
20689 (goto-char (point-at-eol))
20690 (setq end (max end (point)))
20691 (while (re-search-forward re end t)
20692 (when (get-char-property (match-beginning 0) 'invisible)
20693 (throw 'exit t))))
20694 nil))))
20696 (defun org-metaup (&optional _arg)
20697 "Move subtree up or move table row up.
20698 Calls `org-move-subtree-up' or `org-table-move-row' or
20699 `org-move-item-up', depending on context. See the individual commands
20700 for more information."
20701 (interactive "P")
20702 (cond
20703 ((run-hook-with-args-until-success 'org-metaup-hook))
20704 ((org-region-active-p)
20705 (let* ((a (min (region-beginning) (region-end)))
20706 (b (1- (max (region-beginning) (region-end))))
20707 (c (save-excursion (goto-char a)
20708 (move-beginning-of-line 0)))
20709 (d (save-excursion (goto-char a)
20710 (move-end-of-line 0) (point))))
20711 (transpose-regions a b c d)
20712 (goto-char c)))
20713 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20714 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20715 ((org-at-item-p) (call-interactively 'org-move-item-up))
20716 (t (org-drag-element-backward))))
20718 (defun org-metadown (&optional _arg)
20719 "Move subtree down or move table row down.
20720 Calls `org-move-subtree-down' or `org-table-move-row' or
20721 `org-move-item-down', depending on context. See the individual
20722 commands for more information."
20723 (interactive "P")
20724 (cond
20725 ((run-hook-with-args-until-success 'org-metadown-hook))
20726 ((org-region-active-p)
20727 (let* ((a (min (region-beginning) (region-end)))
20728 (b (max (region-beginning) (region-end)))
20729 (c (save-excursion (goto-char b)
20730 (move-beginning-of-line 1)))
20731 (d (save-excursion (goto-char b)
20732 (move-end-of-line 1) (1+ (point)))))
20733 (transpose-regions a b c d)
20734 (goto-char d)))
20735 ((org-at-table-p) (call-interactively 'org-table-move-row))
20736 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20737 ((org-at-item-p) (call-interactively 'org-move-item-down))
20738 (t (org-drag-element-forward))))
20740 (defun org-shiftup (&optional arg)
20741 "Increase item in timestamp or increase priority of current headline.
20742 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20743 depending on context. See the individual commands for more information."
20744 (interactive "P")
20745 (cond
20746 ((run-hook-with-args-until-success 'org-shiftup-hook))
20747 ((and org-support-shift-select (org-region-active-p))
20748 (org-call-for-shift-select 'previous-line))
20749 ((org-at-timestamp-p t)
20750 (call-interactively (if org-edit-timestamp-down-means-later
20751 'org-timestamp-down 'org-timestamp-up)))
20752 ((and (not (eq org-support-shift-select 'always))
20753 org-enable-priority-commands
20754 (org-at-heading-p))
20755 (call-interactively 'org-priority-up))
20756 ((and (not org-support-shift-select) (org-at-item-p))
20757 (call-interactively 'org-previous-item))
20758 ((org-clocktable-try-shift 'up arg))
20759 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20760 (org-support-shift-select
20761 (org-call-for-shift-select 'previous-line))
20762 (t (org-shiftselect-error))))
20764 (defun org-shiftdown (&optional arg)
20765 "Decrease item in timestamp or decrease priority of current headline.
20766 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20767 depending on context. See the individual commands for more information."
20768 (interactive "P")
20769 (cond
20770 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20771 ((and org-support-shift-select (org-region-active-p))
20772 (org-call-for-shift-select 'next-line))
20773 ((org-at-timestamp-p t)
20774 (call-interactively (if org-edit-timestamp-down-means-later
20775 'org-timestamp-up 'org-timestamp-down)))
20776 ((and (not (eq org-support-shift-select 'always))
20777 org-enable-priority-commands
20778 (org-at-heading-p))
20779 (call-interactively 'org-priority-down))
20780 ((and (not org-support-shift-select) (org-at-item-p))
20781 (call-interactively 'org-next-item))
20782 ((org-clocktable-try-shift 'down arg))
20783 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20784 (org-support-shift-select
20785 (org-call-for-shift-select 'next-line))
20786 (t (org-shiftselect-error))))
20788 (defun org-shiftright (&optional arg)
20789 "Cycle the thing at point or in the current line, depending on context.
20790 Depending on context, this does one of the following:
20792 - switch a timestamp at point one day into the future
20793 - on a headline, switch to the next TODO keyword.
20794 - on an item, switch entire list to the next bullet type
20795 - on a property line, switch to the next allowed value
20796 - on a clocktable definition line, move time block into the future"
20797 (interactive "P")
20798 (cond
20799 ((run-hook-with-args-until-success 'org-shiftright-hook))
20800 ((and org-support-shift-select (org-region-active-p))
20801 (org-call-for-shift-select 'forward-char))
20802 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20803 ((and (not (eq org-support-shift-select 'always))
20804 (org-at-heading-p))
20805 (let ((org-inhibit-logging
20806 (not org-treat-S-cursor-todo-selection-as-state-change))
20807 (org-inhibit-blocking
20808 (not org-treat-S-cursor-todo-selection-as-state-change)))
20809 (org-call-with-arg 'org-todo 'right)))
20810 ((or (and org-support-shift-select
20811 (not (eq org-support-shift-select 'always))
20812 (org-at-item-bullet-p))
20813 (and (not org-support-shift-select) (org-at-item-p)))
20814 (org-call-with-arg 'org-cycle-list-bullet nil))
20815 ((and (not (eq org-support-shift-select 'always))
20816 (org-at-property-p))
20817 (call-interactively 'org-property-next-allowed-value))
20818 ((org-clocktable-try-shift 'right arg))
20819 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20820 (org-support-shift-select
20821 (org-call-for-shift-select 'forward-char))
20822 (t (org-shiftselect-error))))
20824 (defun org-shiftleft (&optional arg)
20825 "Cycle the thing at point or in the current line, depending on context.
20826 Depending on context, this does one of the following:
20828 - switch a timestamp at point one day into the past
20829 - on a headline, switch to the previous TODO keyword.
20830 - on an item, switch entire list to the previous bullet type
20831 - on a property line, switch to the previous allowed value
20832 - on a clocktable definition line, move time block into the past"
20833 (interactive "P")
20834 (cond
20835 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20836 ((and org-support-shift-select (org-region-active-p))
20837 (org-call-for-shift-select 'backward-char))
20838 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20839 ((and (not (eq org-support-shift-select 'always))
20840 (org-at-heading-p))
20841 (let ((org-inhibit-logging
20842 (not org-treat-S-cursor-todo-selection-as-state-change))
20843 (org-inhibit-blocking
20844 (not org-treat-S-cursor-todo-selection-as-state-change)))
20845 (org-call-with-arg 'org-todo 'left)))
20846 ((or (and org-support-shift-select
20847 (not (eq org-support-shift-select 'always))
20848 (org-at-item-bullet-p))
20849 (and (not org-support-shift-select) (org-at-item-p)))
20850 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20851 ((and (not (eq org-support-shift-select 'always))
20852 (org-at-property-p))
20853 (call-interactively 'org-property-previous-allowed-value))
20854 ((org-clocktable-try-shift 'left arg))
20855 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20856 (org-support-shift-select
20857 (org-call-for-shift-select 'backward-char))
20858 (t (org-shiftselect-error))))
20860 (defun org-shiftcontrolright ()
20861 "Switch to next TODO set."
20862 (interactive)
20863 (cond
20864 ((and org-support-shift-select (org-region-active-p))
20865 (org-call-for-shift-select 'forward-word))
20866 ((and (not (eq org-support-shift-select 'always))
20867 (org-at-heading-p))
20868 (org-call-with-arg 'org-todo 'nextset))
20869 (org-support-shift-select
20870 (org-call-for-shift-select 'forward-word))
20871 (t (org-shiftselect-error))))
20873 (defun org-shiftcontrolleft ()
20874 "Switch to previous TODO set."
20875 (interactive)
20876 (cond
20877 ((and org-support-shift-select (org-region-active-p))
20878 (org-call-for-shift-select 'backward-word))
20879 ((and (not (eq org-support-shift-select 'always))
20880 (org-at-heading-p))
20881 (org-call-with-arg 'org-todo 'previousset))
20882 (org-support-shift-select
20883 (org-call-for-shift-select 'backward-word))
20884 (t (org-shiftselect-error))))
20886 (defun org-shiftcontrolup (&optional n)
20887 "Change timestamps synchronously up in CLOCK log lines.
20888 Optional argument N tells to change by that many units."
20889 (interactive "P")
20890 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20891 (let (org-support-shift-select)
20892 (org-clock-timestamps-up n))
20893 (user-error "Not at a clock log")))
20895 (defun org-shiftcontroldown (&optional n)
20896 "Change timestamps synchronously down in CLOCK log lines.
20897 Optional argument N tells to change by that many units."
20898 (interactive "P")
20899 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20900 (let (org-support-shift-select)
20901 (org-clock-timestamps-down n))
20902 (user-error "Not at a clock log")))
20904 (defun org-increase-number-at-point (&optional inc)
20905 "Increment the number at point.
20906 With an optional prefix numeric argument INC, increment using
20907 this numeric value."
20908 (interactive "p")
20909 (if (not (number-at-point))
20910 (user-error "Not on a number")
20911 (unless inc (setq inc 1))
20912 (let ((pos (point))
20913 (beg (skip-chars-backward "-+^/*0-9eE."))
20914 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20915 (setq nap (buffer-substring-no-properties
20916 (+ pos beg) (+ pos beg end)))
20917 (delete-region (+ pos beg) (+ pos beg end))
20918 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20919 (when (org-at-table-p)
20920 (org-table-align)
20921 (org-table-end-of-field 1))))
20923 (defun org-decrease-number-at-point (&optional inc)
20924 "Decrement the number at point.
20925 With an optional prefix numeric argument INC, decrement using
20926 this numeric value."
20927 (interactive "p")
20928 (org-increase-number-at-point (- (or inc 1))))
20930 (defun org-ctrl-c-ret ()
20931 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20932 (interactive)
20933 (cond
20934 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20935 (t (call-interactively 'org-insert-heading))))
20937 (defun org-find-visible ()
20938 (let ((s (point)))
20939 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20940 (get-char-property s 'invisible)))
20942 (defun org-find-invisible ()
20943 (let ((s (point)))
20944 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20945 (not (get-char-property s 'invisible))))
20948 (defun org-copy-visible (beg end)
20949 "Copy the visible parts of the region."
20950 (interactive "r")
20951 (let (snippets s)
20952 (save-excursion
20953 (save-restriction
20954 (narrow-to-region beg end)
20955 (setq s (goto-char (point-min)))
20956 (while (not (= (point) (point-max)))
20957 (goto-char (org-find-invisible))
20958 (push (buffer-substring s (point)) snippets)
20959 (setq s (goto-char (org-find-visible))))))
20960 (kill-new (apply 'concat (nreverse snippets)))))
20962 (defun org-copy-special ()
20963 "Copy region in table or copy current subtree.
20964 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20965 See the individual commands for more information."
20966 (interactive)
20967 (call-interactively
20968 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20970 (defun org-cut-special ()
20971 "Cut region in table or cut current subtree.
20972 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20973 See the individual commands for more information."
20974 (interactive)
20975 (call-interactively
20976 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20978 (defun org-paste-special (arg)
20979 "Paste rectangular region into table, or past subtree relative to level.
20980 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20981 See the individual commands for more information."
20982 (interactive "P")
20983 (if (org-at-table-p)
20984 (org-table-paste-rectangle)
20985 (org-paste-subtree arg)))
20987 (defsubst org-in-fixed-width-region-p ()
20988 "Is point in a fixed-width region?"
20989 (save-match-data
20990 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20992 (defun org-edit-special (&optional arg)
20993 "Call a special editor for the element at point.
20994 When at a table, call the formula editor with `org-table-edit-formulas'.
20995 When in a source code block, call `org-edit-src-code'.
20996 When in a fixed-width region, call `org-edit-fixed-width-region'.
20997 When in an export block, call `org-edit-export-block'.
20998 When at an #+INCLUDE keyword, visit the included file.
20999 When at a footnote reference, call `org-edit-footnote-reference'
21000 On a link, call `ffap' to visit the link at point.
21001 Otherwise, return a user error."
21002 (interactive "P")
21003 (let ((element (org-element-at-point)))
21004 (cl-assert (not buffer-read-only) nil
21005 "Buffer is read-only: %s" (buffer-name))
21006 (pcase (org-element-type element)
21007 (`src-block
21008 (if (not arg) (org-edit-src-code)
21009 (let* ((info (org-babel-get-src-block-info))
21010 (lang (nth 0 info))
21011 (params (nth 2 info))
21012 (session (cdr (assq :session params))))
21013 (if (not session) (org-edit-src-code)
21014 ;; At a src-block with a session and function called with
21015 ;; an ARG: switch to the buffer related to the inferior
21016 ;; process.
21017 (switch-to-buffer
21018 (funcall (intern (concat "org-babel-prep-session:" lang))
21019 session params))))))
21020 (`keyword
21021 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21022 (org-open-link-from-string
21023 (format "[[%s]]"
21024 (expand-file-name
21025 (let ((value (org-element-property :value element)))
21026 (cond ((not (org-string-nw-p value))
21027 (user-error "No file to edit"))
21028 ((string-match "\\`\"\\(.*?\\)\"" value)
21029 (match-string 1 value))
21030 ((string-match "\\`[^ \t\"]\\S-*" value)
21031 (match-string 0 value))
21032 (t (user-error "No valid file specified")))))))
21033 (user-error "No special environment to edit here")))
21034 (`table
21035 (if (eq (org-element-property :type element) 'table.el)
21036 (org-edit-table.el)
21037 (call-interactively 'org-table-edit-formulas)))
21038 ;; Only Org tables contain `table-row' type elements.
21039 (`table-row (call-interactively 'org-table-edit-formulas))
21040 (`example-block (org-edit-src-code))
21041 (`export-block (org-edit-export-block))
21042 (`fixed-width (org-edit-fixed-width-region))
21044 ;; No notable element at point. Though, we may be at a link or
21045 ;; a footnote reference, which are objects. Thus, scan deeper.
21046 (let ((context (org-element-context element)))
21047 (pcase (org-element-type context)
21048 (`footnote-reference (org-edit-footnote-reference))
21049 (`inline-src-block (org-edit-inline-src-code))
21050 (`link (call-interactively #'ffap))
21051 (_ (user-error "No special environment to edit here"))))))))
21053 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21054 (defun org-ctrl-c-ctrl-c (&optional arg)
21055 "Set tags in headline, or update according to changed information at point.
21057 This command does many different things, depending on context:
21059 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21060 this is what we do.
21062 - If the cursor is on a statistics cookie, update it.
21064 - If the cursor is in a headline, prompt for tags and insert them
21065 into the current line, aligned to `org-tags-column'. When called
21066 with prefix arg, realign all tags in the current buffer.
21068 - If the cursor is in one of the special #+KEYWORD lines, this
21069 triggers scanning the buffer for these lines and updating the
21070 information.
21072 - If the cursor is inside a table, realign the table. This command
21073 works even if the automatic table editor has been turned off.
21075 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21076 the entire table.
21078 - If the cursor is at a footnote reference or definition, jump to
21079 the corresponding definition or references, respectively.
21081 - If the cursor is a the beginning of a dynamic block, update it.
21083 - If the current buffer is a capture buffer, close note and file it.
21085 - If the cursor is on a <<<target>>>, update radio targets and
21086 corresponding links in this buffer.
21088 - If the cursor is on a numbered item in a plain list, renumber the
21089 ordered list.
21091 - If the cursor is on a checkbox, toggle it.
21093 - If the cursor is on a code block, evaluate it. The variable
21094 `org-confirm-babel-evaluate' can be used to control prompting
21095 before code block evaluation, by default every code block
21096 evaluation requires confirmation. Code block evaluation can be
21097 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21098 (interactive "P")
21099 (cond
21100 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21101 org-occur-highlights)
21102 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21103 (org-remove-occur-highlights)
21104 (message "Temporary highlights/overlays removed from current buffer"))
21105 ((and (local-variable-p 'org-finish-function (current-buffer))
21106 (fboundp org-finish-function))
21107 (funcall org-finish-function))
21108 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21110 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21111 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21112 (user-error "C-c C-c can do nothing useful at this location"))
21113 (let* ((context (org-element-context))
21114 (type (org-element-type context)))
21115 (cl-case type
21116 ;; When at a link, act according to the parent instead.
21117 (link (setq context (org-element-property :parent context))
21118 (setq type (org-element-type context)))
21119 ;; Unsupported object types: refer to the first supported
21120 ;; element or object containing it.
21121 ((bold code entity export-snippet inline-babel-call inline-src-block
21122 italic latex-fragment line-break macro strike-through subscript
21123 superscript underline verbatim)
21124 (setq context
21125 (org-element-lineage
21126 context '(radio-target paragraph verse-block table-cell)))))
21127 ;; For convenience: at the first line of a paragraph on the
21128 ;; same line as an item, apply function on that item instead.
21129 (when (eq type 'paragraph)
21130 (let ((parent (org-element-property :parent context)))
21131 (when (and (eq (org-element-type parent) 'item)
21132 (= (line-beginning-position)
21133 (org-element-property :begin parent)))
21134 (setq context parent type 'item))))
21135 ;; Act according to type of element or object at point.
21136 (cl-case type
21137 (clock (org-clock-update-time-maybe))
21138 (dynamic-block
21139 (save-excursion
21140 (goto-char (org-element-property :post-affiliated context))
21141 (org-update-dblock)))
21142 (footnote-definition
21143 (goto-char (org-element-property :post-affiliated context))
21144 (call-interactively 'org-footnote-action))
21145 (footnote-reference (call-interactively 'org-footnote-action))
21146 ((headline inlinetask)
21147 (save-excursion (goto-char (org-element-property :begin context))
21148 (call-interactively 'org-set-tags)))
21149 (item
21150 ;; At an item: a double C-u set checkbox to "[-]"
21151 ;; unconditionally, whereas a single one will toggle its
21152 ;; presence. Without a universal argument, if the item
21153 ;; has a checkbox, toggle it. Otherwise repair the list.
21154 (let* ((box (org-element-property :checkbox context))
21155 (struct (org-element-property :structure context))
21156 (old-struct (copy-tree struct))
21157 (parents (org-list-parents-alist struct))
21158 (prevs (org-list-prevs-alist struct))
21159 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21160 (org-list-set-checkbox
21161 (org-element-property :begin context) struct
21162 (cond ((equal arg '(16)) "[-]")
21163 ((and (not box) (equal arg '(4))) "[ ]")
21164 ((or (not box) (equal arg '(4))) nil)
21165 ((eq box 'on) "[ ]")
21166 (t "[X]")))
21167 ;; Mimic `org-list-write-struct' but with grabbing
21168 ;; a return value from `org-list-struct-fix-box'.
21169 (org-list-struct-fix-ind struct parents 2)
21170 (org-list-struct-fix-item-end struct)
21171 (org-list-struct-fix-bul struct prevs)
21172 (org-list-struct-fix-ind struct parents)
21173 (let ((block-item
21174 (org-list-struct-fix-box struct parents prevs orderedp)))
21175 (if (and box (equal struct old-struct))
21176 (if (equal arg '(16))
21177 (message "Checkboxes already reset")
21178 (user-error "Cannot toggle this checkbox: %s"
21179 (if (eq box 'on)
21180 "all subitems checked"
21181 "unchecked subitems")))
21182 (org-list-struct-apply-struct struct old-struct)
21183 (org-update-checkbox-count-maybe))
21184 (when block-item
21185 (message "Checkboxes were removed due to empty box at line %d"
21186 (org-current-line block-item))))))
21187 (keyword
21188 (let ((org-inhibit-startup-visibility-stuff t)
21189 (org-startup-align-all-tables nil))
21190 (when (boundp 'org-table-coordinate-overlays)
21191 (mapc #'delete-overlay org-table-coordinate-overlays)
21192 (setq org-table-coordinate-overlays nil))
21193 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21194 (message "Local setup has been refreshed"))
21195 (plain-list
21196 ;; At a plain list, with a double C-u argument, set
21197 ;; checkboxes of each item to "[-]", whereas a single one
21198 ;; will toggle their presence according to the state of the
21199 ;; first item in the list. Without an argument, repair the
21200 ;; list.
21201 (let* ((begin (org-element-property :contents-begin context))
21202 (beginm (move-marker (make-marker) begin))
21203 (struct (org-element-property :structure context))
21204 (old-struct (copy-tree struct))
21205 (first-box (save-excursion
21206 (goto-char begin)
21207 (looking-at org-list-full-item-re)
21208 (match-string-no-properties 3)))
21209 (new-box (cond ((equal arg '(16)) "[-]")
21210 ((equal arg '(4)) (unless first-box "[ ]"))
21211 ((equal first-box "[X]") "[ ]")
21212 (t "[X]"))))
21213 (cond
21214 (arg
21215 (dolist (pos
21216 (org-list-get-all-items
21217 begin struct (org-list-prevs-alist struct)))
21218 (org-list-set-checkbox pos struct new-box)))
21219 ((and first-box (eq (point) begin))
21220 ;; For convenience, when point is at bol on the first
21221 ;; item of the list and no argument is provided, simply
21222 ;; toggle checkbox of that item, if any.
21223 (org-list-set-checkbox begin struct new-box)))
21224 (org-list-write-struct
21225 struct (org-list-parents-alist struct) old-struct)
21226 (org-update-checkbox-count-maybe)
21227 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21228 ((property-drawer node-property)
21229 (call-interactively 'org-property-action))
21230 ((radio-target target)
21231 (call-interactively 'org-update-radio-target-regexp))
21232 (statistics-cookie
21233 (call-interactively 'org-update-statistics-cookies))
21234 ((table table-cell table-row)
21235 ;; At a table, recalculate every field and align it. Also
21236 ;; send the table if necessary. If the table has
21237 ;; a `table.el' type, just give up. At a table row or
21238 ;; cell, maybe recalculate line but always align table.
21239 (if (eq (org-element-property :type context) 'table.el)
21240 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21241 Use \\[org-edit-special] to edit table.el tables"))
21242 (let ((org-enable-table-editor t))
21243 (if (or (eq type 'table)
21244 ;; Check if point is at a TBLFM line.
21245 (and (eq type 'table-row)
21246 (= (point) (org-element-property :end context))))
21247 (save-excursion
21248 (if (org-at-TBLFM-p)
21249 (progn (require 'org-table)
21250 (org-table-calc-current-TBLFM))
21251 (goto-char (org-element-property :contents-begin context))
21252 (org-call-with-arg 'org-table-recalculate (or arg t))
21253 (orgtbl-send-table 'maybe)))
21254 (org-table-maybe-eval-formula)
21255 (cond (arg (call-interactively 'org-table-recalculate))
21256 ((org-table-maybe-recalculate-line))
21257 (t (org-table-align)))))))
21258 (timestamp (org-timestamp-change 0 'day))
21259 (otherwise
21260 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21261 (user-error
21262 "C-c C-c can do nothing useful at this location")))))))))
21264 (defun org-mode-restart ()
21265 (interactive)
21266 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21267 (funcall major-mode)
21268 (hack-local-variables)
21269 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21270 (org-indent-mode -1)))
21271 (message "%s restarted" major-mode))
21273 (defun org-kill-note-or-show-branches ()
21274 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21275 (interactive)
21276 (if (not org-finish-function)
21277 (progn
21278 (outline-hide-subtree)
21279 (call-interactively 'outline-show-branches))
21280 (let ((org-note-abort t))
21281 (funcall org-finish-function))))
21283 (defun org-delete-indentation (&optional ARG)
21284 "Join current line to previous and fix whitespace at join.
21286 If previous line is a headline add to headline title. Otherwise
21287 the function calls `delete-indentation'.
21289 With argument, join this line to following line."
21290 (interactive "*P")
21291 (if (save-excursion
21292 (if ARG (beginning-of-line)
21293 (forward-line -1))
21294 (looking-at org-complex-heading-regexp))
21295 ;; At headline.
21296 (let ((tags-column (when (match-beginning 5)
21297 (save-excursion (goto-char (match-beginning 5))
21298 (current-column))))
21299 (string (concat " " (progn (when ARG (forward-line 1))
21300 (org-trim (delete-and-extract-region
21301 (line-beginning-position)
21302 (line-end-position)))))))
21303 (unless (bobp) (delete-region (point) (1- (point))))
21304 (goto-char (or (match-end 4)
21305 (match-beginning 5)
21306 (match-end 0)))
21307 (skip-chars-backward " \t")
21308 (save-excursion (insert string))
21309 ;; Adjust alignment of tags.
21310 (when tags-column
21311 (org-align-tags-here (if org-auto-align-tags
21312 org-tags-column
21313 tags-column))))
21314 (delete-indentation ARG)))
21316 (defun org-open-line (n)
21317 "Insert a new row in tables, call `open-line' elsewhere.
21318 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21319 (interactive "*p")
21320 (cond
21321 ((not org-special-ctrl-o)
21322 (open-line n))
21323 ((org-at-table-p)
21324 (org-table-insert-row))
21326 (open-line n))))
21328 (defun org-return (&optional indent)
21329 "Goto next table row or insert a newline.
21331 Calls `org-table-next-row' or `newline', depending on context.
21333 When optional INDENT argument is non-nil, call
21334 `newline-and-indent' instead of `newline'.
21336 When `org-return-follows-link' is non-nil and point is on
21337 a timestamp or a link, call `org-open-at-point'. However, it
21338 will not happen if point is in a table or on a \"dead\"
21339 object (e.g., within a comment). In these case, you need to use
21340 `org-open-at-point' directly."
21341 (interactive)
21342 (let ((context (if org-return-follows-link (org-element-context)
21343 (org-element-at-point))))
21344 (cond
21345 ;; In a table, call `org-table-next-row'.
21346 ((or (and (eq (org-element-type context) 'table)
21347 (>= (point) (org-element-property :contents-begin context))
21348 (< (point) (org-element-property :contents-end context)))
21349 (org-element-lineage context '(table-row table-cell) t))
21350 (org-table-justify-field-maybe)
21351 (call-interactively #'org-table-next-row))
21352 ;; On a link or a timestamp, call `org-open-at-point' if
21353 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21354 ;; locations, e.g., in a comment, as `org-open-at-point'.
21355 ((and org-return-follows-link
21356 (or (org-in-regexp org-ts-regexp-both nil t)
21357 (org-in-regexp org-tsr-regexp-both nil t)
21358 (org-in-regexp org-any-link-re nil t)))
21359 (call-interactively #'org-open-at-point))
21360 ;; Insert newline in heading, but preserve tags.
21361 ((and (not (bolp))
21362 (save-excursion (beginning-of-line)
21363 (looking-at org-complex-heading-regexp)))
21364 ;; At headline. Split line. However, if point is on keyword,
21365 ;; priority cookie or tags, do not break any of them: add
21366 ;; a newline after the headline instead.
21367 (let ((tags-column (and (match-beginning 5)
21368 (save-excursion (goto-char (match-beginning 5))
21369 (current-column))))
21370 (string
21371 (when (and (match-end 4)
21372 (>= (point)
21373 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21374 (<= (point) (match-end 4)))
21375 (delete-and-extract-region (point) (match-end 4)))))
21376 (when (and tags-column string) ; Adjust tag alignment.
21377 (org-align-tags-here
21378 (if org-auto-align-tags org-tags-column tags-column)))
21379 (end-of-line)
21380 (org-show-entry)
21381 (if indent (newline-and-indent) (newline))
21382 (when string (save-excursion (insert (org-trim string))))))
21383 ;; In a list, make sure indenting keeps trailing text within.
21384 ((and indent
21385 (not (eolp))
21386 (org-element-lineage context '(item)))
21387 (let ((trailing-data
21388 (delete-and-extract-region (point) (line-end-position))))
21389 (newline-and-indent)
21390 (save-excursion (insert trailing-data))))
21391 (t (if indent (newline-and-indent) (newline))))))
21393 (defun org-return-indent ()
21394 "Goto next table row or insert a newline and indent.
21395 Calls `org-table-next-row' or `newline-and-indent', depending on
21396 context. See the individual commands for more information."
21397 (interactive)
21398 (org-return t))
21400 (defun org-ctrl-c-star ()
21401 "Compute table, or change heading status of lines.
21402 Calls `org-table-recalculate' or `org-toggle-heading',
21403 depending on context."
21404 (interactive)
21405 (cond
21406 ((org-at-table-p)
21407 (call-interactively 'org-table-recalculate))
21409 ;; Convert all lines in region to list items
21410 (call-interactively 'org-toggle-heading))))
21412 (defun org-ctrl-c-minus ()
21413 "Insert separator line in table or modify bullet status of line.
21414 Also turns a plain line or a region of lines into list items.
21415 Calls `org-table-insert-hline', `org-toggle-item', or
21416 `org-cycle-list-bullet', depending on context."
21417 (interactive)
21418 (cond
21419 ((org-at-table-p)
21420 (call-interactively 'org-table-insert-hline))
21421 ((org-region-active-p)
21422 (call-interactively 'org-toggle-item))
21423 ((org-in-item-p)
21424 (call-interactively 'org-cycle-list-bullet))
21426 (call-interactively 'org-toggle-item))))
21428 (defun org-toggle-item (arg)
21429 "Convert headings or normal lines to items, items to normal lines.
21430 If there is no active region, only the current line is considered.
21432 If the first non blank line in the region is a headline, convert
21433 all headlines to items, shifting text accordingly.
21435 If it is an item, convert all items to normal lines.
21437 If it is normal text, change region into a list of items.
21438 With a prefix argument ARG, change the region in a single item."
21439 (interactive "P")
21440 (let ((shift-text
21441 (function
21442 ;; Shift text in current section to IND, from point to END.
21443 ;; The function leaves point to END line.
21444 (lambda (ind end)
21445 (let ((min-i 1000) (end (copy-marker end)))
21446 ;; First determine the minimum indentation (MIN-I) of
21447 ;; the text.
21448 (save-excursion
21449 (catch 'exit
21450 (while (< (point) end)
21451 (let ((i (org-get-indentation)))
21452 (cond
21453 ;; Skip blank lines and inline tasks.
21454 ((looking-at "^[ \t]*$"))
21455 ((looking-at org-outline-regexp-bol))
21456 ;; We can't find less than 0 indentation.
21457 ((zerop i) (throw 'exit (setq min-i 0)))
21458 ((< i min-i) (setq min-i i))))
21459 (forward-line))))
21460 ;; Then indent each line so that a line indented to
21461 ;; MIN-I becomes indented to IND. Ignore blank lines
21462 ;; and inline tasks in the process.
21463 (let ((delta (- ind min-i)))
21464 (while (< (point) end)
21465 (unless (or (looking-at "^[ \t]*$")
21466 (looking-at org-outline-regexp-bol))
21467 (indent-line-to (+ (org-get-indentation) delta)))
21468 (forward-line)))))))
21469 (skip-blanks
21470 (function
21471 ;; Return beginning of first non-blank line, starting from
21472 ;; line at POS.
21473 (lambda (pos)
21474 (save-excursion
21475 (goto-char pos)
21476 (skip-chars-forward " \r\t\n")
21477 (point-at-bol)))))
21478 beg end)
21479 ;; Determine boundaries of changes.
21480 (if (org-region-active-p)
21481 (setq beg (funcall skip-blanks (region-beginning))
21482 end (copy-marker (region-end)))
21483 (setq beg (funcall skip-blanks (point-at-bol))
21484 end (copy-marker (point-at-eol))))
21485 ;; Depending on the starting line, choose an action on the text
21486 ;; between BEG and END.
21487 (org-with-limited-levels
21488 (save-excursion
21489 (goto-char beg)
21490 (cond
21491 ;; Case 1. Start at an item: de-itemize. Note that it only
21492 ;; happens when a region is active: `org-ctrl-c-minus'
21493 ;; would call `org-cycle-list-bullet' otherwise.
21494 ((org-at-item-p)
21495 (while (< (point) end)
21496 (when (org-at-item-p)
21497 (skip-chars-forward " \t")
21498 (delete-region (point) (match-end 0)))
21499 (forward-line)))
21500 ;; Case 2. Start at an heading: convert to items.
21501 ((org-at-heading-p)
21502 (let* ((bul (org-list-bullet-string "-"))
21503 (bul-len (length bul))
21504 (done (org-entry-is-done-p))
21505 (todo (org-entry-is-todo-p))
21506 ;; Indentation of the first heading. It should be
21507 ;; relative to the indentation of its parent, if any.
21508 (start-ind (save-excursion
21509 (cond
21510 ((not org-adapt-indentation) 0)
21511 ((not (outline-previous-heading)) 0)
21512 (t (length (match-string 0))))))
21513 ;; Level of first heading. Further headings will be
21514 ;; compared to it to determine hierarchy in the list.
21515 (ref-level (org-reduced-level (org-outline-level))))
21516 (when (or done todo) (org-todo ""))
21517 (while (< (point) end)
21518 (let* ((level (org-reduced-level (org-outline-level)))
21519 (delta (max 0 (- level ref-level))))
21520 ;; If current headline is less indented than the first
21521 ;; one, set it as reference, in order to preserve
21522 ;; subtrees.
21523 (when (< level ref-level) (setq ref-level level))
21524 (replace-match bul t t)
21525 (indent-line-to (+ start-ind (* delta bul-len)))
21526 (when (or done todo)
21527 (let* ((struct (org-list-struct))
21528 (old (copy-tree struct)))
21529 (org-list-set-checkbox (line-beginning-position)
21530 struct
21531 (if done "[X]" "[ ]"))
21532 (org-list-write-struct struct
21533 (org-list-parents-alist struct)
21534 old)))
21535 ;; Ensure all text down to END (or SECTION-END) belongs
21536 ;; to the newly created item.
21537 (let ((section-end (save-excursion
21538 (or (outline-next-heading) (point)))))
21539 (forward-line)
21540 (funcall shift-text
21541 (+ start-ind (* (1+ delta) bul-len))
21542 (min end section-end)))))))
21543 ;; Case 3. Normal line with ARG: make the first line of region
21544 ;; an item, and shift indentation of others lines to
21545 ;; set them as item's body.
21546 (arg (let* ((bul (org-list-bullet-string "-"))
21547 (bul-len (length bul))
21548 (ref-ind (org-get-indentation)))
21549 (skip-chars-forward " \t")
21550 (insert bul)
21551 (forward-line)
21552 (while (< (point) end)
21553 ;; Ensure that lines less indented than first one
21554 ;; still get included in item body.
21555 (funcall shift-text
21556 (+ ref-ind bul-len)
21557 (min end (save-excursion (or (outline-next-heading)
21558 (point)))))
21559 (forward-line))))
21560 ;; Case 4. Normal line without ARG: turn each non-item line
21561 ;; into an item.
21563 (while (< (point) end)
21564 (unless (or (org-at-heading-p) (org-at-item-p))
21565 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21566 (replace-match
21567 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21568 (forward-line))))))))
21570 (defun org-toggle-heading (&optional nstars)
21571 "Convert headings to normal text, or items or text to headings.
21572 If there is no active region, only convert the current line.
21574 With a \\[universal-argument] prefix, convert the whole list at
21575 point into heading.
21577 In a region:
21579 - If the first non blank line is a headline, remove the stars
21580 from all headlines in the region.
21582 - If it is a normal line, turn each and every normal line (i.e.,
21583 not an heading or an item) in the region into headings. If you
21584 want to convert only the first line of this region, use one
21585 universal prefix argument.
21587 - If it is a plain list item, turn all plain list items into headings.
21589 When converting a line into a heading, the number of stars is chosen
21590 such that the lines become children of the current entry. However,
21591 when a numeric prefix argument is given, its value determines the
21592 number of stars to add."
21593 (interactive "P")
21594 (let ((skip-blanks
21595 (function
21596 ;; Return beginning of first non-blank line, starting from
21597 ;; line at POS.
21598 (lambda (pos)
21599 (save-excursion
21600 (goto-char pos)
21601 (while (org-at-comment-p) (forward-line))
21602 (skip-chars-forward " \r\t\n")
21603 (point-at-bol)))))
21604 beg end toggled)
21605 ;; Determine boundaries of changes. If a universal prefix has
21606 ;; been given, put the list in a region. If region ends at a bol,
21607 ;; do not consider the last line to be in the region.
21609 (when (and current-prefix-arg (org-at-item-p))
21610 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21611 (org-mark-element))
21613 (if (org-region-active-p)
21614 (setq beg (funcall skip-blanks (region-beginning))
21615 end (copy-marker (save-excursion
21616 (goto-char (region-end))
21617 (if (bolp) (point) (point-at-eol)))))
21618 (setq beg (funcall skip-blanks (point-at-bol))
21619 end (copy-marker (point-at-eol))))
21620 ;; Ensure inline tasks don't count as headings.
21621 (org-with-limited-levels
21622 (save-excursion
21623 (goto-char beg)
21624 (cond
21625 ;; Case 1. Started at an heading: de-star headings.
21626 ((org-at-heading-p)
21627 (while (< (point) end)
21628 (when (org-at-heading-p t)
21629 (looking-at org-outline-regexp) (replace-match "")
21630 (setq toggled t))
21631 (forward-line)))
21632 ;; Case 2. Started at an item: change items into headlines.
21633 ;; One star will be added by `org-list-to-subtree'.
21634 ((org-at-item-p)
21635 (while (< (point) end)
21636 (when (org-at-item-p)
21637 ;; Pay attention to cases when region ends before list.
21638 (let* ((struct (org-list-struct))
21639 (list-end
21640 (min (org-list-get-bottom-point struct) (1+ end))))
21641 (save-restriction
21642 (narrow-to-region (point) list-end)
21643 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21644 (setq toggled t))
21645 (forward-line)))
21646 ;; Case 3. Started at normal text: make every line an heading,
21647 ;; skipping headlines and items.
21648 (t (let* ((stars
21649 (make-string
21650 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21651 (add-stars
21652 (cond (nstars "") ; stars from prefix only
21653 ((equal stars "") "*") ; before first heading
21654 (org-odd-levels-only "**") ; inside heading, odd
21655 (t "*"))) ; inside heading, oddeven
21656 (rpl (concat stars add-stars " "))
21657 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21658 (while (< (point) (if (equal nstars '(4)) lend end))
21659 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21660 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21661 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21662 (forward-line)))))))
21663 (unless toggled (message "Cannot toggle heading from here"))))
21665 (defun org-meta-return (&optional _arg)
21666 "Insert a new heading or wrap a region in a table.
21667 Calls `org-insert-heading' or `org-table-wrap-region', depending
21668 on context. See the individual commands for more information."
21669 (interactive)
21670 (org-check-before-invisible-edit 'insert)
21671 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21672 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21673 #'org-insert-heading))))
21675 ;;; Menu entries
21677 (defsubst org-in-subtree-not-table-p ()
21678 "Are we in a subtree and not in a table?"
21679 (and (not (org-before-first-heading-p))
21680 (not (org-at-table-p))))
21682 ;; Define the Org-mode menus
21683 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21684 '("Tbl"
21685 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21686 ["Next Field" org-cycle (org-at-table-p)]
21687 ["Previous Field" org-shifttab (org-at-table-p)]
21688 ["Next Row" org-return (org-at-table-p)]
21689 "--"
21690 ["Blank Field" org-table-blank-field (org-at-table-p)]
21691 ["Edit Field" org-table-edit-field (org-at-table-p)]
21692 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21693 "--"
21694 ("Column"
21695 ["Move Column Left" org-metaleft (org-at-table-p)]
21696 ["Move Column Right" org-metaright (org-at-table-p)]
21697 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21698 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21699 ("Row"
21700 ["Move Row Up" org-metaup (org-at-table-p)]
21701 ["Move Row Down" org-metadown (org-at-table-p)]
21702 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21703 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21704 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21705 "--"
21706 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21707 ("Rectangle"
21708 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21709 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21710 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21711 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21712 "--"
21713 ("Calculate"
21714 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21715 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21716 ["Edit Formulas" org-edit-special (org-at-table-p)]
21717 "--"
21718 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21719 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21720 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21721 "--"
21722 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21723 "--"
21724 ["Sum Column/Rectangle" org-table-sum
21725 (or (org-at-table-p) (org-region-active-p))]
21726 ["Which Column?" org-table-current-column (org-at-table-p)])
21727 ["Debug Formulas"
21728 org-table-toggle-formula-debugger
21729 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21730 ["Show Col/Row Numbers"
21731 org-table-toggle-coordinate-overlays
21732 :style toggle
21733 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21734 "--"
21735 ["Create" org-table-create (and (not (org-at-table-p))
21736 org-enable-table-editor)]
21737 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21738 ["Import from File" org-table-import (not (org-at-table-p))]
21739 ["Export to File" org-table-export (org-at-table-p)]
21740 "--"
21741 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21742 "--"
21743 ("Plot"
21744 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21745 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21747 (easy-menu-define org-org-menu org-mode-map "Org menu"
21748 '("Org"
21749 ("Show/Hide"
21750 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21751 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21752 ["Sparse Tree..." org-sparse-tree t]
21753 ["Reveal Context" org-reveal t]
21754 ["Show All" outline-show-all t]
21755 "--"
21756 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21757 "--"
21758 ["New Heading" org-insert-heading t]
21759 ("Navigate Headings"
21760 ["Up" outline-up-heading t]
21761 ["Next" outline-next-visible-heading t]
21762 ["Previous" outline-previous-visible-heading t]
21763 ["Next Same Level" outline-forward-same-level t]
21764 ["Previous Same Level" outline-backward-same-level t]
21765 "--"
21766 ["Jump" org-goto t])
21767 ("Edit Structure"
21768 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21769 "--"
21770 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21771 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21772 "--"
21773 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21774 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21775 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21776 "--"
21777 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21778 "--"
21779 ["Copy visible text" org-copy-visible t]
21780 "--"
21781 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21782 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21783 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21784 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21785 "--"
21786 ["Sort Region/Children" org-sort t]
21787 "--"
21788 ["Convert to odd levels" org-convert-to-odd-levels t]
21789 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21790 ("Editing"
21791 ["Emphasis..." org-emphasize t]
21792 ["Edit Source Example" org-edit-special t]
21793 "--"
21794 ["Footnote new/jump" org-footnote-action t]
21795 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21796 ("Archive"
21797 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21798 "--"
21799 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21800 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21801 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21803 "--"
21804 ("Hyperlinks"
21805 ["Store Link (Global)" org-store-link t]
21806 ["Find existing link to here" org-occur-link-in-agenda-files t]
21807 ["Insert Link" org-insert-link t]
21808 ["Follow Link" org-open-at-point t]
21809 "--"
21810 ["Next link" org-next-link t]
21811 ["Previous link" org-previous-link t]
21812 "--"
21813 ["Descriptive Links"
21814 org-toggle-link-display
21815 :style radio
21816 :selected org-descriptive-links
21818 ["Literal Links"
21819 org-toggle-link-display
21820 :style radio
21821 :selected (not org-descriptive-links)])
21822 "--"
21823 ("TODO Lists"
21824 ["TODO/DONE/-" org-todo t]
21825 ("Select keyword"
21826 ["Next keyword" org-shiftright (org-at-heading-p)]
21827 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21828 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21829 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21830 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21831 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21832 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21833 "--"
21834 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21835 :selected org-enforce-todo-dependencies :style toggle :active t]
21836 "Settings for tree at point"
21837 ["Do Children sequentially" org-toggle-ordered-property :style radio
21838 :selected (org-entry-get nil "ORDERED")
21839 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21840 ["Do Children parallel" org-toggle-ordered-property :style radio
21841 :selected (not (org-entry-get nil "ORDERED"))
21842 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21843 "--"
21844 ["Set Priority" org-priority t]
21845 ["Priority Up" org-shiftup t]
21846 ["Priority Down" org-shiftdown t]
21847 "--"
21848 ["Get news from all feeds" org-feed-update-all t]
21849 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21850 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21851 ("TAGS and Properties"
21852 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21853 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21854 "--"
21855 ["Set property" org-set-property (not (org-before-first-heading-p))]
21856 ["Column view of properties" org-columns t]
21857 ["Insert Column View DBlock" org-columns-insert-dblock t])
21858 ("Dates and Scheduling"
21859 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21860 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21861 ("Change Date"
21862 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21863 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21864 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21865 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21866 ["Compute Time Range" org-evaluate-time-range t]
21867 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21868 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21869 "--"
21870 ["Custom time format" org-toggle-time-stamp-overlays
21871 :style radio :selected org-display-custom-times]
21872 "--"
21873 ["Goto Calendar" org-goto-calendar t]
21874 ["Date from Calendar" org-date-from-calendar t]
21875 "--"
21876 ["Start/Restart Timer" org-timer-start t]
21877 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21878 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21879 ["Insert Timer String" org-timer t]
21880 ["Insert Timer Item" org-timer-item t])
21881 ("Logging work"
21882 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21883 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21884 ["Clock out" org-clock-out t]
21885 ["Clock cancel" org-clock-cancel t]
21886 "--"
21887 ["Mark as default task" org-clock-mark-default-task t]
21888 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21889 ["Goto running clock" org-clock-goto t]
21890 "--"
21891 ["Display times" org-clock-display t]
21892 ["Create clock table" org-clock-report t]
21893 "--"
21894 ["Record DONE time"
21895 (progn (setq org-log-done (not org-log-done))
21896 (message "Switching to %s will %s record a timestamp"
21897 (car org-done-keywords)
21898 (if org-log-done "automatically" "not")))
21899 :style toggle :selected org-log-done])
21900 "--"
21901 ["Agenda Command..." org-agenda t]
21902 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21903 ("File List for Agenda")
21904 ("Special views current file"
21905 ["TODO Tree" org-show-todo-tree t]
21906 ["Check Deadlines" org-check-deadlines t]
21907 ["Timeline" org-timeline t]
21908 ["Tags/Property tree" org-match-sparse-tree t])
21909 "--"
21910 ["Export/Publish..." org-export-dispatch t]
21911 ("LaTeX"
21912 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21913 :selected org-cdlatex-mode]
21914 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21915 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21916 ["Modify math symbol" org-cdlatex-math-modify
21917 (org-inside-LaTeX-fragment-p)]
21918 ["Insert citation" org-reftex-citation t])
21919 "--"
21920 ("MobileOrg"
21921 ["Push Files and Views" org-mobile-push t]
21922 ["Get Captured and Flagged" org-mobile-pull t]
21923 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21924 "--"
21925 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21926 "--"
21927 ("Documentation"
21928 ["Show Version" org-version t]
21929 ["Info Documentation" org-info t])
21930 ("Customize"
21931 ["Browse Org Group" org-customize t]
21932 "--"
21933 ["Expand This Menu" org-create-customize-menu
21934 (fboundp 'customize-menu-create)])
21935 ["Send bug report" org-submit-bug-report t]
21936 "--"
21937 ("Refresh/Reload"
21938 ["Refresh setup current buffer" org-mode-restart t]
21939 ["Reload Org (after update)" org-reload t]
21940 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21943 (defun org-info (&optional node)
21944 "Read documentation for Org-mode in the info system.
21945 With optional NODE, go directly to that node."
21946 (interactive)
21947 (info (format "(org)%s" (or node ""))))
21949 ;;;###autoload
21950 (defun org-submit-bug-report ()
21951 "Submit a bug report on Org-mode via mail.
21953 Don't hesitate to report any problems or inaccurate documentation.
21955 If you don't have setup sending mail from (X)Emacs, please copy the
21956 output buffer into your mail program, as it gives us important
21957 information about your Org-mode version and configuration."
21958 (interactive)
21959 (require 'reporter)
21960 (defvar reporter-prompt-for-summary-p)
21961 (org-load-modules-maybe)
21962 (org-require-autoloaded-modules)
21963 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21964 (reporter-submit-bug-report
21965 "emacs-orgmode@gnu.org"
21966 (org-version nil 'full)
21967 (let (list)
21968 (save-window-excursion
21969 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21970 (delete-other-windows)
21971 (erase-buffer)
21972 (insert "You are about to submit a bug report to the Org-mode mailing list.
21974 We would like to add your full Org-mode and Outline configuration to the
21975 bug report. This greatly simplifies the work of the maintainer and
21976 other experts on the mailing list.
21978 HOWEVER, some variables you have customized may contain private
21979 information. The names of customers, colleagues, or friends, might
21980 appear in the form of file names, tags, todo states, or search strings.
21981 If you answer yes to the prompt, you might want to check and remove
21982 such private information before sending the email.")
21983 (add-text-properties (point-min) (point-max) '(face org-warning))
21984 (when (yes-or-no-p "Include your Org-mode configuration ")
21985 (mapatoms
21986 (lambda (v)
21987 (and (boundp v)
21988 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21989 (or (and (symbol-value v)
21990 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21991 (and
21992 (get v 'custom-type) (get v 'standard-value)
21993 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21994 (push v list)))))
21995 (kill-buffer (get-buffer "*Warn about privacy*"))
21996 list))
21997 nil nil
21998 "Remember to cover the basics, that is, what you expected to happen and
21999 what in fact did happen. You don't know how to make a good report? See
22001 http://orgmode.org/manual/Feedback.html#Feedback
22003 Your bug report will be posted to the Org-mode mailing list.
22004 ------------------------------------------------------------------------")
22005 (save-excursion
22006 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
22007 (replace-match "\\1Bug: \\3 [\\2]")))))
22010 (defun org-install-agenda-files-menu ()
22011 (let ((bl (buffer-list)))
22012 (save-excursion
22013 (while bl
22014 (set-buffer (pop bl))
22015 (when (derived-mode-p 'org-mode) (setq bl nil)))
22016 (when (derived-mode-p 'org-mode)
22017 (easy-menu-change
22018 '("Org") "File List for Agenda"
22019 (append
22020 (list
22021 ["Edit File List" (org-edit-agenda-file-list) t]
22022 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
22023 ["Remove Current File from List" org-remove-file t]
22024 ["Cycle through agenda files" org-cycle-agenda-files t]
22025 ["Occur in all agenda files" org-occur-in-agenda-files t]
22026 "--")
22027 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22029 ;;;; Documentation
22031 (defun org-require-autoloaded-modules ()
22032 (interactive)
22033 (mapc #'require
22034 '(org-agenda org-archive org-attach org-clock org-colview org-id
22035 org-table org-timer)))
22037 ;;;###autoload
22038 (defun org-reload (&optional uncompiled)
22039 "Reload all org lisp files.
22040 With prefix arg UNCOMPILED, load the uncompiled versions."
22041 (interactive "P")
22042 (require 'loadhist)
22043 (let* ((org-dir (org-find-library-dir "org"))
22044 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22045 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22046 (remove-re (format "\\`%s\\'"
22047 (regexp-opt '("org" "org-loaddefs" "org-version"))))
22048 (feats (delete-dups
22049 (mapcar 'file-name-sans-extension
22050 (mapcar 'file-name-nondirectory
22051 (delq nil
22052 (mapcar 'feature-file
22053 features))))))
22054 (lfeat (append
22055 (sort
22056 (setq feats
22057 (delq nil (mapcar
22058 (lambda (f)
22059 (if (and (string-match feature-re f)
22060 (not (string-match remove-re f)))
22061 f nil))
22062 feats)))
22063 'string-lessp)
22064 (list "org-version" "org")))
22065 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22066 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22067 load-uncore load-misses)
22068 (setq load-misses
22069 (delq 't
22070 (mapcar (lambda (f)
22071 (or (org-load-noerror-mustsuffix (concat org-dir f))
22072 (and (string= org-dir contrib-dir)
22073 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22074 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22075 (add-to-list 'load-uncore f 'append)
22078 lfeat)))
22079 (when load-uncore
22080 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22081 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22082 (if load-misses
22083 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22084 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22085 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22087 ;;;###autoload
22088 (defun org-customize ()
22089 "Call the customize function with org as argument."
22090 (interactive)
22091 (org-load-modules-maybe)
22092 (org-require-autoloaded-modules)
22093 (customize-browse 'org))
22095 (defun org-create-customize-menu ()
22096 "Create a full customization menu for Org-mode, insert it into the menu."
22097 (interactive)
22098 (org-load-modules-maybe)
22099 (org-require-autoloaded-modules)
22100 (if (fboundp 'customize-menu-create)
22101 (progn
22102 (easy-menu-change
22103 '("Org") "Customize"
22104 `(["Browse Org group" org-customize t]
22105 "--"
22106 ,(customize-menu-create 'org)
22107 ["Set" Custom-set t]
22108 ["Save" Custom-save t]
22109 ["Reset to Current" Custom-reset-current t]
22110 ["Reset to Saved" Custom-reset-saved t]
22111 ["Reset to Standard Settings" Custom-reset-standard t]))
22112 (message "\"Org\"-menu now contains full customization menu"))
22113 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22115 ;;;; Miscellaneous stuff
22117 ;;; Generally useful functions
22119 (defun org-get-at-eol (property n)
22120 "Get text property PROPERTY at the end of line less N characters."
22121 (get-text-property (- (point-at-eol) n) property))
22123 (defun org-find-text-property-in-string (prop s)
22124 "Return the first non-nil value of property PROP in string S."
22125 (or (get-text-property 0 prop s)
22126 (get-text-property (or (next-single-property-change 0 prop s) 0)
22127 prop s)))
22129 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22130 "Display the given MESSAGE as a warning."
22131 (if (fboundp 'display-warning)
22132 (display-warning 'org message :warning)
22133 (let ((buf (get-buffer-create "*Org warnings*")))
22134 (with-current-buffer buf
22135 (goto-char (point-max))
22136 (insert "Warning (Org): " message)
22137 (unless (bolp)
22138 (newline)))
22139 (display-buffer buf)
22140 (sit-for 0))))
22142 (defun org-eval (form)
22143 "Eval FORM and return result."
22144 (condition-case error
22145 (eval form)
22146 (error (format "%%![Error: %s]" error))))
22148 (defun org-in-clocktable-p ()
22149 "Check if the cursor is in a clocktable."
22150 (let ((pos (point)) start)
22151 (save-excursion
22152 (end-of-line 1)
22153 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22154 (setq start (match-beginning 0))
22155 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22156 (>= (match-end 0) pos)
22157 start))))
22159 (defun org-in-verbatim-emphasis ()
22160 (save-match-data
22161 (and (org-in-regexp org-emph-re 2)
22162 (>= (point) (match-beginning 3))
22163 (<= (point) (match-end 4))
22164 (member (match-string 3) '("=" "~")))))
22166 (defun org-overlay-display (ovl text &optional face evap)
22167 "Make overlay OVL display TEXT with face FACE."
22168 (overlay-put ovl 'display text)
22169 (if face (overlay-put ovl 'face face))
22170 (if evap (overlay-put ovl 'evaporate t)))
22172 (defun org-overlay-before-string (ovl text &optional face evap)
22173 "Make overlay OVL display TEXT with face FACE."
22174 (if face (org-add-props text nil 'face face))
22175 (overlay-put ovl 'before-string text)
22176 (if evap (overlay-put ovl 'evaporate t)))
22178 (defun org-find-overlays (prop &optional pos delete)
22179 "Find all overlays specifying PROP at POS or point.
22180 If DELETE is non-nil, delete all those overlays."
22181 (let (found)
22182 (dolist (ov (overlays-at (or pos (point))) found)
22183 (cond ((not (overlay-get ov prop)))
22184 (delete (delete-overlay ov))
22185 (t (push ov found))))))
22187 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22188 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22189 (if (and marker (marker-buffer marker)
22190 (buffer-live-p (marker-buffer marker)))
22191 (progn
22192 (org-pop-to-buffer-same-window (marker-buffer marker))
22193 (when (or (> marker (point-max)) (< marker (point-min)))
22194 (widen))
22195 (goto-char marker)
22196 (org-show-context 'org-goto))
22197 (if bookmark
22198 (bookmark-jump bookmark)
22199 (error "Cannot find location"))))
22201 (defun org-quote-csv-field (s)
22202 "Quote field for inclusion in CSV material."
22203 (if (string-match "[\",]" s)
22204 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22207 (defun org-force-self-insert (N)
22208 "Needed to enforce self-insert under remapping."
22209 (interactive "p")
22210 (self-insert-command N))
22212 (defun org-string-width (s)
22213 "Compute width of string, ignoring invisible characters.
22214 This ignores character with invisibility property `org-link', and also
22215 characters with property `org-cwidth', because these will become invisible
22216 upon the next fontification round."
22217 (let (b l)
22218 (when (or (eq t buffer-invisibility-spec)
22219 (assq 'org-link buffer-invisibility-spec))
22220 (while (setq b (text-property-any 0 (length s)
22221 'invisible 'org-link s))
22222 (setq s (concat (substring s 0 b)
22223 (substring s (or (next-single-property-change
22224 b 'invisible s)
22225 (length s)))))))
22226 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22227 (setq s (concat (substring s 0 b)
22228 (substring s (or (next-single-property-change
22229 b 'org-cwidth s)
22230 (length s))))))
22231 (setq l (string-width s) b -1)
22232 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22233 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22236 (defun org-shorten-string (s maxlength)
22237 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22238 If the string is shorter or has length MAXLENGTH, just return the
22239 original string. If it is longer, the functions finds a space in the
22240 string, breaks this string off at that locations and adds three dots
22241 as ellipsis. Including the ellipsis, the string will not be longer
22242 than MAXLENGTH. If finding a good breaking point in the string does
22243 not work, the string is just chopped off in the middle of a word
22244 if necessary."
22245 (if (<= (length s) maxlength)
22247 (let* ((n (max (- maxlength 4) 1))
22248 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22249 (if (string-match re s)
22250 (concat (match-string 1 s) "...")
22251 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22253 (defun org-get-indentation (&optional line)
22254 "Get the indentation of the current line, interpreting tabs.
22255 When LINE is given, assume it represents a line and compute its indentation."
22256 (if line
22257 (when (string-match "^ *" (org-remove-tabs line))
22258 (match-end 0))
22259 (save-excursion
22260 (beginning-of-line 1)
22261 (skip-chars-forward " \t")
22262 (current-column))))
22264 (defun org-get-string-indentation (s)
22265 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22266 (let ((n -1) (i 0) (w tab-width) c)
22267 (catch 'exit
22268 (while (< (setq n (1+ n)) (length s))
22269 (setq c (aref s n))
22270 (cond ((= c ?\ ) (setq i (1+ i)))
22271 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22272 (t (throw 'exit t)))))
22275 (defun org-remove-tabs (s &optional width)
22276 "Replace tabulators in S with spaces.
22277 Assumes that s is a single line, starting in column 0."
22278 (setq width (or width tab-width))
22279 (while (string-match "\t" s)
22280 (setq s (replace-match
22281 (make-string
22282 (- (* width (/ (+ (match-beginning 0) width) width))
22283 (match-beginning 0)) ?\ )
22284 t t s)))
22287 (defun org-fix-indentation (line ind)
22288 "Fix indentation in LINE.
22289 IND is a cons cell with target and minimum indentation.
22290 If the current indentation in LINE is smaller than the minimum,
22291 leave it alone. If it is larger than ind, set it to the target."
22292 (let* ((l (org-remove-tabs line))
22293 (i (org-get-indentation l))
22294 (i1 (car ind)) (i2 (cdr ind)))
22295 (when (>= i i2) (setq l (substring line i2)))
22296 (if (> i1 0)
22297 (concat (make-string i1 ?\ ) l)
22298 l)))
22300 (defun org-remove-indentation (code &optional n)
22301 "Remove maximum common indentation in string CODE and return it.
22302 N may optionally be the number of columns to remove. Return CODE
22303 as-is if removal failed."
22304 (with-temp-buffer
22305 (insert code)
22306 (if (org-do-remove-indentation n) (buffer-string) code)))
22308 (defun org-do-remove-indentation (&optional n)
22309 "Remove the maximum common indentation from the buffer.
22310 When optional argument N is a positive integer, remove exactly
22311 that much characters from indentation, if possible. Return nil
22312 if it fails."
22313 (catch :exit
22314 (goto-char (point-min))
22315 ;; Find maximum common indentation, if not specified.
22316 (let ((n (or n
22317 (let ((min-ind (point-max)))
22318 (save-excursion
22319 (while (re-search-forward "^[ \t]*\\S-" nil t)
22320 (let ((ind (1- (current-column))))
22321 (if (zerop ind) (throw :exit nil)
22322 (setq min-ind (min min-ind ind))))))
22323 min-ind))))
22324 (if (zerop n) (throw :exit nil)
22325 ;; Remove exactly N indentation, but give up if not possible.
22326 (while (not (eobp))
22327 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22328 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22329 ((< ind n) (throw :exit nil))
22330 (t (indent-line-to (- ind n))))
22331 (forward-line)))
22332 ;; Signal success.
22333 t))))
22335 (defun org-fill-template (template alist)
22336 "Find each %key of ALIST in TEMPLATE and replace it."
22337 (let ((case-fold-search nil))
22338 (dolist (entry (sort (copy-sequence alist)
22339 (lambda (a b) (< (length (car a)) (length (car b))))))
22340 (setq template
22341 (replace-regexp-in-string
22342 (concat "%" (regexp-quote (car entry)))
22343 (or (cdr entry) "") template t t)))
22344 template))
22346 (defun org-base-buffer (buffer)
22347 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22348 (if (not buffer)
22349 buffer
22350 (or (buffer-base-buffer buffer)
22351 buffer)))
22353 (defun org-wrap (string &optional width lines)
22354 "Wrap string to either a number of lines, or a width in characters.
22355 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22356 that costs. If there is a word longer than WIDTH, the text is actually
22357 wrapped to the length of that word.
22358 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22359 many lines, whatever width that takes.
22360 The return value is a list of lines, without newlines at the end."
22361 (let* ((words (org-split-string string "[ \t\n]+"))
22362 (maxword (apply 'max (mapcar 'org-string-width words)))
22363 w ll)
22364 (cond (width
22365 (org-do-wrap words (max maxword width)))
22366 (lines
22367 (setq w maxword)
22368 (setq ll (org-do-wrap words maxword))
22369 (if (<= (length ll) lines)
22371 (setq ll words)
22372 (while (> (length ll) lines)
22373 (setq w (1+ w))
22374 (setq ll (org-do-wrap words w)))
22375 ll))
22376 (t (error "Cannot wrap this")))))
22378 (defun org-do-wrap (words width)
22379 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22380 (let (lines line)
22381 (while words
22382 (setq line (pop words))
22383 (while (and words (< (+ (length line) (length (car words))) width))
22384 (setq line (concat line " " (pop words))))
22385 (setq lines (push line lines)))
22386 (nreverse lines)))
22388 (defun org-split-string (string &optional separators)
22389 "Splits STRING into substrings at SEPARATORS.
22390 SEPARATORS is a regular expression.
22391 No empty strings are returned if there are matches at the beginning
22392 and end of string."
22393 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22394 (let ((start 0) notfirst list)
22395 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22396 (if (and notfirst
22397 (= start (match-beginning 0))
22398 (< start (length string)))
22399 (1+ start) start))
22400 (< (match-beginning 0) (length string)))
22401 (setq notfirst t)
22402 (or (eq (match-beginning 0) 0)
22403 (and (eq (match-beginning 0) (match-end 0))
22404 (eq (match-beginning 0) start))
22405 (push (substring string start (match-beginning 0)) list))
22406 (setq start (match-end 0)))
22407 (or (eq start (length string))
22408 (push (substring string start) list))
22409 (nreverse list)))
22411 (defun org-quote-vert (s)
22412 "Replace \"|\" with \"\\vert\"."
22413 (while (string-match "|" s)
22414 (setq s (replace-match "\\vert" t t s)))
22417 (defun org-uuidgen-p (s)
22418 "Is S an ID created by UUIDGEN?"
22419 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22421 (defun org-in-src-block-p (&optional inside)
22422 "Whether point is in a code source block.
22423 When INSIDE is non-nil, don't consider we are within a src block
22424 when point is at #+BEGIN_SRC or #+END_SRC."
22425 (let ((case-fold-search t))
22426 (or (and (eq (get-char-property (point) 'src-block) t))
22427 (and (not inside)
22428 (save-match-data
22429 (save-excursion
22430 (beginning-of-line)
22431 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22433 (defun org-context ()
22434 "Return a list of contexts of the current cursor position.
22435 If several contexts apply, all are returned.
22436 Each context entry is a list with a symbol naming the context, and
22437 two positions indicating start and end of the context. Possible
22438 contexts are:
22440 :headline anywhere in a headline
22441 :headline-stars on the leading stars in a headline
22442 :todo-keyword on a TODO keyword (including DONE) in a headline
22443 :tags on the TAGS in a headline
22444 :priority on the priority cookie in a headline
22445 :item on the first line of a plain list item
22446 :item-bullet on the bullet/number of a plain list item
22447 :checkbox on the checkbox in a plain list item
22448 :table in an org-mode table
22449 :table-special on a special filed in a table
22450 :table-table in a table.el table
22451 :clocktable in a clocktable
22452 :src-block in a source block
22453 :link on a hyperlink
22454 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22455 :target on a <<target>>
22456 :radio-target on a <<<radio-target>>>
22457 :latex-fragment on a LaTeX fragment
22458 :latex-preview on a LaTeX fragment with overlaid preview image
22460 This function expects the position to be visible because it uses font-lock
22461 faces as a help to recognize the following contexts: :table-special, :link,
22462 and :keyword."
22463 (let* ((f (get-text-property (point) 'face))
22464 (faces (if (listp f) f (list f)))
22465 (case-fold-search t)
22466 (p (point)) clist o)
22467 ;; First the large context
22468 (cond
22469 ((org-at-heading-p t)
22470 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22471 (when (progn
22472 (beginning-of-line 1)
22473 (looking-at org-todo-line-tags-regexp))
22474 (push (org-point-in-group p 1 :headline-stars) clist)
22475 (push (org-point-in-group p 2 :todo-keyword) clist)
22476 (push (org-point-in-group p 4 :tags) clist))
22477 (goto-char p)
22478 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22479 (when (looking-at "\\[#[A-Z0-9]\\]")
22480 (push (org-point-in-group p 0 :priority) clist)))
22482 ((org-at-item-p)
22483 (push (org-point-in-group p 2 :item-bullet) clist)
22484 (push (list :item (point-at-bol)
22485 (save-excursion (org-end-of-item) (point)))
22486 clist)
22487 (and (org-at-item-checkbox-p)
22488 (push (org-point-in-group p 0 :checkbox) clist)))
22490 ((org-at-table-p)
22491 (push (list :table (org-table-begin) (org-table-end)) clist)
22492 (when (memq 'org-formula faces)
22493 (push (list :table-special
22494 (previous-single-property-change p 'face)
22495 (next-single-property-change p 'face)) clist)))
22496 ((org-at-table-p 'any)
22497 (push (list :table-table) clist)))
22498 (goto-char p)
22500 (let ((case-fold-search t))
22501 ;; New the "medium" contexts: clocktables, source blocks
22502 (cond ((org-in-clocktable-p)
22503 (push (list :clocktable
22504 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22505 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22506 (match-beginning 1))
22507 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22508 (match-end 0))) clist))
22509 ((org-in-src-block-p)
22510 (push (list :src-block
22511 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22512 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22513 (match-beginning 1))
22514 (and (search-forward "#+END_SRC" nil t)
22515 (match-beginning 0))) clist))))
22516 (goto-char p)
22518 ;; Now the small context
22519 (cond
22520 ((org-at-timestamp-p)
22521 (push (org-point-in-group p 0 :timestamp) clist))
22522 ((memq 'org-link faces)
22523 (push (list :link
22524 (previous-single-property-change p 'face)
22525 (next-single-property-change p 'face)) clist))
22526 ((memq 'org-special-keyword faces)
22527 (push (list :keyword
22528 (previous-single-property-change p 'face)
22529 (next-single-property-change p 'face)) clist))
22530 ((org-at-target-p)
22531 (push (org-point-in-group p 0 :target) clist)
22532 (goto-char (1- (match-beginning 0)))
22533 (when (looking-at org-radio-target-regexp)
22534 (push (org-point-in-group p 0 :radio-target) clist))
22535 (goto-char p))
22536 ((setq o (cl-some
22537 (lambda (o)
22538 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22540 (overlays-at (point))))
22541 (push (list :latex-fragment
22542 (overlay-start o) (overlay-end o)) clist)
22543 (push (list :latex-preview
22544 (overlay-start o) (overlay-end o)) clist))
22545 ((org-inside-LaTeX-fragment-p)
22546 ;; FIXME: positions wrong.
22547 (push (list :latex-fragment (point) (point)) clist)))
22549 (setq clist (nreverse (delq nil clist)))
22550 clist))
22552 (defun org-in-regexp (regexp &optional nlines visually)
22553 "Check if point is inside a match of REGEXP.
22555 Normally only the current line is checked, but you can include
22556 NLINES extra lines around point into the search. If VISUALLY is
22557 set, require that the cursor is not after the match but really
22558 on, so that the block visually is on the match.
22560 Return nil or a cons cell (BEG . END) where BEG and END are,
22561 respectively, the positions at the beginning and the end of the
22562 match."
22563 (catch :exit
22564 (let ((pos (point))
22565 (eol (line-end-position (if nlines (1+ nlines) 1))))
22566 (save-excursion
22567 (beginning-of-line (- 1 (or nlines 0)))
22568 (while (and (re-search-forward regexp eol t)
22569 (<= (match-beginning 0) pos))
22570 (let ((end (match-end 0)))
22571 (when (or (> end pos) (and (= end pos) (not visually)))
22572 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22573 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22574 "Org mode 8.3")
22576 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22577 "Non-nil when point is between matches of START-RE and END-RE.
22579 Also return a non-nil value when point is on one of the matches.
22581 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22582 buffer positions. Default values are the positions of headlines
22583 surrounding the point.
22585 The functions returns a cons cell whose car (resp. cdr) is the
22586 position before START-RE (resp. after END-RE)."
22587 (save-match-data
22588 (let ((pos (point))
22589 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22590 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22591 beg end)
22592 (save-excursion
22593 ;; Point is on a block when on START-RE or if START-RE can be
22594 ;; found before it...
22595 (and (or (org-in-regexp start-re)
22596 (re-search-backward start-re limit-up t))
22597 (setq beg (match-beginning 0))
22598 ;; ... and END-RE after it...
22599 (goto-char (match-end 0))
22600 (re-search-forward end-re limit-down t)
22601 (> (setq end (match-end 0)) pos)
22602 ;; ... without another START-RE in-between.
22603 (goto-char (match-beginning 0))
22604 (not (re-search-backward start-re (1+ beg) t))
22605 ;; Return value.
22606 (cons beg end))))))
22608 (defun org-in-block-p (names)
22609 "Non-nil when point belongs to a block whose name belongs to NAMES.
22611 NAMES is a list of strings containing names of blocks.
22613 Return first block name matched, or nil. Beware that in case of
22614 nested blocks, the returned name may not belong to the closest
22615 block from point."
22616 (save-match-data
22617 (catch 'exit
22618 (let ((case-fold-search t)
22619 (lim-up (save-excursion (outline-previous-heading)))
22620 (lim-down (save-excursion (outline-next-heading))))
22621 (dolist (name names)
22622 (let ((n (regexp-quote name)))
22623 (when (org-between-regexps-p
22624 (concat "^[ \t]*#\\+begin_" n)
22625 (concat "^[ \t]*#\\+end_" n)
22626 lim-up lim-down)
22627 (throw 'exit n)))))
22628 nil)))
22630 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22631 "Call `multi-occur' with buffers for all agenda files."
22632 (interactive "sOrg-files matching: ")
22633 (let* ((files (org-agenda-files))
22634 (tnames (mapcar #'file-truename files))
22635 (extra org-agenda-text-search-extra-files))
22636 (when (eq (car extra) 'agenda-archives)
22637 (setq extra (cdr extra))
22638 (setq files (org-add-archive-files files)))
22639 (dolist (f extra)
22640 (unless (member (file-truename f) tnames)
22641 (unless (member f files) (setq files (append files (list f))))
22642 (setq tnames (append tnames (list (file-truename f))))))
22643 (multi-occur
22644 (mapcar (lambda (x)
22645 (with-current-buffer
22646 ;; FIXME: Why not just (find-file-noselect x)?
22647 ;; Is it to avoid the "revert buffer" prompt?
22648 (or (get-file-buffer x) (find-file-noselect x))
22649 (widen)
22650 (current-buffer)))
22651 files)
22652 regexp)))
22654 (if (boundp 'occur-mode-find-occurrence-hook)
22655 ;; Emacs 23
22656 (add-hook 'occur-mode-find-occurrence-hook
22657 (lambda ()
22658 (when (derived-mode-p 'org-mode)
22659 (org-reveal))))
22660 ;; Emacs 22
22661 (defadvice occur-mode-goto-occurrence
22662 (after org-occur-reveal activate)
22663 (and (derived-mode-p 'org-mode) (org-reveal)))
22664 (defadvice occur-mode-goto-occurrence-other-window
22665 (after org-occur-reveal activate)
22666 (and (derived-mode-p 'org-mode) (org-reveal)))
22667 (defadvice occur-mode-display-occurrence
22668 (after org-occur-reveal activate)
22669 (when (derived-mode-p 'org-mode)
22670 (let ((pos (occur-mode-find-occurrence)))
22671 (with-current-buffer (marker-buffer pos)
22672 (save-excursion
22673 (goto-char pos)
22674 (org-reveal)))))))
22676 (defun org-occur-link-in-agenda-files ()
22677 "Create a link and search for it in the agendas.
22678 The link is not stored in `org-stored-links', it is just created
22679 for the search purpose."
22680 (interactive)
22681 (let ((link (condition-case nil
22682 (org-store-link nil)
22683 (error "Unable to create a link to here"))))
22684 (org-occur-in-agenda-files (regexp-quote link))))
22686 (defun org-reverse-string (string)
22687 "Return the reverse of STRING."
22688 (apply 'string (reverse (string-to-list string))))
22690 ;; defsubst org-uniquify must be defined before first use
22692 (defun org-uniquify-alist (alist)
22693 "Merge elements of ALIST with the same key.
22695 For example, in this alist:
22697 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22698 => \\='((a 1 3) (b 2))
22700 merge (a 1) and (a 3) into (a 1 3).
22702 The function returns the new ALIST."
22703 (let (rtn)
22704 (dolist (e alist rtn)
22705 (let (n)
22706 (if (not (assoc (car e) rtn))
22707 (push e rtn)
22708 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22709 (setq rtn (assq-delete-all (car e) rtn))
22710 (push n rtn))))))
22712 (defun org-delete-all (elts list)
22713 "Remove all elements in ELTS from LIST."
22714 (while elts
22715 (setq list (delete (pop elts) list)))
22716 list)
22718 (defun org-back-over-empty-lines ()
22719 "Move backwards over whitespace, to the beginning of the first empty line.
22720 Returns the number of empty lines passed."
22721 (let ((pos (point)))
22722 (if (cdr (assoc 'heading org-blank-before-new-entry))
22723 (skip-chars-backward " \t\n\r")
22724 (unless (eobp)
22725 (forward-line -1)))
22726 (beginning-of-line 2)
22727 (goto-char (min (point) pos))
22728 (count-lines (point) pos)))
22730 (defun org-skip-whitespace ()
22731 (skip-chars-forward " \t\n\r"))
22733 (defun org-point-in-group (point group &optional context)
22734 "Check if POINT is in match-group GROUP.
22735 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22736 match. If the match group does not exist or point is not inside it,
22737 return nil."
22738 (and (match-beginning group)
22739 (>= point (match-beginning group))
22740 (<= point (match-end group))
22741 (if context
22742 (list context (match-beginning group) (match-end group))
22743 t)))
22745 (defun org-switch-to-buffer-other-window (&rest args)
22746 "Switch to buffer in a second window on the current frame.
22747 In particular, do not allow pop-up frames.
22748 Returns the newly created buffer."
22749 (org-no-popups
22750 (apply 'switch-to-buffer-other-window args)))
22752 (defun org-combine-plists (&rest plists)
22753 "Create a single property list from all plists in PLISTS.
22754 The process starts by copying the first list, and then setting properties
22755 from the other lists. Settings in the last list are the most significant
22756 ones and overrule settings in the other lists."
22757 (let ((rtn (copy-sequence (pop plists)))
22758 p v ls)
22759 (while plists
22760 (setq ls (pop plists))
22761 (while ls
22762 (setq p (pop ls) v (pop ls))
22763 (setq rtn (plist-put rtn p v))))
22764 rtn))
22766 (defun org-replace-escapes (string table)
22767 "Replace %-escapes in STRING with values in TABLE.
22768 TABLE is an association list with keys like \"%a\" and string values.
22769 The sequences in STRING may contain normal field width and padding information,
22770 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22771 so values can contain further %-escapes if they are define later in TABLE."
22772 (let ((tbl (copy-alist table))
22773 (case-fold-search nil)
22774 (pchg 0)
22775 re rpl)
22776 (dolist (e tbl)
22777 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22778 (when (and (cdr e) (string-match re (cdr e)))
22779 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22780 (safe "SREF"))
22781 (add-text-properties 0 3 (list 'sref sref) safe)
22782 (setcdr e (replace-match safe t t (cdr e)))))
22783 (while (string-match re string)
22784 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22785 (cdr e)))
22786 (setq string (replace-match rpl t t string))))
22787 (while (setq pchg (next-property-change pchg string))
22788 (let ((sref (get-text-property pchg 'sref string)))
22789 (when (and sref (string-match "SREF" string pchg))
22790 (setq string (replace-match sref t t string)))))
22791 string))
22793 (defun org-sublist (list start end)
22794 "Return a section of LIST, from START to END.
22796 Counting starts at 1."
22797 (cl-subseq list (1- start) end))
22798 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22800 (defun org-find-base-buffer-visiting (file)
22801 "Like `find-buffer-visiting' but always return the base buffer and
22802 not an indirect buffer."
22803 (let ((buf (or (get-file-buffer file)
22804 (find-buffer-visiting file))))
22805 (if buf
22806 (or (buffer-base-buffer buf) buf)
22807 nil)))
22809 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22810 "Org 9.0")
22812 ;;; TODO: Only called once, from ox-odt which should probably use
22813 ;;; org-export-inline-image-p or something.
22814 (defun org-file-image-p (file)
22815 "Return non-nil if FILE is an image."
22816 (save-match-data
22817 (string-match (image-file-name-regexp) file)))
22819 (defun org-get-cursor-date (&optional with-time)
22820 "Return the date at cursor in as a time.
22821 This works in the calendar and in the agenda, anywhere else it just
22822 returns the current time.
22823 If WITH-TIME is non-nil, returns the time of the event at point (in
22824 the agenda) or the current time of the day."
22825 (let (date day defd tp hod mod)
22826 (when with-time
22827 (setq tp (get-text-property (point) 'time))
22828 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22829 (setq hod (string-to-number (match-string 1 tp))
22830 mod (string-to-number (match-string 2 tp))))
22831 (or tp (let ((now (decode-time)))
22832 (setq hod (nth 2 now)
22833 mod (nth 1 now)))))
22834 (cond
22835 ((eq major-mode 'calendar-mode)
22836 (setq date (calendar-cursor-to-date)
22837 defd (encode-time 0 (or mod 0) (or hod 0)
22838 (nth 1 date) (nth 0 date) (nth 2 date))))
22839 ((eq major-mode 'org-agenda-mode)
22840 (setq day (get-text-property (point) 'day))
22841 (when day
22842 (setq date (calendar-gregorian-from-absolute day)
22843 defd (encode-time 0 (or mod 0) (or hod 0)
22844 (nth 1 date) (nth 0 date) (nth 2 date))))))
22845 (or defd (current-time))))
22847 (defun org-mark-subtree (&optional up)
22848 "Mark the current subtree.
22849 This puts point at the start of the current subtree, and mark at
22850 the end. If a numeric prefix UP is given, move up into the
22851 hierarchy of headlines by UP levels before marking the subtree."
22852 (interactive "P")
22853 (org-with-limited-levels
22854 (cond ((org-at-heading-p) (beginning-of-line))
22855 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22856 (t (outline-previous-visible-heading 1))))
22857 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22858 (if (org-called-interactively-p 'any)
22859 (call-interactively 'org-mark-element)
22860 (org-mark-element)))
22862 (defun org-file-newer-than-p (file time)
22863 "Non-nil if FILE is newer than TIME.
22864 FILE is a filename, as a string, TIME is a list of integers, as
22865 returned by, e.g., `current-time'."
22866 (and (file-exists-p file)
22867 ;; Only compare times up to whole seconds as some file-systems
22868 ;; (e.g. HFS+) do not retain any finer granularity. As
22869 ;; a consequence, make sure we return non-nil when the two
22870 ;; times are equal.
22871 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22872 (cl-subseq time 0 2)))))
22874 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22875 "Compile a SOURCE file using PROCESS.
22877 PROCESS is either a function or a list of shell commands, as
22878 strings. EXT is a file extension, without the leading dot, as
22879 a string. It is used to check if the process actually succeeded.
22881 PROCESS must create a file with the same base name and directory
22882 as SOURCE, but ending with EXT. The function then returns its
22883 filename. Otherwise, it raises an error. The error message can
22884 then be refined by providing string ERR-MSG, which is appended to
22885 the standard message.
22887 If PROCESS is a function, it is called with a single argument:
22888 the SOURCE file.
22890 If it is a list of commands, each of them is called using
22891 `shell-command'. By default, in each command, %b, %f, %F and %o
22892 are replaced with, respectively, SOURCE base name, name, full
22893 name and directory. It is possible, however, to use more
22894 place-holders by specifying them in optional argument SPEC, as an
22895 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22897 When PROCESS is a list of commands, optional argument LOG-BUF can
22898 be set to a buffer or a buffer name. `shell-command' then uses
22899 it for output.
22901 `default-directory' is set to SOURCE directory during the whole
22902 process."
22903 (let* ((source-name (file-name-nondirectory source))
22904 (base-name (file-name-sans-extension source-name))
22905 (full-name (file-truename source))
22906 (out-dir (file-name-directory source))
22907 ;; Properly set working directory for compilation.
22908 (default-directory (file-name-directory full-name))
22909 (time (current-time))
22910 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22911 (save-window-excursion
22912 (pcase process
22913 ((pred functionp) (funcall process (shell-quote-argument source)))
22914 ((pred consp)
22915 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22916 (spec (append spec
22917 `((?b . ,(shell-quote-argument base-name))
22918 (?f . ,(shell-quote-argument source-name))
22919 (?F . ,(shell-quote-argument full-name))
22920 (?o . ,(shell-quote-argument out-dir))))))
22921 (dolist (command process)
22922 (shell-command (format-spec command spec) log-buf))))
22923 (_ (error "No valid command to process %S%s" source err-msg)))
22924 ;; Check for process failure.
22925 (let ((output (concat out-dir base-name "." ext)))
22926 (unless (org-file-newer-than-p output time)
22927 (error (format "File %S wasn't produced%s" output err-msg)))
22928 output))))
22930 ;;; Indentation
22932 (defun org--get-expected-indentation (element contentsp)
22933 "Expected indentation column for current line, according to ELEMENT.
22934 ELEMENT is an element containing point. CONTENTSP is non-nil
22935 when indentation is to be computed according to contents of
22936 ELEMENT."
22937 (let ((type (org-element-type element))
22938 (start (org-element-property :begin element))
22939 (post-affiliated (org-element-property :post-affiliated element)))
22940 (org-with-wide-buffer
22941 (cond
22942 (contentsp
22943 (cl-case type
22944 ((diary-sexp footnote-definition) 0)
22945 ((headline inlinetask nil)
22946 (if (not org-adapt-indentation) 0
22947 (let ((level (org-current-level)))
22948 (if level (1+ level) 0))))
22949 ((item plain-list) (org-list-item-body-column post-affiliated))
22951 (goto-char start)
22952 (org-get-indentation))))
22953 ((memq type '(headline inlinetask nil))
22954 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22955 (org--get-expected-indentation element t)
22957 ((memq type '(diary-sexp footnote-definition)) 0)
22958 ;; First paragraph of a footnote definition or an item.
22959 ;; Indent like parent.
22960 ((< (line-beginning-position) start)
22961 (org--get-expected-indentation
22962 (org-element-property :parent element) t))
22963 ;; At first line: indent according to previous sibling, if any,
22964 ;; ignoring footnote definitions and inline tasks, or parent's
22965 ;; contents.
22966 ((= (line-beginning-position) start)
22967 (catch 'exit
22968 (while t
22969 (if (= (point-min) start) (throw 'exit 0)
22970 (goto-char (1- start))
22971 (let* ((previous (org-element-at-point))
22972 (parent previous))
22973 (while (and parent (<= (org-element-property :end parent) start))
22974 (setq previous parent
22975 parent (org-element-property :parent parent)))
22976 (cond
22977 ((not previous) (throw 'exit 0))
22978 ((> (org-element-property :end previous) start)
22979 (throw 'exit (org--get-expected-indentation previous t)))
22980 ((memq (org-element-type previous)
22981 '(footnote-definition inlinetask))
22982 (setq start (org-element-property :begin previous)))
22983 (t (goto-char (org-element-property :begin previous))
22984 (throw 'exit
22985 (if (bolp) (org-get-indentation)
22986 ;; At first paragraph in an item or
22987 ;; a footnote definition.
22988 (org--get-expected-indentation
22989 (org-element-property :parent previous) t))))))))))
22990 ;; Otherwise, move to the first non-blank line above.
22992 (beginning-of-line)
22993 (let ((pos (point)))
22994 (skip-chars-backward " \r\t\n")
22995 (cond
22996 ;; Two blank lines end a footnote definition or a plain
22997 ;; list. When we indent an empty line after them, the
22998 ;; containing list or footnote definition is over, so it
22999 ;; qualifies as a previous sibling. Therefore, we indent
23000 ;; like its first line.
23001 ((and (memq type '(footnote-definition plain-list))
23002 (> (count-lines (point) pos) 2))
23003 (goto-char start)
23004 (org-get-indentation))
23005 ;; Line above is the first one of a paragraph at the
23006 ;; beginning of an item or a footnote definition. Indent
23007 ;; like parent.
23008 ((< (line-beginning-position) start)
23009 (org--get-expected-indentation
23010 (org-element-property :parent element) t))
23011 ;; Line above is the beginning of an element, i.e., point
23012 ;; was originally on the blank lines between element's start
23013 ;; and contents.
23014 ((= (line-beginning-position) post-affiliated)
23015 (org--get-expected-indentation element t))
23016 ;; POS is after contents in a greater element. Indent like
23017 ;; the beginning of the element.
23019 ;; As a special case, if point is at the end of a footnote
23020 ;; definition or an item, indent like the very last element
23021 ;; within. If that last element is an item, indent like its
23022 ;; contents.
23023 ((and (not (eq type 'paragraph))
23024 (let ((cend (org-element-property :contents-end element)))
23025 (and cend (<= cend pos))))
23026 (if (memq type '(footnote-definition item plain-list))
23027 (let ((last (org-element-at-point)))
23028 (org--get-expected-indentation
23029 last (eq (org-element-type last) 'item)))
23030 (goto-char start)
23031 (org-get-indentation)))
23032 ;; In any other case, indent like the current line.
23033 (t (org-get-indentation)))))))))
23035 (defun org--align-node-property ()
23036 "Align node property at point.
23037 Alignment is done according to `org-property-format', which see."
23038 (when (save-excursion
23039 (beginning-of-line)
23040 (looking-at org-property-re))
23041 (replace-match
23042 (concat (match-string 4)
23043 (org-trim
23044 (format org-property-format (match-string 1) (match-string 3))))
23045 t t)))
23047 (defun org-indent-line ()
23048 "Indent line depending on context.
23050 Indentation is done according to the following rules:
23052 - Footnote definitions, diary sexps, headlines and inline tasks
23053 have to start at column 0.
23055 - On the very first line of an element, consider, in order, the
23056 next rules until one matches:
23058 1. If there's a sibling element before, ignoring footnote
23059 definitions and inline tasks, indent like its first line.
23061 2. If element has a parent, indent like its contents. More
23062 precisely, if parent is an item, indent after the
23063 description part, if any, or the bullet (see
23064 `org-list-description-max-indent'). Else, indent like
23065 parent's first line.
23067 3. Otherwise, indent relatively to current level, if
23068 `org-adapt-indentation' is non-nil, or to left margin.
23070 - On a blank line at the end of an element, indent according to
23071 the type of the element. More precisely
23073 1. If element is a plain list, an item, or a footnote
23074 definition, indent like the very last element within.
23076 2. If element is a paragraph, indent like its last non blank
23077 line.
23079 3. Otherwise, indent like its very first line.
23081 - In the code part of a source block, use language major mode
23082 to indent current line if `org-src-tab-acts-natively' is
23083 non-nil. If it is nil, do nothing.
23085 - Otherwise, indent like the first non-blank line above.
23087 The function doesn't indent an item as it could break the whole
23088 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
23089 \\[org-shiftmetaright].
23091 Also align node properties according to `org-property-format'."
23092 (interactive)
23093 (cond
23094 (orgstruct-is-++
23095 (let ((indent-line-function
23096 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
23097 (indent-according-to-mode)))
23098 ((org-at-heading-p) 'noindent)
23100 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
23101 (type (org-element-type element)))
23102 (cond ((and (memq type '(plain-list item))
23103 (= (line-beginning-position)
23104 (org-element-property :post-affiliated element)))
23105 'noindent)
23106 ((and (eq type 'src-block)
23107 org-src-tab-acts-natively
23108 (> (line-beginning-position)
23109 (org-element-property :post-affiliated element))
23110 (< (line-beginning-position)
23111 (org-with-wide-buffer
23112 (goto-char (org-element-property :end element))
23113 (skip-chars-backward " \r\t\n")
23114 (line-beginning-position))))
23115 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23117 (let ((column (org--get-expected-indentation element nil)))
23118 ;; Preserve current column.
23119 (if (<= (current-column) (current-indentation))
23120 (indent-line-to column)
23121 (save-excursion (indent-line-to column))))
23122 ;; Align node property. Also preserve current column.
23123 (when (eq type 'node-property)
23124 (let ((column (current-column)))
23125 (org--align-node-property)
23126 (org-move-to-column column)))))))))
23128 (defun org-indent-region (start end)
23129 "Indent each non-blank line in the region.
23130 Called from a program, START and END specify the region to
23131 indent. The function will not indent contents of example blocks,
23132 verse blocks and export blocks as leading white spaces are
23133 assumed to be significant there."
23134 (interactive "r")
23135 (save-excursion
23136 (goto-char start)
23137 (skip-chars-forward " \r\t\n")
23138 (unless (eobp) (beginning-of-line))
23139 (let ((indent-to
23140 (lambda (ind pos)
23141 ;; Set IND as indentation for all lines between point and
23142 ;; POS. Blank lines are ignored. Leave point after POS
23143 ;; once done.
23144 (let ((limit (copy-marker pos)))
23145 (while (< (point) limit)
23146 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23147 (forward-line))
23148 (set-marker limit nil))))
23149 (end (copy-marker end)))
23150 (while (< (point) end)
23151 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23152 (let* ((element (org-element-at-point))
23153 (type (org-element-type element))
23154 (element-end (copy-marker (org-element-property :end element)))
23155 (ind (org--get-expected-indentation element nil)))
23156 (cond
23157 ((or (memq type '(paragraph table table-row))
23158 (not (or (org-element-property :contents-begin element)
23159 (memq type
23160 '(example-block export-block src-block)))))
23161 ;; Elements here are indented as a single block. Also
23162 ;; align node properties.
23163 (when (eq type 'node-property)
23164 (org--align-node-property)
23165 (beginning-of-line))
23166 (funcall indent-to ind (min element-end end)))
23168 ;; Elements in this category consist of three parts:
23169 ;; before the contents, the contents, and after the
23170 ;; contents. The contents are treated specially,
23171 ;; according to the element type, or not indented at
23172 ;; all. Other parts are indented as a single block.
23173 (let* ((post (copy-marker
23174 (org-element-property :post-affiliated element)))
23175 (cbeg
23176 (copy-marker
23177 (cond
23178 ((not (org-element-property :contents-begin element))
23179 ;; Fake contents for source blocks.
23180 (org-with-wide-buffer
23181 (goto-char post)
23182 (forward-line)
23183 (point)))
23184 ((memq type '(footnote-definition item plain-list))
23185 ;; Contents in these elements could start on
23186 ;; the same line as the beginning of the
23187 ;; element. Make sure we start indenting
23188 ;; from the second line.
23189 (org-with-wide-buffer
23190 (goto-char post)
23191 (end-of-line)
23192 (skip-chars-forward " \r\t\n")
23193 (if (eobp) (point) (line-beginning-position))))
23194 (t (org-element-property :contents-begin element)))))
23195 (cend (copy-marker
23196 (or (org-element-property :contents-end element)
23197 ;; Fake contents for source blocks.
23198 (org-with-wide-buffer
23199 (goto-char element-end)
23200 (skip-chars-backward " \r\t\n")
23201 (line-beginning-position)))
23202 t)))
23203 ;; Do not change items indentation individually as it
23204 ;; might break the list as a whole. On the other
23205 ;; hand, when at a plain list, indent it as a whole.
23206 (cond ((eq type 'plain-list)
23207 (let ((offset (- ind (org-get-indentation))))
23208 (unless (zerop offset)
23209 (indent-rigidly (org-element-property :begin element)
23210 (org-element-property :end element)
23211 offset))
23212 (goto-char cbeg)))
23213 ((eq type 'item) (goto-char cbeg))
23214 (t (funcall indent-to ind (min cbeg end))))
23215 (when (< (point) end)
23216 (cl-case type
23217 ((example-block export-block verse-block))
23218 (src-block
23219 ;; In a source block, indent source code
23220 ;; according to language major mode, but only if
23221 ;; `org-src-tab-acts-natively' is non-nil.
23222 (when (and (< (point) end) org-src-tab-acts-natively)
23223 (ignore-errors
23224 (org-babel-do-in-edit-buffer
23225 (indent-region (point-min) (point-max))))))
23226 (t (org-indent-region (point) (min cend end))))
23227 (goto-char (min cend end))
23228 (when (< (point) end)
23229 (funcall indent-to ind (min element-end end))))
23230 (set-marker post nil)
23231 (set-marker cbeg nil)
23232 (set-marker cend nil))))
23233 (set-marker element-end nil))))
23234 (set-marker end nil))))
23236 (defun org-indent-drawer ()
23237 "Indent the drawer at point."
23238 (interactive)
23239 (unless (save-excursion
23240 (beginning-of-line)
23241 (looking-at-p org-drawer-regexp))
23242 (user-error "Not at a drawer"))
23243 (let ((element (org-element-at-point)))
23244 (unless (memq (org-element-type element) '(drawer property-drawer))
23245 (user-error "Not at a drawer"))
23246 (org-with-wide-buffer
23247 (org-indent-region (org-element-property :begin element)
23248 (org-element-property :end element))))
23249 (message "Drawer at point indented"))
23251 (defun org-indent-block ()
23252 "Indent the block at point."
23253 (interactive)
23254 (unless (save-excursion
23255 (beginning-of-line)
23256 (let ((case-fold-search t))
23257 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23258 (user-error "Not at a block"))
23259 (let ((element (org-element-at-point)))
23260 (unless (memq (org-element-type element)
23261 '(comment-block center-block dynamic-block example-block
23262 export-block quote-block special-block
23263 src-block verse-block))
23264 (user-error "Not at a block"))
23265 (org-with-wide-buffer
23266 (org-indent-region (org-element-property :begin element)
23267 (org-element-property :end element))))
23268 (message "Block at point indented"))
23271 ;;; Filling
23273 ;; We use our own fill-paragraph and auto-fill functions.
23275 ;; `org-fill-paragraph' relies on adaptive filling and context
23276 ;; checking. Appropriate `fill-prefix' is computed with
23277 ;; `org-adaptive-fill-function'.
23279 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23280 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23281 ;; `org-adaptive-fill-function' value. Internally,
23282 ;; `org-comment-line-break-function' breaks the line.
23284 ;; `org-setup-filling' installs filling and auto-filling related
23285 ;; variables during `org-mode' initialization.
23287 (defvar org-element-paragraph-separate) ; org-element.el
23288 (defun org-setup-filling ()
23289 (require 'org-element)
23290 ;; Prevent auto-fill from inserting unwanted new items.
23291 (when (boundp 'fill-nobreak-predicate)
23292 (setq-local
23293 fill-nobreak-predicate
23294 (org-uniquify
23295 (append fill-nobreak-predicate
23296 '(org-fill-line-break-nobreak-p
23297 org-fill-paragraph-with-timestamp-nobreak-p)))))
23298 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23299 (setq-local paragraph-start paragraph-ending)
23300 (setq-local paragraph-separate paragraph-ending))
23301 (setq-local fill-paragraph-function 'org-fill-paragraph)
23302 (setq-local auto-fill-inhibit-regexp nil)
23303 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23304 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23305 (setq-local comment-line-break-function 'org-comment-line-break-function))
23307 (defun org-fill-line-break-nobreak-p ()
23308 "Non-nil when a new line at point would create an Org line break."
23309 (save-excursion
23310 (skip-chars-backward "[ \t]")
23311 (skip-chars-backward "\\\\")
23312 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23314 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23315 "Non-nil when a new line at point would split a timestamp."
23316 (and (org-at-timestamp-p t)
23317 (not (looking-at org-ts-regexp-both))))
23319 (declare-function message-in-body-p "message" ())
23320 (defvar orgtbl-line-start-regexp) ; From org-table.el
23321 (defun org-adaptive-fill-function ()
23322 "Compute a fill prefix for the current line.
23323 Return fill prefix, as a string, or nil if current line isn't
23324 meant to be filled. For convenience, if `adaptive-fill-regexp'
23325 matches in paragraphs or comments, use it."
23326 (catch 'exit
23327 (when (derived-mode-p 'message-mode)
23328 (save-excursion
23329 (beginning-of-line)
23330 (cond ((not (message-in-body-p)) (throw 'exit nil))
23331 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23332 ((looking-at message-cite-prefix-regexp)
23333 (throw 'exit (match-string-no-properties 0)))
23334 ((looking-at org-outline-regexp)
23335 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23336 (org-with-wide-buffer
23337 (unless (org-at-heading-p)
23338 (let* ((p (line-beginning-position))
23339 (element (save-excursion
23340 (beginning-of-line)
23341 (org-element-at-point)))
23342 (type (org-element-type element))
23343 (post-affiliated (org-element-property :post-affiliated element)))
23344 (unless (< p post-affiliated)
23345 (cl-case type
23346 (comment
23347 (save-excursion
23348 (beginning-of-line)
23349 (looking-at "[ \t]*")
23350 (concat (match-string 0) "# ")))
23351 (footnote-definition "")
23352 ((item plain-list)
23353 (make-string (org-list-item-body-column post-affiliated) ?\s))
23354 (paragraph
23355 ;; Fill prefix is usually the same as the current line,
23356 ;; unless the paragraph is at the beginning of an item.
23357 (let ((parent (org-element-property :parent element)))
23358 (save-excursion
23359 (beginning-of-line)
23360 (cond ((eq (org-element-type parent) 'item)
23361 (make-string (org-list-item-body-column
23362 (org-element-property :begin parent))
23363 ?\s))
23364 ((and adaptive-fill-regexp
23365 ;; Locally disable
23366 ;; `adaptive-fill-function' to let
23367 ;; `fill-context-prefix' handle
23368 ;; `adaptive-fill-regexp' variable.
23369 (let (adaptive-fill-function)
23370 (fill-context-prefix
23371 post-affiliated
23372 (org-element-property :end element)))))
23373 ((looking-at "[ \t]+") (match-string 0))
23374 (t "")))))
23375 (comment-block
23376 ;; Only fill contents if P is within block boundaries.
23377 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23378 (forward-line)
23379 (point)))
23380 (cend (save-excursion
23381 (goto-char (org-element-property :end element))
23382 (skip-chars-backward " \r\t\n")
23383 (line-beginning-position))))
23384 (when (and (>= p cbeg) (< p cend))
23385 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23386 (match-string 0)
23387 "")))))))))))
23389 (declare-function message-goto-body "message" ())
23390 (defvar message-cite-prefix-regexp) ; From message.el
23391 (defun org-fill-paragraph (&optional justify)
23392 "Fill element at point, when applicable.
23394 This function only applies to comment blocks, comments, example
23395 blocks and paragraphs. Also, as a special case, re-align table
23396 when point is at one.
23398 If JUSTIFY is non-nil (interactively, with prefix argument),
23399 justify as well. If `sentence-end-double-space' is non-nil, then
23400 period followed by one space does not end a sentence, so don't
23401 break a line there. The variable `fill-column' controls the
23402 width for filling.
23404 For convenience, when point is at a plain list, an item or
23405 a footnote definition, try to fill the first paragraph within."
23406 (interactive)
23407 (if (and (derived-mode-p 'message-mode)
23408 (or (not (message-in-body-p))
23409 (save-excursion (move-beginning-of-line 1)
23410 (looking-at message-cite-prefix-regexp))))
23411 ;; First ensure filling is correct in message-mode.
23412 (let ((fill-paragraph-function
23413 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23414 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23415 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23416 (paragraph-separate
23417 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23418 (fill-paragraph nil))
23419 (with-syntax-table org-mode-transpose-word-syntax-table
23420 ;; Move to end of line in order to get the first paragraph
23421 ;; within a plain list or a footnote definition.
23422 (let ((element (save-excursion
23423 (end-of-line)
23424 (or (ignore-errors (org-element-at-point))
23425 (user-error "An element cannot be parsed line %d"
23426 (line-number-at-pos (point)))))))
23427 ;; First check if point is in a blank line at the beginning of
23428 ;; the buffer. In that case, ignore filling.
23429 (cl-case (org-element-type element)
23430 ;; Use major mode filling function is src blocks.
23431 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23432 ;; Align Org tables, leave table.el tables as-is.
23433 (table-row (org-table-align) t)
23434 (table
23435 (when (eq (org-element-property :type element) 'org)
23436 (save-excursion
23437 (goto-char (org-element-property :post-affiliated element))
23438 (org-table-align)))
23440 (paragraph
23441 ;; Paragraphs may contain `line-break' type objects.
23442 (let ((beg (max (point-min)
23443 (org-element-property :contents-begin element)))
23444 (end (min (point-max)
23445 (org-element-property :contents-end element))))
23446 ;; Do nothing if point is at an affiliated keyword.
23447 (if (< (line-end-position) beg) t
23448 (when (derived-mode-p 'message-mode)
23449 ;; In `message-mode', do not fill following citation
23450 ;; in current paragraph nor text before message body.
23451 (let ((body-start (save-excursion (message-goto-body))))
23452 (when body-start (setq beg (max body-start beg))))
23453 (when (save-excursion
23454 (re-search-forward
23455 (concat "^" message-cite-prefix-regexp) end t))
23456 (setq end (match-beginning 0))))
23457 ;; Fill paragraph, taking line breaks into account.
23458 (save-excursion
23459 (goto-char beg)
23460 (let ((cuts (list beg)))
23461 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23462 (when (eq 'line-break
23463 (org-element-type
23464 (save-excursion (backward-char)
23465 (org-element-context))))
23466 (push (point) cuts)))
23467 (dolist (c (delq end cuts))
23468 (fill-region-as-paragraph c end justify)
23469 (setq end c))))
23470 t)))
23471 ;; Contents of `comment-block' type elements should be
23472 ;; filled as plain text, but only if point is within block
23473 ;; markers.
23474 (comment-block
23475 (let* ((case-fold-search t)
23476 (beg (save-excursion
23477 (goto-char (org-element-property :begin element))
23478 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23479 (forward-line)
23480 (point)))
23481 (end (save-excursion
23482 (goto-char (org-element-property :end element))
23483 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23484 (line-beginning-position))))
23485 (if (or (< (point) beg) (> (point) end)) t
23486 (fill-region-as-paragraph
23487 (save-excursion (end-of-line)
23488 (re-search-backward "^[ \t]*$" beg 'move)
23489 (line-beginning-position))
23490 (save-excursion (beginning-of-line)
23491 (re-search-forward "^[ \t]*$" end 'move)
23492 (line-beginning-position))
23493 justify))))
23494 ;; Fill comments.
23495 (comment
23496 (let ((begin (org-element-property :post-affiliated element))
23497 (end (org-element-property :end element)))
23498 (when (and (>= (point) begin) (<= (point) end))
23499 (let ((begin (save-excursion
23500 (end-of-line)
23501 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23502 (progn (forward-line) (point))
23503 begin)))
23504 (end (save-excursion
23505 (end-of-line)
23506 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23507 (1- (line-beginning-position))
23508 (skip-chars-backward " \r\t\n")
23509 (line-end-position)))))
23510 ;; Do not fill comments when at a blank line.
23511 (when (> end begin)
23512 (let ((fill-prefix
23513 (save-excursion
23514 (beginning-of-line)
23515 (looking-at "[ \t]*#")
23516 (let ((comment-prefix (match-string 0)))
23517 (goto-char (match-end 0))
23518 (if (looking-at adaptive-fill-regexp)
23519 (concat comment-prefix (match-string 0))
23520 (concat comment-prefix " "))))))
23521 (save-excursion
23522 (fill-region-as-paragraph begin end justify))))))
23524 ;; Ignore every other element.
23525 (otherwise t))))))
23527 (defun org-auto-fill-function ()
23528 "Auto-fill function."
23529 ;; Check if auto-filling is meaningful.
23530 (let ((fc (current-fill-column)))
23531 (when (and fc (> (current-column) fc))
23532 (let* ((fill-prefix (org-adaptive-fill-function))
23533 ;; Enforce empty fill prefix, if required. Otherwise, it
23534 ;; will be computed again.
23535 (adaptive-fill-mode (not (equal fill-prefix ""))))
23536 (when fill-prefix (do-auto-fill))))))
23538 (defun org-comment-line-break-function (&optional soft)
23539 "Break line at point and indent, continuing comment if within one.
23540 The inserted newline is marked hard if variable
23541 `use-hard-newlines' is true, unless optional argument SOFT is
23542 non-nil."
23543 (if soft (insert-and-inherit ?\n) (newline 1))
23544 (save-excursion (forward-char -1) (delete-horizontal-space))
23545 (delete-horizontal-space)
23546 (indent-to-left-margin)
23547 (insert-before-markers-and-inherit fill-prefix))
23550 ;;; Fixed Width Areas
23552 (defun org-toggle-fixed-width ()
23553 "Toggle fixed-width markup.
23555 Add or remove fixed-width markup on current line, whenever it
23556 makes sense. Return an error otherwise.
23558 If a region is active and if it contains only fixed-width areas
23559 or blank lines, remove all fixed-width markup in it. If the
23560 region contains anything else, convert all non-fixed-width lines
23561 to fixed-width ones.
23563 Blank lines at the end of the region are ignored unless the
23564 region only contains such lines."
23565 (interactive)
23566 (if (not (org-region-active-p))
23567 ;; No region:
23569 ;; Remove fixed width marker only in a fixed-with element.
23571 ;; Add fixed width maker in paragraphs, in blank lines after
23572 ;; elements or at the beginning of a headline or an inlinetask,
23573 ;; and before any one-line elements (e.g., a clock).
23574 (progn
23575 (beginning-of-line)
23576 (let* ((element (org-element-at-point))
23577 (type (org-element-type element)))
23578 (cond
23579 ((and (eq type 'fixed-width)
23580 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23581 (replace-match
23582 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23583 ((and (memq type '(babel-call clock comment diary-sexp headline
23584 horizontal-rule keyword paragraph
23585 planning))
23586 (<= (org-element-property :post-affiliated element) (point)))
23587 (skip-chars-forward " \t")
23588 (insert ": "))
23589 ((and (looking-at-p "[ \t]*$")
23590 (or (eq type 'inlinetask)
23591 (save-excursion
23592 (skip-chars-forward " \r\t\n")
23593 (<= (org-element-property :end element) (point)))))
23594 (delete-region (point) (line-end-position))
23595 (org-indent-line)
23596 (insert ": "))
23597 (t (user-error "Cannot insert a fixed-width line here")))))
23598 ;; Region active.
23599 (let* ((begin (save-excursion
23600 (goto-char (region-beginning))
23601 (line-beginning-position)))
23602 (end (copy-marker
23603 (save-excursion
23604 (goto-char (region-end))
23605 (unless (eolp) (beginning-of-line))
23606 (if (save-excursion (re-search-backward "\\S-" begin t))
23607 (progn (skip-chars-backward " \r\t\n") (point))
23608 (point)))))
23609 (all-fixed-width-p
23610 (catch 'not-all-p
23611 (save-excursion
23612 (goto-char begin)
23613 (skip-chars-forward " \r\t\n")
23614 (when (eobp) (throw 'not-all-p nil))
23615 (while (< (point) end)
23616 (let ((element (org-element-at-point)))
23617 (if (eq (org-element-type element) 'fixed-width)
23618 (goto-char (org-element-property :end element))
23619 (throw 'not-all-p nil))))
23620 t))))
23621 (if all-fixed-width-p
23622 (save-excursion
23623 (goto-char begin)
23624 (while (< (point) end)
23625 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23626 (replace-match
23627 "" nil nil nil
23628 (if (= (line-end-position) (match-end 0)) 0 1)))
23629 (forward-line)))
23630 (let ((min-ind (point-max)))
23631 ;; Find minimum indentation across all lines.
23632 (save-excursion
23633 (goto-char begin)
23634 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23635 (setq min-ind 0)
23636 (catch 'zerop
23637 (while (< (point) end)
23638 (unless (looking-at-p "[ \t]*$")
23639 (let ((ind (org-get-indentation)))
23640 (setq min-ind (min min-ind ind))
23641 (when (zerop ind) (throw 'zerop t))))
23642 (forward-line)))))
23643 ;; Loop over all lines and add fixed-width markup everywhere
23644 ;; but in fixed-width lines.
23645 (save-excursion
23646 (goto-char begin)
23647 (while (< (point) end)
23648 (cond
23649 ((org-at-heading-p)
23650 (insert ": ")
23651 (forward-line)
23652 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23653 (insert ":")
23654 (forward-line)))
23655 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23656 (let* ((element (org-element-at-point))
23657 (element-end (org-element-property :end element)))
23658 (if (eq (org-element-type element) 'fixed-width)
23659 (progn (goto-char element-end)
23660 (skip-chars-backward " \r\t\n")
23661 (forward-line))
23662 (let ((limit (min end element-end)))
23663 (while (< (point) limit)
23664 (org-move-to-column min-ind t)
23665 (insert ": ")
23666 (forward-line))))))
23668 (org-move-to-column min-ind t)
23669 (insert ": ")
23670 (forward-line)))))))
23671 (set-marker end nil))))
23674 ;;; Comments
23676 ;; Org comments syntax is quite complex. It requires the entire line
23677 ;; to be just a comment. Also, even with the right syntax at the
23678 ;; beginning of line, some some elements (i.e. verse-block or
23679 ;; example-block) don't accept comments. Usual Emacs comment commands
23680 ;; cannot cope with those requirements. Therefore, Org replaces them.
23682 ;; Org still relies on `comment-dwim', but cannot trust
23683 ;; `comment-only-p'. So, `comment-region-function' and
23684 ;; `uncomment-region-function' both point
23685 ;; to`org-comment-or-uncomment-region'. Eventually,
23686 ;; `org-insert-comment' takes care of insertion of comments at the
23687 ;; beginning of line.
23689 ;; `org-setup-comments-handling' install comments related variables
23690 ;; during `org-mode' initialization.
23692 (defun org-setup-comments-handling ()
23693 (interactive)
23694 (setq-local comment-use-syntax nil)
23695 (setq-local comment-start "# ")
23696 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23697 (setq-local comment-insert-comment-function 'org-insert-comment)
23698 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23699 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23701 (defun org-insert-comment ()
23702 "Insert an empty comment above current line.
23703 If the line is empty, insert comment at its beginning. When
23704 point is within a source block, comment according to the related
23705 major mode."
23706 (if (let ((element (org-element-at-point)))
23707 (and (eq (org-element-type element) 'src-block)
23708 (< (save-excursion
23709 (goto-char (org-element-property :post-affiliated element))
23710 (line-end-position))
23711 (point))
23712 (> (save-excursion
23713 (goto-char (org-element-property :end element))
23714 (skip-chars-backward " \r\t\n")
23715 (line-beginning-position))
23716 (point))))
23717 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23718 (beginning-of-line)
23719 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23720 (open-line 1))
23721 (org-indent-line)
23722 (insert "# ")))
23724 (defvar comment-empty-lines) ; From newcomment.el.
23725 (defun org-comment-or-uncomment-region (beg end &rest _)
23726 "Comment or uncomment each non-blank line in the region.
23727 Uncomment each non-blank line between BEG and END if it only
23728 contains commented lines. Otherwise, comment them. If region is
23729 strictly within a source block, use appropriate comment syntax."
23730 (if (let ((element (org-element-at-point)))
23731 (and (eq (org-element-type element) 'src-block)
23732 (< (save-excursion
23733 (goto-char (org-element-property :post-affiliated element))
23734 (line-end-position))
23735 beg)
23736 (>= (save-excursion
23737 (goto-char (org-element-property :end element))
23738 (skip-chars-backward " \r\t\n")
23739 (line-beginning-position))
23740 end)))
23741 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23742 (save-restriction
23743 ;; Restrict region
23744 (narrow-to-region (save-excursion (goto-char beg)
23745 (skip-chars-forward " \r\t\n" end)
23746 (line-beginning-position))
23747 (save-excursion (goto-char end)
23748 (skip-chars-backward " \r\t\n" beg)
23749 (line-end-position)))
23750 (let ((uncommentp
23751 ;; UNCOMMENTP is non-nil when every non blank line between
23752 ;; BEG and END is a comment.
23753 (save-excursion
23754 (goto-char (point-min))
23755 (while (and (not (eobp))
23756 (let ((element (org-element-at-point)))
23757 (and (eq (org-element-type element) 'comment)
23758 (goto-char (min (point-max)
23759 (org-element-property
23760 :end element)))))))
23761 (eobp))))
23762 (if uncommentp
23763 ;; Only blank lines and comments in region: uncomment it.
23764 (save-excursion
23765 (goto-char (point-min))
23766 (while (not (eobp))
23767 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23768 (replace-match "" nil nil nil 1))
23769 (forward-line)))
23770 ;; Comment each line in region.
23771 (let ((min-indent (point-max)))
23772 ;; First find the minimum indentation across all lines.
23773 (save-excursion
23774 (goto-char (point-min))
23775 (while (and (not (eobp)) (not (zerop min-indent)))
23776 (unless (looking-at "[ \t]*$")
23777 (setq min-indent (min min-indent (current-indentation))))
23778 (forward-line)))
23779 ;; Then loop over all lines.
23780 (save-excursion
23781 (goto-char (point-min))
23782 (while (not (eobp))
23783 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23784 ;; Don't get fooled by invisible text (e.g. link path)
23785 ;; when moving to column MIN-INDENT.
23786 (let ((buffer-invisibility-spec nil))
23787 (org-move-to-column min-indent t))
23788 (insert comment-start))
23789 (forward-line)))))))))
23791 (defun org-comment-dwim (_arg)
23792 "Call `comment-dwim' within a source edit buffer if needed."
23793 (interactive "*P")
23794 (if (org-in-src-block-p)
23795 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23796 (call-interactively 'comment-dwim)))
23799 ;;; Timestamps API
23801 ;; This section contains tools to operate on timestamp objects, as
23802 ;; returned by, e.g. `org-element-context'.
23804 (defun org-timestamp--to-internal-time (timestamp &optional end)
23805 "Encode TIMESTAMP object into Emacs internal time.
23806 Use end of date range or time range when END is non-nil."
23807 (apply #'encode-time
23808 (cons 0
23809 (mapcar
23810 (lambda (prop) (or (org-element-property prop timestamp) 0))
23811 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23812 '(:minute-start :hour-start :day-start :month-start
23813 :year-start))))))
23815 (defun org-timestamp-has-time-p (timestamp)
23816 "Non-nil when TIMESTAMP has a time specified."
23817 (org-element-property :hour-start timestamp))
23819 (defun org-timestamp-format (timestamp format &optional end utc)
23820 "Format a TIMESTAMP object into a string.
23822 FORMAT is a format specifier to be passed to
23823 `format-time-string'.
23825 When optional argument END is non-nil, use end of date-range or
23826 time-range, if possible.
23828 When optional argument UTC is non-nil, time will be expressed as
23829 Universal Time."
23830 (format-time-string
23831 format (org-timestamp--to-internal-time timestamp end)
23832 (and utc t)))
23834 (defun org-timestamp-split-range (timestamp &optional end)
23835 "Extract a TIMESTAMP object from a date or time range.
23837 END, when non-nil, means extract the end of the range.
23838 Otherwise, extract its start.
23840 Return a new timestamp object."
23841 (let ((type (org-element-property :type timestamp)))
23842 (if (memq type '(active inactive diary)) timestamp
23843 (let ((split-ts (org-element-copy timestamp)))
23844 ;; Set new type.
23845 (org-element-put-property
23846 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23847 ;; Copy start properties over end properties if END is
23848 ;; non-nil. Otherwise, copy end properties over `start' ones.
23849 (let ((p-alist '((:minute-start . :minute-end)
23850 (:hour-start . :hour-end)
23851 (:day-start . :day-end)
23852 (:month-start . :month-end)
23853 (:year-start . :year-end))))
23854 (dolist (p-cell p-alist)
23855 (org-element-put-property
23856 split-ts
23857 (funcall (if end #'car #'cdr) p-cell)
23858 (org-element-property
23859 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23860 ;; Eventually refresh `:raw-value'.
23861 (org-element-put-property split-ts :raw-value nil)
23862 (org-element-put-property
23863 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23865 (defun org-timestamp-translate (timestamp &optional boundary)
23866 "Translate TIMESTAMP object to custom format.
23868 Format string is defined in `org-time-stamp-custom-formats',
23869 which see.
23871 When optional argument BOUNDARY is non-nil, it is either the
23872 symbol `start' or `end'. In this case, only translate the
23873 starting or ending part of TIMESTAMP if it is a date or time
23874 range. Otherwise, translate both parts.
23876 Return timestamp as-is if `org-display-custom-times' is nil or if
23877 it has a `diary' type."
23878 (let ((type (org-element-property :type timestamp)))
23879 (if (or (not org-display-custom-times) (eq type 'diary))
23880 (org-element-interpret-data timestamp)
23881 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23882 org-time-stamp-custom-formats)))
23883 (if (and (not boundary) (memq type '(active-range inactive-range)))
23884 (concat (org-timestamp-format timestamp fmt)
23885 "--"
23886 (org-timestamp-format timestamp fmt t))
23887 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23891 ;;; Other stuff.
23893 (defvar reftex-docstruct-symbol)
23894 (defvar reftex-cite-format)
23895 (defvar org--rds)
23897 (defun org-reftex-citation ()
23898 "Use reftex-citation to insert a citation into the buffer.
23899 This looks for a line like
23901 #+BIBLIOGRAPHY: foo plain option:-d
23903 and derives from it that foo.bib is the bibliography file relevant
23904 for this document. It then installs the necessary environment for RefTeX
23905 to work in this buffer and calls `reftex-citation' to insert a citation
23906 into the buffer.
23908 Export of such citations to both LaTeX and HTML is handled by the contributed
23909 package ox-bibtex by Taru Karttunen."
23910 (interactive)
23911 (let ((reftex-docstruct-symbol 'org--rds)
23912 (reftex-cite-format "\\cite{%l}")
23913 org--rds bib)
23914 (save-excursion
23915 (save-restriction
23916 (widen)
23917 (let ((case-fold-search t)
23918 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23919 (if (not (save-excursion
23920 (or (re-search-forward re nil t)
23921 (re-search-backward re nil t))))
23922 (user-error "No bibliography defined in file")
23923 (setq bib (concat (match-string 1) ".bib")
23924 org--rds (list (list 'bib bib)))))))
23925 (call-interactively 'reftex-citation)))
23927 ;;;; Functions extending outline functionality
23929 (defun org-beginning-of-line (&optional arg)
23930 "Go to the beginning of the current line. If that is invisible, continue
23931 to a visible line beginning. This makes the function of C-a more intuitive.
23932 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23933 first attempt, and only move to after the tags when the cursor is already
23934 beyond the end of the headline."
23935 (interactive "P")
23936 (let ((pos (point))
23937 (special (if (consp org-special-ctrl-a/e)
23938 (car org-special-ctrl-a/e)
23939 org-special-ctrl-a/e))
23940 deactivate-mark refpos)
23941 (call-interactively (if (org-bound-and-true-p visual-line-mode)
23942 #'beginning-of-visual-line
23943 #'move-beginning-of-line))
23944 (cond
23945 ((or arg (not special)))
23946 ((and (looking-at org-complex-heading-regexp)
23947 (eq (char-after (match-end 1)) ?\s))
23948 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23949 (point-at-eol)))
23950 (goto-char
23951 (if (eq special t)
23952 (cond ((> pos refpos) refpos)
23953 ((= pos (point)) refpos)
23954 (t (point)))
23955 (cond ((> pos (point)) (point))
23956 ((not (eq last-command this-command)) (point))
23957 (t refpos)))))
23958 ((org-at-item-p)
23959 ;; Being at an item and not looking at an the item means point
23960 ;; was previously moved to beginning of a visual line, which
23961 ;; doesn't contain the item. Therefore, do nothing special,
23962 ;; just stay here.
23963 (when (looking-at org-list-full-item-re)
23964 ;; Set special position at first white space character after
23965 ;; bullet, and check-box, if any.
23966 (let ((after-bullet
23967 (let ((box (match-end 3)))
23968 (if (not box) (match-end 1)
23969 (let ((after (char-after box)))
23970 (if (and after (= after ? )) (1+ box) box))))))
23971 ;; Special case: Move point to special position when
23972 ;; currently after it or at beginning of line.
23973 (if (eq special t)
23974 (when (or (> pos after-bullet) (= (point) pos))
23975 (goto-char after-bullet))
23976 ;; Reversed case: Move point to special position when
23977 ;; point was already at beginning of line and command is
23978 ;; repeated.
23979 (when (and (= (point) pos) (eq last-command this-command))
23980 (goto-char after-bullet))))))))
23981 (setq disable-point-adjustment
23982 (or (not (invisible-p (point)))
23983 (not (invisible-p (max (point-min) (1- (point))))))))
23985 (defun org-end-of-line (&optional arg)
23986 "Go to the end of the line.
23987 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23988 tags on the first attempt, and only move to after the tags when
23989 the cursor is already beyond the end of the headline."
23990 (interactive "P")
23991 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23992 org-special-ctrl-a/e))
23993 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23994 'end-of-visual-line)
23995 ((fboundp 'move-end-of-line) 'move-end-of-line)
23996 (t 'end-of-line)))
23997 deactivate-mark)
23998 (if (or (not special) arg) (call-interactively move-fun)
23999 (let* ((element (save-excursion (beginning-of-line)
24000 (org-element-at-point)))
24001 (type (org-element-type element)))
24002 (cond
24003 ((memq type '(headline inlinetask))
24004 (let ((pos (point)))
24005 (beginning-of-line 1)
24006 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
24007 (if (eq special t)
24008 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
24009 (goto-char (match-beginning 1))
24010 (goto-char (match-end 0)))
24011 (if (or (< pos (match-end 0))
24012 (not (eq this-command last-command)))
24013 (goto-char (match-end 0))
24014 (goto-char (match-beginning 1))))
24015 (call-interactively move-fun))))
24016 ((outline-invisible-p (line-end-position))
24017 ;; If element is hidden, `move-end-of-line' would put point
24018 ;; after it. Use `end-of-line' to stay on current line.
24019 (call-interactively 'end-of-line))
24020 (t (call-interactively move-fun))))))
24021 (setq disable-point-adjustment
24022 (or (not (invisible-p (point)))
24023 (not (invisible-p (max (point-min) (1- (point))))))))
24025 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
24026 (define-key org-mode-map "\C-e" 'org-end-of-line)
24028 (defun org-backward-sentence (&optional _arg)
24029 "Go to beginning of sentence, or beginning of table field.
24030 This will call `backward-sentence' or `org-table-beginning-of-field',
24031 depending on context."
24032 (interactive)
24033 (let* ((element (org-element-at-point))
24034 (contents-begin (org-element-property :contents-begin element))
24035 (table (org-element-lineage element '(table) t)))
24036 (if (and table
24037 (> (point) contents-begin)
24038 (<= (point) (org-element-property :contents-end table)))
24039 (call-interactively #'org-table-beginning-of-field)
24040 (save-restriction
24041 (when (and contents-begin
24042 (< (point-min) contents-begin)
24043 (> (point) contents-begin))
24044 (narrow-to-region contents-begin
24045 (org-element-property :contents-end element)))
24046 (call-interactively #'backward-sentence)))))
24048 (defun org-forward-sentence (&optional _arg)
24049 "Go to end of sentence, or end of table field.
24050 This will call `forward-sentence' or `org-table-end-of-field',
24051 depending on context."
24052 (interactive)
24053 (let* ((element (org-element-at-point))
24054 (contents-end (org-element-property :contents-end element))
24055 (table (org-element-lineage element '(table) t)))
24056 (if (and table
24057 (>= (point) (org-element-property :contents-begin table))
24058 (< (point) contents-end))
24059 (call-interactively #'org-table-end-of-field)
24060 (save-restriction
24061 (when (and contents-end
24062 (> (point-max) contents-end)
24063 ;; Skip blank lines between elements.
24064 (< (org-element-property :end element)
24065 (save-excursion (goto-char contents-end)
24066 (skip-chars-forward " \r\t\n"))))
24067 (narrow-to-region (org-element-property :contents-begin element)
24068 contents-end))
24069 (call-interactively #'forward-sentence)))))
24071 (define-key org-mode-map "\M-a" 'org-backward-sentence)
24072 (define-key org-mode-map "\M-e" 'org-forward-sentence)
24074 (defun org-kill-line (&optional _arg)
24075 "Kill line, to tags or end of line."
24076 (interactive)
24077 (cond
24078 ((or (not org-special-ctrl-k)
24079 (bolp)
24080 (not (org-at-heading-p)))
24081 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
24082 org-ctrl-k-protect-subtree
24083 (or (eq org-ctrl-k-protect-subtree 'error)
24084 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
24085 (user-error "C-k aborted as it would kill a hidden subtree"))
24086 (call-interactively
24087 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
24088 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
24089 (kill-region (point) (match-beginning 1))
24090 (org-set-tags nil t))
24091 (t (kill-region (point) (point-at-eol)))))
24093 (define-key org-mode-map "\C-k" 'org-kill-line)
24095 (defun org-yank (&optional arg)
24096 "Yank. If the kill is a subtree, treat it specially.
24097 This command will look at the current kill and check if is a single
24098 subtree, or a series of subtrees[1]. If it passes the test, and if the
24099 cursor is at the beginning of a line or after the stars of a currently
24100 empty headline, then the yank is handled specially. How exactly depends
24101 on the value of the following variables.
24103 `org-yank-folded-subtrees'
24104 By default, this variable is non-nil, which results in subtree(s)
24105 being folded after insertion, but only if doing so would now
24106 swallow text after the yanked text.
24108 `org-yank-adjusted-subtrees'
24109 When non-nil (the default value is nil), the subtree will be
24110 promoted or demoted in order to fit into the local outline tree
24111 structure, which means that the level will be adjusted so that it
24112 becomes the smaller one of the two *visible* surrounding headings.
24114 Any prefix to this command will cause `yank' to be called directly with
24115 no special treatment. In particular, a simple \\[universal-argument] prefix \
24116 will just
24117 plainly yank the text as it is.
24119 \[1] The test checks if the first non-white line is a heading
24120 and if there are no other headings with fewer stars."
24121 (interactive "P")
24122 (org-yank-generic 'yank arg))
24124 (defun org-yank-generic (command arg)
24125 "Perform some yank-like command.
24127 This function implements the behavior described in the `org-yank'
24128 documentation. However, it has been generalized to work for any
24129 interactive command with similar behavior."
24131 ;; pretend to be command COMMAND
24132 (setq this-command command)
24134 (if arg
24135 (call-interactively command)
24137 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24138 (and (org-kill-is-subtree-p)
24139 (or (bolp)
24140 (and (looking-at "[ \t]*$")
24141 (string-match
24142 "\\`\\*+\\'"
24143 (buffer-substring (point-at-bol) (point)))))))
24144 swallowp)
24145 (cond
24146 ((and subtreep org-yank-folded-subtrees)
24147 (let ((beg (point))
24148 end)
24149 (if (and subtreep org-yank-adjusted-subtrees)
24150 (org-paste-subtree nil nil 'for-yank)
24151 (call-interactively command))
24153 (setq end (point))
24154 (goto-char beg)
24155 (when (and (bolp) subtreep
24156 (not (setq swallowp
24157 (org-yank-folding-would-swallow-text beg end))))
24158 (org-with-limited-levels
24159 (or (looking-at org-outline-regexp)
24160 (re-search-forward org-outline-regexp-bol end t))
24161 (while (and (< (point) end) (looking-at org-outline-regexp))
24162 (outline-hide-subtree)
24163 (org-cycle-show-empty-lines 'folded)
24164 (condition-case nil
24165 (outline-forward-same-level 1)
24166 (error (goto-char end))))))
24167 (when swallowp
24168 (message
24169 "Inserted text not folded because that would swallow text"))
24171 (goto-char end)
24172 (skip-chars-forward " \t\n\r")
24173 (beginning-of-line 1)
24174 (push-mark beg 'nomsg)))
24175 ((and subtreep org-yank-adjusted-subtrees)
24176 (let ((beg (point-at-bol)))
24177 (org-paste-subtree nil nil 'for-yank)
24178 (push-mark beg 'nomsg)))
24180 (call-interactively command))))))
24182 (defun org-yank-folding-would-swallow-text (beg end)
24183 "Would hide-subtree at BEG swallow any text after END?"
24184 (let (level)
24185 (org-with-limited-levels
24186 (save-excursion
24187 (goto-char beg)
24188 (when (or (looking-at org-outline-regexp)
24189 (re-search-forward org-outline-regexp-bol end t))
24190 (setq level (org-outline-level)))
24191 (goto-char end)
24192 (skip-chars-forward " \t\r\n\v\f")
24193 (not (or (eobp)
24194 (and (bolp) (looking-at-p org-outline-regexp)
24195 (<= (org-outline-level) level))))))))
24197 (define-key org-mode-map "\C-y" 'org-yank)
24199 (defun org-truely-invisible-p ()
24200 "Check if point is at a character currently not visible.
24201 This version does not only check the character property, but also
24202 `visible-mode'."
24203 ;; Early versions of noutline don't have `outline-invisible-p'.
24204 (unless (org-bound-and-true-p visible-mode)
24205 (outline-invisible-p)))
24207 (defun org-invisible-p2 ()
24208 "Check if point is at a character currently not visible."
24209 (save-excursion
24210 (when (and (eolp) (not (bobp))) (backward-char 1))
24211 ;; Early versions of noutline don't have `outline-invisible-p'.
24212 (outline-invisible-p)))
24214 (defun org-back-to-heading (&optional invisible-ok)
24215 "Call `outline-back-to-heading', but provide a better error message."
24216 (condition-case nil
24217 (outline-back-to-heading invisible-ok)
24218 (error (error "Before first headline at position %d in buffer %s"
24219 (point) (current-buffer)))))
24221 (defun org-before-first-heading-p ()
24222 "Before first heading?"
24223 (save-excursion
24224 (end-of-line)
24225 (null (re-search-backward org-outline-regexp-bol nil t))))
24227 (defun org-at-heading-p (&optional ignored)
24228 (outline-on-heading-p t))
24229 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24230 ;;; warning was only added in Org 9.0, which should be taken into
24231 ;;; account when deciding when to remove the alias.
24232 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24234 (defun org-in-commented-heading-p (&optional no-inheritance)
24235 "Non-nil if point is under a commented heading.
24236 This function also checks ancestors of the current headline,
24237 unless optional argument NO-INHERITANCE is non-nil."
24238 (cond
24239 ((org-before-first-heading-p) nil)
24240 ((let ((headline (nth 4 (org-heading-components))))
24241 (and headline
24242 (let ((case-fold-search nil))
24243 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24244 headline)))))
24245 (no-inheritance nil)
24247 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24249 (defun org-at-comment-p nil
24250 "Is cursor in a commented line?"
24251 (save-excursion
24252 (save-match-data
24253 (beginning-of-line)
24254 (looking-at "^[ \t]*# "))))
24256 (defun org-at-drawer-p nil
24257 "Is cursor at a drawer keyword?"
24258 (save-excursion
24259 (move-beginning-of-line 1)
24260 (looking-at org-drawer-regexp)))
24262 (defun org-at-block-p nil
24263 "Is cursor at a block keyword?"
24264 (save-excursion
24265 (move-beginning-of-line 1)
24266 (looking-at org-block-regexp)))
24268 (defun org-point-at-end-of-empty-headline ()
24269 "If point is at the end of an empty headline, return t, else nil.
24270 If the heading only contains a TODO keyword, it is still still considered
24271 empty."
24272 (and (looking-at "[ \t]*$")
24273 (when org-todo-line-regexp
24274 (save-excursion
24275 (beginning-of-line 1)
24276 (let ((case-fold-search nil))
24277 (looking-at org-todo-line-regexp)
24278 (string= (match-string 3) ""))))))
24280 (defun org-at-heading-or-item-p ()
24281 (or (org-at-heading-p) (org-at-item-p)))
24283 (defun org-at-target-p ()
24284 (or (org-in-regexp org-radio-target-regexp)
24285 (org-in-regexp org-target-regexp)))
24286 ;; Compatibility alias with Org versions < 7.8.03
24287 (defalias 'org-on-target-p 'org-at-target-p)
24289 (defun org-up-heading-all (arg)
24290 "Move to the heading line of which the present line is a subheading.
24291 This function considers both visible and invisible heading lines.
24292 With argument, move up ARG levels."
24293 (if (fboundp 'outline-up-heading-all)
24294 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24295 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24297 (defun org-up-heading-safe ()
24298 "Move to the heading line of which the present line is a subheading.
24299 This version will not throw an error. It will return the level of the
24300 headline found, or nil if no higher level is found.
24302 Also, this function will be a lot faster than `outline-up-heading',
24303 because it relies on stars being the outline starters. This can really
24304 make a significant difference in outlines with very many siblings."
24305 (when (ignore-errors (org-back-to-heading t))
24306 (let ((level-up (1- (funcall outline-level))))
24307 (and (> level-up 0)
24308 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24309 (funcall outline-level)))))
24311 (defun org-first-sibling-p ()
24312 "Is this heading the first child of its parents?"
24313 (interactive)
24314 (let ((re org-outline-regexp-bol)
24315 level l)
24316 (unless (org-at-heading-p t)
24317 (user-error "Not at a heading"))
24318 (setq level (funcall outline-level))
24319 (save-excursion
24320 (if (not (re-search-backward re nil t))
24322 (setq l (funcall outline-level))
24323 (< l level)))))
24325 (defun org-goto-sibling (&optional previous)
24326 "Goto the next sibling, even if it is invisible.
24327 When PREVIOUS is set, go to the previous sibling instead. Returns t
24328 when a sibling was found. When none is found, return nil and don't
24329 move point."
24330 (let ((fun (if previous 're-search-backward 're-search-forward))
24331 (pos (point))
24332 (re org-outline-regexp-bol)
24333 level l)
24334 (when (ignore-errors (org-back-to-heading t))
24335 (setq level (funcall outline-level))
24336 (catch 'exit
24337 (or previous (forward-char 1))
24338 (while (funcall fun re nil t)
24339 (setq l (funcall outline-level))
24340 (when (< l level) (goto-char pos) (throw 'exit nil))
24341 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24342 (goto-char pos)
24343 nil))))
24345 (defun org-show-siblings ()
24346 "Show all siblings of the current headline."
24347 (save-excursion
24348 (while (org-goto-sibling) (org-flag-heading nil)))
24349 (save-excursion
24350 (while (org-goto-sibling 'previous)
24351 (org-flag-heading nil))))
24353 (defun org-goto-first-child ()
24354 "Goto the first child, even if it is invisible.
24355 Return t when a child was found. Otherwise don't move point and
24356 return nil."
24357 (let (level (pos (point)) (re org-outline-regexp-bol))
24358 (when (ignore-errors (org-back-to-heading t))
24359 (setq level (outline-level))
24360 (forward-char 1)
24361 (if (and (re-search-forward re nil t) (> (outline-level) level))
24362 (progn (goto-char (match-beginning 0)) t)
24363 (goto-char pos) nil))))
24365 (defun org-show-hidden-entry ()
24366 "Show an entry where even the heading is hidden."
24367 (save-excursion
24368 (org-show-entry)))
24370 (defun org-flag-heading (flag &optional entry)
24371 "Flag the current heading. FLAG non-nil means make invisible.
24372 When ENTRY is non-nil, show the entire entry."
24373 (save-excursion
24374 (org-back-to-heading t)
24375 ;; Check if we should show the entire entry
24376 (if entry
24377 (progn
24378 (org-show-entry)
24379 (save-excursion
24380 (and (outline-next-heading)
24381 (org-flag-heading nil))))
24382 (outline-flag-region (max (point-min) (1- (point)))
24383 (save-excursion (outline-end-of-heading) (point))
24384 flag))))
24386 (defun org-get-next-sibling ()
24387 "Move to next heading of the same level, and return point.
24388 If there is no such heading, return nil.
24389 This is like outline-next-sibling, but invisible headings are ok."
24390 (let ((level (funcall outline-level)))
24391 (outline-next-heading)
24392 (while (and (not (eobp)) (> (funcall outline-level) level))
24393 (outline-next-heading))
24394 (unless (or (eobp) (< (funcall outline-level) level))
24395 (point))))
24397 (defun org-get-last-sibling ()
24398 "Move to previous heading of the same level, and return point.
24399 If there is no such heading, return nil."
24400 (let ((opoint (point))
24401 (level (funcall outline-level)))
24402 (outline-previous-heading)
24403 (when (and (/= (point) opoint) (outline-on-heading-p t))
24404 (while (and (> (funcall outline-level) level)
24405 (not (bobp)))
24406 (outline-previous-heading))
24407 (unless (< (funcall outline-level) level)
24408 (point)))))
24410 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24411 "Goto to the end of a subtree."
24412 ;; This contains an exact copy of the original function, but it uses
24413 ;; `org-back-to-heading', to make it work also in invisible
24414 ;; trees. And is uses an invisible-ok argument.
24415 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24416 ;; Furthermore, when used inside Org, finding the end of a large subtree
24417 ;; with many children and grandchildren etc, this can be much faster
24418 ;; than the outline version.
24419 (org-back-to-heading invisible-ok)
24420 (let ((first t)
24421 (level (funcall outline-level)))
24422 (if (and (derived-mode-p 'org-mode) (< level 1000))
24423 ;; A true heading (not a plain list item), in Org-mode
24424 ;; This means we can easily find the end by looking
24425 ;; only for the right number of stars. Using a regexp to do
24426 ;; this is so much faster than using a Lisp loop.
24427 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24428 (forward-char 1)
24429 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24430 ;; something else, do it the slow way
24431 (while (and (not (eobp))
24432 (or first (> (funcall outline-level) level)))
24433 (setq first nil)
24434 (outline-next-heading)))
24435 (unless to-heading
24436 (when (memq (preceding-char) '(?\n ?\^M))
24437 ;; Go to end of line before heading
24438 (forward-char -1)
24439 (when (memq (preceding-char) '(?\n ?\^M))
24440 ;; leave blank line before heading
24441 (forward-char -1)))))
24442 (point))
24444 (defun org-end-of-meta-data (&optional full)
24445 "Skip planning line and properties drawer in current entry.
24446 When optional argument FULL is non-nil, also skip empty lines,
24447 clocking lines and regular drawers at the beginning of the
24448 entry."
24449 (org-back-to-heading t)
24450 (forward-line)
24451 (when (looking-at-p org-planning-line-re) (forward-line))
24452 (when (looking-at org-property-drawer-re)
24453 (goto-char (match-end 0))
24454 (forward-line))
24455 (when (and full (not (org-at-heading-p)))
24456 (catch 'exit
24457 (let ((end (save-excursion (outline-next-heading) (point)))
24458 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24459 (while (not (eobp))
24460 (cond ((looking-at-p org-drawer-regexp)
24461 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24462 (forward-line)
24463 (throw 'exit t)))
24464 ((looking-at-p re) (forward-line))
24465 (t (throw 'exit t))))))))
24467 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24468 "Move forward to the ARG'th subheading at same level as this one.
24469 Stop at the first and last subheadings of a superior heading.
24470 Normally this only looks at visible headings, but when INVISIBLE-OK is
24471 non-nil it will also look at invisible ones."
24472 (interactive "p")
24473 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24474 (if (and arg (< arg 0))
24475 (goto-char (point-min))
24476 (outline-next-heading))
24477 (org-at-heading-p)
24478 (let ((level (- (match-end 0) (match-beginning 0) 1))
24479 (f (if (and arg (< arg 0))
24480 're-search-backward
24481 're-search-forward))
24482 (count (if arg (abs arg) 1))
24483 (result (point)))
24484 (while (and (prog1 (> count 0)
24485 (forward-char (if (and arg (< arg 0)) -1 1)))
24486 (funcall f org-outline-regexp-bol nil 'move))
24487 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24488 (cond ((< l level) (setq count 0))
24489 ((and (= l level)
24490 (or invisible-ok
24491 (progn
24492 (goto-char (line-beginning-position))
24493 (not (outline-invisible-p)))))
24494 (setq count (1- count))
24495 (when (eq l level)
24496 (setq result (point)))))))
24497 (goto-char result))
24498 (beginning-of-line 1)))
24500 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24501 "Move backward to the ARG'th subheading at same level as this one.
24502 Stop at the first and last subheadings of a superior heading."
24503 (interactive "p")
24504 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24506 (defun org-next-visible-heading (arg)
24507 "Move to the next visible heading.
24509 This function wraps `outline-next-visible-heading' with
24510 `org-with-limited-levels' in order to skip over inline tasks and
24511 respect customization of `org-odd-levels-only'."
24512 (interactive "p")
24513 (org-with-limited-levels
24514 (outline-next-visible-heading arg)))
24516 (defun org-previous-visible-heading (arg)
24517 "Move to the previous visible heading.
24519 This function wraps `outline-previous-visible-heading' with
24520 `org-with-limited-levels' in order to skip over inline tasks and
24521 respect customization of `org-odd-levels-only'."
24522 (interactive "p")
24523 (org-with-limited-levels
24524 (outline-previous-visible-heading arg)))
24526 (defun org-next-block (arg &optional backward block-regexp)
24527 "Jump to the next block.
24529 With a prefix argument ARG, jump forward ARG many blocks.
24531 When BACKWARD is non-nil, jump to the previous block.
24533 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24534 Match data is set according to this regexp when the function
24535 returns.
24537 Return point at beginning of the opening line of found block.
24538 Throw an error if no block is found."
24539 (interactive "p")
24540 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24541 (case-fold-search t)
24542 (search-fn (if backward #'re-search-backward #'re-search-forward))
24543 (count (or arg 1))
24544 (origin (point))
24545 last-element)
24546 (if backward (beginning-of-line) (end-of-line))
24547 (while (and (> count 0) (funcall search-fn re nil t))
24548 (let ((element (save-excursion
24549 (goto-char (match-beginning 0))
24550 (save-match-data (org-element-at-point)))))
24551 (when (and (memq (org-element-type element)
24552 '(center-block comment-block dynamic-block
24553 example-block export-block quote-block
24554 special-block src-block verse-block))
24555 (<= (match-beginning 0)
24556 (org-element-property :post-affiliated element)))
24557 (setq last-element element)
24558 (cl-decf count))))
24559 (if (= count 0)
24560 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24561 (save-match-data (org-show-context)))
24562 (goto-char origin)
24563 (user-error "No %s code blocks" (if backward "previous" "further")))))
24565 (defun org-previous-block (arg &optional block-regexp)
24566 "Jump to the previous block.
24567 With a prefix argument ARG, jump backward ARG many source blocks.
24568 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24569 (interactive "p")
24570 (org-next-block arg t block-regexp))
24572 (defun org-forward-paragraph ()
24573 "Move forward to beginning of next paragraph or equivalent.
24575 The function moves point to the beginning of the next visible
24576 structural element, which can be a paragraph, a table, a list
24577 item, etc. It also provides some special moves for convenience:
24579 - On an affiliated keyword, jump to the beginning of the
24580 relative element.
24581 - On an item or a footnote definition, move to the second
24582 element inside, if any.
24583 - On a table or a property drawer, jump after it.
24584 - On a verse or source block, stop after blank lines."
24585 (interactive)
24586 (when (eobp) (user-error "Cannot move further down"))
24587 (let* ((deactivate-mark nil)
24588 (element (org-element-at-point))
24589 (type (org-element-type element))
24590 (post-affiliated (org-element-property :post-affiliated element))
24591 (contents-begin (org-element-property :contents-begin element))
24592 (contents-end (org-element-property :contents-end element))
24593 (end (let ((end (org-element-property :end element)) (parent element))
24594 (while (and (setq parent (org-element-property :parent parent))
24595 (= (org-element-property :contents-end parent) end))
24596 (setq end (org-element-property :end parent)))
24597 end)))
24598 (cond ((not element)
24599 (skip-chars-forward " \r\t\n")
24600 (or (eobp) (beginning-of-line)))
24601 ;; On affiliated keywords, move to element's beginning.
24602 ((< (point) post-affiliated)
24603 (goto-char post-affiliated))
24604 ;; At a table row, move to the end of the table. Similarly,
24605 ;; at a node property, move to the end of the property
24606 ;; drawer.
24607 ((memq type '(node-property table-row))
24608 (goto-char (org-element-property
24609 :end (org-element-property :parent element))))
24610 ((memq type '(property-drawer table)) (goto-char end))
24611 ;; Consider blank lines as separators in verse and source
24612 ;; blocks to ease editing.
24613 ((memq type '(src-block verse-block))
24614 (when (eq type 'src-block)
24615 (setq contents-end
24616 (save-excursion (goto-char end)
24617 (skip-chars-backward " \r\t\n")
24618 (line-beginning-position))))
24619 (beginning-of-line)
24620 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24621 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24622 (goto-char end)
24623 (skip-chars-forward " \r\t\n")
24624 (if (= (point) contents-end) (goto-char end)
24625 (beginning-of-line))))
24626 ;; With no contents, just skip element.
24627 ((not contents-begin) (goto-char end))
24628 ;; If contents are invisible, skip the element altogether.
24629 ((outline-invisible-p (line-end-position))
24630 (cl-case type
24631 (headline
24632 (org-with-limited-levels (outline-next-visible-heading 1)))
24633 ;; At a plain list, make sure we move to the next item
24634 ;; instead of skipping the whole list.
24635 (plain-list (forward-char)
24636 (org-forward-paragraph))
24637 (otherwise (goto-char end))))
24638 ((>= (point) contents-end) (goto-char end))
24639 ((>= (point) contents-begin)
24640 ;; This can only happen on paragraphs and plain lists.
24641 (cl-case type
24642 (paragraph (goto-char end))
24643 ;; At a plain list, try to move to second element in
24644 ;; first item, if possible.
24645 (plain-list (end-of-line)
24646 (org-forward-paragraph))))
24647 ;; When contents start on the middle of a line (e.g. in
24648 ;; items and footnote definitions), try to reach first
24649 ;; element starting after current line.
24650 ((> (line-end-position) contents-begin)
24651 (end-of-line)
24652 (org-forward-paragraph))
24653 (t (goto-char contents-begin)))))
24655 (defun org-backward-paragraph ()
24656 "Move backward to start of previous paragraph or equivalent.
24658 The function moves point to the beginning of the current
24659 structural element, which can be a paragraph, a table, a list
24660 item, etc., or to the beginning of the previous visible one if
24661 point is already there. It also provides some special moves for
24662 convenience:
24664 - On an affiliated keyword, jump to the first one.
24665 - On a table or a property drawer, move to its beginning.
24666 - On a verse or source block, stop before blank lines."
24667 (interactive)
24668 (when (bobp) (user-error "Cannot move further up"))
24669 (let* ((deactivate-mark nil)
24670 (element (org-element-at-point))
24671 (type (org-element-type element))
24672 (contents-begin (org-element-property :contents-begin element))
24673 (contents-end (org-element-property :contents-end element))
24674 (post-affiliated (org-element-property :post-affiliated element))
24675 (begin (org-element-property :begin element)))
24676 (cond
24677 ((not element) (goto-char (point-min)))
24678 ((= (point) begin)
24679 (backward-char)
24680 (org-backward-paragraph))
24681 ((<= (point) post-affiliated) (goto-char begin))
24682 ((memq type '(node-property table-row))
24683 (goto-char (org-element-property
24684 :post-affiliated (org-element-property :parent element))))
24685 ((memq type '(property-drawer table)) (goto-char begin))
24686 ((memq type '(src-block verse-block))
24687 (when (eq type 'src-block)
24688 (setq contents-begin
24689 (save-excursion (goto-char begin) (forward-line) (point))))
24690 (if (= (point) contents-begin) (goto-char post-affiliated)
24691 ;; Inside a verse block, see blank lines as paragraph
24692 ;; separators.
24693 (let ((origin (point)))
24694 (skip-chars-backward " \r\t\n" contents-begin)
24695 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24696 (skip-chars-forward " \r\t\n" origin)
24697 (if (= (point) origin) (goto-char contents-begin)
24698 (beginning-of-line))))))
24699 ((not contents-begin) (goto-char (or post-affiliated begin)))
24700 ((eq type 'paragraph)
24701 (goto-char contents-begin)
24702 ;; When at first paragraph in an item or a footnote definition,
24703 ;; move directly to beginning of line.
24704 (let ((parent-contents
24705 (org-element-property
24706 :contents-begin (org-element-property :parent element))))
24707 (when (and parent-contents (= parent-contents contents-begin))
24708 (beginning-of-line))))
24709 ;; At the end of a greater element, move to the beginning of the
24710 ;; last element within.
24711 ((>= (point) contents-end)
24712 (goto-char (1- contents-end))
24713 (org-backward-paragraph))
24714 (t (goto-char (or post-affiliated begin))))
24715 ;; Ensure we never leave point invisible.
24716 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24718 (defun org-forward-element ()
24719 "Move forward by one element.
24720 Move to the next element at the same level, when possible."
24721 (interactive)
24722 (cond ((eobp) (user-error "Cannot move further down"))
24723 ((org-with-limited-levels (org-at-heading-p))
24724 (let ((origin (point)))
24725 (goto-char (org-end-of-subtree nil t))
24726 (unless (org-with-limited-levels (org-at-heading-p))
24727 (goto-char origin)
24728 (user-error "Cannot move further down"))))
24730 (let* ((elem (org-element-at-point))
24731 (end (org-element-property :end elem))
24732 (parent (org-element-property :parent elem)))
24733 (cond ((and parent (= (org-element-property :contents-end parent) end))
24734 (goto-char (org-element-property :end parent)))
24735 ((integer-or-marker-p end) (goto-char end))
24736 (t (message "No element at point")))))))
24738 (defun org-backward-element ()
24739 "Move backward by one element.
24740 Move to the previous element at the same level, when possible."
24741 (interactive)
24742 (cond ((bobp) (user-error "Cannot move further up"))
24743 ((org-with-limited-levels (org-at-heading-p))
24744 ;; At a headline, move to the previous one, if any, or stay
24745 ;; here.
24746 (let ((origin (point)))
24747 (org-with-limited-levels (org-backward-heading-same-level 1))
24748 ;; When current headline has no sibling above, move to its
24749 ;; parent.
24750 (when (= (point) origin)
24751 (or (org-with-limited-levels (org-up-heading-safe))
24752 (progn (goto-char origin)
24753 (user-error "Cannot move further up"))))))
24755 (let* ((elem (org-element-at-point))
24756 (beg (org-element-property :begin elem)))
24757 (cond
24758 ;; Move to beginning of current element if point isn't
24759 ;; there already.
24760 ((null beg) (message "No element at point"))
24761 ((/= (point) beg) (goto-char beg))
24762 (t (goto-char beg)
24763 (skip-chars-backward " \r\t\n")
24764 (unless (bobp)
24765 (let ((prev (org-element-at-point)))
24766 (goto-char (org-element-property :begin prev))
24767 (while (and (setq prev (org-element-property :parent prev))
24768 (<= (org-element-property :end prev) beg))
24769 (goto-char (org-element-property :begin prev)))))))))))
24771 (defun org-up-element ()
24772 "Move to upper element."
24773 (interactive)
24774 (if (org-with-limited-levels (org-at-heading-p))
24775 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24776 (let* ((elem (org-element-at-point))
24777 (parent (org-element-property :parent elem)))
24778 (if parent (goto-char (org-element-property :begin parent))
24779 (if (org-with-limited-levels (org-before-first-heading-p))
24780 (user-error "No surrounding element")
24781 (org-with-limited-levels (org-back-to-heading)))))))
24783 (defvar org-element-greater-elements)
24784 (defun org-down-element ()
24785 "Move to inner element."
24786 (interactive)
24787 (let ((element (org-element-at-point)))
24788 (cond
24789 ((memq (org-element-type element) '(plain-list table))
24790 (goto-char (org-element-property :contents-begin element))
24791 (forward-char))
24792 ((memq (org-element-type element) org-element-greater-elements)
24793 ;; If contents are hidden, first disclose them.
24794 (when (outline-invisible-p (line-end-position)) (org-cycle))
24795 (goto-char (or (org-element-property :contents-begin element)
24796 (user-error "No content for this element"))))
24797 (t (user-error "No inner element")))))
24799 (defun org-drag-element-backward ()
24800 "Move backward element at point."
24801 (interactive)
24802 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24803 (let* ((elem (org-element-at-point))
24804 (prev-elem
24805 (save-excursion
24806 (goto-char (org-element-property :begin elem))
24807 (skip-chars-backward " \r\t\n")
24808 (unless (bobp)
24809 (let* ((beg (org-element-property :begin elem))
24810 (prev (org-element-at-point))
24811 (up prev))
24812 (while (and (setq up (org-element-property :parent up))
24813 (<= (org-element-property :end up) beg))
24814 (setq prev up))
24815 prev)))))
24816 ;; Error out if no previous element or previous element is
24817 ;; a parent of the current one.
24818 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24819 (user-error "Cannot drag element backward")
24820 (let ((pos (point)))
24821 (org-element-swap-A-B prev-elem elem)
24822 (goto-char (+ (org-element-property :begin prev-elem)
24823 (- pos (org-element-property :begin elem)))))))))
24825 (defun org-drag-element-forward ()
24826 "Move forward element at point."
24827 (interactive)
24828 (let* ((pos (point))
24829 (elem (org-element-at-point)))
24830 (when (= (point-max) (org-element-property :end elem))
24831 (user-error "Cannot drag element forward"))
24832 (goto-char (org-element-property :end elem))
24833 (let ((next-elem (org-element-at-point)))
24834 (when (or (org-element-nested-p elem next-elem)
24835 (and (eq (org-element-type next-elem) 'headline)
24836 (not (eq (org-element-type elem) 'headline))))
24837 (goto-char pos)
24838 (user-error "Cannot drag element forward"))
24839 ;; Compute new position of point: it's shifted by NEXT-ELEM
24840 ;; body's length (without final blanks) and by the length of
24841 ;; blanks between ELEM and NEXT-ELEM.
24842 (let ((size-next (- (save-excursion
24843 (goto-char (org-element-property :end next-elem))
24844 (skip-chars-backward " \r\t\n")
24845 (forward-line)
24846 ;; Small correction if buffer doesn't end
24847 ;; with a newline character.
24848 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24849 (org-element-property :begin next-elem)))
24850 (size-blank (- (org-element-property :end elem)
24851 (save-excursion
24852 (goto-char (org-element-property :end elem))
24853 (skip-chars-backward " \r\t\n")
24854 (forward-line)
24855 (point)))))
24856 (org-element-swap-A-B elem next-elem)
24857 (goto-char (+ pos size-next size-blank))))))
24859 (defun org-drag-line-forward (arg)
24860 "Drag the line at point ARG lines forward."
24861 (interactive "p")
24862 (dotimes (_ (abs arg))
24863 (let ((c (current-column)))
24864 (if (< 0 arg)
24865 (progn
24866 (beginning-of-line 2)
24867 (transpose-lines 1)
24868 (beginning-of-line 0))
24869 (transpose-lines 1)
24870 (beginning-of-line -1))
24871 (org-move-to-column c))))
24873 (defun org-drag-line-backward (arg)
24874 "Drag the line at point ARG lines backward."
24875 (interactive "p")
24876 (org-drag-line-forward (- arg)))
24878 (defun org-mark-element ()
24879 "Put point at beginning of this element, mark at end.
24881 Interactively, if this command is repeated or (in Transient Mark
24882 mode) if the mark is active, it marks the next element after the
24883 ones already marked."
24884 (interactive)
24885 (let (deactivate-mark)
24886 (if (and (org-called-interactively-p 'any)
24887 (or (and (eq last-command this-command) (mark t))
24888 (and transient-mark-mode mark-active)))
24889 (set-mark
24890 (save-excursion
24891 (goto-char (mark))
24892 (goto-char (org-element-property :end (org-element-at-point)))))
24893 (let ((element (org-element-at-point)))
24894 (end-of-line)
24895 (push-mark (org-element-property :end element) t t)
24896 (goto-char (org-element-property :begin element))))))
24898 (defun org-narrow-to-element ()
24899 "Narrow buffer to current element."
24900 (interactive)
24901 (let ((elem (org-element-at-point)))
24902 (cond
24903 ((eq (car elem) 'headline)
24904 (narrow-to-region
24905 (org-element-property :begin elem)
24906 (org-element-property :end elem)))
24907 ((memq (car elem) org-element-greater-elements)
24908 (narrow-to-region
24909 (org-element-property :contents-begin elem)
24910 (org-element-property :contents-end elem)))
24912 (narrow-to-region
24913 (org-element-property :begin elem)
24914 (org-element-property :end elem))))))
24916 (defun org-transpose-element ()
24917 "Transpose current and previous elements, keeping blank lines between.
24918 Point is moved after both elements."
24919 (interactive)
24920 (org-skip-whitespace)
24921 (let ((end (org-element-property :end (org-element-at-point))))
24922 (org-drag-element-backward)
24923 (goto-char end)))
24925 (defun org-unindent-buffer ()
24926 "Un-indent the visible part of the buffer.
24927 Relative indentation (between items, inside blocks, etc.) isn't
24928 modified."
24929 (interactive)
24930 (unless (eq major-mode 'org-mode)
24931 (user-error "Cannot un-indent a buffer not in Org mode"))
24932 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24933 (unindent-tree
24934 (lambda (contents)
24935 (dolist (element (reverse contents))
24936 (if (memq (org-element-type element) '(headline section))
24937 (funcall unindent-tree (org-element-contents element))
24938 (save-excursion
24939 (save-restriction
24940 (narrow-to-region
24941 (org-element-property :begin element)
24942 (org-element-property :end element))
24943 (org-do-remove-indentation))))))))
24944 (funcall unindent-tree (org-element-contents parse-tree))))
24946 (defun org-show-children (&optional level)
24947 "Show all direct subheadings of this heading.
24948 Prefix arg LEVEL is how many levels below the current level
24949 should be shown. Default is enough to cause the following
24950 heading to appear."
24951 (interactive "p")
24952 ;; If `orgstruct-mode' is active, use the slower version.
24953 (if orgstruct-mode (call-interactively #'outline-show-children)
24954 (save-excursion
24955 (org-back-to-heading t)
24956 (let* ((current-level (funcall outline-level))
24957 (max-level (org-get-valid-level
24958 current-level
24959 (if level (prefix-numeric-value level) 1)))
24960 (end (save-excursion (org-end-of-subtree t t)))
24961 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24962 (past-first-child nil)
24963 ;; Make sure to skip inlinetasks.
24964 (re (format regexp-fmt
24965 current-level
24966 (cond
24967 ((not (featurep 'org-inlinetask)) "")
24968 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24970 (t (1- org-inlinetask-min-level))))))
24971 ;; Display parent heading.
24972 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24973 (forward-line)
24974 ;; Display children. First child may be deeper than expected
24975 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24976 ;; MAX-LEVEL accordingly.
24977 (while (re-search-forward re end t)
24978 (unless past-first-child
24979 (setq re (format regexp-fmt
24980 current-level
24981 (max (funcall outline-level) max-level)))
24982 (setq past-first-child t))
24983 (outline-flag-region
24984 (line-end-position 0) (line-end-position) nil))))))
24986 (defun org-show-subtree ()
24987 "Show everything after this heading at deeper levels."
24988 (interactive)
24989 (outline-flag-region
24990 (point)
24991 (save-excursion
24992 (org-end-of-subtree t t))
24993 nil))
24995 (defun org-show-entry ()
24996 "Show the body directly following this heading.
24997 Show the heading too, if it is currently invisible."
24998 (interactive)
24999 (save-excursion
25000 (ignore-errors
25001 (org-back-to-heading t)
25002 (outline-flag-region
25003 (max (point-min) (1- (point)))
25004 (save-excursion
25005 (if (re-search-forward
25006 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
25007 (match-beginning 1)
25008 (point-max)))
25009 nil)
25010 (org-cycle-hide-drawers 'children))))
25012 (defun org-make-options-regexp (kwds &optional extra)
25013 "Make a regular expression for keyword lines.
25014 KWDS is a list of keywords, as strings. Optional argument EXTRA,
25015 when non-nil, is a regexp matching keywords names."
25016 (concat "^[ \t]*#\\+\\("
25017 (regexp-opt kwds)
25018 (and extra (concat (and kwds "\\|") extra))
25019 "\\):[ \t]*\\(.*\\)"))
25021 ;;;; Integration with and fixes for other packages
25023 ;;; Imenu support
25025 (defvar-local org-imenu-markers nil
25026 "All markers currently used by Imenu.")
25028 (defun org-imenu-new-marker (&optional pos)
25029 "Return a new marker for use by Imenu, and remember the marker."
25030 (let ((m (make-marker)))
25031 (move-marker m (or pos (point)))
25032 (push m org-imenu-markers)
25035 (defun org-imenu-get-tree ()
25036 "Produce the index for Imenu."
25037 (dolist (x org-imenu-markers) (move-marker x nil))
25038 (setq org-imenu-markers nil)
25039 (let* ((case-fold-search nil)
25040 (n org-imenu-depth)
25041 (re (concat "^" (org-get-limited-outline-regexp)))
25042 (subs (make-vector (1+ n) nil))
25043 (last-level 0)
25044 m level head0 head)
25045 (save-excursion
25046 (save-restriction
25047 (widen)
25048 (goto-char (point-max))
25049 (while (re-search-backward re nil t)
25050 (setq level (org-reduced-level (funcall outline-level)))
25051 (when (and (<= level n)
25052 (looking-at org-complex-heading-regexp)
25053 (setq head0 (match-string-no-properties 4)))
25054 (setq head (org-link-display-format head0)
25055 m (org-imenu-new-marker))
25056 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
25057 (if (>= level last-level)
25058 (push (cons head m) (aref subs level))
25059 (push (cons head (aref subs (1+ level))) (aref subs level))
25060 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
25061 (setq last-level level)))))
25062 (aref subs 1)))
25064 (eval-after-load "imenu"
25065 '(progn
25066 (add-hook 'imenu-after-jump-hook
25067 (lambda ()
25068 (when (derived-mode-p 'org-mode)
25069 (org-show-context 'org-goto))))))
25071 (defun org-link-display-format (s)
25072 "Replace links in string S with their description.
25073 If there is no description, use the link target."
25074 (save-match-data
25075 (replace-regexp-in-string
25076 org-bracket-link-analytic-regexp
25077 (lambda (m)
25078 (if (match-end 5) (match-string 5 m)
25079 (concat (match-string 1 m) (match-string 3 m))))
25080 s nil t)))
25082 (defun org-toggle-link-display ()
25083 "Toggle the literal or descriptive display of links."
25084 (interactive)
25085 (if org-descriptive-links
25086 (progn (org-remove-from-invisibility-spec '(org-link))
25087 (org-restart-font-lock)
25088 (setq org-descriptive-links nil))
25089 (progn (add-to-invisibility-spec '(org-link))
25090 (org-restart-font-lock)
25091 (setq org-descriptive-links t))))
25093 ;; Speedbar support
25095 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25096 "Overlay marking the agenda restriction line in speedbar.")
25097 (overlay-put org-speedbar-restriction-lock-overlay
25098 'face 'org-agenda-restriction-lock)
25099 (overlay-put org-speedbar-restriction-lock-overlay
25100 'help-echo "Agendas are currently limited to this item.")
25101 (delete-overlay org-speedbar-restriction-lock-overlay)
25103 (defun org-speedbar-set-agenda-restriction ()
25104 "Restrict future agenda commands to the location at point in speedbar.
25105 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25106 (interactive)
25107 (require 'org-agenda)
25108 (let (p m tp np dir txt)
25109 (cond
25110 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25111 'org-imenu t))
25112 (setq m (get-text-property p 'org-imenu-marker))
25113 (with-current-buffer (marker-buffer m)
25114 (goto-char m)
25115 (org-agenda-set-restriction-lock 'subtree)))
25116 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25117 'speedbar-function 'speedbar-find-file))
25118 (setq tp (previous-single-property-change
25119 (1+ p) 'speedbar-function)
25120 np (next-single-property-change
25121 tp 'speedbar-function)
25122 dir (speedbar-line-directory)
25123 txt (buffer-substring-no-properties (or tp (point-min))
25124 (or np (point-max))))
25125 (with-current-buffer (find-file-noselect
25126 (let ((default-directory dir))
25127 (expand-file-name txt)))
25128 (unless (derived-mode-p 'org-mode)
25129 (user-error "Cannot restrict to non-Org-mode file"))
25130 (org-agenda-set-restriction-lock 'file)))
25131 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25132 (move-overlay org-speedbar-restriction-lock-overlay
25133 (point-at-bol) (point-at-eol))
25134 (setq current-prefix-arg nil)
25135 (org-agenda-maybe-redo)))
25137 (defvar speedbar-file-key-map)
25138 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25139 (eval-after-load "speedbar"
25140 '(progn
25141 (speedbar-add-supported-extension ".org")
25142 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25143 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25144 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25145 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25146 (add-hook 'speedbar-visiting-tag-hook
25147 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25149 ;;; Fixes and Hacks for problems with other packages
25151 (defun org--flyspell-object-check-p (element)
25152 "Non-nil when Flyspell can check object at point.
25153 ELEMENT is the element at point."
25154 (let ((object (save-excursion
25155 (when (looking-at-p "\\>") (backward-char))
25156 (org-element-context element))))
25157 (cl-case (org-element-type object)
25158 ;; Prevent checks in links due to keybinding conflict with
25159 ;; Flyspell.
25160 ((code entity export-snippet inline-babel-call
25161 inline-src-block line-break latex-fragment link macro
25162 statistics-cookie target timestamp verbatim)
25163 nil)
25164 (footnote-reference
25165 ;; Only in inline footnotes, within the definition.
25166 (and (eq (org-element-property :type object) 'inline)
25167 (< (save-excursion
25168 (goto-char (org-element-property :begin object))
25169 (search-forward ":" nil t 2))
25170 (point))))
25171 (otherwise t))))
25173 (defun org-mode-flyspell-verify ()
25174 "Function used for `flyspell-generic-check-word-predicate'."
25175 (if (org-at-heading-p)
25176 ;; At a headline or an inlinetask, check title only. This is
25177 ;; faster than relying on `org-element-at-point'.
25178 (and (save-excursion (beginning-of-line)
25179 (and (let ((case-fold-search t))
25180 (not (looking-at "\\*+ END[ \t]*$")))
25181 (looking-at org-complex-heading-regexp)))
25182 (match-beginning 4)
25183 (>= (point) (match-beginning 4))
25184 (or (not (match-beginning 5))
25185 (< (point) (match-beginning 5))))
25186 (let* ((element (org-element-at-point))
25187 (post-affiliated (org-element-property :post-affiliated element)))
25188 (cond
25189 ;; Ignore checks in all affiliated keywords but captions.
25190 ((< (point) post-affiliated)
25191 (and (save-excursion
25192 (beginning-of-line)
25193 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25194 (> (point) (match-end 0))
25195 (org--flyspell-object-check-p element)))
25196 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25197 ((let ((log (org-log-into-drawer)))
25198 (and log
25199 (let ((drawer (org-element-lineage element '(drawer))))
25200 (and drawer
25201 (eq (compare-strings
25202 log nil nil
25203 (org-element-property :drawer-name drawer) nil nil t)
25204 t)))))
25205 nil)
25207 (cl-case (org-element-type element)
25208 ((comment quote-section) t)
25209 (comment-block
25210 ;; Allow checks between block markers, not on them.
25211 (and (> (line-beginning-position) post-affiliated)
25212 (save-excursion
25213 (end-of-line)
25214 (skip-chars-forward " \r\t\n")
25215 (< (point) (org-element-property :end element)))))
25216 ;; Arbitrary list of keywords where checks are meaningful.
25217 ;; Make sure point is on the value part of the element.
25218 (keyword
25219 (and (member (org-element-property :key element)
25220 '("DESCRIPTION" "TITLE"))
25221 (save-excursion
25222 (search-backward ":" (line-beginning-position) t))))
25223 ;; Check is globally allowed in paragraphs verse blocks and
25224 ;; table rows (after affiliated keywords) but some objects
25225 ;; must not be affected.
25226 ((paragraph table-row verse-block)
25227 (let ((cbeg (org-element-property :contents-begin element))
25228 (cend (org-element-property :contents-end element)))
25229 (and cbeg (>= (point) cbeg) (< (point) cend)
25230 (org--flyspell-object-check-p element))))))))))
25231 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25233 (defun org-remove-flyspell-overlays-in (beg end)
25234 "Remove flyspell overlays in region."
25235 (and (org-bound-and-true-p flyspell-mode)
25236 (fboundp 'flyspell-delete-region-overlays)
25237 (flyspell-delete-region-overlays beg end)))
25239 (defvar flyspell-delayed-commands)
25240 (eval-after-load "flyspell"
25241 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25243 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25244 (eval-after-load "bookmark"
25245 '(if (boundp 'bookmark-after-jump-hook)
25246 ;; We can use the hook
25247 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25248 ;; Hook not available, use advice
25249 (defadvice bookmark-jump (after org-make-visible activate)
25250 "Make the position visible."
25251 (org-bookmark-jump-unhide))))
25253 ;; Make sure saveplace shows the location if it was hidden
25254 (eval-after-load "saveplace"
25255 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25256 "Make the position visible."
25257 (org-bookmark-jump-unhide)))
25259 ;; Make sure ecb shows the location if it was hidden
25260 (eval-after-load "ecb"
25261 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25262 "Make hierarchy visible when jumping into location from ECB tree buffer."
25263 (when (derived-mode-p 'org-mode)
25264 (org-show-context))))
25266 (defun org-bookmark-jump-unhide ()
25267 "Unhide the current position, to show the bookmark location."
25268 (and (derived-mode-p 'org-mode)
25269 (or (outline-invisible-p)
25270 (save-excursion (goto-char (max (point-min) (1- (point))))
25271 (outline-invisible-p)))
25272 (org-show-context 'bookmark-jump)))
25274 (defun org-mark-jump-unhide ()
25275 "Make the point visible with `org-show-context' after jumping to the mark."
25276 (when (and (derived-mode-p 'org-mode)
25277 (outline-invisible-p))
25278 (org-show-context 'mark-goto)))
25280 (eval-after-load "simple"
25281 '(defadvice pop-to-mark-command (after org-make-visible activate)
25282 "Make the point visible with `org-show-context'."
25283 (org-mark-jump-unhide)))
25285 (eval-after-load "simple"
25286 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25287 "Make the point visible with `org-show-context'."
25288 (org-mark-jump-unhide)))
25290 (eval-after-load "simple"
25291 '(defadvice pop-global-mark (after org-make-visible activate)
25292 "Make the point visible with `org-show-context'."
25293 (org-mark-jump-unhide)))
25295 ;; Make session.el ignore our circular variable
25296 (defvar session-globals-exclude)
25297 (eval-after-load "session"
25298 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25300 ;;;; Finish up
25302 (provide 'org)
25304 (run-hooks 'org-load-hook)
25306 ;;; org.el ends here