Merge branch 'maint'
[org-mode/org-tableheadings.git] / lisp / org.el
blob28b4d52b6d6372511e0fd1ebc930eb7277e4a1e2
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (require 'cl-lib)
73 (eval-when-compile (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 (declare-function calendar-check-holidays "holidays" (date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function isearch-no-upper-case-p "isearch" (string regexp-flag))
115 (declare-function org-add-archive-files "org-archive" (files))
116 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
117 (declare-function org-agenda-list "org-agenda"
118 (&optional arg start-day span with-hour))
119 (declare-function org-agenda-redo "org-agenda" (&optional all))
120 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body) t)
121 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
122 (declare-function org-beamer-mode "ox-beamer" (&optional prefix) t)
123 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
124 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
125 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
126 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
127 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
128 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
129 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
130 (declare-function org-clock-update-time-maybe "org-clock" ())
131 (declare-function org-clocktable-shift "org-clock" (dir n))
132 (declare-function org-element-at-point "org-element" ())
133 (declare-function org-element-cache-refresh "org-element" (pos))
134 (declare-function org-element-cache-reset "org-element" (&optional all))
135 (declare-function org-element-contents "org-element" (element))
136 (declare-function org-element-context "org-element" (&optional element))
137 (declare-function org-element-copy "org-element" (datum))
138 (declare-function org-element-interpret-data "org-element" (data))
139 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
140 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
141 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
142 (declare-function org-element-property "org-element" (property element))
143 (declare-function org-element-put-property "org-element" (element property value))
144 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
145 (declare-function org-element-type "org-element" (element))
146 (declare-function org-element-update-syntax "org-element" ())
147 (declare-function org-id-find-id-file "org-id" (id))
148 (declare-function org-id-get-create "org-id" (&optional force))
149 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
150 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
151 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
152 (declare-function org-plot/gnuplot "org-plot" (&optional params))
153 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
154 (declare-function org-table-align "org-table" ())
155 (declare-function org-table-begin "org-table" (&optional table-type))
156 (declare-function org-table-beginning-of-field "org-table" (&optional n))
157 (declare-function org-table-blank-field "org-table" ())
158 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
159 (declare-function org-table-edit-field "org-table" (arg))
160 (declare-function org-table-end "org-table" (&optional table-type))
161 (declare-function org-table-end-of-field "org-table" (&optional n))
162 (declare-function org-table-insert-row "org-table" (&optional arg))
163 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
164 (declare-function org-table-maybe-eval-formula "org-table" ())
165 (declare-function org-table-maybe-recalculate-line "org-table" ())
166 (declare-function org-table-next-row "org-table" ())
167 (declare-function org-table-paste-rectangle "org-table" ())
168 (declare-function org-table-wrap-region "org-table" (arg))
169 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
170 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
171 (declare-function orgtbl-mode "org-table" (&optional arg))
173 (defsubst org-uniquify (list)
174 "Non-destructively remove duplicate elements from LIST."
175 (let ((res (copy-sequence list))) (delete-dups res)))
177 (defsubst org-get-at-bol (property)
178 "Get text property PROPERTY at the beginning of line."
179 (get-text-property (point-at-bol) property))
181 (defsubst org-trim (s)
182 "Remove whitespace at the beginning and the end of string S."
183 (replace-regexp-in-string
184 "\\`[ \t\n\r]+" ""
185 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
187 ;; load languages based on value of `org-babel-load-languages'
188 (defvar org-babel-load-languages)
190 ;;;###autoload
191 (defun org-babel-do-load-languages (sym value)
192 "Load the languages defined in `org-babel-load-languages'."
193 (set-default sym value)
194 (dolist (pair org-babel-load-languages)
195 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
196 (if active
197 (require (intern (concat "ob-" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-execute:" lang)))
200 (funcall 'fmakunbound
201 (intern (concat "org-babel-expand-body:" lang)))))))
203 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
204 ;;;###autoload
205 (defun org-babel-load-file (file &optional compile)
206 "Load Emacs Lisp source code blocks in the Org-mode FILE.
207 This function exports the source code using `org-babel-tangle'
208 and then loads the resulting file using `load-file'. With prefix
209 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
210 file to byte-code before it is loaded."
211 (interactive "fFile to load: \nP")
212 (let* ((age (lambda (file)
213 (float-time
214 (time-subtract (current-time)
215 (nth 5 (or (file-attributes (file-truename file))
216 (file-attributes file)))))))
217 (base-name (file-name-sans-extension file))
218 (exported-file (concat base-name ".el")))
219 ;; tangle if the org-mode file is newer than the elisp file
220 (unless (and (file-exists-p exported-file)
221 (> (funcall age file) (funcall age exported-file)))
222 ;; Tangle-file traversal returns reversed list of tangled files
223 ;; and we want to evaluate the first target.
224 (setq exported-file
225 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
226 (message "%s %s"
227 (if compile
228 (progn (byte-compile-file exported-file 'load)
229 "Compiled and loaded")
230 (progn (load-file exported-file) "Loaded"))
231 exported-file)))
233 (defcustom org-babel-load-languages '((emacs-lisp . t))
234 "Languages which can be evaluated in Org-mode buffers.
235 This list can be used to load support for any of the languages
236 below, note that each language will depend on a different set of
237 system executables and/or Emacs modes. When a language is
238 \"loaded\", then code blocks in that language can be evaluated
239 with `org-babel-execute-src-block' bound by default to C-c
240 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
241 be set to remove code block evaluation from the C-c C-c
242 keybinding. By default only Emacs Lisp (which has no
243 requirements) is loaded."
244 :group 'org-babel
245 :set 'org-babel-do-load-languages
246 :version "24.1"
247 :type '(alist :tag "Babel Languages"
248 :key-type
249 (choice
250 (const :tag "Awk" awk)
251 (const :tag "C" C)
252 (const :tag "R" R)
253 (const :tag "Asymptote" asymptote)
254 (const :tag "Calc" calc)
255 (const :tag "Clojure" clojure)
256 (const :tag "CSS" css)
257 (const :tag "Ditaa" ditaa)
258 (const :tag "Dot" dot)
259 (const :tag "Emacs Lisp" emacs-lisp)
260 (const :tag "Forth" forth)
261 (const :tag "Fortran" fortran)
262 (const :tag "Gnuplot" gnuplot)
263 (const :tag "Haskell" haskell)
264 (const :tag "IO" io)
265 (const :tag "J" J)
266 (const :tag "Java" java)
267 (const :tag "Javascript" js)
268 (const :tag "LaTeX" latex)
269 (const :tag "Ledger" ledger)
270 (const :tag "Lilypond" lilypond)
271 (const :tag "Lisp" lisp)
272 (const :tag "Makefile" makefile)
273 (const :tag "Maxima" maxima)
274 (const :tag "Matlab" matlab)
275 (const :tag "Mscgen" mscgen)
276 (const :tag "Ocaml" ocaml)
277 (const :tag "Octave" octave)
278 (const :tag "Org" org)
279 (const :tag "Perl" perl)
280 (const :tag "Pico Lisp" picolisp)
281 (const :tag "PlantUML" plantuml)
282 (const :tag "Python" python)
283 (const :tag "Ruby" ruby)
284 (const :tag "Sass" sass)
285 (const :tag "Scala" scala)
286 (const :tag "Scheme" scheme)
287 (const :tag "Screen" screen)
288 (const :tag "Shell Script" shell)
289 (const :tag "Shen" shen)
290 (const :tag "Sql" sql)
291 (const :tag "Sqlite" sqlite)
292 (const :tag "Stan" stan)
293 (const :tag "ebnf2ps" ebnf2ps))
294 :value-type (boolean :tag "Activate" :value t)))
296 ;;;; Customization variables
297 (defcustom org-clone-delete-id nil
298 "Remove ID property of clones of a subtree.
299 When non-nil, clones of a subtree don't inherit the ID property.
300 Otherwise they inherit the ID property with a new unique
301 identifier."
302 :type 'boolean
303 :version "24.1"
304 :group 'org-id)
306 ;;; Version
307 (org-check-version)
309 ;;;###autoload
310 (defun org-version (&optional here full message)
311 "Show the org-mode version.
312 Interactively, or when MESSAGE is non-nil, show it in echo area.
313 With prefix argument, or when HERE is non-nil, insert it at point.
314 In non-interactive uses, a reduced version string is output unless
315 FULL is given."
316 (interactive (list current-prefix-arg t (not current-prefix-arg)))
317 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
318 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
319 (load-suffixes (list ".el"))
320 (org-install-dir
321 (ignore-errors (org-find-library-dir "org-loaddefs"))))
322 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
323 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
324 (let* ((load-suffixes save-load-suffixes)
325 (release (org-release))
326 (git-version (org-git-version))
327 (version (format "Org-mode version %s (%s @ %s)"
328 release
329 git-version
330 (if org-install-dir
331 (if (string= org-dir org-install-dir)
332 org-install-dir
333 (concat "mixed installation! "
334 org-install-dir
335 " and "
336 org-dir))
337 "org-loaddefs.el can not be found!")))
338 (version1 (if full version release)))
339 (when here (insert version1))
340 (when message (message "%s" version1))
341 version1)))
343 (defconst org-version (org-version))
346 ;;; Syntax Constants
348 ;;;; Block
350 (defconst org-block-regexp
351 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
352 "Regular expression for hiding blocks.")
354 (defconst org-dblock-start-re
355 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
356 "Matches the start line of a dynamic block, with parameters.")
358 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
359 "Matches the end of a dynamic block.")
361 ;;;; Clock and Planning
363 (defconst org-clock-string "CLOCK:"
364 "String used as prefix for timestamps clocking work hours on an item.")
366 (defvar org-closed-string "CLOSED:"
367 "String used as the prefix for timestamps logging closing a TODO entry.")
369 (defvar org-deadline-string "DEADLINE:"
370 "String to mark deadline entries.
371 A deadline is this string, followed by a time stamp. Should be a word,
372 terminated by a colon. You can insert a schedule keyword and
373 a timestamp with \\[org-deadline].")
375 (defvar org-scheduled-string "SCHEDULED:"
376 "String to mark scheduled TODO entries.
377 A schedule is this string, followed by a time stamp. Should be a word,
378 terminated by a colon. You can insert a schedule keyword and
379 a timestamp with \\[org-schedule].")
381 (defconst org-ds-keyword-length
382 (+ 2
383 (apply #'max
384 (mapcar #'length
385 (list org-deadline-string org-scheduled-string
386 org-clock-string org-closed-string))))
387 "Maximum length of the DEADLINE and SCHEDULED keywords.")
389 (defconst org-planning-line-re
390 (concat "^[ \t]*"
391 (regexp-opt
392 (list org-closed-string org-deadline-string org-scheduled-string)
394 "Matches a line with planning info.
395 Matched keyword is in group 1.")
397 (defconst org-clock-line-re
398 (concat "^[ \t]*" org-clock-string)
399 "Matches a line with clock info.")
401 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
402 "Matches the DEADLINE keyword.")
404 (defconst org-deadline-time-regexp
405 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
406 "Matches the DEADLINE keyword together with a time stamp.")
408 (defconst org-deadline-time-hour-regexp
409 (concat "\\<" org-deadline-string
410 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
411 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
413 (defconst org-deadline-line-regexp
414 (concat "\\<\\(" org-deadline-string "\\).*")
415 "Matches the DEADLINE keyword and the rest of the line.")
417 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
418 "Matches the SCHEDULED keyword.")
420 (defconst org-scheduled-time-regexp
421 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
422 "Matches the SCHEDULED keyword together with a time stamp.")
424 (defconst org-scheduled-time-hour-regexp
425 (concat "\\<" org-scheduled-string
426 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
427 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
429 (defconst org-closed-time-regexp
430 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
431 "Matches the CLOSED keyword together with a time stamp.")
433 (defconst org-keyword-time-regexp
434 (concat "\\<"
435 (regexp-opt
436 (list org-scheduled-string org-deadline-string org-closed-string
437 org-clock-string)
439 " *[[<]\\([^]>]+\\)[]>]")
440 "Matches any of the 4 keywords, together with the time stamp.")
442 (defconst org-keyword-time-not-clock-regexp
443 (concat
444 "\\<"
445 (regexp-opt
446 (list org-scheduled-string org-deadline-string org-closed-string) t)
447 " *[[<]\\([^]>]+\\)[]>]")
448 "Matches any of the 3 keywords, together with the time stamp.")
450 (defconst org-maybe-keyword-time-regexp
451 (concat "\\(\\<"
452 (regexp-opt
453 (list org-scheduled-string org-deadline-string org-closed-string
454 org-clock-string)
456 "\\)?"
457 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
458 "\\|"
459 "<%%([^\r\n>]*>\\)")
460 "Matches a timestamp, possibly preceded by a keyword.")
462 (defconst org-all-time-keywords
463 (mapcar (lambda (w) (substring w 0 -1))
464 (list org-scheduled-string org-deadline-string
465 org-clock-string org-closed-string))
466 "List of time keywords.")
468 ;;;; Drawer
470 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
471 "Matches first or last line of a hidden block.
472 Group 1 contains drawer's name or \"END\".")
474 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
475 "Regular expression matching the first line of a property drawer.")
477 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
478 "Regular expression matching the last line of a property drawer.")
480 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
481 "Regular expression matching the first line of a clock drawer.")
483 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
484 "Regular expression matching the last line of a clock drawer.")
486 (defconst org-property-drawer-re
487 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
488 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
489 "[ \t]*:END:[ \t]*$")
490 "Matches an entire property drawer.")
492 (defconst org-clock-drawer-re
493 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
494 org-clock-drawer-end-re "\\)\n?")
495 "Matches an entire clock drawer.")
497 ;;;; Headline
499 (defconst org-heading-keyword-regexp-format
500 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
501 "Printf format for a regexp matching a headline with some keyword.
502 This regexp will match the headline of any node which has the
503 exact keyword that is put into the format. The keyword isn't in
504 any group by default, but the stars and the body are.")
506 (defconst org-heading-keyword-maybe-regexp-format
507 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
508 "Printf format for a regexp matching a headline, possibly with some keyword.
509 This regexp can match any headline with the specified keyword, or
510 without a keyword. The keyword isn't in any group by default,
511 but the stars and the body are.")
513 (defconst org-archive-tag "ARCHIVE"
514 "The tag that marks a subtree as archived.
515 An archived subtree does not open during visibility cycling, and does
516 not contribute to the agenda listings.")
518 (defconst org-comment-string "COMMENT"
519 "Entries starting with this keyword will never be exported.
520 An entry can be toggled between COMMENT and normal with
521 \\[org-toggle-comment].")
524 ;;;; LaTeX Environments and Fragments
526 (defconst org-latex-regexps
527 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
528 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
529 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
530 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
531 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
532 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
533 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
534 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
535 "Regular expressions for matching embedded LaTeX.")
537 ;;;; Node Property
539 (defconst org-effort-property "Effort"
540 "The property that is being used to keep track of effort estimates.
541 Effort estimates given in this property need to have the format H:MM.")
543 ;;;; Table
545 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
546 "Detect an org-type or table-type table.")
548 (defconst org-table-line-regexp "^[ \t]*|"
549 "Detect an org-type table line.")
551 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
552 "Detect an org-type table line.")
554 (defconst org-table-hline-regexp "^[ \t]*|-"
555 "Detect an org-type table hline.")
557 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
558 "Detect a table-type table hline.")
560 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
561 "Detect the first line outside a table when searching from within it.
562 This works for both table types.")
564 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
565 "Detect a #+TBLFM line.")
567 ;;;; Timestamp
569 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
570 "Regular expression for fast time stamp matching.")
572 (defconst org-ts-regexp-inactive
573 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
574 "Regular expression for fast inactive time stamp matching.")
576 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
577 "Regular expression for fast time stamp matching.")
579 (defconst org-ts-regexp0
580 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
581 "Regular expression matching time strings for analysis.
582 This one does not require the space after the date, so it can be used
583 on a string that terminates immediately after the date.")
585 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
586 "Regular expression matching time strings for analysis.")
588 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
589 "Regular expression matching time stamps, with groups.")
591 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
592 "Regular expression matching time stamps (also [..]), with groups.")
594 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
595 "Regular expression matching a time stamp range.")
597 (defconst org-tr-regexp-both
598 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
599 "Regular expression matching a time stamp range.")
601 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
602 org-ts-regexp "\\)?")
603 "Regular expression matching a time stamp or time stamp range.")
605 (defconst org-tsr-regexp-both
606 (concat org-ts-regexp-both "\\(--?-?"
607 org-ts-regexp-both "\\)?")
608 "Regular expression matching a time stamp or time stamp range.
609 The time stamps may be either active or inactive.")
611 (defconst org-repeat-re
612 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
613 "Regular expression for specifying repeated events.
614 After a match, group 1 contains the repeat expression.")
616 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
617 "Formats for `format-time-string' which are used for time stamps.")
620 ;;; The custom variables
622 (defgroup org nil
623 "Outline-based notes management and organizer."
624 :tag "Org"
625 :group 'outlines
626 :group 'calendar)
628 (defcustom org-mode-hook nil
629 "Mode hook for Org-mode, run after the mode was turned on."
630 :group 'org
631 :type 'hook)
633 (defcustom org-load-hook nil
634 "Hook that is run after org.el has been loaded."
635 :group 'org
636 :type 'hook)
638 (defcustom org-log-buffer-setup-hook nil
639 "Hook that is run after an Org log buffer is created."
640 :group 'org
641 :version "24.1"
642 :type 'hook)
644 (defvar org-modules) ; defined below
645 (defvar org-modules-loaded nil
646 "Have the modules been loaded already?")
648 (defun org-load-modules-maybe (&optional force)
649 "Load all extensions listed in `org-modules'."
650 (when (or force (not org-modules-loaded))
651 (dolist (ext org-modules)
652 (condition-case nil (require ext)
653 (error (message "Problems while trying to load feature `%s'" ext))))
654 (setq org-modules-loaded t)))
656 (defun org-set-modules (var value)
657 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
658 (set var value)
659 (when (featurep 'org)
660 (org-load-modules-maybe 'force)
661 (org-element-cache-reset 'all)))
663 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
664 "Modules that should always be loaded together with org.el.
666 If a description starts with <C>, the file is not part of Emacs
667 and loading it will require that you have downloaded and properly
668 installed the Org mode distribution.
670 You can also use this system to load external packages (i.e. neither Org
671 core modules, nor modules from the CONTRIB directory). Just add symbols
672 to the end of the list. If the package is called org-xyz.el, then you need
673 to add the symbol `xyz', and the package must have a call to:
675 (provide \\='org-xyz)
677 For export specific modules, see also `org-export-backends'."
678 :group 'org
679 :set 'org-set-modules
680 :version "24.4"
681 :package-version '(Org . "8.0")
682 :type
683 '(set :greedy t
684 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
685 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
686 (const :tag " crypt: Encryption of subtrees" org-crypt)
687 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
688 (const :tag " docview: Links to doc-view buffers" org-docview)
689 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
690 (const :tag " habit: Track your consistency with habits" org-habit)
691 (const :tag " id: Global IDs for identifying entries" org-id)
692 (const :tag " info: Links to Info nodes" org-info)
693 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
694 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
695 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
696 (const :tag " mouse: Additional mouse support" org-mouse)
697 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
698 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
699 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
701 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
702 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
703 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
704 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
705 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
706 (const :tag "C collector: Collect properties into tables" org-collector)
707 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
708 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
709 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
710 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
711 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
712 (const :tag "C eval: Include command output as text" org-eval)
713 (const :tag "C eww: Store link to url of eww" org-eww)
714 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
715 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
716 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
717 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
718 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
719 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
720 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
721 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
722 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
723 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
724 (const :tag "C mew: Links to Mew folders/messages" org-mew)
725 (const :tag "C mtags: Support for muse-like tags" org-mtags)
726 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
727 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
728 (const :tag "C registry: A registry for Org-mode links" org-registry)
729 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
730 (const :tag "C secretary: Team management with org-mode" org-secretary)
731 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
732 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
733 (const :tag "C track: Keep up with Org-mode development" org-track)
734 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
735 (const :tag "C vm: Links to VM folders/messages" org-vm)
736 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
737 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
738 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
740 (defvar org-export-registered-backends) ; From ox.el.
741 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
742 (declare-function org-export-backend-name "ox" (backend) t)
743 (defcustom org-export-backends '(ascii html icalendar latex odt)
744 "List of export back-ends that should be always available.
746 If a description starts with <C>, the file is not part of Emacs
747 and loading it will require that you have downloaded and properly
748 installed the Org mode distribution.
750 Unlike to `org-modules', libraries in this list will not be
751 loaded along with Org, but only once the export framework is
752 needed.
754 This variable needs to be set before org.el is loaded. If you
755 need to make a change while Emacs is running, use the customize
756 interface or run the following code, where VAL stands for the new
757 value of the variable, after updating it:
759 (progn
760 (setq org-export-registered-backends
761 (cl-remove-if-not
762 (lambda (backend)
763 (let ((name (org-export-backend-name backend)))
764 (or (memq name val)
765 (catch \\='parentp
766 (dolist (b val)
767 (and (org-export-derived-backend-p b name)
768 (throw \\='parentp t)))))))
769 org-export-registered-backends))
770 (let ((new-list (mapcar #\\='org-export-backend-name
771 org-export-registered-backends)))
772 (dolist (backend val)
773 (cond
774 ((not (load (format \"ox-%s\" backend) t t))
775 (message \"Problems while trying to load export back-end \\=`%s\\='\"
776 backend))
777 ((not (memq backend new-list)) (push backend new-list))))
778 (set-default \\='org-export-backends new-list)))
780 Adding a back-end to this list will also pull the back-end it
781 depends on, if any."
782 :group 'org
783 :group 'org-export
784 :version "25.1"
785 :package-version '(Org . "9.0")
786 :initialize 'custom-initialize-set
787 :set (lambda (var val)
788 (if (not (featurep 'ox)) (set-default var val)
789 ;; Any back-end not required anymore (not present in VAL and not
790 ;; a parent of any back-end in the new value) is removed from the
791 ;; list of registered back-ends.
792 (setq org-export-registered-backends
793 (cl-remove-if-not
794 (lambda (backend)
795 (let ((name (org-export-backend-name backend)))
796 (or (memq name val)
797 (catch 'parentp
798 (dolist (b val)
799 (and (org-export-derived-backend-p b name)
800 (throw 'parentp t)))))))
801 org-export-registered-backends))
802 ;; Now build NEW-LIST of both new back-ends and required
803 ;; parents.
804 (let ((new-list (mapcar #'org-export-backend-name
805 org-export-registered-backends)))
806 (dolist (backend val)
807 (cond
808 ((not (load (format "ox-%s" backend) t t))
809 (message "Problems while trying to load export back-end `%s'"
810 backend))
811 ((not (memq backend new-list)) (push backend new-list))))
812 ;; Set VAR to that list with fixed dependencies.
813 (set-default var new-list))))
814 :type '(set :greedy t
815 (const :tag " ascii Export buffer to ASCII format" ascii)
816 (const :tag " beamer Export buffer to Beamer presentation" beamer)
817 (const :tag " html Export buffer to HTML format" html)
818 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
819 (const :tag " latex Export buffer to LaTeX format" latex)
820 (const :tag " man Export buffer to MAN format" man)
821 (const :tag " md Export buffer to Markdown format" md)
822 (const :tag " odt Export buffer to ODT format" odt)
823 (const :tag " org Export buffer to Org format" org)
824 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
825 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
826 (const :tag "C deck Export buffer to deck.js presentations" deck)
827 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
828 (const :tag "C groff Export buffer to Groff format" groff)
829 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
830 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
831 (const :tag "C s5 Export buffer to s5 presentations" s5)
832 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
834 (eval-after-load 'ox
835 '(dolist (backend org-export-backends)
836 (condition-case nil (require (intern (format "ox-%s" backend)))
837 (error (message "Problems while trying to load export back-end `%s'"
838 backend)))))
840 (defcustom org-support-shift-select nil
841 "Non-nil means make shift-cursor commands select text when possible.
842 \\<org-mode-map>\
844 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
845 start selecting a region, or enlarge regions started in this way.
846 In Org-mode, in special contexts, these same keys are used for
847 other purposes, important enough to compete with shift selection.
848 Org tries to balance these needs by supporting `shift-select-mode'
849 outside these special contexts, under control of this variable.
851 The default of this variable is nil, to avoid confusing behavior. Shifted
852 cursor keys will then execute Org commands in the following contexts:
853 - on a headline, changing TODO state (left/right) and priority (up/down)
854 - on a time stamp, changing the time
855 - in a plain list item, changing the bullet type
856 - in a property definition line, switching between allowed values
857 - in the BEGIN line of a clock table (changing the time block).
858 Outside these contexts, the commands will throw an error.
860 When this variable is t and the cursor is not in a special
861 context, Org-mode will support shift-selection for making and
862 enlarging regions. To make this more effective, the bullet
863 cycling will no longer happen anywhere in an item line, but only
864 if the cursor is exactly on the bullet.
866 If you set this variable to the symbol `always', then the keys
867 will not be special in headlines, property lines, and item lines,
868 to make shift selection work there as well. If this is what you
869 want, you can use the following alternative commands:
870 `\\[org-todo]' and `\\[org-priority]' \
871 to change TODO state and priority,
872 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
873 can be used to switch TODO sets,
874 `\\[org-ctrl-c-minus]' to cycle item bullet types,
875 and properties can be edited by hand or in column view.
877 However, when the cursor is on a timestamp, shift-cursor commands
878 will still edit the time stamp - this is just too good to give up."
879 :group 'org
880 :type '(choice
881 (const :tag "Never" nil)
882 (const :tag "When outside special context" t)
883 (const :tag "Everywhere except timestamps" always)))
885 (defcustom org-loop-over-headlines-in-active-region nil
886 "Shall some commands act upon headlines in the active region?
888 When set to t, some commands will be performed in all headlines
889 within the active region.
891 When set to `start-level', some commands will be performed in all
892 headlines within the active region, provided that these headlines
893 are of the same level than the first one.
895 When set to a string, those commands will be performed on the
896 matching headlines within the active region. Such string must be
897 a tags/property/todo match as it is used in the agenda tags view.
899 The list of commands is: `org-schedule', `org-deadline',
900 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
901 `org-archive-to-archive-sibling'. The archiving commands skip
902 already archived entries."
903 :type '(choice (const :tag "Don't loop" nil)
904 (const :tag "All headlines in active region" t)
905 (const :tag "In active region, headlines at the same level than the first one" start-level)
906 (string :tag "Tags/Property/Todo matcher"))
907 :version "24.1"
908 :group 'org-todo
909 :group 'org-archive)
911 (defgroup org-startup nil
912 "Options concerning startup of Org-mode."
913 :tag "Org Startup"
914 :group 'org)
916 (defcustom org-startup-folded t
917 "Non-nil means entering Org-mode will switch to OVERVIEW.
918 This can also be configured on a per-file basis by adding one of
919 the following lines anywhere in the buffer:
921 #+STARTUP: fold (or `overview', this is equivalent)
922 #+STARTUP: nofold (or `showall', this is equivalent)
923 #+STARTUP: content
924 #+STARTUP: showeverything
926 By default, this option is ignored when Org opens agenda files
927 for the first time. If you want the agenda to honor the startup
928 option, set `org-agenda-inhibit-startup' to nil."
929 :group 'org-startup
930 :type '(choice
931 (const :tag "nofold: show all" nil)
932 (const :tag "fold: overview" t)
933 (const :tag "content: all headlines" content)
934 (const :tag "show everything, even drawers" showeverything)))
936 (defcustom org-startup-truncated t
937 "Non-nil means entering Org-mode will set `truncate-lines'.
938 This is useful since some lines containing links can be very long and
939 uninteresting. Also tables look terrible when wrapped."
940 :group 'org-startup
941 :type 'boolean)
943 (defcustom org-startup-indented nil
944 "Non-nil means turn on `org-indent-mode' on startup.
945 This can also be configured on a per-file basis by adding one of
946 the following lines anywhere in the buffer:
948 #+STARTUP: indent
949 #+STARTUP: noindent"
950 :group 'org-structure
951 :type '(choice
952 (const :tag "Not" nil)
953 (const :tag "Globally (slow on startup in large files)" t)))
955 (defcustom org-use-sub-superscripts t
956 "Non-nil means interpret \"_\" and \"^\" for display.
958 If you want to control how Org exports those characters, see
959 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
960 used to be an alias for `org-export-with-sub-superscripts' in
961 Org <8.0, it is not anymore.
963 When this option is turned on, you can use TeX-like syntax for
964 sub- and superscripts within the buffer. Several characters after
965 \"_\" or \"^\" will be considered as a single item - so grouping
966 with {} is normally not needed. For example, the following things
967 will be parsed as single sub- or superscripts:
969 10^24 or 10^tau several digits will be considered 1 item.
970 10^-12 or 10^-tau a leading sign with digits or a word
971 x^2-y^3 will be read as x^2 - y^3, because items are
972 terminated by almost any nonword/nondigit char.
973 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
975 Still, ambiguity is possible. So when in doubt, use {} to enclose
976 the sub/superscript. If you set this variable to the symbol `{}',
977 the braces are *required* in order to trigger interpretations as
978 sub/superscript. This can be helpful in documents that need \"_\"
979 frequently in plain text."
980 :group 'org-startup
981 :version "24.4"
982 :package-version '(Org . "8.0")
983 :type '(choice
984 (const :tag "Always interpret" t)
985 (const :tag "Only with braces" {})
986 (const :tag "Never interpret" nil)))
988 (defcustom org-startup-with-beamer-mode nil
989 "Non-nil means turn on `org-beamer-mode' on startup.
990 This can also be configured on a per-file basis by adding one of
991 the following lines anywhere in the buffer:
993 #+STARTUP: beamer"
994 :group 'org-startup
995 :version "24.1"
996 :type 'boolean)
998 (defcustom org-startup-align-all-tables nil
999 "Non-nil means align all tables when visiting a file.
1000 This is useful when the column width in tables is forced with <N> cookies
1001 in table fields. Such tables will look correct only after the first re-align.
1002 This can also be configured on a per-file basis by adding one of
1003 the following lines anywhere in the buffer:
1004 #+STARTUP: align
1005 #+STARTUP: noalign"
1006 :group 'org-startup
1007 :type 'boolean)
1009 (defcustom org-startup-with-inline-images nil
1010 "Non-nil means show inline images when loading a new Org file.
1011 This can also be configured on a per-file basis by adding one of
1012 the following lines anywhere in the buffer:
1013 #+STARTUP: inlineimages
1014 #+STARTUP: noinlineimages"
1015 :group 'org-startup
1016 :version "24.1"
1017 :type 'boolean)
1019 (defcustom org-startup-with-latex-preview nil
1020 "Non-nil means preview LaTeX fragments when loading a new Org file.
1022 This can also be configured on a per-file basis by adding one of
1023 the following lines anywhere in the buffer:
1024 #+STARTUP: latexpreview
1025 #+STARTUP: nolatexpreview"
1026 :group 'org-startup
1027 :version "24.4"
1028 :package-version '(Org . "8.0")
1029 :type 'boolean)
1031 (defcustom org-insert-mode-line-in-empty-file nil
1032 "Non-nil means insert the first line setting Org-mode in empty files.
1033 When the function `org-mode' is called interactively in an empty file, this
1034 normally means that the file name does not automatically trigger Org-mode.
1035 To ensure that the file will always be in Org-mode in the future, a
1036 line enforcing Org-mode will be inserted into the buffer, if this option
1037 has been set."
1038 :group 'org-startup
1039 :type 'boolean)
1041 (defcustom org-replace-disputed-keys nil
1042 "Non-nil means use alternative key bindings for some keys.
1043 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1044 These keys are also used by other packages like shift-selection-mode'
1045 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1046 If you want to use Org-mode together with one of these other modes,
1047 or more generally if you would like to move some Org-mode commands to
1048 other keys, set this variable and configure the keys with the variable
1049 `org-disputed-keys'.
1051 This option is only relevant at load-time of Org-mode, and must be set
1052 *before* org.el is loaded. Changing it requires a restart of Emacs to
1053 become effective."
1054 :group 'org-startup
1055 :type 'boolean)
1057 (defcustom org-use-extra-keys nil
1058 "Non-nil means use extra key sequence definitions for certain commands.
1059 This happens automatically if `window-system' is nil. This
1060 variable lets you do the same manually. You must set it before
1061 loading org.
1063 Example: on Carbon Emacs 22 running graphically, with an external
1064 keyboard on a Powerbook, the default way of setting M-left might
1065 not work for either Alt or ESC. Setting this variable will make
1066 it work for ESC."
1067 :group 'org-startup
1068 :type 'boolean)
1070 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1072 (defcustom org-disputed-keys
1073 '(([(shift up)] . [(meta p)])
1074 ([(shift down)] . [(meta n)])
1075 ([(shift left)] . [(meta -)])
1076 ([(shift right)] . [(meta +)])
1077 ([(control shift right)] . [(meta shift +)])
1078 ([(control shift left)] . [(meta shift -)]))
1079 "Keys for which Org-mode and other modes compete.
1080 This is an alist, cars are the default keys, second element specifies
1081 the alternative to use when `org-replace-disputed-keys' is t.
1083 Keys can be specified in any syntax supported by `define-key'.
1084 The value of this option takes effect only at Org-mode's startup,
1085 therefore you'll have to restart Emacs to apply it after changing."
1086 :group 'org-startup
1087 :type 'alist)
1089 (defun org-key (key)
1090 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1091 Or return the original if not disputed."
1092 (when org-replace-disputed-keys
1093 (let* ((nkey (key-description key))
1094 (x (org-find-if (lambda (x)
1095 (equal (key-description (car x)) nkey))
1096 org-disputed-keys)))
1097 (setq key (if x (cdr x) key))))
1098 key)
1100 (defun org-find-if (predicate seq)
1101 (catch 'exit
1102 (while seq
1103 (if (funcall predicate (car seq))
1104 (throw 'exit (car seq))
1105 (pop seq)))))
1107 (defun org-defkey (keymap key def)
1108 "Define a key, possibly translated, as returned by `org-key'."
1109 (define-key keymap (org-key key) def))
1111 (defcustom org-ellipsis nil
1112 "The ellipsis to use in the Org-mode outline.
1113 When nil, just use the standard three dots.
1114 When a string, use that string instead.
1115 When a face, use the standard 3 dots, but with the specified face.
1116 The change affects only Org-mode (which will then use its own display table).
1117 Changing this requires executing \\[org-mode] in a buffer to become
1118 effective."
1119 :group 'org-startup
1120 :type '(choice (const :tag "Default" nil)
1121 (face :tag "Face" :value org-warning)
1122 (string :tag "String" :value "...#")))
1124 (defvar org-display-table nil
1125 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1127 (defgroup org-keywords nil
1128 "Keywords in Org-mode."
1129 :tag "Org Keywords"
1130 :group 'org)
1132 (defcustom org-closed-keep-when-no-todo nil
1133 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1134 :group 'org-todo
1135 :group 'org-keywords
1136 :version "24.4"
1137 :package-version '(Org . "8.0")
1138 :type 'boolean)
1140 (defgroup org-structure nil
1141 "Options concerning the general structure of Org-mode files."
1142 :tag "Org Structure"
1143 :group 'org)
1145 (defgroup org-reveal-location nil
1146 "Options about how to make context of a location visible."
1147 :tag "Org Reveal Location"
1148 :group 'org-structure)
1150 (defcustom org-show-context-detail '((agenda . local)
1151 (bookmark-jump . lineage)
1152 (isearch . lineage)
1153 (default . ancestors))
1154 "Alist between context and visibility span when revealing a location.
1156 \\<org-mode-map>Some actions may move point into invisible
1157 locations. As a consequence, Org always expose a neighborhood
1158 around point. How much is shown depends on the initial action,
1159 or context. Valid contexts are
1161 agenda when exposing an entry from the agenda
1162 org-goto when using the command `org-goto' (\\[org-goto])
1163 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1164 tags-tree when constructing a sparse tree based on tags matches
1165 link-search when exposing search matches associated with a link
1166 mark-goto when exposing the jump goal of a mark
1167 bookmark-jump when exposing a bookmark location
1168 isearch when exiting from an incremental search
1169 default default for all contexts not set explicitly
1171 Allowed visibility spans are
1173 minimal show current headline; if point is not on headline,
1174 also show entry
1176 local show current headline, entry and next headline
1178 ancestors show current headline and its direct ancestors; if
1179 point is not on headline, also show entry
1181 lineage show current headline, its direct ancestors and all
1182 their children; if point is not on headline, also show
1183 entry and first child
1185 tree show current headline, its direct ancestors and all
1186 their children; if point is not on headline, also show
1187 entry and all children
1189 canonical show current headline, its direct ancestors along with
1190 their entries and children; if point is not located on
1191 the headline, also show current entry and all children
1193 As special cases, a nil or t value means show all contexts in
1194 `minimal' or `canonical' view, respectively.
1196 Some views can make displayed information very compact, but also
1197 make it harder to edit the location of the match. In such
1198 a case, use the command `org-reveal' (\\[org-reveal]) to show
1199 more context."
1200 :group 'org-reveal-location
1201 :version "25.2"
1202 :package-version '(Org . "9.0")
1203 :type '(choice
1204 (const :tag "Canonical" t)
1205 (const :tag "Minimal" nil)
1206 (repeat :greedy t :tag "Individual contexts"
1207 (cons
1208 (choice :tag "Context"
1209 (const agenda)
1210 (const org-goto)
1211 (const occur-tree)
1212 (const tags-tree)
1213 (const link-search)
1214 (const mark-goto)
1215 (const bookmark-jump)
1216 (const isearch)
1217 (const default))
1218 (choice :tag "Detail level"
1219 (const minimal)
1220 (const local)
1221 (const ancestors)
1222 (const lineage)
1223 (const tree)
1224 (const canonical))))))
1226 (defcustom org-indirect-buffer-display 'other-window
1227 "How should indirect tree buffers be displayed?
1228 This applies to indirect buffers created with the commands
1229 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1230 Valid values are:
1231 current-window Display in the current window
1232 other-window Just display in another window.
1233 dedicated-frame Create one new frame, and re-use it each time.
1234 new-frame Make a new frame each time. Note that in this case
1235 previously-made indirect buffers are kept, and you need to
1236 kill these buffers yourself."
1237 :group 'org-structure
1238 :group 'org-agenda-windows
1239 :type '(choice
1240 (const :tag "In current window" current-window)
1241 (const :tag "In current frame, other window" other-window)
1242 (const :tag "Each time a new frame" new-frame)
1243 (const :tag "One dedicated frame" dedicated-frame)))
1245 (defcustom org-use-speed-commands nil
1246 "Non-nil means activate single letter commands at beginning of a headline.
1247 This may also be a function to test for appropriate locations where speed
1248 commands should be active.
1250 For example, to activate speed commands when the point is on any
1251 star at the beginning of the headline, you can do this:
1253 (setq org-use-speed-commands
1254 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1255 :group 'org-structure
1256 :type '(choice
1257 (const :tag "Never" nil)
1258 (const :tag "At beginning of headline stars" t)
1259 (function)))
1261 (defcustom org-speed-commands-user nil
1262 "Alist of additional speed commands.
1263 This list will be checked before `org-speed-commands-default'
1264 when the variable `org-use-speed-commands' is non-nil
1265 and when the cursor is at the beginning of a headline.
1266 The car if each entry is a string with a single letter, which must
1267 be assigned to `self-insert-command' in the global map.
1268 The cdr is either a command to be called interactively, a function
1269 to be called, or a form to be evaluated.
1270 An entry that is just a list with a single string will be interpreted
1271 as a descriptive headline that will be added when listing the speed
1272 commands in the Help buffer using the `?' speed command."
1273 :group 'org-structure
1274 :type '(repeat :value ("k" . ignore)
1275 (choice :value ("k" . ignore)
1276 (list :tag "Descriptive Headline" (string :tag "Headline"))
1277 (cons :tag "Letter and Command"
1278 (string :tag "Command letter")
1279 (choice
1280 (function)
1281 (sexp))))))
1283 (defcustom org-bookmark-names-plist
1284 '(:last-capture "org-capture-last-stored"
1285 :last-refile "org-refile-last-stored"
1286 :last-capture-marker "org-capture-last-stored-marker")
1287 "Names for bookmarks automatically set by some Org commands.
1288 This can provide strings as names for a number of bookmarks Org sets
1289 automatically. The following keys are currently implemented:
1290 :last-capture
1291 :last-capture-marker
1292 :last-refile
1293 When a key does not show up in the property list, the corresponding bookmark
1294 is not set."
1295 :group 'org-structure
1296 :type 'plist)
1298 (defgroup org-cycle nil
1299 "Options concerning visibility cycling in Org-mode."
1300 :tag "Org Cycle"
1301 :group 'org-structure)
1303 (defcustom org-cycle-skip-children-state-if-no-children t
1304 "Non-nil means skip CHILDREN state in entries that don't have any."
1305 :group 'org-cycle
1306 :type 'boolean)
1308 (defcustom org-cycle-max-level nil
1309 "Maximum level which should still be subject to visibility cycling.
1310 Levels higher than this will, for cycling, be treated as text, not a headline.
1311 When `org-odd-levels-only' is set, a value of N in this variable actually
1312 means 2N-1 stars as the limiting headline.
1313 When nil, cycle all levels.
1314 Note that the limiting level of cycling is also influenced by
1315 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1316 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1317 than its value."
1318 :group 'org-cycle
1319 :type '(choice
1320 (const :tag "No limit" nil)
1321 (integer :tag "Maximum level")))
1323 (defcustom org-hide-block-startup nil
1324 "Non-nil means entering Org-mode will fold all blocks.
1325 This can also be set in on a per-file basis with
1327 #+STARTUP: hideblocks
1328 #+STARTUP: showblocks"
1329 :group 'org-startup
1330 :group 'org-cycle
1331 :type 'boolean)
1333 (defcustom org-cycle-global-at-bob nil
1334 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1335 This makes it possible to do global cycling without having to use S-TAB or
1336 \\[universal-argument] TAB. For this special case to work, the first line
1337 of the buffer must not be a headline -- it may be empty or some other text.
1338 When used in this way, `org-cycle-hook' is disabled temporarily to make
1339 sure the cursor stays at the beginning of the buffer. When this option is
1340 nil, don't do anything special at the beginning of the buffer."
1341 :group 'org-cycle
1342 :type 'boolean)
1344 (defcustom org-cycle-level-after-item/entry-creation t
1345 "Non-nil means cycle entry level or item indentation in new empty entries.
1347 When the cursor is at the end of an empty headline, i.e., with only stars
1348 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1349 and then all possible ancestor states, before returning to the original state.
1350 This makes data entry extremely fast: M-RET to create a new headline,
1351 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1353 When the cursor is at the end of an empty plain list item, one TAB will
1354 make it a subitem, two or more tabs will back up to make this an item
1355 higher up in the item hierarchy."
1356 :group 'org-cycle
1357 :type 'boolean)
1359 (defcustom org-cycle-emulate-tab t
1360 "Where should `org-cycle' emulate TAB.
1361 nil Never
1362 white Only in completely white lines
1363 whitestart Only at the beginning of lines, before the first non-white char
1364 t Everywhere except in headlines
1365 exc-hl-bol Everywhere except at the start of a headline
1366 If TAB is used in a place where it does not emulate TAB, the current subtree
1367 visibility is cycled."
1368 :group 'org-cycle
1369 :type '(choice (const :tag "Never" nil)
1370 (const :tag "Only in completely white lines" white)
1371 (const :tag "Before first char in a line" whitestart)
1372 (const :tag "Everywhere except in headlines" t)
1373 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1375 (defcustom org-cycle-separator-lines 2
1376 "Number of empty lines needed to keep an empty line between collapsed trees.
1377 If you leave an empty line between the end of a subtree and the following
1378 headline, this empty line is hidden when the subtree is folded.
1379 Org-mode will leave (exactly) one empty line visible if the number of
1380 empty lines is equal or larger to the number given in this variable.
1381 So the default 2 means at least 2 empty lines after the end of a subtree
1382 are needed to produce free space between a collapsed subtree and the
1383 following headline.
1385 If the number is negative, and the number of empty lines is at least -N,
1386 all empty lines are shown.
1388 Special case: when 0, never leave empty lines in collapsed view."
1389 :group 'org-cycle
1390 :type 'integer)
1391 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1393 (defcustom org-pre-cycle-hook nil
1394 "Hook that is run before visibility cycling is happening.
1395 The function(s) in this hook must accept a single argument which indicates
1396 the new state that will be set right after running this hook. The
1397 argument is a symbol. Before a global state change, it can have the values
1398 `overview', `content', or `all'. Before a local state change, it can have
1399 the values `folded', `children', or `subtree'."
1400 :group 'org-cycle
1401 :type 'hook)
1403 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1404 org-cycle-hide-drawers
1405 org-cycle-show-empty-lines
1406 org-optimize-window-after-visibility-change)
1407 "Hook that is run after `org-cycle' has changed the buffer visibility.
1408 The function(s) in this hook must accept a single argument which indicates
1409 the new state that was set by the most recent `org-cycle' command. The
1410 argument is a symbol. After a global state change, it can have the values
1411 `overview', `contents', or `all'. After a local state change, it can have
1412 the values `folded', `children', or `subtree'."
1413 :group 'org-cycle
1414 :type 'hook
1415 :version "25.1"
1416 :package-version '(Org . "8.3"))
1418 (defgroup org-edit-structure nil
1419 "Options concerning structure editing in Org-mode."
1420 :tag "Org Edit Structure"
1421 :group 'org-structure)
1423 (defcustom org-odd-levels-only nil
1424 "Non-nil means skip even levels and only use odd levels for the outline.
1425 This has the effect that two stars are being added/taken away in
1426 promotion/demotion commands. It also influences how levels are
1427 handled by the exporters.
1428 Changing it requires restart of `font-lock-mode' to become effective
1429 for fontification also in regions already fontified.
1430 You may also set this on a per-file basis by adding one of the following
1431 lines to the buffer:
1433 #+STARTUP: odd
1434 #+STARTUP: oddeven"
1435 :group 'org-edit-structure
1436 :group 'org-appearance
1437 :type 'boolean)
1439 (defcustom org-adapt-indentation t
1440 "Non-nil means adapt indentation to outline node level.
1442 When this variable is set, Org assumes that you write outlines by
1443 indenting text in each node to align with the headline (after the
1444 stars). The following issues are influenced by this variable:
1446 - The indentation is increased by one space in a demotion
1447 command, and decreased by one in a promotion command. However,
1448 in the latter case, if shifting some line in the entry body
1449 would alter document structure (e.g., insert a new headline),
1450 indentation is not changed at all.
1452 - Property drawers and planning information is inserted indented
1453 when this variable is set. When nil, they will not be indented.
1455 - TAB indents a line relative to current level. The lines below
1456 a headline will be indented when this variable is set.
1458 Note that this is all about true indentation, by adding and
1459 removing space characters. See also `org-indent.el' which does
1460 level-dependent indentation in a virtual way, i.e. at display
1461 time in Emacs."
1462 :group 'org-edit-structure
1463 :type 'boolean)
1465 (defcustom org-special-ctrl-a/e nil
1466 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1468 When t, `C-a' will bring back the cursor to the beginning of the
1469 headline text, i.e. after the stars and after a possible TODO
1470 keyword. In an item, this will be the position after bullet and
1471 check-box, if any. When the cursor is already at that position,
1472 another `C-a' will bring it to the beginning of the line.
1474 `C-e' will jump to the end of the headline, ignoring the presence
1475 of tags in the headline. A second `C-e' will then jump to the
1476 true end of the line, after any tags. This also means that, when
1477 this variable is non-nil, `C-e' also will never jump beyond the
1478 end of the heading of a folded section, i.e. not after the
1479 ellipses.
1481 When set to the symbol `reversed', the first `C-a' or `C-e' works
1482 normally, going to the true line boundary first. Only a directly
1483 following, identical keypress will bring the cursor to the
1484 special positions.
1486 This may also be a cons cell where the behavior for `C-a' and
1487 `C-e' is set separately."
1488 :group 'org-edit-structure
1489 :type '(choice
1490 (const :tag "off" nil)
1491 (const :tag "on: after stars/bullet and before tags first" t)
1492 (const :tag "reversed: true line boundary first" reversed)
1493 (cons :tag "Set C-a and C-e separately"
1494 (choice :tag "Special C-a"
1495 (const :tag "off" nil)
1496 (const :tag "on: after stars/bullet first" t)
1497 (const :tag "reversed: before stars/bullet first" reversed))
1498 (choice :tag "Special C-e"
1499 (const :tag "off" nil)
1500 (const :tag "on: before tags first" t)
1501 (const :tag "reversed: after tags first" reversed)))))
1502 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1504 (defcustom org-special-ctrl-k nil
1505 "Non-nil means `C-k' will behave specially in headlines.
1506 When nil, `C-k' will call the default `kill-line' command.
1507 When t, the following will happen while the cursor is in the headline:
1509 - When the cursor is at the beginning of a headline, kill the entire
1510 line and possible the folded subtree below the line.
1511 - When in the middle of the headline text, kill the headline up to the tags.
1512 - When after the headline text, kill the tags."
1513 :group 'org-edit-structure
1514 :type 'boolean)
1516 (defcustom org-ctrl-k-protect-subtree nil
1517 "Non-nil means, do not delete a hidden subtree with C-k.
1518 When set to the symbol `error', simply throw an error when C-k is
1519 used to kill (part-of) a headline that has hidden text behind it.
1520 Any other non-nil value will result in a query to the user, if it is
1521 OK to kill that hidden subtree. When nil, kill without remorse."
1522 :group 'org-edit-structure
1523 :version "24.1"
1524 :type '(choice
1525 (const :tag "Do not protect hidden subtrees" nil)
1526 (const :tag "Protect hidden subtrees with a security query" t)
1527 (const :tag "Never kill a hidden subtree with C-k" error)))
1529 (defcustom org-special-ctrl-o t
1530 "Non-nil means, make `C-o' insert a row in tables."
1531 :group 'org-edit-structure
1532 :type 'boolean)
1534 (defcustom org-catch-invisible-edits nil
1535 "Check if in invisible region before inserting or deleting a character.
1536 Valid values are:
1538 nil Do not check, so just do invisible edits.
1539 error Throw an error and do nothing.
1540 show Make point visible, and do the requested edit.
1541 show-and-error Make point visible, then throw an error and abort the edit.
1542 smart Make point visible, and do insertion/deletion if it is
1543 adjacent to visible text and the change feels predictable.
1544 Never delete a previously invisible character or add in the
1545 middle or right after an invisible region. Basically, this
1546 allows insertion and backward-delete right before ellipses.
1547 FIXME: maybe in this case we should not even show?"
1548 :group 'org-edit-structure
1549 :version "24.1"
1550 :type '(choice
1551 (const :tag "Do not check" nil)
1552 (const :tag "Throw error when trying to edit" error)
1553 (const :tag "Unhide, but do not do the edit" show-and-error)
1554 (const :tag "Show invisible part and do the edit" show)
1555 (const :tag "Be smart and do the right thing" smart)))
1557 (defcustom org-yank-folded-subtrees t
1558 "Non-nil means when yanking subtrees, fold them.
1559 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1560 it starts with a heading and all other headings in it are either children
1561 or siblings, then fold all the subtrees. However, do this only if no
1562 text after the yank would be swallowed into a folded tree by this action."
1563 :group 'org-edit-structure
1564 :type 'boolean)
1566 (defcustom org-yank-adjusted-subtrees nil
1567 "Non-nil means when yanking subtrees, adjust the level.
1568 With this setting, `org-paste-subtree' is used to insert the subtree, see
1569 this function for details."
1570 :group 'org-edit-structure
1571 :type 'boolean)
1573 (defcustom org-M-RET-may-split-line '((default . t))
1574 "Non-nil means M-RET will split the line at the cursor position.
1575 When nil, it will go to the end of the line before making a
1576 new line.
1577 You may also set this option in a different way for different
1578 contexts. Valid contexts are:
1580 headline when creating a new headline
1581 item when creating a new item
1582 table in a table field
1583 default the value to be used for all contexts not explicitly
1584 customized"
1585 :group 'org-structure
1586 :group 'org-table
1587 :type '(choice
1588 (const :tag "Always" t)
1589 (const :tag "Never" nil)
1590 (repeat :greedy t :tag "Individual contexts"
1591 (cons
1592 (choice :tag "Context"
1593 (const headline)
1594 (const item)
1595 (const table)
1596 (const default))
1597 (boolean)))))
1600 (defcustom org-insert-heading-respect-content nil
1601 "Non-nil means insert new headings after the current subtree.
1602 When nil, the new heading is created directly after the current line.
1603 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1604 this variable on for the duration of the command."
1605 :group 'org-structure
1606 :type 'boolean)
1608 (defcustom org-blank-before-new-entry '((heading . auto)
1609 (plain-list-item . auto))
1610 "Should `org-insert-heading' leave a blank line before new heading/item?
1611 The value is an alist, with `heading' and `plain-list-item' as CAR,
1612 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1613 which case Org will look at the surrounding headings/items and try to
1614 make an intelligent decision whether to insert a blank line or not."
1615 :group 'org-edit-structure
1616 :type '(list
1617 (cons (const heading)
1618 (choice (const :tag "Never" nil)
1619 (const :tag "Always" t)
1620 (const :tag "Auto" auto)))
1621 (cons (const plain-list-item)
1622 (choice (const :tag "Never" nil)
1623 (const :tag "Always" t)
1624 (const :tag "Auto" auto)))))
1626 (defcustom org-insert-heading-hook nil
1627 "Hook being run after inserting a new heading."
1628 :group 'org-edit-structure
1629 :type 'hook)
1631 (defcustom org-enable-fixed-width-editor t
1632 "Non-nil means lines starting with \":\" are treated as fixed-width.
1633 This currently only means they are never auto-wrapped.
1634 When nil, such lines will be treated like ordinary lines."
1635 :group 'org-edit-structure
1636 :type 'boolean)
1638 (defcustom org-goto-auto-isearch t
1639 "Non-nil means typing characters in `org-goto' starts incremental search.
1640 When nil, you can use these keybindings to navigate the buffer:
1642 q Quit the org-goto interface
1643 n Go to the next visible heading
1644 p Go to the previous visible heading
1645 f Go one heading forward on same level
1646 b Go one heading backward on same level
1647 u Go one heading up"
1648 :group 'org-edit-structure
1649 :type 'boolean)
1651 (defgroup org-sparse-trees nil
1652 "Options concerning sparse trees in Org-mode."
1653 :tag "Org Sparse Trees"
1654 :group 'org-structure)
1656 (defcustom org-highlight-sparse-tree-matches t
1657 "Non-nil means highlight all matches that define a sparse tree.
1658 The highlights will automatically disappear the next time the buffer is
1659 changed by an edit command."
1660 :group 'org-sparse-trees
1661 :type 'boolean)
1663 (defcustom org-remove-highlights-with-change t
1664 "Non-nil means any change to the buffer will remove temporary highlights.
1665 \\<org-mode-map>\
1666 Such highlights are created by `org-occur' and `org-clock-display'.
1667 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1668 to get rid of the highlights.
1669 The highlights created by `org-toggle-latex-fragment' always need
1670 `\\[org-toggle-latex-fragment]' to be removed."
1671 :group 'org-sparse-trees
1672 :group 'org-time
1673 :type 'boolean)
1675 (defcustom org-occur-case-fold-search t
1676 "Non-nil means `org-occur' should be case-insensitive.
1677 If set to `smart' the search will be case-insensitive only if it
1678 doesn't specify any upper case character."
1679 :group 'org-sparse-trees
1680 :version "25.1"
1681 :type '(choice
1682 (const :tag "Case-sensitive" nil)
1683 (const :tag "Case-insensitive" t)
1684 (const :tag "Case-insensitive for lower case searches only" 'smart)))
1686 (defcustom org-occur-hook '(org-first-headline-recenter)
1687 "Hook that is run after `org-occur' has constructed a sparse tree.
1688 This can be used to recenter the window to show as much of the structure
1689 as possible."
1690 :group 'org-sparse-trees
1691 :type 'hook)
1693 (defgroup org-imenu-and-speedbar nil
1694 "Options concerning imenu and speedbar in Org-mode."
1695 :tag "Org Imenu and Speedbar"
1696 :group 'org-structure)
1698 (defcustom org-imenu-depth 2
1699 "The maximum level for Imenu access to Org-mode headlines.
1700 This also applied for speedbar access."
1701 :group 'org-imenu-and-speedbar
1702 :type 'integer)
1704 (defgroup org-table nil
1705 "Options concerning tables in Org-mode."
1706 :tag "Org Table"
1707 :group 'org)
1709 (defcustom org-enable-table-editor 'optimized
1710 "Non-nil means lines starting with \"|\" are handled by the table editor.
1711 When nil, such lines will be treated like ordinary lines.
1713 When equal to the symbol `optimized', the table editor will be optimized to
1714 do the following:
1715 - Automatic overwrite mode in front of whitespace in table fields.
1716 This makes the structure of the table stay in tact as long as the edited
1717 field does not exceed the column width.
1718 - Minimize the number of realigns. Normally, the table is aligned each time
1719 TAB or RET are pressed to move to another field. With optimization this
1720 happens only if changes to a field might have changed the column width.
1721 Optimization requires replacing the functions `self-insert-command',
1722 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1723 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1724 very good at guessing when a re-align will be necessary, but you can always
1725 force one with \\[org-ctrl-c-ctrl-c].
1727 If you would like to use the optimized version in Org-mode, but the
1728 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1730 This variable can be used to turn on and off the table editor during a session,
1731 but in order to toggle optimization, a restart is required.
1733 See also the variable `org-table-auto-blank-field'."
1734 :group 'org-table
1735 :type '(choice
1736 (const :tag "off" nil)
1737 (const :tag "on" t)
1738 (const :tag "on, optimized" optimized)))
1740 (defcustom org-self-insert-cluster-for-undo nil
1741 "Non-nil means cluster self-insert commands for undo when possible.
1742 If this is set, then, like in the Emacs command loop, 20 consecutive
1743 characters will be undone together.
1744 This is configurable, because there is some impact on typing performance."
1745 :group 'org-table
1746 :type 'boolean)
1748 (defcustom org-table-tab-recognizes-table.el t
1749 "Non-nil means TAB will automatically notice a table.el table.
1750 When it sees such a table, it moves point into it and - if necessary -
1751 calls `table-recognize-table'."
1752 :group 'org-table-editing
1753 :type 'boolean)
1755 (defgroup org-link nil
1756 "Options concerning links in Org-mode."
1757 :tag "Org Link"
1758 :group 'org)
1760 (defvar-local org-link-abbrev-alist-local nil
1761 "Buffer-local version of `org-link-abbrev-alist', which see.
1762 The value of this is taken from the #+LINK lines.")
1764 (defcustom org-link-abbrev-alist nil
1765 "Alist of link abbreviations.
1766 The car of each element is a string, to be replaced at the start of a link.
1767 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1768 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1770 [[linkkey:tag][description]]
1772 The `linkkey' must be a word word, starting with a letter, followed
1773 by letters, numbers, `-' or `_'.
1775 If REPLACE is a string, the tag will simply be appended to create the link.
1776 If the string contains \"%s\", the tag will be inserted there. If the string
1777 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1778 at that point (see the function `url-hexify-string'). If the string contains
1779 the specifier \"%(my-function)\", then the custom function `my-function' will
1780 be invoked: this function takes the tag as its only argument and must return
1781 a string.
1783 REPLACE may also be a function that will be called with the tag as the
1784 only argument to create the link, which should be returned as a string.
1786 See the manual for examples."
1787 :group 'org-link
1788 :type '(repeat
1789 (cons
1790 (string :tag "Protocol")
1791 (choice
1792 (string :tag "Format")
1793 (function)))))
1795 (defcustom org-descriptive-links t
1796 "Non-nil means Org will display descriptive links.
1797 E.g. [[http://orgmode.org][Org website]] will be displayed as
1798 \"Org Website\", hiding the link itself and just displaying its
1799 description. When set to nil, Org will display the full links
1800 literally.
1802 You can interactively set the value of this variable by calling
1803 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1804 :group 'org-link
1805 :type 'boolean)
1807 (defcustom org-link-file-path-type 'adaptive
1808 "How the path name in file links should be stored.
1809 Valid values are:
1811 relative Relative to the current directory, i.e. the directory of the file
1812 into which the link is being inserted.
1813 absolute Absolute path, if possible with ~ for home directory.
1814 noabbrev Absolute path, no abbreviation of home directory.
1815 adaptive Use relative path for files in the current directory and sub-
1816 directories of it. For other files, use an absolute path."
1817 :group 'org-link
1818 :type '(choice
1819 (const relative)
1820 (const absolute)
1821 (const noabbrev)
1822 (const adaptive)))
1824 (defvaralias 'org-activate-links 'org-highlight-links)
1825 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1826 "Types of links that should be highlighted in Org-mode files.
1828 This is a list of symbols, each one of them leading to the
1829 highlighting of a certain link type.
1831 You can still open links that are not highlighted.
1833 In principle, it does not hurt to turn on highlighting for all
1834 link types. There may be a small gain when turning off unused
1835 link types. The types are:
1837 bracket The recommended [[link][description]] or [[link]] links with hiding.
1838 angle Links in angular brackets that may contain whitespace like
1839 <bbdb:Carsten Dominik>.
1840 plain Plain links in normal text, no whitespace, like http://google.com.
1841 radio Text that is matched by a radio target, see manual for details.
1842 tag Tag settings in a headline (link to tag search).
1843 date Time stamps (link to calendar).
1844 footnote Footnote labels.
1846 If you set this variable during an Emacs session, use `org-mode-restart'
1847 in the Org buffer so that the change takes effect."
1848 :group 'org-link
1849 :group 'org-appearance
1850 :type '(set :greedy t
1851 (const :tag "Double bracket links" bracket)
1852 (const :tag "Angular bracket links" angle)
1853 (const :tag "Plain text links" plain)
1854 (const :tag "Radio target matches" radio)
1855 (const :tag "Tags" tag)
1856 (const :tag "Timestamps" date)
1857 (const :tag "Footnotes" footnote)))
1859 (defcustom org-make-link-description-function nil
1860 "Function to use for generating link descriptions from links.
1861 When nil, the link location will be used. This function must take
1862 two parameters: the first one is the link, the second one is the
1863 description generated by `org-insert-link'. The function should
1864 return the description to use."
1865 :group 'org-link
1866 :type '(choice (const nil) (function)))
1868 (defgroup org-link-store nil
1869 "Options concerning storing links in Org-mode."
1870 :tag "Org Store Link"
1871 :group 'org-link)
1873 (defcustom org-url-hexify-p t
1874 "When non-nil, hexify URL when creating a link."
1875 :type 'boolean
1876 :version "24.3"
1877 :group 'org-link-store)
1879 (defcustom org-email-link-description-format "Email %c: %.30s"
1880 "Format of the description part of a link to an email or usenet message.
1881 The following %-escapes will be replaced by corresponding information:
1883 %F full \"From\" field
1884 %f name, taken from \"From\" field, address if no name
1885 %T full \"To\" field
1886 %t first name in \"To\" field, address if no name
1887 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1888 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1889 %s subject
1890 %d date
1891 %m message-id.
1893 You may use normal field width specification between the % and the letter.
1894 This is for example useful to limit the length of the subject.
1896 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1897 :group 'org-link-store
1898 :type 'string)
1900 (defcustom org-from-is-user-regexp
1901 (let (r1 r2)
1902 (when (and user-mail-address (not (string= user-mail-address "")))
1903 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1904 (when (and user-full-name (not (string= user-full-name "")))
1905 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1906 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1907 "Regexp matched against the \"From:\" header of an email or usenet message.
1908 It should match if the message is from the user him/herself."
1909 :group 'org-link-store
1910 :type 'regexp)
1912 (defcustom org-context-in-file-links t
1913 "Non-nil means file links from `org-store-link' contain context.
1914 A search string will be added to the file name with :: as separator and
1915 used to find the context when the link is activated by the command
1916 `org-open-at-point'. When this option is t, the entire active region
1917 will be placed in the search string of the file link. If set to a
1918 positive integer, only the first n lines of context will be stored.
1920 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1921 negates this setting for the duration of the command."
1922 :group 'org-link-store
1923 :type '(choice boolean integer))
1925 (defcustom org-keep-stored-link-after-insertion nil
1926 "Non-nil means keep link in list for entire session.
1928 The command `org-store-link' adds a link pointing to the current
1929 location to an internal list. These links accumulate during a session.
1930 The command `org-insert-link' can be used to insert links into any
1931 Org-mode file (offering completion for all stored links). When this
1932 option is nil, every link which has been inserted once using \\[org-insert-link]
1933 will be removed from the list, to make completing the unused links
1934 more efficient."
1935 :group 'org-link-store
1936 :type 'boolean)
1938 (defgroup org-link-follow nil
1939 "Options concerning following links in Org-mode."
1940 :tag "Org Follow Link"
1941 :group 'org-link)
1943 (defcustom org-link-translation-function nil
1944 "Function to translate links with different syntax to Org syntax.
1945 This can be used to translate links created for example by the Planner
1946 or emacs-wiki packages to Org syntax.
1947 The function must accept two parameters, a TYPE containing the link
1948 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1949 which is everything after the link protocol. It should return a cons
1950 with possibly modified values of type and path.
1951 Org contains a function for this, so if you set this variable to
1952 `org-translate-link-from-planner', you should be able follow many
1953 links created by planner."
1954 :group 'org-link-follow
1955 :type '(choice (const nil) (function)))
1957 (defcustom org-follow-link-hook nil
1958 "Hook that is run after a link has been followed."
1959 :group 'org-link-follow
1960 :type 'hook)
1962 (defcustom org-tab-follows-link nil
1963 "Non-nil means on links TAB will follow the link.
1964 Needs to be set before org.el is loaded.
1965 This really should not be used, it does not make sense, and the
1966 implementation is bad."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-return-follows-link nil
1971 "Non-nil means on links RET will follow the link.
1972 In tables, the special behavior of RET has precedence."
1973 :group 'org-link-follow
1974 :type 'boolean)
1976 (defcustom org-mouse-1-follows-link
1977 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1978 "Non-nil means mouse-1 on a link will follow the link.
1979 A longer mouse click will still set point. Needs to be set
1980 before org.el is loaded."
1981 :group 'org-link-follow
1982 :version "24.4"
1983 :package-version '(Org . "8.3")
1984 :type '(choice
1985 (const :tag "A double click follows the link" double)
1986 (const :tag "Unconditionally follow the link with mouse-1" t)
1987 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1989 (defcustom org-mark-ring-length 4
1990 "Number of different positions to be recorded in the ring.
1991 Changing this requires a restart of Emacs to work correctly."
1992 :group 'org-link-follow
1993 :type 'integer)
1995 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1996 "Non-nil means internal links in Org files must exactly match a headline.
1997 When nil, the link search tries to match a phrase with all words
1998 in the search text."
1999 :group 'org-link-follow
2000 :version "24.1"
2001 :type '(choice
2002 (const :tag "Use fuzzy text search" nil)
2003 (const :tag "Match only exact headline" t)
2004 (const :tag "Match exact headline or query to create it"
2005 query-to-create)))
2007 (defcustom org-link-frame-setup
2008 '((vm . vm-visit-folder-other-frame)
2009 (vm-imap . vm-visit-imap-folder-other-frame)
2010 (gnus . org-gnus-no-new-news)
2011 (file . find-file-other-window)
2012 (wl . wl-other-frame))
2013 "Setup the frame configuration for following links.
2014 When following a link with Emacs, it may often be useful to display
2015 this link in another window or frame. This variable can be used to
2016 set this up for the different types of links.
2017 For VM, use any of
2018 `vm-visit-folder'
2019 `vm-visit-folder-other-window'
2020 `vm-visit-folder-other-frame'
2021 For Gnus, use any of
2022 `gnus'
2023 `gnus-other-frame'
2024 `org-gnus-no-new-news'
2025 For FILE, use any of
2026 `find-file'
2027 `find-file-other-window'
2028 `find-file-other-frame'
2029 For Wanderlust use any of
2030 `wl'
2031 `wl-other-frame'
2032 For the calendar, use the variable `calendar-setup'.
2033 For BBDB, it is currently only possible to display the matches in
2034 another window."
2035 :group 'org-link-follow
2036 :type '(list
2037 (cons (const vm)
2038 (choice
2039 (const vm-visit-folder)
2040 (const vm-visit-folder-other-window)
2041 (const vm-visit-folder-other-frame)))
2042 (cons (const vm-imap)
2043 (choice
2044 (const vm-visit-imap-folder)
2045 (const vm-visit-imap-folder-other-window)
2046 (const vm-visit-imap-folder-other-frame)))
2047 (cons (const gnus)
2048 (choice
2049 (const gnus)
2050 (const gnus-other-frame)
2051 (const org-gnus-no-new-news)))
2052 (cons (const file)
2053 (choice
2054 (const find-file)
2055 (const find-file-other-window)
2056 (const find-file-other-frame)))
2057 (cons (const wl)
2058 (choice
2059 (const wl)
2060 (const wl-other-frame)))))
2062 (defcustom org-display-internal-link-with-indirect-buffer nil
2063 "Non-nil means use indirect buffer to display infile links.
2064 Activating internal links (from one location in a file to another location
2065 in the same file) normally just jumps to the location. When the link is
2066 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2067 is displayed in
2068 another window. When this option is set, the other window actually displays
2069 an indirect buffer clone of the current buffer, to avoid any visibility
2070 changes to the current buffer."
2071 :group 'org-link-follow
2072 :type 'boolean)
2074 (defcustom org-open-non-existing-files nil
2075 "Non-nil means `org-open-file' will open non-existing files.
2076 When nil, an error will be generated.
2077 This variable applies only to external applications because they
2078 might choke on non-existing files. If the link is to a file that
2079 will be opened in Emacs, the variable is ignored."
2080 :group 'org-link-follow
2081 :type 'boolean)
2083 (defcustom org-open-directory-means-index-dot-org nil
2084 "Non-nil means a link to a directory really means to index.org.
2085 When nil, following a directory link will run dired or open a finder/explorer
2086 window on that directory."
2087 :group 'org-link-follow
2088 :type 'boolean)
2090 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2091 "Non-nil means ask for confirmation before executing shell links.
2092 Shell links can be dangerous: just think about a link
2094 [[shell:rm -rf ~/*][Google Search]]
2096 This link would show up in your Org-mode document as \"Google Search\",
2097 but really it would remove your entire home directory.
2098 Therefore we advise against setting this variable to nil.
2099 Just change it to `y-or-n-p' if you want to confirm with a
2100 single keystroke rather than having to type \"yes\"."
2101 :group 'org-link-follow
2102 :type '(choice
2103 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2104 (const :tag "with y-or-n (faster)" y-or-n-p)
2105 (const :tag "no confirmation (dangerous)" nil)))
2106 (put 'org-confirm-shell-link-function
2107 'safe-local-variable
2108 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2110 (defcustom org-confirm-shell-link-not-regexp ""
2111 "A regexp to skip confirmation for shell links."
2112 :group 'org-link-follow
2113 :version "24.1"
2114 :type 'regexp)
2116 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2117 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2118 Elisp links can be dangerous: just think about a link
2120 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2122 This link would show up in your Org-mode document as \"Google Search\",
2123 but really it would remove your entire home directory.
2124 Therefore we advise against setting this variable to nil.
2125 Just change it to `y-or-n-p' if you want to confirm with a
2126 single keystroke rather than having to type \"yes\"."
2127 :group 'org-link-follow
2128 :type '(choice
2129 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2130 (const :tag "with y-or-n (faster)" y-or-n-p)
2131 (const :tag "no confirmation (dangerous)" nil)))
2132 (put 'org-confirm-shell-link-function
2133 'safe-local-variable
2134 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2136 (defcustom org-confirm-elisp-link-not-regexp ""
2137 "A regexp to skip confirmation for Elisp links."
2138 :group 'org-link-follow
2139 :version "24.1"
2140 :type 'regexp)
2142 (defconst org-file-apps-defaults-gnu
2143 '((remote . emacs)
2144 (system . mailcap)
2145 (t . mailcap))
2146 "Default file applications on a UNIX or GNU/Linux system.
2147 See `org-file-apps'.")
2149 (defconst org-file-apps-defaults-macosx
2150 '((remote . emacs)
2151 (system . "open %s")
2152 ("ps.gz" . "gv %s")
2153 ("eps.gz" . "gv %s")
2154 ("dvi" . "xdvi %s")
2155 ("fig" . "xfig %s")
2156 (t . "open %s"))
2157 "Default file applications on a MacOS X system.
2158 The system \"open\" is known as a default, but we use X11 applications
2159 for some files for which the OS does not have a good default.
2160 See `org-file-apps'.")
2162 (defconst org-file-apps-defaults-windowsnt
2163 (list '(remote . emacs)
2164 (cons 'system (lambda (file _path)
2165 (with-no-warnings (w32-shell-execute "open" file))))
2166 (cons t (lambda (file _path)
2167 (with-no-warnings (w32-shell-execute "open" file)))))
2168 "Default file applications on a Windows NT system.
2169 The system \"open\" is used for most files.
2170 See `org-file-apps'.")
2172 (defcustom org-file-apps
2173 '((auto-mode . emacs)
2174 ("\\.mm\\'" . default)
2175 ("\\.x?html?\\'" . default)
2176 ("\\.pdf\\'" . default))
2177 "External applications for opening `file:path' items in a document.
2178 \\<org-mode-map>\
2179 Org mode uses system defaults for different file types, but
2180 you can use this variable to set the application for a given file
2181 extension. The entries in this list are cons cells where the car identifies
2182 files and the cdr the corresponding command. Possible values for the
2183 file identifier are
2184 \"string\" A string as a file identifier can be interpreted in different
2185 ways, depending on its contents:
2187 - Alphanumeric characters only:
2188 Match links with this file extension.
2189 Example: (\"pdf\" . \"evince %s\")
2190 to open PDFs with evince.
2192 - Regular expression: Match links where the
2193 filename matches the regexp. If you want to
2194 use groups here, use shy groups.
2196 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2197 \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2198 to open *.html and *.xhtml with firefox.
2200 - Regular expression which contains (non-shy) groups:
2201 Match links where the whole link, including \"::\", and
2202 anything after that, matches the regexp.
2203 In a custom command string, %1, %2, etc. are replaced with
2204 the parts of the link that were matched by the groups.
2205 For backwards compatibility, if a command string is given
2206 that does not use any of the group matches, this case is
2207 handled identically to the second one (i.e. match against
2208 file name only).
2209 In a custom function, you can access the group matches with
2210 \(match-string n link).
2212 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2213 to open [[file:document.pdf::5]] with evince at page 5.
2215 `directory' Matches a directory
2216 `remote' Matches a remote file, accessible through tramp or efs.
2217 Remote files most likely should be visited through Emacs
2218 because external applications cannot handle such paths.
2219 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2220 so all files Emacs knows how to handle. Using this with
2221 command `emacs' will open most files in Emacs. Beware that this
2222 will also open html files inside Emacs, unless you add
2223 \(\"html\" . default) to the list as well.
2224 `system' The system command to open files, like `open' on Windows
2225 and Mac OS X, and mailcap under GNU/Linux. This is the command
2226 that will be selected if you call \\[org-open-at-point] with a double
2227 \\[universal-argument] \\[universal-argument] prefix.
2228 t Default for files not matched by any of the other options.
2230 Possible values for the command are:
2231 `emacs' The file will be visited by the current Emacs process.
2232 `default' Use the default application for this file type, which is the
2233 association for t in the list, most likely in the system-specific
2234 part. This can be used to overrule an unwanted setting in the
2235 system-specific variable.
2236 `system' Use the system command for opening files, like \"open\".
2237 This command is specified by the entry whose car is `system'.
2238 Most likely, the system-specific version of this variable
2239 does define this command, but you can overrule/replace it
2240 here.
2241 `mailcap' Use command specified in the mailcaps.
2242 string A command to be executed by a shell; %s will be replaced
2243 by the path to the file.
2245 function A Lisp function, which will be called with two arguments:
2246 the file path and the original link string, without the
2247 \"file:\" prefix.
2249 For more examples, see the system specific constants
2250 `org-file-apps-defaults-macosx'
2251 `org-file-apps-defaults-windowsnt'
2252 `org-file-apps-defaults-gnu'."
2253 :group 'org-link-follow
2254 :type '(repeat
2255 (cons (choice :value ""
2256 (string :tag "Extension")
2257 (const :tag "System command to open files" system)
2258 (const :tag "Default for unrecognized files" t)
2259 (const :tag "Remote file" remote)
2260 (const :tag "Links to a directory" directory)
2261 (const :tag "Any files that have Emacs modes"
2262 auto-mode))
2263 (choice :value ""
2264 (const :tag "Visit with Emacs" emacs)
2265 (const :tag "Use default" default)
2266 (const :tag "Use the system command" system)
2267 (string :tag "Command")
2268 (function :tag "Function")))))
2270 (defcustom org-doi-server-url "http://dx.doi.org/"
2271 "The URL of the DOI server."
2272 :type 'string
2273 :version "24.3"
2274 :group 'org-link-follow)
2276 (defgroup org-refile nil
2277 "Options concerning refiling entries in Org-mode."
2278 :tag "Org Refile"
2279 :group 'org)
2281 (defcustom org-directory "~/org"
2282 "Directory with Org files.
2283 This is just a default location to look for Org files. There is no need
2284 at all to put your files into this directory. It is used in the
2285 following situations:
2287 1. When a capture template specifies a target file that is not an
2288 absolute path. The path will then be interpreted relative to
2289 `org-directory'
2290 2. When the value of variable `org-agenda-files' is a single file, any
2291 relative paths in this file will be taken as relative to
2292 `org-directory'."
2293 :group 'org-refile
2294 :group 'org-capture
2295 :type 'directory)
2297 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2298 "Default target for storing notes.
2299 Used as a fall back file for org-capture.el, for templates that
2300 do not specify a target file."
2301 :group 'org-refile
2302 :group 'org-capture
2303 :type 'file)
2305 (defcustom org-goto-interface 'outline
2306 "The default interface to be used for `org-goto'.
2307 Allowed values are:
2308 outline The interface shows an outline of the relevant file
2309 and the correct heading is found by moving through
2310 the outline or by searching with incremental search.
2311 outline-path-completion Headlines in the current buffer are offered via
2312 completion. This is the interface also used by
2313 the refile command."
2314 :group 'org-refile
2315 :type '(choice
2316 (const :tag "Outline" outline)
2317 (const :tag "Outline-path-completion" outline-path-completion)))
2319 (defcustom org-goto-max-level 5
2320 "Maximum target level when running `org-goto' with refile interface."
2321 :group 'org-refile
2322 :type 'integer)
2324 (defcustom org-reverse-note-order nil
2325 "Non-nil means store new notes at the beginning of a file or entry.
2326 When nil, new notes will be filed to the end of a file or entry.
2327 This can also be a list with cons cells of regular expressions that
2328 are matched against file names, and values."
2329 :group 'org-capture
2330 :group 'org-refile
2331 :type '(choice
2332 (const :tag "Reverse always" t)
2333 (const :tag "Reverse never" nil)
2334 (repeat :tag "By file name regexp"
2335 (cons regexp boolean))))
2337 (defcustom org-log-refile nil
2338 "Information to record when a task is refiled.
2340 Possible values are:
2342 nil Don't add anything
2343 time Add a time stamp to the task
2344 note Prompt for a note and add it with template `org-log-note-headings'
2346 This option can also be set with on a per-file-basis with
2348 #+STARTUP: nologrefile
2349 #+STARTUP: logrefile
2350 #+STARTUP: lognoterefile
2352 You can have local logging settings for a subtree by setting the LOGGING
2353 property to one or more of these keywords.
2355 When bulk-refiling from the agenda, the value `note' is forbidden and
2356 will temporarily be changed to `time'."
2357 :group 'org-refile
2358 :group 'org-progress
2359 :version "24.1"
2360 :type '(choice
2361 (const :tag "No logging" nil)
2362 (const :tag "Record timestamp" time)
2363 (const :tag "Record timestamp with note." note)))
2365 (defcustom org-refile-targets nil
2366 "Targets for refiling entries with \\[org-refile].
2367 This is a list of cons cells. Each cell contains:
2368 - a specification of the files to be considered, either a list of files,
2369 or a symbol whose function or variable value will be used to retrieve
2370 a file name or a list of file names. If you use `org-agenda-files' for
2371 that, all agenda files will be scanned for targets. Nil means consider
2372 headings in the current buffer.
2373 - A specification of how to find candidate refile targets. This may be
2374 any of:
2375 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2376 This tag has to be present in all target headlines, inheritance will
2377 not be considered.
2378 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2379 todo keyword.
2380 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2381 headlines that are refiling targets.
2382 - a cons cell (:level . N). Any headline of level N is considered a target.
2383 Note that, when `org-odd-levels-only' is set, level corresponds to
2384 order in hierarchy, not to the number of stars.
2385 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2386 Note that, when `org-odd-levels-only' is set, level corresponds to
2387 order in hierarchy, not to the number of stars.
2389 Each element of this list generates a set of possible targets.
2390 The union of these sets is presented (with completion) to
2391 the user by `org-refile'.
2393 You can set the variable `org-refile-target-verify-function' to a function
2394 to verify each headline found by the simple criteria above.
2396 When this variable is nil, all top-level headlines in the current buffer
2397 are used, equivalent to the value `((nil . (:level . 1))'."
2398 :group 'org-refile
2399 :type '(repeat
2400 (cons
2401 (choice :value org-agenda-files
2402 (const :tag "All agenda files" org-agenda-files)
2403 (const :tag "Current buffer" nil)
2404 (function) (variable) (file))
2405 (choice :tag "Identify target headline by"
2406 (cons :tag "Specific tag" (const :value :tag) (string))
2407 (cons :tag "TODO keyword" (const :value :todo) (string))
2408 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2409 (cons :tag "Level number" (const :value :level) (integer))
2410 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2412 (defcustom org-refile-target-verify-function nil
2413 "Function to verify if the headline at point should be a refile target.
2414 The function will be called without arguments, with point at the
2415 beginning of the headline. It should return t and leave point
2416 where it is if the headline is a valid target for refiling.
2418 If the target should not be selected, the function must return nil.
2419 In addition to this, it may move point to a place from where the search
2420 should be continued. For example, the function may decide that the entire
2421 subtree of the current entry should be excluded and move point to the end
2422 of the subtree."
2423 :group 'org-refile
2424 :type '(choice
2425 (const nil)
2426 (function)))
2428 (defcustom org-refile-use-cache nil
2429 "Non-nil means cache refile targets to speed up the process.
2430 \\<org-mode-map>\
2431 The cache for a particular file will be updated automatically when
2432 the buffer has been killed, or when any of the marker used for flagging
2433 refile targets no longer points at a live buffer.
2434 If you have added new entries to a buffer that might themselves be targets,
2435 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2436 if you find that easier, \
2437 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2438 \\[org-refile]'."
2439 :group 'org-refile
2440 :version "24.1"
2441 :type 'boolean)
2443 (defcustom org-refile-use-outline-path nil
2444 "Non-nil means provide refile targets as paths.
2445 So a level 3 headline will be available as level1/level2/level3.
2447 When the value is `file', also include the file name (without directory)
2448 into the path. In this case, you can also stop the completion after
2449 the file name, to get entries inserted as top level in the file.
2451 When `full-file-path', include the full file path."
2452 :group 'org-refile
2453 :type '(choice
2454 (const :tag "Not" nil)
2455 (const :tag "Yes" t)
2456 (const :tag "Start with file name" file)
2457 (const :tag "Start with full file path" full-file-path)))
2459 (defcustom org-outline-path-complete-in-steps t
2460 "Non-nil means complete the outline path in hierarchical steps.
2461 When Org-mode uses the refile interface to select an outline path
2462 \(see variable `org-refile-use-outline-path'), the completion of
2463 the path can be done in a single go, or it can be done in steps down
2464 the headline hierarchy. Going in steps is probably the best if you
2465 do not use a special completion package like `ido' or `icicles'.
2466 However, when using these packages, going in one step can be very
2467 fast, while still showing the whole path to the entry."
2468 :group 'org-refile
2469 :type 'boolean)
2471 (defcustom org-refile-allow-creating-parent-nodes nil
2472 "Non-nil means allow the creation of new nodes as refile targets.
2473 New nodes are then created by adding \"/new node name\" to the completion
2474 of an existing node. When the value of this variable is `confirm',
2475 new node creation must be confirmed by the user (recommended).
2476 When nil, the completion must match an existing entry.
2478 Note that, if the new heading is not seen by the criteria
2479 listed in `org-refile-targets', multiple instances of the same
2480 heading would be created by trying again to file under the new
2481 heading."
2482 :group 'org-refile
2483 :type '(choice
2484 (const :tag "Never" nil)
2485 (const :tag "Always" t)
2486 (const :tag "Prompt for confirmation" confirm)))
2488 (defcustom org-refile-active-region-within-subtree nil
2489 "Non-nil means also refile active region within a subtree.
2491 By default `org-refile' doesn't allow refiling regions if they
2492 don't contain a set of subtrees, but it might be convenient to
2493 do so sometimes: in that case, the first line of the region is
2494 converted to a headline before refiling."
2495 :group 'org-refile
2496 :version "24.1"
2497 :type 'boolean)
2499 (defgroup org-todo nil
2500 "Options concerning TODO items in Org-mode."
2501 :tag "Org TODO"
2502 :group 'org)
2504 (defgroup org-progress nil
2505 "Options concerning Progress logging in Org-mode."
2506 :tag "Org Progress"
2507 :group 'org-time)
2509 (defvar org-todo-interpretation-widgets
2510 '((:tag "Sequence (cycling hits every state)" sequence)
2511 (:tag "Type (cycling directly to DONE)" type))
2512 "The available interpretation symbols for customizing `org-todo-keywords'.
2513 Interested libraries should add to this list.")
2515 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2516 "List of TODO entry keyword sequences and their interpretation.
2517 \\<org-mode-map>This is a list of sequences.
2519 Each sequence starts with a symbol, either `sequence' or `type',
2520 indicating if the keywords should be interpreted as a sequence of
2521 action steps, or as different types of TODO items. The first
2522 keywords are states requiring action - these states will select a headline
2523 for inclusion into the global TODO list Org-mode produces. If one of
2524 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2525 signify that no further action is necessary. If \"|\" is not found,
2526 the last keyword is treated as the only DONE state of the sequence.
2528 The command \\[org-todo] cycles an entry through these states, and one
2529 additional state where no keyword is present. For details about this
2530 cycling, see the manual.
2532 TODO keywords and interpretation can also be set on a per-file basis with
2533 the special #+SEQ_TODO and #+TYP_TODO lines.
2535 Each keyword can optionally specify a character for fast state selection
2536 \(in combination with the variable `org-use-fast-todo-selection')
2537 and specifiers for state change logging, using the same syntax that
2538 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2539 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2540 indicates to record a time stamp each time this state is selected.
2542 Each keyword may also specify if a timestamp or a note should be
2543 recorded when entering or leaving the state, by adding additional
2544 characters in the parenthesis after the keyword. This looks like this:
2545 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2546 record only the time of the state change. With X and Y being either
2547 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2548 Y when leaving the state if and only if the *target* state does not
2549 define X. You may omit any of the fast-selection key or X or /Y,
2550 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2552 For backward compatibility, this variable may also be just a list
2553 of keywords. In this case the interpretation (sequence or type) will be
2554 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2555 :group 'org-todo
2556 :group 'org-keywords
2557 :type '(choice
2558 (repeat :tag "Old syntax, just keywords"
2559 (string :tag "Keyword"))
2560 (repeat :tag "New syntax"
2561 (cons
2562 (choice
2563 :tag "Interpretation"
2564 ;;Quick and dirty way to see
2565 ;;`org-todo-interpretations'. This takes the
2566 ;;place of item arguments
2567 :convert-widget
2568 (lambda (widget)
2569 (widget-put widget
2570 :args (mapcar
2571 (lambda (x)
2572 (widget-convert
2573 (cons 'const x)))
2574 org-todo-interpretation-widgets))
2575 widget))
2576 (repeat
2577 (string :tag "Keyword"))))))
2579 (defvar-local org-todo-keywords-1 nil
2580 "All TODO and DONE keywords active in a buffer.")
2581 (defvar org-todo-keywords-for-agenda nil)
2582 (defvar org-done-keywords-for-agenda nil)
2583 (defvar org-todo-keyword-alist-for-agenda nil)
2584 (defvar org-tag-alist-for-agenda nil
2585 "Alist of all tags from all agenda files.")
2586 (defvar org-tag-groups-alist-for-agenda nil
2587 "Alist of all groups tags from all current agenda files.")
2588 (defvar-local org-tag-groups-alist nil)
2589 (defvar org-agenda-contributing-files nil)
2590 (defvar-local org-current-tag-alist nil
2591 "Alist of all tag groups in current buffer.
2592 This variable takes into consideration `org-tag-alist',
2593 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2594 (defvar-local org-not-done-keywords nil)
2595 (defvar-local org-done-keywords nil)
2596 (defvar-local org-todo-heads nil)
2597 (defvar-local org-todo-sets nil)
2598 (defvar-local org-todo-log-states nil)
2599 (defvar-local org-todo-kwd-alist nil)
2600 (defvar-local org-todo-key-alist nil)
2601 (defvar-local org-todo-key-trigger nil)
2603 (defcustom org-todo-interpretation 'sequence
2604 "Controls how TODO keywords are interpreted.
2605 This variable is in principle obsolete and is only used for
2606 backward compatibility, if the interpretation of todo keywords is
2607 not given already in `org-todo-keywords'. See that variable for
2608 more information."
2609 :group 'org-todo
2610 :group 'org-keywords
2611 :type '(choice (const sequence)
2612 (const type)))
2614 (defcustom org-use-fast-todo-selection t
2615 "\\<org-mode-map>\
2616 Non-nil means use the fast todo selection scheme with \\[org-todo].
2617 This variable describes if and under what circumstances the cycling
2618 mechanism for TODO keywords will be replaced by a single-key, direct
2619 selection scheme.
2621 When nil, fast selection is never used.
2623 When the symbol `prefix', it will be used when `org-todo' is called
2624 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2625 in an Org-mode buffer, and
2626 `\\[universal-argument] t' in an agenda buffer.
2628 When t, fast selection is used by default. In this case, the prefix
2629 argument forces cycling instead.
2631 In all cases, the special interface is only used if access keys have
2632 actually been assigned by the user, i.e. if keywords in the configuration
2633 are followed by a letter in parenthesis, like TODO(t)."
2634 :group 'org-todo
2635 :type '(choice
2636 (const :tag "Never" nil)
2637 (const :tag "By default" t)
2638 (const :tag "Only with C-u C-c C-t" prefix)))
2640 (defcustom org-provide-todo-statistics t
2641 "Non-nil means update todo statistics after insert and toggle.
2642 ALL-HEADLINES means update todo statistics by including headlines
2643 with no TODO keyword as well, counting them as not done.
2644 A list of TODO keywords means the same, but skip keywords that are
2645 not in this list.
2646 When set to a list of two lists, the first list contains keywords
2647 to consider as TODO keywords, the second list contains keywords
2648 to consider as DONE keywords.
2650 When this is set, todo statistics is updated in the parent of the
2651 current entry each time a todo state is changed."
2652 :group 'org-todo
2653 :type '(choice
2654 (const :tag "Yes, only for TODO entries" t)
2655 (const :tag "Yes, including all entries" all-headlines)
2656 (repeat :tag "Yes, for TODOs in this list"
2657 (string :tag "TODO keyword"))
2658 (list :tag "Yes, for TODOs and DONEs in these lists"
2659 (repeat (string :tag "TODO keyword"))
2660 (repeat (string :tag "DONE keyword")))
2661 (other :tag "No TODO statistics" nil)))
2663 (defcustom org-hierarchical-todo-statistics t
2664 "Non-nil means TODO statistics covers just direct children.
2665 When nil, all entries in the subtree are considered.
2666 This has only an effect if `org-provide-todo-statistics' is set.
2667 To set this to nil for only a single subtree, use a COOKIE_DATA
2668 property and include the word \"recursive\" into the value."
2669 :group 'org-todo
2670 :type 'boolean)
2672 (defcustom org-after-todo-state-change-hook nil
2673 "Hook which is run after the state of a TODO item was changed.
2674 The new state (a string with a TODO keyword, or nil) is available in the
2675 Lisp variable `org-state'."
2676 :group 'org-todo
2677 :type 'hook)
2679 (defvar org-blocker-hook nil
2680 "Hook for functions that are allowed to block a state change.
2682 Functions in this hook should not modify the buffer.
2683 Each function gets as its single argument a property list,
2684 see `org-trigger-hook' for more information about this list.
2686 If any of the functions in this hook returns nil, the state change
2687 is blocked.")
2689 (defvar org-trigger-hook nil
2690 "Hook for functions that are triggered by a state change.
2692 Each function gets as its single argument a property list with at
2693 least the following elements:
2695 (:type type-of-change :position pos-at-entry-start
2696 :from old-state :to new-state)
2698 Depending on the type, more properties may be present.
2700 This mechanism is currently implemented for:
2702 TODO state changes
2703 ------------------
2704 :type todo-state-change
2705 :from previous state (keyword as a string), or nil, or a symbol
2706 `todo' or `done', to indicate the general type of state.
2707 :to new state, like in :from")
2709 (defcustom org-enforce-todo-dependencies nil
2710 "Non-nil means undone TODO entries will block switching the parent to DONE.
2711 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2712 be blocked if any prior sibling is not yet done.
2713 Finally, if the parent is blocked because of ordered siblings of its own,
2714 the child will also be blocked."
2715 :set (lambda (var val)
2716 (set var val)
2717 (if val
2718 (add-hook 'org-blocker-hook
2719 'org-block-todo-from-children-or-siblings-or-parent)
2720 (remove-hook 'org-blocker-hook
2721 'org-block-todo-from-children-or-siblings-or-parent)))
2722 :group 'org-todo
2723 :type 'boolean)
2725 (defcustom org-enforce-todo-checkbox-dependencies nil
2726 "Non-nil means unchecked boxes will block switching the parent to DONE.
2727 When this is nil, checkboxes have no influence on switching TODO states.
2728 When non-nil, you first need to check off all check boxes before the TODO
2729 entry can be switched to DONE.
2730 This variable needs to be set before org.el is loaded, and you need to
2731 restart Emacs after a change to make the change effective. The only way
2732 to change is while Emacs is running is through the customize interface."
2733 :set (lambda (var val)
2734 (set var val)
2735 (if val
2736 (add-hook 'org-blocker-hook
2737 'org-block-todo-from-checkboxes)
2738 (remove-hook 'org-blocker-hook
2739 'org-block-todo-from-checkboxes)))
2740 :group 'org-todo
2741 :type 'boolean)
2743 (defcustom org-treat-insert-todo-heading-as-state-change nil
2744 "Non-nil means inserting a TODO heading is treated as state change.
2745 So when the command \\[org-insert-todo-heading] is used, state change
2746 logging will apply if appropriate. When nil, the new TODO item will
2747 be inserted directly, and no logging will take place."
2748 :group 'org-todo
2749 :type 'boolean)
2751 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2752 "Non-nil means switching TODO states with S-cursor counts as state change.
2753 This is the default behavior. However, setting this to nil allows a
2754 convenient way to select a TODO state and bypass any logging associated
2755 with that."
2756 :group 'org-todo
2757 :type 'boolean)
2759 (defcustom org-todo-state-tags-triggers nil
2760 "Tag changes that should be triggered by TODO state changes.
2761 This is a list. Each entry is
2763 (state-change (tag . flag) .......)
2765 State-change can be a string with a state, and empty string to indicate the
2766 state that has no TODO keyword, or it can be one of the symbols `todo'
2767 or `done', meaning any not-done or done state, respectively."
2768 :group 'org-todo
2769 :group 'org-tags
2770 :type '(repeat
2771 (cons (choice :tag "When changing to"
2772 (const :tag "Not-done state" todo)
2773 (const :tag "Done state" done)
2774 (string :tag "State"))
2775 (repeat
2776 (cons :tag "Tag action"
2777 (string :tag "Tag")
2778 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2780 (defcustom org-log-done nil
2781 "Information to record when a task moves to the DONE state.
2783 Possible values are:
2785 nil Don't add anything, just change the keyword
2786 time Add a time stamp to the task
2787 note Prompt for a note and add it with template `org-log-note-headings'
2789 This option can also be set with on a per-file-basis with
2791 #+STARTUP: nologdone
2792 #+STARTUP: logdone
2793 #+STARTUP: lognotedone
2795 You can have local logging settings for a subtree by setting the LOGGING
2796 property to one or more of these keywords."
2797 :group 'org-todo
2798 :group 'org-progress
2799 :type '(choice
2800 (const :tag "No logging" nil)
2801 (const :tag "Record CLOSED timestamp" time)
2802 (const :tag "Record CLOSED timestamp with note." note)))
2804 ;; Normalize old uses of org-log-done.
2805 (cond
2806 ((eq org-log-done t) (setq org-log-done 'time))
2807 ((and (listp org-log-done) (memq 'done org-log-done))
2808 (setq org-log-done 'note)))
2810 (defcustom org-log-reschedule nil
2811 "Information to record when the scheduling date of a tasks is modified.
2813 Possible values are:
2815 nil Don't add anything, just change the date
2816 time Add a time stamp to the task
2817 note Prompt for a note and add it with template `org-log-note-headings'
2819 This option can also be set with on a per-file-basis with
2821 #+STARTUP: nologreschedule
2822 #+STARTUP: logreschedule
2823 #+STARTUP: lognotereschedule"
2824 :group 'org-todo
2825 :group 'org-progress
2826 :type '(choice
2827 (const :tag "No logging" nil)
2828 (const :tag "Record timestamp" time)
2829 (const :tag "Record timestamp with note." note)))
2831 (defcustom org-log-redeadline nil
2832 "Information to record when the deadline date of a tasks is modified.
2834 Possible values are:
2836 nil Don't add anything, just change the date
2837 time Add a time stamp to the task
2838 note Prompt for a note and add it with template `org-log-note-headings'
2840 This option can also be set with on a per-file-basis with
2842 #+STARTUP: nologredeadline
2843 #+STARTUP: logredeadline
2844 #+STARTUP: lognoteredeadline
2846 You can have local logging settings for a subtree by setting the LOGGING
2847 property to one or more of these keywords."
2848 :group 'org-todo
2849 :group 'org-progress
2850 :type '(choice
2851 (const :tag "No logging" nil)
2852 (const :tag "Record timestamp" time)
2853 (const :tag "Record timestamp with note." note)))
2855 (defcustom org-log-note-clock-out nil
2856 "Non-nil means record a note when clocking out of an item.
2857 This can also be configured on a per-file basis by adding one of
2858 the following lines anywhere in the buffer:
2860 #+STARTUP: lognoteclock-out
2861 #+STARTUP: nolognoteclock-out"
2862 :group 'org-todo
2863 :group 'org-progress
2864 :type 'boolean)
2866 (defcustom org-log-done-with-time t
2867 "Non-nil means the CLOSED time stamp will contain date and time.
2868 When nil, only the date will be recorded."
2869 :group 'org-progress
2870 :type 'boolean)
2872 (defcustom org-log-note-headings
2873 '((done . "CLOSING NOTE %t")
2874 (state . "State %-12s from %-12S %t")
2875 (note . "Note taken on %t")
2876 (reschedule . "Rescheduled from %S on %t")
2877 (delschedule . "Not scheduled, was %S on %t")
2878 (redeadline . "New deadline from %S on %t")
2879 (deldeadline . "Removed deadline, was %S on %t")
2880 (refile . "Refiled on %t")
2881 (clock-out . ""))
2882 "Headings for notes added to entries.
2884 The value is an alist, with the car being a symbol indicating the
2885 note context, and the cdr is the heading to be used. The heading
2886 may also be the empty string. The following placeholders can be
2887 used:
2889 %t a time stamp.
2890 %T an active time stamp instead the default inactive one
2891 %d a short-format time stamp.
2892 %D an active short-format time stamp.
2893 %s the new TODO state or time stamp (inactive), in double quotes.
2894 %S the old TODO state or time stamp (inactive), in double quotes.
2895 %u the user name.
2896 %U full user name.
2898 In fact, it is not a good idea to change the `state' entry,
2899 because Agenda Log mode depends on the format of these entries."
2900 :group 'org-todo
2901 :group 'org-progress
2902 :type '(list :greedy t
2903 (cons (const :tag "Heading when closing an item" done) string)
2904 (cons (const :tag
2905 "Heading when changing todo state (todo sequence only)"
2906 state) string)
2907 (cons (const :tag "Heading when just taking a note" note) string)
2908 (cons (const :tag "Heading when rescheduling" reschedule) string)
2909 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2910 (cons (const :tag "Heading when changing deadline" redeadline) string)
2911 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2912 (cons (const :tag "Heading when refiling" refile) string)
2913 (cons (const :tag "Heading when clocking out" clock-out) string)))
2915 (unless (assq 'note org-log-note-headings)
2916 (push '(note . "%t") org-log-note-headings))
2918 (defcustom org-log-into-drawer nil
2919 "Non-nil means insert state change notes and time stamps into a drawer.
2920 When nil, state changes notes will be inserted after the headline and
2921 any scheduling and clock lines, but not inside a drawer.
2923 The value of this variable should be the name of the drawer to use.
2924 LOGBOOK is proposed as the default drawer for this purpose, you can
2925 also set this to a string to define the drawer of your choice.
2927 A value of t is also allowed, representing \"LOGBOOK\".
2929 A value of t or nil can also be set with on a per-file-basis with
2931 #+STARTUP: logdrawer
2932 #+STARTUP: nologdrawer
2934 If this variable is set, `org-log-state-notes-insert-after-drawers'
2935 will be ignored.
2937 You can set the property LOG_INTO_DRAWER to overrule this setting for
2938 a subtree.
2940 Do not check directly this variable in a Lisp program. Call
2941 function `org-log-into-drawer' instead."
2942 :group 'org-todo
2943 :group 'org-progress
2944 :type '(choice
2945 (const :tag "Not into a drawer" nil)
2946 (const :tag "LOGBOOK" t)
2947 (string :tag "Other")))
2949 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2951 (defun org-log-into-drawer ()
2952 "Name of the log drawer, as a string, or nil.
2953 This is the value of `org-log-into-drawer'. However, if the
2954 current entry has or inherits a LOG_INTO_DRAWER property, it will
2955 be used instead of the default value."
2956 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2957 (cond ((equal p "nil") nil)
2958 ((equal p "t") "LOGBOOK")
2959 ((stringp p) p)
2960 (p "LOGBOOK")
2961 ((stringp org-log-into-drawer) org-log-into-drawer)
2962 (org-log-into-drawer "LOGBOOK"))))
2964 (defcustom org-log-state-notes-insert-after-drawers nil
2965 "Non-nil means insert state change notes after any drawers in entry.
2966 Only the drawers that *immediately* follow the headline and the
2967 deadline/scheduled line are skipped.
2968 When nil, insert notes right after the heading and perhaps the line
2969 with deadline/scheduling if present.
2971 This variable will have no effect if `org-log-into-drawer' is
2972 set."
2973 :group 'org-todo
2974 :group 'org-progress
2975 :type 'boolean)
2977 (defcustom org-log-states-order-reversed t
2978 "Non-nil means the latest state note will be directly after heading.
2979 When nil, the state change notes will be ordered according to time.
2981 This option can also be set with on a per-file-basis with
2983 #+STARTUP: logstatesreversed
2984 #+STARTUP: nologstatesreversed"
2985 :group 'org-todo
2986 :group 'org-progress
2987 :type 'boolean)
2989 (defcustom org-todo-repeat-to-state nil
2990 "The TODO state to which a repeater should return the repeating task.
2991 By default this is the first task in a TODO sequence, or the previous state
2992 in a TODO_TYP set. But you can specify another task here.
2993 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2994 :group 'org-todo
2995 :version "24.1"
2996 :type '(choice (const :tag "Head of sequence" nil)
2997 (string :tag "Specific state")))
2999 (defcustom org-log-repeat 'time
3000 "Non-nil means record moving through the DONE state when triggering repeat.
3001 An auto-repeating task is immediately switched back to TODO when
3002 marked DONE. If you are not logging state changes (by adding \"@\"
3003 or \"!\" to the TODO keyword definition), or set `org-log-done' to
3004 record a closing note, there will be no record of the task moving
3005 through DONE. This variable forces taking a note anyway.
3007 nil Don't force a record
3008 time Record a time stamp
3009 note Prompt for a note and add it with template `org-log-note-headings'
3011 This option can also be set with on a per-file-basis with
3013 #+STARTUP: nologrepeat
3014 #+STARTUP: logrepeat
3015 #+STARTUP: lognoterepeat
3017 You can have local logging settings for a subtree by setting the LOGGING
3018 property to one or more of these keywords."
3019 :group 'org-todo
3020 :group 'org-progress
3021 :type '(choice
3022 (const :tag "Don't force a record" nil)
3023 (const :tag "Force recording the DONE state" time)
3024 (const :tag "Force recording a note with the DONE state" note)))
3027 (defgroup org-priorities nil
3028 "Priorities in Org-mode."
3029 :tag "Org Priorities"
3030 :group 'org-todo)
3032 (defcustom org-enable-priority-commands t
3033 "Non-nil means priority commands are active.
3034 When nil, these commands will be disabled, so that you never accidentally
3035 set a priority."
3036 :group 'org-priorities
3037 :type 'boolean)
3039 (defcustom org-highest-priority ?A
3040 "The highest priority of TODO items. A character like ?A, ?B etc.
3041 Must have a smaller ASCII number than `org-lowest-priority'."
3042 :group 'org-priorities
3043 :type 'character)
3045 (defcustom org-lowest-priority ?C
3046 "The lowest priority of TODO items. A character like ?A, ?B etc.
3047 Must have a larger ASCII number than `org-highest-priority'."
3048 :group 'org-priorities
3049 :type 'character)
3051 (defcustom org-default-priority ?B
3052 "The default priority of TODO items.
3053 This is the priority an item gets if no explicit priority is given.
3054 When starting to cycle on an empty priority the first step in the cycle
3055 depends on `org-priority-start-cycle-with-default'. The resulting first
3056 step priority must not exceed the range from `org-highest-priority' to
3057 `org-lowest-priority' which means that `org-default-priority' has to be
3058 in this range exclusive or inclusive the range boundaries. Else the
3059 first step refuses to set the default and the second will fall back
3060 to (depending on the command used) the highest or lowest priority."
3061 :group 'org-priorities
3062 :type 'character)
3064 (defcustom org-priority-start-cycle-with-default t
3065 "Non-nil means start with default priority when starting to cycle.
3066 When this is nil, the first step in the cycle will be (depending on the
3067 command used) one higher or lower than the default priority.
3068 See also `org-default-priority'."
3069 :group 'org-priorities
3070 :type 'boolean)
3072 (defcustom org-get-priority-function nil
3073 "Function to extract the priority from a string.
3074 The string is normally the headline. If this is nil Org computes the
3075 priority from the priority cookie like [#A] in the headline. It returns
3076 an integer, increasing by 1000 for each priority level.
3077 The user can set a different function here, which should take a string
3078 as an argument and return the numeric priority."
3079 :group 'org-priorities
3080 :version "24.1"
3081 :type '(choice
3082 (const nil)
3083 (function)))
3085 (defgroup org-time nil
3086 "Options concerning time stamps and deadlines in Org-mode."
3087 :tag "Org Time"
3088 :group 'org)
3090 (defcustom org-time-stamp-rounding-minutes '(0 5)
3091 "Number of minutes to round time stamps to.
3092 \\<org-mode-map>\
3093 These are two values, the first applies when first creating a time stamp.
3094 The second applies when changing it with the commands `S-up' and `S-down'.
3095 When changing the time stamp, this means that it will change in steps
3096 of N minutes, as given by the second value.
3098 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3099 numbers should be factors of 60, so for example 5, 10, 15.
3101 When this is larger than 1, you can still force an exact time stamp by using
3102 a double prefix argument to a time stamp command like \
3103 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3104 and by using a prefix arg to `S-up/down' to specify the exact number
3105 of minutes to shift."
3106 :group 'org-time
3107 :get (lambda (var) ; Make sure both elements are there
3108 (if (integerp (default-value var))
3109 (list (default-value var) 5)
3110 (default-value var)))
3111 :type '(list
3112 (integer :tag "when inserting times")
3113 (integer :tag "when modifying times")))
3115 ;; Normalize old customizations of this variable.
3116 (when (integerp org-time-stamp-rounding-minutes)
3117 (setq org-time-stamp-rounding-minutes
3118 (list org-time-stamp-rounding-minutes
3119 org-time-stamp-rounding-minutes)))
3121 (defcustom org-display-custom-times nil
3122 "Non-nil means overlay custom formats over all time stamps.
3123 The formats are defined through the variable `org-time-stamp-custom-formats'.
3124 To turn this on on a per-file basis, insert anywhere in the file:
3125 #+STARTUP: customtime"
3126 :group 'org-time
3127 :set 'set-default
3128 :type 'sexp)
3129 (make-variable-buffer-local 'org-display-custom-times)
3131 (defcustom org-time-stamp-custom-formats
3132 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3133 "Custom formats for time stamps. See `format-time-string' for the syntax.
3134 These are overlaid over the default ISO format if the variable
3135 `org-display-custom-times' is set. Time like %H:%M should be at the
3136 end of the second format. The custom formats are also honored by export
3137 commands, if custom time display is turned on at the time of export."
3138 :group 'org-time
3139 :type 'sexp)
3141 (defun org-time-stamp-format (&optional long inactive)
3142 "Get the right format for a time string."
3143 (let ((f (if long (cdr org-time-stamp-formats)
3144 (car org-time-stamp-formats))))
3145 (if inactive
3146 (concat "[" (substring f 1 -1) "]")
3147 f)))
3149 (defcustom org-time-clocksum-format
3150 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3151 "The format string used when creating CLOCKSUM lines.
3152 This is also used when Org mode generates a time duration.
3154 The value can be a single format string containing two
3155 %-sequences, which will be filled with the number of hours and
3156 minutes in that order.
3158 Alternatively, the value can be a plist associating any of the
3159 keys :years, :months, :weeks, :days, :hours or :minutes with
3160 format strings. The time duration is formatted using only the
3161 time components that are needed and concatenating the results.
3162 If a time unit in absent, it falls back to the next smallest
3163 unit.
3165 The keys :require-years, :require-months, :require-days,
3166 :require-weeks, :require-hours, :require-minutes are also
3167 meaningful. A non-nil value for these keys indicates that the
3168 corresponding time component should always be included, even if
3169 its value is 0.
3172 For example,
3174 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3175 :require-minutes t)
3177 means durations longer than a day will be expressed in days,
3178 hours and minutes, and durations less than a day will always be
3179 expressed in hours and minutes (even for durations less than an
3180 hour).
3182 The value
3184 (:days \"%dd\" :minutes \"%dm\")
3186 means durations longer than a day will be expressed in days and
3187 minutes, and durations less than a day will be expressed entirely
3188 in minutes (even for durations longer than an hour)."
3189 :group 'org-time
3190 :group 'org-clock
3191 :version "24.4"
3192 :package-version '(Org . "8.0")
3193 :type '(choice (string :tag "Format string")
3194 (set :tag "Plist"
3195 (group :inline t (const :tag "Years" :years)
3196 (string :tag "Format string"))
3197 (group :inline t
3198 (const :tag "Always show years" :require-years)
3199 (const t))
3200 (group :inline t (const :tag "Months" :months)
3201 (string :tag "Format string"))
3202 (group :inline t
3203 (const :tag "Always show months" :require-months)
3204 (const t))
3205 (group :inline t (const :tag "Weeks" :weeks)
3206 (string :tag "Format string"))
3207 (group :inline t
3208 (const :tag "Always show weeks" :require-weeks)
3209 (const t))
3210 (group :inline t (const :tag "Days" :days)
3211 (string :tag "Format string"))
3212 (group :inline t
3213 (const :tag "Always show days" :require-days)
3214 (const t))
3215 (group :inline t (const :tag "Hours" :hours)
3216 (string :tag "Format string"))
3217 (group :inline t
3218 (const :tag "Always show hours" :require-hours)
3219 (const t))
3220 (group :inline t (const :tag "Minutes" :minutes)
3221 (string :tag "Format string"))
3222 (group :inline t
3223 (const :tag "Always show minutes" :require-minutes)
3224 (const t)))))
3226 (defcustom org-time-clocksum-use-fractional nil
3227 "When non-nil, \\[org-clock-display] uses fractional times.
3228 See `org-time-clocksum-format' for more on time clock formats."
3229 :group 'org-time
3230 :group 'org-clock
3231 :version "24.3"
3232 :type 'boolean)
3234 (defcustom org-time-clocksum-use-effort-durations nil
3235 "When non-nil, \\[org-clock-display] uses effort durations.
3236 E.g. by default, one day is considered to be a 8 hours effort,
3237 so a task that has been clocked for 16 hours will be displayed
3238 as during 2 days in the clock display or in the clocktable.
3240 See `org-effort-durations' on how to set effort durations
3241 and `org-time-clocksum-format' for more on time clock formats."
3242 :group 'org-time
3243 :group 'org-clock
3244 :version "24.4"
3245 :package-version '(Org . "8.0")
3246 :type 'boolean)
3248 (defcustom org-time-clocksum-fractional-format "%.2f"
3249 "The format string used when creating CLOCKSUM lines,
3250 or when Org mode generates a time duration, if
3251 `org-time-clocksum-use-fractional' is enabled.
3253 The value can be a single format string containing one
3254 %-sequence, which will be filled with the number of hours as
3255 a float.
3257 Alternatively, the value can be a plist associating any of the
3258 keys :years, :months, :weeks, :days, :hours or :minutes with
3259 a format string. The time duration is formatted using the
3260 largest time unit which gives a non-zero integer part. If all
3261 specified formats have zero integer part, the smallest time unit
3262 is used."
3263 :group 'org-time
3264 :type '(choice (string :tag "Format string")
3265 (set (group :inline t (const :tag "Years" :years)
3266 (string :tag "Format string"))
3267 (group :inline t (const :tag "Months" :months)
3268 (string :tag "Format string"))
3269 (group :inline t (const :tag "Weeks" :weeks)
3270 (string :tag "Format string"))
3271 (group :inline t (const :tag "Days" :days)
3272 (string :tag "Format string"))
3273 (group :inline t (const :tag "Hours" :hours)
3274 (string :tag "Format string"))
3275 (group :inline t (const :tag "Minutes" :minutes)
3276 (string :tag "Format string")))))
3278 (defcustom org-deadline-warning-days 14
3279 "Number of days before expiration during which a deadline becomes active.
3280 This variable governs the display in sparse trees and in the agenda.
3281 When 0 or negative, it means use this number (the absolute value of it)
3282 even if a deadline has a different individual lead time specified.
3284 Custom commands can set this variable in the options section."
3285 :group 'org-time
3286 :group 'org-agenda-daily/weekly
3287 :type 'integer)
3289 (defcustom org-scheduled-delay-days 0
3290 "Number of days before a scheduled item becomes active.
3291 This variable governs the display in sparse trees and in the agenda.
3292 The default value (i.e. 0) means: don't delay scheduled item.
3293 When negative, it means use this number (the absolute value of it)
3294 even if a scheduled item has a different individual delay time
3295 specified.
3297 Custom commands can set this variable in the options section."
3298 :group 'org-time
3299 :group 'org-agenda-daily/weekly
3300 :version "24.4"
3301 :package-version '(Org . "8.0")
3302 :type 'integer)
3304 (defcustom org-read-date-prefer-future t
3305 "Non-nil means assume future for incomplete date input from user.
3306 This affects the following situations:
3307 1. The user gives a month but not a year.
3308 For example, if it is April and you enter \"feb 2\", this will be read
3309 as Feb 2, *next* year. \"May 5\", however, will be this year.
3310 2. The user gives a day, but no month.
3311 For example, if today is the 15th, and you enter \"3\", Org-mode will
3312 read this as the third of *next* month. However, if you enter \"17\",
3313 it will be considered as *this* month.
3315 If you set this variable to the symbol `time', then also the following
3316 will work:
3318 3. If the user gives a time.
3319 If the time is before now, it will be interpreted as tomorrow.
3321 Currently none of this works for ISO week specifications.
3323 When this option is nil, the current day, month and year will always be
3324 used as defaults.
3326 See also `org-agenda-jump-prefer-future'."
3327 :group 'org-time
3328 :type '(choice
3329 (const :tag "Never" nil)
3330 (const :tag "Check month and day" t)
3331 (const :tag "Check month, day, and time" time)))
3333 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3334 "Should the agenda jump command prefer the future for incomplete dates?
3335 The default is to do the same as configured in `org-read-date-prefer-future'.
3336 But you can also set a deviating value here.
3337 This may t or nil, or the symbol `org-read-date-prefer-future'."
3338 :group 'org-agenda
3339 :group 'org-time
3340 :version "24.1"
3341 :type '(choice
3342 (const :tag "Use org-read-date-prefer-future"
3343 org-read-date-prefer-future)
3344 (const :tag "Never" nil)
3345 (const :tag "Always" t)))
3347 (defcustom org-read-date-force-compatible-dates t
3348 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3350 Depending on the system Emacs is running on, certain dates cannot
3351 be represented with the type used internally to represent time.
3352 Dates between 1970-1-1 and 2038-1-1 can always be represented
3353 correctly. Some systems allow for earlier dates, some for later,
3354 some for both. One way to find out it to insert any date into an
3355 Org buffer, putting the cursor on the year and hitting S-up and
3356 S-down to test the range.
3358 When this variable is set to t, the date/time prompt will not let
3359 you specify dates outside the 1970-2037 range, so it is certain that
3360 these dates will work in whatever version of Emacs you are
3361 running, and also that you can move a file from one Emacs implementation
3362 to another. WHenever Org is forcing the year for you, it will display
3363 a message and beep.
3365 When this variable is nil, Org will check if the date is
3366 representable in the specific Emacs implementation you are using.
3367 If not, it will force a year, usually the current year, and beep
3368 to remind you. Currently this setting is not recommended because
3369 the likelihood that you will open your Org files in an Emacs that
3370 has limited date range is not negligible.
3372 A workaround for this problem is to use diary sexp dates for time
3373 stamps outside of this range."
3374 :group 'org-time
3375 :version "24.1"
3376 :type 'boolean)
3378 (defcustom org-read-date-display-live t
3379 "Non-nil means display current interpretation of date prompt live.
3380 This display will be in an overlay, in the minibuffer."
3381 :group 'org-time
3382 :type 'boolean)
3384 (defcustom org-read-date-popup-calendar t
3385 "Non-nil means pop up a calendar when prompting for a date.
3386 In the calendar, the date can be selected with mouse-1. However, the
3387 minibuffer will also be active, and you can simply enter the date as well.
3388 When nil, only the minibuffer will be available."
3389 :group 'org-time
3390 :type 'boolean)
3391 (org-defvaralias 'org-popup-calendar-for-date-prompt
3392 'org-read-date-popup-calendar)
3394 (make-obsolete-variable
3395 'org-read-date-minibuffer-setup-hook
3396 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3397 (defcustom org-read-date-minibuffer-setup-hook nil
3398 "Hook to be used to set up keys for the date/time interface.
3399 Add key definitions to `minibuffer-local-map', which will be a
3400 temporary copy.
3402 WARNING: This option is obsolete, you should use
3403 `org-read-date-minibuffer-local-map' to set up keys."
3404 :group 'org-time
3405 :type 'hook)
3407 (defcustom org-extend-today-until 0
3408 "The hour when your day really ends. Must be an integer.
3409 This has influence for the following applications:
3410 - When switching the agenda to \"today\". It it is still earlier than
3411 the time given here, the day recognized as TODAY is actually yesterday.
3412 - When a date is read from the user and it is still before the time given
3413 here, the current date and time will be assumed to be yesterday, 23:59.
3414 Also, timestamps inserted in capture templates follow this rule.
3416 IMPORTANT: This is a feature whose implementation is and likely will
3417 remain incomplete. Really, it is only here because past midnight seems to
3418 be the favorite working time of John Wiegley :-)"
3419 :group 'org-time
3420 :type 'integer)
3422 (defcustom org-use-effective-time nil
3423 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3424 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3425 \"effective time\" of any timestamps between midnight and 8am will be
3426 23:59 of the previous day."
3427 :group 'org-time
3428 :version "24.1"
3429 :type 'boolean)
3431 (defcustom org-use-last-clock-out-time-as-effective-time nil
3432 "When non-nil, use the last clock out time for `org-todo'.
3433 Note that this option has precedence over the combined use of
3434 `org-use-effective-time' and `org-extend-today-until'."
3435 :group 'org-time
3436 :version "24.4"
3437 :package-version '(Org . "8.0")
3438 :type 'boolean)
3440 (defcustom org-edit-timestamp-down-means-later nil
3441 "Non-nil means S-down will increase the time in a time stamp.
3442 When nil, S-up will increase."
3443 :group 'org-time
3444 :type 'boolean)
3446 (defcustom org-calendar-follow-timestamp-change t
3447 "Non-nil means make the calendar window follow timestamp changes.
3448 When a timestamp is modified and the calendar window is visible, it will be
3449 moved to the new date."
3450 :group 'org-time
3451 :type 'boolean)
3453 (defgroup org-tags nil
3454 "Options concerning tags in Org-mode."
3455 :tag "Org Tags"
3456 :group 'org)
3458 (defcustom org-tag-alist nil
3459 "Default tags available in Org files.
3461 The value of this variable is an alist. Associations either:
3463 (TAG)
3464 (TAG . SELECT)
3465 (SPECIAL)
3467 where TAG is a tag as a string, SELECT is a character, used to
3468 select that tag through the fast tag selection interface, and
3469 SPECIAL is one of the following keywords: `:startgroup',
3470 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3471 `:newline'. These keywords are used to define a hierarchy of
3472 tags. See manual for details.
3474 When this variable is nil, Org mode bases tag input on what is
3475 already in the buffer. The value can be overridden locally by
3476 using a TAGS keyword, e.g.,
3478 #+TAGS: tag1 tag2
3480 See also `org-tag-persistent-alist' to sidestep this behavior."
3481 :group 'org-tags
3482 :type '(repeat
3483 (choice
3484 (cons (string :tag "Tag name")
3485 (character :tag "Access char"))
3486 (const :tag "Start radio group" (:startgroup))
3487 (const :tag "Start tag group, non distinct" (:startgrouptag))
3488 (const :tag "Group tags delimiter" (:grouptags))
3489 (const :tag "End radio group" (:endgroup))
3490 (const :tag "End tag group, non distinct" (:endgrouptag))
3491 (const :tag "New line" (:newline)))))
3493 (defcustom org-tag-persistent-alist nil
3494 "Tags always available in Org files.
3496 The value of this variable is an alist. Associations either:
3498 (TAG)
3499 (TAG . SELECT)
3500 (SPECIAL)
3502 where TAG is a tag as a string, SELECT is a character, used to
3503 select that tag through the fast tag selection interface, and
3504 SPECIAL is one of the following keywords: `:startgroup',
3505 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3506 `:newline'. These keywords are used to define a hierarchy of
3507 tags. See manual for details.
3509 Unlike to `org-tag-alist', tags defined in this variable do not
3510 depend on a local TAGS keyword. Instead, to disable these tags
3511 on a per-file basis, insert anywhere in the file:
3513 #+STARTUP: noptag"
3514 :group 'org-tags
3515 :type '(repeat
3516 (choice
3517 (cons (string :tag "Tag name")
3518 (character :tag "Access char"))
3519 (const :tag "Start radio group" (:startgroup))
3520 (const :tag "Start tag group, non distinct" (:startgrouptag))
3521 (const :tag "Group tags delimiter" (:grouptags))
3522 (const :tag "End radio group" (:endgroup))
3523 (const :tag "End tag group, non distinct" (:endgrouptag))
3524 (const :tag "New line" (:newline)))))
3526 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3527 "If non-nil, always offer completion for all tags of all agenda files.
3528 Instead of customizing this variable directly, you might want to
3529 set it locally for capture buffers, because there no list of
3530 tags in that file can be created dynamically (there are none).
3532 (add-hook \\='org-capture-mode-hook
3533 (lambda ()
3534 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3535 :group 'org-tags
3536 :version "24.1"
3537 :type 'boolean)
3539 (defvar org-file-tags nil
3540 "List of tags that can be inherited by all entries in the file.
3541 The tags will be inherited if the variable `org-use-tag-inheritance'
3542 says they should be.
3543 This variable is populated from #+FILETAGS lines.")
3545 (defcustom org-use-fast-tag-selection 'auto
3546 "Non-nil means use fast tag selection scheme.
3547 This is a special interface to select and deselect tags with single keys.
3548 When nil, fast selection is never used.
3549 When the symbol `auto', fast selection is used if and only if selection
3550 characters for tags have been configured, either through the variable
3551 `org-tag-alist' or through a #+TAGS line in the buffer.
3552 When t, fast selection is always used and selection keys are assigned
3553 automatically if necessary."
3554 :group 'org-tags
3555 :type '(choice
3556 (const :tag "Always" t)
3557 (const :tag "Never" nil)
3558 (const :tag "When selection characters are configured" auto)))
3560 (defcustom org-fast-tag-selection-single-key nil
3561 "Non-nil means fast tag selection exits after first change.
3562 When nil, you have to press RET to exit it.
3563 During fast tag selection, you can toggle this flag with `C-c'.
3564 This variable can also have the value `expert'. In this case, the window
3565 displaying the tags menu is not even shown, until you press C-c again."
3566 :group 'org-tags
3567 :type '(choice
3568 (const :tag "No" nil)
3569 (const :tag "Yes" t)
3570 (const :tag "Expert" expert)))
3572 (defvar org-fast-tag-selection-include-todo nil
3573 "Non-nil means fast tags selection interface will also offer TODO states.
3574 This is an undocumented feature, you should not rely on it.")
3576 (defcustom org-tags-column -77
3577 "The column to which tags should be indented in a headline.
3578 If this number is positive, it specifies the column. If it is negative,
3579 it means that the tags should be flushright to that column. For example,
3580 -80 works well for a normal 80 character screen.
3581 When 0, place tags directly after headline text, with only one space in
3582 between."
3583 :group 'org-tags
3584 :type 'integer)
3586 (defcustom org-auto-align-tags t
3587 "Non-nil keeps tags aligned when modifying headlines.
3588 Some operations (i.e. demoting) change the length of a headline and
3589 therefore shift the tags around. With this option turned on, after
3590 each such operation the tags are again aligned to `org-tags-column'."
3591 :group 'org-tags
3592 :type 'boolean)
3594 (defcustom org-use-tag-inheritance t
3595 "Non-nil means tags in levels apply also for sublevels.
3596 When nil, only the tags directly given in a specific line apply there.
3597 This may also be a list of tags that should be inherited, or a regexp that
3598 matches tags that should be inherited. Additional control is possible
3599 with the variable `org-tags-exclude-from-inheritance' which gives an
3600 explicit list of tags to be excluded from inheritance, even if the value of
3601 `org-use-tag-inheritance' would select it for inheritance.
3603 If this option is t, a match early-on in a tree can lead to a large
3604 number of matches in the subtree when constructing the agenda or creating
3605 a sparse tree. If you only want to see the first match in a tree during
3606 a search, check out the variable `org-tags-match-list-sublevels'."
3607 :group 'org-tags
3608 :type '(choice
3609 (const :tag "Not" nil)
3610 (const :tag "Always" t)
3611 (repeat :tag "Specific tags" (string :tag "Tag"))
3612 (regexp :tag "Tags matched by regexp")))
3614 (defcustom org-tags-exclude-from-inheritance nil
3615 "List of tags that should never be inherited.
3616 This is a way to exclude a few tags from inheritance. For way to do
3617 the opposite, to actively allow inheritance for selected tags,
3618 see the variable `org-use-tag-inheritance'."
3619 :group 'org-tags
3620 :type '(repeat (string :tag "Tag")))
3622 (defun org-tag-inherit-p (tag)
3623 "Check if TAG is one that should be inherited."
3624 (cond
3625 ((member tag org-tags-exclude-from-inheritance) nil)
3626 ((eq org-use-tag-inheritance t) t)
3627 ((not org-use-tag-inheritance) nil)
3628 ((stringp org-use-tag-inheritance)
3629 (string-match org-use-tag-inheritance tag))
3630 ((listp org-use-tag-inheritance)
3631 (member tag org-use-tag-inheritance))
3632 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3634 (defcustom org-tags-match-list-sublevels t
3635 "Non-nil means list also sublevels of headlines matching a search.
3636 This variable applies to tags/property searches, and also to stuck
3637 projects because this search is based on a tags match as well.
3639 When set to the symbol `indented', sublevels are indented with
3640 leading dots.
3642 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3643 the sublevels of a headline matching a tag search often also match
3644 the same search. Listing all of them can create very long lists.
3645 Setting this variable to nil causes subtrees of a match to be skipped.
3647 This variable is semi-obsolete and probably should always be true. It
3648 is better to limit inheritance to certain tags using the variables
3649 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3650 :group 'org-tags
3651 :type '(choice
3652 (const :tag "No, don't list them" nil)
3653 (const :tag "Yes, do list them" t)
3654 (const :tag "List them, indented with leading dots" indented)))
3656 (defcustom org-tags-sort-function nil
3657 "When set, tags are sorted using this function as a comparator."
3658 :group 'org-tags
3659 :type '(choice
3660 (const :tag "No sorting" nil)
3661 (const :tag "Alphabetical" string<)
3662 (const :tag "Reverse alphabetical" string>)
3663 (function :tag "Custom function" nil)))
3665 (defvar org-tags-history nil
3666 "History of minibuffer reads for tags.")
3667 (defvar org-last-tags-completion-table nil
3668 "The last used completion table for tags.")
3669 (defvar org-after-tags-change-hook nil
3670 "Hook that is run after the tags in a line have changed.")
3672 (defgroup org-properties nil
3673 "Options concerning properties in Org-mode."
3674 :tag "Org Properties"
3675 :group 'org)
3677 (defcustom org-property-format "%-10s %s"
3678 "How property key/value pairs should be formatted by `indent-line'.
3679 When `indent-line' hits a property definition, it will format the line
3680 according to this format, mainly to make sure that the values are
3681 lined-up with respect to each other."
3682 :group 'org-properties
3683 :type 'string)
3685 (defcustom org-properties-postprocess-alist nil
3686 "Alist of properties and functions to adjust inserted values.
3687 Elements of this alist must be of the form
3689 ([string] [function])
3691 where [string] must be a property name and [function] must be a
3692 lambda expression: this lambda expression must take one argument,
3693 the value to adjust, and return the new value as a string.
3695 For example, this element will allow the property \"Remaining\"
3696 to be updated wrt the relation between the \"Effort\" property
3697 and the clock summary:
3699 ((\"Remaining\" (lambda(value)
3700 (let ((clocksum (org-clock-sum-current-item))
3701 (effort (org-duration-string-to-minutes
3702 (org-entry-get (point) \"Effort\"))))
3703 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3704 :group 'org-properties
3705 :version "24.1"
3706 :type '(alist :key-type (string :tag "Property")
3707 :value-type (function :tag "Function")))
3709 (defcustom org-use-property-inheritance nil
3710 "Non-nil means properties apply also for sublevels.
3712 This setting is chiefly used during property searches. Turning it on can
3713 cause significant overhead when doing a search, which is why it is not
3714 on by default.
3716 When nil, only the properties directly given in the current entry count.
3717 When t, every property is inherited. The value may also be a list of
3718 properties that should have inheritance, or a regular expression matching
3719 properties that should be inherited.
3721 However, note that some special properties use inheritance under special
3722 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3723 and the properties ending in \"_ALL\" when they are used as descriptor
3724 for valid values of a property.
3726 Note for programmers:
3727 When querying an entry with `org-entry-get', you can control if inheritance
3728 should be used. By default, `org-entry-get' looks only at the local
3729 properties. You can request inheritance by setting the inherit argument
3730 to t (to force inheritance) or to `selective' (to respect the setting
3731 in this variable)."
3732 :group 'org-properties
3733 :type '(choice
3734 (const :tag "Not" nil)
3735 (const :tag "Always" t)
3736 (repeat :tag "Specific properties" (string :tag "Property"))
3737 (regexp :tag "Properties matched by regexp")))
3739 (defun org-property-inherit-p (property)
3740 "Check if PROPERTY is one that should be inherited."
3741 (cond
3742 ((eq org-use-property-inheritance t) t)
3743 ((not org-use-property-inheritance) nil)
3744 ((stringp org-use-property-inheritance)
3745 (string-match org-use-property-inheritance property))
3746 ((listp org-use-property-inheritance)
3747 (member property org-use-property-inheritance))
3748 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3750 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3751 "The default column format, if no other format has been defined.
3752 This variable can be set on the per-file basis by inserting a line
3754 #+COLUMNS: %25ITEM ....."
3755 :group 'org-properties
3756 :type 'string)
3758 (defcustom org-columns-ellipses ".."
3759 "The ellipses to be used when a field in column view is truncated.
3760 When this is the empty string, as many characters as possible are shown,
3761 but then there will be no visual indication that the field has been truncated.
3762 When this is a string of length N, the last N characters of a truncated
3763 field are replaced by this string. If the column is narrower than the
3764 ellipses string, only part of the ellipses string will be shown."
3765 :group 'org-properties
3766 :type 'string)
3768 (defconst org-global-properties-fixed
3769 '(("VISIBILITY_ALL" . "folded children content all")
3770 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3771 "List of property/value pairs that can be inherited by any entry.
3773 These are fixed values, for the preset properties. The user variable
3774 that can be used to add to this list is `org-global-properties'.
3776 The entries in this list are cons cells where the car is a property
3777 name and cdr is a string with the value. If the value represents
3778 multiple items like an \"_ALL\" property, separate the items by
3779 spaces.")
3781 (defcustom org-global-properties nil
3782 "List of property/value pairs that can be inherited by any entry.
3784 This list will be combined with the constant `org-global-properties-fixed'.
3786 The entries in this list are cons cells where the car is a property
3787 name and cdr is a string with the value.
3789 You can set buffer-local values for the same purpose in the variable
3790 `org-file-properties' this by adding lines like
3792 #+PROPERTY: NAME VALUE"
3793 :group 'org-properties
3794 :type '(repeat
3795 (cons (string :tag "Property")
3796 (string :tag "Value"))))
3798 (defvar-local org-file-properties nil
3799 "List of property/value pairs that can be inherited by any entry.
3800 Valid for the current buffer.
3801 This variable is populated from #+PROPERTY lines.")
3803 (defgroup org-agenda nil
3804 "Options concerning agenda views in Org-mode."
3805 :tag "Org Agenda"
3806 :group 'org)
3808 (defvar-local org-category nil
3809 "Variable used by org files to set a category for agenda display.
3810 Such files should use a file variable to set it, for example
3812 # -*- mode: org; org-category: \"ELisp\"
3814 or contain a special line
3816 #+CATEGORY: ELisp
3818 If the file does not specify a category, then file's base name
3819 is used instead.")
3820 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3822 (defcustom org-agenda-files nil
3823 "The files to be used for agenda display.
3824 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3825 \\[org-remove-file]. You can also use customize to edit the list.
3827 If an entry is a directory, all files in that directory that are matched by
3828 `org-agenda-file-regexp' will be part of the file list.
3830 If the value of the variable is not a list but a single file name, then
3831 the list of agenda files is actually stored and maintained in that file, one
3832 agenda file per line. In this file paths can be given relative to
3833 `org-directory'. Tilde expansion and environment variable substitution
3834 are also made."
3835 :group 'org-agenda
3836 :type '(choice
3837 (repeat :tag "List of files and directories" file)
3838 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3840 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3841 "Regular expression to match files for `org-agenda-files'.
3842 If any element in the list in that variable contains a directory instead
3843 of a normal file, all files in that directory that are matched by this
3844 regular expression will be included."
3845 :group 'org-agenda
3846 :type 'regexp)
3848 (defcustom org-agenda-text-search-extra-files nil
3849 "List of extra files to be searched by text search commands.
3850 These files will be searched in addition to the agenda files by the
3851 commands `org-search-view' (`\\[org-agenda] s') \
3852 and `org-occur-in-agenda-files'.
3853 Note that these files will only be searched for text search commands,
3854 not for the other agenda views like todo lists, tag searches or the weekly
3855 agenda. This variable is intended to list notes and possibly archive files
3856 that should also be searched by these two commands.
3857 In fact, if the first element in the list is the symbol `agenda-archives',
3858 then all archive files of all agenda files will be added to the search
3859 scope."
3860 :group 'org-agenda
3861 :type '(set :greedy t
3862 (const :tag "Agenda Archives" agenda-archives)
3863 (repeat :inline t (file))))
3865 (org-defvaralias 'org-agenda-multi-occur-extra-files
3866 'org-agenda-text-search-extra-files)
3868 (defcustom org-agenda-skip-unavailable-files nil
3869 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3870 A nil value means to remove them, after a query, from the list."
3871 :group 'org-agenda
3872 :type 'boolean)
3874 (defcustom org-calendar-to-agenda-key [?c]
3875 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3876 The command `org-calendar-goto-agenda' will be bound to this key. The
3877 default is the character `c' because then `c' can be used to switch back and
3878 forth between agenda and calendar."
3879 :group 'org-agenda
3880 :type 'sexp)
3882 (defcustom org-calendar-insert-diary-entry-key [?i]
3883 "The key to be installed in `calendar-mode-map' for adding diary entries.
3884 This option is irrelevant until `org-agenda-diary-file' has been configured
3885 to point to an Org-mode file. When that is the case, the command
3886 `org-agenda-diary-entry' will be bound to the key given here, by default
3887 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3888 if you want to continue doing this, you need to change this to a different
3889 key."
3890 :group 'org-agenda
3891 :type 'sexp)
3893 (defcustom org-agenda-diary-file 'diary-file
3894 "File to which to add new entries with the `i' key in agenda and calendar.
3895 When this is the symbol `diary-file', the functionality in the Emacs
3896 calendar will be used to add entries to the `diary-file'. But when this
3897 points to a file, `org-agenda-diary-entry' will be used instead."
3898 :group 'org-agenda
3899 :type '(choice
3900 (const :tag "The standard Emacs diary file" diary-file)
3901 (file :tag "Special Org file diary entries")))
3903 (eval-after-load "calendar"
3904 '(progn
3905 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3906 'org-calendar-goto-agenda)
3907 (add-hook 'calendar-mode-hook
3908 (lambda ()
3909 (unless (eq org-agenda-diary-file 'diary-file)
3910 (define-key calendar-mode-map
3911 org-calendar-insert-diary-entry-key
3912 'org-agenda-diary-entry))))))
3914 (defgroup org-latex nil
3915 "Options for embedding LaTeX code into Org-mode."
3916 :tag "Org LaTeX"
3917 :group 'org)
3919 (defcustom org-format-latex-options
3920 '(:foreground default :background default :scale 1.0
3921 :html-foreground "Black" :html-background "Transparent"
3922 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3923 "Options for creating images from LaTeX fragments.
3924 This is a property list with the following properties:
3925 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3926 `default' means use the foreground of the default face.
3927 `auto' means use the foreground from the text face.
3928 :background the background color, or \"Transparent\".
3929 `default' means use the background of the default face.
3930 `auto' means use the background from the text face.
3931 :scale a scaling factor for the size of the images, to get more pixels
3932 :html-foreground, :html-background, :html-scale
3933 the same numbers for HTML export.
3934 :matchers a list indicating which matchers should be used to
3935 find LaTeX fragments. Valid members of this list are:
3936 \"begin\" find environments
3937 \"$1\" find single characters surrounded by $.$
3938 \"$\" find math expressions surrounded by $...$
3939 \"$$\" find math expressions surrounded by $$....$$
3940 \"\\(\" find math expressions surrounded by \\(...\\)
3941 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3942 :group 'org-latex
3943 :type 'plist)
3945 (defcustom org-format-latex-signal-error t
3946 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3947 When nil, just push out a message."
3948 :group 'org-latex
3949 :version "24.1"
3950 :type 'boolean)
3952 (defcustom org-latex-to-mathml-jar-file nil
3953 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3954 Use this to specify additional executable file say a jar file.
3956 When using MathToWeb as the converter, specify the full-path to
3957 your mathtoweb.jar file."
3958 :group 'org-latex
3959 :version "24.1"
3960 :type '(choice
3961 (const :tag "None" nil)
3962 (file :tag "JAR file" :must-match t)))
3964 (defcustom org-latex-to-mathml-convert-command nil
3965 "Command to convert LaTeX fragments to MathML.
3966 Replace format-specifiers in the command as noted below and use
3967 `shell-command' to convert LaTeX to MathML.
3968 %j: Executable file in fully expanded form as specified by
3969 `org-latex-to-mathml-jar-file'.
3970 %I: Input LaTeX file in fully expanded form.
3971 %i: The latex fragment to be converted.
3972 %o: Output MathML file.
3974 This command is used by `org-create-math-formula'.
3976 When using MathToWeb as the converter, set this option to
3977 \"java -jar %j -unicode -force -df %o %I\".
3979 When using LaTeXML set this option to
3980 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3981 :group 'org-latex
3982 :version "24.1"
3983 :type '(choice
3984 (const :tag "None" nil)
3985 (string :tag "\nShell command")))
3987 (define-obsolete-variable-alias
3988 'org-latex-create-formula-image-program
3989 'org-preview-latex-default-process "25.1")
3991 (defcustom org-preview-latex-default-process 'dvipng
3992 "The default process to convert LaTeX fragments to image files.
3993 All available processes and theirs documents can be found in
3994 `org-preview-latex-process-alist', which see."
3995 :group 'org-latex
3996 :version "25.2"
3997 :package-version '(Org . "9.0")
3998 :type 'symbol)
4000 (defcustom org-preview-latex-process-alist
4001 '((dvipng
4002 :programs ("latex" "dvipng" "gs")
4003 :description "dvi > png"
4004 :message "you need to install the programs: latex, dvipng and ghostscript."
4005 :image-input-type "dvi"
4006 :image-output-type "png"
4007 :image-size-adjust (1.0 . 1.0)
4008 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4009 :image-converter ("dvipng -fg %F -bg %B -D %D -T tight -o %b.png %f"))
4010 (dvisvgm
4011 :programs ("latex" "dvisvgm" "gs")
4012 :description "dvi > svg"
4013 :message "you need to install the programs: latex, dvisvgm and ghostscript."
4014 :use-xcolor t
4015 :image-input-type "dvi"
4016 :image-output-type "svg"
4017 :image-size-adjust (1.7 . 1.5)
4018 :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f")
4019 :image-converter ("dvisvgm %f -n -b min -c %S -o %b.svg"))
4020 (imagemagick
4021 :programs ("latex" "convert" "gs")
4022 :description "pdf > png"
4023 :message
4024 "you need to install the programs: latex, imagemagick and ghostscript."
4025 :use-xcolor t
4026 :image-input-type "pdf"
4027 :image-output-type "png"
4028 :image-size-adjust (1.0 . 1.0)
4029 :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f")
4030 :image-converter
4031 ("convert -density %D -trim -antialias %f -quality 100 %b.png")))
4032 "Definitions of external processes for LaTeX previewing.
4033 Org mode can use some external commands to generate TeX snippet's images for
4034 previewing or inserting into HTML files, e.g., \"dvipng\". This variable tells
4035 `org-create-formula-image' how to call them.
4037 The value is an alist with the pattern (NAME . PROPERTIES). NAME is a symbol.
4038 PROPERTIES accepts the following attributes:
4040 :programs list of strings, required programs.
4041 :description string, describe the process.
4042 :message string, message it when required programs cannot be found.
4043 :image-input-type string, input file type of image converter (e.g., \"dvi\").
4044 :image-output-type string, output file type of image converter (e.g., \"png\").
4045 :use-xcolor boolean, when non-nil, LaTeX \"xcolor\" macro is used to
4046 deal with background and foreground color of image.
4047 Otherwise, dvipng style background and foregroud color
4048 format are generated. You may then refer to them in
4049 command options with \"%F\" and \"%B\".
4050 :image-size-adjust cons of numbers, the car element is used to adjust LaTeX
4051 image size showed in buffer and the cdr element is for
4052 HTML file. This option is only useful for process
4053 developers, users should use variable
4054 `org-format-latex-options' instead.
4055 :post-clean list of strings, files matched are to be cleaned up once
4056 the image is generated. When nil, the files with \".dvi\",
4057 \".xdv\", \".pdf\", \".tex\", \".aux\", \".log\", \".svg\",
4058 \".png\", \".jpg\", \".jpeg\" or \".out\" extension will
4059 be cleaned up.
4060 :latex-header list of strings, the LaTeX header of the snippet file.
4061 When nil, the fallback value is used instead, which is
4062 controlled by `org-format-latex-header',
4063 `org-latex-default-packages-alist' and
4064 `org-latex-packages-alist', which see.
4065 :latex-compiler list of LaTeX commands, as strings. Each of them is given
4066 to the shell. Place-holders \"%t\", \"%b\" and \"%o\" are
4067 replaced with values defined below.
4068 :image-converter list of image converter commands strings. Each of them is
4069 given to the shell and supports any of the following
4070 place-holders defined below.
4072 Place-holders used by `:image-converter' and `:latex-compiler':
4074 %f input file name.
4075 %b base name of input file.
4076 %o base directory of input file.
4078 Place-holders only used by `:image-converter':
4080 %F foreground of image
4081 %B background of image
4082 %D dpi, which is used to adjust image size by some processing commands.
4083 %S the image size scale ratio, which is used to adjust image size by some
4084 processing commands."
4085 :group 'org-latex
4086 :version "25.2"
4087 :package-version '(Org . "9.0")
4088 :type '(alist :tag "LaTeX to image backends"
4089 :value-type (plist)))
4091 (define-obsolete-variable-alias
4092 'org-latex-preview-ltxpng-directory
4093 'org-preview-latex-image-directory "25.1")
4095 (defcustom org-preview-latex-image-directory "ltximg/"
4096 "Path to store latex preview images.
4097 A relative path here creates many directories relative to the
4098 processed org files paths. An absolute path puts all preview
4099 images at the same place."
4100 :group 'org-latex
4101 :version "25.1"
4102 :package-version '(Org . "9.0")
4103 :type 'string)
4105 (defun org-format-latex-mathml-available-p ()
4106 "Return t if `org-latex-to-mathml-convert-command' is usable."
4107 (save-match-data
4108 (when (and (boundp 'org-latex-to-mathml-convert-command)
4109 org-latex-to-mathml-convert-command)
4110 (let ((executable (car (split-string
4111 org-latex-to-mathml-convert-command))))
4112 (when (executable-find executable)
4113 (if (string-match
4114 "%j" org-latex-to-mathml-convert-command)
4115 (file-readable-p org-latex-to-mathml-jar-file)
4116 t))))))
4118 (defcustom org-format-latex-header "\\documentclass{article}
4119 \\usepackage[usenames]{color}
4120 \[PACKAGES]
4121 \[DEFAULT-PACKAGES]
4122 \\pagestyle{empty} % do not remove
4123 % The settings below are copied from fullpage.sty
4124 \\setlength{\\textwidth}{\\paperwidth}
4125 \\addtolength{\\textwidth}{-3cm}
4126 \\setlength{\\oddsidemargin}{1.5cm}
4127 \\addtolength{\\oddsidemargin}{-2.54cm}
4128 \\setlength{\\evensidemargin}{\\oddsidemargin}
4129 \\setlength{\\textheight}{\\paperheight}
4130 \\addtolength{\\textheight}{-\\headheight}
4131 \\addtolength{\\textheight}{-\\headsep}
4132 \\addtolength{\\textheight}{-\\footskip}
4133 \\addtolength{\\textheight}{-3cm}
4134 \\setlength{\\topmargin}{1.5cm}
4135 \\addtolength{\\topmargin}{-2.54cm}"
4136 "The document header used for processing LaTeX fragments.
4137 It is imperative that this header make sure that no page number
4138 appears on the page. The package defined in the variables
4139 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4140 will either replace the placeholder \"[PACKAGES]\" in this
4141 header, or they will be appended."
4142 :group 'org-latex
4143 :type 'string)
4145 (defun org-set-packages-alist (var val)
4146 "Set the packages alist and make sure it has 3 elements per entry."
4147 (set var (mapcar (lambda (x)
4148 (if (and (consp x) (= (length x) 2))
4149 (list (car x) (nth 1 x) t)
4151 val)))
4153 (defun org-get-packages-alist (var)
4154 "Get the packages alist and make sure it has 3 elements per entry."
4155 (mapcar (lambda (x)
4156 (if (and (consp x) (= (length x) 2))
4157 (list (car x) (nth 1 x) t)
4159 (default-value var)))
4161 (defcustom org-latex-default-packages-alist
4162 '(("AUTO" "inputenc" t ("pdflatex"))
4163 ("T1" "fontenc" t ("pdflatex"))
4164 ("" "graphicx" t)
4165 ("" "grffile" t)
4166 ("" "longtable" nil)
4167 ("" "wrapfig" nil)
4168 ("" "rotating" nil)
4169 ("normalem" "ulem" t)
4170 ("" "amsmath" t)
4171 ("" "textcomp" t)
4172 ("" "amssymb" t)
4173 ("" "capt-of" nil)
4174 ("" "hyperref" nil))
4175 "Alist of default packages to be inserted in the header.
4177 Change this only if one of the packages here causes an
4178 incompatibility with another package you are using.
4180 The packages in this list are needed by one part or another of
4181 Org mode to function properly:
4183 - inputenc, fontenc: for basic font and character selection
4184 - graphicx: for including images
4185 - grffile: allow periods and spaces in graphics file names
4186 - longtable: For multipage tables
4187 - wrapfig: for figure placement
4188 - rotating: for sideways figures and tables
4189 - ulem: for underline and strike-through
4190 - amsmath: for subscript and superscript and math environments
4191 - textcomp, amssymb: for various symbols used
4192 for interpreting the entities in `org-entities'. You can skip
4193 some of these packages if you don't use any of their symbols.
4194 - capt-of: for captions outside of floats
4195 - hyperref: for cross references
4197 Therefore you should not modify this variable unless you know
4198 what you are doing. The one reason to change it anyway is that
4199 you might be loading some other package that conflicts with one
4200 of the default packages. Each element is either a cell or
4201 a string.
4203 A cell is of the format
4205 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4207 If SNIPPET-FLAG is non-nil, the package also needs to be included
4208 when compiling LaTeX snippets into images for inclusion into
4209 non-LaTeX output. COMPILERS is a list of compilers that should
4210 include the package, see `org-latex-compiler'. If the document
4211 compiler is not in the list, and the list is non-nil, the package
4212 will not be inserted in the final document.
4214 A string will be inserted as-is in the header of the document."
4215 :group 'org-latex
4216 :group 'org-export-latex
4217 :set 'org-set-packages-alist
4218 :get 'org-get-packages-alist
4219 :version "25.1"
4220 :package-version '(Org . "8.3")
4221 :type '(repeat
4222 (choice
4223 (list :tag "options/package pair"
4224 (string :tag "options")
4225 (string :tag "package")
4226 (boolean :tag "Snippet"))
4227 (string :tag "A line of LaTeX"))))
4229 (defcustom org-latex-packages-alist nil
4230 "Alist of packages to be inserted in every LaTeX header.
4232 These will be inserted after `org-latex-default-packages-alist'.
4233 Each element is either a cell or a string.
4235 A cell is of the format:
4237 (\"options\" \"package\" SNIPPET-FLAG)
4239 SNIPPET-FLAG, when non-nil, indicates that this package is also
4240 needed when turning LaTeX snippets into images for inclusion into
4241 non-LaTeX output.
4243 A string will be inserted as-is in the header of the document.
4245 Make sure that you only list packages here which:
4247 - you want in every file;
4248 - do not conflict with the setup in `org-format-latex-header';
4249 - do not conflict with the default packages in
4250 `org-latex-default-packages-alist'."
4251 :group 'org-latex
4252 :group 'org-export-latex
4253 :set 'org-set-packages-alist
4254 :get 'org-get-packages-alist
4255 :type '(repeat
4256 (choice
4257 (list :tag "options/package pair"
4258 (string :tag "options")
4259 (string :tag "package")
4260 (boolean :tag "Snippet"))
4261 (string :tag "A line of LaTeX"))))
4263 (defgroup org-appearance nil
4264 "Settings for Org-mode appearance."
4265 :tag "Org Appearance"
4266 :group 'org)
4268 (defcustom org-level-color-stars-only nil
4269 "Non-nil means fontify only the stars in each headline.
4270 When nil, the entire headline is fontified.
4271 Changing it requires restart of `font-lock-mode' to become effective
4272 also in regions already fontified."
4273 :group 'org-appearance
4274 :type 'boolean)
4276 (defcustom org-hide-leading-stars nil
4277 "Non-nil means hide the first N-1 stars in a headline.
4278 This works by using the face `org-hide' for these stars. This
4279 face is white for a light background, and black for a dark
4280 background. You may have to customize the face `org-hide' to
4281 make this work.
4282 Changing it requires restart of `font-lock-mode' to become effective
4283 also in regions already fontified.
4284 You may also set this on a per-file basis by adding one of the following
4285 lines to the buffer:
4287 #+STARTUP: hidestars
4288 #+STARTUP: showstars"
4289 :group 'org-appearance
4290 :type 'boolean)
4292 (defcustom org-hidden-keywords nil
4293 "List of symbols corresponding to keywords to be hidden the org buffer.
4294 For example, a value \\='(title) for this list will make the document's title
4295 appear in the buffer without the initial #+TITLE: keyword."
4296 :group 'org-appearance
4297 :version "24.1"
4298 :type '(set (const :tag "#+AUTHOR" author)
4299 (const :tag "#+DATE" date)
4300 (const :tag "#+EMAIL" email)
4301 (const :tag "#+TITLE" title)))
4303 (defcustom org-custom-properties nil
4304 "List of properties (as strings) with a special meaning.
4305 The default use of these custom properties is to let the user
4306 hide them with `org-toggle-custom-properties-visibility'."
4307 :group 'org-properties
4308 :group 'org-appearance
4309 :version "24.3"
4310 :type '(repeat (string :tag "Property Name")))
4312 (defcustom org-fontify-done-headline nil
4313 "Non-nil means change the face of a headline if it is marked DONE.
4314 Normally, only the TODO/DONE keyword indicates the state of a headline.
4315 When this is non-nil, the headline after the keyword is set to the
4316 `org-headline-done' as an additional indication."
4317 :group 'org-appearance
4318 :type 'boolean)
4320 (defcustom org-fontify-emphasized-text t
4321 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4322 Changing this variable requires a restart of Emacs to take effect."
4323 :group 'org-appearance
4324 :type 'boolean)
4326 (defcustom org-fontify-whole-heading-line nil
4327 "Non-nil means fontify the whole line for headings.
4328 This is useful when setting a background color for the
4329 org-level-* faces."
4330 :group 'org-appearance
4331 :type 'boolean)
4333 (defcustom org-highlight-latex-and-related nil
4334 "Non-nil means highlight LaTeX related syntax in the buffer.
4335 When non nil, the value should be a list containing any of the
4336 following symbols:
4337 `latex' Highlight LaTeX snippets and environments.
4338 `script' Highlight subscript and superscript.
4339 `entities' Highlight entities."
4340 :group 'org-appearance
4341 :version "24.4"
4342 :package-version '(Org . "8.0")
4343 :type '(choice
4344 (const :tag "No highlighting" nil)
4345 (set :greedy t :tag "Highlight"
4346 (const :tag "LaTeX snippets and environments" latex)
4347 (const :tag "Subscript and superscript" script)
4348 (const :tag "Entities" entities))))
4350 (defcustom org-hide-emphasis-markers nil
4351 "Non-nil mean font-lock should hide the emphasis marker characters."
4352 :group 'org-appearance
4353 :type 'boolean)
4355 (defcustom org-hide-macro-markers nil
4356 "Non-nil mean font-lock should hide the brackets marking macro calls."
4357 :group 'org-appearance
4358 :type 'boolean)
4360 (defcustom org-pretty-entities nil
4361 "Non-nil means show entities as UTF8 characters.
4362 When nil, the \\name form remains in the buffer."
4363 :group 'org-appearance
4364 :version "24.1"
4365 :type 'boolean)
4367 (defcustom org-pretty-entities-include-sub-superscripts t
4368 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4369 :group 'org-appearance
4370 :version "24.1"
4371 :type 'boolean)
4373 (defvar org-emph-re nil
4374 "Regular expression for matching emphasis.
4375 After a match, the match groups contain these elements:
4376 0 The match of the full regular expression, including the characters
4377 before and after the proper match
4378 1 The character before the proper match, or empty at beginning of line
4379 2 The proper match, including the leading and trailing markers
4380 3 The leading marker like * or /, indicating the type of highlighting
4381 4 The text between the emphasis markers, not including the markers
4382 5 The character after the match, empty at the end of a line")
4383 (defvar org-verbatim-re nil
4384 "Regular expression for matching verbatim text.")
4385 (defvar org-emphasis-regexp-components) ; defined just below
4386 (defvar org-emphasis-alist) ; defined just below
4387 (defun org-set-emph-re (var val)
4388 "Set variable and compute the emphasis regular expression."
4389 (set var val)
4390 (when (and (boundp 'org-emphasis-alist)
4391 (boundp 'org-emphasis-regexp-components)
4392 org-emphasis-alist org-emphasis-regexp-components)
4393 (let* ((e org-emphasis-regexp-components)
4394 (pre (car e))
4395 (post (nth 1 e))
4396 (border (nth 2 e))
4397 (body (nth 3 e))
4398 (nl (nth 4 e))
4399 (body1 (concat body "*?"))
4400 (markers (mapconcat 'car org-emphasis-alist ""))
4401 (vmarkers (mapconcat
4402 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4403 org-emphasis-alist "")))
4404 ;; make sure special characters appear at the right position in the class
4405 (if (string-match "\\^" markers)
4406 (setq markers (concat (replace-match "" t t markers) "^")))
4407 (if (string-match "-" markers)
4408 (setq markers (concat (replace-match "" t t markers) "-")))
4409 (if (string-match "\\^" vmarkers)
4410 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4411 (if (string-match "-" vmarkers)
4412 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4413 (if (> nl 0)
4414 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4415 (int-to-string nl) "\\}")))
4416 ;; Make the regexp
4417 (setq org-emph-re
4418 (concat "\\([" pre "]\\|^\\)"
4419 "\\("
4420 "\\([" markers "]\\)"
4421 "\\("
4422 "[^" border "]\\|"
4423 "[^" border "]"
4424 body1
4425 "[^" border "]"
4426 "\\)"
4427 "\\3\\)"
4428 "\\([" post "]\\|$\\)"))
4429 (setq org-verbatim-re
4430 (concat "\\([" pre "]\\|^\\)"
4431 "\\("
4432 "\\([" vmarkers "]\\)"
4433 "\\("
4434 "[^" border "]\\|"
4435 "[^" border "]"
4436 body1
4437 "[^" border "]"
4438 "\\)"
4439 "\\3\\)"
4440 "\\([" post "]\\|$\\)")))))
4442 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4443 ;; set this option proved cumbersome. See this message/thread:
4444 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4445 (defvar org-emphasis-regexp-components
4446 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4447 "Components used to build the regular expression for emphasis.
4448 This is a list with five entries. Terminology: In an emphasis string
4449 like \" *strong word* \", we call the initial space PREMATCH, the final
4450 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4451 and \"trong wor\" is the body. The different components in this variable
4452 specify what is allowed/forbidden in each part:
4454 pre Chars allowed as prematch. Beginning of line will be allowed too.
4455 post Chars allowed as postmatch. End of line will be allowed too.
4456 border The chars *forbidden* as border characters.
4457 body-regexp A regexp like \".\" to match a body character. Don't use
4458 non-shy groups here, and don't allow newline here.
4459 newline The maximum number of newlines allowed in an emphasis exp.
4461 You need to reload Org or to restart Emacs after customizing this.")
4463 (defcustom org-emphasis-alist
4464 '(("*" bold)
4465 ("/" italic)
4466 ("_" underline)
4467 ("=" org-verbatim verbatim)
4468 ("~" org-code verbatim)
4469 ("+" (:strike-through t)))
4470 "Alist of characters and faces to emphasize text.
4471 Text starting and ending with a special character will be emphasized,
4472 for example *bold*, _underlined_ and /italic/. This variable sets the
4473 marker characters and the face to be used by font-lock for highlighting
4474 in Org-mode Emacs buffers.
4476 You need to reload Org or to restart Emacs after customizing this."
4477 :group 'org-appearance
4478 :set 'org-set-emph-re
4479 :version "24.4"
4480 :package-version '(Org . "8.0")
4481 :type '(repeat
4482 (list
4483 (string :tag "Marker character")
4484 (choice
4485 (face :tag "Font-lock-face")
4486 (plist :tag "Face property list"))
4487 (option (const verbatim)))))
4489 (defvar org-protecting-blocks '("src" "example" "export")
4490 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4491 This is needed for font-lock setup.")
4493 ;;; Functions and variables from their packages
4494 ;; Declared here to avoid compiler warnings
4495 (defvar mark-active)
4497 ;; Various packages
4498 (declare-function calc-eval "calc" (str &optional separator &rest args))
4499 (declare-function calendar-forward-day "cal-move" (arg))
4500 (declare-function calendar-goto-date "cal-move" (date))
4501 (declare-function calendar-goto-today "cal-move" ())
4502 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4503 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4504 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4505 (declare-function cdlatex-tab "ext:cdlatex" ())
4506 (declare-function dired-get-filename
4507 "dired"
4508 (&optional localp no-error-if-not-filep))
4509 (declare-function iswitchb-read-buffer
4510 "iswitchb"
4511 (prompt &optional
4512 default require-match _predicate start matches-set))
4513 (declare-function org-agenda-change-all-lines
4514 "org-agenda"
4515 (newhead hdmarker &optional fixface just-this))
4516 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4517 "org-agenda"
4518 (&optional end))
4519 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4520 (declare-function org-agenda-format-item
4521 "org-agenda"
4522 (extra txt &optional level category tags dotime
4523 remove-re habitp))
4524 (declare-function org-agenda-maybe-redo "org-agenda" ())
4525 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4526 (declare-function org-agenda-save-markers-for-cut-and-paste
4527 "org-agenda"
4528 (beg end))
4529 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4530 (declare-function org-agenda-skip "org-agenda" ())
4531 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4532 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4533 (declare-function org-indent-mode "org-indent" (&optional arg))
4534 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4535 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4536 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4537 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4538 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4539 (declare-function parse-time-string "parse-time" (string))
4540 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4541 (declare-function table--at-cell-p
4542 "table"
4543 (position &optional object at-column))
4545 (defvar align-mode-rules-list)
4546 (defvar calc-embedded-close-formula)
4547 (defvar calc-embedded-open-formula)
4548 (defvar calc-embedded-open-mode)
4549 (defvar font-lock-unfontify-region-function)
4550 (defvar iswitchb-temp-buflist)
4551 (defvar org-agenda-tags-todo-honor-ignore-options)
4552 (defvar remember-data-file)
4553 (defvar texmathp-why)
4555 ;;;###autoload
4556 (defun turn-on-orgtbl ()
4557 "Unconditionally turn on `orgtbl-mode'."
4558 (require 'org-table)
4559 (orgtbl-mode 1))
4561 (defun org-at-table-p (&optional table-type)
4562 "Non-nil if the cursor is inside an Org table.
4563 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4564 If `org-enable-table-editor' is nil, return nil unconditionally."
4565 (and
4566 org-enable-table-editor
4567 (save-excursion
4568 (beginning-of-line)
4569 (looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4570 (or (not (derived-mode-p 'org-mode))
4571 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4572 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4573 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4575 (defun org-at-table.el-p ()
4576 "Non-nil when point is at a table.el table."
4577 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4578 (let ((element (org-element-at-point)))
4579 (and (eq (org-element-type element) 'table)
4580 (eq (org-element-property :type element) 'table.el)))))
4582 (defun org-table-recognize-table.el ()
4583 "If there is a table.el table nearby, recognize it and move into it."
4584 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4585 (beginning-of-line)
4586 (unless (or (looking-at org-table-dataline-regexp)
4587 (not (looking-at org-table1-hline-regexp)))
4588 (forward-line)
4589 (when (looking-at org-table-any-border-regexp)
4590 (forward-line -2)))
4591 (if (re-search-forward "|" (org-table-end t) t)
4592 (progn
4593 (require 'table)
4594 (if (table--at-cell-p (point)) t
4595 (message "recognizing table.el table...")
4596 (table-recognize-table)
4597 (message "recognizing table.el table...done")))
4598 (error "This should not happen"))))
4599 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4600 (make-obsolete 'org-table-recognize-table.el
4601 "please notify the org mailing list if you use this function."
4602 "Org 9.0")
4604 (defun org-at-table-hline-p ()
4605 "Non-nil when point is inside a hline in a table.
4606 Assume point is already in a table. If `org-enable-table-editor'
4607 is nil, return nil unconditionally."
4608 (and org-enable-table-editor
4609 (save-excursion
4610 (beginning-of-line)
4611 (looking-at org-table-hline-regexp))))
4613 (defun org-table-map-tables (function &optional quietly)
4614 "Apply FUNCTION to the start of all tables in the buffer."
4615 (save-excursion
4616 (save-restriction
4617 (widen)
4618 (goto-char (point-min))
4619 (while (re-search-forward org-table-any-line-regexp nil t)
4620 (unless quietly
4621 (message "Mapping tables: %d%%"
4622 (floor (* 100.0 (point)) (buffer-size))))
4623 (beginning-of-line 1)
4624 (when (and (looking-at org-table-line-regexp)
4625 ;; Exclude tables in src/example/verbatim/clocktable blocks
4626 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4627 (save-excursion (funcall function))
4628 (or (looking-at org-table-line-regexp)
4629 (forward-char 1)))
4630 (re-search-forward org-table-any-border-regexp nil 1))))
4631 (unless quietly (message "Mapping tables: done")))
4633 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4634 (declare-function org-clock-update-mode-line "org-clock" ())
4635 (declare-function org-resolve-clocks "org-clock"
4636 (&optional also-non-dangling-p prompt last-valid))
4638 (defun org-at-TBLFM-p (&optional pos)
4639 "Non-nil when point (or POS) is in #+TBLFM line."
4640 (save-excursion
4641 (goto-char (or pos (point)))
4642 (beginning-of-line)
4643 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4644 (eq (org-element-type (org-element-at-point)) 'table))))
4646 (defvar org-clock-start-time)
4647 (defvar org-clock-marker (make-marker)
4648 "Marker recording the last clock-in.")
4649 (defvar org-clock-hd-marker (make-marker)
4650 "Marker recording the last clock-in, but the headline position.")
4651 (defvar org-clock-heading ""
4652 "The heading of the current clock entry.")
4653 (defun org-clock-is-active ()
4654 "Return the buffer where the clock is currently running.
4655 Return nil if no clock is running."
4656 (marker-buffer org-clock-marker))
4658 (defun org-check-running-clock ()
4659 "Check if the current buffer contains the running clock.
4660 If yes, offer to stop it and to save the buffer with the changes."
4661 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4662 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4663 (buffer-name))))
4664 (org-clock-out)
4665 (when (y-or-n-p "Save changed buffer?")
4666 (save-buffer))))
4668 (defun org-clocktable-try-shift (dir n)
4669 "Check if this line starts a clock table, if yes, shift the time block."
4670 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4671 (org-clocktable-shift dir n)))
4673 ;;;###autoload
4674 (defun org-clock-persistence-insinuate ()
4675 "Set up hooks for clock persistence."
4676 (require 'org-clock)
4677 (add-hook 'org-mode-hook 'org-clock-load)
4678 (add-hook 'kill-emacs-hook 'org-clock-save))
4680 (defgroup org-archive nil
4681 "Options concerning archiving in Org-mode."
4682 :tag "Org Archive"
4683 :group 'org-structure)
4685 (defcustom org-archive-location "%s_archive::"
4686 "The location where subtrees should be archived.
4688 The value of this variable is a string, consisting of two parts,
4689 separated by a double-colon. The first part is a filename and
4690 the second part is a headline.
4692 When the filename is omitted, archiving happens in the same file.
4693 %s in the filename will be replaced by the current file
4694 name (without the directory part). Archiving to a different file
4695 is useful to keep archived entries from contributing to the
4696 Org-mode Agenda.
4698 The archived entries will be filed as subtrees of the specified
4699 headline. When the headline is omitted, the subtrees are simply
4700 filed away at the end of the file, as top-level entries. Also in
4701 the heading you can use %s to represent the file name, this can be
4702 useful when using the same archive for a number of different files.
4704 Here are a few examples:
4705 \"%s_archive::\"
4706 If the current file is Projects.org, archive in file
4707 Projects.org_archive, as top-level trees. This is the default.
4709 \"::* Archived Tasks\"
4710 Archive in the current file, under the top-level headline
4711 \"* Archived Tasks\".
4713 \"~/org/archive.org::\"
4714 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4716 \"~/org/archive.org::* From %s\"
4717 Archive in file ~/org/archive.org (absolute path), under headlines
4718 \"From FILENAME\" where file name is the current file name.
4720 \"~/org/datetree.org::datetree/* Finished Tasks\"
4721 The \"datetree/\" string is special, signifying to archive
4722 items to the datetree. Items are placed in either the CLOSED
4723 date of the item, or the current date if there is no CLOSED date.
4724 The heading will be a subentry to the current date. There doesn't
4725 need to be a heading, but there always needs to be a slash after
4726 datetree. For example, to store archived items directly in the
4727 datetree, use \"~/org/datetree.org::datetree/\".
4729 \"basement::** Finished Tasks\"
4730 Archive in file ./basement (relative path), as level 3 trees
4731 below the level 2 heading \"** Finished Tasks\".
4733 You may set this option on a per-file basis by adding to the buffer a
4734 line like
4736 #+ARCHIVE: basement::** Finished Tasks
4738 You may also define it locally for a subtree by setting an ARCHIVE property
4739 in the entry. If such a property is found in an entry, or anywhere up
4740 the hierarchy, it will be used."
4741 :group 'org-archive
4742 :type 'string)
4744 (defcustom org-agenda-skip-archived-trees t
4745 "Non-nil means the agenda will skip any items located in archived trees.
4746 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4747 variable is no longer recommended, you should leave it at the value t.
4748 Instead, use the key `v' to cycle the archives-mode in the agenda."
4749 :group 'org-archive
4750 :group 'org-agenda-skip
4751 :type 'boolean)
4753 (defcustom org-columns-skip-archived-trees t
4754 "Non-nil means ignore archived trees when creating column view."
4755 :group 'org-archive
4756 :group 'org-properties
4757 :type 'boolean)
4759 (defcustom org-cycle-open-archived-trees nil
4760 "Non-nil means `org-cycle' will open archived trees.
4761 An archived tree is a tree marked with the tag ARCHIVE.
4762 When nil, archived trees will stay folded. You can still open them with
4763 normal outline commands like `show-all', but not with the cycling commands."
4764 :group 'org-archive
4765 :group 'org-cycle
4766 :type 'boolean)
4768 (defcustom org-sparse-tree-open-archived-trees nil
4769 "Non-nil means sparse tree construction shows matches in archived trees.
4770 When nil, matches in these trees are highlighted, but the trees are kept in
4771 collapsed state."
4772 :group 'org-archive
4773 :group 'org-sparse-trees
4774 :type 'boolean)
4776 (defcustom org-sparse-tree-default-date-type nil
4777 "The default date type when building a sparse tree.
4778 When this is nil, a date is a scheduled or a deadline timestamp.
4779 Otherwise, these types are allowed:
4781 all: all timestamps
4782 active: only active timestamps (<...>)
4783 inactive: only inactive timestamps ([...])
4784 scheduled: only scheduled timestamps
4785 deadline: only deadline timestamps"
4786 :type '(choice (const :tag "Scheduled or deadline" nil)
4787 (const :tag "All timestamps" all)
4788 (const :tag "Only active timestamps" active)
4789 (const :tag "Only inactive timestamps" inactive)
4790 (const :tag "Only scheduled timestamps" scheduled)
4791 (const :tag "Only deadline timestamps" deadline)
4792 (const :tag "Only closed timestamps" closed))
4793 :version "25.1"
4794 :package-version '(Org . "8.3")
4795 :group 'org-sparse-trees)
4797 (defun org-cycle-hide-archived-subtrees (state)
4798 "Re-hide all archived subtrees after a visibility state change."
4799 (when (and (not org-cycle-open-archived-trees)
4800 (not (memq state '(overview folded))))
4801 (save-excursion
4802 (let* ((globalp (memq state '(contents all)))
4803 (beg (if globalp (point-min) (point)))
4804 (end (if globalp (point-max) (org-end-of-subtree t))))
4805 (org-hide-archived-subtrees beg end)
4806 (goto-char beg)
4807 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4808 (message "%s" (substitute-command-keys
4809 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4811 (defun org-force-cycle-archived ()
4812 "Cycle subtree even if it is archived."
4813 (interactive)
4814 (setq this-command 'org-cycle)
4815 (let ((org-cycle-open-archived-trees t))
4816 (call-interactively 'org-cycle)))
4818 (defun org-hide-archived-subtrees (beg end)
4819 "Re-hide all archived subtrees after a visibility state change."
4820 (org-with-wide-buffer
4821 (let ((case-fold-search nil)
4822 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4823 (goto-char beg)
4824 ;; Include headline point is currently on.
4825 (beginning-of-line)
4826 (while (and (< (point) end) (re-search-forward re end t))
4827 (when (member org-archive-tag (org-get-tags))
4828 (org-flag-subtree t)
4829 (org-end-of-subtree t))))))
4831 (declare-function outline-end-of-heading "outline" ())
4832 (declare-function outline-flag-region "outline" (from to flag))
4833 (defun org-flag-subtree (flag)
4834 (save-excursion
4835 (org-back-to-heading t)
4836 (outline-end-of-heading)
4837 (outline-flag-region (point)
4838 (progn (org-end-of-subtree t) (point))
4839 flag)))
4841 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4843 ;; Declare Column View Code
4845 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4846 (declare-function org-columns-compute "org-colview" (property))
4848 ;; Declare ID code
4850 (declare-function org-id-store-link "org-id")
4851 (declare-function org-id-locations-load "org-id")
4852 (declare-function org-id-locations-save "org-id")
4853 (defvar org-id-track-globally)
4855 ;;; Variables for pre-computed regular expressions, all buffer local
4857 (defvar-local org-todo-regexp nil
4858 "Matches any of the TODO state keywords.")
4859 (defvar-local org-not-done-regexp nil
4860 "Matches any of the TODO state keywords except the last one.")
4861 (defvar-local org-not-done-heading-regexp nil
4862 "Matches a TODO headline that is not done.")
4863 (defvar-local org-todo-line-regexp nil
4864 "Matches a headline and puts TODO state into group 2 if present.")
4865 (defvar-local org-complex-heading-regexp nil
4866 "Matches a headline and puts everything into groups:
4867 group 1: the stars
4868 group 2: The todo keyword, maybe
4869 group 3: Priority cookie
4870 group 4: True headline
4871 group 5: Tags")
4872 (defvar-local org-complex-heading-regexp-format nil
4873 "Printf format to make regexp to match an exact headline.
4874 This regexp will match the headline of any node which has the
4875 exact headline text that is put into the format, but may have any
4876 TODO state, priority and tags.")
4877 (defvar-local org-todo-line-tags-regexp nil
4878 "Matches a headline and puts TODO state into group 2 if present.
4879 Also put tags into group 4 if tags are present.")
4881 (defconst org-plain-time-of-day-regexp
4882 (concat
4883 "\\(\\<[012]?[0-9]"
4884 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4885 "\\(--?"
4886 "\\(\\<[012]?[0-9]"
4887 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4888 "\\)?")
4889 "Regular expression to match a plain time or time range.
4890 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4891 groups carry important information:
4892 0 the full match
4893 1 the first time, range or not
4894 8 the second time, if it is a range.")
4896 (defconst org-plain-time-extension-regexp
4897 (concat
4898 "\\(\\<[012]?[0-9]"
4899 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4900 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4901 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4902 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4903 groups carry important information:
4904 0 the full match
4905 7 hours of duration
4906 9 minutes of duration")
4908 (defconst org-stamp-time-of-day-regexp
4909 (concat
4910 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4911 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4912 "\\(--?"
4913 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4914 "Regular expression to match a timestamp time or time range.
4915 After a match, the following groups carry important information:
4916 0 the full match
4917 1 date plus weekday, for back referencing to make sure both times are on the same day
4918 2 the first time, range or not
4919 4 the second time, if it is a range.")
4921 (defconst org-startup-options
4922 '(("fold" org-startup-folded t)
4923 ("overview" org-startup-folded t)
4924 ("nofold" org-startup-folded nil)
4925 ("showall" org-startup-folded nil)
4926 ("showeverything" org-startup-folded showeverything)
4927 ("content" org-startup-folded content)
4928 ("indent" org-startup-indented t)
4929 ("noindent" org-startup-indented nil)
4930 ("hidestars" org-hide-leading-stars t)
4931 ("showstars" org-hide-leading-stars nil)
4932 ("odd" org-odd-levels-only t)
4933 ("oddeven" org-odd-levels-only nil)
4934 ("align" org-startup-align-all-tables t)
4935 ("noalign" org-startup-align-all-tables nil)
4936 ("inlineimages" org-startup-with-inline-images t)
4937 ("noinlineimages" org-startup-with-inline-images nil)
4938 ("latexpreview" org-startup-with-latex-preview t)
4939 ("nolatexpreview" org-startup-with-latex-preview nil)
4940 ("customtime" org-display-custom-times t)
4941 ("logdone" org-log-done time)
4942 ("lognotedone" org-log-done note)
4943 ("nologdone" org-log-done nil)
4944 ("lognoteclock-out" org-log-note-clock-out t)
4945 ("nolognoteclock-out" org-log-note-clock-out nil)
4946 ("logrepeat" org-log-repeat state)
4947 ("lognoterepeat" org-log-repeat note)
4948 ("logdrawer" org-log-into-drawer t)
4949 ("nologdrawer" org-log-into-drawer nil)
4950 ("logstatesreversed" org-log-states-order-reversed t)
4951 ("nologstatesreversed" org-log-states-order-reversed nil)
4952 ("nologrepeat" org-log-repeat nil)
4953 ("logreschedule" org-log-reschedule time)
4954 ("lognotereschedule" org-log-reschedule note)
4955 ("nologreschedule" org-log-reschedule nil)
4956 ("logredeadline" org-log-redeadline time)
4957 ("lognoteredeadline" org-log-redeadline note)
4958 ("nologredeadline" org-log-redeadline nil)
4959 ("logrefile" org-log-refile time)
4960 ("lognoterefile" org-log-refile note)
4961 ("nologrefile" org-log-refile nil)
4962 ("fninline" org-footnote-define-inline t)
4963 ("nofninline" org-footnote-define-inline nil)
4964 ("fnlocal" org-footnote-section nil)
4965 ("fnauto" org-footnote-auto-label t)
4966 ("fnprompt" org-footnote-auto-label nil)
4967 ("fnconfirm" org-footnote-auto-label confirm)
4968 ("fnplain" org-footnote-auto-label plain)
4969 ("fnadjust" org-footnote-auto-adjust t)
4970 ("nofnadjust" org-footnote-auto-adjust nil)
4971 ("constcgs" constants-unit-system cgs)
4972 ("constSI" constants-unit-system SI)
4973 ("noptag" org-tag-persistent-alist nil)
4974 ("hideblocks" org-hide-block-startup t)
4975 ("nohideblocks" org-hide-block-startup nil)
4976 ("beamer" org-startup-with-beamer-mode t)
4977 ("entitiespretty" org-pretty-entities t)
4978 ("entitiesplain" org-pretty-entities nil))
4979 "Variable associated with STARTUP options for org-mode.
4980 Each element is a list of three items: the startup options (as written
4981 in the #+STARTUP line), the corresponding variable, and the value to set
4982 this variable to if the option is found. An optional forth element PUSH
4983 means to push this value onto the list in the variable.")
4985 (defcustom org-group-tags t
4986 "When non-nil (the default), use group tags.
4987 This can be turned on/off through `org-toggle-tags-groups'."
4988 :group 'org-tags
4989 :group 'org-startup
4990 :type 'boolean)
4992 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4994 (defun org-toggle-tags-groups ()
4995 "Toggle support for group tags.
4996 Support for group tags is controlled by the option
4997 `org-group-tags', which is non-nil by default."
4998 (interactive)
4999 (setq org-group-tags (not org-group-tags))
5000 (cond ((and (derived-mode-p 'org-agenda-mode)
5001 org-group-tags)
5002 (org-agenda-redo))
5003 ((derived-mode-p 'org-mode)
5004 (let ((org-inhibit-startup t)) (org-mode))))
5005 (message "Groups tags support has been turned %s"
5006 (if org-group-tags "on" "off")))
5008 (defun org-set-regexps-and-options (&optional tags-only)
5009 "Precompute regular expressions used in the current buffer.
5010 When optional argument TAGS-ONLY is non-nil, only compute tags
5011 related expressions."
5012 (when (derived-mode-p 'org-mode)
5013 (let ((alist (org--setup-collect-keywords
5014 (org-make-options-regexp
5015 (append '("FILETAGS" "TAGS" "SETUPFILE")
5016 (and (not tags-only)
5017 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
5018 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
5019 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
5020 ;; Startup options. Get this early since it does change
5021 ;; behavior for other options (e.g., tags).
5022 (let ((startup (cdr (assq 'startup alist))))
5023 (dolist (option startup)
5024 (let ((entry (assoc-string option org-startup-options t)))
5025 (when entry
5026 (let ((var (nth 1 entry))
5027 (val (nth 2 entry)))
5028 (if (not (nth 3 entry)) (set (make-local-variable var) val)
5029 (unless (listp (symbol-value var))
5030 (set (make-local-variable var) nil))
5031 (add-to-list var val)))))))
5032 (setq-local org-file-tags
5033 (mapcar #'org-add-prop-inherited
5034 (cdr (assq 'filetags alist))))
5035 (setq org-current-tag-alist
5036 (append org-tag-persistent-alist
5037 (let ((tags (cdr (assq 'tags alist))))
5038 (if tags (org-tag-string-to-alist tags)
5039 org-tag-alist))))
5040 (setq org-tag-groups-alist
5041 (org-tag-alist-to-groups org-current-tag-alist))
5042 (unless tags-only
5043 ;; File properties.
5044 (setq-local org-file-properties (cdr (assq 'property alist)))
5045 ;; Archive location.
5046 (let ((archive (cdr (assq 'archive alist))))
5047 (when archive (setq-local org-archive-location archive)))
5048 ;; Category.
5049 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
5050 (when cat
5051 (setq-local org-category (intern cat))
5052 (setq-local org-file-properties
5053 (org--update-property-plist
5054 "CATEGORY" cat org-file-properties))))
5055 ;; Columns.
5056 (let ((column (cdr (assq 'columns alist))))
5057 (when column (setq-local org-columns-default-format column)))
5058 ;; Constants.
5059 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
5060 ;; Link abbreviations.
5061 (let ((links (cdr (assq 'link alist))))
5062 (when links (setq org-link-abbrev-alist-local (nreverse links))))
5063 ;; Priorities.
5064 (let ((priorities (cdr (assq 'priorities alist))))
5065 (when priorities
5066 (setq-local org-highest-priority (nth 0 priorities))
5067 (setq-local org-lowest-priority (nth 1 priorities))
5068 (setq-local org-default-priority (nth 2 priorities))))
5069 ;; Scripts.
5070 (let ((scripts (assq 'scripts alist)))
5071 (when scripts
5072 (setq-local org-use-sub-superscripts (cdr scripts))))
5073 ;; TODO keywords.
5074 (setq-local org-todo-kwd-alist nil)
5075 (setq-local org-todo-key-alist nil)
5076 (setq-local org-todo-key-trigger nil)
5077 (setq-local org-todo-keywords-1 nil)
5078 (setq-local org-done-keywords nil)
5079 (setq-local org-todo-heads nil)
5080 (setq-local org-todo-sets nil)
5081 (setq-local org-todo-log-states nil)
5082 (let ((todo-sequences
5083 (or (nreverse (cdr (assq 'todo alist)))
5084 (let ((d (default-value 'org-todo-keywords)))
5085 (if (not (stringp (car d))) d
5086 ;; XXX: Backward compatibility code.
5087 (list (cons org-todo-interpretation d)))))))
5088 (dolist (sequence todo-sequences)
5089 (let* ((sequence (or (run-hook-with-args-until-success
5090 'org-todo-setup-filter-hook sequence)
5091 sequence))
5092 (sequence-type (car sequence))
5093 (keywords (cdr sequence))
5094 (sep (member "|" keywords))
5095 names alist)
5096 (dolist (k (remove "|" keywords))
5097 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5099 (error "Invalid TODO keyword %s" k))
5100 (let ((name (match-string 1 k))
5101 (key (match-string 2 k))
5102 (log (org-extract-log-state-settings k)))
5103 (push name names)
5104 (push (cons name (and key (string-to-char key))) alist)
5105 (when log (push log org-todo-log-states))))
5106 (let* ((names (nreverse names))
5107 (done (if sep (org-remove-keyword-keys (cdr sep))
5108 (last names)))
5109 (head (car names))
5110 (tail (list sequence-type head (car done) (org-last done))))
5111 (add-to-list 'org-todo-heads head 'append)
5112 (push names org-todo-sets)
5113 (setq org-done-keywords (append org-done-keywords done nil))
5114 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5115 (setq org-todo-key-alist
5116 (append org-todo-key-alist
5117 (and alist
5118 (append '((:startgroup))
5119 (nreverse alist)
5120 '((:endgroup))))))
5121 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5122 (setq org-todo-sets (nreverse org-todo-sets)
5123 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5124 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5125 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5126 ;; Compute the regular expressions and other local variables.
5127 ;; Using `org-outline-regexp-bol' would complicate them much,
5128 ;; because of the fixed white space at the end of that string.
5129 (unless org-done-keywords
5130 (setq org-done-keywords
5131 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5132 (setq org-not-done-keywords
5133 (org-delete-all org-done-keywords
5134 (copy-sequence org-todo-keywords-1))
5135 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5136 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5137 org-not-done-heading-regexp
5138 (format org-heading-keyword-regexp-format org-not-done-regexp)
5139 org-todo-line-regexp
5140 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5141 org-complex-heading-regexp
5142 (concat "^\\(\\*+\\)"
5143 "\\(?: +" org-todo-regexp "\\)?"
5144 "\\(?: +\\(\\[#.\\]\\)\\)?"
5145 "\\(?: +\\(.*?\\)\\)??"
5146 "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?"
5147 "[ \t]*$")
5148 org-complex-heading-regexp-format
5149 (concat "^\\(\\*+\\)"
5150 "\\(?: +" org-todo-regexp "\\)?"
5151 "\\(?: +\\(\\[#.\\]\\)\\)?"
5152 "\\(?: +"
5153 ;; Stats cookies can be stuck to body.
5154 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5155 "\\(%s\\)"
5156 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5157 "\\)"
5158 "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?"
5159 "[ \t]*$")
5160 org-todo-line-tags-regexp
5161 (concat "^\\(\\*+\\)"
5162 "\\(?: +" org-todo-regexp "\\)?"
5163 "\\(?: +\\(.*?\\)\\)??"
5164 "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?"
5165 "[ \t]*$"))
5166 (org-compute-latex-and-related-regexp)))))
5168 (defun org--setup-collect-keywords (regexp &optional files alist)
5169 "Return setup keywords values as an alist.
5171 REGEXP matches a subset of setup keywords. FILES is a list of
5172 file names already visited. It is used to avoid circular setup
5173 files. ALIST, when non-nil, is the alist computed so far.
5175 Return value contains the following keys: `archive', `category',
5176 `columns', `constants', `filetags', `link', `priorities',
5177 `property', `scripts', `startup', `tags' and `todo'."
5178 (org-with-wide-buffer
5179 (goto-char (point-min))
5180 (let ((case-fold-search t))
5181 (while (re-search-forward regexp nil t)
5182 (let ((element (org-element-at-point)))
5183 (when (eq (org-element-type element) 'keyword)
5184 (let ((key (org-element-property :key element))
5185 (value (org-element-property :value element)))
5186 (cond
5187 ((equal key "ARCHIVE")
5188 (when (org-string-nw-p value)
5189 (push (cons 'archive value) alist)))
5190 ((equal key "CATEGORY") (push (cons 'category value) alist))
5191 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5192 ((equal key "CONSTANTS")
5193 (let* ((constants (assq 'constants alist))
5194 (store (cdr constants)))
5195 (dolist (pair (org-split-string value))
5196 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5197 pair)
5198 (let* ((name (match-string 1 pair))
5199 (value (match-string 2 pair))
5200 (old (assoc name store)))
5201 (if old (setcdr old value)
5202 (push (cons name value) store)))))
5203 (if constants (setcdr constants store)
5204 (push (cons 'constants store) alist))))
5205 ((equal key "FILETAGS")
5206 (when (org-string-nw-p value)
5207 (let ((old (assq 'filetags alist))
5208 (new (apply #'nconc
5209 (mapcar (lambda (x) (org-split-string x ":"))
5210 (org-split-string value)))))
5211 (if old (setcdr old (append new (cdr old)))
5212 (push (cons 'filetags new) alist)))))
5213 ((equal key "LINK")
5214 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5215 (let ((links (assq 'link alist))
5216 (pair (cons (match-string-no-properties 1 value)
5217 (match-string-no-properties 2 value))))
5218 (if links (push pair (cdr links))
5219 (push (list 'link pair) alist)))))
5220 ((equal key "OPTIONS")
5221 (when (and (org-string-nw-p value)
5222 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5223 (push (cons 'scripts (read (match-string 1 value))) alist)))
5224 ((equal key "PRIORITIES")
5225 (push (cons 'priorities
5226 (let ((prio (org-split-string value)))
5227 (if (< (length prio) 3) '(?A ?C ?B)
5228 (mapcar #'string-to-char prio))))
5229 alist))
5230 ((equal key "PROPERTY")
5231 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5232 (let* ((property (assq 'property alist))
5233 (value (org--update-property-plist
5234 (match-string-no-properties 1 value)
5235 (match-string-no-properties 2 value)
5236 (cdr property))))
5237 (if property (setcdr property value)
5238 (push (cons 'property value) alist)))))
5239 ((equal key "STARTUP")
5240 (let ((startup (assq 'startup alist)))
5241 (if startup
5242 (setcdr startup
5243 (append (cdr startup) (org-split-string value)))
5244 (push (cons 'startup (org-split-string value)) alist))))
5245 ((equal key "TAGS")
5246 (let ((tag-cell (assq 'tags alist)))
5247 (if tag-cell
5248 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5249 (push (cons 'tags value) alist))))
5250 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5251 (let ((todo (assq 'todo alist))
5252 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5253 (org-split-string value))))
5254 (if todo (push value (cdr todo))
5255 (push (list 'todo value) alist))))
5256 ((equal key "SETUPFILE")
5257 (unless buffer-read-only ; Do not check in Gnus messages.
5258 (let ((f (and (org-string-nw-p value)
5259 (expand-file-name
5260 (org-remove-double-quotes value)))))
5261 (when (and f (file-readable-p f) (not (member f files)))
5262 (with-temp-buffer
5263 (setq default-directory (file-name-directory f))
5264 (insert-file-contents f)
5265 (setq alist
5266 ;; Fake Org mode to benefit from cache
5267 ;; without recurring needlessly.
5268 (let ((major-mode 'org-mode))
5269 (org--setup-collect-keywords
5270 regexp (cons f files) alist)))))))))))))))
5271 alist)
5273 (defun org-tag-string-to-alist (s)
5274 "Return tag alist associated to string S.
5275 S is a value for TAGS keyword or produced with
5276 `org-tag-alist-to-string'. Return value is an alist suitable for
5277 `org-tag-alist' or `org-tag-persistent-alist'."
5278 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5279 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5280 "\\|{.+?}\\)" ; regular expression
5281 "\\(?:(\\(.\\))\\)?\\'"))
5282 alist group-flag)
5283 (dolist (tokens lines (cdr (nreverse alist)))
5284 (push '(:newline) alist)
5285 (while tokens
5286 (let ((token (pop tokens)))
5287 (pcase token
5288 ("{"
5289 (push '(:startgroup) alist)
5290 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5291 ("}"
5292 (push '(:endgroup) alist)
5293 (setq group-flag nil))
5294 ("["
5295 (push '(:startgrouptag) alist)
5296 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5297 ("]"
5298 (push '(:endgrouptag) alist)
5299 (setq group-flag nil))
5300 (":"
5301 (push '(:grouptags) alist))
5302 ((guard (string-match tag-re token))
5303 (let ((tag (match-string 1 token))
5304 (key (and (match-beginning 2)
5305 (string-to-char (match-string 2 token)))))
5306 ;; Push all tags in groups, no matter if they already
5307 ;; appear somewhere else in the list.
5308 (when (or group-flag (not (assoc tag alist)))
5309 (push (cons tag key) alist))))))))))
5311 (defun org-tag-alist-to-string (alist &optional skip-key)
5312 "Return tag string associated to ALIST.
5314 ALIST is an alist, as defined in `org-tag-alist' or
5315 `org-tag-persistent-alist', or produced with
5316 `org-tag-string-to-alist'.
5318 Return value is a string suitable as a value for \"TAGS\"
5319 keyword.
5321 When optional argument SKIP-KEY is non-nil, skip selection keys
5322 next to tags."
5323 (mapconcat (lambda (token)
5324 (pcase token
5325 (`(:startgroup) "{")
5326 (`(:endgroup) "}")
5327 (`(:startgrouptag) "[")
5328 (`(:endgrouptag) "]")
5329 (`(:grouptags) ":")
5330 (`(:newline) "\\n")
5331 ((and
5332 (guard (not skip-key))
5333 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5334 (format "%s(%c)" tag key))
5335 (`(,(and tag (pred stringp)) . ,_) tag)
5336 (_ (user-error "Invalid tag token: %S" token))))
5337 alist
5338 " "))
5340 (defun org-tag-alist-to-groups (alist)
5341 "Return group alist from tag ALIST.
5342 ALIST is an alist, as defined in `org-tag-alist' or
5343 `org-tag-persistent-alist', or produced with
5344 `org-tag-string-to-alist'. Return value is an alist following
5345 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5346 a string, summarizing TAGS, as a list of strings."
5347 (let (groups group-status current-group)
5348 (dolist (token alist (nreverse groups))
5349 (pcase token
5350 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5351 (`(,(or :endgroup :endgrouptag))
5352 (when (eq group-status 'append)
5353 (push (nreverse current-group) groups))
5354 (setq group-status nil))
5355 (`(:grouptags) (setq group-status 'append))
5356 ((and `(,tag . ,_) (guard group-status))
5357 (if (eq group-status 'append) (push tag current-group)
5358 (setq current-group (list tag))))
5359 (_ nil)))))
5361 (defun org-file-contents (file &optional noerror)
5362 "Return the contents of FILE, as a string."
5363 (if (and file (file-readable-p file))
5364 (with-temp-buffer
5365 (insert-file-contents file)
5366 (buffer-string))
5367 (funcall (if noerror 'message 'error)
5368 "Cannot read file \"%s\"%s"
5369 file
5370 (let ((from (buffer-file-name (buffer-base-buffer))))
5371 (if from (concat " (referenced in file \"" from "\")") "")))))
5373 (defun org-extract-log-state-settings (x)
5374 "Extract the log state setting from a TODO keyword string.
5375 This will extract info from a string like \"WAIT(w@/!)\"."
5376 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5377 (let ((kw (match-string 1 x))
5378 (log1 (and (match-end 3) (match-string 3 x)))
5379 (log2 (and (match-end 4) (match-string 4 x))))
5380 (and (or log1 log2)
5381 (list kw
5382 (and log1 (if (equal log1 "!") 'time 'note))
5383 (and log2 (if (equal log2 "!") 'time 'note)))))))
5385 (defun org-remove-keyword-keys (list)
5386 "Remove a pair of parenthesis at the end of each string in LIST."
5387 (mapcar (lambda (x)
5388 (if (string-match "(.*)$" x)
5389 (substring x 0 (match-beginning 0))
5391 list))
5393 (defun org-assign-fast-keys (alist)
5394 "Assign fast keys to a keyword-key alist.
5395 Respect keys that are already there."
5396 (let (new e (alt ?0))
5397 (while (setq e (pop alist))
5398 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5399 (cdr e)) ;; Key already assigned.
5400 (push e new)
5401 (let ((clist (string-to-list (downcase (car e))))
5402 (used (append new alist)))
5403 (when (= (car clist) ?@)
5404 (pop clist))
5405 (while (and clist (rassoc (car clist) used))
5406 (pop clist))
5407 (unless clist
5408 (while (rassoc alt used)
5409 (cl-incf alt)))
5410 (push (cons (car e) (or (car clist) alt)) new))))
5411 (nreverse new)))
5413 ;;; Some variables used in various places
5415 (defvar org-window-configuration nil
5416 "Used in various places to store a window configuration.")
5417 (defvar org-selected-window nil
5418 "Used in various places to store a window configuration.")
5419 (defvar org-finish-function nil
5420 "Function to be called when `C-c C-c' is used.
5421 This is for getting out of special buffers like capture.")
5422 (defvar org-last-state)
5424 ;; Defined somewhere in this file, but used before definition.
5425 (defvar org-entities) ;; defined in org-entities.el
5426 (defvar org-struct-menu)
5427 (defvar org-org-menu)
5428 (defvar org-tbl-menu)
5430 ;;;; Define the Org-mode
5432 ;; We use a before-change function to check if a table might need
5433 ;; an update.
5434 (defvar org-table-may-need-update t
5435 "Indicates that a table might need an update.
5436 This variable is set by `org-before-change-function'.
5437 `org-table-align' sets it back to nil.")
5438 (defun org-before-change-function (_beg _end)
5439 "Every change indicates that a table might need an update."
5440 (setq org-table-may-need-update t))
5441 (defvar org-mode-map)
5442 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5443 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5444 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5445 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5446 (defvar org-table-buffer-is-an nil)
5448 (defvar bidi-paragraph-direction)
5449 (defvar buffer-face-mode-face)
5451 (require 'outline)
5452 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5453 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5455 ;; Other stuff we need.
5456 (require 'time-date)
5457 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5458 (require 'easymenu)
5459 (autoload 'easy-menu-add "easymenu")
5460 (require 'overlay)
5462 ;; (require 'org-macs) moved higher up in the file before it is first used
5463 (require 'org-entities)
5464 ;; (require 'org-compat) moved higher up in the file before it is first used
5465 (require 'org-faces)
5466 (require 'org-list)
5467 (require 'org-pcomplete)
5468 (require 'org-src)
5469 (require 'org-footnote)
5470 (require 'org-macro)
5472 ;; babel
5473 (require 'ob)
5475 ;;;###autoload
5476 (define-derived-mode org-mode outline-mode "Org"
5477 "Outline-based notes management and organizer, alias
5478 \"Carsten's outline-mode for keeping track of everything.\"
5480 Org-mode develops organizational tasks around a NOTES file which
5481 contains information about projects as plain text. Org-mode is
5482 implemented on top of outline-mode, which is ideal to keep the content
5483 of large files well structured. It supports ToDo items, deadlines and
5484 time stamps, which magically appear in the diary listing of the Emacs
5485 calendar. Tables are easily created with a built-in table editor.
5486 Plain text URL-like links connect to websites, emails (VM), Usenet
5487 messages (Gnus), BBDB entries, and any files related to the project.
5488 For printing and sharing of notes, an Org-mode file (or a part of it)
5489 can be exported as a structured ASCII or HTML file.
5491 The following commands are available:
5493 \\{org-mode-map}"
5495 ;; Get rid of Outline menus, they are not needed
5496 ;; Need to do this here because define-derived-mode sets up
5497 ;; the keymap so late. Still, it is a waste to call this each time
5498 ;; we switch another buffer into Org mode.
5499 (define-key org-mode-map [menu-bar headings] 'undefined)
5500 (define-key org-mode-map [menu-bar hide] 'undefined)
5501 (define-key org-mode-map [menu-bar show] 'undefined)
5503 (org-load-modules-maybe)
5504 (org-install-agenda-files-menu)
5505 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5506 (add-to-invisibility-spec '(org-cwidth))
5507 (add-to-invisibility-spec '(org-hide-block . t))
5508 (setq-local outline-regexp org-outline-regexp)
5509 (setq-local outline-level 'org-outline-level)
5510 (setq bidi-paragraph-direction 'left-to-right)
5511 (when (and org-ellipsis
5512 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5513 (fboundp 'make-glyph-code))
5514 (unless org-display-table
5515 (setq org-display-table (make-display-table)))
5516 (set-display-table-slot
5517 org-display-table 4
5518 (vconcat (mapcar
5519 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5520 org-ellipsis)))
5521 (if (stringp org-ellipsis) org-ellipsis "..."))))
5522 (setq buffer-display-table org-display-table))
5523 (org-set-regexps-and-options)
5524 (org-set-font-lock-defaults)
5525 (when (and org-tag-faces (not org-tags-special-faces-re))
5526 ;; tag faces set outside customize.... force initialization.
5527 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5528 ;; Calc embedded
5529 (setq-local calc-embedded-open-mode "# ")
5530 ;; Modify a few syntax entries
5531 (modify-syntax-entry ?@ "w")
5532 (modify-syntax-entry ?\" "\"")
5533 (modify-syntax-entry ?\\ "_")
5534 (modify-syntax-entry ?~ "_")
5535 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5536 ;; Activate before-change-function
5537 (setq-local org-table-may-need-update t)
5538 (add-hook 'before-change-functions 'org-before-change-function nil 'local)
5539 ;; Check for running clock before killing a buffer
5540 (add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5541 ;; Initialize macros templates.
5542 (org-macro-initialize-templates)
5543 ;; Initialize radio targets.
5544 (org-update-radio-target-regexp)
5545 ;; Indentation.
5546 (setq-local indent-line-function 'org-indent-line)
5547 (setq-local indent-region-function 'org-indent-region)
5548 ;; Filling and auto-filling.
5549 (org-setup-filling)
5550 ;; Comments.
5551 (org-setup-comments-handling)
5552 ;; Initialize cache.
5553 (org-element-cache-reset)
5554 ;; Beginning/end of defun
5555 (setq-local beginning-of-defun-function 'org-backward-element)
5556 (setq-local end-of-defun-function
5557 (lambda ()
5558 (if (not (org-at-heading-p))
5559 (org-forward-element)
5560 (org-forward-element)
5561 (forward-char -1))))
5562 ;; Next error for sparse trees
5563 (setq-local next-error-function 'org-occur-next-match)
5564 ;; Make sure dependence stuff works reliably, even for users who set it
5565 ;; too late :-(
5566 (if org-enforce-todo-dependencies
5567 (add-hook 'org-blocker-hook
5568 'org-block-todo-from-children-or-siblings-or-parent)
5569 (remove-hook 'org-blocker-hook
5570 'org-block-todo-from-children-or-siblings-or-parent))
5571 (if org-enforce-todo-checkbox-dependencies
5572 (add-hook 'org-blocker-hook
5573 'org-block-todo-from-checkboxes)
5574 (remove-hook 'org-blocker-hook
5575 'org-block-todo-from-checkboxes))
5577 ;; Align options lines
5578 (setq-local
5579 align-mode-rules-list
5580 '((org-in-buffer-settings
5581 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5582 (modes . '(org-mode)))))
5584 ;; Imenu
5585 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5587 ;; Make isearch reveal context
5588 (setq-local outline-isearch-open-invisible-function
5589 (lambda (&rest _) (org-show-context 'isearch)))
5591 ;; Setup the pcomplete hooks
5592 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5593 (setq-local pcomplete-command-name-function 'org-command-at-point)
5594 (setq-local pcomplete-default-completion-function 'ignore)
5595 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5596 (setq-local pcomplete-termination-string "")
5597 (setq-local buffer-face-mode-face 'org-default)
5599 ;; If empty file that did not turn on Org mode automatically, make
5600 ;; it to.
5601 (when (and org-insert-mode-line-in-empty-file
5602 (org-called-interactively-p 'any)
5603 (= (point-min) (point-max)))
5604 (insert "# -*- mode: org -*-\n\n"))
5605 (unless org-inhibit-startup
5606 (org-unmodified
5607 (when org-startup-with-beamer-mode (org-beamer-mode))
5608 (when org-startup-align-all-tables
5609 (org-table-map-tables #'org-table-align t))
5610 (when org-startup-with-inline-images (org-display-inline-images))
5611 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5612 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5613 (when org-startup-truncated (setq truncate-lines t))
5614 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5615 (org-refresh-effort-properties)))
5616 ;; Try to set `org-hide' face correctly.
5617 (let ((foreground (org-find-invisible-foreground)))
5618 (when foreground
5619 (set-face-foreground 'org-hide foreground))))
5621 ;; Update `customize-package-emacs-version-alist'
5622 (add-to-list 'customize-package-emacs-version-alist
5623 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5624 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5625 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5627 (defvar org-mode-transpose-word-syntax-table
5628 (let ((st (make-syntax-table text-mode-syntax-table)))
5629 (dolist (c org-emphasis-alist st)
5630 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5632 (when (fboundp 'abbrev-table-put)
5633 (abbrev-table-put org-mode-abbrev-table
5634 :parents (list text-mode-abbrev-table)))
5636 (defun org-find-invisible-foreground ()
5637 (let ((candidates (remove
5638 "unspecified-bg"
5639 (nconc
5640 (list (face-background 'default)
5641 (face-background 'org-default))
5642 (mapcar
5643 (lambda (alist)
5644 (when (boundp alist)
5645 (cdr (assoc 'background-color (symbol-value alist)))))
5646 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5647 (list (face-foreground 'org-hide))))))
5648 (car (remove nil candidates))))
5650 (defun org-current-time (&optional rounding-minutes past)
5651 "Current time, possibly rounded to ROUNDING-MINUTES.
5652 When ROUNDING-MINUTES is not an integer, fall back on the car of
5653 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5654 the rounding returns a past time."
5655 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5656 (car org-time-stamp-rounding-minutes)))
5657 (time (decode-time)) res)
5658 (if (< r 1)
5659 (current-time)
5660 (setq res
5661 (apply 'encode-time
5662 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5663 (nthcdr 2 time))))
5664 (if (and past (< (float-time (time-subtract (current-time) res)) 0))
5665 (seconds-to-time (- (float-time res) (* r 60)))
5666 res))))
5668 (defun org-today ()
5669 "Return today date, considering `org-extend-today-until'."
5670 (time-to-days
5671 (time-subtract (current-time)
5672 (list 0 (* 3600 org-extend-today-until) 0))))
5674 ;;;; Font-Lock stuff, including the activators
5676 (defvar org-mouse-map (make-sparse-keymap))
5677 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5678 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5679 (when org-mouse-1-follows-link
5680 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5681 (when org-tab-follows-link
5682 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5683 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5685 (require 'font-lock)
5687 (defconst org-non-link-chars "]\t\n\r<>")
5688 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5689 "file+sys" "news" "shell" "elisp" "doi" "message"
5690 "help"))
5691 (defvar org-link-types-re nil
5692 "Matches a link that has a url-like prefix like \"http:\"")
5693 (defvar org-link-re-with-space nil
5694 "Matches a link with spaces, optional angular brackets around it.")
5695 (defvar org-link-re-with-space2 nil
5696 "Matches a link with spaces, optional angular brackets around it.")
5697 (defvar org-link-re-with-space3 nil
5698 "Matches a link with spaces, only for internal part in bracket links.")
5699 (defvar org-angle-link-re nil
5700 "Matches link with angular brackets, spaces are allowed.")
5701 (defvar org-plain-link-re nil
5702 "Matches plain link, without spaces.")
5703 (defvar org-bracket-link-regexp nil
5704 "Matches a link in double brackets.")
5705 (defvar org-bracket-link-analytic-regexp nil
5706 "Regular expression used to analyze links.
5707 Here is what the match groups contain after a match:
5708 1: http:
5709 2: http
5710 3: path
5711 4: [desc]
5712 5: desc")
5713 (defvar org-bracket-link-analytic-regexp++ nil
5714 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5715 (defvar org-any-link-re nil
5716 "Regular expression matching any link.")
5718 (defconst org-match-sexp-depth 3
5719 "Number of stacked braces for sub/superscript matching.")
5721 (defun org-create-multibrace-regexp (left right n)
5722 "Create a regular expression which will match a balanced sexp.
5723 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5724 as single character strings.
5725 The regexp returned will match the entire expression including the
5726 delimiters. It will also define a single group which contains the
5727 match except for the outermost delimiters. The maximum depth of
5728 stacked delimiters is N. Escaping delimiters is not possible."
5729 (let* ((nothing (concat "[^" left right "]*?"))
5730 (or "\\|")
5731 (re nothing)
5732 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5733 (while (> n 1)
5734 (setq n (1- n)
5735 re (concat re or next)
5736 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5737 (concat left "\\(" re "\\)" right)))
5739 (defconst org-match-substring-regexp
5740 (concat
5741 "\\(\\S-\\)\\([_^]\\)\\("
5742 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5743 "\\|"
5744 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5745 "\\|"
5746 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5747 "The regular expression matching a sub- or superscript.")
5749 (defconst org-match-substring-with-braces-regexp
5750 (concat
5751 "\\(\\S-\\)\\([_^]\\)"
5752 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5753 "The regular expression matching a sub- or superscript, forcing braces.")
5755 (defun org-make-link-regexps ()
5756 "Update the link regular expressions.
5757 This should be called after the variable `org-link-types' has changed."
5758 (let ((types-re (regexp-opt org-link-types t)))
5759 (setq org-link-types-re
5760 (concat "\\`" types-re ":")
5761 org-link-re-with-space
5762 (concat "<?" types-re ":"
5763 "\\([^" org-non-link-chars " ]"
5764 "[^" org-non-link-chars "]*"
5765 "[^" org-non-link-chars " ]\\)>?")
5766 org-link-re-with-space2
5767 (concat "<?" types-re ":"
5768 "\\([^" org-non-link-chars " ]"
5769 "[^\t\n\r]*"
5770 "[^" org-non-link-chars " ]\\)>?")
5771 org-link-re-with-space3
5772 (concat "<?" types-re ":"
5773 "\\([^" org-non-link-chars " ]"
5774 "[^\t\n\r]*\\)")
5775 org-angle-link-re
5776 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5777 types-re)
5778 org-plain-link-re
5779 (concat
5780 "\\<" types-re ":"
5781 "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)")
5782 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5783 org-bracket-link-regexp
5784 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5785 org-bracket-link-analytic-regexp
5786 (concat
5787 "\\[\\["
5788 "\\(" types-re ":\\)?"
5789 "\\([^]]+\\)"
5790 "\\]"
5791 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5792 "\\]")
5793 org-bracket-link-analytic-regexp++
5794 (concat
5795 "\\[\\["
5796 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5797 "\\([^]]+\\)"
5798 "\\]"
5799 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5800 "\\]")
5801 org-any-link-re
5802 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5803 org-angle-link-re "\\)\\|\\("
5804 org-plain-link-re "\\)"))))
5806 (org-make-link-regexps)
5808 (defvar org-emph-face nil)
5810 (defun org-do-emphasis-faces (limit)
5811 "Run through the buffer and emphasize strings."
5812 (let (rtn a)
5813 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5814 (let* ((border (char-after (match-beginning 3)))
5815 (bre (regexp-quote (char-to-string border))))
5816 (when (and (not (= border (char-after (match-beginning 4))))
5817 (not (string-match-p (concat bre ".*" bre)
5818 (replace-regexp-in-string
5819 "\n" " "
5820 (substring (match-string 2) 1 -1)))))
5821 (setq rtn t)
5822 (setq a (assoc (match-string 3) org-emphasis-alist))
5823 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5824 'face
5825 (nth 1 a))
5826 (and (nth 2 a)
5827 (org-remove-flyspell-overlays-in
5828 (match-beginning 0) (match-end 0)))
5829 (add-text-properties (match-beginning 2) (match-end 2)
5830 '(font-lock-multiline t org-emphasis t))
5831 (when org-hide-emphasis-markers
5832 (add-text-properties (match-end 4) (match-beginning 5)
5833 '(invisible org-link))
5834 (add-text-properties (match-beginning 3) (match-end 3)
5835 '(invisible org-link)))))
5836 (goto-char (1+ (match-beginning 0))))
5837 rtn))
5839 (defun org-emphasize (&optional char)
5840 "Insert or change an emphasis, i.e. a font like bold or italic.
5841 If there is an active region, change that region to a new emphasis.
5842 If there is no region, just insert the marker characters and position
5843 the cursor between them.
5844 CHAR should be the marker character. If it is a space, it means to
5845 remove the emphasis of the selected region.
5846 If CHAR is not given (for example in an interactive call) it will be
5847 prompted for."
5848 (interactive)
5849 (let ((erc org-emphasis-regexp-components)
5850 (string "") beg end move s)
5851 (if (org-region-active-p)
5852 (setq beg (region-beginning)
5853 end (region-end)
5854 string (buffer-substring beg end))
5855 (setq move t))
5857 (unless char
5858 (message "Emphasis marker or tag: [%s]"
5859 (mapconcat #'car org-emphasis-alist ""))
5860 (setq char (read-char-exclusive)))
5861 (if (equal char ?\s)
5862 (setq s ""
5863 move nil)
5864 (unless (assoc (char-to-string char) org-emphasis-alist)
5865 (user-error "No such emphasis marker: \"%c\"" char))
5866 (setq s (char-to-string char)))
5867 (while (and (> (length string) 1)
5868 (equal (substring string 0 1) (substring string -1))
5869 (assoc (substring string 0 1) org-emphasis-alist))
5870 (setq string (substring string 1 -1)))
5871 (setq string (concat s string s))
5872 (when beg (delete-region beg end))
5873 (unless (or (bolp)
5874 (string-match (concat "[" (nth 0 erc) "\n]")
5875 (char-to-string (char-before (point)))))
5876 (insert " "))
5877 (unless (or (eobp)
5878 (string-match (concat "[" (nth 1 erc) "\n]")
5879 (char-to-string (char-after (point)))))
5880 (insert " ") (backward-char 1))
5881 (insert string)
5882 (and move (backward-char 1))))
5884 (defconst org-nonsticky-props
5885 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5887 (defsubst org-rear-nonsticky-at (pos)
5888 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5890 (defun org-activate-plain-links (limit)
5891 "Add link properties for plain links."
5892 (when (and (re-search-forward org-plain-link-re limit t)
5893 (not (org-in-src-block-p)))
5894 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5895 'face))
5896 (link (match-string-no-properties 0)))
5897 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5898 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5899 (add-text-properties (match-beginning 0) (match-end 0)
5900 (list 'mouse-face 'highlight
5901 'face 'org-link
5902 'htmlize-link `(:uri ,link)
5903 'keymap org-mouse-map))
5904 (org-rear-nonsticky-at (match-end 0))
5905 t))))
5907 (defun org-activate-code (limit)
5908 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5909 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5910 (remove-text-properties (match-beginning 0) (match-end 0)
5911 '(display t invisible t intangible t))
5914 (defcustom org-src-fontify-natively t
5915 "When non-nil, fontify code in code blocks."
5916 :type 'boolean
5917 :version "24.4"
5918 :package-version '(Org . "8.3")
5919 :group 'org-appearance
5920 :group 'org-babel)
5922 (defcustom org-allow-promoting-top-level-subtree nil
5923 "When non-nil, allow promoting a top level subtree.
5924 The leading star of the top level headline will be replaced
5925 by a #."
5926 :type 'boolean
5927 :version "24.1"
5928 :group 'org-appearance)
5930 (defun org-fontify-meta-lines-and-blocks (limit)
5931 (condition-case nil
5932 (org-fontify-meta-lines-and-blocks-1 limit)
5933 (error (message "org-mode fontification error in %S at %d"
5934 (current-buffer)
5935 (line-number-at-pos)))))
5937 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5938 "Fontify #+ lines and blocks."
5939 (let ((case-fold-search t))
5940 (when (re-search-forward
5941 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5942 limit t)
5943 (let ((beg (match-beginning 0))
5944 (block-start (match-end 0))
5945 (block-end nil)
5946 (lang (match-string 7))
5947 (beg1 (line-beginning-position 2))
5948 (dc1 (downcase (match-string 2)))
5949 (dc3 (downcase (match-string 3)))
5950 end end1 quoting block-type)
5951 (cond
5952 ((and (match-end 4) (equal dc3 "+begin"))
5953 ;; Truly a block
5954 (setq block-type (downcase (match-string 5))
5955 quoting (member block-type org-protecting-blocks))
5956 (when (re-search-forward
5957 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5958 nil t) ;; on purpose, we look further than LIMIT
5959 (setq end (min (point-max) (match-end 0))
5960 end1 (min (point-max) (1- (match-beginning 0))))
5961 (setq block-end (match-beginning 0))
5962 (when quoting
5963 (org-remove-flyspell-overlays-in beg1 end1)
5964 (remove-text-properties beg end
5965 '(display t invisible t intangible t)))
5966 (add-text-properties
5967 beg end '(font-lock-fontified t font-lock-multiline t))
5968 (add-text-properties beg beg1 '(face org-meta-line))
5969 (org-remove-flyspell-overlays-in beg beg1)
5970 (add-text-properties ; For end_src
5971 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5972 (org-remove-flyspell-overlays-in end1 end)
5973 (cond
5974 ((and lang (not (string= lang "")) org-src-fontify-natively)
5975 (org-src-font-lock-fontify-block lang block-start block-end)
5976 (add-text-properties beg1 block-end '(src-block t)))
5977 (quoting
5978 (add-text-properties beg1 (min (point-max) (1+ end1))
5979 '(face org-block))) ; end of source block
5980 ((not org-fontify-quote-and-verse-blocks))
5981 ((string= block-type "quote")
5982 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5983 ((string= block-type "verse")
5984 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5985 (add-text-properties beg beg1 '(face org-block-begin-line))
5986 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5987 '(face org-block-end-line))
5989 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5990 (org-remove-flyspell-overlays-in
5991 (match-beginning 0)
5992 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5993 (add-text-properties
5994 beg (match-end 3)
5995 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5996 '(font-lock-fontified t invisible t)
5997 '(font-lock-fontified t face org-document-info-keyword)))
5998 (add-text-properties
5999 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
6000 (if (string-equal dc1 "+title:")
6001 '(font-lock-fontified t face org-document-title)
6002 '(font-lock-fontified t face org-document-info))))
6003 ((equal dc1 "+caption:")
6004 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
6005 (remove-text-properties (match-beginning 0) (match-end 0)
6006 '(display t invisible t intangible t))
6007 (add-text-properties (match-beginning 1) (match-end 3)
6008 '(font-lock-fontified t face org-meta-line))
6009 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
6010 '(font-lock-fontified t face org-block))
6012 ((member dc3 '(" " ""))
6013 (org-remove-flyspell-overlays-in beg (match-end 0))
6014 (add-text-properties
6015 beg (match-end 0)
6016 '(font-lock-fontified t face font-lock-comment-face)))
6017 (t ;; just any other in-buffer setting, but not indented
6018 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6019 (remove-text-properties (match-beginning 0) (match-end 0)
6020 '(display t invisible t intangible t))
6021 (add-text-properties beg (match-end 0)
6022 '(font-lock-fontified t face org-meta-line))
6023 t))))))
6025 (defun org-fontify-drawers (limit)
6026 "Fontify drawers."
6027 (when (re-search-forward org-drawer-regexp limit t)
6028 (add-text-properties
6029 (match-beginning 0) (match-end 0)
6030 '(font-lock-fontified t face org-special-keyword))
6031 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6034 (defun org-fontify-macros (limit)
6035 "Fontify macros."
6036 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
6037 (add-text-properties
6038 (match-beginning 0) (match-end 0)
6039 '(font-lock-fontified t face org-macro))
6040 (when org-hide-macro-markers
6041 (add-text-properties (match-end 2) (match-beginning 2)
6042 '(invisible t))
6043 (add-text-properties (match-beginning 1) (match-end 1)
6044 '(invisible t)))
6045 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6048 (defun org-activate-angle-links (limit)
6049 "Add text properties for angle links."
6050 (when (and (re-search-forward org-angle-link-re limit t)
6051 (not (org-in-src-block-p)))
6052 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6053 (add-text-properties (match-beginning 0) (match-end 0)
6054 (list 'mouse-face 'highlight
6055 'keymap org-mouse-map
6056 'font-lock-multiline t))
6057 (org-rear-nonsticky-at (match-end 0))
6060 (defun org-activate-footnote-links (limit)
6061 "Add text properties for footnotes."
6062 (let ((fn (org-footnote-next-reference-or-definition limit)))
6063 (when fn
6064 (let* ((beg (nth 1 fn))
6065 (end (nth 2 fn))
6066 (label (car fn))
6067 (referencep (/= (line-beginning-position) beg)))
6068 (when (and referencep (nth 3 fn))
6069 (save-excursion
6070 (goto-char beg)
6071 (search-forward (or label "fn:"))
6072 (org-remove-flyspell-overlays-in beg (match-end 0))))
6073 (add-text-properties beg end
6074 (list 'mouse-face 'highlight
6075 'keymap org-mouse-map
6076 'help-echo
6077 (if referencep "Footnote reference"
6078 "Footnote definition")
6079 'font-lock-fontified t
6080 'font-lock-multiline t
6081 'face 'org-footnote))))))
6083 (defun org-activate-bracket-links (limit)
6084 "Add text properties for bracketed links."
6085 (when (and (re-search-forward org-bracket-link-regexp limit t)
6086 (not (org-in-src-block-p)))
6087 (let* ((hl (match-string-no-properties 1))
6088 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6089 (ip (org-maybe-intangible
6090 (list 'invisible 'org-link
6091 'keymap org-mouse-map 'mouse-face 'highlight
6092 'font-lock-multiline t 'help-echo help
6093 'htmlize-link `(:uri ,hl))))
6094 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6095 'font-lock-multiline t 'help-echo help
6096 'htmlize-link `(:uri ,hl))))
6097 ;; We need to remove the invisible property here. Table narrowing
6098 ;; may have made some of this invisible.
6099 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6100 (remove-text-properties (match-beginning 0) (match-end 0)
6101 '(invisible nil))
6102 (if (match-end 3)
6103 (progn
6104 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6105 (org-rear-nonsticky-at (match-beginning 3))
6106 (add-text-properties (match-beginning 3) (match-end 3) vp)
6107 (org-rear-nonsticky-at (match-end 3))
6108 (add-text-properties (match-end 3) (match-end 0) ip)
6109 (org-rear-nonsticky-at (match-end 0)))
6110 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6111 (org-rear-nonsticky-at (match-beginning 1))
6112 (add-text-properties (match-beginning 1) (match-end 1) vp)
6113 (org-rear-nonsticky-at (match-end 1))
6114 (add-text-properties (match-end 1) (match-end 0) ip)
6115 (org-rear-nonsticky-at (match-end 0)))
6116 t)))
6118 (defun org-activate-dates (limit)
6119 "Add text properties for dates."
6120 (when (and (re-search-forward org-tsr-regexp-both limit t)
6121 (not (equal (char-before (match-beginning 0)) 91)))
6122 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6123 (add-text-properties (match-beginning 0) (match-end 0)
6124 (list 'mouse-face 'highlight
6125 'keymap org-mouse-map))
6126 (org-rear-nonsticky-at (match-end 0))
6127 (when org-display-custom-times
6128 (if (match-end 3)
6129 (org-display-custom-time (match-beginning 3) (match-end 3))
6130 (org-display-custom-time (match-beginning 1) (match-end 1))))
6133 (defvar-local org-target-link-regexp nil
6134 "Regular expression matching radio targets in plain text.")
6136 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6137 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6138 border border border))
6139 "Regular expression matching a link target.")
6141 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6142 "Regular expression matching a radio target.")
6144 (defconst org-any-target-regexp
6145 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6146 "Regular expression matching any target.")
6148 (defun org-activate-target-links (limit)
6149 "Add text properties for target matches."
6150 (when org-target-link-regexp
6151 (let ((case-fold-search t))
6152 (when (re-search-forward org-target-link-regexp limit t)
6153 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6154 (add-text-properties (match-beginning 1) (match-end 1)
6155 (list 'mouse-face 'highlight
6156 'keymap org-mouse-map
6157 'help-echo "Radio target link"
6158 'org-linked-text t))
6159 (org-rear-nonsticky-at (match-end 1))
6160 t))))
6162 (defun org-update-radio-target-regexp ()
6163 "Find all radio targets in this file and update the regular expression.
6164 Also refresh fontification if needed."
6165 (interactive)
6166 (let ((old-regexp org-target-link-regexp)
6167 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6168 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6169 (targets
6170 (org-with-wide-buffer
6171 (goto-char (point-min))
6172 (let (rtn)
6173 (while (re-search-forward org-radio-target-regexp nil t)
6174 ;; Make sure point is really within the object.
6175 (backward-char)
6176 (let ((obj (org-element-context)))
6177 (when (eq (org-element-type obj) 'radio-target)
6178 (cl-pushnew (org-element-property :value obj) rtn
6179 :test #'equal))))
6180 rtn))))
6181 (setq org-target-link-regexp
6182 (and targets
6183 (concat before-re
6184 (mapconcat
6185 (lambda (x)
6186 (replace-regexp-in-string
6187 " +" "\\s-+" (regexp-quote x) t t))
6188 targets
6189 "\\|")
6190 after-re)))
6191 (unless (equal old-regexp org-target-link-regexp)
6192 ;; Clean-up cache.
6193 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6194 ((not org-target-link-regexp) old-regexp)
6196 (concat before-re
6197 (mapconcat
6198 (lambda (re)
6199 (substring re (length before-re)
6200 (- (length after-re))))
6201 (list old-regexp org-target-link-regexp)
6202 "\\|")
6203 after-re)))))
6204 (org-with-wide-buffer
6205 (goto-char (point-min))
6206 (while (re-search-forward regexp nil t)
6207 (org-element-cache-refresh (match-beginning 1)))))
6208 ;; Re fontify buffer.
6209 (when (memq 'radio org-highlight-links)
6210 (org-restart-font-lock)))))
6212 (defun org-hide-wide-columns (limit)
6213 (let (s e)
6214 (setq s (text-property-any (point) (or limit (point-max))
6215 'org-cwidth t))
6216 (when s
6217 (setq e (next-single-property-change s 'org-cwidth))
6218 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6219 (goto-char e)
6220 t)))
6222 (defvar org-latex-and-related-regexp nil
6223 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6225 (defun org-compute-latex-and-related-regexp ()
6226 "Compute regular expression for LaTeX, entities and sub/superscript.
6227 Result depends on variable `org-highlight-latex-and-related'."
6228 (setq-local
6229 org-latex-and-related-regexp
6230 (let* ((re-sub
6231 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6232 ((eq org-use-sub-superscripts '{})
6233 (list org-match-substring-with-braces-regexp))
6234 (org-use-sub-superscripts (list org-match-substring-regexp))))
6235 (re-latex
6236 (when (memq 'latex org-highlight-latex-and-related)
6237 (let ((matchers (plist-get org-format-latex-options :matchers)))
6238 (delq nil
6239 (mapcar (lambda (x)
6240 (and (member (car x) matchers) (nth 1 x)))
6241 org-latex-regexps)))))
6242 (re-entities
6243 (when (memq 'entities org-highlight-latex-and-related)
6244 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6245 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6247 (defun org-do-latex-and-related (limit)
6248 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6249 LIMIT bounds the search for syntax to highlight. Stop at first
6250 highlighted object, if any. Return t if some highlighting was
6251 done, nil otherwise."
6252 (when (org-string-nw-p org-latex-and-related-regexp)
6253 (catch 'found
6254 (while (re-search-forward org-latex-and-related-regexp limit t)
6255 (unless
6256 (cl-some
6257 (lambda (f)
6258 (memq f '(org-code org-verbatim underline org-special-keyword)))
6259 (save-excursion
6260 (goto-char (1+ (match-beginning 0)))
6261 (face-at-point nil t)))
6262 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6263 '(?_ ?^))
6265 0)))
6266 (font-lock-prepend-text-property
6267 (+ offset (match-beginning 0)) (match-end 0)
6268 'face 'org-latex-and-related)
6269 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6270 '(font-lock-multiline t)))
6271 (throw 'found t)))
6272 nil)))
6274 (defun org-restart-font-lock ()
6275 "Restart `font-lock-mode', to force refontification."
6276 (when (and (boundp 'font-lock-mode) font-lock-mode)
6277 (font-lock-mode -1)
6278 (font-lock-mode 1)))
6280 (defun org-activate-tags (limit)
6281 (when (re-search-forward
6282 "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$" limit t)
6283 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6284 (add-text-properties (match-beginning 1) (match-end 1)
6285 (list 'mouse-face 'highlight
6286 'keymap org-mouse-map))
6287 (org-rear-nonsticky-at (match-end 1))
6290 (defun org-outline-level ()
6291 "Compute the outline level of the heading at point.
6293 If this is called at a normal headline, the level is the number
6294 of stars. Use `org-reduced-level' to remove the effect of
6295 `org-odd-levels'. Unlike to `org-current-level', this function
6296 takes into consideration inlinetasks."
6297 (org-with-wide-buffer
6298 (end-of-line)
6299 (if (re-search-backward org-outline-regexp-bol nil t)
6300 (1- (- (match-end 0) (match-beginning 0)))
6301 0)))
6303 (defvar org-font-lock-keywords nil)
6305 (defsubst org-re-property (property &optional literal allow-null value)
6306 "Return a regexp matching a PROPERTY line.
6308 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6309 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6310 non-nil, match properties even without a value.
6312 Match group 3 is set to the value when it exists. If there is no
6313 value and ALLOW-NULL is non-nil, it is set to the empty string.
6315 With optional argument VALUE, match only property lines with
6316 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6317 unless LITERAL is non-nil."
6318 (concat
6319 "^\\(?4:[ \t]*\\)"
6320 (format "\\(?1::\\(?2:%s\\):\\)"
6321 (if literal property (regexp-quote property)))
6322 (cond (value
6323 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6324 (if literal value (regexp-quote value))))
6325 (allow-null
6326 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6328 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6330 (defconst org-property-re
6331 (org-re-property "\\S-+" 'literal t)
6332 "Regular expression matching a property line.
6333 There are four matching groups:
6334 1: :PROPKEY: including the leading and trailing colon,
6335 2: PROPKEY without the leading and trailing colon,
6336 3: PROPVAL without leading or trailing spaces,
6337 4: the indentation of the current line,
6338 5: trailing whitespace.")
6340 (defvar org-font-lock-hook nil
6341 "Functions to be called for special font lock stuff.")
6343 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6345 (defvar org-font-lock-set-keywords-hook nil
6346 "Functions that can manipulate `org-font-lock-extra-keywords'.
6347 This is called after `org-font-lock-extra-keywords' is defined, but before
6348 it is installed to be used by font lock. This can be useful if something
6349 needs to be inserted at a specific position in the font-lock sequence.")
6351 (defun org-font-lock-hook (limit)
6352 "Run `org-font-lock-hook' within LIMIT."
6353 (run-hook-with-args 'org-font-lock-hook limit))
6355 (defun org-set-font-lock-defaults ()
6356 "Set font lock defaults for the current buffer."
6357 (let* ((em org-fontify-emphasized-text)
6358 (lk org-highlight-links)
6359 (org-font-lock-extra-keywords
6360 (list
6361 ;; Call the hook
6362 '(org-font-lock-hook)
6363 ;; Headlines
6364 `(,(if org-fontify-whole-heading-line
6365 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6366 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6367 (1 (org-get-level-face 1))
6368 (2 (org-get-level-face 2))
6369 (3 (org-get-level-face 3)))
6370 ;; Table lines
6371 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6372 (1 'org-table t))
6373 ;; Table internals
6374 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6375 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6376 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6377 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6378 ;; Drawers
6379 '(org-fontify-drawers)
6380 ;; Properties
6381 (list org-property-re
6382 '(1 'org-special-keyword t)
6383 '(3 'org-property-value t))
6384 ;; Links
6385 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6386 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6387 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6388 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6389 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6390 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6391 (when (memq 'footnote lk) '(org-activate-footnote-links))
6392 ;; Targets.
6393 (list org-any-target-regexp '(0 'org-target t))
6394 ;; Diary sexps.
6395 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6396 ;; Macro
6397 '(org-fontify-macros)
6398 '(org-hide-wide-columns (0 nil append))
6399 ;; TODO keyword
6400 (list (format org-heading-keyword-regexp-format
6401 org-todo-regexp)
6402 '(2 (org-get-todo-face 2) t))
6403 ;; DONE
6404 (if org-fontify-done-headline
6405 (list (format org-heading-keyword-regexp-format
6406 (concat
6407 "\\(?:"
6408 (mapconcat 'regexp-quote org-done-keywords "\\|")
6409 "\\)"))
6410 '(2 'org-headline-done t))
6411 nil)
6412 ;; Priorities
6413 '(org-font-lock-add-priority-faces)
6414 ;; Tags
6415 '(org-font-lock-add-tag-faces)
6416 ;; Tags groups
6417 (when (and org-group-tags org-tag-groups-alist)
6418 (list (concat org-outline-regexp-bol ".+\\(:"
6419 (regexp-opt (mapcar 'car org-tag-groups-alist))
6420 ":\\).*$")
6421 '(1 'org-tag-group prepend)))
6422 ;; Special keywords
6423 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6424 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6425 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6426 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6427 ;; Emphasis
6428 (when em '(org-do-emphasis-faces))
6429 ;; Checkboxes
6430 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6431 1 'org-checkbox prepend)
6432 (when (cdr (assq 'checkbox org-list-automatic-rules))
6433 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6434 (0 (org-get-checkbox-statistics-face) t)))
6435 ;; Description list items
6436 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6437 1 'org-list-dt prepend)
6438 ;; ARCHIVEd headings
6439 (list (concat
6440 org-outline-regexp-bol
6441 "\\(.*:" org-archive-tag ":.*\\)")
6442 '(1 'org-archived prepend))
6443 ;; Specials
6444 '(org-do-latex-and-related)
6445 '(org-fontify-entities)
6446 '(org-raise-scripts)
6447 ;; Code
6448 '(org-activate-code (1 'org-code t))
6449 ;; COMMENT
6450 (list (format
6451 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6452 org-todo-regexp
6453 org-comment-string)
6454 '(9 'org-special-keyword t))
6455 ;; Blocks and meta lines
6456 '(org-fontify-meta-lines-and-blocks))))
6457 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6458 (run-hooks 'org-font-lock-set-keywords-hook)
6459 ;; Now set the full font-lock-keywords
6460 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6461 (setq-local font-lock-defaults
6462 '(org-font-lock-keywords t nil nil backward-paragraph))
6463 (kill-local-variable 'font-lock-keywords) nil))
6465 (defun org-toggle-pretty-entities ()
6466 "Toggle the composition display of entities as UTF8 characters."
6467 (interactive)
6468 (setq-local org-pretty-entities (not org-pretty-entities))
6469 (org-restart-font-lock)
6470 (if org-pretty-entities
6471 (message "Entities are now displayed as UTF8 characters")
6472 (save-restriction
6473 (widen)
6474 (decompose-region (point-min) (point-max))
6475 (message "Entities are now displayed as plain text"))))
6477 (defvar-local org-custom-properties-overlays nil
6478 "List of overlays used for custom properties.")
6480 (defun org-toggle-custom-properties-visibility ()
6481 "Display or hide properties in `org-custom-properties'."
6482 (interactive)
6483 (if org-custom-properties-overlays
6484 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6485 (setq org-custom-properties-overlays nil))
6486 (when org-custom-properties
6487 (org-with-wide-buffer
6488 (goto-char (point-min))
6489 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6490 (while (re-search-forward regexp nil t)
6491 (let ((end (cdr (save-match-data (org-get-property-block)))))
6492 (when (and end (< (point) end))
6493 ;; Hide first custom property in current drawer.
6494 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6495 (overlay-put o 'invisible t)
6496 (overlay-put o 'org-custom-property t)
6497 (push o org-custom-properties-overlays))
6498 ;; Hide additional custom properties in the same drawer.
6499 (while (re-search-forward regexp end t)
6500 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6501 (overlay-put o 'invisible t)
6502 (overlay-put o 'org-custom-property t)
6503 (push o org-custom-properties-overlays)))))
6504 ;; Each entry is limited to a single property drawer.
6505 (outline-next-heading)))))))
6507 (defun org-fontify-entities (limit)
6508 "Find an entity to fontify."
6509 (let (ee)
6510 (when org-pretty-entities
6511 (catch 'match
6512 ;; "\_ "-family is left out on purpose. Only the first one,
6513 ;; i.e., "\_ ", could be fontified anyway, and it would be
6514 ;; confusing when adding a second white space character.
6515 (while (re-search-forward
6516 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6517 limit t)
6518 (when (and (not (org-at-comment-p))
6519 (setq ee (org-entity-get (match-string 1)))
6520 (= (length (nth 6 ee)) 1))
6521 (let* ((end (if (equal (match-string 2) "{}")
6522 (match-end 2)
6523 (match-end 1))))
6524 (add-text-properties
6525 (match-beginning 0) end
6526 (list 'font-lock-fontified t))
6527 (compose-region (match-beginning 0) end
6528 (nth 6 ee) nil)
6529 (backward-char 1)
6530 (throw 'match t))))
6531 nil))))
6533 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6534 "Fontify string S like in Org-mode."
6535 (with-temp-buffer
6536 (insert s)
6537 (let ((org-odd-levels-only odd-levels))
6538 (org-mode)
6539 (org-font-lock-ensure)
6540 (buffer-string))))
6542 (defvar org-m nil)
6543 (defvar org-l nil)
6544 (defvar org-f nil)
6545 (defun org-get-level-face (n)
6546 "Get the right face for match N in font-lock matching of headlines."
6547 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6548 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6549 (if org-cycle-level-faces
6550 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6551 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6552 (cond
6553 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6554 ((eq n 2) org-f)
6555 (t (unless org-level-color-stars-only org-f))))
6557 (defun org-face-from-face-or-color (context inherit face-or-color)
6558 "Create a face list that inherits INHERIT, but sets the foreground color.
6559 When FACE-OR-COLOR is not a string, just return it."
6560 (if (stringp face-or-color)
6561 (list :inherit inherit
6562 (cdr (assoc context org-faces-easy-properties))
6563 face-or-color)
6564 face-or-color))
6566 (defun org-get-todo-face (kwd)
6567 "Get the right face for a TODO keyword KWD.
6568 If KWD is a number, get the corresponding match group."
6569 (when (numberp kwd) (setq kwd (match-string kwd)))
6570 (or (org-face-from-face-or-color
6571 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6572 (and (member kwd org-done-keywords) 'org-done)
6573 'org-todo))
6575 (defun org-get-priority-face (priority)
6576 "Get the right face for PRIORITY.
6577 PRIORITY is a character."
6578 (or (org-face-from-face-or-color
6579 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6580 'org-priority))
6582 (defun org-get-tag-face (tag)
6583 "Get the right face for TAG.
6584 If TAG is a number, get the corresponding match group."
6585 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6586 (or (org-face-from-face-or-color
6587 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6588 'org-tag)))
6590 (defun org-font-lock-add-priority-faces (limit)
6591 "Add the special priority faces."
6592 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6593 (add-text-properties
6594 (match-beginning 1) (match-end 1)
6595 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6596 'font-lock-fontified t))))
6598 (defun org-font-lock-add-tag-faces (limit)
6599 "Add the special tag faces."
6600 (when (and org-tag-faces org-tags-special-faces-re)
6601 (while (re-search-forward org-tags-special-faces-re limit t)
6602 (add-text-properties (match-beginning 1) (match-end 1)
6603 (list 'face (org-get-tag-face 1)
6604 'font-lock-fontified t))
6605 (backward-char 1))))
6607 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6608 "Remove fontification and activation overlays from links."
6609 (font-lock-default-unfontify-region beg end)
6610 (let* ((buffer-undo-list t)
6611 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6612 (inhibit-modification-hooks t)
6613 deactivate-mark buffer-file-name buffer-file-truename)
6614 (decompose-region beg end)
6615 (remove-text-properties beg end
6616 '(mouse-face t keymap t org-linked-text t
6617 invisible t intangible t
6618 org-emphasis t))
6619 (org-remove-font-lock-display-properties beg end)))
6621 (defconst org-script-display '(((raise -0.3) (height 0.7))
6622 ((raise 0.3) (height 0.7))
6623 ((raise -0.5))
6624 ((raise 0.5)))
6625 "Display properties for showing superscripts and subscripts.")
6627 (defun org-remove-font-lock-display-properties (beg end)
6628 "Remove specific display properties that have been added by font lock.
6629 The will remove the raise properties that are used to show superscripts
6630 and subscripts."
6631 (let (next prop)
6632 (while (< beg end)
6633 (setq next (next-single-property-change beg 'display nil end)
6634 prop (get-text-property beg 'display))
6635 (when (member prop org-script-display)
6636 (put-text-property beg next 'display nil))
6637 (setq beg next))))
6639 (defun org-raise-scripts (limit)
6640 "Add raise properties to sub/superscripts."
6641 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6642 (re-search-forward
6643 (if (eq org-use-sub-superscripts t)
6644 org-match-substring-regexp
6645 org-match-substring-with-braces-regexp)
6646 limit t))
6647 (let* ((pos (point)) table-p comment-p
6648 (mpos (match-beginning 3))
6649 (emph-p (get-text-property mpos 'org-emphasis))
6650 (link-p (get-text-property mpos 'mouse-face))
6651 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6652 (goto-char (point-at-bol))
6653 (setq table-p (looking-at-p org-table-dataline-regexp)
6654 comment-p (looking-at-p "^[ \t]*#[ +]"))
6655 (goto-char pos)
6656 ;; Handle a_b^c
6657 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6658 (unless (or comment-p emph-p link-p keyw-p)
6659 (put-text-property (match-beginning 3) (match-end 0)
6660 'display
6661 (if (equal (char-after (match-beginning 2)) ?^)
6662 (nth (if table-p 3 1) org-script-display)
6663 (nth (if table-p 2 0) org-script-display)))
6664 (add-text-properties (match-beginning 2) (match-end 2)
6665 (list 'invisible t
6666 'org-dwidth t 'org-dwidth-n 1))
6667 (if (and (eq (char-after (match-beginning 3)) ?{)
6668 (eq (char-before (match-end 3)) ?}))
6669 (progn
6670 (add-text-properties
6671 (match-beginning 3) (1+ (match-beginning 3))
6672 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6673 (add-text-properties
6674 (1- (match-end 3)) (match-end 3)
6675 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6676 t)))
6678 ;;;; Visibility cycling, including org-goto and indirect buffer
6680 ;;; Cycling
6682 (defvar-local org-cycle-global-status nil)
6683 (put 'org-cycle-global-status 'org-state t)
6684 (defvar-local org-cycle-subtree-status nil)
6685 (put 'org-cycle-subtree-status 'org-state t)
6687 (defvar org-inlinetask-min-level)
6689 (defun org-unlogged-message (&rest args)
6690 "Display a message, but avoid logging it in the *Messages* buffer."
6691 (let ((message-log-max nil))
6692 (apply 'message args)))
6694 ;;;###autoload
6695 (defun org-cycle (&optional arg)
6696 "TAB-action and visibility cycling for Org-mode.
6698 This is the command invoked in Org-mode by the TAB key. Its main purpose
6699 is outline visibility cycling, but it also invokes other actions
6700 in special contexts.
6702 - When this function is called with a prefix argument, rotate the entire
6703 buffer through 3 states (global cycling)
6704 1. OVERVIEW: Show only top-level headlines.
6705 2. CONTENTS: Show all headlines of all levels, but no body text.
6706 3. SHOW ALL: Show everything.
6707 With a double \\[universal-argument] prefix argument, \
6708 switch to the startup visibility,
6709 determined by the variable `org-startup-folded', and by any VISIBILITY
6710 properties in the buffer.
6711 With a triple \\[universal-argument] prefix argument, \
6712 show the entire buffer, including any drawers.
6714 - When inside a table, re-align the table and move to the next field.
6716 - When point is at the beginning of a headline, rotate the subtree started
6717 by this line through 3 different states (local cycling)
6718 1. FOLDED: Only the main headline is shown.
6719 2. CHILDREN: The main headline and the direct children are shown.
6720 From this state, you can move to one of the children
6721 and zoom in further.
6722 3. SUBTREE: Show the entire subtree, including body text.
6723 If there is no subtree, switch directly from CHILDREN to FOLDED.
6725 - When point is at the beginning of an empty headline and the variable
6726 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6727 of the headline by demoting and promoting it to likely levels. This
6728 speeds up creation document structure by pressing TAB once or several
6729 times right after creating a new headline.
6731 - When there is a numeric prefix, go up to a heading with level ARG, do
6732 a `show-subtree' and return to the previous cursor position. If ARG
6733 is negative, go up that many levels.
6735 - When point is not at the beginning of a headline, execute the global
6736 binding for TAB, which is re-indenting the line. See the option
6737 `org-cycle-emulate-tab' for details.
6739 - Special case: if point is at the beginning of the buffer and there is
6740 no headline in line 1, this function will act as if called with prefix arg
6741 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6742 But only if also the variable `org-cycle-global-at-bob' is t."
6743 (interactive "P")
6744 (org-load-modules-maybe)
6745 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6746 (and org-cycle-level-after-item/entry-creation
6747 (or (org-cycle-level)
6748 (org-cycle-item-indentation))))
6749 (let* ((limit-level
6750 (or org-cycle-max-level
6751 (and (boundp 'org-inlinetask-min-level)
6752 org-inlinetask-min-level
6753 (1- org-inlinetask-min-level))))
6754 (nstars (and limit-level
6755 (if org-odd-levels-only
6756 (and limit-level (1- (* limit-level 2)))
6757 limit-level)))
6758 (org-outline-regexp
6759 (if (not (derived-mode-p 'org-mode))
6760 outline-regexp
6761 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6762 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6763 (not (looking-at org-outline-regexp))))
6764 (org-cycle-hook
6765 (if bob-special
6766 (delq 'org-optimize-window-after-visibility-change
6767 (copy-sequence org-cycle-hook))
6768 org-cycle-hook))
6769 (pos (point)))
6771 (when (or bob-special (equal arg '(4)))
6772 ;; special case: use global cycling
6773 (setq arg t))
6775 (cond
6777 ((equal arg '(16))
6778 (setq last-command 'dummy)
6779 (org-set-startup-visibility)
6780 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6782 ((equal arg '(64))
6783 (outline-show-all)
6784 (org-unlogged-message "Entire buffer visible, including drawers"))
6786 ;; Try cdlatex TAB completion
6787 ((org-try-cdlatex-tab))
6789 ;; Table: enter it or move to the next field.
6790 ((org-at-table-p 'any)
6791 (if (org-at-table.el-p)
6792 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6793 Use \\[org-edit-special] to edit table.el tables"))
6794 (if arg (org-table-edit-field t)
6795 (org-table-justify-field-maybe)
6796 (call-interactively 'org-table-next-field))))
6798 ((run-hook-with-args-until-success
6799 'org-tab-after-check-for-table-hook))
6801 ;; Global cycling: delegate to `org-cycle-internal-global'.
6802 ((eq arg t) (org-cycle-internal-global))
6804 ;; Drawers: delegate to `org-flag-drawer'.
6805 ((save-excursion
6806 (beginning-of-line 1)
6807 (looking-at org-drawer-regexp))
6808 (org-flag-drawer ; toggle block visibility
6809 (not (get-char-property (match-end 0) 'invisible))))
6811 ;; Show-subtree, ARG levels up from here.
6812 ((integerp arg)
6813 (save-excursion
6814 (org-back-to-heading)
6815 (outline-up-heading (if (< arg 0) (- arg)
6816 (- (funcall outline-level) arg)))
6817 (org-show-subtree)))
6819 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6820 ((and (featurep 'org-inlinetask)
6821 (org-inlinetask-at-task-p)
6822 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6823 (org-inlinetask-toggle-visibility))
6825 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6826 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6827 (save-excursion (move-beginning-of-line 1)
6828 (looking-at org-outline-regexp)))
6829 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6830 (org-cycle-internal-local))
6832 ;; From there: TAB emulation and template completion.
6833 (buffer-read-only (org-back-to-heading))
6835 ((run-hook-with-args-until-success
6836 'org-tab-after-check-for-cycling-hook))
6838 ((org-try-structure-completion))
6840 ((run-hook-with-args-until-success
6841 'org-tab-before-tab-emulation-hook))
6843 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6844 (or (not (bolp))
6845 (not (looking-at org-outline-regexp))))
6846 (call-interactively (global-key-binding "\t")))
6848 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6849 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6850 (or (and (eq org-cycle-emulate-tab 'white)
6851 (= (match-end 0) (point-at-eol)))
6852 (and (eq org-cycle-emulate-tab 'whitestart)
6853 (>= (match-end 0) pos))))
6855 (eq org-cycle-emulate-tab t))
6856 (call-interactively (global-key-binding "\t")))
6858 (t (save-excursion
6859 (org-back-to-heading)
6860 (org-cycle)))))))
6862 (defun org-cycle-internal-global ()
6863 "Do the global cycling action."
6864 ;; Hack to avoid display of messages for .org attachments in Gnus
6865 (let ((ga (string-match "\\*fontification" (buffer-name))))
6866 (cond
6867 ((and (eq last-command this-command)
6868 (eq org-cycle-global-status 'overview))
6869 ;; We just created the overview - now do table of contents
6870 ;; This can be slow in very large buffers, so indicate action
6871 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6872 (unless ga (org-unlogged-message "CONTENTS..."))
6873 (org-content)
6874 (unless ga (org-unlogged-message "CONTENTS...done"))
6875 (setq org-cycle-global-status 'contents)
6876 (run-hook-with-args 'org-cycle-hook 'contents))
6878 ((and (eq last-command this-command)
6879 (eq org-cycle-global-status 'contents))
6880 ;; We just showed the table of contents - now show everything
6881 (run-hook-with-args 'org-pre-cycle-hook 'all)
6882 (outline-show-all)
6883 (unless ga (org-unlogged-message "SHOW ALL"))
6884 (setq org-cycle-global-status 'all)
6885 (run-hook-with-args 'org-cycle-hook 'all))
6888 ;; Default action: go to overview
6889 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6890 (org-overview)
6891 (unless ga (org-unlogged-message "OVERVIEW"))
6892 (setq org-cycle-global-status 'overview)
6893 (run-hook-with-args 'org-cycle-hook 'overview)))))
6895 (defvar org-called-with-limited-levels nil
6896 "Non-nil when `org-with-limited-levels' is currently active.")
6898 (defun org-cycle-internal-local ()
6899 "Do the local cycling action."
6900 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6901 ;; First, determine end of headline (EOH), end of subtree or item
6902 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6903 (save-excursion
6904 (if (org-at-item-p)
6905 (progn
6906 (beginning-of-line)
6907 (setq struct (org-list-struct))
6908 (setq eoh (point-at-eol))
6909 (setq eos (org-list-get-item-end-before-blank (point) struct))
6910 (setq has-children (org-list-has-child-p (point) struct)))
6911 (org-back-to-heading)
6912 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6913 (setq eos (save-excursion (org-end-of-subtree t t)
6914 (when (bolp) (backward-char)) (point)))
6915 (setq has-children
6916 (or (save-excursion
6917 (let ((level (funcall outline-level)))
6918 (outline-next-heading)
6919 (and (org-at-heading-p t)
6920 (> (funcall outline-level) level))))
6921 (save-excursion
6922 (org-list-search-forward (org-item-beginning-re) eos t)))))
6923 ;; Determine end invisible part of buffer (EOL)
6924 (beginning-of-line 2)
6925 (while (and (not (eobp)) ;This is like `next-line'.
6926 (get-char-property (1- (point)) 'invisible))
6927 (goto-char (next-single-char-property-change (point) 'invisible))
6928 (and (eolp) (beginning-of-line 2)))
6929 (setq eol (point)))
6930 ;; Find out what to do next and set `this-command'
6931 (cond
6932 ((= eos eoh)
6933 ;; Nothing is hidden behind this heading
6934 (unless (org-before-first-heading-p)
6935 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6936 (org-unlogged-message "EMPTY ENTRY")
6937 (setq org-cycle-subtree-status nil)
6938 (save-excursion
6939 (goto-char eos)
6940 (outline-next-heading)
6941 (when (outline-invisible-p) (org-flag-heading nil))))
6942 ((and (or (>= eol eos)
6943 (not (string-match "\\S-" (buffer-substring eol eos))))
6944 (or has-children
6945 (not (setq children-skipped
6946 org-cycle-skip-children-state-if-no-children))))
6947 ;; Entire subtree is hidden in one line: children view
6948 (unless (org-before-first-heading-p)
6949 (run-hook-with-args 'org-pre-cycle-hook 'children))
6950 (if (org-at-item-p)
6951 (org-list-set-item-visibility (point-at-bol) struct 'children)
6952 (org-show-entry)
6953 (org-with-limited-levels (org-show-children))
6954 ;; FIXME: This slows down the func way too much.
6955 ;; How keep drawers hidden in subtree anyway?
6956 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6957 ;; (org-cycle-hide-drawers 'subtree))
6959 ;; Fold every list in subtree to top-level items.
6960 (when (eq org-cycle-include-plain-lists 'integrate)
6961 (save-excursion
6962 (org-back-to-heading)
6963 (while (org-list-search-forward (org-item-beginning-re) eos t)
6964 (beginning-of-line 1)
6965 (let* ((struct (org-list-struct))
6966 (prevs (org-list-prevs-alist struct))
6967 (end (org-list-get-bottom-point struct)))
6968 (dolist (e (org-list-get-all-items (point) struct prevs))
6969 (org-list-set-item-visibility e struct 'folded))
6970 (goto-char (if (< end eos) end eos)))))))
6971 (org-unlogged-message "CHILDREN")
6972 (save-excursion
6973 (goto-char eos)
6974 (outline-next-heading)
6975 (when (outline-invisible-p) (org-flag-heading nil)))
6976 (setq org-cycle-subtree-status 'children)
6977 (unless (org-before-first-heading-p)
6978 (run-hook-with-args 'org-cycle-hook 'children)))
6979 ((or children-skipped
6980 (and (eq last-command this-command)
6981 (eq org-cycle-subtree-status 'children)))
6982 ;; We just showed the children, or no children are there,
6983 ;; now show everything.
6984 (unless (org-before-first-heading-p)
6985 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6986 (outline-flag-region eoh eos nil)
6987 (org-unlogged-message
6988 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6989 (setq org-cycle-subtree-status 'subtree)
6990 (unless (org-before-first-heading-p)
6991 (run-hook-with-args 'org-cycle-hook 'subtree)))
6993 ;; Default action: hide the subtree.
6994 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6995 (outline-flag-region eoh eos t)
6996 (org-unlogged-message "FOLDED")
6997 (setq org-cycle-subtree-status 'folded)
6998 (unless (org-before-first-heading-p)
6999 (run-hook-with-args 'org-cycle-hook 'folded))))))
7001 ;;;###autoload
7002 (defun org-global-cycle (&optional arg)
7003 "Cycle the global visibility. For details see `org-cycle'.
7004 With \\[universal-argument] prefix arg, switch to startup visibility.
7005 With a numeric prefix, show all headlines up to that level."
7006 (interactive "P")
7007 (let ((org-cycle-include-plain-lists
7008 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
7009 (cond
7010 ((integerp arg)
7011 (outline-show-all)
7012 (outline-hide-sublevels arg)
7013 (setq org-cycle-global-status 'contents))
7014 ((equal arg '(4))
7015 (org-set-startup-visibility)
7016 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
7018 (org-cycle '(4))))))
7020 (defun org-set-startup-visibility ()
7021 "Set the visibility required by startup options and properties."
7022 (cond
7023 ((eq org-startup-folded t)
7024 (org-overview))
7025 ((eq org-startup-folded 'content)
7026 (org-content))
7027 ((or (eq org-startup-folded 'showeverything)
7028 (eq org-startup-folded nil))
7029 (outline-show-all)))
7030 (unless (eq org-startup-folded 'showeverything)
7031 (when org-hide-block-startup (org-hide-block-all))
7032 (org-set-visibility-according-to-property 'no-cleanup)
7033 (org-cycle-hide-archived-subtrees 'all)
7034 (org-cycle-hide-drawers 'all)
7035 (org-cycle-show-empty-lines t)))
7037 (defun org-set-visibility-according-to-property (&optional no-cleanup)
7038 "Switch subtree visibilities according to :VISIBILITY: property."
7039 (interactive)
7040 (org-with-wide-buffer
7041 (goto-char (point-min))
7042 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
7043 (if (not (org-at-property-p)) (outline-next-heading)
7044 (let ((state (match-string 3)))
7045 (save-excursion
7046 (org-back-to-heading t)
7047 (outline-hide-subtree)
7048 (org-reveal)
7049 (cond
7050 ((equal state "folded")
7051 (outline-hide-subtree))
7052 ((equal state "children")
7053 (org-show-hidden-entry)
7054 (org-show-children))
7055 ((equal state "content")
7056 (save-excursion
7057 (save-restriction
7058 (org-narrow-to-subtree)
7059 (org-content))))
7060 ((member state '("all" "showall"))
7061 (outline-show-subtree)))))))
7062 (unless no-cleanup
7063 (org-cycle-hide-archived-subtrees 'all)
7064 (org-cycle-hide-drawers 'all)
7065 (org-cycle-show-empty-lines 'all))))
7067 ;; This function uses outline-regexp instead of the more fundamental
7068 ;; org-outline-regexp so that org-cycle-global works outside of Org
7069 ;; buffers, where outline-regexp is needed.
7070 (defun org-overview ()
7071 "Switch to overview mode, showing only top-level headlines.
7072 This shows all headlines with a level equal or greater than the level
7073 of the first headline in the buffer. This is important, because if the
7074 first headline is not level one, then (hide-sublevels 1) gives confusing
7075 results."
7076 (interactive)
7077 (save-excursion
7078 (let ((level
7079 (save-excursion
7080 (goto-char (point-min))
7081 (when (re-search-forward (concat "^" outline-regexp) nil t)
7082 (goto-char (match-beginning 0))
7083 (funcall outline-level)))))
7084 (and level (outline-hide-sublevels level)))))
7086 (defun org-content (&optional arg)
7087 "Show all headlines in the buffer, like a table of contents.
7088 With numerical argument N, show content up to level N."
7089 (interactive "P")
7090 (org-overview)
7091 (save-excursion
7092 ;; Visit all headings and show their offspring
7093 (and (integerp arg) (org-overview))
7094 (goto-char (point-max))
7095 (catch 'exit
7096 (while (and (progn (condition-case nil
7097 (outline-previous-visible-heading 1)
7098 (error (goto-char (point-min))))
7100 (looking-at org-outline-regexp))
7101 (if (integerp arg)
7102 (org-show-children (1- arg))
7103 (outline-show-branches))
7104 (when (bobp) (throw 'exit nil))))))
7106 (defun org-optimize-window-after-visibility-change (state)
7107 "Adjust the window after a change in outline visibility.
7108 This function is the default value of the hook `org-cycle-hook'."
7109 (when (get-buffer-window (current-buffer))
7110 (cond
7111 ((eq state 'content) nil)
7112 ((eq state 'all) nil)
7113 ((eq state 'folded) nil)
7114 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7115 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7117 (defun org-remove-empty-overlays-at (pos)
7118 "Remove outline overlays that do not contain non-white stuff."
7119 (dolist (o (overlays-at pos))
7120 (and (eq 'outline (overlay-get o 'invisible))
7121 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7122 (overlay-end o))))
7123 (delete-overlay o))))
7125 (defun org-clean-visibility-after-subtree-move ()
7126 "Fix visibility issues after moving a subtree."
7127 ;; First, find a reasonable region to look at:
7128 ;; Start two siblings above, end three below
7129 (let* ((beg (save-excursion
7130 (and (org-get-last-sibling)
7131 (org-get-last-sibling))
7132 (point)))
7133 (end (save-excursion
7134 (and (org-get-next-sibling)
7135 (org-get-next-sibling)
7136 (org-get-next-sibling))
7137 (if (org-at-heading-p)
7138 (point-at-eol)
7139 (point))))
7140 (level (looking-at "\\*+"))
7141 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7142 (save-excursion
7143 (save-restriction
7144 (narrow-to-region beg end)
7145 (when re
7146 ;; Properly fold already folded siblings
7147 (goto-char (point-min))
7148 (while (re-search-forward re nil t)
7149 (when (and (not (outline-invisible-p))
7150 (save-excursion
7151 (goto-char (point-at-eol)) (outline-invisible-p)))
7152 (outline-hide-entry))))
7153 (org-cycle-show-empty-lines 'overview)
7154 (org-cycle-hide-drawers 'overview)))))
7156 (defun org-cycle-show-empty-lines (state)
7157 "Show empty lines above all visible headlines.
7158 The region to be covered depends on STATE when called through
7159 `org-cycle-hook'. Lisp program can use t for STATE to get the
7160 entire buffer covered. Note that an empty line is only shown if there
7161 are at least `org-cycle-separator-lines' empty lines before the headline."
7162 (when (/= org-cycle-separator-lines 0)
7163 (save-excursion
7164 (let* ((n (abs org-cycle-separator-lines))
7165 (re (cond
7166 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7167 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7168 (t (let ((ns (number-to-string (- n 2))))
7169 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7170 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7171 beg end)
7172 (cond
7173 ((memq state '(overview contents t))
7174 (setq beg (point-min) end (point-max)))
7175 ((memq state '(children folded))
7176 (setq beg (point)
7177 end (progn (org-end-of-subtree t t)
7178 (line-beginning-position 2)))))
7179 (when beg
7180 (goto-char beg)
7181 (while (re-search-forward re end t)
7182 (unless (get-char-property (match-end 1) 'invisible)
7183 (let ((e (match-end 1))
7184 (b (if (>= org-cycle-separator-lines 0)
7185 (match-beginning 1)
7186 (save-excursion
7187 (goto-char (match-beginning 0))
7188 (skip-chars-backward " \t\n")
7189 (line-end-position)))))
7190 (outline-flag-region b e nil))))))))
7191 ;; Never hide empty lines at the end of the file.
7192 (save-excursion
7193 (goto-char (point-max))
7194 (outline-previous-heading)
7195 (outline-end-of-heading)
7196 (when (and (looking-at "[ \t\n]+")
7197 (= (match-end 0) (point-max)))
7198 (outline-flag-region (point) (match-end 0) nil))))
7200 (defun org-show-empty-lines-in-parent ()
7201 "Move to the parent and re-show empty lines before visible headlines."
7202 (save-excursion
7203 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7204 (org-cycle-show-empty-lines context))))
7206 (defun org-files-list ()
7207 "Return `org-agenda-files' list, plus all open org-mode files.
7208 This is useful for operations that need to scan all of a user's
7209 open and agenda-wise Org files."
7210 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7211 (dolist (buf (buffer-list))
7212 (with-current-buffer buf
7213 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7214 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7215 files))
7217 (defsubst org-entry-beginning-position ()
7218 "Return the beginning position of the current entry."
7219 (save-excursion (org-back-to-heading t) (point)))
7221 (defsubst org-entry-end-position ()
7222 "Return the end position of the current entry."
7223 (save-excursion (outline-next-heading) (point)))
7225 (defun org-cycle-hide-drawers (state &optional exceptions)
7226 "Re-hide all drawers after a visibility state change.
7227 When non-nil, optional argument EXCEPTIONS is a list of strings
7228 specifying which drawers should not be hidden."
7229 (when (and (derived-mode-p 'org-mode)
7230 (not (memq state '(overview folded contents))))
7231 (save-excursion
7232 (let* ((globalp (memq state '(contents all)))
7233 (beg (if globalp (point-min) (point)))
7234 (end (if globalp (point-max)
7235 (if (eq state 'children)
7236 (save-excursion (outline-next-heading) (point))
7237 (org-end-of-subtree t)))))
7238 (goto-char beg)
7239 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7240 (unless (member-ignore-case (match-string 1) exceptions)
7241 (let ((drawer (org-element-at-point)))
7242 (when (memq (org-element-type drawer) '(drawer property-drawer))
7243 (org-flag-drawer t drawer)
7244 ;; Make sure to skip drawer entirely or we might flag
7245 ;; it another time when matching its ending line with
7246 ;; `org-drawer-regexp'.
7247 (goto-char (org-element-property :end drawer))))))))))
7249 (defun org-flag-drawer (flag &optional element)
7250 "When FLAG is non-nil, hide the drawer we are at.
7251 Otherwise make it visible. When optional argument ELEMENT is
7252 a parsed drawer, as returned by `org-element-at-point', hide or
7253 show that drawer instead."
7254 (let ((drawer (or element
7255 (and (save-excursion
7256 (beginning-of-line)
7257 (looking-at-p org-drawer-regexp))
7258 (org-element-at-point)))))
7259 (when (memq (org-element-type drawer) '(drawer property-drawer))
7260 (let ((post (org-element-property :post-affiliated drawer)))
7261 (save-excursion
7262 (outline-flag-region
7263 (progn (goto-char post) (line-end-position))
7264 (progn (goto-char (org-element-property :end drawer))
7265 (skip-chars-backward " \r\t\n")
7266 (line-end-position))
7267 flag))
7268 ;; When the drawer is hidden away, make sure point lies in
7269 ;; a visible part of the buffer.
7270 (when (and flag (> (line-beginning-position) post))
7271 (goto-char post))))))
7273 (defun org-subtree-end-visible-p ()
7274 "Is the end of the current subtree visible?"
7275 (pos-visible-in-window-p
7276 (save-excursion (org-end-of-subtree t) (point))))
7278 (defun org-first-headline-recenter ()
7279 "Move cursor to the first headline and recenter the headline."
7280 (let ((window (get-buffer-window)))
7281 (when window
7282 (goto-char (point-min))
7283 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7284 (set-window-start window (line-beginning-position))))))
7286 ;;; Saving and restoring visibility
7288 (defun org-outline-overlay-data (&optional use-markers)
7289 "Return a list of the locations of all outline overlays.
7290 These are overlays with the `invisible' property value `outline'.
7291 The return value is a list of cons cells, with start and stop
7292 positions for each overlay.
7293 If USE-MARKERS is set, return the positions as markers."
7294 (let (beg end)
7295 (save-excursion
7296 (save-restriction
7297 (widen)
7298 (delq nil
7299 (mapcar (lambda (o)
7300 (when (eq (overlay-get o 'invisible) 'outline)
7301 (setq beg (overlay-start o)
7302 end (overlay-end o))
7303 (and beg end (> end beg)
7304 (if use-markers
7305 (cons (copy-marker beg)
7306 (copy-marker end t))
7307 (cons beg end)))))
7308 (overlays-in (point-min) (point-max))))))))
7310 (defun org-set-outline-overlay-data (data)
7311 "Create visibility overlays for all positions in DATA.
7312 DATA should have been made by `org-outline-overlay-data'."
7313 (org-with-wide-buffer
7314 (outline-show-all)
7315 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7317 ;;; Folding of blocks
7319 (defvar-local org-hide-block-overlays nil
7320 "Overlays hiding blocks.")
7322 (defun org-block-map (function &optional start end)
7323 "Call FUNCTION at the head of all source blocks in the current buffer.
7324 Optional arguments START and END can be used to limit the range."
7325 (let ((start (or start (point-min)))
7326 (end (or end (point-max))))
7327 (save-excursion
7328 (goto-char start)
7329 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7330 (save-excursion
7331 (save-match-data
7332 (goto-char (match-beginning 0))
7333 (funcall function)))))))
7335 (defun org-hide-block-toggle-all ()
7336 "Toggle the visibility of all blocks in the current buffer."
7337 (org-block-map 'org-hide-block-toggle))
7339 (defun org-hide-block-all ()
7340 "Fold all blocks in the current buffer."
7341 (interactive)
7342 (org-show-block-all)
7343 (org-block-map 'org-hide-block-toggle-maybe))
7345 (defun org-show-block-all ()
7346 "Unfold all blocks in the current buffer."
7347 (interactive)
7348 (mapc #'delete-overlay org-hide-block-overlays)
7349 (setq org-hide-block-overlays nil))
7351 (defun org-hide-block-toggle-maybe ()
7352 "Toggle visibility of block at point.
7353 Unlike to `org-hide-block-toggle', this function does not throw
7354 an error. Return a non-nil value when toggling is successful."
7355 (interactive)
7356 (ignore-errors (org-hide-block-toggle)))
7358 (defun org-hide-block-toggle (&optional force)
7359 "Toggle the visibility of the current block.
7360 When optional argument FORCE is `off', make block visible. If it
7361 is non-nil, hide it unconditionally. Throw an error when not at
7362 a block. Return a non-nil value when toggling is successful."
7363 (interactive)
7364 (let ((element (org-element-at-point)))
7365 (unless (memq (org-element-type element)
7366 '(center-block comment-block dynamic-block example-block
7367 export-block quote-block special-block
7368 src-block verse-block))
7369 (user-error "Not at a block"))
7370 (let* ((start (save-excursion
7371 (goto-char (org-element-property :post-affiliated element))
7372 (line-end-position)))
7373 (end (save-excursion
7374 (goto-char (org-element-property :end element))
7375 (skip-chars-backward " \r\t\n")
7376 (line-end-position)))
7377 (overlays (overlays-at start)))
7378 (cond
7379 ;; Do nothing when not before or at the block opening line or
7380 ;; at the block closing line.
7381 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7382 ((and (not (eq force 'off))
7383 (not (memq t (mapcar
7384 (lambda (o)
7385 (eq (overlay-get o 'invisible) 'org-hide-block))
7386 overlays))))
7387 (let ((ov (make-overlay start end)))
7388 (overlay-put ov 'invisible 'org-hide-block)
7389 ;; Make the block accessible to `isearch'.
7390 (overlay-put
7391 ov 'isearch-open-invisible
7392 (lambda (ov)
7393 (when (memq ov org-hide-block-overlays)
7394 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7395 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7396 (delete-overlay ov))))
7397 (push ov org-hide-block-overlays)
7398 ;; When the block is hidden away, make sure point is left in
7399 ;; a visible part of the buffer.
7400 (when (> (line-beginning-position) start)
7401 (goto-char start)
7402 (beginning-of-line))
7403 ;; Signal successful toggling.
7405 ((or (not force) (eq force 'off))
7406 (dolist (ov overlays t)
7407 (when (memq ov org-hide-block-overlays)
7408 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7409 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7410 (delete-overlay ov))))))))
7412 ;; org-tab-after-check-for-cycling-hook
7413 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7414 ;; Remove overlays when changing major mode
7415 (add-hook 'org-mode-hook
7416 (lambda () (add-hook 'change-major-mode-hook
7417 'org-show-block-all 'append 'local)))
7419 ;;; Org-goto
7421 (defvar org-goto-window-configuration nil)
7422 (defvar org-goto-marker nil)
7423 (defvar org-goto-map)
7424 (defun org-goto-map ()
7425 "Set the keymap `org-goto'."
7426 (setq org-goto-map
7427 (let ((map (make-sparse-keymap)))
7428 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7429 mouse-drag-region universal-argument org-occur)))
7430 (dolist (cmd cmds)
7431 (substitute-key-definition cmd cmd map global-map)))
7432 (suppress-keymap map)
7433 (org-defkey map "\C-m" 'org-goto-ret)
7434 (org-defkey map [(return)] 'org-goto-ret)
7435 (org-defkey map [(left)] 'org-goto-left)
7436 (org-defkey map [(right)] 'org-goto-right)
7437 (org-defkey map [(control ?g)] 'org-goto-quit)
7438 (org-defkey map "\C-i" 'org-cycle)
7439 (org-defkey map [(tab)] 'org-cycle)
7440 (org-defkey map [(down)] 'outline-next-visible-heading)
7441 (org-defkey map [(up)] 'outline-previous-visible-heading)
7442 (if org-goto-auto-isearch
7443 (if (fboundp 'define-key-after)
7444 (define-key-after map [t] 'org-goto-local-auto-isearch)
7445 nil)
7446 (org-defkey map "q" 'org-goto-quit)
7447 (org-defkey map "n" 'outline-next-visible-heading)
7448 (org-defkey map "p" 'outline-previous-visible-heading)
7449 (org-defkey map "f" 'outline-forward-same-level)
7450 (org-defkey map "b" 'outline-backward-same-level)
7451 (org-defkey map "u" 'outline-up-heading))
7452 (org-defkey map "/" 'org-occur)
7453 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7454 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7455 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7456 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7457 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7458 map)))
7460 (defconst org-goto-help
7461 "Browse buffer copy, to find location or copy text.%s
7462 RET=jump to location C-g=quit and return to previous location
7463 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7465 (defvar org-goto-start-pos) ; dynamically scoped parameter
7467 (defun org-goto (&optional alternative-interface)
7468 "Look up a different location in the current file, keeping current visibility.
7470 When you want look-up or go to a different location in a
7471 document, the fastest way is often to fold the entire buffer and
7472 then dive into the tree. This method has the disadvantage, that
7473 the previous location will be folded, which may not be what you
7474 want.
7476 This command works around this by showing a copy of the current
7477 buffer in an indirect buffer, in overview mode. You can dive
7478 into the tree in that copy, use org-occur and incremental search
7479 to find a location. When pressing RET or `Q', the command
7480 returns to the original buffer in which the visibility is still
7481 unchanged. After RET it will also jump to the location selected
7482 in the indirect buffer and expose the headline hierarchy above.
7484 With a prefix argument, use the alternative interface: e.g., if
7485 `org-goto-interface' is `outline' use `outline-path-completion'."
7486 (interactive "P")
7487 (org-goto-map)
7488 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7489 (org-refile-use-outline-path t)
7490 (org-refile-target-verify-function nil)
7491 (interface
7492 (if (not alternative-interface)
7493 org-goto-interface
7494 (if (eq org-goto-interface 'outline)
7495 'outline-path-completion
7496 'outline)))
7497 (org-goto-start-pos (point))
7498 (selected-point
7499 (if (eq interface 'outline)
7500 (car (org-get-location (current-buffer) org-goto-help))
7501 (let ((pa (org-refile-get-location "Goto")))
7502 (org-refile-check-position pa)
7503 (nth 3 pa)))))
7504 (if selected-point
7505 (progn
7506 (org-mark-ring-push org-goto-start-pos)
7507 (goto-char selected-point)
7508 (when (or (outline-invisible-p) (org-invisible-p2))
7509 (org-show-context 'org-goto)))
7510 (message "Quit"))))
7512 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7513 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7514 (defvar org-goto-local-auto-isearch-map) ; defined below
7516 (defun org-get-location (_buf help)
7517 "Let the user select a location in current buffer.
7518 This function uses a recursive edit. It returns the selected position
7519 or nil."
7520 (org-no-popups
7521 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7522 (isearch-hide-immediately nil)
7523 (isearch-search-fun-function
7524 (lambda () 'org-goto-local-search-headings))
7525 (org-goto-selected-point org-goto-exit-command))
7526 (save-excursion
7527 (save-window-excursion
7528 (delete-other-windows)
7529 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7530 (org-pop-to-buffer-same-window
7531 (condition-case nil
7532 (make-indirect-buffer (current-buffer) "*org-goto*")
7533 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7534 (with-output-to-temp-buffer "*Org Help*"
7535 (princ (format help (if org-goto-auto-isearch
7536 " Just type for auto-isearch."
7537 " n/p/f/b/u to navigate, q to quit."))))
7538 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7539 (setq buffer-read-only nil)
7540 (let ((org-startup-truncated t)
7541 (org-startup-folded nil)
7542 (org-startup-align-all-tables nil))
7543 (org-mode)
7544 (org-overview))
7545 (setq buffer-read-only t)
7546 (if (and (boundp 'org-goto-start-pos)
7547 (integer-or-marker-p org-goto-start-pos))
7548 (progn (goto-char org-goto-start-pos)
7549 (when (outline-invisible-p)
7550 (org-show-set-visibility 'lineage)))
7551 (goto-char (point-min)))
7552 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7553 (message "Select location and press RET")
7554 (use-local-map org-goto-map)
7555 (recursive-edit)))
7556 (kill-buffer "*org-goto*")
7557 (cons org-goto-selected-point org-goto-exit-command))))
7559 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7560 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7561 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7562 (if (fboundp 'isearch-other-control-char)
7563 (progn
7564 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7565 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7566 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7567 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7568 (define-key org-goto-local-auto-isearch-map [return] nil))
7570 (defun org-goto-local-search-headings (string bound noerror)
7571 "Search and make sure that any matches are in headlines."
7572 (catch 'return
7573 (while (if isearch-forward
7574 (search-forward string bound noerror)
7575 (search-backward string bound noerror))
7576 (when (save-match-data
7577 (and (save-excursion
7578 (beginning-of-line)
7579 (looking-at org-complex-heading-regexp))
7580 (or (not (match-beginning 5))
7581 (< (point) (match-beginning 5)))))
7582 (throw 'return (point))))))
7584 (defun org-goto-local-auto-isearch ()
7585 "Start isearch."
7586 (interactive)
7587 (goto-char (point-min))
7588 (let ((keys (this-command-keys)))
7589 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7590 (isearch-mode t)
7591 (isearch-process-search-char (string-to-char keys)))))
7593 (defun org-goto-ret (&optional _arg)
7594 "Finish `org-goto' by going to the new location."
7595 (interactive "P")
7596 (setq org-goto-selected-point (point))
7597 (setq org-goto-exit-command 'return)
7598 (throw 'exit nil))
7600 (defun org-goto-left ()
7601 "Finish `org-goto' by going to the new location."
7602 (interactive)
7603 (if (org-at-heading-p)
7604 (progn
7605 (beginning-of-line 1)
7606 (setq org-goto-selected-point (point)
7607 org-goto-exit-command 'left)
7608 (throw 'exit nil))
7609 (user-error "Not on a heading")))
7611 (defun org-goto-right ()
7612 "Finish `org-goto' by going to the new location."
7613 (interactive)
7614 (if (org-at-heading-p)
7615 (progn
7616 (setq org-goto-selected-point (point)
7617 org-goto-exit-command 'right)
7618 (throw 'exit nil))
7619 (user-error "Not on a heading")))
7621 (defun org-goto-quit ()
7622 "Finish `org-goto' without cursor motion."
7623 (interactive)
7624 (setq org-goto-selected-point nil)
7625 (setq org-goto-exit-command 'quit)
7626 (throw 'exit nil))
7628 ;;; Indirect buffer display of subtrees
7630 (defvar org-indirect-dedicated-frame nil
7631 "This is the frame being used for indirect tree display.")
7632 (defvar org-last-indirect-buffer nil)
7634 (defun org-tree-to-indirect-buffer (&optional arg)
7635 "Create indirect buffer and narrow it to current subtree.
7636 With a numerical prefix ARG, go up to this level and then take that tree.
7637 If ARG is negative, go up that many levels.
7639 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7640 indirect buffer previously made with this command, to avoid proliferation of
7641 indirect buffers. However, when you call the command with a \
7642 \\[universal-argument] prefix, or
7643 when `org-indirect-buffer-display' is `new-frame', the last buffer
7644 is kept so that you can work with several indirect buffers at the same time.
7645 If `org-indirect-buffer-display' is `dedicated-frame', the \
7646 \\[universal-argument] prefix also
7647 requests that a new frame be made for the new buffer, so that the dedicated
7648 frame is not changed."
7649 (interactive "P")
7650 (let ((cbuf (current-buffer))
7651 (cwin (selected-window))
7652 (pos (point))
7653 beg end level heading ibuf)
7654 (save-excursion
7655 (org-back-to-heading t)
7656 (when (numberp arg)
7657 (setq level (org-outline-level))
7658 (when (< arg 0) (setq arg (+ level arg)))
7659 (while (> (setq level (org-outline-level)) arg)
7660 (org-up-heading-safe)))
7661 (setq beg (point)
7662 heading (org-get-heading 'no-tags))
7663 (org-end-of-subtree t t)
7664 (when (org-at-heading-p) (backward-char 1))
7665 (setq end (point)))
7666 (when (and (buffer-live-p org-last-indirect-buffer)
7667 (not (eq org-indirect-buffer-display 'new-frame))
7668 (not arg))
7669 (kill-buffer org-last-indirect-buffer))
7670 (setq ibuf (org-get-indirect-buffer cbuf heading)
7671 org-last-indirect-buffer ibuf)
7672 (cond
7673 ((or (eq org-indirect-buffer-display 'new-frame)
7674 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7675 (select-frame (make-frame))
7676 (delete-other-windows)
7677 (org-pop-to-buffer-same-window ibuf)
7678 (org-set-frame-title heading))
7679 ((eq org-indirect-buffer-display 'dedicated-frame)
7680 (raise-frame
7681 (select-frame (or (and org-indirect-dedicated-frame
7682 (frame-live-p org-indirect-dedicated-frame)
7683 org-indirect-dedicated-frame)
7684 (setq org-indirect-dedicated-frame (make-frame)))))
7685 (delete-other-windows)
7686 (org-pop-to-buffer-same-window ibuf)
7687 (org-set-frame-title (concat "Indirect: " heading)))
7688 ((eq org-indirect-buffer-display 'current-window)
7689 (org-pop-to-buffer-same-window ibuf))
7690 ((eq org-indirect-buffer-display 'other-window)
7691 (pop-to-buffer ibuf))
7692 (t (error "Invalid value")))
7693 (narrow-to-region beg end)
7694 (outline-show-all)
7695 (goto-char pos)
7696 (run-hook-with-args 'org-cycle-hook 'all)
7697 (and (window-live-p cwin) (select-window cwin))))
7699 (defun org-get-indirect-buffer (&optional buffer heading)
7700 (setq buffer (or buffer (current-buffer)))
7701 (let ((n 1) (base (buffer-name buffer)) bname)
7702 (while (buffer-live-p
7703 (get-buffer
7704 (setq bname
7705 (concat base "-"
7706 (if heading (concat heading "-" (number-to-string n))
7707 (number-to-string n))))))
7708 (setq n (1+ n)))
7709 (condition-case nil
7710 (make-indirect-buffer buffer bname 'clone)
7711 (error (make-indirect-buffer buffer bname)))))
7713 (defun org-set-frame-title (title)
7714 "Set the title of the current frame to the string TITLE."
7715 (modify-frame-parameters (selected-frame) (list (cons 'name title))))
7717 ;;;; Structure editing
7719 ;;; Inserting headlines
7721 (defun org--line-empty-p (n)
7722 "Is the Nth next line empty?
7724 Counts the current line as N = 1 and the previous line as N = 0;
7725 see `beginning-of-line'."
7726 (save-excursion
7727 (and (not (bobp))
7728 (or (beginning-of-line n) t)
7729 (save-match-data
7730 (looking-at "[ \t]*$")))))
7732 (defun org-previous-line-empty-p ()
7733 "Is the previous line a blank line?
7734 When NEXT is non-nil, check the next line instead."
7735 (org--line-empty-p 0))
7737 (defun org-next-line-empty-p ()
7738 "Is the previous line a blank line?
7739 When NEXT is non-nil, check the next line instead."
7740 (org--line-empty-p 2))
7742 (defun org-insert-heading (&optional arg invisible-ok top)
7743 "Insert a new heading or an item with the same depth at point.
7745 If point is at the beginning of a heading or a list item, insert
7746 a new heading or a new item above the current one. If point is
7747 at the beginning of a normal line, turn the line into a heading.
7749 If point is in the middle of a headline or a list item, split the
7750 headline or the item and create a new headline/item with the text
7751 in the current line after point \(see `org-M-RET-may-split-line'
7752 on how to modify this behavior).
7754 With one universal prefix argument, set the user option
7755 `org-insert-heading-respect-content' to t for the duration of
7756 the command. This modifies the behavior described above in this
7757 ways: on list items and at the beginning of normal lines, force
7758 the insertion of a heading after the current subtree.
7760 With two universal prefix arguments, insert the heading at the
7761 end of the grandparent subtree. For example, if point is within
7762 a 2nd-level heading, then it will insert a 2nd-level heading at
7763 the end of the 1st-level parent heading.
7765 If point is at the beginning of a headline, insert a sibling
7766 before the current headline. If point is not at the beginning,
7767 split the line and create a new headline with the text in the
7768 current line after point \(see `org-M-RET-may-split-line' on how
7769 to modify this behavior).
7771 If point is at the beginning of a normal line, turn this line
7772 into a heading.
7774 When INVISIBLE-OK is set, stop at invisible headlines when going
7775 back. This is important for non-interactive uses of the
7776 command.
7778 When optional argument TOP is non-nil, insert a level 1 heading,
7779 unconditionally."
7780 (interactive "P")
7781 (when (org-called-interactively-p 'any) (org-reveal))
7782 (let ((itemp (and (not top) (org-in-item-p)))
7783 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7784 (respect-content (or org-insert-heading-respect-content
7785 (equal arg '(4))))
7786 (initial-content ""))
7788 (cond
7790 ((or (= (buffer-size) 0)
7791 (and (not (save-excursion
7792 (and (ignore-errors (org-back-to-heading invisible-ok))
7793 (org-at-heading-p))))
7794 (or arg (not itemp))))
7795 ;; At beginning of buffer or so high up that only a heading
7796 ;; makes sense.
7797 (cond ((and (bolp) (not respect-content)) (insert "* "))
7798 ((not respect-content)
7799 (unless may-split (end-of-line))
7800 (insert "\n* "))
7801 ((re-search-forward org-outline-regexp-bol nil t)
7802 (beginning-of-line)
7803 (insert "* \n")
7804 (backward-char))
7805 (t (goto-char (point-max))
7806 (insert "\n* ")))
7807 (run-hooks 'org-insert-heading-hook))
7809 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7812 ;; Maybe move at the end of the subtree
7813 (when (equal arg '(16))
7814 (org-up-heading-safe)
7815 (org-end-of-subtree t))
7816 ;; Insert a heading
7817 (save-restriction
7818 (widen)
7819 (let* ((level nil)
7820 (on-heading (org-at-heading-p))
7821 (empty-line-p (if on-heading
7822 (org-previous-line-empty-p)
7823 ;; We will decide later
7824 nil))
7825 ;; Get a level string to fall back on.
7826 (fix-level
7827 (if (org-before-first-heading-p) "*"
7828 (save-excursion
7829 (org-back-to-heading t)
7830 (when (org-previous-line-empty-p) (setq empty-line-p t))
7831 (looking-at org-outline-regexp)
7832 (make-string (1- (length (match-string 0))) ?*))))
7833 (stars
7834 (save-excursion
7835 (condition-case nil
7836 (if top "* "
7837 (org-back-to-heading invisible-ok)
7838 (when (and (not on-heading)
7839 (featurep 'org-inlinetask)
7840 (integerp org-inlinetask-min-level)
7841 (>= (length (match-string 0))
7842 org-inlinetask-min-level))
7843 ;; Find a heading level before the inline
7844 ;; task.
7845 (while (and (setq level (org-up-heading-safe))
7846 (>= level org-inlinetask-min-level)))
7847 (if (org-at-heading-p)
7848 (org-back-to-heading invisible-ok)
7849 (error "This should not happen")))
7850 (unless (and (save-excursion
7851 (save-match-data
7852 (org-backward-heading-same-level
7853 1 invisible-ok))
7854 (= (point) (match-beginning 0)))
7855 (not (org-next-line-empty-p)))
7856 (setq empty-line-p (or empty-line-p
7857 (org-previous-line-empty-p))))
7858 (match-string 0))
7859 (error (or fix-level "* ")))))
7860 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7861 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7863 ;; If we insert after content, move there and clean up
7864 ;; whitespace.
7865 (when (and respect-content
7866 (not (looking-at-p org-outline-regexp-bol)))
7867 (if (not (org-before-first-heading-p))
7868 (org-end-of-subtree nil t)
7869 (re-search-forward org-outline-regexp-bol)
7870 (beginning-of-line 0))
7871 (skip-chars-backward " \r\t\n")
7872 (and (not (looking-back "^\\*+" (line-beginning-position)))
7873 (looking-at "[ \t]+") (replace-match ""))
7874 (unless (eobp) (forward-char 1))
7875 (when (looking-at "^\\*")
7876 (unless (bobp) (backward-char 1))
7877 (insert "\n")))
7879 ;; If we are splitting, grab the text that should be moved
7880 ;; to the new headline.
7881 (when may-split
7882 (if (org-at-heading-p)
7883 ;; This is a heading: split intelligently (keeping
7884 ;; tags).
7885 (let ((pos (point)))
7886 (beginning-of-line)
7887 (unless (looking-at org-complex-heading-regexp)
7888 (error "This should not happen"))
7889 (when (and (match-beginning 4)
7890 (> pos (match-beginning 4))
7891 (< pos (match-end 4)))
7892 (setq initial-content (buffer-substring pos (match-end 4)))
7893 (goto-char pos)
7894 (delete-region (point) (match-end 4))
7895 (if (looking-at "[ \t]*$")
7896 (replace-match "")
7897 (insert (make-string (length initial-content) ?\s)))
7898 (setq initial-content (org-trim initial-content)))
7899 (goto-char pos))
7900 ;; A normal line.
7901 (setq initial-content
7902 (org-trim
7903 (delete-and-extract-region (point) (line-end-position))))))
7905 ;; If we are at the beginning of the line, insert before it.
7906 ;; Otherwise, after it.
7907 (cond
7908 ((and (bolp) (looking-at "[ \t]*$")))
7909 ((bolp) (save-excursion (insert "\n")))
7910 (t (end-of-line)
7911 (insert "\n")))
7913 ;; Insert the new heading
7914 (insert stars)
7915 (just-one-space)
7916 (insert initial-content)
7917 (unless (and blank (org-previous-line-empty-p))
7918 (org-N-empty-lines-before-current (if blank 1 0)))
7919 ;; Adjust visibility, which may be messed up if we removed
7920 ;; blank lines while previous entry was hidden.
7921 (let ((bol (line-beginning-position)))
7922 (dolist (o (overlays-at (1- bol)))
7923 (when (and (eq (overlay-get o 'invisible) 'outline)
7924 (eq (overlay-end o) bol))
7925 (move-overlay o (overlay-start o) (1- bol)))))
7926 (run-hooks 'org-insert-heading-hook)))))))
7928 (defun org-N-empty-lines-before-current (N)
7929 "Make the number of empty lines before current exactly N.
7930 So this will delete or add empty lines."
7931 (save-excursion
7932 (beginning-of-line)
7933 (let ((p (point)))
7934 (skip-chars-backward " \r\t\n")
7935 (unless (bolp) (forward-line))
7936 (delete-region (point) p))
7937 (when (> N 0) (insert (make-string N ?\n)))))
7939 (defun org-get-heading (&optional no-tags no-todo)
7940 "Return the heading of the current entry, without the stars.
7941 When NO-TAGS is non-nil, don't include tags.
7942 When NO-TODO is non-nil, don't include TODO keywords."
7943 (save-excursion
7944 (org-back-to-heading t)
7945 (let ((case-fold-search nil))
7946 (cond
7947 ((and no-tags no-todo)
7948 (looking-at org-complex-heading-regexp)
7949 (match-string 4))
7950 (no-tags
7951 (looking-at (concat org-outline-regexp
7952 "\\(.*?\\)"
7953 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7954 (match-string 1))
7955 (no-todo
7956 (looking-at org-todo-line-regexp)
7957 (match-string 3))
7958 (t (looking-at org-heading-regexp)
7959 (match-string 2))))))
7961 (defvar orgstruct-mode) ; defined below
7963 (defun org-heading-components ()
7964 "Return the components of the current heading.
7965 This is a list with the following elements:
7966 - the level as an integer
7967 - the reduced level, different if `org-odd-levels-only' is set.
7968 - the TODO keyword, or nil
7969 - the priority character, like ?A, or nil if no priority is given
7970 - the headline text itself, or the tags string if no headline text
7971 - the tags string, or nil."
7972 (save-excursion
7973 (org-back-to-heading t)
7974 (when (let (case-fold-search)
7975 (looking-at
7976 (if orgstruct-mode
7977 org-heading-regexp
7978 org-complex-heading-regexp)))
7979 (if orgstruct-mode
7980 (list (length (match-string 1))
7981 (org-reduced-level (length (match-string 1)))
7984 (match-string 2)
7985 nil)
7986 (list (length (match-string 1))
7987 (org-reduced-level (length (match-string 1)))
7988 (match-string-no-properties 2)
7989 (and (match-end 3) (aref (match-string 3) 2))
7990 (match-string-no-properties 4)
7991 (match-string-no-properties 5))))))
7993 (defun org-get-entry ()
7994 "Get the entry text, after heading, entire subtree."
7995 (save-excursion
7996 (org-back-to-heading t)
7997 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7999 (defun org-edit-headline (&optional heading)
8000 "Edit the current headline.
8001 Set it to HEADING when provided."
8002 (interactive)
8003 (org-with-wide-buffer
8004 (org-back-to-heading t)
8005 (when (looking-at org-complex-heading-regexp)
8006 (let* ((old (match-string-no-properties 4))
8007 (new (save-match-data
8008 (org-trim (or heading (read-string "Edit: " old))))))
8009 (unless (equal old new)
8010 (if old (replace-match new t t nil 4)
8011 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
8012 (insert " " new))
8013 (org-set-tags nil t)
8014 (when (looking-at "[ \t]*$") (replace-match "")))))))
8016 (defun org-insert-heading-after-current ()
8017 "Insert a new heading with same level as current, after current subtree."
8018 (interactive)
8019 (org-back-to-heading)
8020 (org-insert-heading)
8021 (org-move-subtree-down)
8022 (end-of-line 1))
8024 (defun org-insert-heading-respect-content (&optional invisible-ok)
8025 "Insert heading with `org-insert-heading-respect-content' set to t."
8026 (interactive)
8027 (org-insert-heading '(4) invisible-ok))
8029 (defun org-insert-todo-heading-respect-content (&optional force-state)
8030 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
8031 (interactive)
8032 (org-insert-todo-heading force-state '(4)))
8034 (defun org-insert-todo-heading (arg &optional force-heading)
8035 "Insert a new heading with the same level and TODO state as current heading.
8036 If the heading has no TODO state, or if the state is DONE, use the first
8037 state (TODO by default). Also with one prefix arg, force first state. With
8038 two prefix args, force inserting at the end of the parent subtree."
8039 (interactive "P")
8040 (when (or force-heading (not (org-insert-item 'checkbox)))
8041 (org-insert-heading (or (and (equal arg '(16)) '(16))
8042 force-heading))
8043 (save-excursion
8044 (org-back-to-heading)
8045 (outline-previous-heading)
8046 (looking-at org-todo-line-regexp))
8047 (let*
8048 ((new-mark-x
8049 (if (or (equal arg '(4))
8050 (not (match-beginning 2))
8051 (member (match-string 2) org-done-keywords))
8052 (car org-todo-keywords-1)
8053 (match-string 2)))
8054 (new-mark
8056 (run-hook-with-args-until-success
8057 'org-todo-get-default-hook new-mark-x nil)
8058 new-mark-x)))
8059 (beginning-of-line 1)
8060 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
8061 (if org-treat-insert-todo-heading-as-state-change
8062 (org-todo new-mark)
8063 (insert new-mark " "))))
8064 (when org-provide-todo-statistics
8065 (org-update-parent-todo-statistics))))
8067 (defun org-insert-subheading (arg)
8068 "Insert a new subheading and demote it.
8069 Works for outline headings and for plain lists alike."
8070 (interactive "P")
8071 (org-insert-heading arg)
8072 (cond
8073 ((org-at-heading-p) (org-do-demote))
8074 ((org-at-item-p) (org-indent-item))))
8076 (defun org-insert-todo-subheading (arg)
8077 "Insert a new subheading with TODO keyword or checkbox and demote it.
8078 Works for outline headings and for plain lists alike."
8079 (interactive "P")
8080 (org-insert-todo-heading arg)
8081 (cond
8082 ((org-at-heading-p) (org-do-demote))
8083 ((org-at-item-p) (org-indent-item))))
8085 ;;; Promotion and Demotion
8087 (defvar org-after-demote-entry-hook nil
8088 "Hook run after an entry has been demoted.
8089 The cursor will be at the beginning of the entry.
8090 When a subtree is being demoted, the hook will be called for each node.")
8092 (defvar org-after-promote-entry-hook nil
8093 "Hook run after an entry has been promoted.
8094 The cursor will be at the beginning of the entry.
8095 When a subtree is being promoted, the hook will be called for each node.")
8097 (defun org-promote-subtree ()
8098 "Promote the entire subtree.
8099 See also `org-promote'."
8100 (interactive)
8101 (save-excursion
8102 (org-with-limited-levels (org-map-tree 'org-promote)))
8103 (org-fix-position-after-promote))
8105 (defun org-demote-subtree ()
8106 "Demote the entire subtree.
8107 See `org-demote' and `org-promote'."
8108 (interactive)
8109 (save-excursion
8110 (org-with-limited-levels (org-map-tree 'org-demote)))
8111 (org-fix-position-after-promote))
8113 (defun org-do-promote ()
8114 "Promote the current heading higher up the tree.
8115 If the region is active in `transient-mark-mode', promote all
8116 headings in the region."
8117 (interactive)
8118 (save-excursion
8119 (if (org-region-active-p)
8120 (org-map-region 'org-promote (region-beginning) (region-end))
8121 (org-promote)))
8122 (org-fix-position-after-promote))
8124 (defun org-do-demote ()
8125 "Demote the current heading lower down the tree.
8126 If the region is active in `transient-mark-mode', demote all
8127 headings in the region."
8128 (interactive)
8129 (save-excursion
8130 (if (org-region-active-p)
8131 (org-map-region 'org-demote (region-beginning) (region-end))
8132 (org-demote)))
8133 (org-fix-position-after-promote))
8135 (defun org-fix-position-after-promote ()
8136 "Fix cursor position and indentation after demoting/promoting."
8137 (let ((pos (point)))
8138 (when (save-excursion
8139 (beginning-of-line 1)
8140 (looking-at org-todo-line-regexp)
8141 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8142 (cond ((eobp) (insert " "))
8143 ((eolp) (insert " "))
8144 ((equal (char-after) ?\ ) (forward-char 1))))))
8146 (defun org-current-level ()
8147 "Return the level of the current entry, or nil if before the first headline.
8148 The level is the number of stars at the beginning of the
8149 headline. Use `org-reduced-level' to remove the effect of
8150 `org-odd-levels'. Unlike to `org-outline-level', this function
8151 ignores inlinetasks."
8152 (let ((level (org-with-limited-levels (org-outline-level))))
8153 (and (> level 0) level)))
8155 (defun org-get-previous-line-level ()
8156 "Return the outline depth of the last headline before the current line.
8157 Returns 0 for the first headline in the buffer, and nil if before the
8158 first headline."
8159 (and (org-current-level)
8160 (or (and (/= (line-beginning-position) (point-min))
8161 (save-excursion (beginning-of-line 0) (org-current-level)))
8162 0)))
8164 (defun org-reduced-level (l)
8165 "Compute the effective level of a heading.
8166 This takes into account the setting of `org-odd-levels-only'."
8167 (cond
8168 ((zerop l) 0)
8169 (org-odd-levels-only (1+ (floor (/ l 2))))
8170 (t l)))
8172 (defun org-level-increment ()
8173 "Return the number of stars that will be added or removed at a
8174 time to headlines when structure editing, based on the value of
8175 `org-odd-levels-only'."
8176 (if org-odd-levels-only 2 1))
8178 (defun org-get-valid-level (level &optional change)
8179 "Rectify a level change under the influence of `org-odd-levels-only'
8180 LEVEL is a current level, CHANGE is by how much the level should be
8181 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8182 even level numbers will become the next higher odd number."
8183 (if org-odd-levels-only
8184 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8185 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8186 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8187 (max 1 (+ level (or change 0)))))
8188 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8190 (defun org-promote ()
8191 "Promote the current heading higher up the tree."
8192 (org-with-wide-buffer
8193 (org-back-to-heading t)
8194 (let* ((after-change-functions (remq 'flyspell-after-change-function
8195 after-change-functions))
8196 (level (save-match-data (funcall outline-level)))
8197 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8198 (diff (abs (- level (length up-head) -1))))
8199 (cond
8200 ((and (= level 1) org-allow-promoting-top-level-subtree)
8201 (replace-match "# " nil t))
8202 ((= level 1)
8203 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8204 (t (replace-match up-head nil t)))
8205 (unless (= level 1)
8206 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8207 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8208 (run-hooks 'org-after-promote-entry-hook))))
8210 (defun org-demote ()
8211 "Demote the current heading lower down the tree."
8212 (org-with-wide-buffer
8213 (org-back-to-heading t)
8214 (let* ((after-change-functions (remq 'flyspell-after-change-function
8215 after-change-functions))
8216 (level (save-match-data (funcall outline-level)))
8217 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8218 (diff (abs (- level (length down-head) -1))))
8219 (replace-match down-head nil t)
8220 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8221 (when org-adapt-indentation (org-fixup-indentation diff))
8222 (run-hooks 'org-after-demote-entry-hook))))
8224 (defun org-cycle-level ()
8225 "Cycle the level of an empty headline through possible states.
8226 This goes first to child, then to parent, level, then up the hierarchy.
8227 After top level, it switches back to sibling level."
8228 (interactive)
8229 (let ((org-adapt-indentation nil))
8230 (when (org-point-at-end-of-empty-headline)
8231 (setq this-command 'org-cycle-level) ; Only needed for caching
8232 (let ((cur-level (org-current-level))
8233 (prev-level (org-get-previous-line-level)))
8234 (cond
8235 ;; If first headline in file, promote to top-level.
8236 ((= prev-level 0)
8237 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8238 do (org-do-promote)))
8239 ;; If same level as prev, demote one.
8240 ((= prev-level cur-level)
8241 (org-do-demote))
8242 ;; If parent is top-level, promote to top level if not already.
8243 ((= prev-level 1)
8244 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8245 do (org-do-promote)))
8246 ;; If top-level, return to prev-level.
8247 ((= cur-level 1)
8248 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8249 do (org-do-demote)))
8250 ;; If less than prev-level, promote one.
8251 ((< cur-level prev-level)
8252 (org-do-promote))
8253 ;; If deeper than prev-level, promote until higher than
8254 ;; prev-level.
8255 ((> cur-level prev-level)
8256 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8257 do (org-do-promote))))
8258 t))))
8260 (defun org-map-tree (fun)
8261 "Call FUN for every heading underneath the current one."
8262 (org-back-to-heading)
8263 (let ((level (funcall outline-level)))
8264 (save-excursion
8265 (funcall fun)
8266 (while (and (progn
8267 (outline-next-heading)
8268 (> (funcall outline-level) level))
8269 (not (eobp)))
8270 (funcall fun)))))
8272 (defun org-map-region (fun beg end)
8273 "Call FUN for every heading between BEG and END."
8274 (let ((org-ignore-region t))
8275 (save-excursion
8276 (setq end (copy-marker end))
8277 (goto-char beg)
8278 (when (and (re-search-forward org-outline-regexp-bol nil t)
8279 (< (point) end))
8280 (funcall fun))
8281 (while (and (progn
8282 (outline-next-heading)
8283 (< (point) end))
8284 (not (eobp)))
8285 (funcall fun)))))
8287 (defun org-fixup-indentation (diff)
8288 "Change the indentation in the current entry by DIFF.
8290 DIFF is an integer. Indentation is done according to the
8291 following rules:
8293 - Planning information and property drawers are always indented
8294 according to the new level of the headline;
8296 - Footnote definitions and their contents are ignored;
8298 - Inlinetasks' boundaries are not shifted;
8300 - Empty lines are ignored;
8302 - Other lines' indentation are shifted by DIFF columns, unless
8303 it would introduce a structural change in the document, in
8304 which case no shifting is done at all.
8306 Assume point is at a heading or an inlinetask beginning."
8307 (org-with-wide-buffer
8308 (narrow-to-region (line-beginning-position)
8309 (save-excursion
8310 (if (org-with-limited-levels (org-at-heading-p))
8311 (org-with-limited-levels (outline-next-heading))
8312 (org-inlinetask-goto-end))
8313 (point)))
8314 (forward-line)
8315 ;; Indent properly planning info and property drawer.
8316 (when (looking-at-p org-planning-line-re)
8317 (org-indent-line)
8318 (forward-line))
8319 (when (looking-at org-property-drawer-re)
8320 (goto-char (match-end 0))
8321 (forward-line)
8322 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8323 (catch 'no-shift
8324 (when (zerop diff) (throw 'no-shift nil))
8325 ;; If DIFF is negative, first check if a shift is possible at all
8326 ;; (e.g., it doesn't break structure). This can only happen if
8327 ;; some contents are not properly indented.
8328 (let ((case-fold-search t))
8329 (when (< diff 0)
8330 (let ((diff (- diff))
8331 (forbidden-re (concat org-outline-regexp
8332 "\\|"
8333 (substring org-footnote-definition-re 1))))
8334 (save-excursion
8335 (while (not (eobp))
8336 (cond
8337 ((looking-at-p "[ \t]*$") (forward-line))
8338 ((and (looking-at-p org-footnote-definition-re)
8339 (let ((e (org-element-at-point)))
8340 (and (eq (org-element-type e) 'footnote-definition)
8341 (goto-char (org-element-property :end e))))))
8342 ((looking-at-p org-outline-regexp) (forward-line))
8343 ;; Give up if shifting would move before column 0 or
8344 ;; if it would introduce a headline or a footnote
8345 ;; definition.
8347 (skip-chars-forward " \t")
8348 (let ((ind (current-column)))
8349 (when (or (< ind diff)
8350 (and (= ind diff) (looking-at-p forbidden-re)))
8351 (throw 'no-shift nil)))
8352 ;; Ignore contents of example blocks and source
8353 ;; blocks if their indentation is meant to be
8354 ;; preserved. Jump to block's closing line.
8355 (beginning-of-line)
8356 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8357 (let ((e (org-element-at-point)))
8358 (and (memq (org-element-type e)
8359 '(example-block src-block))
8360 (or org-src-preserve-indentation
8361 (org-element-property :preserve-indent e))
8362 (goto-char (org-element-property :end e))
8363 (progn (skip-chars-backward " \r\t\n")
8364 (beginning-of-line)
8365 t))))
8366 (forward-line))))))))
8367 ;; Shift lines but footnote definitions, inlinetasks boundaries
8368 ;; by DIFF. Also skip contents of source or example blocks
8369 ;; when indentation is meant to be preserved.
8370 (while (not (eobp))
8371 (cond
8372 ((and (looking-at-p org-footnote-definition-re)
8373 (let ((e (org-element-at-point)))
8374 (and (eq (org-element-type e) 'footnote-definition)
8375 (goto-char (org-element-property :end e))))))
8376 ((looking-at-p org-outline-regexp) (forward-line))
8377 ((looking-at-p "[ \t]*$") (forward-line))
8379 (indent-line-to (+ (org-get-indentation) diff))
8380 (beginning-of-line)
8381 (or (and (looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8382 (let ((e (org-element-at-point)))
8383 (and (memq (org-element-type e)
8384 '(example-block src-block))
8385 (or org-src-preserve-indentation
8386 (org-element-property :preserve-indent e))
8387 (goto-char (org-element-property :end e))
8388 (progn (skip-chars-backward " \r\t\n")
8389 (beginning-of-line)
8390 t))))
8391 (forward-line)))))))))
8393 (defun org-convert-to-odd-levels ()
8394 "Convert an org-mode file with all levels allowed to one with odd levels.
8395 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8396 level 5 etc."
8397 (interactive)
8398 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8399 (let ((outline-level 'org-outline-level)
8400 (org-odd-levels-only nil) n)
8401 (save-excursion
8402 (goto-char (point-min))
8403 (while (re-search-forward "^\\*\\*+ " nil t)
8404 (setq n (- (length (match-string 0)) 2))
8405 (while (>= (setq n (1- n)) 0)
8406 (org-demote))
8407 (end-of-line 1))))))
8409 (defun org-convert-to-oddeven-levels ()
8410 "Convert an org-mode file with only odd levels to one with odd/even levels.
8411 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8412 file contains a section with an even level, conversion would
8413 destroy the structure of the file. An error is signaled in this
8414 case."
8415 (interactive)
8416 (goto-char (point-min))
8417 ;; First check if there are no even levels
8418 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8419 (org-show-set-visibility 'canonical)
8420 (error "Not all levels are odd in this file. Conversion not possible"))
8421 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8422 (let ((outline-regexp org-outline-regexp)
8423 (outline-level 'org-outline-level)
8424 (org-odd-levels-only nil) n)
8425 (save-excursion
8426 (goto-char (point-min))
8427 (while (re-search-forward "^\\*\\*+ " nil t)
8428 (setq n (/ (1- (length (match-string 0))) 2))
8429 (while (>= (setq n (1- n)) 0)
8430 (org-promote))
8431 (end-of-line 1))))))
8433 (defun org-tr-level (n)
8434 "Make N odd if required."
8435 (if org-odd-levels-only (1+ (/ n 2)) n))
8437 ;;; Vertical tree motion, cutting and pasting of subtrees
8439 (defun org-move-subtree-up (&optional arg)
8440 "Move the current subtree up past ARG headlines of the same level."
8441 (interactive "p")
8442 (org-move-subtree-down (- (prefix-numeric-value arg))))
8444 (defun org-move-subtree-down (&optional arg)
8445 "Move the current subtree down past ARG headlines of the same level."
8446 (interactive "p")
8447 (setq arg (prefix-numeric-value arg))
8448 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8449 'org-get-last-sibling))
8450 (ins-point (make-marker))
8451 (cnt (abs arg))
8452 (col (current-column))
8453 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8454 ;; Select the tree
8455 (org-back-to-heading)
8456 (setq beg0 (point))
8457 (save-excursion
8458 (setq ne-beg (org-back-over-empty-lines))
8459 (setq beg (point)))
8460 (save-match-data
8461 (save-excursion (outline-end-of-heading)
8462 (setq folded (outline-invisible-p)))
8463 (progn (org-end-of-subtree nil t)
8464 (unless (eobp) (backward-char))))
8465 (outline-next-heading)
8466 (setq ne-end (org-back-over-empty-lines))
8467 (setq end (point))
8468 (goto-char beg0)
8469 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8470 ;; include less whitespace
8471 (save-excursion
8472 (goto-char beg)
8473 (forward-line (- ne-beg ne-end))
8474 (setq beg (point))))
8475 ;; Find insertion point, with error handling
8476 (while (> cnt 0)
8477 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8478 (progn (goto-char beg0)
8479 (user-error "Cannot move past superior level or buffer limit")))
8480 (setq cnt (1- cnt)))
8481 (when (> arg 0)
8482 ;; Moving forward - still need to move over subtree
8483 (org-end-of-subtree t t)
8484 (save-excursion
8485 (org-back-over-empty-lines)
8486 (or (bolp) (newline))))
8487 (setq ne-ins (org-back-over-empty-lines))
8488 (move-marker ins-point (point))
8489 (setq txt (buffer-substring beg end))
8490 (org-save-markers-in-region beg end)
8491 (delete-region beg end)
8492 (org-remove-empty-overlays-at beg)
8493 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8494 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8495 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8496 (let ((bbb (point)))
8497 (insert-before-markers txt)
8498 (org-reinstall-markers-in-region bbb)
8499 (move-marker ins-point bbb))
8500 (or (bolp) (insert "\n"))
8501 (setq ins-end (point))
8502 (goto-char ins-point)
8503 (org-skip-whitespace)
8504 (when (and (< arg 0)
8505 (org-first-sibling-p)
8506 (> ne-ins ne-beg))
8507 ;; Move whitespace back to beginning
8508 (save-excursion
8509 (goto-char ins-end)
8510 (let ((kill-whole-line t))
8511 (kill-line (- ne-ins ne-beg)) (point)))
8512 (insert (make-string (- ne-ins ne-beg) ?\n)))
8513 (move-marker ins-point nil)
8514 (if folded
8515 (outline-hide-subtree)
8516 (org-show-entry)
8517 (org-show-children)
8518 (org-cycle-hide-drawers 'children))
8519 (org-clean-visibility-after-subtree-move)
8520 ;; move back to the initial column we were at
8521 (move-to-column col)))
8523 (defvar org-subtree-clip ""
8524 "Clipboard for cut and paste of subtrees.
8525 This is actually only a copy of the kill, because we use the normal kill
8526 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8528 (defvar org-subtree-clip-folded nil
8529 "Was the last copied subtree folded?
8530 This is used to fold the tree back after pasting.")
8532 (defun org-cut-subtree (&optional n)
8533 "Cut the current subtree into the clipboard.
8534 With prefix arg N, cut this many sequential subtrees.
8535 This is a short-hand for marking the subtree and then cutting it."
8536 (interactive "p")
8537 (org-copy-subtree n 'cut))
8539 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8540 "Copy the current subtree it in the clipboard.
8541 With prefix arg N, copy this many sequential subtrees.
8542 This is a short-hand for marking the subtree and then copying it.
8543 If CUT is non-nil, actually cut the subtree.
8544 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8545 of some markers in the region, even if CUT is non-nil. This is
8546 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8547 (interactive "p")
8548 (let (beg end folded (beg0 (point)))
8549 (if (org-called-interactively-p 'any)
8550 (org-back-to-heading nil) ; take what looks like a subtree
8551 (org-back-to-heading t)) ; take what is really there
8552 (setq beg (point))
8553 (skip-chars-forward " \t\r\n")
8554 (save-match-data
8555 (if nosubtrees
8556 (outline-next-heading)
8557 (save-excursion (outline-end-of-heading)
8558 (setq folded (outline-invisible-p)))
8559 (ignore-errors (org-forward-heading-same-level (1- n) t))
8560 (org-end-of-subtree t t)))
8561 ;; Include the end of an inlinetask
8562 (when (and (featurep 'org-inlinetask)
8563 (looking-at-p (concat (org-inlinetask-outline-regexp)
8564 "END[ \t]*$")))
8565 (end-of-line))
8566 (setq end (point))
8567 (goto-char beg0)
8568 (when (> end beg)
8569 (setq org-subtree-clip-folded folded)
8570 (when (or cut force-store-markers)
8571 (org-save-markers-in-region beg end))
8572 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8573 (setq org-subtree-clip (current-kill 0))
8574 (message "%s: Subtree(s) with %d characters"
8575 (if cut "Cut" "Copied")
8576 (length org-subtree-clip)))))
8578 (defun org-paste-subtree (&optional level tree for-yank remove)
8579 "Paste the clipboard as a subtree, with modification of headline level.
8580 The entire subtree is promoted or demoted in order to match a new headline
8581 level.
8583 If the cursor is at the beginning of a headline, the same level as
8584 that headline is used to paste the tree.
8586 If not, the new level is derived from the *visible* headings
8587 before and after the insertion point, and taken to be the inferior headline
8588 level of the two. So if the previous visible heading is level 3 and the
8589 next is level 4 (or vice versa), level 4 will be used for insertion.
8590 This makes sure that the subtree remains an independent subtree and does
8591 not swallow low level entries.
8593 You can also force a different level, either by using a numeric prefix
8594 argument, or by inserting the heading marker by hand. For example, if the
8595 cursor is after \"*****\", then the tree will be shifted to level 5.
8597 If optional TREE is given, use this text instead of the kill ring.
8599 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8600 move back over whitespace before inserting, and move point to the end of
8601 the inserted text when done.
8603 When REMOVE is non-nil, remove the subtree from the clipboard."
8604 (interactive "P")
8605 (setq tree (or tree (and kill-ring (current-kill 0))))
8606 (unless (org-kill-is-subtree-p tree)
8607 (user-error "%s"
8608 (substitute-command-keys
8609 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8610 (org-with-limited-levels
8611 (let* ((visp (not (outline-invisible-p)))
8612 (txt tree)
8613 (^re_ "\\(\\*+\\)[ \t]*")
8614 (old-level (if (string-match org-outline-regexp-bol txt)
8615 (- (match-end 0) (match-beginning 0) 1)
8616 -1))
8617 (force-level (cond (level (prefix-numeric-value level))
8618 ((and (looking-at "[ \t]*$")
8619 (string-match
8620 "^\\*+$" (buffer-substring
8621 (point-at-bol) (point))))
8622 (- (match-end 0) (match-beginning 0)))
8623 ((and (bolp)
8624 (looking-at org-outline-regexp))
8625 (- (match-end 0) (point) 1))))
8626 (previous-level (save-excursion
8627 (condition-case nil
8628 (progn
8629 (outline-previous-visible-heading 1)
8630 (if (looking-at ^re_)
8631 (- (match-end 0) (match-beginning 0) 1)
8633 (error 1))))
8634 (next-level (save-excursion
8635 (condition-case nil
8636 (progn
8637 (or (looking-at org-outline-regexp)
8638 (outline-next-visible-heading 1))
8639 (if (looking-at ^re_)
8640 (- (match-end 0) (match-beginning 0) 1)
8642 (error 1))))
8643 (new-level (or force-level (max previous-level next-level)))
8644 (shift (if (or (= old-level -1)
8645 (= new-level -1)
8646 (= old-level new-level))
8648 (- new-level old-level)))
8649 (delta (if (> shift 0) -1 1))
8650 (func (if (> shift 0) 'org-demote 'org-promote))
8651 (org-odd-levels-only nil)
8652 beg end newend)
8653 ;; Remove the forced level indicator
8654 (when force-level
8655 (delete-region (point-at-bol) (point)))
8656 ;; Paste
8657 (beginning-of-line (if (bolp) 1 2))
8658 (setq beg (point))
8659 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8660 (insert-before-markers txt)
8661 (unless (string-match "\n\\'" txt) (insert "\n"))
8662 (setq newend (point))
8663 (org-reinstall-markers-in-region beg)
8664 (setq end (point))
8665 (goto-char beg)
8666 (skip-chars-forward " \t\n\r")
8667 (setq beg (point))
8668 (when (and (outline-invisible-p) visp)
8669 (save-excursion (outline-show-heading)))
8670 ;; Shift if necessary
8671 (unless (= shift 0)
8672 (save-restriction
8673 (narrow-to-region beg end)
8674 (while (not (= shift 0))
8675 (org-map-region func (point-min) (point-max))
8676 (setq shift (+ delta shift)))
8677 (goto-char (point-min))
8678 (setq newend (point-max))))
8679 (when (or (org-called-interactively-p 'interactive) for-yank)
8680 (message "Clipboard pasted as level %d subtree" new-level))
8681 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8682 kill-ring
8683 (eq org-subtree-clip (current-kill 0))
8684 org-subtree-clip-folded)
8685 ;; The tree was folded before it was killed/copied
8686 (outline-hide-subtree))
8687 (and for-yank (goto-char newend))
8688 (and remove (setq kill-ring (cdr kill-ring))))))
8690 (defun org-kill-is-subtree-p (&optional txt)
8691 "Check if the current kill is an outline subtree, or a set of trees.
8692 Returns nil if kill does not start with a headline, or if the first
8693 headline level is not the largest headline level in the tree.
8694 So this will actually accept several entries of equal levels as well,
8695 which is OK for `org-paste-subtree'.
8696 If optional TXT is given, check this string instead of the current kill."
8697 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8698 (re (org-get-limited-outline-regexp))
8699 (^re (concat "^" re))
8700 (start-level (and kill
8701 (string-match
8702 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8703 kill)
8704 (- (match-end 2) (match-beginning 2) 1)))
8705 (start (1+ (or (match-beginning 2) -1))))
8706 (if (not start-level)
8707 (progn
8708 nil) ;; does not even start with a heading
8709 (catch 'exit
8710 (while (setq start (string-match ^re kill (1+ start)))
8711 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8712 (throw 'exit nil)))
8713 t))))
8715 (defvar org-markers-to-move nil
8716 "Markers that should be moved with a cut-and-paste operation.
8717 Those markers are stored together with their positions relative to
8718 the start of the region.")
8720 (defun org-save-markers-in-region (beg end)
8721 "Check markers in region.
8722 If these markers are between BEG and END, record their position relative
8723 to BEG, so that after moving the block of text, we can put the markers back
8724 into place.
8725 This function gets called just before an entry or tree gets cut from the
8726 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8727 called immediately, to move the markers with the entries."
8728 (setq org-markers-to-move nil)
8729 (when (featurep 'org-clock)
8730 (org-clock-save-markers-for-cut-and-paste beg end))
8731 (when (featurep 'org-agenda)
8732 (org-agenda-save-markers-for-cut-and-paste beg end)))
8734 (defun org-check-and-save-marker (marker beg end)
8735 "Check if MARKER is between BEG and END.
8736 If yes, remember the marker and the distance to BEG."
8737 (when (and (marker-buffer marker)
8738 (equal (marker-buffer marker) (current-buffer))
8739 (>= marker beg) (< marker end))
8740 (push (cons marker (- marker beg)) org-markers-to-move)))
8742 (defun org-reinstall-markers-in-region (beg)
8743 "Move all remembered markers to their position relative to BEG."
8744 (dolist (x org-markers-to-move)
8745 (move-marker (car x) (+ beg (cdr x))))
8746 (setq org-markers-to-move nil))
8748 (defun org-narrow-to-subtree ()
8749 "Narrow buffer to the current subtree."
8750 (interactive)
8751 (save-excursion
8752 (save-match-data
8753 (org-with-limited-levels
8754 (narrow-to-region
8755 (progn (org-back-to-heading t) (point))
8756 (progn (org-end-of-subtree t t)
8757 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8758 (point)))))))
8760 (defun org-narrow-to-block ()
8761 "Narrow buffer to the current block."
8762 (interactive)
8763 (let* ((case-fold-search t)
8764 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8765 "^[ \t]*#\\+end_.*")))
8766 (if blockp
8767 (narrow-to-region (car blockp) (cdr blockp))
8768 (user-error "Not in a block"))))
8770 (defun org-clone-subtree-with-time-shift (n &optional shift)
8771 "Clone the task (subtree) at point N times.
8772 The clones will be inserted as siblings.
8774 In interactive use, the user will be prompted for the number of
8775 clones to be produced. If the entry has a timestamp, the user
8776 will also be prompted for a time shift, which may be a repeater
8777 as used in time stamps, for example `+3d'. To disable this,
8778 you can call the function with a universal prefix argument.
8780 When a valid repeater is given and the entry contains any time
8781 stamps, the clones will become a sequence in time, with time
8782 stamps in the subtree shifted for each clone produced. If SHIFT
8783 is nil or the empty string, time stamps will be left alone. The
8784 ID property of the original subtree is removed.
8786 If the original subtree did contain time stamps with a repeater,
8787 the following will happen:
8788 - the repeater will be removed in each clone
8789 - an additional clone will be produced, with the current, unshifted
8790 date(s) in the entry.
8791 - the original entry will be placed *after* all the clones, with
8792 repeater intact.
8793 - the start days in the repeater in the original entry will be shifted
8794 to past the last clone.
8795 In this way you can spell out a number of instances of a repeating task,
8796 and still retain the repeater to cover future instances of the task.
8798 As described above, N+1 clones are produced when the original
8799 subtree has a repeater. Setting N to 0, then, can be used to
8800 remove the repeater from a subtree and create a shifted clone
8801 with the original repeater."
8802 (interactive "nNumber of clones to produce: ")
8803 (let ((shift
8804 (or shift
8805 (if (and (not (equal current-prefix-arg '(4)))
8806 (save-excursion
8807 (re-search-forward org-ts-regexp-both
8808 (save-excursion
8809 (org-end-of-subtree t)
8810 (point)) t)))
8811 (read-from-minibuffer
8812 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8813 ""))) ;; No time shift
8814 (n-no-remove -1)
8815 (drawer-re org-drawer-regexp)
8816 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8817 beg end template task idprop
8818 shift-n shift-what doshift nmin nmax)
8819 (unless (wholenump n)
8820 (user-error "Invalid number of replications %s" n))
8821 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8822 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8823 shift)))
8824 (user-error "Invalid shift specification %s" shift))
8825 (when doshift
8826 (setq shift-n (string-to-number (match-string 1 shift))
8827 shift-what (cdr (assoc (match-string 2 shift)
8828 '(("d" . day) ("w" . week)
8829 ("m" . month) ("y" . year))))))
8830 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8831 (setq nmin 1 nmax n)
8832 (org-back-to-heading t)
8833 (setq beg (point))
8834 (setq idprop (org-entry-get nil "ID"))
8835 (org-end-of-subtree t t)
8836 (or (bolp) (insert "\n"))
8837 (setq end (point))
8838 (setq template (buffer-substring beg end))
8839 (when (and doshift
8840 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8841 (delete-region beg end)
8842 (setq end beg)
8843 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8844 (goto-char end)
8845 (cl-loop for n from nmin to nmax do
8846 ;; prepare clone
8847 (with-temp-buffer
8848 (insert template)
8849 (org-mode)
8850 (goto-char (point-min))
8851 (org-show-subtree)
8852 (and idprop (if org-clone-delete-id
8853 (org-entry-delete nil "ID")
8854 (org-id-get-create t)))
8855 (unless (= n 0)
8856 (while (re-search-forward org-clock-re nil t)
8857 (kill-whole-line))
8858 (goto-char (point-min))
8859 (while (re-search-forward drawer-re nil t)
8860 (org-remove-empty-drawer-at (point))))
8861 (goto-char (point-min))
8862 (when doshift
8863 (while (re-search-forward org-ts-regexp-both nil t)
8864 (org-timestamp-change (* n shift-n) shift-what))
8865 (unless (= n n-no-remove)
8866 (goto-char (point-min))
8867 (while (re-search-forward org-ts-regexp nil t)
8868 (save-excursion
8869 (goto-char (match-beginning 0))
8870 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8871 (delete-region (match-beginning 1) (match-end 1)))))))
8872 (setq task (buffer-string)))
8873 (insert task))
8874 (goto-char beg)))
8876 ;;; Outline Sorting
8878 (defun org-sort (with-case)
8879 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8880 Optional argument WITH-CASE means sort case-sensitively."
8881 (interactive "P")
8882 (cond
8883 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8884 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8886 (org-call-with-arg 'org-sort-entries with-case))))
8888 (defun org-sort-remove-invisible (s)
8889 "Remove invisible links from string S."
8890 (remove-text-properties 0 (length s) org-rm-props s)
8891 (while (string-match org-bracket-link-regexp s)
8892 (setq s (replace-match (if (match-end 2)
8893 (match-string 3 s)
8894 (match-string 1 s))
8895 t t s)))
8896 (let ((st (format " %s " s)))
8897 (while (string-match org-emph-re st)
8898 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8899 (setq s (substring st 1 -1)))
8902 (defvar org-priority-regexp) ; defined later in the file
8904 (defvar org-after-sorting-entries-or-items-hook nil
8905 "Hook that is run after a bunch of entries or items have been sorted.
8906 When children are sorted, the cursor is in the parent line when this
8907 hook gets called. When a region or a plain list is sorted, the cursor
8908 will be in the first entry of the sorted region/list.")
8910 (defun org-sort-entries
8911 (&optional with-case sorting-type getkey-func compare-func property)
8912 "Sort entries on a certain level of an outline tree.
8913 If there is an active region, the entries in the region are sorted.
8914 Else, if the cursor is before the first entry, sort the top-level items.
8915 Else, the children of the entry at point are sorted.
8917 Sorting can be alphabetically, numerically, by date/time as given by
8918 a time stamp, by a property, by priority order, or by a custom function.
8920 The command prompts for the sorting type unless it has been given to the
8921 function through the SORTING-TYPE argument, which needs to be a character,
8922 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8923 the precise meaning of each character:
8925 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8926 c By creation time, which is assumed to be the first inactive time stamp
8927 at the beginning of a line.
8928 d By deadline date/time.
8929 k By clocking time.
8930 n Numerically, by converting the beginning of the entry/item to a number.
8931 o By order of TODO keywords.
8932 p By priority according to the cookie.
8933 r By the value of a property.
8934 s By scheduled date/time.
8935 t By date/time, either the first active time stamp in the entry, or, if
8936 none exist, by the first inactive one.
8938 Capital letters will reverse the sort order.
8940 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8941 called with point at the beginning of the record. It must return either
8942 a string or a number that should serve as the sorting key for that record.
8944 Comparing entries ignores case by default. However, with an optional argument
8945 WITH-CASE, the sorting considers case as well.
8947 Sorting is done against the visible part of the headlines, it ignores hidden
8948 links.
8950 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8951 (interactive "P")
8952 (let ((case-func (if with-case 'identity 'downcase))
8953 (cmstr
8954 ;; The clock marker is lost when using `sort-subr', let's
8955 ;; store the clocking string.
8956 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8957 (save-excursion
8958 (goto-char org-clock-marker)
8959 (buffer-substring-no-properties (line-beginning-position)
8960 (point)))))
8961 start beg end stars re re2
8962 txt what tmp)
8963 ;; Find beginning and end of region to sort
8964 (cond
8965 ((org-region-active-p)
8966 ;; we will sort the region
8967 (setq end (region-end)
8968 what "region")
8969 (goto-char (region-beginning))
8970 (unless (org-at-heading-p) (outline-next-heading))
8971 (setq start (point)))
8972 ((or (org-at-heading-p)
8973 (ignore-errors (progn (org-back-to-heading) t)))
8974 ;; we will sort the children of the current headline
8975 (org-back-to-heading)
8976 (setq start (point)
8977 end (progn (org-end-of-subtree t t)
8978 (or (bolp) (insert "\n"))
8979 (when (>= (org-back-over-empty-lines) 1)
8980 (forward-line 1))
8981 (point))
8982 what "children")
8983 (goto-char start)
8984 (outline-show-subtree)
8985 (outline-next-heading))
8987 ;; we will sort the top-level entries in this file
8988 (goto-char (point-min))
8989 (or (org-at-heading-p) (outline-next-heading))
8990 (setq start (point))
8991 (goto-char (point-max))
8992 (beginning-of-line 1)
8993 (when (looking-at ".*?\\S-")
8994 ;; File ends in a non-white line
8995 (end-of-line 1)
8996 (insert "\n"))
8997 (setq end (point-max))
8998 (setq what "top-level")
8999 (goto-char start)
9000 (outline-show-all)))
9002 (setq beg (point))
9003 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
9005 (looking-at "\\(\\*+\\)")
9006 (setq stars (match-string 1)
9007 re (concat "^" (regexp-quote stars) " +")
9008 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
9009 txt (buffer-substring beg end))
9010 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
9011 (when (and (not (equal stars "*")) (string-match re2 txt))
9012 (user-error "Region to sort contains a level above the first entry"))
9014 (unless sorting-type
9015 (message
9016 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
9017 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
9018 A/N/P/R/O/F/T/S/D/C/K means reversed:"
9019 what)
9020 (setq sorting-type (read-char-exclusive))
9022 (unless getkey-func
9023 (and (= (downcase sorting-type) ?f)
9024 (setq getkey-func
9025 (completing-read "Sort using function: "
9026 obarray 'fboundp t nil nil))
9027 (setq getkey-func (intern getkey-func))))
9029 (and (= (downcase sorting-type) ?r)
9030 (not property)
9031 (setq property
9032 (completing-read "Property: "
9033 (mapcar #'list (org-buffer-property-keys t))
9034 nil t))))
9036 (when (member sorting-type '(?k ?K)) (org-clock-sum))
9037 (message "Sorting entries...")
9039 (save-restriction
9040 (narrow-to-region start end)
9041 (let ((dcst (downcase sorting-type))
9042 (case-fold-search nil)
9043 (now (current-time)))
9044 (sort-subr
9045 (/= dcst sorting-type)
9046 ;; This function moves to the beginning character of the "record" to
9047 ;; be sorted.
9048 (lambda nil
9049 (if (re-search-forward re nil t)
9050 (goto-char (match-beginning 0))
9051 (goto-char (point-max))))
9052 ;; This function moves to the last character of the "record" being
9053 ;; sorted.
9054 (lambda nil
9055 (save-match-data
9056 (condition-case nil
9057 (outline-forward-same-level 1)
9058 (error
9059 (goto-char (point-max))))))
9060 ;; This function returns the value that gets sorted against.
9061 (lambda nil
9062 (cond
9063 ((= dcst ?n)
9064 (if (looking-at org-complex-heading-regexp)
9065 (string-to-number (org-sort-remove-invisible (match-string 4)))
9066 nil))
9067 ((= dcst ?a)
9068 (if (looking-at org-complex-heading-regexp)
9069 (funcall case-func (org-sort-remove-invisible (match-string 4)))
9070 nil))
9071 ((= dcst ?k)
9072 (or (get-text-property (point) :org-clock-minutes) 0))
9073 ((= dcst ?t)
9074 (let ((end (save-excursion (outline-next-heading) (point))))
9075 (if (or (re-search-forward org-ts-regexp end t)
9076 (re-search-forward org-ts-regexp-both end t))
9077 (org-time-string-to-seconds (match-string 0))
9078 (float-time now))))
9079 ((= dcst ?c)
9080 (let ((end (save-excursion (outline-next-heading) (point))))
9081 (if (re-search-forward
9082 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9083 end t)
9084 (org-time-string-to-seconds (match-string 0))
9085 (float-time now))))
9086 ((= dcst ?s)
9087 (let ((end (save-excursion (outline-next-heading) (point))))
9088 (if (re-search-forward org-scheduled-time-regexp end t)
9089 (org-time-string-to-seconds (match-string 1))
9090 (float-time now))))
9091 ((= dcst ?d)
9092 (let ((end (save-excursion (outline-next-heading) (point))))
9093 (if (re-search-forward org-deadline-time-regexp end t)
9094 (org-time-string-to-seconds (match-string 1))
9095 (float-time now))))
9096 ((= dcst ?p)
9097 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9098 (string-to-char (match-string 2))
9099 org-default-priority))
9100 ((= dcst ?r)
9101 (or (org-entry-get nil property) ""))
9102 ((= dcst ?o)
9103 (when (looking-at org-complex-heading-regexp)
9104 (let* ((m (match-string 2))
9105 (s (if (member m org-done-keywords) '- '+)))
9106 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9107 ((= dcst ?f)
9108 (if getkey-func
9109 (progn
9110 (setq tmp (funcall getkey-func))
9111 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9112 tmp)
9113 (error "Invalid key function `%s'" getkey-func)))
9114 (t (error "Invalid sorting type `%c'" sorting-type))))
9116 (cond
9117 ((= dcst ?a) 'string<)
9118 ((= dcst ?f) compare-func)
9119 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9120 (run-hooks 'org-after-sorting-entries-or-items-hook)
9121 ;; Reset the clock marker if needed
9122 (when cmstr
9123 (save-excursion
9124 (goto-char start)
9125 (search-forward cmstr nil t)
9126 (move-marker org-clock-marker (point))))
9127 (message "Sorting entries...done")))
9129 ;;; The orgstruct minor mode
9131 ;; Define a minor mode which can be used in other modes in order to
9132 ;; integrate the org-mode structure editing commands.
9134 ;; This is really a hack, because the org-mode structure commands use
9135 ;; keys which normally belong to the major mode. Here is how it
9136 ;; works: The minor mode defines all the keys necessary to operate the
9137 ;; structure commands, but wraps the commands into a function which
9138 ;; tests if the cursor is currently at a headline or a plain list
9139 ;; item. If that is the case, the structure command is used,
9140 ;; temporarily setting many Org-mode variables like regular
9141 ;; expressions for filling etc. However, when any of those keys is
9142 ;; used at a different location, function uses `key-binding' to look
9143 ;; up if the key has an associated command in another currently active
9144 ;; keymap (minor modes, major mode, global), and executes that
9145 ;; command. There might be problems if any of the keys is otherwise
9146 ;; used as a prefix key.
9148 (defcustom orgstruct-heading-prefix-regexp ""
9149 "Regexp that matches the custom prefix of Org headlines in
9150 orgstruct(++)-mode."
9151 :group 'org
9152 :version "24.4"
9153 :package-version '(Org . "8.3")
9154 :type 'regexp)
9155 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9157 (defcustom orgstruct-setup-hook nil
9158 "Hook run after orgstruct-mode-map is filled."
9159 :group 'org
9160 :version "24.4"
9161 :package-version '(Org . "8.0")
9162 :type 'hook)
9164 (defvar orgstruct-initialized nil)
9166 (defvar org-local-vars nil
9167 "List of local variables, for use by `orgstruct-mode'.")
9169 ;;;###autoload
9170 (define-minor-mode orgstruct-mode
9171 "Toggle the minor mode `orgstruct-mode'.
9172 This mode is for using Org-mode structure commands in other
9173 modes. The following keys behave as if Org-mode were active, if
9174 the cursor is on a headline, or on a plain list item (both as
9175 defined by Org-mode)."
9176 nil " OrgStruct" (make-sparse-keymap)
9177 (funcall (if orgstruct-mode
9178 'add-to-invisibility-spec
9179 'remove-from-invisibility-spec)
9180 '(outline . t))
9181 (when orgstruct-mode
9182 (org-load-modules-maybe)
9183 (unless orgstruct-initialized
9184 (orgstruct-setup)
9185 (setq orgstruct-initialized t))))
9187 ;;;###autoload
9188 (defun turn-on-orgstruct ()
9189 "Unconditionally turn on `orgstruct-mode'."
9190 (orgstruct-mode 1))
9192 (defvar-local orgstruct-is-++ nil
9193 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9194 (defvar-local org-fb-vars nil)
9195 (defun orgstruct++-mode (&optional arg)
9196 "Toggle `orgstruct-mode', the enhanced version of it.
9197 In addition to setting orgstruct-mode, this also exports all
9198 indentation and autofilling variables from org-mode into the
9199 buffer. It will also recognize item context in multiline items."
9200 (interactive "P")
9201 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9202 (if (< arg 1)
9203 (progn (orgstruct-mode -1)
9204 (dolist (v org-fb-vars)
9205 (set (make-local-variable (car v))
9206 (if (eq (car-safe (cadr v)) 'quote)
9207 (cl-cadadr v)
9208 (nth 1 v)))))
9209 (orgstruct-mode 1)
9210 (setq org-fb-vars nil)
9211 (unless org-local-vars
9212 (setq org-local-vars (org-get-local-variables)))
9213 (let (var val)
9214 (dolist (x org-local-vars)
9215 (when (string-match
9216 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9217 \\|fill-prefix\\|indent-\\)"
9218 (symbol-name (car x)))
9219 (setq var (car x) val (nth 1 x))
9220 (push (list var `(quote ,(eval var))) org-fb-vars)
9221 (set (make-local-variable var)
9222 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9223 (setq-local orgstruct-is-++ t))))
9225 ;;;###autoload
9226 (defun turn-on-orgstruct++ ()
9227 "Unconditionally turn on `orgstruct++-mode'."
9228 (orgstruct++-mode 1))
9230 (defun orgstruct-error ()
9231 "Error when there is no default binding for a structure key."
9232 (interactive)
9233 (funcall (if (fboundp 'user-error)
9234 'user-error
9235 'error)
9236 "This key has no function outside structure elements"))
9238 (defun orgstruct-setup ()
9239 "Setup orgstruct keymap."
9240 (dolist (cell '((org-demote . t)
9241 (org-metaleft . t)
9242 (org-metaright . t)
9243 (org-promote . t)
9244 (org-shiftmetaleft . t)
9245 (org-shiftmetaright . t)
9246 org-backward-element
9247 org-backward-heading-same-level
9248 org-ctrl-c-ret
9249 org-ctrl-c-minus
9250 org-ctrl-c-star
9251 org-cycle
9252 org-force-cycle-archived
9253 org-forward-heading-same-level
9254 org-insert-heading
9255 org-insert-heading-respect-content
9256 org-kill-note-or-show-branches
9257 org-mark-subtree
9258 org-meta-return
9259 org-metadown
9260 org-metaup
9261 org-narrow-to-subtree
9262 org-promote-subtree
9263 org-reveal
9264 org-shiftdown
9265 org-shiftleft
9266 org-shiftmetadown
9267 org-shiftmetaup
9268 org-shiftright
9269 org-shifttab
9270 org-shifttab
9271 org-shiftup
9272 org-show-children
9273 org-show-subtree
9274 org-sort
9275 org-up-element
9276 outline-demote
9277 outline-next-visible-heading
9278 outline-previous-visible-heading
9279 outline-promote
9280 outline-up-heading))
9281 (let ((f (or (car-safe cell) cell))
9282 (disable-when-heading-prefix (cdr-safe cell)))
9283 (when (fboundp f)
9284 (let ((new-bindings))
9285 (dolist (binding (nconc (where-is-internal f org-mode-map)
9286 (where-is-internal f outline-mode-map)))
9287 (push binding new-bindings)
9288 ;; TODO use local-function-key-map
9289 (dolist (rep '(("<tab>" . "TAB")
9290 ("<return>" . "RET")
9291 ("<escape>" . "ESC")
9292 ("<delete>" . "DEL")))
9293 (setq binding (read-kbd-macro
9294 (let ((case-fold-search))
9295 (replace-regexp-in-string
9296 (regexp-quote (cdr rep))
9297 (car rep)
9298 (key-description binding)))))
9299 (cl-pushnew binding new-bindings :test 'equal)))
9300 (dolist (binding new-bindings)
9301 (let ((key (lookup-key orgstruct-mode-map binding)))
9302 (when (or (not key) (numberp key))
9303 (ignore-errors
9304 (org-defkey orgstruct-mode-map
9305 binding
9306 (orgstruct-make-binding
9307 f binding disable-when-heading-prefix))))))))))
9308 (run-hooks 'orgstruct-setup-hook))
9310 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9311 "Create a function for binding in the structure minor mode.
9312 FUN is the command to call inside a table. KEY is the key that
9313 should be checked in for a command to execute outside of tables.
9314 Non-nil `disable-when-heading-prefix' means to disable the command
9315 if `orgstruct-heading-prefix-regexp' is not empty."
9316 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9317 (let ((nname name)
9318 (i 0))
9319 (while (fboundp (intern nname))
9320 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9321 (setq name (intern nname)))
9322 (eval
9323 (let ((bindings '((org-heading-regexp
9324 (concat "^"
9325 orgstruct-heading-prefix-regexp
9326 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9327 (org-outline-regexp
9328 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9329 (org-outline-regexp-bol
9330 (concat "^" org-outline-regexp))
9331 (outline-regexp org-outline-regexp)
9332 (outline-heading-end-regexp "\n")
9333 (outline-level 'org-outline-level)
9334 (outline-heading-alist))))
9335 `(defun ,name (arg)
9336 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9337 "Outside of structure, run the binding of `"
9338 (key-description key) "'."
9339 (when disable-when-heading-prefix
9340 (concat
9341 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9342 "back to the default binding due to limitations of Org's implementation of\n"
9343 "`" (symbol-name fun) "'.")))
9344 (interactive "p")
9345 (let* ((disable
9346 ,(and disable-when-heading-prefix
9347 '(not (string= orgstruct-heading-prefix-regexp ""))))
9348 (fallback
9349 (or disable
9350 (not
9351 (let* ,bindings
9352 (org-context-p 'headline 'item
9353 ,(when (memq fun
9354 '(org-insert-heading
9355 org-insert-heading-respect-content
9356 org-meta-return))
9357 '(when orgstruct-is-++
9358 'item-body))))))))
9359 (if fallback
9360 (let* ((orgstruct-mode)
9361 (binding
9362 (let ((key ,key))
9363 (catch 'exit
9364 (dolist
9365 (rep
9366 '(nil
9367 ("<\\([^>]*\\)tab>" . "\\1TAB")
9368 ("<\\([^>]*\\)return>" . "\\1RET")
9369 ("<\\([^>]*\\)escape>" . "\\1ESC")
9370 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9371 nil)
9372 (when rep
9373 (setq key (read-kbd-macro
9374 (let ((case-fold-search))
9375 (replace-regexp-in-string
9376 (car rep)
9377 (cdr rep)
9378 (key-description key))))))
9379 (when (key-binding key)
9380 (throw 'exit (key-binding key))))))))
9381 (if (keymapp binding)
9382 (org-set-transient-map binding)
9383 (let ((func (or binding
9384 (unless disable
9385 'orgstruct-error))))
9386 (when func
9387 (call-interactively func)))))
9388 (org-run-like-in-org-mode
9389 (lambda ()
9390 (interactive)
9391 (let* ,bindings
9392 (call-interactively ',fun)))))))))
9393 name))
9395 (defun org-contextualize-keys (alist contexts)
9396 "Return valid elements in ALIST depending on CONTEXTS.
9398 `org-agenda-custom-commands' or `org-capture-templates' are the
9399 values used for ALIST, and `org-agenda-custom-commands-contexts'
9400 or `org-capture-templates-contexts' are the associated contexts
9401 definitions."
9402 (let ((contexts
9403 ;; normalize contexts
9404 (mapcar
9405 (lambda(c) (cond ((listp (cadr c))
9406 (list (car c) (car c) (nth 1 c)))
9407 ((string= "" (cadr c))
9408 (list (car c) (car c) (nth 2 c)))
9409 (t c)))
9410 contexts))
9411 (a alist) r s)
9412 ;; loop over all commands or templates
9413 (dolist (c a)
9414 (let (vrules repl)
9415 (cond
9416 ((not (assoc (car c) contexts))
9417 (push c r))
9418 ((and (assoc (car c) contexts)
9419 (setq vrules (org-contextualize-validate-key
9420 (car c) contexts)))
9421 (mapc (lambda (vr)
9422 (unless (equal (car vr) (cadr vr))
9423 (setq repl vr)))
9424 vrules)
9425 (if (not repl) (push c r)
9426 (push (cadr repl) s)
9427 (push
9428 (cons (car c)
9429 (cdr (or (assoc (cadr repl) alist)
9430 (error "Undefined key `%s' as contextual replacement for `%s'"
9431 (cadr repl) (car c)))))
9432 r))))))
9433 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9434 (delq
9436 (delete-dups
9437 (mapcar (lambda (x)
9438 (let ((tpl (car x)))
9439 (unless (delq
9441 (mapcar (lambda (y)
9442 (equal y tpl))
9444 x)))
9445 (reverse r))))))
9447 (defun org-contextualize-validate-key (key contexts)
9448 "Check CONTEXTS for agenda or capture KEY."
9449 (let (res)
9450 (dolist (r contexts)
9451 (dolist (rr (car (last r)))
9452 (when
9453 (and (equal key (car r))
9454 (if (functionp rr) (funcall rr)
9455 (or (and (eq (car rr) 'in-file)
9456 (buffer-file-name)
9457 (string-match (cdr rr) (buffer-file-name)))
9458 (and (eq (car rr) 'in-mode)
9459 (string-match (cdr rr) (symbol-name major-mode)))
9460 (and (eq (car rr) 'in-buffer)
9461 (string-match (cdr rr) (buffer-name)))
9462 (when (and (eq (car rr) 'not-in-file)
9463 (buffer-file-name))
9464 (not (string-match (cdr rr) (buffer-file-name))))
9465 (when (eq (car rr) 'not-in-mode)
9466 (not (string-match (cdr rr) (symbol-name major-mode))))
9467 (when (eq (car rr) 'not-in-buffer)
9468 (not (string-match (cdr rr) (buffer-name)))))))
9469 (push r res))))
9470 (delete-dups (delq nil res))))
9472 (defun org-context-p (&rest contexts)
9473 "Check if local context is any of CONTEXTS.
9474 Possible values in the list of contexts are `table', `headline', and `item'."
9475 (let ((pos (point)))
9476 (goto-char (point-at-bol))
9477 (prog1 (or (and (memq 'table contexts)
9478 (looking-at "[ \t]*|"))
9479 (and (memq 'headline contexts)
9480 (looking-at org-outline-regexp))
9481 (and (memq 'item contexts)
9482 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9483 (and (memq 'item-body contexts)
9484 (org-in-item-p)))
9485 (goto-char pos))))
9487 (defconst org-unique-local-variables
9488 '(org-element--cache
9489 org-element--cache-objects
9490 org-element--cache-sync-keys
9491 org-element--cache-sync-requests
9492 org-element--cache-sync-timer)
9493 "List of local variables that cannot be transferred to another buffer.")
9495 (defun org-get-local-variables ()
9496 "Return a list of all local variables in an Org mode buffer."
9497 (delq nil
9498 (mapcar
9499 (lambda (x)
9500 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9501 (name (car binding)))
9502 (and (not (get name 'org-state))
9503 (not (memq name org-unique-local-variables))
9504 (string-match-p
9505 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9506 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9507 (symbol-name name))
9508 binding)))
9509 (with-temp-buffer
9510 (org-mode)
9511 (buffer-local-variables)))))
9513 (defun org-clone-local-variables (from-buffer &optional regexp)
9514 "Clone local variables from FROM-BUFFER.
9515 Optional argument REGEXP selects variables to clone."
9516 (dolist (pair (buffer-local-variables from-buffer))
9517 (let ((name (car pair)))
9518 (when (and (symbolp name)
9519 (not (memq name org-unique-local-variables))
9520 (or (null regexp) (string-match regexp (symbol-name name))))
9521 (set (make-local-variable name) (cdr pair))))))
9523 ;;;###autoload
9524 (defun org-run-like-in-org-mode (cmd)
9525 "Run a command, pretending that the current buffer is in Org-mode.
9526 This will temporarily bind local variables that are typically bound in
9527 Org-mode to the values they have in Org-mode, and then interactively
9528 call CMD."
9529 (org-load-modules-maybe)
9530 (unless org-local-vars
9531 (setq org-local-vars (org-get-local-variables)))
9532 (let (binds)
9533 (dolist (var org-local-vars)
9534 (when (or (not (boundp (car var)))
9535 (eq (symbol-value (car var))
9536 (default-value (car var))))
9537 (push (list (car var) `(quote ,(cadr var))) binds)))
9538 (eval `(let ,binds
9539 (call-interactively (quote ,cmd))))))
9541 (defun org-get-category (&optional pos force-refresh)
9542 "Get the category applying to position POS."
9543 (save-match-data
9544 (when force-refresh (org-refresh-category-properties))
9545 (let ((pos (or pos (point))))
9546 (or (get-text-property pos 'org-category)
9547 (progn (org-refresh-category-properties)
9548 (get-text-property pos 'org-category))))))
9550 ;;; Refresh properties
9552 (defun org-refresh-properties (dprop tprop)
9553 "Refresh buffer text properties.
9554 DPROP is the drawer property and TPROP is either the
9555 corresponding text property to set, or an alist with each element
9556 being a text property (as a symbol) and a function to apply to
9557 the value of the drawer property."
9558 (let ((case-fold-search t)
9559 (inhibit-read-only t))
9560 (org-with-silent-modifications
9561 (save-excursion
9562 (save-restriction
9563 (widen)
9564 (goto-char (point-min))
9565 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9566 (org-refresh-property tprop (match-string-no-properties 1))))))))
9568 (defun org-refresh-property (tprop p)
9569 "Refresh the buffer text property TPROP from the drawer property P.
9570 The refresh happens only for the current tree (not subtree)."
9571 (unless (org-before-first-heading-p)
9572 (save-excursion
9573 (org-back-to-heading t)
9574 (if (symbolp tprop)
9575 ;; TPROP is a text property symbol
9576 (put-text-property
9577 (point) (or (outline-next-heading) (point-max)) tprop p)
9578 ;; TPROP is an alist with (properties . function) elements
9579 (dolist (al tprop)
9580 (save-excursion
9581 (put-text-property
9582 (line-beginning-position) (or (outline-next-heading) (point-max))
9583 (car al)
9584 (funcall (cdr al) p))))))))
9586 (defun org-refresh-category-properties ()
9587 "Refresh category text properties in the buffer."
9588 (let ((case-fold-search t)
9589 (inhibit-read-only t)
9590 (default-category
9591 (cond ((null org-category)
9592 (if buffer-file-name
9593 (file-name-sans-extension
9594 (file-name-nondirectory buffer-file-name))
9595 "???"))
9596 ((symbolp org-category) (symbol-name org-category))
9597 (t org-category))))
9598 (org-with-silent-modifications
9599 (org-with-wide-buffer
9600 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9601 ;; This is the default category for the buffer. If none is
9602 ;; found, fall-back to `org-category' or buffer file name.
9603 (put-text-property
9604 (point-min) (point-max)
9605 'org-category
9606 (catch 'buffer-category
9607 (goto-char (point-max))
9608 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9609 (let ((element (org-element-at-point)))
9610 (when (eq (org-element-type element) 'keyword)
9611 (throw 'buffer-category
9612 (org-element-property :value element)))))
9613 default-category))
9614 ;; Set sub-tree specific categories.
9615 (goto-char (point-min))
9616 (let ((regexp (org-re-property "CATEGORY")))
9617 (while (re-search-forward regexp nil t)
9618 (let ((value (match-string-no-properties 3)))
9619 (when (org-at-property-p)
9620 (put-text-property
9621 (save-excursion (org-back-to-heading t) (point))
9622 (save-excursion (org-end-of-subtree t t) (point))
9623 'org-category
9624 value)))))))))
9626 (defun org-refresh-stats-properties ()
9627 "Refresh stats text properties in the buffer."
9628 (let (stats)
9629 (org-with-silent-modifications
9630 (save-excursion
9631 (save-restriction
9632 (widen)
9633 (goto-char (point-min))
9634 (while (re-search-forward
9635 (concat org-outline-regexp-bol ".*"
9636 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9637 nil t)
9638 (setq stats (cond ((equal (match-string 3) "0") 0)
9639 ((match-string 2)
9640 (/ (* (string-to-number (match-string 2)) 100)
9641 (string-to-number (match-string 3))))
9642 (t (string-to-number (match-string 1)))))
9643 (org-back-to-heading t)
9644 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9645 'org-stats stats)))))))
9647 (defun org-refresh-effort-properties ()
9648 "Refresh effort properties"
9649 (org-refresh-properties
9650 org-effort-property
9651 '((effort . identity)
9652 (effort-minutes . org-duration-string-to-minutes))))
9654 ;;;; Link Stuff
9656 ;;; Link abbreviations
9658 (defun org-link-expand-abbrev (link)
9659 "Apply replacements as defined in `org-link-abbrev-alist'."
9660 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9661 (let* ((key (match-string 1 link))
9662 (as (or (assoc key org-link-abbrev-alist-local)
9663 (assoc key org-link-abbrev-alist)))
9664 (tag (and (match-end 2) (match-string 3 link)))
9665 rpl)
9666 (if (not as)
9667 link
9668 (setq rpl (cdr as))
9669 (cond
9670 ((symbolp rpl) (funcall rpl tag))
9671 ((string-match "%(\\([^)]+\\))" rpl)
9672 (replace-match
9673 (save-match-data
9674 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9675 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9676 ((string-match "%h" rpl)
9677 (replace-match (url-hexify-string (or tag "")) t t rpl))
9678 (t (concat rpl tag)))))
9679 link))
9681 ;;; Storing and inserting links
9683 (defvar org-insert-link-history nil
9684 "Minibuffer history for links inserted with `org-insert-link'.")
9686 (defvar org-stored-links nil
9687 "Contains the links stored with `org-store-link'.")
9689 (defvar org-store-link-plist nil
9690 "Plist with info about the most recently link created with `org-store-link'.")
9692 (defvar org-link-protocols nil
9693 "Link protocols added to Org-mode using `org-add-link-type'.")
9695 (defvar org-store-link-functions nil
9696 "List of functions that are called to create and store a link.
9697 Each function will be called in turn until one returns a non-nil
9698 value. Each function should check if it is responsible for creating
9699 this link (for example by looking at the major mode).
9700 If not, it must exit and return nil.
9701 If yes, it should return a non-nil value after a calling
9702 `org-store-link-props' with a list of properties and values.
9703 Special properties are:
9705 :type The link prefix, like \"http\". This must be given.
9706 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9707 This is obligatory as well.
9708 :description Optional default description for the second pair
9709 of brackets in an Org-mode link. The user can still change
9710 this when inserting this link into an Org-mode buffer.
9712 In addition to these, any additional properties can be specified
9713 and then used in capture templates.")
9715 (defun org-add-link-type (type &optional follow export)
9716 "Add TYPE to the list of `org-link-types'.
9717 Re-compute all regular expressions depending on `org-link-types'
9719 FOLLOW and EXPORT are two functions.
9721 FOLLOW should take the link path as the single argument and do whatever
9722 is necessary to follow the link, for example find a file or display
9723 a mail message.
9725 EXPORT should format the link path for export to one of the export formats.
9726 It should be a function accepting three arguments:
9728 path the path of the link, the text after the prefix (like \"http:\")
9729 desc the description of the link, if any
9730 format the export format, a symbol like `html' or `latex' or `ascii'.
9732 The function may use the FORMAT information to return different values
9733 depending on the format. The return value will be put literally into
9734 the exported file. If the return value is nil, this means Org should
9735 do what it normally does with links which do not have EXPORT defined.
9737 Org mode has a built-in default for exporting links. If you are happy with
9738 this default, there is no need to define an export function for the link
9739 type. For a simple example of an export function, see `org-bbdb.el'."
9740 (add-to-list 'org-link-types type t)
9741 (org-make-link-regexps)
9742 (org-element-update-syntax)
9743 (if (assoc type org-link-protocols)
9744 (setcdr (assoc type org-link-protocols) (list follow export))
9745 (push (list type follow export) org-link-protocols)))
9747 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9748 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9750 ;;;###autoload
9751 (defun org-store-link (arg)
9752 "\\<org-mode-map>Store an org-link to the current location.
9753 This link is added to `org-stored-links' and can later be inserted
9754 into an Org buffer with \\[org-insert-link].
9756 For some link types, a prefix ARG is interpreted.
9757 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9758 For file links, ARG negates `org-context-in-file-links'.
9760 A double prefix ARG force skipping storing functions that are not
9761 part of Org's core.
9763 A triple prefix ARG force storing a link for each line in the
9764 active region."
9765 (interactive "P")
9766 (org-load-modules-maybe)
9767 (if (and (equal arg '(64)) (org-region-active-p))
9768 (save-excursion
9769 (let ((end (region-end)))
9770 (goto-char (region-beginning))
9771 (set-mark (point))
9772 (while (< (point-at-eol) end)
9773 (move-end-of-line 1) (activate-mark)
9774 (let (current-prefix-arg)
9775 (call-interactively 'org-store-link))
9776 (move-beginning-of-line 2)
9777 (set-mark (point)))))
9778 (org-with-limited-levels
9779 (setq org-store-link-plist nil)
9780 (let (link cpltxt desc description search
9781 txt custom-id agenda-link sfuns sfunsn)
9782 (cond
9784 ;; Store a link using an external link type
9785 ((and (not (equal arg '(16)))
9786 (setq sfuns
9787 (delq
9788 nil (mapcar (lambda (f)
9789 (let (fs) (if (funcall f) (push f fs))))
9790 org-store-link-functions))
9791 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9792 (or (and (cdr sfuns)
9793 (funcall (intern
9794 (completing-read
9795 "Which function for creating the link? "
9796 sfunsn nil t (car sfunsn)))))
9797 (funcall (caar sfuns)))
9798 (setq link (plist-get org-store-link-plist :link)
9799 desc (or (plist-get org-store-link-plist
9800 :description)
9801 link))))
9803 ;; Store a link from a source code buffer.
9804 ((org-src-edit-buffer-p)
9805 (cond
9806 ((save-excursion
9807 (beginning-of-line)
9808 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9809 "[ \t]*$")))
9810 (setq link (format "(%s)" (match-string-no-properties 1))))
9811 ((org-called-interactively-p 'any)
9812 (let (label)
9813 (while (or (not label)
9814 (org-with-wide-buffer
9815 (goto-char (point-min))
9816 (re-search-forward
9817 (regexp-quote (format org-coderef-label-format label))
9818 nil t)))
9819 (when label (message "Label exists already") (sit-for 2))
9820 (setq label (read-string "Code line label: " label)))
9821 (end-of-line)
9822 (setq link (format org-coderef-label-format label))
9823 (let ((gc (- 79 (length link))))
9824 (if (< (current-column) gc) (org-move-to-column gc t)
9825 (insert " ")))
9826 (insert link)
9827 (setq link (concat "(" label ")") desc nil)))
9828 (t (setq link nil))))
9830 ;; We are in the agenda, link to referenced location
9831 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9832 (let ((m (or (get-text-property (point) 'org-hd-marker)
9833 (get-text-property (point) 'org-marker))))
9834 (when m
9835 (org-with-point-at m
9836 (setq agenda-link
9837 (if (org-called-interactively-p 'any)
9838 (call-interactively 'org-store-link)
9839 (org-store-link nil)))))))
9841 ((eq major-mode 'calendar-mode)
9842 (let ((cd (calendar-cursor-to-date)))
9843 (setq link
9844 (format-time-string
9845 (car org-time-stamp-formats)
9846 (apply 'encode-time
9847 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9848 nil nil nil))))
9849 (org-store-link-props :type "calendar" :date cd)))
9851 ((eq major-mode 'help-mode)
9852 (setq link (concat "help:" (save-excursion
9853 (goto-char (point-min))
9854 (looking-at "^[^ ]+")
9855 (match-string 0))))
9856 (org-store-link-props :type "help"))
9858 ((eq major-mode 'w3-mode)
9859 (setq cpltxt (if (and (buffer-name)
9860 (not (string-match "Untitled" (buffer-name))))
9861 (buffer-name)
9862 (url-view-url t))
9863 link (url-view-url t))
9864 (org-store-link-props :type "w3" :url (url-view-url t)))
9866 ((eq major-mode 'image-mode)
9867 (setq cpltxt (concat "file:"
9868 (abbreviate-file-name buffer-file-name))
9869 link cpltxt)
9870 (org-store-link-props :type "image" :file buffer-file-name))
9872 ;; In dired, store a link to the file of the current line
9873 ((derived-mode-p 'dired-mode)
9874 (let ((file (dired-get-filename nil t)))
9875 (setq file (if file
9876 (abbreviate-file-name
9877 (expand-file-name (dired-get-filename nil t)))
9878 ;; otherwise, no file so use current directory.
9879 default-directory))
9880 (setq cpltxt (concat "file:" file)
9881 link cpltxt)))
9883 ((setq search (run-hook-with-args-until-success
9884 'org-create-file-search-functions))
9885 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9886 "::" search))
9887 (setq cpltxt (or description link)))
9889 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9890 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9891 (cond
9892 ;; Store a link using the target at point
9893 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9894 (setq cpltxt
9895 (concat "file:"
9896 (abbreviate-file-name
9897 (buffer-file-name (buffer-base-buffer)))
9898 "::" (match-string 1))
9899 link cpltxt))
9900 ((and (featurep 'org-id)
9901 (or (eq org-id-link-to-org-use-id t)
9902 (and (org-called-interactively-p 'any)
9903 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9904 (and (eq org-id-link-to-org-use-id
9905 'create-if-interactive-and-no-custom-id)
9906 (not custom-id))))
9907 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9908 ;; Store a link using the ID at point
9909 (setq link (condition-case nil
9910 (prog1 (org-id-store-link)
9911 (setq desc (or (plist-get org-store-link-plist
9912 :description)
9913 "")))
9914 (error
9915 ;; Probably before first headline, link only to file
9916 (concat "file:"
9917 (abbreviate-file-name
9918 (buffer-file-name (buffer-base-buffer))))))))
9920 ;; Just link to current headline
9921 (setq cpltxt (concat "file:"
9922 (abbreviate-file-name
9923 (buffer-file-name (buffer-base-buffer)))))
9924 ;; Add a context search string
9925 (when (org-xor org-context-in-file-links arg)
9926 (let* ((element (org-element-at-point))
9927 (name (org-element-property :name element)))
9928 (setq txt (cond
9929 ((org-at-heading-p) nil)
9930 (name)
9931 ((org-region-active-p)
9932 (buffer-substring (region-beginning) (region-end)))))
9933 (when (or (null txt) (string-match "\\S-" txt))
9934 (setq cpltxt
9935 (concat cpltxt "::"
9936 (condition-case nil
9937 (org-make-org-heading-search-string txt)
9938 (error "")))
9939 desc (or name
9940 (nth 4 (ignore-errors (org-heading-components)))
9941 "NONE")))))
9942 (when (string-match "::\\'" cpltxt)
9943 (setq cpltxt (substring cpltxt 0 -2)))
9944 (setq link cpltxt))))
9946 ((buffer-file-name (buffer-base-buffer))
9947 ;; Just link to this file here.
9948 (setq cpltxt (concat "file:"
9949 (abbreviate-file-name
9950 (buffer-file-name (buffer-base-buffer)))))
9951 ;; Add a context string.
9952 (when (org-xor org-context-in-file-links arg)
9953 (setq txt (if (org-region-active-p)
9954 (buffer-substring (region-beginning) (region-end))
9955 (buffer-substring (point-at-bol) (point-at-eol))))
9956 ;; Only use search option if there is some text.
9957 (when (string-match "\\S-" txt)
9958 (setq cpltxt
9959 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9960 desc "NONE")))
9961 (setq link cpltxt))
9963 ((org-called-interactively-p 'interactive)
9964 (user-error "No method for storing a link from this buffer"))
9966 (t (setq link nil)))
9968 ;; We're done setting link and desc, clean up
9969 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9970 (setq link (or link cpltxt)
9971 desc (or desc cpltxt))
9972 (cond ((not desc))
9973 ((equal desc "NONE") (setq desc nil))
9974 (t (setq desc
9975 (replace-regexp-in-string
9976 org-bracket-link-analytic-regexp
9977 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9978 desc))))
9979 ;; Return the link
9980 (if (not (and (or (org-called-interactively-p 'any)
9981 executing-kbd-macro)
9982 link))
9983 (or agenda-link (and link (org-make-link-string link desc)))
9984 (push (list link desc) org-stored-links)
9985 (message "Stored: %s" (or desc link))
9986 (when custom-id
9987 (setq link (concat "file:" (abbreviate-file-name
9988 (buffer-file-name)) "::#" custom-id))
9989 (push (list link desc) org-stored-links))
9990 (car org-stored-links))))))
9992 (defun org-store-link-props (&rest plist)
9993 "Store link properties, extract names, addresses and dates."
9994 (let ((x (plist-get plist :from)))
9995 (when x
9996 (let ((adr (mail-extract-address-components x)))
9997 (setq plist (plist-put plist :fromname (car adr)))
9998 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9999 (let ((x (plist-get plist :to)))
10000 (when x
10001 (let ((adr (mail-extract-address-components x)))
10002 (setq plist (plist-put plist :toname (car adr)))
10003 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
10004 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
10005 (when x
10006 (setq plist (plist-put plist :date-timestamp
10007 (format-time-string
10008 (org-time-stamp-format t) x)))
10009 (setq plist (plist-put plist :date-timestamp-inactive
10010 (format-time-string
10011 (org-time-stamp-format t t) x)))))
10012 (let ((from (plist-get plist :from))
10013 (to (plist-get plist :to)))
10014 (when (and from to org-from-is-user-regexp)
10015 (setq plist
10016 (plist-put plist :fromto
10017 (if (string-match org-from-is-user-regexp from)
10018 (concat "to %t")
10019 (concat "from %f"))))))
10020 (setq org-store-link-plist plist))
10022 (defun org-add-link-props (&rest plist)
10023 "Add these properties to the link property list."
10024 (let (key value)
10025 (while plist
10026 (setq key (pop plist) value (pop plist))
10027 (setq org-store-link-plist
10028 (plist-put org-store-link-plist key value)))))
10030 (defun org-email-link-description (&optional fmt)
10031 "Return the description part of an email link.
10032 This takes information from `org-store-link-plist' and formats it
10033 according to FMT (default from `org-email-link-description-format')."
10034 (setq fmt (or fmt org-email-link-description-format))
10035 (let* ((p org-store-link-plist)
10036 (to (plist-get p :toaddress))
10037 (from (plist-get p :fromaddress))
10038 (table
10039 (list
10040 (cons "%c" (plist-get p :fromto))
10041 (cons "%F" (plist-get p :from))
10042 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
10043 (cons "%T" (plist-get p :to))
10044 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
10045 (cons "%s" (plist-get p :subject))
10046 (cons "%d" (plist-get p :date))
10047 (cons "%m" (plist-get p :message-id)))))
10048 (when (string-match "%c" fmt)
10049 ;; Check if the user wrote this message
10050 (if (and org-from-is-user-regexp from to
10051 (save-match-data (string-match org-from-is-user-regexp from)))
10052 (setq fmt (replace-match "to %t" t t fmt))
10053 (setq fmt (replace-match "from %f" t t fmt))))
10054 (org-replace-escapes fmt table)))
10056 (defun org-make-org-heading-search-string (&optional string)
10057 "Make search string for the current headline or STRING."
10058 (let ((s (or string
10059 (and (derived-mode-p 'org-mode)
10060 (save-excursion
10061 (org-back-to-heading t)
10062 (org-element-property :raw-value (org-element-at-point))))))
10063 (lines org-context-in-file-links))
10064 (or string (setq s (concat "*" s))) ; Add * for headlines
10065 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
10066 (when (and string (integerp lines) (> lines 0))
10067 (let ((slines (org-split-string s "\n")))
10068 (when (< lines (length slines))
10069 (setq s (mapconcat
10070 'identity
10071 (reverse (nthcdr (- (length slines) lines)
10072 (reverse slines))) "\n")))))
10073 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10075 (defun org-make-link-string (link &optional description)
10076 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10077 (unless (org-string-nw-p link) (error "Empty link"))
10078 (let ((uri (cond ((string-match org-link-types-re link)
10079 (concat (match-string 1 link)
10080 (org-link-escape (substring link (match-end 1)))))
10081 ;; For readability, url-encode internal links only
10082 ;; when absolutely needed (i.e, when they contain
10083 ;; square brackets). File links however, are
10084 ;; encoded since, e.g., spaces are significant.
10085 ((or (file-name-absolute-p link)
10086 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10087 (org-link-escape link))
10088 (t link)))
10089 (description
10090 (and (org-string-nw-p description)
10091 ;; Remove brackets from description, as they are fatal.
10092 (replace-regexp-in-string
10093 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10094 (org-trim description)))))
10095 (format "[[%s]%s]"
10097 (if description (format "[%s]" description) ""))))
10099 (defconst org-link-escape-chars
10100 ;;%20 %5B %5D %25
10101 '(?\s ?\[ ?\] ?%)
10102 "List of characters that should be escaped in a link when stored to Org.
10103 This is the list that is used for internal purposes.")
10105 (defconst org-link-escape-chars-browser
10106 ;;%20 %22
10107 '(?\s ?\")
10108 "List of characters to be escaped before handing over to the browser.
10109 If you consider using this constant then you probably want to use
10110 the function `org-link-escape-browser' instead. See there why
10111 this constant is a candidate to be removed once Org drops support
10112 for Emacs 24.1 and 24.2.")
10114 (defun org-link-escape (text &optional table merge)
10115 "Return percent escaped representation of TEXT.
10116 TEXT is a string with the text to escape.
10117 Optional argument TABLE is a list with characters that should be
10118 escaped. When nil, `org-link-escape-chars' is used.
10119 If optional argument MERGE is set, merge TABLE into
10120 `org-link-escape-chars'."
10121 (let ((characters-to-encode
10122 (cond ((null table) org-link-escape-chars)
10123 (merge (append org-link-escape-chars table))
10124 (t table))))
10125 (mapconcat
10126 (lambda (c)
10127 (if (or (memq c characters-to-encode)
10128 (and org-url-hexify-p (or (< c 32) (> c 126))))
10129 (mapconcat (lambda (e) (format "%%%.2X" e))
10130 (or (encode-coding-char c 'utf-8)
10131 (error "Unable to percent escape character: %c" c))
10133 (char-to-string c)))
10134 text "")))
10136 (defun org-link-escape-browser (text)
10137 "Escape some characters before handing over to the browser.
10138 This function is a candidate to be removed together with the
10139 constant `org-link-escape-chars-browser' once Org drops support
10140 for Emacs 24.1 and 24.2. All calls to this function will have to
10141 be replaced with `url-encode-url' which is available since Emacs
10142 24.3.1."
10143 ;; Example with the Org link
10144 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10145 ;; to open the browser with +subject:"Release 8.2" filled into the
10146 ;; query field: In this case the variable TEXT contains the
10147 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10148 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10149 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10150 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10151 (if (fboundp 'url-encode-url)
10152 (url-encode-url text)
10153 (if (org-string-match-p
10154 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10155 text)
10156 (org-link-escape text org-link-escape-chars-browser)
10157 text)))
10159 (defun org-link-unescape (str)
10160 "Unhex hexified Unicode parts in string STR.
10161 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10162 reciprocal of `org-link-escape', which see."
10163 (if (org-string-nw-p str)
10164 (replace-regexp-in-string
10165 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10166 str))
10168 (defun org-link-unescape-compound (hex)
10169 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10170 Note: this function also decodes single byte encodings like
10171 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10172 (save-match-data
10173 (let* ((bytes (cdr (split-string hex "%")))
10174 (ret "")
10175 (eat 0)
10176 (sum 0))
10177 (while bytes
10178 (let* ((val (string-to-number (pop bytes) 16))
10179 (shift-xor
10180 (if (= 0 eat)
10181 (cond
10182 ((>= val 252) (cons 6 252))
10183 ((>= val 248) (cons 5 248))
10184 ((>= val 240) (cons 4 240))
10185 ((>= val 224) (cons 3 224))
10186 ((>= val 192) (cons 2 192))
10187 (t (cons 0 0)))
10188 (cons 6 128))))
10189 (when (>= val 192) (setq eat (car shift-xor)))
10190 (setq val (logxor val (cdr shift-xor)))
10191 (setq sum (+ (lsh sum (car shift-xor)) val))
10192 (when (> eat 0) (setq eat (- eat 1)))
10193 (cond
10194 ((= 0 eat) ;multi byte
10195 (setq ret (concat ret (org-char-to-string sum)))
10196 (setq sum 0))
10197 ((not bytes) ; single byte(s)
10198 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10199 ret)))
10201 (defun org-link-unescape-single-byte-sequence (hex)
10202 "Unhexify hex-encoded single byte character sequences."
10203 (mapconcat (lambda (byte)
10204 (char-to-string (string-to-number byte 16)))
10205 (cdr (split-string hex "%")) ""))
10207 (defun org-xor (a b)
10208 "Exclusive or."
10209 (if a (not b) b))
10211 (defun org-fixup-message-id-for-http (s)
10212 "Replace special characters in a message id, so it can be used in an http query."
10213 (when (string-match "%" s)
10214 (setq s (mapconcat (lambda (c)
10215 (if (eq c ?%)
10216 "%25"
10217 (char-to-string c)))
10218 s "")))
10219 (while (string-match "<" s)
10220 (setq s (replace-match "%3C" t t s)))
10221 (while (string-match ">" s)
10222 (setq s (replace-match "%3E" t t s)))
10223 (while (string-match "@" s)
10224 (setq s (replace-match "%40" t t s)))
10227 (defun org-link-prettify (link)
10228 "Return a human-readable representation of LINK.
10229 The car of LINK must be a raw link.
10230 The cdr of LINK must be either a link description or nil."
10231 (let ((desc (or (cadr link) "<no description>")))
10232 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10233 "<" (car link) ">")))
10235 ;;;###autoload
10236 (defun org-insert-link-global ()
10237 "Insert a link like Org-mode does.
10238 This command can be called in any mode to insert a link in Org-mode syntax."
10239 (interactive)
10240 (org-load-modules-maybe)
10241 (org-run-like-in-org-mode 'org-insert-link))
10243 (defun org-insert-all-links (arg &optional pre post)
10244 "Insert all links in `org-stored-links'.
10245 When a universal prefix, do not delete the links from `org-stored-links'.
10246 When `ARG' is a number, insert the last N link(s).
10247 `PRE' and `POST' are optional arguments to define a string to
10248 prepend or to append."
10249 (interactive "P")
10250 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10251 (links (copy-sequence org-stored-links))
10252 (pr (or pre "- "))
10253 (po (or post "\n"))
10254 (cnt 1) l)
10255 (if (null org-stored-links)
10256 (message "No link to insert")
10257 (while (and (or (listp arg) (>= arg cnt))
10258 (setq l (if (listp arg)
10259 (pop links)
10260 (pop org-stored-links))))
10261 (setq cnt (1+ cnt))
10262 (insert pr)
10263 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10264 (insert po)))))
10266 (defun org-insert-last-stored-link (arg)
10267 "Insert the last link stored in `org-stored-links'."
10268 (interactive "p")
10269 (org-insert-all-links arg "" "\n"))
10271 (defun org-link-fontify-links-to-this-file ()
10272 "Fontify links to the current file in `org-stored-links'."
10273 (let ((f (buffer-file-name)) a b)
10274 (setq a (mapcar (lambda(l)
10275 (let ((ll (car l)))
10276 (when (and (string-match "^file:\\(.+\\)::" ll)
10277 (equal f (expand-file-name (match-string 1 ll))))
10278 ll)))
10279 org-stored-links))
10280 (when (featurep 'org-id)
10281 (setq b (mapcar (lambda(l)
10282 (let ((ll (car l)))
10283 (when (and (string-match "^id:\\(.+\\)$" ll)
10284 (equal f (expand-file-name
10285 (or (org-id-find-id-file
10286 (match-string 1 ll)) ""))))
10287 ll)))
10288 org-stored-links)))
10289 (mapcar (lambda(l)
10290 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10291 (delq nil (append a b)))))
10293 (defvar org--links-history nil)
10294 (defun org-insert-link (&optional complete-file link-location default-description)
10295 "Insert a link. At the prompt, enter the link.
10297 Completion can be used to insert any of the link protocol prefixes like
10298 http or ftp in use.
10300 The history can be used to select a link previously stored with
10301 `org-store-link'. When the empty string is entered (i.e. if you just
10302 press RET at the prompt), the link defaults to the most recently
10303 stored link. As SPC triggers completion in the minibuffer, you need to
10304 use M-SPC or C-q SPC to force the insertion of a space character.
10306 You will also be prompted for a description, and if one is given, it will
10307 be displayed in the buffer instead of the link.
10309 If there is already a link at point, this command will allow you to edit link
10310 and description parts.
10312 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10313 be selected using completion. The path to the file will be relative to the
10314 current directory if the file is in the current directory or a subdirectory.
10315 Otherwise, the link will be the absolute path as completed in the minibuffer
10316 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10317 option `org-link-file-path-type'.
10319 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10320 the current directory or below.
10322 With three \\[universal-argument] prefixes, negate the meaning of
10323 `org-keep-stored-link-after-insertion'.
10325 If `org-make-link-description-function' is non-nil, this function will be
10326 called with the link target, and the result will be the default
10327 link description.
10329 If the LINK-LOCATION parameter is non-nil, this value will be
10330 used as the link location instead of reading one interactively.
10332 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10333 be used as the default description."
10334 (interactive "P")
10335 (let* ((wcf (current-window-configuration))
10336 (origbuf (current-buffer))
10337 (region (when (org-region-active-p)
10338 (buffer-substring (region-beginning) (region-end))))
10339 (remove (and region (list (region-beginning) (region-end))))
10340 (desc region)
10341 (link link-location)
10342 (abbrevs org-link-abbrev-alist-local)
10343 entry all-prefixes auto-desc)
10344 (cond
10345 (link-location) ; specified by arg, just use it.
10346 ((org-in-regexp org-bracket-link-regexp 1)
10347 ;; We do have a link at point, and we are going to edit it.
10348 (setq remove (list (match-beginning 0) (match-end 0)))
10349 (setq desc (when (match-end 3) (match-string-no-properties 3)))
10350 (setq link (read-string "Link: "
10351 (org-link-unescape
10352 (match-string-no-properties 1)))))
10353 ((or (org-in-regexp org-angle-link-re)
10354 (org-in-regexp org-plain-link-re))
10355 ;; Convert to bracket link
10356 (setq remove (list (match-beginning 0) (match-end 0))
10357 link (read-string "Link: "
10358 (org-remove-angle-brackets (match-string 0)))))
10359 ((member complete-file '((4) (16)))
10360 ;; Completing read for file names.
10361 (setq link (org-file-complete-link complete-file)))
10363 ;; Read link, with completion for stored links.
10364 (org-link-fontify-links-to-this-file)
10365 (org-switch-to-buffer-other-window "*Org Links*")
10366 (with-current-buffer "*Org Links*"
10367 (erase-buffer)
10368 (insert "Insert a link.
10369 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10370 (when org-stored-links
10371 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10372 (insert (mapconcat 'org-link-prettify
10373 (reverse org-stored-links) "\n")))
10374 (goto-char (point-min)))
10375 (let ((cw (selected-window)))
10376 (select-window (get-buffer-window "*Org Links*" 'visible))
10377 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10378 (unless (pos-visible-in-window-p (point-max))
10379 (org-fit-window-to-buffer))
10380 (and (window-live-p cw) (select-window cw)))
10381 (setq all-prefixes (append (mapcar 'car abbrevs)
10382 (mapcar 'car org-link-abbrev-alist)
10383 org-link-types))
10384 (unwind-protect
10385 ;; Fake a link history, containing the stored links.
10386 (let ((org--links-history
10387 (append (mapcar #'car org-stored-links)
10388 org-insert-link-history)))
10389 (setq link
10390 (org-completing-read
10391 "Link: "
10392 (append
10393 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10394 (mapcar #'car org-stored-links))
10395 nil nil nil
10396 'org--links-history
10397 (caar org-stored-links)))
10398 (unless (org-string-nw-p link) (user-error "No link selected"))
10399 (dolist (l org-stored-links)
10400 (when (equal link (cadr l))
10401 (setq link (car l))
10402 (setq auto-desc t)))
10403 (when (or (member link all-prefixes)
10404 (and (equal ":" (substring link -1))
10405 (member (substring link 0 -1) all-prefixes)
10406 (setq link (substring link 0 -1))))
10407 (setq link (with-current-buffer origbuf
10408 (org-link-try-special-completion link)))))
10409 (set-window-configuration wcf)
10410 (kill-buffer "*Org Links*"))
10411 (setq entry (assoc link org-stored-links))
10412 (or entry (push link org-insert-link-history))
10413 (setq desc (or desc (nth 1 entry)))))
10415 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10416 (not org-keep-stored-link-after-insertion))
10417 (setq org-stored-links (delq (assoc link org-stored-links)
10418 org-stored-links)))
10420 (when (and (string-match org-plain-link-re link)
10421 (not (string-match org-ts-regexp link)))
10422 ;; URL-like link, normalize the use of angular brackets.
10423 (setq link (org-remove-angle-brackets link)))
10425 ;; Check if we are linking to the current file with a search
10426 ;; option If yes, simplify the link by using only the search
10427 ;; option.
10428 (when (and buffer-file-name
10429 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10430 (let* ((path (match-string 1 link))
10431 (case-fold-search nil)
10432 (search (match-string 2 link)))
10433 (save-match-data
10434 (when (equal (file-truename buffer-file-name) (file-truename path))
10435 ;; We are linking to this same file, with a search option
10436 (setq link search)))))
10438 ;; Check if we can/should use a relative path. If yes, simplify the link
10439 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10440 (let* ((type (match-string 1 link))
10441 (path (match-string 2 link))
10442 (origpath path)
10443 (case-fold-search nil))
10444 (cond
10445 ((or (eq org-link-file-path-type 'absolute)
10446 (equal complete-file '(16)))
10447 (setq path (abbreviate-file-name (expand-file-name path))))
10448 ((eq org-link-file-path-type 'noabbrev)
10449 (setq path (expand-file-name path)))
10450 ((eq org-link-file-path-type 'relative)
10451 (setq path (file-relative-name path)))
10453 (save-match-data
10454 (if (string-match (concat "^" (regexp-quote
10455 (expand-file-name
10456 (file-name-as-directory
10457 default-directory))))
10458 (expand-file-name path))
10459 ;; We are linking a file with relative path name.
10460 (setq path (substring (expand-file-name path)
10461 (match-end 0)))
10462 (setq path (abbreviate-file-name (expand-file-name path)))))))
10463 (setq link (concat type path))
10464 (when (equal desc origpath)
10465 (setq desc path))))
10467 (if org-make-link-description-function
10468 (setq desc
10469 (or (condition-case nil
10470 (funcall org-make-link-description-function link desc)
10471 (error (progn (message "Can't get link description from `%s'"
10472 (symbol-name org-make-link-description-function))
10473 (sit-for 2) nil)))
10474 (read-string "Description: " default-description)))
10475 (if default-description (setq desc default-description)
10476 (setq desc (or (and auto-desc desc)
10477 (read-string "Description: " desc)))))
10479 (unless (string-match "\\S-" desc) (setq desc nil))
10480 (when remove (apply 'delete-region remove))
10481 (insert (org-make-link-string link desc))
10482 ;; Redisplay so as the new link has proper invisible characters.
10483 (sit-for 0)))
10485 (defun org-link-try-special-completion (type)
10486 "If there is completion support for link type TYPE, offer it."
10487 (let ((fun (intern (concat "org-" type "-complete-link"))))
10488 (if (functionp fun)
10489 (funcall fun)
10490 (read-string "Link (no completion support): " (concat type ":")))))
10492 (defun org-file-complete-link (&optional arg)
10493 "Create a file link using completion."
10494 (let ((file (read-file-name "File: "))
10495 (pwd (file-name-as-directory (expand-file-name ".")))
10496 (pwd1 (file-name-as-directory (abbreviate-file-name
10497 (expand-file-name ".")))))
10498 (cond ((equal arg '(16))
10499 (concat "file:"
10500 (abbreviate-file-name (expand-file-name file))))
10501 ((string-match
10502 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10503 (concat "file:" (match-string 1 file)))
10504 ((string-match
10505 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10506 (expand-file-name file))
10507 (concat "file:"
10508 (match-string 1 (expand-file-name file))))
10509 (t (concat "file:" file)))))
10511 (defun org-completing-read (&rest args)
10512 "Completing-read with SPACE being a normal character."
10513 (let ((enable-recursive-minibuffers t)
10514 (minibuffer-local-completion-map
10515 (copy-keymap minibuffer-local-completion-map)))
10516 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10517 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10518 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10519 'org-time-stamp-inactive)
10520 (apply #'completing-read args)))
10522 (define-obsolete-function-alias
10523 'org-completing-read-no-i 'completing-read "Org 9.0")
10524 (define-obsolete-function-alias
10525 'org-icompleting-read 'completing-read "Org 9.0")
10526 (define-obsolete-function-alias
10527 'org-iread-file-name 'read-file-name "Org 9.0")
10529 ;;; Opening/following a link
10531 (defvar org-link-search-failed nil)
10533 (defvar org-open-link-functions nil
10534 "Hook for functions finding a plain text link.
10535 These functions must take a single argument, the link content.
10536 They will be called for links that look like [[link text][description]]
10537 when LINK TEXT does not have a protocol like \"http:\" and does not look
10538 like a filename (e.g. \"./blue.png\").
10540 These functions will be called *before* Org attempts to resolve the
10541 link by doing text searches in the current buffer - so if you want a
10542 link \"[[target]]\" to still find \"<<target>>\", your function should
10543 handle this as a special case.
10545 When the function does handle the link, it must return a non-nil value.
10546 If it decides that it is not responsible for this link, it must return
10547 nil to indicate that that Org-mode can continue with other options
10548 like exact and fuzzy text search.")
10550 (defun org-next-link (&optional search-backward)
10551 "Move forward to the next link.
10552 If the link is in hidden text, expose it."
10553 (interactive "P")
10554 (when (and org-link-search-failed (eq this-command last-command))
10555 (goto-char (point-min))
10556 (message "Link search wrapped back to beginning of buffer"))
10557 (setq org-link-search-failed nil)
10558 (let* ((pos (point))
10559 (ct (org-context))
10560 (a (assoc :link ct))
10561 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10562 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10563 ((looking-at org-any-link-re)
10564 ;; Don't stay stuck at link without an org-link face
10565 (forward-char (if search-backward -1 1))))
10566 (if (funcall srch-fun org-any-link-re nil t)
10567 (progn
10568 (goto-char (match-beginning 0))
10569 (when (outline-invisible-p) (org-show-context)))
10570 (goto-char pos)
10571 (setq org-link-search-failed t)
10572 (message "No further link found"))))
10574 (defun org-previous-link ()
10575 "Move backward to the previous link.
10576 If the link is in hidden text, expose it."
10577 (interactive)
10578 (funcall 'org-next-link t))
10580 (defun org-translate-link (s)
10581 "Translate a link string if a translation function has been defined."
10582 (with-temp-buffer
10583 (insert (org-trim s))
10584 (org-trim (org-element-interpret-data (org-element-context)))))
10586 (defun org-translate-link-from-planner (type path)
10587 "Translate a link from Emacs Planner syntax so that Org can follow it.
10588 This is still an experimental function, your mileage may vary."
10589 (cond
10590 ((member type '("http" "https" "news" "ftp"))
10591 ;; standard Internet links are the same.
10592 nil)
10593 ((and (equal type "irc") (string-match "^//" path))
10594 ;; Planner has two / at the beginning of an irc link, we have 1.
10595 ;; We should have zero, actually....
10596 (setq path (substring path 1)))
10597 ((and (equal type "lisp") (string-match "^/" path))
10598 ;; Planner has a slash, we do not.
10599 (setq type "elisp" path (substring path 1)))
10600 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10601 ;; A typical message link. Planner has the id after the final slash,
10602 ;; we separate it with a hash mark
10603 (setq path (concat (match-string 1 path) "#"
10604 (org-remove-angle-brackets (match-string 2 path))))))
10605 (cons type path))
10607 (defun org-find-file-at-mouse (ev)
10608 "Open file link or URL at mouse."
10609 (interactive "e")
10610 (mouse-set-point ev)
10611 (org-open-at-point 'in-emacs))
10613 (defun org-open-at-mouse (ev)
10614 "Open file link or URL at mouse.
10615 See the docstring of `org-open-file' for details."
10616 (interactive "e")
10617 (mouse-set-point ev)
10618 (when (eq major-mode 'org-agenda-mode)
10619 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10620 (org-open-at-point))
10622 (defvar org-window-config-before-follow-link nil
10623 "The window configuration before following a link.
10624 This is saved in case the need arises to restore it.")
10626 ;;;###autoload
10627 (defun org-open-at-point-global ()
10628 "Follow a link or time-stamp like Org mode does.
10629 This command can be called in any mode to follow an external link
10630 or a time-stamp that has Org mode syntax. Its behavior is
10631 undefined when called on internal links (e.g., fuzzy links).
10632 Raise an error when there is nothing to follow. "
10633 (interactive)
10634 (cond ((org-in-regexp org-any-link-re)
10635 (org-open-link-from-string (match-string-no-properties 0)))
10636 ((or (org-in-regexp org-ts-regexp-both nil t)
10637 (org-in-regexp org-tsr-regexp-both nil t))
10638 (org-follow-timestamp-link))
10639 (t (user-error "No link found"))))
10641 ;;;###autoload
10642 (defun org-open-link-from-string (s &optional arg reference-buffer)
10643 "Open a link in the string S, as if it was in Org-mode."
10644 (interactive "sLink: \nP")
10645 (let ((reference-buffer (or reference-buffer (current-buffer))))
10646 (with-temp-buffer
10647 (let ((org-inhibit-startup (not reference-buffer)))
10648 (org-mode)
10649 (insert s)
10650 (goto-char (point-min))
10651 (when reference-buffer
10652 (setq org-link-abbrev-alist-local
10653 (with-current-buffer reference-buffer
10654 org-link-abbrev-alist-local)))
10655 (org-open-at-point arg reference-buffer)))))
10657 (defvar org-open-at-point-functions nil
10658 "Hook that is run when following a link at point.
10660 Functions in this hook must return t if they identify and follow
10661 a link at point. If they don't find anything interesting at point,
10662 they must return nil.")
10664 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10665 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10666 (defun org-open-at-point (&optional arg reference-buffer)
10667 "Open link, timestamp, footnote or tags at point.
10669 When point is on a link, follow it. Normally, files will be
10670 opened by an appropriate application. If the optional prefix
10671 argument ARG is non-nil, Emacs will visit the file. With
10672 a double prefix argument, try to open outside of Emacs, in the
10673 application the system uses for this file type.
10675 When point is on a timestamp, open the agenda at the day
10676 specified.
10678 When point is a footnote definition, move to the first reference
10679 found. If it is on a reference, move to the associated
10680 definition.
10682 When point is on a headline, display a list of every link in the
10683 entry, so it is possible to pick one, or all, of them. If point
10684 is on a tag, call `org-tags-view' instead.
10686 When optional argument REFERENCE-BUFFER is non-nil, it should
10687 specify a buffer from where the link search should happen. This
10688 is used internally by `org-open-link-from-string'.
10690 On top of syntactically correct links, this function will open
10691 the link at point in comments or comment blocks and the first
10692 link in a property drawer line."
10693 (interactive "P")
10694 ;; On a code block, open block's results.
10695 (unless (call-interactively 'org-babel-open-src-block-result)
10696 (org-load-modules-maybe)
10697 (setq org-window-config-before-follow-link (current-window-configuration))
10698 (org-remove-occur-highlights nil nil t)
10699 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10700 (let* ((context
10701 ;; Only consider supported types, even if they are not
10702 ;; the closest one.
10703 (org-element-lineage
10704 (org-element-context)
10705 '(clock comment comment-block footnote-definition
10706 footnote-reference headline inlinetask keyword link
10707 node-property timestamp)
10709 (type (org-element-type context))
10710 (value (org-element-property :value context)))
10711 (cond
10712 ((not context) (user-error "No link found"))
10713 ;; Exception: open timestamps and links in properties
10714 ;; drawers, keywords and comments.
10715 ((memq type '(comment comment-block keyword node-property))
10716 (call-interactively #'org-open-at-point-global))
10717 ;; On a headline or an inlinetask, but not on a timestamp,
10718 ;; a link, a footnote reference or on tags.
10719 ((and (memq type '(headline inlinetask))
10720 ;; Not on tags.
10721 (progn (save-excursion (beginning-of-line)
10722 (looking-at org-complex-heading-regexp))
10723 (or (not (match-beginning 5))
10724 (< (point) (match-beginning 5)))))
10725 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10726 (links (car data))
10727 (links-end (cdr data)))
10728 (if links
10729 (dolist (link (if (stringp links) (list links) links))
10730 (search-forward link nil links-end)
10731 (goto-char (match-beginning 0))
10732 (org-open-at-point))
10733 (require 'org-attach)
10734 (org-attach-reveal 'if-exists))))
10735 ;; On a clock line, make sure point is on the timestamp
10736 ;; before opening it.
10737 ((and (eq type 'clock)
10738 value
10739 (>= (point) (org-element-property :begin value))
10740 (<= (point) (org-element-property :end value)))
10741 (org-follow-timestamp-link))
10742 ;; Do nothing on white spaces after an object.
10743 ((>= (point)
10744 (save-excursion
10745 (goto-char (org-element-property :end context))
10746 (skip-chars-backward " \t")
10747 (point)))
10748 (user-error "No link found"))
10749 ((eq type 'timestamp) (org-follow-timestamp-link))
10750 ;; On tags within a headline or an inlinetask.
10751 ((and (memq type '(headline inlinetask))
10752 (progn (save-excursion (beginning-of-line)
10753 (looking-at org-complex-heading-regexp))
10754 (and (match-beginning 5)
10755 (>= (point) (match-beginning 5)))))
10756 (org-tags-view arg (substring (match-string 5) 0 -1)))
10757 ((eq type 'link)
10758 ;; When link is located within the description of another
10759 ;; link (e.g., an inline image), always open the parent
10760 ;; link.
10761 (let*((link (let ((up (org-element-property :parent context)))
10762 (if (eq (org-element-type up) 'link) up context)))
10763 (type (org-element-property :type link))
10764 (path (org-link-unescape (org-element-property :path link))))
10765 ;; Switch back to REFERENCE-BUFFER needed when called in
10766 ;; a temporary buffer through `org-open-link-from-string'.
10767 (with-current-buffer (or reference-buffer (current-buffer))
10768 (cond
10769 ((equal type "file")
10770 (if (string-match "[*?{]" (file-name-nondirectory path))
10771 (dired path)
10772 ;; Look into `org-link-protocols' in order to find
10773 ;; a DEDICATED-FUNCTION to open file. The function
10774 ;; will be applied on raw link instead of parsed
10775 ;; link due to the limitation in `org-add-link-type'
10776 ;; ("open" function called with a single argument).
10777 ;; If no such function is found, fallback to
10778 ;; `org-open-file'.
10780 ;; Note : "file+emacs" and "file+sys" types are
10781 ;; hard-coded in order to escape the previous
10782 ;; limitation.
10783 (let* ((option (org-element-property :search-option link))
10784 (app (org-element-property :application link))
10785 (dedicated-function
10786 (nth 1 (assoc app org-link-protocols))))
10787 (if dedicated-function
10788 (funcall dedicated-function
10789 (concat path
10790 (and option (concat "::" option))))
10791 (apply #'org-open-file
10792 path
10793 (cond (arg)
10794 ((equal app "emacs") 'emacs)
10795 ((equal app "sys") 'system))
10796 (cond ((not option) nil)
10797 ((org-string-match-p "\\`[0-9]+\\'" option)
10798 (list (string-to-number option)))
10799 (t (list nil
10800 (org-link-unescape option)))))))))
10801 ((assoc type org-link-protocols)
10802 (funcall (nth 1 (assoc type org-link-protocols)) path))
10803 ((equal type "help")
10804 (let ((f-or-v (intern path)))
10805 (cond ((fboundp f-or-v) (describe-function f-or-v))
10806 ((boundp f-or-v) (describe-variable f-or-v))
10807 (t (error "Not a known function or variable")))))
10808 ((member type '("http" "https" "ftp" "mailto" "news"))
10809 (browse-url (org-link-escape-browser (concat type ":" path))))
10810 ((equal type "doi")
10811 (browse-url
10812 (org-link-escape-browser (concat org-doi-server-url path))))
10813 ((equal type "message") (browse-url (concat type ":" path)))
10814 ((equal type "shell")
10815 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10816 (cmd path))
10817 (if (or (and (org-string-nw-p
10818 org-confirm-shell-link-not-regexp)
10819 (string-match
10820 org-confirm-shell-link-not-regexp cmd))
10821 (not org-confirm-shell-link-function)
10822 (funcall org-confirm-shell-link-function
10823 (format "Execute \"%s\" in shell? "
10824 (org-add-props cmd nil
10825 'face 'org-warning))))
10826 (progn
10827 (message "Executing %s" cmd)
10828 (shell-command cmd buf)
10829 (when (featurep 'midnight)
10830 (setq clean-buffer-list-kill-buffer-names
10831 (cons (buffer-name buf)
10832 clean-buffer-list-kill-buffer-names))))
10833 (user-error "Abort"))))
10834 ((equal type "elisp")
10835 (let ((cmd path))
10836 (if (or (and (org-string-nw-p
10837 org-confirm-elisp-link-not-regexp)
10838 (org-string-match-p
10839 org-confirm-elisp-link-not-regexp cmd))
10840 (not org-confirm-elisp-link-function)
10841 (funcall org-confirm-elisp-link-function
10842 (format "Execute \"%s\" as elisp? "
10843 (org-add-props cmd nil
10844 'face 'org-warning))))
10845 (message "%s => %s" cmd
10846 (if (eq (string-to-char cmd) ?\()
10847 (eval (read cmd))
10848 (call-interactively (read cmd))))
10849 (user-error "Abort"))))
10850 ((equal type "id")
10851 (require 'org-id)
10852 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10853 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10854 (unless (run-hook-with-args-until-success
10855 'org-open-link-functions path)
10856 (if (not arg) (org-mark-ring-push)
10857 (switch-to-buffer-other-window
10858 (org-get-buffer-for-internal-link (current-buffer))))
10859 (let ((destination
10860 (org-with-wide-buffer
10861 (if (equal type "radio")
10862 (org-search-radio-target
10863 (org-element-property :path link))
10864 (org-link-search
10865 (if (member type '("custom-id" "coderef"))
10866 (org-element-property :raw-link link)
10867 path)
10868 ;; Prevent fuzzy links from matching
10869 ;; themselves.
10870 (and (equal type "fuzzy")
10871 (+ 2 (org-element-property :begin link)))))
10872 (point))))
10873 (unless (and (<= (point-min) destination)
10874 (>= (point-max) destination))
10875 (widen))
10876 (goto-char destination))))
10877 (t (browse-url-at-point))))))
10878 ;; On a footnote reference or at a footnote definition's label.
10879 ((or (eq type 'footnote-reference)
10880 (and (eq type 'footnote-definition)
10881 (save-excursion
10882 ;; Do not validate action when point is on the
10883 ;; spaces right after the footnote label, in
10884 ;; order to be on par with behaviour on links.
10885 (skip-chars-forward " \t")
10886 (let ((begin
10887 (org-element-property :contents-begin context)))
10888 (if begin (< (point) begin)
10889 (= (org-element-property :post-affiliated context)
10890 (line-beginning-position)))))))
10891 (org-footnote-action))
10892 (t (user-error "No link found")))))
10893 (run-hook-with-args 'org-follow-link-hook)))
10895 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10896 "Offer links in the current entry and return the selected link.
10897 If there is only one link, return it.
10898 If NTH is an integer, return the NTH link found.
10899 If ZERO is a string, check also this string for a link, and if
10900 there is one, return it."
10901 (with-current-buffer buffer
10902 (save-excursion
10903 (save-restriction
10904 (widen)
10905 (goto-char marker)
10906 (let ((cnt ?0)
10907 have-zero end links link c)
10908 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10909 (push (match-string 0 zero) links)
10910 (setq cnt (1- cnt) have-zero t))
10911 (save-excursion
10912 (org-back-to-heading t)
10913 (setq end (save-excursion (outline-next-heading) (point)))
10914 (while (re-search-forward org-any-link-re end t)
10915 (push (match-string 0) links))
10916 (setq links (org-uniquify (reverse links))))
10917 (cond
10918 ((null links)
10919 (message "No links"))
10920 ((equal (length links) 1)
10921 (setq link (car links)))
10922 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10923 (setq link (nth (if have-zero nth (1- nth)) links)))
10924 (t ; we have to select a link
10925 (save-excursion
10926 (save-window-excursion
10927 (delete-other-windows)
10928 (with-output-to-temp-buffer "*Select Link*"
10929 (dolist (l links)
10930 (cond
10931 ((not (string-match org-bracket-link-regexp l))
10932 (princ (format "[%c] %s\n" (cl-incf cnt)
10933 (org-remove-angle-brackets l))))
10934 ((match-end 3)
10935 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10936 (match-string 3 l) (match-string 1 l))))
10937 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10938 (match-string 1 l)))))))
10939 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10940 (message "Select link to open, RET to open all:")
10941 (setq c (read-char-exclusive))
10942 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10943 (when (equal c ?q) (user-error "Abort"))
10944 (if (equal c ?\C-m)
10945 (setq link links)
10946 (setq nth (- c ?0))
10947 (when have-zero (setq nth (1+ nth)))
10948 (unless (and (integerp nth) (>= (length links) nth))
10949 (user-error "Invalid link selection"))
10950 (setq link (nth (1- nth) links)))))
10951 (cons link end))))))
10953 ;; TODO: These functions are deprecated since `org-open-at-point'
10954 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10955 (defun org-open-file-with-system (path)
10956 "Open file at PATH using the system way of opening it."
10957 (org-open-file path 'system))
10958 (defun org-open-file-with-emacs (path)
10959 "Open file at PATH in Emacs."
10960 (org-open-file path 'emacs))
10963 ;;; File search
10965 (defvar org-create-file-search-functions nil
10966 "List of functions to construct the right search string for a file link.
10967 These functions are called in turn with point at the location to
10968 which the link should point.
10970 A function in the hook should first test if it would like to
10971 handle this file type, for example by checking the `major-mode'
10972 or the file extension. If it decides not to handle this file, it
10973 should just return nil to give other functions a chance. If it
10974 does handle the file, it must return the search string to be used
10975 when following the link. The search string will be part of the
10976 file link, given after a double colon, and `org-open-at-point'
10977 will automatically search for it. If special measures must be
10978 taken to make the search successful, another function should be
10979 added to the companion hook `org-execute-file-search-functions',
10980 which see.
10982 A function in this hook may also use `setq' to set the variable
10983 `description' to provide a suggestion for the descriptive text to
10984 be used for this link when it gets inserted into an Org-mode
10985 buffer with \\[org-insert-link].")
10987 (defvar org-execute-file-search-functions nil
10988 "List of functions to execute a file search triggered by a link.
10990 Functions added to this hook must accept a single argument, the
10991 search string that was part of the file link, the part after the
10992 double colon. The function must first check if it would like to
10993 handle this search, for example by checking the `major-mode' or
10994 the file extension. If it decides not to handle this search, it
10995 should just return nil to give other functions a chance. If it
10996 does handle the search, it must return a non-nil value to keep
10997 other functions from trying.
10999 Each function can access the current prefix argument through the
11000 variable `current-prefix-arg'. Note that a single prefix is used
11001 to force opening a link in Emacs, so it may be good to only use a
11002 numeric or double prefix to guide the search function.
11004 In case this is needed, a function in this hook can also restore
11005 the window configuration before `org-open-at-point' was called using:
11007 \(set-window-configuration org-window-config-before-follow-link)")
11009 (defun org-search-radio-target (target)
11010 "Search a radio target matching TARGET in current buffer.
11011 White spaces are not significant."
11012 (let ((re (format "<<<%s>>>"
11013 (mapconcat #'regexp-quote
11014 (org-split-string target "[ \t\n]+")
11015 "[ \t]+\\(?:\n[ \t]*\\)?")))
11016 (origin (point)))
11017 (goto-char (point-min))
11018 (catch :radio-match
11019 (while (re-search-forward re nil t)
11020 (backward-char)
11021 (let ((object (org-element-context)))
11022 (when (eq (org-element-type object) 'radio-target)
11023 (goto-char (org-element-property :begin object))
11024 (org-show-context 'link-search)
11025 (throw :radio-match nil))))
11026 (goto-char origin)
11027 (user-error "No match for radio target: %s" target))))
11029 (defun org-link-search (s &optional avoid-pos stealth)
11030 "Search for a search string S.
11032 If S starts with \"#\", it triggers a custom ID search.
11034 If S is enclosed within parenthesis, it initiates a coderef
11035 search.
11037 If S is surrounded by forward slashes, it is interpreted as
11038 a regular expression. In Org mode files, this will create an
11039 `org-occur' sparse tree. In ordinary files, `occur' will be used
11040 to list matches. If the current buffer is in `dired-mode', grep
11041 will be used to search in all files.
11043 When AVOID-POS is given, ignore matches near that position.
11045 When optional argument STEALTH is non-nil, do not modify
11046 visibility around point, thus ignoring `org-show-context-detail'
11047 variable.
11049 Search is case-insensitive and ignores white spaces. Return type
11050 of matched result, with is either `dedicated' or `fuzzy'."
11051 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
11052 (let* ((case-fold-search t)
11053 (origin (point))
11054 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
11055 (words (org-split-string s "[ \t\n]+"))
11056 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
11057 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
11058 type)
11059 (cond
11060 ;; Check if there are any special search functions.
11061 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
11062 ((eq (string-to-char s) ?#)
11063 ;; Look for a custom ID S if S starts with "#".
11064 (let* ((id (substring normalized 1))
11065 (match (org-find-property "CUSTOM_ID" id)))
11066 (if match (progn (goto-char match) (setf type 'dedicated))
11067 (error "No match for custom ID: %s" id))))
11068 ((string-match "\\`(\\(.*\\))\\'" normalized)
11069 ;; Look for coderef targets if S is enclosed within parenthesis.
11070 (let ((coderef (match-string-no-properties 1 normalized))
11071 (re (substring s-single-re 1 -1)))
11072 (goto-char (point-min))
11073 (catch :coderef-match
11074 (while (re-search-forward re nil t)
11075 (let ((element (org-element-at-point)))
11076 (when (and (memq (org-element-type element)
11077 '(example-block src-block))
11078 ;; Build proper regexp according to current
11079 ;; block's label format.
11080 (let ((label-fmt
11081 (regexp-quote
11082 (or (org-element-property :label-fmt element)
11083 org-coderef-label-format))))
11084 (save-excursion
11085 (beginning-of-line)
11086 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11087 (format label-fmt coderef))))))
11088 (setq type 'dedicated)
11089 (goto-char (match-beginning 1))
11090 (throw :coderef-match nil))))
11091 (goto-char origin)
11092 (error "No match for coderef: %s" coderef))))
11093 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11094 ;; Look for a regular expression.
11095 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11096 (match-string 1 s)))
11097 ;; Fuzzy links.
11099 (let ((starred (eq (string-to-char normalized) ?*)))
11100 (cond
11101 ;; Look for targets, only if not in a headline search.
11102 ((and (not starred)
11103 (let ((target (format "<<%s>>" s-multi-re)))
11104 (catch :target-match
11105 (goto-char (point-min))
11106 (while (re-search-forward target nil t)
11107 (backward-char)
11108 (let ((context (org-element-context)))
11109 (when (eq (org-element-type context) 'target)
11110 (setq type 'dedicated)
11111 (goto-char (org-element-property :begin context))
11112 (throw :target-match t))))
11113 nil))))
11114 ;; Look for elements named after S, only if not in a headline
11115 ;; search.
11116 ((and (not starred)
11117 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11118 (catch :name-match
11119 (goto-char (point-min))
11120 (while (re-search-forward name nil t)
11121 (let ((element (org-element-at-point)))
11122 (when (equal (org-split-string
11123 (org-element-property :name element)
11124 "[ \t]+")
11125 words)
11126 (setq type 'dedicated)
11127 (beginning-of-line)
11128 (throw :name-match t))))
11129 nil))))
11130 ;; Regular text search. Prefer headlines in Org mode
11131 ;; buffers.
11132 ((and (derived-mode-p 'org-mode)
11133 (let* ((wspace "[ \t]")
11134 (wspaceopt (concat wspace "*"))
11135 (cookie (concat "\\(?:"
11136 wspaceopt
11137 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11138 wspaceopt
11139 "\\)"))
11140 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11141 (re (concat
11142 org-outline-regexp-bol
11143 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11144 "\\(?:\\[#.\\][ \t]+\\)?"
11145 "\\(?:" org-comment-string "[ \t]+\\)?"
11146 sep "?"
11147 (let ((title (mapconcat #'regexp-quote
11148 words
11149 sep)))
11150 (if starred (substring title 1) title))
11151 sep "?"
11152 "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?"
11153 "[ \t]*$")))
11154 (goto-char (point-min))
11155 (re-search-forward re nil t)))
11156 (goto-char (match-beginning 0))
11157 (setq type 'dedicated))
11158 ;; Offer to create non-existent headline depending on
11159 ;; `org-link-search-must-match-exact-headline'.
11160 ((and (derived-mode-p 'org-mode)
11161 (not org-link-search-inhibit-query)
11162 (eq org-link-search-must-match-exact-headline 'query-to-create)
11163 (yes-or-no-p "No match - create this as a new heading? "))
11164 (goto-char (point-max))
11165 (unless (bolp) (newline))
11166 (org-insert-heading nil t t)
11167 (insert s "\n")
11168 (beginning-of-line 0))
11169 ;; Only headlines are looked after. No need to process
11170 ;; further: throw an error.
11171 ((and (derived-mode-p 'org-mode)
11172 (or starred org-link-search-must-match-exact-headline))
11173 (goto-char origin)
11174 (error "No match for fuzzy expression: %s" normalized))
11175 ;; Regular text search.
11176 ((catch :fuzzy-match
11177 (goto-char (point-min))
11178 (while (re-search-forward s-multi-re nil t)
11179 ;; Skip match if it contains AVOID-POS or it is included
11180 ;; in a link with a description but outside the
11181 ;; description.
11182 (unless (or (and avoid-pos
11183 (<= (match-beginning 0) avoid-pos)
11184 (> (match-end 0) avoid-pos))
11185 (and (save-match-data
11186 (org-in-regexp org-bracket-link-regexp))
11187 (match-beginning 3)
11188 (or (> (match-beginning 3) (point))
11189 (<= (match-end 3) (point)))
11190 (org-element-lineage
11191 (save-match-data (org-element-context))
11192 '(link) t)))
11193 (goto-char (match-beginning 0))
11194 (setq type 'fuzzy)
11195 (throw :fuzzy-match t)))
11196 nil))
11197 ;; All failed. Throw an error.
11198 (t (goto-char origin)
11199 (error "No match for fuzzy expression: %s" normalized))))))
11200 ;; Disclose surroundings of match, if appropriate.
11201 (when (and (derived-mode-p 'org-mode) (not stealth))
11202 (org-show-context 'link-search))
11203 type))
11205 (defun org-get-buffer-for-internal-link (buffer)
11206 "Return a buffer to be used for displaying the link target of internal links."
11207 (cond
11208 ((not org-display-internal-link-with-indirect-buffer)
11209 buffer)
11210 ((string-match "(Clone)$" (buffer-name buffer))
11211 (message "Buffer is already a clone, not making another one")
11212 ;; we also do not modify visibility in this case
11213 buffer)
11214 (t ; make a new indirect buffer for displaying the link
11215 (let* ((bn (buffer-name buffer))
11216 (ibn (concat bn "(Clone)"))
11217 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11218 (with-current-buffer ib (org-overview))
11219 ib))))
11221 (defun org-do-occur (regexp &optional cleanup)
11222 "Call the Emacs command `occur'.
11223 If CLEANUP is non-nil, remove the printout of the regular expression
11224 in the *Occur* buffer. This is useful if the regex is long and not useful
11225 to read."
11226 (occur regexp)
11227 (when cleanup
11228 (let ((cwin (selected-window)) win beg end)
11229 (when (setq win (get-buffer-window "*Occur*"))
11230 (select-window win))
11231 (goto-char (point-min))
11232 (when (re-search-forward "match[a-z]+" nil t)
11233 (setq beg (match-end 0))
11234 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11235 (setq end (1- (match-beginning 0)))))
11236 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11237 (goto-char (point-min))
11238 (select-window cwin))))
11240 ;;; The mark ring for links jumps
11242 (defvar org-mark-ring nil
11243 "Mark ring for positions before jumps in Org-mode.")
11244 (defvar org-mark-ring-last-goto nil
11245 "Last position in the mark ring used to go back.")
11246 ;; Fill and close the ring
11247 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11248 (dotimes (_ org-mark-ring-length)
11249 (push (make-marker) org-mark-ring))
11250 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11251 org-mark-ring)
11253 (defun org-mark-ring-push (&optional pos buffer)
11254 "Put the current position or POS into the mark ring and rotate it."
11255 (interactive)
11256 (setq pos (or pos (point)))
11257 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11258 (move-marker (car org-mark-ring)
11259 (or pos (point))
11260 (or buffer (current-buffer)))
11261 (message "%s"
11262 (substitute-command-keys
11263 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11265 (defun org-mark-ring-goto (&optional n)
11266 "Jump to the previous position in the mark ring.
11267 With prefix arg N, jump back that many stored positions. When
11268 called several times in succession, walk through the entire ring.
11269 Org-mode commands jumping to a different position in the current file,
11270 or to another Org-mode file, automatically push the old position
11271 onto the ring."
11272 (interactive "p")
11273 (let (p m)
11274 (if (eq last-command this-command)
11275 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11276 (setq p org-mark-ring))
11277 (setq org-mark-ring-last-goto p)
11278 (setq m (car p))
11279 (org-pop-to-buffer-same-window (marker-buffer m))
11280 (goto-char m)
11281 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11283 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11284 ;;; Emacs 24.4+
11285 (defun org-remove-angle-brackets (s)
11286 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11287 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11289 (defun org-add-angle-brackets (s)
11290 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11291 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11293 (defun org-remove-double-quotes (s)
11294 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11295 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11298 ;;; Following specific links
11300 (defvar org-agenda-buffer-tmp-name)
11301 (defvar org-agenda-start-on-weekday)
11302 (defun org-follow-timestamp-link ()
11303 "Open an agenda view for the time-stamp date/range at point."
11304 (cond
11305 ((org-at-date-range-p t)
11306 (let ((org-agenda-start-on-weekday)
11307 (t1 (match-string 1))
11308 (t2 (match-string 2)) tt1 tt2)
11309 (setq tt1 (time-to-days (org-time-string-to-time t1))
11310 tt2 (time-to-days (org-time-string-to-time t2)))
11311 (let ((org-agenda-buffer-tmp-name
11312 (format "*Org Agenda(a:%s)"
11313 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11314 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11315 ((org-at-timestamp-p t)
11316 (let ((org-agenda-buffer-tmp-name
11317 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11318 (org-agenda-list nil (time-to-days (org-time-string-to-time
11319 (substring (match-string 1) 0 10)))
11320 1)))
11321 (t (error "This should not happen"))))
11324 ;;; Following file links
11325 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11326 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11327 (declare-function mailcap-mime-info
11328 "mailcap" (string &optional request no-decode))
11329 (defvar org-wait nil)
11330 (defun org-open-file (path &optional in-emacs line search)
11331 "Open the file at PATH.
11332 First, this expands any special file name abbreviations. Then the
11333 configuration variable `org-file-apps' is checked if it contains an
11334 entry for this file type, and if yes, the corresponding command is launched.
11336 If no application is found, Emacs simply visits the file.
11338 With optional prefix argument IN-EMACS, Emacs will visit the file.
11339 With a double \\[universal-argument] \\[universal-argument] \
11340 prefix arg, Org tries to avoid opening in Emacs
11341 and to use an external application to visit the file.
11343 Optional LINE specifies a line to go to, optional SEARCH a string
11344 to search for. If LINE or SEARCH is given, the file will be
11345 opened in Emacs, unless an entry from org-file-apps that makes
11346 use of groups in a regexp matches.
11348 If you want to change the way frames are used when following a
11349 link, please customize `org-link-frame-setup'.
11351 If the file does not exist, an error is thrown."
11352 (let* ((file (if (equal path "")
11353 buffer-file-name
11354 (substitute-in-file-name (expand-file-name path))))
11355 (file-apps (append org-file-apps (org-default-apps)))
11356 (apps (cl-remove-if
11357 'org-file-apps-entry-match-against-dlink-p file-apps))
11358 (apps-dlink (cl-remove-if-not
11359 'org-file-apps-entry-match-against-dlink-p file-apps))
11360 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11361 (dirp (unless remp (file-directory-p file)))
11362 (file (if (and dirp org-open-directory-means-index-dot-org)
11363 (concat (file-name-as-directory file) "index.org")
11364 file))
11365 (a-m-a-p (assq 'auto-mode apps))
11366 (dfile (downcase file))
11367 ;; Reconstruct the original link from the PATH, LINE and
11368 ;; SEARCH args.
11369 (link (cond (line (concat file "::" (number-to-string line)))
11370 (search (concat file "::" search))
11371 (t file)))
11372 (dlink (downcase link))
11373 (old-buffer (current-buffer))
11374 (old-pos (point))
11375 (old-mode major-mode)
11376 (ext
11377 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11378 (match-string 1 dfile)))
11379 cmd link-match-data)
11380 (cond
11381 ((member in-emacs '((16) system))
11382 (setq cmd (cdr (assq 'system apps))))
11383 (in-emacs (setq cmd 'emacs))
11385 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11386 (and dirp (cdr (assq 'directory apps)))
11387 ;; First, try matching against apps-dlink if we
11388 ;; get a match here, store the match data for
11389 ;; later.
11390 (let ((match (assoc-default dlink apps-dlink
11391 'string-match)))
11392 (if match
11393 (progn (setq link-match-data (match-data))
11394 match)
11395 (progn (setq in-emacs (or in-emacs line search))
11396 nil))) ; if we have no match in apps-dlink,
11397 ; always open the file in emacs if line or search
11398 ; is given (for backwards compatibility)
11399 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11400 'string-match)
11401 (cdr (assoc ext apps))
11402 (cdr (assq t apps))))))
11403 (when (eq cmd 'system)
11404 (setq cmd (cdr (assoc 'system apps))))
11405 (when (eq cmd 'default)
11406 (setq cmd (cdr (assoc t apps))))
11407 (when (eq cmd 'mailcap)
11408 (require 'mailcap)
11409 (mailcap-parse-mailcaps)
11410 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11411 (command (mailcap-mime-info mime-type)))
11412 (if (stringp command)
11413 (setq cmd command)
11414 (setq cmd 'emacs))))
11415 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11416 (not (file-exists-p file))
11417 (not org-open-non-existing-files))
11418 (user-error "No such file: %s" file))
11419 (cond
11420 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11421 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11422 (while (string-match "['\"]%s['\"]" cmd)
11423 (setq cmd (replace-match "%s" t t cmd)))
11424 (while (string-match "%s" cmd)
11425 (setq cmd (replace-match
11426 (save-match-data
11427 (shell-quote-argument
11428 (convert-standard-filename file)))
11429 t t cmd)))
11431 ;; Replace "%1", "%2" etc. in command with group matches from regex
11432 (save-match-data
11433 (let ((match-index 1)
11434 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11435 (set-match-data link-match-data)
11436 (while (<= match-index number-of-groups)
11437 (let ((regex (concat "%" (number-to-string match-index)))
11438 (replace-with (match-string match-index dlink)))
11439 (while (string-match regex cmd)
11440 (setq cmd (replace-match replace-with t t cmd))))
11441 (setq match-index (+ match-index 1)))))
11443 (save-window-excursion
11444 (message "Running %s...done" cmd)
11445 (start-process-shell-command cmd nil cmd)
11446 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11447 ((or (stringp cmd)
11448 (eq cmd 'emacs))
11449 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11450 (widen)
11451 (cond (line (org-goto-line line)
11452 (when (derived-mode-p 'org-mode) (org-reveal)))
11453 (search (org-link-search search))))
11454 ((functionp cmd)
11455 (save-match-data
11456 (set-match-data link-match-data)
11457 (condition-case nil
11458 (funcall cmd file link)
11459 ;; FIXME: Remove this check when most default installations
11460 ;; of Emacs have at least Org 9.0.
11461 ((debug wrong-number-of-arguments wrong-type-argument
11462 invalid-function)
11463 (user-error "Please see Org News for version 9.0 about \
11464 `org-file-apps'--Lisp error: %S" cmd)))))
11465 ((consp cmd)
11466 ;; FIXME: Remove this check when most default installations of
11467 ;; Emacs have at least Org 9.0.
11468 ;; Heads-up instead of silently fall back to
11469 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11470 ;; with sexp instead of a function for `cmd'.
11471 (user-error "Please see Org News for version 9.0 about \
11472 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11473 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11474 (and (derived-mode-p 'org-mode)
11475 (eq old-mode 'org-mode)
11476 (or (not (eq old-buffer (current-buffer)))
11477 (not (eq old-pos (point))))
11478 (org-mark-ring-push old-pos old-buffer))))
11480 (defun org-file-apps-entry-match-against-dlink-p (entry)
11481 "This function returns non-nil if `entry' uses a regular
11482 expression which should be matched against the whole link by
11483 org-open-file.
11485 It assumes that is the case when the entry uses a regular
11486 expression which has at least one grouping construct and the
11487 action is either a lisp form or a command string containing
11488 `%1', i.e. using at least one subexpression match as a
11489 parameter."
11490 (let ((selector (car entry))
11491 (action (cdr entry)))
11492 (if (stringp selector)
11493 (and (> (regexp-opt-depth selector) 0)
11494 (or (and (stringp action)
11495 (string-match "%[0-9]" action))
11496 (consp action)))
11497 nil)))
11499 (defun org-default-apps ()
11500 "Return the default applications for this operating system."
11501 (cond
11502 ((eq system-type 'darwin)
11503 org-file-apps-defaults-macosx)
11504 ((eq system-type 'windows-nt)
11505 org-file-apps-defaults-windowsnt)
11506 (t org-file-apps-defaults-gnu)))
11508 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11509 "Convert extensions to regular expressions in the cars of LIST.
11510 Also, weed out any non-string entries, because the return value is used
11511 only for regexp matching.
11512 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11513 point to the symbol `emacs', indicating that the file should
11514 be opened in Emacs."
11515 (append
11516 (delq nil
11517 (mapcar (lambda (x)
11518 (unless (not (stringp (car x)))
11519 (if (string-match "\\W" (car x))
11521 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11522 list))
11523 (when add-auto-mode
11524 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11526 (defvar ange-ftp-name-format)
11527 (defun org-file-remote-p (file)
11528 "Test whether FILE specifies a location on a remote system.
11529 Return non-nil if the location is indeed remote.
11531 For example, the filename \"/user@host:/foo\" specifies a location
11532 on the system \"/user@host:\"."
11533 (cond ((fboundp 'file-remote-p)
11534 (file-remote-p file))
11535 ((fboundp 'tramp-handle-file-remote-p)
11536 (tramp-handle-file-remote-p file))
11537 ((and (boundp 'ange-ftp-name-format)
11538 (string-match (car ange-ftp-name-format) file))
11539 t)))
11542 ;;;; Refiling
11544 (defun org-get-org-file ()
11545 "Read a filename, with default directory `org-directory'."
11546 (let ((default (or org-default-notes-file remember-data-file)))
11547 (read-file-name (format "File name [%s]: " default)
11548 (file-name-as-directory org-directory)
11549 default)))
11551 (defun org-notes-order-reversed-p ()
11552 "Check if the current file should receive notes in reversed order."
11553 (cond
11554 ((not org-reverse-note-order) nil)
11555 ((eq t org-reverse-note-order) t)
11556 ((not (listp org-reverse-note-order)) nil)
11557 (t (catch 'exit
11558 (dolist (entry org-reverse-note-order)
11559 (when (string-match (car entry) buffer-file-name)
11560 (throw 'exit (cdr entry))))))))
11562 (defvar org-refile-target-table nil
11563 "The list of refile targets, created by `org-refile'.")
11565 (defvar org-agenda-new-buffers nil
11566 "Buffers created to visit agenda files.")
11568 (defvar org-refile-cache nil
11569 "Cache for refile targets.")
11571 (defvar org-refile-markers nil
11572 "All the markers used for caching refile locations.")
11574 (defun org-refile-marker (pos)
11575 "Get a new refile marker, but only if caching is in use."
11576 (if (not org-refile-use-cache)
11578 (let ((m (make-marker)))
11579 (move-marker m pos)
11580 (push m org-refile-markers)
11581 m)))
11583 (defun org-refile-cache-clear ()
11584 "Clear the refile cache and disable all the markers."
11585 (dolist (m org-refile-markers) (move-marker m nil))
11586 (setq org-refile-markers nil)
11587 (setq org-refile-cache nil)
11588 (message "Refile cache has been cleared"))
11590 (defun org-refile-cache-check-set (set)
11591 "Check if all the markers in the cache still have live buffers."
11592 (let (marker)
11593 (catch 'exit
11594 (while (and set (setq marker (nth 3 (pop set))))
11595 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11596 (when (and marker (null (marker-buffer marker)))
11597 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11598 (sit-for 3)
11599 (throw 'exit nil)))
11600 t)))
11602 (defun org-refile-cache-put (set &rest identifiers)
11603 "Push the refile targets SET into the cache, under IDENTIFIERS."
11604 (let* ((key (sha1 (prin1-to-string identifiers)))
11605 (entry (assoc key org-refile-cache)))
11606 (if entry
11607 (setcdr entry set)
11608 (push (cons key set) org-refile-cache))))
11610 (defun org-refile-cache-get (&rest identifiers)
11611 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11612 (cond
11613 ((not org-refile-cache) nil)
11614 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11616 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11617 org-refile-cache))))
11618 (and set (org-refile-cache-check-set set) set)))))
11620 (defvar org-outline-path-cache nil
11621 "Alist between buffer positions and outline paths.
11622 It value is an alist (POSITION . PATH) where POSITION is the
11623 buffer position at the beginning of an entry and PATH is a list
11624 of strings describing the outline path for that entry, in reverse
11625 order.")
11627 (defun org-refile-get-targets (&optional default-buffer)
11628 "Produce a table with refile targets."
11629 (let ((case-fold-search nil)
11630 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11631 (entries (or org-refile-targets '((nil . (:level . 1)))))
11632 targets tgs files desc descre)
11633 (message "Getting targets...")
11634 (with-current-buffer (or default-buffer (current-buffer))
11635 (dolist (entry entries)
11636 (setq files (car entry) desc (cdr entry))
11637 (cond
11638 ((null files) (setq files (list (current-buffer))))
11639 ((eq files 'org-agenda-files)
11640 (setq files (org-agenda-files 'unrestricted)))
11641 ((and (symbolp files) (fboundp files))
11642 (setq files (funcall files)))
11643 ((and (symbolp files) (boundp files))
11644 (setq files (symbol-value files))))
11645 (when (stringp files) (setq files (list files)))
11646 (cond
11647 ((eq (car desc) :tag)
11648 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11649 ((eq (car desc) :todo)
11650 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11651 ((eq (car desc) :regexp)
11652 (setq descre (cdr desc)))
11653 ((eq (car desc) :level)
11654 (setq descre (concat "^\\*\\{" (number-to-string
11655 (if org-odd-levels-only
11656 (1- (* 2 (cdr desc)))
11657 (cdr desc)))
11658 "\\}[ \t]")))
11659 ((eq (car desc) :maxlevel)
11660 (setq descre (concat "^\\*\\{1," (number-to-string
11661 (if org-odd-levels-only
11662 (1- (* 2 (cdr desc)))
11663 (cdr desc)))
11664 "\\}[ \t]")))
11665 (t (error "Bad refiling target description %s" desc)))
11666 (dolist (f files)
11667 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11669 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11670 (progn
11671 (when (bufferp f)
11672 (setq f (buffer-file-name (buffer-base-buffer f))))
11673 (setq f (and f (expand-file-name f)))
11674 (when (eq org-refile-use-outline-path 'file)
11675 (push (list (file-name-nondirectory f) f nil nil) tgs))
11676 (org-with-wide-buffer
11677 (goto-char (point-min))
11678 (setq org-outline-path-cache nil)
11679 (while (re-search-forward descre nil t)
11680 (beginning-of-line)
11681 (looking-at org-complex-heading-regexp)
11682 (let ((begin (point))
11683 (heading (match-string-no-properties 4)))
11684 (unless (or (and
11685 org-refile-target-verify-function
11686 (not
11687 (funcall org-refile-target-verify-function)))
11688 (not heading))
11689 (let ((re (format org-complex-heading-regexp-format
11690 (regexp-quote heading)))
11691 (target
11692 (if (not org-refile-use-outline-path) heading
11693 (mapconcat
11694 #'org-protect-slash
11695 (append
11696 (pcase org-refile-use-outline-path
11697 (`file (list (file-name-nondirectory
11698 (buffer-file-name
11699 (buffer-base-buffer)))))
11700 (`full-file-path
11701 (list (buffer-file-name
11702 (buffer-base-buffer))))
11703 (_ nil))
11704 (org-get-outline-path t t))
11705 "/"))))
11706 (push (list target f re (org-refile-marker (point)))
11707 tgs)))
11708 (when (= (point) begin)
11709 ;; Verification function has not moved point.
11710 (end-of-line)))))))
11711 (when org-refile-use-cache
11712 (org-refile-cache-put tgs (buffer-file-name) descre))
11713 (setq targets (append tgs targets))))))
11714 (message "Getting targets...done")
11715 (nreverse targets)))
11717 (defun org-protect-slash (s)
11718 (while (string-match "/" s)
11719 (setq s (replace-match "\\" t t s)))
11722 (defun org--get-outline-path-1 (&optional use-cache)
11723 "Return outline path to current headline.
11725 Outline path is a list of strings, in reverse order. When
11726 optional argument USE-CACHE is non-nil, make use of a cache. See
11727 `org-get-outline-path' for details.
11729 Assume buffer is widened and point is on a headline."
11730 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11731 (let ((p (point))
11732 (heading (progn
11733 (looking-at org-complex-heading-regexp)
11734 (if (not (match-end 4)) ""
11735 ;; Remove statistics cookies.
11736 (org-trim
11737 (org-link-display-format
11738 (replace-regexp-in-string
11739 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11740 (match-string-no-properties 4))))))))
11741 (if (org-up-heading-safe)
11742 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11743 (when use-cache
11744 (push (cons p path) org-outline-path-cache))
11745 path)
11746 ;; This is a new root node. Since we assume we are moving
11747 ;; forward, we can drop previous cache so as to limit number
11748 ;; of associations there.
11749 (let ((path (list heading)))
11750 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11751 path)))))
11753 (defun org-get-outline-path (&optional with-self use-cache)
11754 "Return the outline path to the current entry.
11756 An outline path is a list of ancestors for current headline, as
11757 a list of strings. Statistics cookies are removed and links are
11758 replaced with their description, if any, or their path otherwise.
11760 When optional argument WITH-SELF is non-nil, the path also
11761 includes the current headline.
11763 When optional argument USE-CACHE is non-nil, cache outline paths
11764 between calls to this function so as to avoid backtracking. This
11765 argument is useful when planning to find more than one outline
11766 path in the same document. In that case, there are two
11767 conditions to satisfy:
11768 - `org-outline-path-cache' is set to nil before starting the
11769 process;
11770 - outline paths are computed by increasing buffer positions."
11771 (org-with-wide-buffer
11772 (and (or (and with-self (org-back-to-heading t))
11773 (org-up-heading-safe))
11774 (reverse (org--get-outline-path-1 use-cache)))))
11776 (defun org-format-outline-path (path &optional width prefix separator)
11777 "Format the outline path PATH for display.
11778 WIDTH is the maximum number of characters that is available.
11779 PREFIX is a prefix to be included in the returned string,
11780 such as the file name.
11781 SEPARATOR is inserted between the different parts of the path,
11782 the default is \"/\"."
11783 (setq width (or width 79))
11784 (setq path (delq nil path))
11785 (unless (> width 0)
11786 (user-error "Argument `width' must be positive"))
11787 (setq separator (or separator "/"))
11788 (let* ((org-odd-levels-only nil)
11789 (fpath (concat
11790 prefix (and prefix path separator)
11791 (mapconcat
11792 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11793 (cl-loop for head in path
11794 for n from 0
11795 collect (org-add-props
11796 head nil 'face
11797 (nth (% n org-n-level-faces) org-level-faces)))
11798 separator))))
11799 (when (> (length fpath) width)
11800 (if (< width 7)
11801 ;; It's unlikely that `width' will be this small, but don't
11802 ;; waste characters by adding ".." if it is.
11803 (setq fpath (substring fpath 0 width))
11804 (setf (substring fpath (- width 2)) "..")))
11805 fpath))
11807 (defun org-display-outline-path (&optional file current separator just-return-string)
11808 "Display the current outline path in the echo area.
11810 If FILE is non-nil, prepend the output with the file name.
11811 If CURRENT is non-nil, append the current heading to the output.
11812 SEPARATOR is passed through to `org-format-outline-path'. It separates
11813 the different parts of the path and defaults to \"/\".
11814 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11815 (interactive "P")
11816 (let* (case-fold-search
11817 (bfn (buffer-file-name (buffer-base-buffer)))
11818 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11819 res)
11820 (when current (setq path (append path
11821 (save-excursion
11822 (org-back-to-heading t)
11823 (when (looking-at org-complex-heading-regexp)
11824 (list (match-string 4)))))))
11825 (setq res
11826 (org-format-outline-path
11827 path
11828 (1- (frame-width))
11829 (and file bfn (concat (file-name-nondirectory bfn) separator))
11830 separator))
11831 (if just-return-string
11832 (org-no-properties res)
11833 (org-unlogged-message "%s" res))))
11835 (defvar org-refile-history nil
11836 "History for refiling operations.")
11838 (defvar org-after-refile-insert-hook nil
11839 "Hook run after `org-refile' has inserted its stuff at the new location.
11840 Note that this is still *before* the stuff will be removed from
11841 the *old* location.")
11843 (defvar org-capture-last-stored-marker)
11844 (defvar org-refile-keep nil
11845 "Non-nil means `org-refile' will copy instead of refile.")
11847 (defun org-copy ()
11848 "Like `org-refile', but copy."
11849 (interactive)
11850 (let ((org-refile-keep t))
11851 (funcall 'org-refile nil nil nil "Copy")))
11853 (defun org-refile (&optional arg default-buffer rfloc msg)
11854 "Move the entry or entries at point to another heading.
11855 The list of target headings is compiled using the information in
11856 `org-refile-targets', which see.
11858 At the target location, the entry is filed as a subitem of the
11859 target heading. Depending on `org-reverse-note-order', the new
11860 subitem will either be the first or the last subitem.
11862 If there is an active region, all entries in that region will be
11863 refiled. However, the region must fulfill the requirement that
11864 the first heading sets the top-level of the moved text.
11866 With prefix arg ARG, the command will only visit the target
11867 location and not actually move anything.
11869 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11870 refiling operation has put the subtree.
11872 With a numeric prefix argument of `2', refile to the running clock.
11874 With a numeric prefix argument of `3', emulate `org-refile-keep'
11875 being set to t and copy to the target location, don't move it.
11876 Beware that keeping refiled entries may result in duplicated ID
11877 properties.
11879 RFLOC can be a refile location obtained in a different way.
11881 MSG is a string to replace \"Refile\" in the default prompt with
11882 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11884 See also `org-refile-use-outline-path'.
11886 If you are using target caching (see `org-refile-use-cache'), you
11887 have to clear the target cache in order to find new targets.
11888 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11889 prefix argument (`C-u C-u C-u C-c C-w')."
11890 (interactive "P")
11891 (if (member arg '(0 (64)))
11892 (org-refile-cache-clear)
11893 (let* ((actionmsg (cond (msg msg)
11894 ((equal arg 3) "Refile (and keep)")
11895 (t "Refile")))
11896 (regionp (org-region-active-p))
11897 (region-start (and regionp (region-beginning)))
11898 (region-end (and regionp (region-end)))
11899 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11900 pos it nbuf file level reversed)
11901 (setq last-command nil)
11902 (when regionp
11903 (goto-char region-start)
11904 (or (bolp) (goto-char (point-at-bol)))
11905 (setq region-start (point))
11906 (unless (or (org-kill-is-subtree-p
11907 (buffer-substring region-start region-end))
11908 (prog1 org-refile-active-region-within-subtree
11909 (let ((s (point-at-eol)))
11910 (org-toggle-heading)
11911 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11912 (user-error "The region is not a (sequence of) subtree(s)")))
11913 (if (equal arg '(16))
11914 (org-refile-goto-last-stored)
11915 (when (or
11916 (and (equal arg 2)
11917 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11918 (prog1
11919 (setq it (list (or org-clock-heading "running clock")
11920 (buffer-file-name
11921 (marker-buffer org-clock-hd-marker))
11923 (marker-position org-clock-hd-marker)))
11924 (setq arg nil)))
11925 (setq it
11926 (or rfloc
11927 (let (heading-text)
11928 (save-excursion
11929 (unless (and arg (listp arg))
11930 (org-back-to-heading t)
11931 (setq heading-text
11932 (replace-regexp-in-string
11933 org-bracket-link-regexp
11934 "\\3"
11935 (nth 4 (org-heading-components)))))
11936 (org-refile-get-location
11937 (cond ((and arg (listp arg)) "Goto")
11938 (regionp (concat actionmsg " region to"))
11939 (t (concat actionmsg " subtree \""
11940 heading-text "\" to")))
11941 default-buffer
11942 (and (not (equal '(4) arg))
11943 org-refile-allow-creating-parent-nodes)))))))
11944 (setq file (nth 1 it)
11945 pos (nth 3 it))
11946 (when (and (not arg)
11948 (equal (buffer-file-name) file)
11949 (if regionp
11950 (and (>= pos region-start)
11951 (<= pos region-end))
11952 (and (>= pos (point))
11953 (< pos (save-excursion
11954 (org-end-of-subtree t t))))))
11955 (error "Cannot refile to position inside the tree or region"))
11956 (setq nbuf (or (find-buffer-visiting file)
11957 (find-file-noselect file)))
11958 (if (and arg (not (equal arg 3)))
11959 (progn
11960 (org-pop-to-buffer-same-window nbuf)
11961 (goto-char pos)
11962 (org-show-context 'org-goto))
11963 (if regionp
11964 (progn
11965 (org-kill-new (buffer-substring region-start region-end))
11966 (org-save-markers-in-region region-start region-end))
11967 (org-copy-subtree 1 nil t))
11968 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11969 (find-file-noselect file)))
11970 (setq reversed (org-notes-order-reversed-p))
11971 (save-excursion
11972 (save-restriction
11973 (widen)
11974 (if pos
11975 (progn
11976 (goto-char pos)
11977 (looking-at org-outline-regexp)
11978 (setq level (org-get-valid-level (funcall outline-level) 1))
11979 (goto-char
11980 (if reversed
11981 (or (outline-next-heading) (point-max))
11982 (or (save-excursion (org-get-next-sibling))
11983 (org-end-of-subtree t t)
11984 (point-max)))))
11985 (setq level 1)
11986 (if (not reversed)
11987 (goto-char (point-max))
11988 (goto-char (point-min))
11989 (or (outline-next-heading) (goto-char (point-max)))))
11990 (unless (bolp) (newline))
11991 (org-paste-subtree level nil nil t)
11992 (when org-log-refile
11993 (org-add-log-setup 'refile nil nil org-log-refile)
11994 (unless (eq org-log-refile 'note)
11995 (save-excursion (org-add-log-note))))
11996 (and org-auto-align-tags
11997 (let ((org-loop-over-headlines-in-active-region nil))
11998 (org-set-tags nil t)))
11999 (let ((bookmark-name (plist-get org-bookmark-names-plist
12000 :last-refile)))
12001 (when bookmark-name
12002 (with-demoted-errors
12003 (bookmark-set bookmark-name))))
12004 ;; If we are refiling for capture, make sure that the
12005 ;; last-capture pointers point here
12006 (when (org-bound-and-true-p org-capture-is-refiling)
12007 (let ((bookmark-name (plist-get org-bookmark-names-plist
12008 :last-capture-marker)))
12009 (when bookmark-name
12010 (with-demoted-errors
12011 (bookmark-set bookmark-name))))
12012 (move-marker org-capture-last-stored-marker (point)))
12013 (when (fboundp 'deactivate-mark) (deactivate-mark))
12014 (run-hooks 'org-after-refile-insert-hook))))
12015 (unless org-refile-keep
12016 (if regionp
12017 (delete-region (point) (+ (point) (- region-end region-start)))
12018 (delete-region
12019 (and (org-back-to-heading t) (point))
12020 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
12021 (when (featurep 'org-inlinetask)
12022 (org-inlinetask-remove-END-maybe))
12023 (setq org-markers-to-move nil)
12024 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
12026 (defun org-refile-goto-last-stored ()
12027 "Go to the location where the last refile was stored."
12028 (interactive)
12029 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
12030 (message "This is the location of the last refile"))
12032 (defun org-refile--get-location (refloc tbl)
12033 "When user refile to REFLOC, find the associated target in TBL.
12034 Also check `org-refile-target-table'."
12035 (car (delq
12037 (mapcar
12038 (lambda (r) (or (assoc r tbl)
12039 (assoc r org-refile-target-table)))
12040 (list (replace-regexp-in-string "/$" "" refloc)
12041 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
12043 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
12044 "Prompt the user for a refile location, using PROMPT.
12045 PROMPT should not be suffixed with a colon and a space, because
12046 this function appends the default value from
12047 `org-refile-history' automatically, if that is not empty."
12048 (let ((org-refile-targets org-refile-targets)
12049 (org-refile-use-outline-path org-refile-use-outline-path))
12050 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
12051 (unless org-refile-target-table
12052 (user-error "No refile targets"))
12053 (let* ((cbuf (current-buffer))
12054 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
12055 (cfunc (if (and org-refile-use-outline-path
12056 org-outline-path-complete-in-steps)
12057 #'org-olpath-completing-read
12058 #'completing-read))
12059 (extra (if org-refile-use-outline-path "/" ""))
12060 (cbnex (concat (buffer-name) extra))
12061 (filename (and cfn (expand-file-name cfn)))
12062 (tbl (mapcar
12063 (lambda (x)
12064 (if (and (not (member org-refile-use-outline-path
12065 '(file full-file-path)))
12066 (not (equal filename (nth 1 x))))
12067 (cons (concat (car x) extra " ("
12068 (file-name-nondirectory (nth 1 x)) ")")
12069 (cdr x))
12070 (cons (concat (car x) extra) (cdr x))))
12071 org-refile-target-table))
12072 (completion-ignore-case t)
12073 cdef
12074 (prompt (concat prompt
12075 (or (and (car org-refile-history)
12076 (concat " (default " (car org-refile-history) ")"))
12077 (and (assoc cbnex tbl) (setq cdef cbnex)
12078 (concat " (default " cbnex ")"))) ": "))
12079 pa answ parent-target child parent old-hist)
12080 (setq old-hist org-refile-history)
12081 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12082 nil 'org-refile-history (or cdef (car org-refile-history))))
12083 (if (setq pa (org-refile--get-location answ tbl))
12084 (progn
12085 (org-refile-check-position pa)
12086 (when (or (not org-refile-history)
12087 (not (eq old-hist org-refile-history))
12088 (not (equal (car pa) (car org-refile-history))))
12089 (setq org-refile-history
12090 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12091 org-refile-history
12092 (cdr org-refile-history))))
12093 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12094 (pop org-refile-history)))
12096 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12097 (progn
12098 (setq parent (match-string 1 answ)
12099 child (match-string 2 answ))
12100 (setq parent-target (org-refile--get-location parent tbl))
12101 (when (and parent-target
12102 (or (eq new-nodes t)
12103 (and (eq new-nodes 'confirm)
12104 (y-or-n-p (format "Create new node \"%s\"? "
12105 child)))))
12106 (org-refile-new-child parent-target child)))
12107 (user-error "Invalid target location")))))
12109 (declare-function org-string-nw-p "org-macs" (s))
12110 (defun org-refile-check-position (refile-pointer)
12111 "Check if the refile pointer matches the headline to which it points."
12112 (let* ((file (nth 1 refile-pointer))
12113 (re (nth 2 refile-pointer))
12114 (pos (nth 3 refile-pointer))
12115 buffer)
12116 (if (and (not (markerp pos)) (not file))
12117 (user-error "Please indicate a target file in the refile path")
12118 (when (org-string-nw-p re)
12119 (setq buffer (if (markerp pos)
12120 (marker-buffer pos)
12121 (or (find-buffer-visiting file)
12122 (find-file-noselect file))))
12123 (with-current-buffer buffer
12124 (save-excursion
12125 (save-restriction
12126 (widen)
12127 (goto-char pos)
12128 (beginning-of-line 1)
12129 (unless (looking-at-p re)
12130 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12132 (defun org-refile-new-child (parent-target child)
12133 "Use refile target PARENT-TARGET to add new CHILD below it."
12134 (unless parent-target
12135 (error "Cannot find parent for new node"))
12136 (let ((file (nth 1 parent-target))
12137 (pos (nth 3 parent-target))
12138 level)
12139 (with-current-buffer (or (find-buffer-visiting file)
12140 (find-file-noselect file))
12141 (save-excursion
12142 (save-restriction
12143 (widen)
12144 (if pos
12145 (goto-char pos)
12146 (goto-char (point-max))
12147 (unless (bolp) (newline)))
12148 (when (looking-at org-outline-regexp)
12149 (setq level (funcall outline-level))
12150 (org-end-of-subtree t t))
12151 (org-back-over-empty-lines)
12152 (insert "\n" (make-string
12153 (if pos (org-get-valid-level level 1) 1) ?*)
12154 " " child "\n")
12155 (beginning-of-line 0)
12156 (list (concat (car parent-target) "/" child) file "" (point)))))))
12158 (defun org-olpath-completing-read (prompt collection &rest args)
12159 "Read an outline path like a file name."
12160 (let ((thetable collection))
12161 (apply #'completing-read
12162 prompt
12163 (lambda (string predicate &optional flag)
12164 (cond
12165 ((eq flag nil) (try-completion string thetable))
12166 ((eq flag t)
12167 (let ((l (length string)))
12168 (mapcar (lambda (x)
12169 (let ((r (substring x l))
12170 (f (if (string-match " ([^)]*)$" x)
12171 (match-string 0 x)
12172 "")))
12173 (if (string-match "/" r)
12174 (concat string (substring r 0 (match-end 0)) f)
12175 x)))
12176 (all-completions string thetable predicate))))
12177 ;; Exact match?
12178 ((eq flag 'lambda) (assoc string thetable))))
12179 args)))
12181 ;;;; Dynamic blocks
12183 (defun org-find-dblock (name)
12184 "Find the first dynamic block with name NAME in the buffer.
12185 If not found, stay at current position and return nil."
12186 (let ((case-fold-search t) pos)
12187 (save-excursion
12188 (goto-char (point-min))
12189 (setq pos (and (re-search-forward
12190 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12191 (match-beginning 0))))
12192 (when pos (goto-char pos))
12193 pos))
12195 (defun org-create-dblock (plist)
12196 "Create a dynamic block section, with parameters taken from PLIST.
12197 PLIST must contain a :name entry which is used as the name of the block."
12198 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12199 (end-of-line 1)
12200 (newline))
12201 (let ((col (current-column))
12202 (name (plist-get plist :name)))
12203 (insert "#+BEGIN: " name)
12204 (while plist
12205 (if (eq (car plist) :name)
12206 (setq plist (cddr plist))
12207 (insert " " (prin1-to-string (pop plist)))))
12208 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12209 (beginning-of-line -2)))
12211 (defun org-prepare-dblock ()
12212 "Prepare dynamic block for refresh.
12213 This empties the block, puts the cursor at the insert position and returns
12214 the property list including an extra property :name with the block name."
12215 (unless (looking-at org-dblock-start-re)
12216 (user-error "Not at a dynamic block"))
12217 (let* ((begdel (1+ (match-end 0)))
12218 (name (org-no-properties (match-string 1)))
12219 (params (append (list :name name)
12220 (read (concat "(" (match-string 3) ")")))))
12221 (save-excursion
12222 (beginning-of-line 1)
12223 (skip-chars-forward " \t")
12224 (setq params (plist-put params :indentation-column (current-column))))
12225 (unless (re-search-forward org-dblock-end-re nil t)
12226 (error "Dynamic block not terminated"))
12227 (setq params
12228 (append params
12229 (list :content (buffer-substring
12230 begdel (match-beginning 0)))))
12231 (delete-region begdel (match-beginning 0))
12232 (goto-char begdel)
12233 (open-line 1)
12234 params))
12236 (defun org-map-dblocks (&optional command)
12237 "Apply COMMAND to all dynamic blocks in the current buffer.
12238 If COMMAND is not given, use `org-update-dblock'."
12239 (let ((cmd (or command 'org-update-dblock)))
12240 (save-excursion
12241 (goto-char (point-min))
12242 (while (re-search-forward org-dblock-start-re nil t)
12243 (goto-char (match-beginning 0))
12244 (save-excursion
12245 (condition-case nil
12246 (funcall cmd)
12247 (error (message "Error during update of dynamic block"))))
12248 (unless (re-search-forward org-dblock-end-re nil t)
12249 (error "Dynamic block not terminated"))))))
12251 (defun org-dblock-update (&optional arg)
12252 "User command for updating dynamic blocks.
12253 Update the dynamic block at point. With prefix ARG, update all dynamic
12254 blocks in the buffer."
12255 (interactive "P")
12256 (if arg
12257 (org-update-all-dblocks)
12258 (or (looking-at org-dblock-start-re)
12259 (org-beginning-of-dblock))
12260 (org-update-dblock)))
12262 (defun org-update-dblock ()
12263 "Update the dynamic block at point.
12264 This means to empty the block, parse for parameters and then call
12265 the correct writing function."
12266 (interactive)
12267 (save-excursion
12268 (let* ((win (selected-window))
12269 (pos (point))
12270 (line (org-current-line))
12271 (params (org-prepare-dblock))
12272 (name (plist-get params :name))
12273 (indent (plist-get params :indentation-column))
12274 (cmd (intern (concat "org-dblock-write:" name))))
12275 (message "Updating dynamic block `%s' at line %d..." name line)
12276 (funcall cmd params)
12277 (message "Updating dynamic block `%s' at line %d...done" name line)
12278 (goto-char pos)
12279 (when (and indent (> indent 0))
12280 (setq indent (make-string indent ?\ ))
12281 (save-excursion
12282 (select-window win)
12283 (org-beginning-of-dblock)
12284 (forward-line 1)
12285 (while (not (looking-at org-dblock-end-re))
12286 (insert indent)
12287 (beginning-of-line 2))
12288 (when (looking-at org-dblock-end-re)
12289 (and (looking-at "[ \t]+")
12290 (replace-match ""))
12291 (insert indent)))))))
12293 (defun org-beginning-of-dblock ()
12294 "Find the beginning of the dynamic block at point.
12295 Error if there is no such block at point."
12296 (let ((pos (point))
12297 beg)
12298 (end-of-line 1)
12299 (if (and (re-search-backward org-dblock-start-re nil t)
12300 (setq beg (match-beginning 0))
12301 (re-search-forward org-dblock-end-re nil t)
12302 (> (match-end 0) pos))
12303 (goto-char beg)
12304 (goto-char pos)
12305 (error "Not in a dynamic block"))))
12307 (defun org-update-all-dblocks ()
12308 "Update all dynamic blocks in the buffer.
12309 This function can be used in a hook."
12310 (interactive)
12311 (when (derived-mode-p 'org-mode)
12312 (org-map-dblocks 'org-update-dblock)))
12315 ;;;; Completion
12317 (declare-function org-export-backend-options "ox" (cl-x) t)
12318 (defun org-get-export-keywords ()
12319 "Return a list of all currently understood export keywords.
12320 Export keywords include options, block names, attributes and
12321 keywords relative to each registered export back-end."
12322 (let (keywords)
12323 (dolist (backend
12324 (org-bound-and-true-p org-export-registered-backends)
12325 (delq nil keywords))
12326 ;; Back-end name (for keywords, like #+LATEX:)
12327 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12328 (dolist (option-entry (org-export-backend-options backend))
12329 ;; Back-end options.
12330 (push (nth 1 option-entry) keywords)))))
12332 (defconst org-options-keywords
12333 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12334 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12335 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12336 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12337 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12339 (defcustom org-structure-template-alist
12340 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12341 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12342 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12343 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12344 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12345 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12346 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12347 ("L" "#+LaTeX: ")
12348 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12349 ("H" "#+HTML: ")
12350 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12351 ("A" "#+ASCII: ")
12352 ("i" "#+INDEX: ?")
12353 ("I" "#+INCLUDE: %file ?"))
12354 "Structure completion elements.
12355 This is a list of abbreviation keys and values. The value gets inserted
12356 if you type `<' followed by the key and then press the completion key,
12357 usually `TAB'. %file will be replaced by a file name after prompting
12358 for the file using completion. The cursor will be placed at the position
12359 of the `?' in the template.
12360 There are two templates for each key, the first uses the original Org syntax,
12361 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12362 the default when the /org-mtags.el/ module has been loaded. See also the
12363 variable `org-mtags-prefer-muse-templates'."
12364 :group 'org-completion
12365 :type '(repeat
12366 (list
12367 (string :tag "Key")
12368 (string :tag "Template")))
12369 :version "25.1"
12370 :package-version '(Org . "8.3"))
12372 (defun org-try-structure-completion ()
12373 "Try to complete a structure template before point.
12374 This looks for strings like \"<e\" on an otherwise empty line and
12375 expands them."
12376 (let ((l (buffer-substring (point-at-bol) (point)))
12378 (when (and (looking-at "[ \t]*$")
12379 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12380 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12381 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12382 (match-beginning 1)) a)
12383 t)))
12385 (defun org-complete-expand-structure-template (start cell)
12386 "Expand a structure template."
12387 (let ((rpl (nth 1 cell))
12388 (ind ""))
12389 (delete-region start (point))
12390 (when (string-match "\\`[ \t]*#\\+" rpl)
12391 (cond
12392 ((bolp))
12393 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12394 (setq ind (buffer-substring (point-at-bol) (point))))
12395 (t (newline))))
12396 (setq start (point))
12397 (when (string-match "%file" rpl)
12398 (setq rpl (replace-match
12399 (concat
12400 "\""
12401 (save-match-data
12402 (abbreviate-file-name (read-file-name "Include file: ")))
12403 "\"")
12404 t t rpl)))
12405 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12406 (concat "\n" ind)))
12407 (insert rpl)
12408 (when (re-search-backward "\\?" start t) (delete-char 1))))
12410 ;;;; TODO, DEADLINE, Comments
12412 (defun org-toggle-comment ()
12413 "Change the COMMENT state of an entry."
12414 (interactive)
12415 (save-excursion
12416 (org-back-to-heading)
12417 (looking-at org-complex-heading-regexp)
12418 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12419 (skip-chars-forward " \t")
12420 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12421 (if (org-in-commented-heading-p t)
12422 (delete-region (point)
12423 (progn (search-forward " " (line-end-position) 'move)
12424 (skip-chars-forward " \t")
12425 (point)))
12426 (insert org-comment-string)
12427 (unless (eolp) (insert " ")))))
12429 (defvar org-last-todo-state-is-todo nil
12430 "This is non-nil when the last TODO state change led to a TODO state.
12431 If the last change removed the TODO tag or switched to DONE, then
12432 this is nil.")
12434 (defvar org-setting-tags nil) ; dynamically skipped
12436 (defvar org-todo-setup-filter-hook nil
12437 "Hook for functions that pre-filter todo specs.
12438 Each function takes a todo spec and returns either nil or the spec
12439 transformed into canonical form." )
12441 (defvar org-todo-get-default-hook nil
12442 "Hook for functions that get a default item for todo.
12443 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12444 nil or a string to be used for the todo mark." )
12446 (defvar org-agenda-headline-snapshot-before-repeat)
12448 (defun org-current-effective-time ()
12449 "Return current time adjusted for `org-extend-today-until' variable."
12450 (let* ((ct (org-current-time))
12451 (dct (decode-time ct))
12452 (ct1
12453 (cond
12454 (org-use-last-clock-out-time-as-effective-time
12455 (or (org-clock-get-last-clock-out-time) ct))
12456 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12457 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12458 (t ct))))
12459 ct1))
12461 (defun org-todo-yesterday (&optional arg)
12462 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12463 (interactive "P")
12464 (if (eq major-mode 'org-agenda-mode)
12465 (apply 'org-agenda-todo-yesterday arg)
12466 (let* ((org-use-effective-time t)
12467 (hour (nth 2 (decode-time (org-current-time))))
12468 (org-extend-today-until (1+ hour)))
12469 (org-todo arg))))
12471 (defvar org-block-entry-blocking ""
12472 "First entry preventing the TODO state change.")
12474 (defun org-cancel-repeater ()
12475 "Cancel a repeater by setting its numeric value to zero."
12476 (interactive)
12477 (save-excursion
12478 (org-back-to-heading t)
12479 (let ((bound1 (point))
12480 (bound0 (save-excursion (outline-next-heading) (point))))
12481 (when (and (re-search-forward
12482 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12483 org-deadline-time-regexp "\\)\\|\\("
12484 org-ts-regexp "\\)")
12485 bound0 t)
12486 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12487 bound1 t))
12488 (replace-match "0" t nil nil 1)))))
12490 (defvar org-state) ;; dynamically scoped into this function
12491 (defun org-todo (&optional arg)
12492 "Change the TODO state of an item.
12493 The state of an item is given by a keyword at the start of the heading,
12494 like
12495 *** TODO Write paper
12496 *** DONE Call mom
12498 The different keywords are specified in the variable `org-todo-keywords'.
12499 By default the available states are \"TODO\" and \"DONE\".
12500 So for this example: when the item starts with TODO, it is changed to DONE.
12501 When it starts with DONE, the DONE is removed. And when neither TODO nor
12502 DONE are present, add TODO at the beginning of the heading.
12504 With \\[universal-argument] prefix arg, use completion to determine the new \
12505 state.
12506 With numeric prefix arg, switch to that state.
12507 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12508 keywords (nextset).
12509 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12510 With a numeric prefix arg of 0, inhibit note taking for the change.
12511 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12513 When called through ELisp, arg is also interpreted in the following way:
12514 `none' -> empty state
12515 \"\"(empty string) -> switch to empty state
12516 `done' -> switch to DONE
12517 `nextset' -> switch to the next set of keywords
12518 `previousset' -> switch to the previous set of keywords
12519 \"WAITING\" -> switch to the specified keyword, but only if it
12520 really is a member of `org-todo-keywords'."
12521 (interactive "P")
12522 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12523 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12524 'region-start-level 'region))
12525 org-loop-over-headlines-in-active-region)
12526 (org-map-entries
12527 `(org-todo ,arg)
12528 org-loop-over-headlines-in-active-region
12529 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12530 (when (equal arg '(16)) (setq arg 'nextset))
12531 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12532 (let ((org-blocker-hook org-blocker-hook)
12533 commentp
12534 case-fold-search)
12535 (when (equal arg '(64))
12536 (setq arg nil org-blocker-hook nil))
12537 (when (and org-blocker-hook
12538 (or org-inhibit-blocking
12539 (org-entry-get nil "NOBLOCKING")))
12540 (setq org-blocker-hook nil))
12541 (save-excursion
12542 (catch 'exit
12543 (org-back-to-heading t)
12544 (when (org-in-commented-heading-p t)
12545 (org-toggle-comment)
12546 (setq commentp t))
12547 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12548 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12549 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12550 (let* ((match-data (match-data))
12551 (startpos (point-at-bol))
12552 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12553 (org-log-done org-log-done)
12554 (org-log-repeat org-log-repeat)
12555 (org-todo-log-states org-todo-log-states)
12556 (org-inhibit-logging
12557 (if (equal arg 0)
12558 (progn (setq arg nil) 'note) org-inhibit-logging))
12559 (this (match-string 1))
12560 (hl-pos (match-beginning 0))
12561 (head (org-get-todo-sequence-head this))
12562 (ass (assoc head org-todo-kwd-alist))
12563 (interpret (nth 1 ass))
12564 (done-word (nth 3 ass))
12565 (final-done-word (nth 4 ass))
12566 (org-last-state (or this ""))
12567 (completion-ignore-case t)
12568 (member (member this org-todo-keywords-1))
12569 (tail (cdr member))
12570 (org-state (cond
12571 ((and org-todo-key-trigger
12572 (or (and (equal arg '(4))
12573 (eq org-use-fast-todo-selection 'prefix))
12574 (and (not arg) org-use-fast-todo-selection
12575 (not (eq org-use-fast-todo-selection
12576 'prefix)))))
12577 ;; Use fast selection
12578 (org-fast-todo-selection))
12579 ((and (equal arg '(4))
12580 (or (not org-use-fast-todo-selection)
12581 (not org-todo-key-trigger)))
12582 ;; Read a state with completion
12583 (completing-read
12584 "State: " (mapcar #'list org-todo-keywords-1)
12585 nil t))
12586 ((eq arg 'right)
12587 (if this
12588 (if tail (car tail) nil)
12589 (car org-todo-keywords-1)))
12590 ((eq arg 'left)
12591 (unless (equal member org-todo-keywords-1)
12592 (if this
12593 (nth (- (length org-todo-keywords-1)
12594 (length tail) 2)
12595 org-todo-keywords-1)
12596 (org-last org-todo-keywords-1))))
12597 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12598 (setq arg nil))) ; hack to fall back to cycling
12599 (arg
12600 ;; user or caller requests a specific state
12601 (cond
12602 ((equal arg "") nil)
12603 ((eq arg 'none) nil)
12604 ((eq arg 'done) (or done-word (car org-done-keywords)))
12605 ((eq arg 'nextset)
12606 (or (car (cdr (member head org-todo-heads)))
12607 (car org-todo-heads)))
12608 ((eq arg 'previousset)
12609 (let ((org-todo-heads (reverse org-todo-heads)))
12610 (or (car (cdr (member head org-todo-heads)))
12611 (car org-todo-heads))))
12612 ((car (member arg org-todo-keywords-1)))
12613 ((stringp arg)
12614 (user-error "State `%s' not valid in this file" arg))
12615 ((nth (1- (prefix-numeric-value arg))
12616 org-todo-keywords-1))))
12617 ((null member) (or head (car org-todo-keywords-1)))
12618 ((equal this final-done-word) nil) ;; -> make empty
12619 ((null tail) nil) ;; -> first entry
12620 ((memq interpret '(type priority))
12621 (if (eq this-command last-command)
12622 (car tail)
12623 (if (> (length tail) 0)
12624 (or done-word (car org-done-keywords))
12625 nil)))
12627 (car tail))))
12628 (org-state (or
12629 (run-hook-with-args-until-success
12630 'org-todo-get-default-hook org-state org-last-state)
12631 org-state))
12632 (next (if org-state (concat " " org-state " ") " "))
12633 (change-plist (list :type 'todo-state-change :from this :to org-state
12634 :position startpos))
12635 dolog now-done-p)
12636 (when org-blocker-hook
12637 (setq org-last-todo-state-is-todo
12638 (not (member this org-done-keywords)))
12639 (unless (save-excursion
12640 (save-match-data
12641 (org-with-wide-buffer
12642 (run-hook-with-args-until-failure
12643 'org-blocker-hook change-plist))))
12644 (if (org-called-interactively-p 'interactive)
12645 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12646 this org-state org-block-entry-blocking)
12647 ;; fail silently
12648 (message "TODO state change from %s to %s blocked (by \"%s\")"
12649 this org-state org-block-entry-blocking)
12650 (throw 'exit nil))))
12651 (store-match-data match-data)
12652 (replace-match next t t)
12653 (cond ((equal this org-state)
12654 (message "TODO state was already %s" (org-trim next)))
12655 ((pos-visible-in-window-p hl-pos)
12656 (message "TODO state changed to %s" (org-trim next))))
12657 (unless head
12658 (setq head (org-get-todo-sequence-head org-state)
12659 ass (assoc head org-todo-kwd-alist)
12660 interpret (nth 1 ass)
12661 done-word (nth 3 ass)
12662 final-done-word (nth 4 ass)))
12663 (when (memq arg '(nextset previousset))
12664 (message "Keyword-Set %d/%d: %s"
12665 (- (length org-todo-sets) -1
12666 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12667 (length org-todo-sets)
12668 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12669 (setq org-last-todo-state-is-todo
12670 (not (member org-state org-done-keywords)))
12671 (setq now-done-p (and (member org-state org-done-keywords)
12672 (not (member this org-done-keywords))))
12673 (and logging (org-local-logging logging))
12674 (when (and (or org-todo-log-states org-log-done)
12675 (not (eq org-inhibit-logging t))
12676 (not (memq arg '(nextset previousset))))
12677 ;; we need to look at recording a time and note
12678 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12679 (nth 2 (assoc this org-todo-log-states))))
12680 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12681 (setq dolog 'time))
12682 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12683 (and org-state
12684 (member org-state org-not-done-keywords)
12685 (not (member this org-not-done-keywords))))
12686 ;; This is now a todo state and was not one before
12687 ;; If there was a CLOSED time stamp, get rid of it.
12688 (org-add-planning-info nil nil 'closed))
12689 (when (and now-done-p org-log-done)
12690 ;; It is now done, and it was not done before
12691 (org-add-planning-info 'closed (org-current-effective-time))
12692 (when (and (not dolog) (eq 'note org-log-done))
12693 (org-add-log-setup 'done org-state this 'note)))
12694 (when (and org-state dolog)
12695 ;; This is a non-nil state, and we need to log it
12696 (org-add-log-setup 'state org-state this dolog)))
12697 ;; Fixup tag positioning
12698 (org-todo-trigger-tag-changes org-state)
12699 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12700 (when org-provide-todo-statistics
12701 (org-update-parent-todo-statistics))
12702 (run-hooks 'org-after-todo-state-change-hook)
12703 (when (and arg (not (member org-state org-done-keywords)))
12704 (setq head (org-get-todo-sequence-head org-state)))
12705 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12706 ;; Do we need to trigger a repeat?
12707 (when now-done-p
12708 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12709 ;; This is for the agenda, take a snapshot of the headline.
12710 (save-match-data
12711 (setq org-agenda-headline-snapshot-before-repeat
12712 (org-get-heading))))
12713 (org-auto-repeat-maybe org-state))
12714 ;; Fixup cursor location if close to the keyword
12715 (when (and (outline-on-heading-p)
12716 (not (bolp))
12717 (save-excursion (beginning-of-line 1)
12718 (looking-at org-todo-line-regexp))
12719 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12720 (goto-char (or (match-end 2) (match-end 1)))
12721 (and (looking-at " ") (just-one-space)))
12722 (when org-trigger-hook
12723 (save-excursion
12724 (run-hook-with-args 'org-trigger-hook change-plist)))
12725 (when commentp (org-toggle-comment))))))))
12727 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12728 "Block turning an entry into a TODO, using the hierarchy.
12729 This checks whether the current task should be blocked from state
12730 changes. Such blocking occurs when:
12732 1. The task has children which are not all in a completed state.
12734 2. A task has a parent with the property :ORDERED:, and there
12735 are siblings prior to the current task with incomplete
12736 status.
12738 3. The parent of the task is blocked because it has siblings that should
12739 be done first, or is child of a block grandparent TODO entry."
12741 (if (not org-enforce-todo-dependencies)
12742 t ; if locally turned off don't block
12743 (catch 'dont-block
12744 ;; If this is not a todo state change, or if this entry is already DONE,
12745 ;; do not block
12746 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12747 (member (plist-get change-plist :from)
12748 (cons 'done org-done-keywords))
12749 (member (plist-get change-plist :to)
12750 (cons 'todo org-not-done-keywords))
12751 (not (plist-get change-plist :to)))
12752 (throw 'dont-block t))
12753 ;; If this task has children, and any are undone, it's blocked
12754 (save-excursion
12755 (org-back-to-heading t)
12756 (let ((this-level (funcall outline-level)))
12757 (outline-next-heading)
12758 (let ((child-level (funcall outline-level)))
12759 (while (and (not (eobp))
12760 (> child-level this-level))
12761 ;; this todo has children, check whether they are all
12762 ;; completed
12763 (when (and (not (org-entry-is-done-p))
12764 (org-entry-is-todo-p))
12765 (setq org-block-entry-blocking (org-get-heading))
12766 (throw 'dont-block nil))
12767 (outline-next-heading)
12768 (setq child-level (funcall outline-level))))))
12769 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12770 ;; any previous siblings are undone, it's blocked
12771 (save-excursion
12772 (org-back-to-heading t)
12773 (let* ((pos (point))
12774 (parent-pos (and (org-up-heading-safe) (point))))
12775 (unless parent-pos (throw 'dont-block t)) ; no parent
12776 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12777 (forward-line 1)
12778 (re-search-forward org-not-done-heading-regexp pos t))
12779 (setq org-block-entry-blocking (match-string 0))
12780 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12781 ;; Search further up the hierarchy, to see if an ancestor is blocked
12782 (while t
12783 (goto-char parent-pos)
12784 (unless (looking-at org-not-done-heading-regexp)
12785 (throw 'dont-block t)) ; do not block, parent is not a TODO
12786 (setq pos (point))
12787 (setq parent-pos (and (org-up-heading-safe) (point)))
12788 (unless parent-pos (throw 'dont-block t)) ; no parent
12789 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12790 (forward-line 1)
12791 (re-search-forward org-not-done-heading-regexp pos t)
12792 (setq org-block-entry-blocking (org-get-heading)))
12793 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12795 (defcustom org-track-ordered-property-with-tag nil
12796 "Should the ORDERED property also be shown as a tag?
12797 The ORDERED property decides if an entry should require subtasks to be
12798 completed in sequence. Since a property is not very visible, setting
12799 this option means that toggling the ORDERED property with the command
12800 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12801 not relevant for the behavior, but it makes things more visible.
12803 Note that toggling the tag with tags commands will not change the property
12804 and therefore not influence behavior!
12806 This can be t, meaning the tag ORDERED should be used, It can also be a
12807 string to select a different tag for this task."
12808 :group 'org-todo
12809 :type '(choice
12810 (const :tag "No tracking" nil)
12811 (const :tag "Track with ORDERED tag" t)
12812 (string :tag "Use other tag")))
12814 (defun org-toggle-ordered-property ()
12815 "Toggle the ORDERED property of the current entry.
12816 For better visibility, you can track the value of this property with a tag.
12817 See variable `org-track-ordered-property-with-tag'."
12818 (interactive)
12819 (let* ((t1 org-track-ordered-property-with-tag)
12820 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12821 (save-excursion
12822 (org-back-to-heading)
12823 (if (org-entry-get nil "ORDERED")
12824 (progn
12825 (org-delete-property "ORDERED")
12826 (and tag (org-toggle-tag tag 'off))
12827 (message "Subtasks can be completed in arbitrary order"))
12828 (org-entry-put nil "ORDERED" "t")
12829 (and tag (org-toggle-tag tag 'on))
12830 (message "Subtasks must be completed in sequence")))))
12832 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12833 (defun org-block-todo-from-checkboxes (change-plist)
12834 "Block turning an entry into a TODO, using checkboxes.
12835 This checks whether the current task should be blocked from state
12836 changes because there are unchecked boxes in this entry."
12837 (if (not org-enforce-todo-checkbox-dependencies)
12838 t ; if locally turned off don't block
12839 (catch 'dont-block
12840 ;; If this is not a todo state change, or if this entry is already DONE,
12841 ;; do not block
12842 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12843 (member (plist-get change-plist :from)
12844 (cons 'done org-done-keywords))
12845 (member (plist-get change-plist :to)
12846 (cons 'todo org-not-done-keywords))
12847 (not (plist-get change-plist :to)))
12848 (throw 'dont-block t))
12849 ;; If this task has checkboxes that are not checked, it's blocked
12850 (save-excursion
12851 (org-back-to-heading t)
12852 (let ((beg (point)) end)
12853 (outline-next-heading)
12854 (setq end (point))
12855 (goto-char beg)
12856 (when (org-list-search-forward
12857 (concat (org-item-beginning-re)
12858 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12859 "\\[[- ]\\]")
12860 end t)
12861 (when (boundp 'org-blocked-by-checkboxes)
12862 (setq org-blocked-by-checkboxes t))
12863 (throw 'dont-block nil))))
12864 t))) ; do not block
12866 (defun org-entry-blocked-p ()
12867 "Non-nil if entry at point is blocked."
12868 (and (not (org-entry-get nil "NOBLOCKING"))
12869 (member (org-entry-get nil "TODO") org-not-done-keywords)
12870 (not (run-hook-with-args-until-failure
12871 'org-blocker-hook
12872 (list :type 'todo-state-change
12873 :position (point)
12874 :from 'todo
12875 :to 'done)))))
12877 (defun org-update-statistics-cookies (all)
12878 "Update the statistics cookie, either from TODO or from checkboxes.
12879 This should be called with the cursor in a line with a statistics cookie."
12880 (interactive "P")
12881 (if all
12882 (progn
12883 (org-update-checkbox-count 'all)
12884 (org-map-entries 'org-update-parent-todo-statistics))
12885 (if (not (org-at-heading-p))
12886 (org-update-checkbox-count)
12887 (let ((pos (point-marker))
12888 end l1 l2)
12889 (ignore-errors (org-back-to-heading t))
12890 (if (not (org-at-heading-p))
12891 (org-update-checkbox-count)
12892 (setq l1 (org-outline-level))
12893 (setq end (save-excursion
12894 (outline-next-heading)
12895 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12896 (point)))
12897 (if (and (save-excursion
12898 (re-search-forward
12899 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12900 (not (save-excursion (re-search-forward
12901 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12902 (org-update-checkbox-count)
12903 (if (and l2 (> l2 l1))
12904 (progn
12905 (goto-char end)
12906 (org-update-parent-todo-statistics))
12907 (goto-char pos)
12908 (beginning-of-line 1)
12909 (while (re-search-forward
12910 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12911 (point-at-eol) t)
12912 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12913 (goto-char pos)
12914 (move-marker pos nil)))))
12916 (defvar org-entry-property-inherited-from) ;; defined below
12917 (defun org-update-parent-todo-statistics ()
12918 "Update any statistics cookie in the parent of the current headline.
12919 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12920 the entire subtree and this will travel up the hierarchy and update
12921 statistics everywhere."
12922 (let* ((prop (save-excursion (org-up-heading-safe)
12923 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12924 (recursive (or (not org-hierarchical-todo-statistics)
12925 (and prop (string-match "\\<recursive\\>" prop))))
12926 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12928 (first t)
12929 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12930 level ltoggle l1 new ndel
12931 (cnt-all 0) (cnt-done 0) is-percent kwd
12932 checkbox-beg ov ovs ove cookie-present)
12933 (catch 'exit
12934 (save-excursion
12935 (beginning-of-line 1)
12936 (setq ltoggle (funcall outline-level))
12937 ;; Three situations are to consider:
12939 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12940 ;; to the top-level ancestor on the headline;
12942 ;; 2. If parent has "recursive" property, repeat up to the
12943 ;; headline setting that property, taking inheritance into
12944 ;; account;
12946 ;; 3. Else, move up to direct parent and proceed only once.
12947 (while (and (setq level (org-up-heading-safe))
12948 (or recursive first)
12949 (>= (point) lim))
12950 (setq first nil cookie-present nil)
12951 (unless (and level
12952 (not (string-match
12953 "\\<checkbox\\>"
12954 (downcase (or (org-entry-get nil "COOKIE_DATA")
12955 "")))))
12956 (throw 'exit nil))
12957 (while (re-search-forward box-re (point-at-eol) t)
12958 (setq cnt-all 0 cnt-done 0 cookie-present t)
12959 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12960 (save-match-data
12961 (unless (outline-next-heading) (throw 'exit nil))
12962 (while (and (looking-at org-complex-heading-regexp)
12963 (> (setq l1 (length (match-string 1))) level))
12964 (setq kwd (and (or recursive (= l1 ltoggle))
12965 (match-string 2)))
12966 (if (or (eq org-provide-todo-statistics 'all-headlines)
12967 (and (eq org-provide-todo-statistics t)
12968 (or (member kwd org-done-keywords)))
12969 (and (listp org-provide-todo-statistics)
12970 (stringp (car org-provide-todo-statistics))
12971 (or (member kwd org-provide-todo-statistics)
12972 (member kwd org-done-keywords)))
12973 (and (listp org-provide-todo-statistics)
12974 (listp (car org-provide-todo-statistics))
12975 (or (member kwd (car org-provide-todo-statistics))
12976 (and (member kwd org-done-keywords)
12977 (member kwd (cadr org-provide-todo-statistics))))))
12978 (setq cnt-all (1+ cnt-all))
12979 (and (eq org-provide-todo-statistics t)
12981 (setq cnt-all (1+ cnt-all))))
12982 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12983 (member kwd org-done-keywords))
12984 (and (listp org-provide-todo-statistics)
12985 (listp (car org-provide-todo-statistics))
12986 (member kwd org-done-keywords)
12987 (member kwd (cadr org-provide-todo-statistics)))
12988 (and (listp org-provide-todo-statistics)
12989 (stringp (car org-provide-todo-statistics))
12990 (member kwd org-done-keywords)))
12991 (setq cnt-done (1+ cnt-done)))
12992 (outline-next-heading)))
12993 (setq new
12994 (if is-percent
12995 (format "[%d%%]" (floor (* 100.0 cnt-done)
12996 (max 1 cnt-all)))
12997 (format "[%d/%d]" cnt-done cnt-all))
12998 ndel (- (match-end 0) checkbox-beg))
12999 ;; handle overlays when updating cookie from column view
13000 (when (setq ov (car (overlays-at checkbox-beg)))
13001 (setq ovs (overlay-start ov) ove (overlay-end ov))
13002 (delete-overlay ov))
13003 (goto-char checkbox-beg)
13004 (insert new)
13005 (delete-region (point) (+ (point) ndel))
13006 (when org-auto-align-tags (org-fix-tags-on-the-fly))
13007 (when ov (move-overlay ov ovs ove)))
13008 (when cookie-present
13009 (run-hook-with-args 'org-after-todo-statistics-hook
13010 cnt-done (- cnt-all cnt-done))))))
13011 (run-hooks 'org-todo-statistics-hook)))
13013 (defvar org-after-todo-statistics-hook nil
13014 "Hook that is called after a TODO statistics cookie has been updated.
13015 Each function is called with two arguments: the number of not-done entries
13016 and the number of done entries.
13018 For example, the following function, when added to this hook, will switch
13019 an entry to DONE when all children are done, and back to TODO when new
13020 entries are set to a TODO status. Note that this hook is only called
13021 when there is a statistics cookie in the headline!
13023 \(defun org-summary-todo (n-done n-not-done)
13024 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
13025 \(let (org-log-done org-log-states) ; turn off logging
13026 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
13029 (defvar org-todo-statistics-hook nil
13030 "Hook that is run whenever Org thinks TODO statistics should be updated.
13031 This hook runs even if there is no statistics cookie present, in which case
13032 `org-after-todo-statistics-hook' would not run.")
13034 (defun org-todo-trigger-tag-changes (state)
13035 "Apply the changes defined in `org-todo-state-tags-triggers'."
13036 (let ((l org-todo-state-tags-triggers)
13037 changes)
13038 (when (or (not state) (equal state ""))
13039 (setq changes (append changes (cdr (assoc "" l)))))
13040 (when (and (stringp state) (> (length state) 0))
13041 (setq changes (append changes (cdr (assoc state l)))))
13042 (when (member state org-not-done-keywords)
13043 (setq changes (append changes (cdr (assoc 'todo l)))))
13044 (when (member state org-done-keywords)
13045 (setq changes (append changes (cdr (assoc 'done l)))))
13046 (dolist (c changes)
13047 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
13049 (defun org-local-logging (value)
13050 "Get logging settings from a property VALUE."
13051 ;; Directly set the variables, they are already local.
13052 (setq org-log-done nil
13053 org-log-repeat nil
13054 org-todo-log-states nil)
13055 (dolist (w (org-split-string value))
13056 (let (a)
13057 (cond
13058 ((setq a (assoc w org-startup-options))
13059 (and (member (nth 1 a) '(org-log-done org-log-repeat))
13060 (set (nth 1 a) (nth 2 a))))
13061 ((setq a (org-extract-log-state-settings w))
13062 (and (member (car a) org-todo-keywords-1)
13063 (push a org-todo-log-states)))))))
13065 (defun org-get-todo-sequence-head (kwd)
13066 "Return the head of the TODO sequence to which KWD belongs.
13067 If KWD is not set, check if there is a text property remembering the
13068 right sequence."
13069 (let (p)
13070 (cond
13071 ((not kwd)
13072 (or (get-text-property (point-at-bol) 'org-todo-head)
13073 (progn
13074 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13075 nil (point-at-eol)))
13076 (get-text-property p 'org-todo-head))))
13077 ((not (member kwd org-todo-keywords-1))
13078 (car org-todo-keywords-1))
13079 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13081 (defun org-fast-todo-selection ()
13082 "Fast TODO keyword selection with single keys.
13083 Returns the new TODO keyword, or nil if no state change should occur."
13084 (let* ((fulltable org-todo-key-alist)
13085 (done-keywords org-done-keywords) ;; needed for the faces.
13086 (maxlen (apply 'max (mapcar
13087 (lambda (x)
13088 (if (stringp (car x)) (string-width (car x)) 0))
13089 fulltable)))
13090 (expert nil)
13091 (fwidth (+ maxlen 3 1 3))
13092 (ncol (/ (- (window-width) 4) fwidth))
13093 tg cnt e c tbl
13094 groups ingroup)
13095 (save-excursion
13096 (save-window-excursion
13097 (if expert
13098 (set-buffer (get-buffer-create " *Org todo*"))
13099 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13100 (erase-buffer)
13101 (setq-local org-done-keywords done-keywords)
13102 (setq tbl fulltable cnt 0)
13103 (while (setq e (pop tbl))
13104 (cond
13105 ((equal e '(:startgroup))
13106 (push '() groups) (setq ingroup t)
13107 (unless (= cnt 0)
13108 (setq cnt 0)
13109 (insert "\n"))
13110 (insert "{ "))
13111 ((equal e '(:endgroup))
13112 (setq ingroup nil cnt 0)
13113 (insert "}\n"))
13114 ((equal e '(:newline))
13115 (unless (= cnt 0)
13116 (setq cnt 0)
13117 (insert "\n")
13118 (setq e (car tbl))
13119 (while (equal (car tbl) '(:newline))
13120 (insert "\n")
13121 (setq tbl (cdr tbl)))))
13123 (setq tg (car e) c (cdr e))
13124 (when ingroup (push tg (car groups)))
13125 (setq tg (org-add-props tg nil 'face
13126 (org-get-todo-face tg)))
13127 (when (and (= cnt 0) (not ingroup)) (insert " "))
13128 (insert "[" c "] " tg (make-string
13129 (- fwidth 4 (length tg)) ?\ ))
13130 (when (= (setq cnt (1+ cnt)) ncol)
13131 (insert "\n")
13132 (when ingroup (insert " "))
13133 (setq cnt 0)))))
13134 (insert "\n")
13135 (goto-char (point-min))
13136 (unless expert (org-fit-window-to-buffer))
13137 (message "[a-z..]:Set [SPC]:clear")
13138 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13139 (cond
13140 ((or (= c ?\C-g)
13141 (and (= c ?q) (not (rassoc c fulltable))))
13142 (setq quit-flag t))
13143 ((= c ?\ ) nil)
13144 ((setq e (rassoc c fulltable) tg (car e))
13146 (t (setq quit-flag t)))))))
13148 (defun org-entry-is-todo-p ()
13149 (member (org-get-todo-state) org-not-done-keywords))
13151 (defun org-entry-is-done-p ()
13152 (member (org-get-todo-state) org-done-keywords))
13154 (defun org-get-todo-state ()
13155 "Return the TODO keyword of the current subtree."
13156 (save-excursion
13157 (org-back-to-heading t)
13158 (and (looking-at org-todo-line-regexp)
13159 (match-end 2)
13160 (match-string 2))))
13162 (defun org-at-date-range-p (&optional inactive-ok)
13163 "Non-nil if point is inside a date range.
13165 When optional argument INACTIVE-OK is non-nil, also consider
13166 inactive time ranges.
13168 When this function returns a non-nil value, match data is set
13169 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13170 on INACTIVE-OK."
13171 (interactive)
13172 (save-excursion
13173 (catch 'exit
13174 (let ((pos (point)))
13175 (skip-chars-backward "^[<\r\n")
13176 (skip-chars-backward "<[")
13177 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13178 (>= (match-end 0) pos)
13179 (throw 'exit t))
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 nil)))
13187 (defun org-get-repeat (&optional tagline)
13188 "Check if there is a deadline/schedule with repeater in this entry."
13189 (save-match-data
13190 (save-excursion
13191 (org-back-to-heading t)
13192 (and (re-search-forward (if tagline
13193 (concat tagline "\\s-*" org-repeat-re)
13194 org-repeat-re)
13195 (org-entry-end-position) t)
13196 (match-string-no-properties 1)))))
13198 (defvar org-last-changed-timestamp)
13199 (defvar org-last-inserted-timestamp)
13200 (defvar org-log-post-message)
13201 (defvar org-log-note-purpose)
13202 (defvar org-log-note-how nil)
13203 (defvar org-log-note-extra)
13204 (defun org-auto-repeat-maybe (done-word)
13205 "Check if the current headline contains a repeated time-stamp.
13207 If yes, set TODO state back to what it was and change the base date
13208 of repeating deadline/scheduled time stamps to new date.
13210 This function is run automatically after each state change to a DONE state."
13211 (let* ((repeat (org-get-repeat))
13212 (aa (assoc org-last-state org-todo-kwd-alist))
13213 (interpret (nth 1 aa))
13214 (head (nth 2 aa))
13215 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13216 (msg "Entry repeats: ")
13217 (org-log-done nil)
13218 (org-todo-log-states nil))
13219 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13220 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13221 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13222 org-todo-repeat-to-state)))
13223 (unless (and to-state (member to-state org-todo-keywords-1))
13224 (setq to-state (if (eq interpret 'type) org-last-state head)))
13225 (org-todo to-state))
13226 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13227 (org-entry-put nil "LAST_REPEAT" (format-time-string
13228 (org-time-stamp-format t t))))
13229 (when org-log-repeat
13230 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13231 (memq 'org-add-log-note post-command-hook))
13232 ;; We are already setup for some record.
13233 (when (eq org-log-repeat 'note)
13234 ;; Make sure we take a note, not only a time stamp.
13235 (setq org-log-note-how 'note))
13236 ;; Set up for taking a record.
13237 (org-add-log-setup 'state
13238 (or done-word (car org-done-keywords))
13239 org-last-state
13240 org-log-repeat)))
13241 (org-back-to-heading t)
13242 (org-add-planning-info nil nil 'closed)
13243 (let ((end (save-excursion (outline-next-heading) (point))))
13244 (while (re-search-forward org-ts-regexp end t)
13245 (when (save-match-data
13246 (or (org-at-planning-p)
13247 (org-at-property-p)
13248 (eq (org-element-type (save-excursion
13249 (backward-char)
13250 (org-element-context)))
13251 'timestamp)))
13252 (let ((type (cond ((match-end 1) org-scheduled-string)
13253 ((match-end 3) org-deadline-string)
13254 (t "Plain:")))
13255 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13256 (cond
13257 ((not
13258 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13259 ;; Time-stamps without a repeater are usually skipped.
13260 ;; However, a SCHEDULED time-stamp without one is
13261 ;; removed, as it is considered as no longer relevant.
13262 (when (equal type org-scheduled-string)
13263 (org-remove-timestamp-with-keyword type)))
13265 (let ((n (string-to-number (match-string 2 ts)))
13266 (what (match-string 3 ts)))
13267 (when (equal what "w") (setq n (* n 7) what "d"))
13268 (when (and (equal what "h")
13269 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13270 ts)))
13271 (user-error
13272 "Cannot repeat in Repeat in %d hour(s) because no hour \
13273 has been set"
13275 ;; Preparation, see if we need to modify the start
13276 ;; date for the change.
13277 (when (match-end 1)
13278 (let ((time (save-match-data (org-time-string-to-time ts))))
13279 (cond
13280 ((equal (match-string 1 ts) ".")
13281 ;; Shift starting date to today
13282 (org-timestamp-change
13283 (- (org-today) (time-to-days time))
13284 'day))
13285 ((equal (match-string 1 ts) "+")
13286 (let ((nshiftmax 10)
13287 (nshift 0))
13288 (while (or (= nshift 0)
13289 (<= (time-to-days time)
13290 (time-to-days (current-time))))
13291 (when (= (cl-incf nshift) nshiftmax)
13292 (or (y-or-n-p
13293 (format "%d repeater intervals were not \
13294 enough to shift date past today. Continue? "
13295 nshift))
13296 (user-error "Abort")))
13297 (org-timestamp-change n (cdr (assoc what whata)))
13298 (org-at-timestamp-p t)
13299 (setq ts (match-string 1))
13300 (setq time
13301 (save-match-data
13302 (org-time-string-to-time ts)))))
13303 (org-timestamp-change (- n) (cdr (assoc what whata)))
13304 ;; Rematch, so that we have everything in
13305 ;; place for the real shift.
13306 (org-at-timestamp-p t)
13307 (setq ts (match-string 1))
13308 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13309 ts)))))
13310 (save-excursion
13311 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13312 (setq msg
13313 (concat
13314 msg type " " org-last-changed-timestamp " ")))))))))
13315 (setq org-log-post-message msg)
13316 (message "%s" msg))))
13318 (defun org-show-todo-tree (arg)
13319 "Make a compact tree which shows all headlines marked with TODO.
13320 The tree will show the lines where the regexp matches, and all higher
13321 headlines above the match.
13322 With a \\[universal-argument] prefix, prompt for a regexp to match.
13323 With a numeric prefix N, construct a sparse tree for the Nth element
13324 of `org-todo-keywords-1'."
13325 (interactive "P")
13326 (let ((case-fold-search nil)
13327 (kwd-re
13328 (cond ((null arg) org-not-done-regexp)
13329 ((equal arg '(4))
13330 (let ((kwd
13331 (completing-read "Keyword (or KWD1|KWD2|...): "
13332 (mapcar #'list org-todo-keywords-1))))
13333 (concat "\\("
13334 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13335 "\\)\\>")))
13336 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13337 (regexp-quote (nth (1- (prefix-numeric-value arg))
13338 org-todo-keywords-1)))
13339 (t (user-error "Invalid prefix argument: %s" arg)))))
13340 (message "%d TODO entries found"
13341 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13343 (defun org-deadline (arg &optional time)
13344 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13345 With one universal prefix argument, remove any deadline from the item.
13346 With two universal prefix arguments, prompt for a warning delay.
13347 With argument TIME, set the deadline at the corresponding date. TIME
13348 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13349 (interactive "P")
13350 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13351 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13352 'region-start-level 'region))
13353 org-loop-over-headlines-in-active-region)
13354 (org-map-entries
13355 `(org-deadline ',arg ,time)
13356 org-loop-over-headlines-in-active-region
13357 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13358 (let* ((old-date (org-entry-get nil "DEADLINE"))
13359 (old-date-time (when old-date (org-time-string-to-time old-date)))
13360 (repeater (and old-date
13361 (string-match
13362 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13363 old-date)
13364 (match-string 1 old-date))))
13365 (cond
13366 ((equal arg '(4))
13367 (when (and old-date org-log-redeadline)
13368 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13369 (org-remove-timestamp-with-keyword org-deadline-string)
13370 (message "Item no longer has a deadline."))
13371 ((equal arg '(16))
13372 (save-excursion
13373 (org-back-to-heading t)
13374 (if (re-search-forward
13375 org-deadline-time-regexp
13376 (save-excursion (outline-next-heading) (point)) t)
13377 (let* ((rpl0 (match-string 1))
13378 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13379 (replace-match
13380 (concat org-deadline-string
13381 " <" rpl
13382 (format " -%dd"
13383 (abs
13384 (- (time-to-days
13385 (save-match-data
13386 (org-read-date nil t nil "Warn starting from" old-date-time)))
13387 (time-to-days old-date-time))))
13388 ">") t t))
13389 (user-error "No deadline information to update"))))
13391 (org-add-planning-info 'deadline time 'closed)
13392 (when (and old-date
13393 org-log-redeadline
13394 (not (equal old-date org-last-inserted-timestamp)))
13395 (org-add-log-setup
13396 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13397 (when repeater
13398 (save-excursion
13399 (org-back-to-heading t)
13400 (when (re-search-forward (concat org-deadline-string " "
13401 org-last-inserted-timestamp)
13402 (save-excursion
13403 (outline-next-heading) (point)) t)
13404 (goto-char (1- (match-end 0)))
13405 (insert " " repeater)
13406 (setq org-last-inserted-timestamp
13407 (concat (substring org-last-inserted-timestamp 0 -1)
13408 " " repeater
13409 (substring org-last-inserted-timestamp -1))))))
13410 (message "Deadline on %s" org-last-inserted-timestamp))))))
13412 (defun org-schedule (arg &optional time)
13413 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13414 With one universal prefix argument, remove any scheduling date from the item.
13415 With two universal prefix arguments, prompt for a delay cookie.
13416 With argument TIME, scheduled at the corresponding date. TIME can
13417 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13418 (interactive "P")
13419 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13420 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13421 'region-start-level 'region))
13422 org-loop-over-headlines-in-active-region)
13423 (org-map-entries
13424 `(org-schedule ',arg ,time)
13425 org-loop-over-headlines-in-active-region
13426 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13427 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13428 (old-date-time (when old-date (org-time-string-to-time old-date)))
13429 (repeater (and old-date
13430 (string-match
13431 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13432 old-date)
13433 (match-string 1 old-date))))
13434 (cond
13435 ((equal arg '(4))
13436 (progn
13437 (when (and old-date org-log-reschedule)
13438 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13439 (org-remove-timestamp-with-keyword org-scheduled-string)
13440 (message "Item is no longer scheduled.")))
13441 ((equal arg '(16))
13442 (save-excursion
13443 (org-back-to-heading t)
13444 (if (re-search-forward
13445 org-scheduled-time-regexp
13446 (save-excursion (outline-next-heading) (point)) t)
13447 (let* ((rpl0 (match-string 1))
13448 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13449 (replace-match
13450 (concat org-scheduled-string
13451 " <" rpl
13452 (format " -%dd"
13453 (abs
13454 (- (time-to-days
13455 (save-match-data
13456 (org-read-date nil t nil "Delay until" old-date-time)))
13457 (time-to-days old-date-time))))
13458 ">") t t))
13459 (user-error "No scheduled information to update"))))
13461 (org-add-planning-info 'scheduled time 'closed)
13462 (when (and old-date
13463 org-log-reschedule
13464 (not (equal old-date org-last-inserted-timestamp)))
13465 (org-add-log-setup
13466 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13467 (when repeater
13468 (save-excursion
13469 (org-back-to-heading t)
13470 (when (re-search-forward (concat org-scheduled-string " "
13471 org-last-inserted-timestamp)
13472 (save-excursion
13473 (outline-next-heading) (point)) t)
13474 (goto-char (1- (match-end 0)))
13475 (insert " " repeater)
13476 (setq org-last-inserted-timestamp
13477 (concat (substring org-last-inserted-timestamp 0 -1)
13478 " " repeater
13479 (substring org-last-inserted-timestamp -1))))))
13480 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13482 (defun org-get-scheduled-time (pom &optional inherit)
13483 "Get the scheduled time as a time tuple, of a format suitable
13484 for calling org-schedule with, or if there is no scheduling,
13485 returns nil."
13486 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13487 (when time
13488 (apply 'encode-time (org-parse-time-string time)))))
13490 (defun org-get-deadline-time (pom &optional inherit)
13491 "Get the deadline as a time tuple, of a format suitable for
13492 calling org-deadline with, or if there is no scheduling, returns
13493 nil."
13494 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13495 (when time
13496 (apply 'encode-time (org-parse-time-string time)))))
13498 (defun org-remove-timestamp-with-keyword (keyword)
13499 "Remove all time stamps with KEYWORD in the current entry."
13500 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13501 beg)
13502 (save-excursion
13503 (org-back-to-heading t)
13504 (setq beg (point))
13505 (outline-next-heading)
13506 (while (re-search-backward re beg t)
13507 (replace-match "")
13508 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13509 (equal (char-before) ?\ ))
13510 (backward-delete-char 1)
13511 (when (string-match "^[ \t]*$" (buffer-substring
13512 (point-at-bol) (point-at-eol)))
13513 (delete-region (point-at-bol)
13514 (min (point-max) (1+ (point-at-eol))))))))))
13516 (defvar org-time-was-given) ; dynamically scoped parameter
13517 (defvar org-end-time-was-given) ; dynamically scoped parameter
13519 (defun org-at-planning-p ()
13520 "Non-nil when point is on a planning info line."
13521 ;; This is as accurate and faster than `org-element-at-point' since
13522 ;; planning info location is fixed in the section.
13523 (org-with-wide-buffer
13524 (beginning-of-line)
13525 (and (looking-at-p org-planning-line-re)
13526 (eq (point)
13527 (ignore-errors
13528 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13529 (org-back-to-heading t)
13530 (org-with-limited-levels (org-back-to-heading t)))
13531 (line-beginning-position 2))))))
13533 (defun org-add-planning-info (what &optional time &rest remove)
13534 "Insert new timestamp with keyword in the planning line.
13535 WHAT indicates what kind of time stamp to add. It is a symbol
13536 among `closed', `deadline', `scheduled' and nil. TIME indicates
13537 the time to use. If none is given, the user is prompted for
13538 a date. REMOVE indicates what kind of entries to remove. An old
13539 WHAT entry will also be removed."
13540 (let (org-time-was-given org-end-time-was-given default-time default-input)
13541 (catch 'exit
13542 (when (and (memq what '(scheduled deadline))
13543 (or (not time)
13544 (and (stringp time)
13545 (string-match "^[-+]+[0-9]" time))))
13546 ;; Try to get a default date/time from existing timestamp
13547 (save-excursion
13548 (org-back-to-heading t)
13549 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13550 (when (re-search-forward (if (eq what 'scheduled)
13551 org-scheduled-time-regexp
13552 org-deadline-time-regexp)
13553 end t)
13554 (setq ts (match-string 1)
13555 default-time (apply 'encode-time (org-parse-time-string ts))
13556 default-input (and ts (org-get-compact-tod ts)))))))
13557 (when what
13558 (setq time
13559 (if (stringp time)
13560 ;; This is a string (relative or absolute), set
13561 ;; proper date.
13562 (apply #'encode-time
13563 (org-read-date-analyze
13564 time default-time (decode-time default-time)))
13565 ;; If necessary, get the time from the user
13566 (or time (org-read-date nil 'to-time nil nil
13567 default-time default-input)))))
13569 (org-with-wide-buffer
13570 (org-back-to-heading t)
13571 (forward-line)
13572 (unless (bolp) (insert "\n"))
13573 (cond ((looking-at-p org-planning-line-re)
13574 ;; Move to current indentation.
13575 (skip-chars-forward " \t")
13576 ;; Check if we have to remove something.
13577 (dolist (type (if what (cons what remove) remove))
13578 (save-excursion
13579 (when (re-search-forward
13580 (cl-case type
13581 (closed org-closed-time-regexp)
13582 (deadline org-deadline-time-regexp)
13583 (scheduled org-scheduled-time-regexp)
13584 (otherwise
13585 (error "Invalid planning type: %s" type)))
13586 (line-end-position) t)
13587 ;; Delete until next keyword or end of line.
13588 (delete-region
13589 (match-beginning 0)
13590 (if (re-search-forward org-keyword-time-not-clock-regexp
13591 (line-end-position)
13593 (match-beginning 0)
13594 (line-end-position))))))
13595 ;; If there is nothing more to add and no more keyword
13596 ;; is left, remove the line completely.
13597 (if (and (looking-at-p "[ \t]*$") (not what))
13598 (delete-region (line-beginning-position)
13599 (line-beginning-position 2))
13600 ;; If we removed last keyword, do not leave trailing
13601 ;; white space at the end of line.
13602 (let ((p (point)))
13603 (save-excursion
13604 (end-of-line)
13605 (unless (= (skip-chars-backward " \t" p) 0)
13606 (delete-region (point) (line-end-position)))))))
13607 ((not what) (throw 'exit nil)) ; Nothing to do.
13608 (t (insert-before-markers "\n")
13609 (backward-char 1)
13610 (when org-adapt-indentation
13611 (indent-to-column (1+ (org-outline-level))))))
13612 (when what
13613 ;; Insert planning keyword.
13614 (insert (cl-case what
13615 (closed org-closed-string)
13616 (deadline org-deadline-string)
13617 (scheduled org-scheduled-string)
13618 (otherwise (error "Invalid planning type: %s" what)))
13619 " ")
13620 ;; Insert associated timestamp.
13621 (let ((ts (org-insert-time-stamp
13622 time
13623 (or org-time-was-given
13624 (and (eq what 'closed) org-log-done-with-time))
13625 (eq what 'closed)
13626 nil nil (list org-end-time-was-given))))
13627 (unless (eolp) (insert " "))
13628 ts))))))
13630 (defvar org-log-note-marker (make-marker)
13631 "Marker pointing at the entry where the note is to be inserted.")
13632 (defvar org-log-note-purpose nil)
13633 (defvar org-log-note-state nil)
13634 (defvar org-log-note-previous-state nil)
13635 (defvar org-log-note-extra nil)
13636 (defvar org-log-note-window-configuration nil)
13637 (defvar org-log-note-return-to (make-marker))
13638 (defvar org-log-note-effective-time nil
13639 "Remembered current time so that dynamically scoped
13640 `org-extend-today-until' affects timestamps in state change log")
13642 (defvar org-log-post-message nil
13643 "Message to be displayed after a log note has been stored.
13644 The auto-repeater uses this.")
13646 (defun org-add-note ()
13647 "Add a note to the current entry.
13648 This is done in the same way as adding a state change note."
13649 (interactive)
13650 (org-add-log-setup 'note))
13652 (defun org-log-beginning (&optional create)
13653 "Return expected start of log notes in current entry.
13654 When optional argument CREATE is non-nil, the function creates
13655 a drawer to store notes, if necessary. Returned position ignores
13656 narrowing."
13657 (org-with-wide-buffer
13658 (let ((drawer (org-log-into-drawer)))
13659 (cond
13660 (drawer
13661 (org-end-of-meta-data)
13662 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13663 (end (if (org-at-heading-p) (point)
13664 (save-excursion (outline-next-heading) (point))))
13665 (case-fold-search t))
13666 (catch 'exit
13667 ;; Try to find existing drawer.
13668 (while (re-search-forward regexp end t)
13669 (let ((element (org-element-at-point)))
13670 (when (eq (org-element-type element) 'drawer)
13671 (let ((cend (org-element-property :contents-end element)))
13672 (when (and (not org-log-states-order-reversed) cend)
13673 (goto-char cend)))
13674 (throw 'exit nil))))
13675 ;; No drawer found. Create one, if permitted.
13676 (when create
13677 (unless (bolp) (insert "\n"))
13678 (let ((beg (point)))
13679 (insert ":" drawer ":\n:END:\n")
13680 (org-indent-region beg (point)))
13681 (end-of-line -1)))))
13683 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13684 (skip-chars-forward " \t\n")
13685 (beginning-of-line)
13686 (unless org-log-states-order-reversed
13687 (org-skip-over-state-notes)
13688 (skip-chars-backward " \t\n")
13689 (forward-line)))))
13690 (if (bolp) (point) (line-beginning-position 2))))
13692 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13693 "Set up the post command hook to take a note.
13694 If this is about to TODO state change, the new state is expected in STATE.
13695 HOW is an indicator what kind of note should be created.
13696 EXTRA is additional text that will be inserted into the notes buffer."
13697 (move-marker org-log-note-marker (point))
13698 (setq org-log-note-purpose purpose
13699 org-log-note-state state
13700 org-log-note-previous-state prev-state
13701 org-log-note-how how
13702 org-log-note-extra extra
13703 org-log-note-effective-time (org-current-effective-time))
13704 (add-hook 'post-command-hook 'org-add-log-note 'append))
13706 (defun org-skip-over-state-notes ()
13707 "Skip past the list of State notes in an entry."
13708 (when (ignore-errors (goto-char (org-in-item-p)))
13709 (let* ((struct (org-list-struct))
13710 (prevs (org-list-prevs-alist struct))
13711 (regexp
13712 (concat "[ \t]*- +"
13713 (replace-regexp-in-string
13714 " +" " +"
13715 (org-replace-escapes
13716 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13717 `(("%d" . ,org-ts-regexp-inactive)
13718 ("%D" . ,org-ts-regexp)
13719 ("%s" . "\"\\S-+\"")
13720 ("%S" . "\"\\S-+\"")
13721 ("%t" . ,org-ts-regexp-inactive)
13722 ("%T" . ,org-ts-regexp)
13723 ("%u" . ".*?")
13724 ("%U" . ".*?")))))))
13725 (while (looking-at-p regexp)
13726 (goto-char (or (org-list-get-next-item (point) struct prevs)
13727 (org-list-get-item-end (point) struct)))))))
13729 (defun org-add-log-note (&optional _purpose)
13730 "Pop up a window for taking a note, and add this note later."
13731 (remove-hook 'post-command-hook 'org-add-log-note)
13732 (setq org-log-note-window-configuration (current-window-configuration))
13733 (delete-other-windows)
13734 (move-marker org-log-note-return-to (point))
13735 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13736 (goto-char org-log-note-marker)
13737 (org-switch-to-buffer-other-window "*Org Note*")
13738 (erase-buffer)
13739 (if (memq org-log-note-how '(time state))
13740 (let (current-prefix-arg) (org-store-log-note))
13741 (let ((org-inhibit-startup t)) (org-mode))
13742 (insert (format "# Insert note for %s.
13743 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13744 (cond
13745 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13746 ((eq org-log-note-purpose 'done) "closed todo item")
13747 ((eq org-log-note-purpose 'state)
13748 (format "state change from \"%s\" to \"%s\""
13749 (or org-log-note-previous-state "")
13750 (or org-log-note-state "")))
13751 ((eq org-log-note-purpose 'reschedule)
13752 "rescheduling")
13753 ((eq org-log-note-purpose 'delschedule)
13754 "no longer scheduled")
13755 ((eq org-log-note-purpose 'redeadline)
13756 "changing deadline")
13757 ((eq org-log-note-purpose 'deldeadline)
13758 "removing deadline")
13759 ((eq org-log-note-purpose 'refile)
13760 "refiling")
13761 ((eq org-log-note-purpose 'note)
13762 "this entry")
13763 (t (error "This should not happen")))))
13764 (when org-log-note-extra (insert org-log-note-extra))
13765 (setq-local org-finish-function 'org-store-log-note)
13766 (run-hooks 'org-log-buffer-setup-hook)))
13768 (defvar org-note-abort nil) ; dynamically scoped
13769 (defun org-store-log-note ()
13770 "Finish taking a log note, and insert it to where it belongs."
13771 (let ((txt (prog1 (buffer-string)
13772 (kill-buffer)))
13773 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13774 lines)
13775 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13776 (setq txt (replace-match "" t t txt)))
13777 (when (string-match "\\s-+\\'" txt)
13778 (setq txt (replace-match "" t t txt)))
13779 (setq lines (org-split-string txt "\n"))
13780 (when (org-string-nw-p note)
13781 (setq note
13782 (org-replace-escapes
13783 note
13784 (list (cons "%u" (user-login-name))
13785 (cons "%U" user-full-name)
13786 (cons "%t" (format-time-string
13787 (org-time-stamp-format 'long 'inactive)
13788 org-log-note-effective-time))
13789 (cons "%T" (format-time-string
13790 (org-time-stamp-format 'long nil)
13791 org-log-note-effective-time))
13792 (cons "%d" (format-time-string
13793 (org-time-stamp-format nil 'inactive)
13794 org-log-note-effective-time))
13795 (cons "%D" (format-time-string
13796 (org-time-stamp-format nil nil)
13797 org-log-note-effective-time))
13798 (cons "%s" (cond
13799 ((not org-log-note-state) "")
13800 ((org-string-match-p org-ts-regexp
13801 org-log-note-state)
13802 (format "\"[%s]\""
13803 (substring org-log-note-state 1 -1)))
13804 (t (format "\"%s\"" org-log-note-state))))
13805 (cons "%S"
13806 (cond
13807 ((not org-log-note-previous-state) "")
13808 ((org-string-match-p org-ts-regexp
13809 org-log-note-previous-state)
13810 (format "\"[%s]\""
13811 (substring
13812 org-log-note-previous-state 1 -1)))
13813 (t (format "\"%s\""
13814 org-log-note-previous-state)))))))
13815 (when lines (setq note (concat note " \\\\")))
13816 (push note lines))
13817 (when (and lines (not (or current-prefix-arg org-note-abort)))
13818 (with-current-buffer (marker-buffer org-log-note-marker)
13819 (org-with-wide-buffer
13820 ;; Find location for the new note.
13821 (goto-char org-log-note-marker)
13822 (set-marker org-log-note-marker nil)
13823 (goto-char (org-log-beginning t))
13824 ;; Make sure point is at the beginning of an empty line.
13825 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13826 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13827 ;; In an existing list, add a new item at the top level.
13828 ;; Otherwise, indent line like a regular one.
13829 (let ((itemp (org-in-item-p)))
13830 (if itemp
13831 (indent-line-to
13832 (let ((struct (save-excursion
13833 (goto-char itemp) (org-list-struct))))
13834 (org-list-get-ind (org-list-get-top-point struct) struct)))
13835 (org-indent-line)))
13836 (insert (org-list-bullet-string "-") (pop lines))
13837 (let ((ind (org-list-item-body-column (line-beginning-position))))
13838 (dolist (line lines)
13839 (insert "\n")
13840 (indent-line-to ind)
13841 (insert line)))
13842 (message "Note stored")
13843 (org-back-to-heading t)
13844 (org-cycle-hide-drawers 'children))
13845 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13846 ;; from within `org-add-log-note' because `buffer-undo-list'
13847 ;; is then modified outside of `org-with-remote-undo'.
13848 (when (eq this-command 'org-agenda-todo)
13849 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13850 ;; Don't add undo information when called from `org-agenda-todo'.
13851 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13852 (set-window-configuration org-log-note-window-configuration)
13853 (with-current-buffer (marker-buffer org-log-note-return-to)
13854 (goto-char org-log-note-return-to))
13855 (move-marker org-log-note-return-to nil)
13856 (when org-log-post-message (message "%s" org-log-post-message))))
13858 (defun org-remove-empty-drawer-at (pos)
13859 "Remove an empty drawer at position POS.
13860 POS may also be a marker."
13861 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13862 (org-with-wide-buffer
13863 (goto-char pos)
13864 (let ((drawer (org-element-at-point)))
13865 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13866 (not (org-element-property :contents-begin drawer)))
13867 (delete-region (org-element-property :begin drawer)
13868 (progn (goto-char (org-element-property :end drawer))
13869 (skip-chars-backward " \r\t\n")
13870 (forward-line)
13871 (point))))))))
13873 (defvar org-ts-type nil)
13874 (defun org-sparse-tree (&optional arg type)
13875 "Create a sparse tree, prompt for the details.
13876 This command can create sparse trees. You first need to select the type
13877 of match used to create the tree:
13879 t Show all TODO entries.
13880 T Show entries with a specific TODO keyword.
13881 m Show entries selected by a tags/property match.
13882 p Enter a property name and its value (both with completion on existing
13883 names/values) and show entries with that property.
13884 r Show entries matching a regular expression (`/' can be used as well).
13885 b Show deadlines and scheduled items before a date.
13886 a Show deadlines and scheduled items after a date.
13887 d Show deadlines due within `org-deadline-warning-days'.
13888 D Show deadlines and scheduled items between a date range."
13889 (interactive "P")
13890 (setq type (or type org-sparse-tree-default-date-type))
13891 (setq org-ts-type type)
13892 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13893 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13894 \[c]ycle through date types: %s"
13895 (cl-case type
13896 (all "all timestamps")
13897 (scheduled "only scheduled")
13898 (deadline "only deadline")
13899 (active "only active timestamps")
13900 (inactive "only inactive timestamps")
13901 (closed "with a closed time-stamp")
13902 (otherwise "scheduled/deadline")))
13903 (let ((answer (read-char-exclusive)))
13904 (cl-case answer
13906 (org-sparse-tree
13908 (cadr
13909 (memq type '(nil all scheduled deadline active inactive closed)))))
13910 (?d (call-interactively 'org-check-deadlines))
13911 (?b (call-interactively 'org-check-before-date))
13912 (?a (call-interactively 'org-check-after-date))
13913 (?D (call-interactively 'org-check-dates-range))
13914 (?t (call-interactively 'org-show-todo-tree))
13915 (?T (org-show-todo-tree '(4)))
13916 (?m (call-interactively 'org-match-sparse-tree))
13917 ((?p ?P)
13918 (let* ((kwd (completing-read
13919 "Property: " (mapcar #'list (org-buffer-property-keys))))
13920 (value (completing-read
13921 "Value: " (mapcar #'list (org-property-values kwd)))))
13922 (unless (string-match "\\`{.*}\\'" value)
13923 (setq value (concat "\"" value "\"")))
13924 (org-match-sparse-tree arg (concat kwd "=" value))))
13925 ((?r ?R ?/) (call-interactively 'org-occur))
13926 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13928 (defvar-local org-occur-highlights nil
13929 "List of overlays used for occur matches.")
13930 (defvar-local org-occur-parameters nil
13931 "Parameters of the active org-occur calls.
13932 This is a list, each call to org-occur pushes as cons cell,
13933 containing the regular expression and the callback, onto the list.
13934 The list can contain several entries if `org-occur' has been called
13935 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13936 will only contain one set of parameters. When the highlights are
13937 removed (for example with `C-c C-c', or with the next edit (depending
13938 on `org-remove-highlights-with-change'), this variable is emptied
13939 as well.")
13941 (defun org-occur (regexp &optional keep-previous callback)
13942 "Make a compact tree which shows all matches of REGEXP.
13944 The tree will show the lines where the regexp matches, and any other context
13945 defined in `org-show-context-detail', which see.
13947 When optional argument KEEP-PREVIOUS is non-nil, highlighting and exposing
13948 done by a previous call to `org-occur' will be kept, to allow stacking of
13949 calls to this command.
13951 Optional argument CALLBACK can be a function of no argument. In this case,
13952 it is called with point at the end of the match, match data being set
13953 accordingly. Current match is shown only if the return value is non-nil.
13954 The function must neither move point nor alter narrowing."
13955 (interactive "sRegexp: \nP")
13956 (when (equal regexp "")
13957 (user-error "Regexp cannot be empty"))
13958 (unless keep-previous
13959 (org-remove-occur-highlights nil nil t))
13960 (push (cons regexp callback) org-occur-parameters)
13961 (let ((cnt 0))
13962 (save-excursion
13963 (goto-char (point-min))
13964 (when (or (not keep-previous) ; do not want to keep
13965 (not org-occur-highlights)) ; no previous matches
13966 ;; hide everything
13967 (org-overview))
13968 (let ((case-fold-search (if (eq org-occur-case-fold-search 'smart)
13969 (isearch-no-upper-case-p regexp t)
13970 org-occur-case-fold-search)))
13971 (while (re-search-forward regexp nil t)
13972 (when (or (not callback)
13973 (save-match-data (funcall callback)))
13974 (setq cnt (1+ cnt))
13975 (when org-highlight-sparse-tree-matches
13976 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13977 (org-show-context 'occur-tree)))))
13978 (when org-remove-highlights-with-change
13979 (add-hook 'before-change-functions 'org-remove-occur-highlights
13980 nil 'local))
13981 (unless org-sparse-tree-open-archived-trees
13982 (org-hide-archived-subtrees (point-min) (point-max)))
13983 (run-hooks 'org-occur-hook)
13984 (when (org-called-interactively-p 'interactive)
13985 (message "%d match(es) for regexp %s" cnt regexp))
13986 cnt))
13988 (defun org-occur-next-match (&optional n _reset)
13989 "Function for `next-error-function' to find sparse tree matches.
13990 N is the number of matches to move, when negative move backwards.
13991 This function always goes back to the starting point when no
13992 match is found."
13993 (let* ((limit (if (< n 0) (point-min) (point-max)))
13994 (search-func (if (< n 0)
13995 'previous-single-char-property-change
13996 'next-single-char-property-change))
13997 (n (abs n))
13998 (pos (point))
14000 (catch 'exit
14001 (while (setq p1 (funcall search-func (point) 'org-type))
14002 (when (equal p1 limit)
14003 (goto-char pos)
14004 (user-error "No more matches"))
14005 (when (equal (get-char-property p1 'org-type) 'org-occur)
14006 (setq n (1- n))
14007 (when (= n 0)
14008 (goto-char p1)
14009 (throw 'exit (point))))
14010 (goto-char p1))
14011 (goto-char p1)
14012 (user-error "No more matches"))))
14014 (defun org-show-context (&optional key)
14015 "Make sure point and context are visible.
14016 Optional argument KEY, when non-nil, is a symbol. See
14017 `org-show-context-detail' for allowed values and how much is to
14018 be shown."
14019 (org-show-set-visibility
14020 (cond ((symbolp org-show-context-detail) org-show-context-detail)
14021 ((cdr (assq key org-show-context-detail)))
14022 (t (cdr (assq 'default org-show-context-detail))))))
14024 (defun org-show-set-visibility (detail)
14025 "Set visibility around point according to DETAIL.
14026 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
14027 `tree', `canonical' or t. See `org-show-context-detail' for more
14028 information."
14029 ;; Show current heading and possibly its entry, following headline
14030 ;; or all children.
14031 (if (and (org-at-heading-p) (not (eq detail 'local)))
14032 (org-flag-heading nil)
14033 (org-show-entry)
14034 ;; If point is hidden within a drawer or a block, make sure to
14035 ;; expose it.
14036 (dolist (o (overlays-at (point)))
14037 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
14038 (delete-overlay o)))
14039 (unless (org-before-first-heading-p)
14040 (org-with-limited-levels
14041 (cl-case detail
14042 ((tree canonical t) (org-show-children))
14043 ((nil minimal ancestors))
14044 (t (save-excursion
14045 (outline-next-heading)
14046 (org-flag-heading nil)))))))
14047 ;; Show all siblings.
14048 (when (eq detail 'lineage) (org-show-siblings))
14049 ;; Show ancestors, possibly with their children.
14050 (when (memq detail '(ancestors lineage tree canonical t))
14051 (save-excursion
14052 (while (org-up-heading-safe)
14053 (org-flag-heading nil)
14054 (when (memq detail '(canonical t)) (org-show-entry))
14055 (when (memq detail '(tree canonical t)) (org-show-children))))))
14057 (defvar org-reveal-start-hook nil
14058 "Hook run before revealing a location.")
14060 (defun org-reveal (&optional siblings)
14061 "Show current entry, hierarchy above it, and the following headline.
14063 This can be used to show a consistent set of context around
14064 locations exposed with `org-show-context'.
14066 With optional argument SIBLINGS, on each level of the hierarchy all
14067 siblings are shown. This repairs the tree structure to what it would
14068 look like when opened with hierarchical calls to `org-cycle'.
14070 With double optional argument \\[universal-argument] \\[universal-argument], \
14071 go to the parent and show the
14072 entire tree."
14073 (interactive "P")
14074 (run-hooks 'org-reveal-start-hook)
14075 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
14076 ((equal siblings '(16))
14077 (save-excursion
14078 (when (org-up-heading-safe)
14079 (org-show-subtree)
14080 (run-hook-with-args 'org-cycle-hook 'subtree))))
14081 (t (org-show-set-visibility 'lineage))))
14083 (defun org-highlight-new-match (beg end)
14084 "Highlight from BEG to END and mark the highlight is an occur headline."
14085 (let ((ov (make-overlay beg end)))
14086 (overlay-put ov 'face 'secondary-selection)
14087 (overlay-put ov 'org-type 'org-occur)
14088 (push ov org-occur-highlights)))
14090 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14091 "Remove the occur highlights from the buffer.
14092 BEG and END are ignored. If NOREMOVE is nil, remove this function
14093 from the `before-change-functions' in the current buffer."
14094 (interactive)
14095 (unless org-inhibit-highlight-removal
14096 (mapc #'delete-overlay org-occur-highlights)
14097 (setq org-occur-highlights nil)
14098 (setq org-occur-parameters nil)
14099 (unless noremove
14100 (remove-hook 'before-change-functions
14101 'org-remove-occur-highlights 'local))))
14103 ;;;; Priorities
14105 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14106 "Regular expression matching the priority indicator.")
14108 (defvar org-remove-priority-next-time nil)
14110 (defun org-priority-up ()
14111 "Increase the priority of the current item."
14112 (interactive)
14113 (org-priority 'up))
14115 (defun org-priority-down ()
14116 "Decrease the priority of the current item."
14117 (interactive)
14118 (org-priority 'down))
14120 (defun org-priority (&optional action _show)
14121 "Change the priority of an item.
14122 ACTION can be `set', `up', `down', or a character."
14123 (interactive "P")
14124 (if (equal action '(4))
14125 (org-show-priority)
14126 (unless org-enable-priority-commands
14127 (user-error "Priority commands are disabled"))
14128 (setq action (or action 'set))
14129 (let (current new news have remove)
14130 (save-excursion
14131 (org-back-to-heading t)
14132 (when (looking-at org-priority-regexp)
14133 (setq current (string-to-char (match-string 2))
14134 have t))
14135 (cond
14136 ((eq action 'remove)
14137 (setq remove t new ?\ ))
14138 ((or (eq action 'set)
14139 (integerp action))
14140 (if (not (eq action 'set))
14141 (setq new action)
14142 (message "Priority %c-%c, SPC to remove: "
14143 org-highest-priority org-lowest-priority)
14144 (save-match-data
14145 (setq new (read-char-exclusive))))
14146 (when (and (= (upcase org-highest-priority) org-highest-priority)
14147 (= (upcase org-lowest-priority) org-lowest-priority))
14148 (setq new (upcase new)))
14149 (cond ((equal new ?\ ) (setq remove t))
14150 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14151 (user-error "Priority must be between `%c' and `%c'"
14152 org-highest-priority org-lowest-priority))))
14153 ((eq action 'up)
14154 (setq new (if have
14155 (1- current) ; normal cycling
14156 ;; last priority was empty
14157 (if (eq last-command this-command)
14158 org-lowest-priority ; wrap around empty to lowest
14159 ;; default
14160 (if org-priority-start-cycle-with-default
14161 org-default-priority
14162 (1- org-default-priority))))))
14163 ((eq action 'down)
14164 (setq new (if have
14165 (1+ current) ; normal cycling
14166 ;; last priority was empty
14167 (if (eq last-command this-command)
14168 org-highest-priority ; wrap around empty to highest
14169 ;; default
14170 (if org-priority-start-cycle-with-default
14171 org-default-priority
14172 (1+ org-default-priority))))))
14173 (t (user-error "Invalid action")))
14174 (when (or (< (upcase new) org-highest-priority)
14175 (> (upcase new) org-lowest-priority))
14176 (if (and (memq action '(up down))
14177 (not have) (not (eq last-command this-command)))
14178 ;; `new' is from default priority
14179 (error
14180 "The default can not be set, see `org-default-priority' why")
14181 ;; normal cycling: `new' is beyond highest/lowest priority
14182 ;; and is wrapped around to the empty priority
14183 (setq remove t)))
14184 (setq news (format "%c" new))
14185 (if have
14186 (if remove
14187 (replace-match "" t t nil 1)
14188 (replace-match news t t nil 2))
14189 (if remove
14190 (user-error "No priority cookie found in line")
14191 (let ((case-fold-search nil))
14192 (looking-at org-todo-line-regexp))
14193 (if (match-end 2)
14194 (progn
14195 (goto-char (match-end 2))
14196 (insert " [#" news "]"))
14197 (goto-char (match-beginning 3))
14198 (insert "[#" news "] "))))
14199 (org-set-tags nil 'align))
14200 (if remove
14201 (message "Priority removed")
14202 (message "Priority of current item set to %s" news)))))
14204 (defun org-show-priority ()
14205 "Show the priority of the current item.
14206 This priority is composed of the main priority given with the [#A] cookies,
14207 and by additional input from the age of a schedules or deadline entry."
14208 (interactive)
14209 (let ((pri (if (eq major-mode 'org-agenda-mode)
14210 (org-get-at-bol 'priority)
14211 (save-excursion
14212 (save-match-data
14213 (beginning-of-line)
14214 (and (looking-at org-heading-regexp)
14215 (org-get-priority (match-string 0))))))))
14216 (message "Priority is %d" (if pri pri -1000))))
14218 (defun org-get-priority (s)
14219 "Find priority cookie and return priority."
14220 (save-match-data
14221 (if (functionp org-get-priority-function)
14222 (funcall org-get-priority-function)
14223 (if (not (string-match org-priority-regexp s))
14224 (* 1000 (- org-lowest-priority org-default-priority))
14225 (* 1000 (- org-lowest-priority
14226 (string-to-char (match-string 2 s))))))))
14228 ;;;; Tags
14230 (defvar org-agenda-archives-mode)
14231 (defvar org-map-continue-from nil
14232 "Position from where mapping should continue.
14233 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14235 (defvar org-scanner-tags nil
14236 "The current tag list while the tags scanner is running.")
14238 (defvar org-trust-scanner-tags nil
14239 "Should `org-get-tags-at' use the tags for the scanner.
14240 This is for internal dynamical scoping only.
14241 When this is non-nil, the function `org-get-tags-at' will return the value
14242 of `org-scanner-tags' instead of building the list by itself. This
14243 can lead to large speed-ups when the tags scanner is used in a file with
14244 many entries, and when the list of tags is retrieved, for example to
14245 obtain a list of properties. Building the tags list for each entry in such
14246 a file becomes an N^2 operation - but with this variable set, it scales
14247 as N.")
14249 (defvar org--matcher-tags-todo-only nil)
14251 (defun org-scan-tags (action matcher todo-only &optional start-level)
14252 "Scan headline tags with inheritance and produce output ACTION.
14254 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14255 or `agenda' to produce an entry list for an agenda view. It can also be
14256 a Lisp form or a function that should be called at each matched headline, in
14257 this case the return value is a list of all return values from these calls.
14259 MATCHER is a function accepting three arguments, returning
14260 a non-nil value whenever a given set of tags qualifies a headline
14261 for inclusion. See `org-make-tags-matcher' for more information.
14262 As a special case, it can also be set to t (respectively nil) in
14263 order to match all (respectively none) headline.
14265 When TODO-ONLY is non-nil, only lines with a not-done TODO
14266 keyword are included in the output.
14268 START-LEVEL can be a string with asterisks, reducing the scope to
14269 headlines matching this string."
14270 (require 'org-agenda)
14271 (let* ((re (concat "^"
14272 (if start-level
14273 ;; Get the correct level to match
14274 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14275 org-outline-regexp)
14276 " *\\(\\<\\("
14277 (mapconcat #'regexp-quote org-todo-keywords-1 "\\|")
14278 "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$"))
14279 (props (list 'face 'default
14280 'done-face 'org-agenda-done
14281 'undone-face 'default
14282 'mouse-face 'highlight
14283 'org-not-done-regexp org-not-done-regexp
14284 'org-todo-regexp org-todo-regexp
14285 'org-complex-heading-regexp org-complex-heading-regexp
14286 'help-echo
14287 (format "mouse-2 or RET jump to org file %s"
14288 (abbreviate-file-name
14289 (or (buffer-file-name (buffer-base-buffer))
14290 (buffer-name (buffer-base-buffer)))))))
14291 (org-map-continue-from nil)
14292 lspos tags tags-list
14293 (tags-alist (list (cons 0 org-file-tags)))
14294 (llast 0) rtn rtn1 level category i txt
14295 todo marker entry priority
14296 ts-date ts-date-type ts-date-pair)
14297 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14298 (setq action (list 'lambda nil action)))
14299 (save-excursion
14300 (goto-char (point-min))
14301 (when (eq action 'sparse-tree)
14302 (org-overview)
14303 (org-remove-occur-highlights))
14304 (while (let (case-fold-search)
14305 (re-search-forward re nil t))
14306 (setq org-map-continue-from nil)
14307 (catch :skip
14308 (setq todo
14309 ;; TODO: is the 1-2 difference a bug?
14310 (when (match-end 1) (match-string-no-properties 2))
14311 tags (when (match-end 4) (match-string-no-properties 4)))
14312 (goto-char (setq lspos (match-beginning 0)))
14313 (setq level (org-reduced-level (org-outline-level))
14314 category (org-get-category))
14315 (when (eq action 'agenda)
14316 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14317 ts-date (car ts-date-pair)
14318 ts-date-type (cdr ts-date-pair)))
14319 (setq i llast llast level)
14320 ;; remove tag lists from same and sublevels
14321 (while (>= i level)
14322 (when (setq entry (assoc i tags-alist))
14323 (setq tags-alist (delete entry tags-alist)))
14324 (setq i (1- i)))
14325 ;; add the next tags
14326 (when tags
14327 (setq tags (org-split-string tags ":")
14328 tags-alist
14329 (cons (cons level tags) tags-alist)))
14330 ;; compile tags for current headline
14331 (setq tags-list
14332 (if org-use-tag-inheritance
14333 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14334 tags)
14335 org-scanner-tags tags-list)
14336 (when org-use-tag-inheritance
14337 (setcdr (car tags-alist)
14338 (mapcar (lambda (x)
14339 (setq x (copy-sequence x))
14340 (org-add-prop-inherited x))
14341 (cdar tags-alist))))
14342 (when (and tags org-use-tag-inheritance
14343 (or (not (eq t org-use-tag-inheritance))
14344 org-tags-exclude-from-inheritance))
14345 ;; Selective inheritance, remove uninherited ones.
14346 (setcdr (car tags-alist)
14347 (org-remove-uninherited-tags (cdar tags-alist))))
14348 (when (and
14350 ;; eval matcher only when the todo condition is OK
14351 (and (or (not todo-only) (member todo org-not-done-keywords))
14352 (if (functionp matcher)
14353 (let ((case-fold-search t) (org-trust-scanner-tags t))
14354 (funcall matcher todo tags-list level))
14355 matcher))
14357 ;; Call the skipper, but return t if it does not
14358 ;; skip, so that the `and' form continues evaluating.
14359 (progn
14360 (unless (eq action 'sparse-tree) (org-agenda-skip))
14363 ;; Check if timestamps are deselecting this entry
14364 (or (not todo-only)
14365 (and (member todo org-not-done-keywords)
14366 (or (not org-agenda-tags-todo-honor-ignore-options)
14367 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14369 ;; select this headline
14370 (cond
14371 ((eq action 'sparse-tree)
14372 (and org-highlight-sparse-tree-matches
14373 (org-get-heading) (match-end 0)
14374 (org-highlight-new-match
14375 (match-beginning 1) (match-end 1)))
14376 (org-show-context 'tags-tree))
14377 ((eq action 'agenda)
14378 (setq txt (org-agenda-format-item
14380 (concat
14381 (if (eq org-tags-match-list-sublevels 'indented)
14382 (make-string (1- level) ?.) "")
14383 (org-get-heading))
14384 (make-string level ?\s)
14385 category
14386 tags-list)
14387 priority (org-get-priority txt))
14388 (goto-char lspos)
14389 (setq marker (org-agenda-new-marker))
14390 (org-add-props txt props
14391 'org-marker marker 'org-hd-marker marker 'org-category category
14392 'todo-state todo
14393 'ts-date ts-date
14394 'priority priority
14395 'type (concat "tagsmatch" ts-date-type))
14396 (push txt rtn))
14397 ((functionp action)
14398 (setq org-map-continue-from nil)
14399 (save-excursion
14400 (setq rtn1 (funcall action))
14401 (push rtn1 rtn)))
14402 (t (user-error "Invalid action")))
14404 ;; if we are to skip sublevels, jump to end of subtree
14405 (unless org-tags-match-list-sublevels
14406 (org-end-of-subtree t)
14407 (backward-char 1))))
14408 ;; Get the correct position from where to continue
14409 (if org-map-continue-from
14410 (goto-char org-map-continue-from)
14411 (and (= (point) lspos) (end-of-line 1)))))
14412 (when (and (eq action 'sparse-tree)
14413 (not org-sparse-tree-open-archived-trees))
14414 (org-hide-archived-subtrees (point-min) (point-max)))
14415 (nreverse rtn)))
14417 (defun org-remove-uninherited-tags (tags)
14418 "Remove all tags that are not inherited from the list TAGS."
14419 (cond
14420 ((eq org-use-tag-inheritance t)
14421 (if org-tags-exclude-from-inheritance
14422 (org-delete-all org-tags-exclude-from-inheritance tags)
14423 tags))
14424 ((not org-use-tag-inheritance) nil)
14425 ((stringp org-use-tag-inheritance)
14426 (delq nil (mapcar
14427 (lambda (x)
14428 (if (and (string-match org-use-tag-inheritance x)
14429 (not (member x org-tags-exclude-from-inheritance)))
14430 x nil))
14431 tags)))
14432 ((listp org-use-tag-inheritance)
14433 (delq nil (mapcar
14434 (lambda (x)
14435 (if (member x org-use-tag-inheritance) x nil))
14436 tags)))))
14438 (defun org-match-sparse-tree (&optional todo-only match)
14439 "Create a sparse tree according to tags string MATCH.
14440 MATCH can contain positive and negative selection of tags, like
14441 \"+WORK+URGENT-WITHBOSS\".
14442 If optional argument TODO-ONLY is non-nil, only select lines that are
14443 also TODO lines."
14444 (interactive "P")
14445 (org-agenda-prepare-buffers (list (current-buffer)))
14446 (let ((org--matcher-tags-todo-only todo-only))
14447 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14448 org--matcher-tags-todo-only)))
14450 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14452 (defvar org-cached-props nil)
14453 (defun org-cached-entry-get (pom property)
14454 (if (or (eq t org-use-property-inheritance)
14455 (and (stringp org-use-property-inheritance)
14456 (let ((case-fold-search t))
14457 (org-string-match-p org-use-property-inheritance property)))
14458 (and (listp org-use-property-inheritance)
14459 (member-ignore-case property org-use-property-inheritance)))
14460 ;; Caching is not possible, check it directly.
14461 (org-entry-get pom property 'inherit)
14462 ;; Get all properties, so we can do complicated checks easily.
14463 (cdr (assoc-string property
14464 (or org-cached-props
14465 (setq org-cached-props (org-entry-properties pom)))
14466 t))))
14468 (defun org-global-tags-completion-table (&optional files)
14469 "Return the list of all tags in all agenda buffer/files.
14470 Optional FILES argument is a list of files which can be used
14471 instead of the agenda files."
14472 (save-excursion
14473 (org-uniquify
14474 (delq nil
14475 (apply #'append
14476 (mapcar
14477 (lambda (file)
14478 (set-buffer (find-file-noselect file))
14479 (mapcar (lambda (x)
14480 (and (stringp (car-safe x))
14481 (list (car-safe x))))
14482 (or org-current-tag-alist (org-get-buffer-tags))))
14483 (if (car-safe files) files
14484 (org-agenda-files))))))))
14486 (defun org-make-tags-matcher (match)
14487 "Create the TAGS/TODO matcher form for the selection string MATCH.
14489 Returns a cons of the selection string MATCH and a function
14490 implementing the matcher.
14492 The matcher is to be called at an Org entry, with point on the
14493 headline, and returns non-nil if the entry matches the selection
14494 string MATCH. It must be called with three arguments: the TODO
14495 keyword at the entry (or nil if none), the list of all tags at
14496 the entry including inherited ones and the reduced level of the
14497 headline. Additionally, the category of the entry, if any, must
14498 be specified as the text property `org-category' on the headline.
14500 This function sets the variable `org--matcher-tags-todo-only' to
14501 a non-nil value if the matcher restricts matching to TODO
14502 entries, otherwise it is not touched.
14504 See also `org-scan-tags'."
14505 (unless match
14506 ;; Get a new match request, with completion against the global
14507 ;; tags table and the local tags in current buffer.
14508 (let ((org-last-tags-completion-table
14509 (org-uniquify
14510 (delq nil (append (org-get-buffer-tags)
14511 (org-global-tags-completion-table))))))
14512 (setq match
14513 (completing-read
14514 "Match: "
14515 'org-tags-completion-function nil nil nil 'org-tags-history))))
14517 (let ((match0 match)
14518 (re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)")
14519 (start 0)
14520 tagsmatch todomatch tagsmatcher todomatcher)
14522 ;; Expand group tags.
14523 (setq match (org-tags-expand match))
14525 ;; Check if there is a TODO part of this match, which would be the
14526 ;; part after a "/". To make sure that this slash is not part of
14527 ;; a property value to be matched against, we also check that
14528 ;; there is no / after that slash. First, find the last slash.
14529 (let ((s 0))
14530 (while (string-match "/+" match s)
14531 (setq start (match-beginning 0))
14532 (setq s (match-end 0))))
14533 (if (and (string-match "/+" match start)
14534 (not (string-match-p "\"" match start)))
14535 ;; Match contains also a TODO-matching request.
14536 (progn
14537 (setq tagsmatch (substring match 0 (match-beginning 0)))
14538 (setq todomatch (substring match (match-end 0)))
14539 (when (string-match "\\`!" todomatch)
14540 (setq org--matcher-tags-todo-only t)
14541 (setq todomatch (substring todomatch 1)))
14542 (when (string-match "\\`\\s-*\\'" todomatch)
14543 (setq todomatch nil)))
14544 ;; Only matching tags.
14545 (setq tagsmatch match)
14546 (setq todomatch nil))
14548 ;; Make the tags matcher.
14549 (when (org-string-nw-p tagsmatch)
14550 (let ((orlist nil)
14551 (orterms (org-split-string tagsmatch "|"))
14552 term)
14553 (while (setq term (pop orterms))
14554 (while (and (equal (substring term -1) "\\") orterms)
14555 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14556 (while (string-match re term)
14557 (let* ((rest (substring term (match-end 0)))
14558 (minus (and (match-end 1)
14559 (equal (match-string 1 term) "-")))
14560 (tag (save-match-data
14561 (replace-regexp-in-string
14562 "\\\\-" "-" (match-string 2 term))))
14563 (regexp (eq (string-to-char tag) ?{))
14564 (levelp (match-end 4))
14565 (propp (match-end 5))
14567 (cond
14568 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14569 (levelp
14570 `(,(org-op-to-function (match-string 3 term))
14571 level
14572 ,(string-to-number (match-string 4 term))))
14573 (propp
14574 (let* ((gv (pcase (upcase (match-string 5 term))
14575 ("CATEGORY"
14576 '(get-text-property (point) 'org-category))
14577 ("TODO" 'todo)
14578 (p `(org-cached-entry-get nil ,p))))
14579 (pv (match-string 7 term))
14580 (regexp (eq (string-to-char pv) ?{))
14581 (strp (eq (string-to-char pv) ?\"))
14582 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14583 (po (org-op-to-function (match-string 6 term)
14584 (if timep 'time strp))))
14585 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14586 (when timep (setq pv (org-matcher-time pv)))
14587 (cond ((and regexp (eq po 'org<>))
14588 `(not (string-match ,pv (or ,gv ""))))
14589 (regexp `(string-match ,pv (or ,gv "")))
14590 (strp `(,po (or ,gv "") ,pv))
14592 `(,po
14593 (string-to-number (or ,gv ""))
14594 ,(string-to-number pv))))))
14595 (t `(member ,tag tags-list)))))
14596 (push (if minus `(not ,mm) mm) tagsmatcher)
14597 (setq term rest)))
14598 (push `(and ,@tagsmatcher) orlist)
14599 (setq tagsmatcher nil))
14600 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14602 ;; Make the TODO matcher.
14603 (when (org-string-nw-p todomatch)
14604 (let ((orlist nil))
14605 (dolist (term (org-split-string todomatch "|"))
14606 (while (string-match re term)
14607 (let* ((minus (and (match-end 1)
14608 (equal (match-string 1 term) "-")))
14609 (kwd (match-string 2 term))
14610 (regexp (eq (string-to-char kwd) ?{))
14611 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14612 `(equal todo ,kwd))))
14613 (push (if minus `(not ,mm) mm) todomatcher))
14614 (setq term (substring term (match-end 0))))
14615 (push (if (> (length todomatcher) 1)
14616 (cons 'and todomatcher)
14617 (car todomatcher))
14618 orlist)
14619 (setq todomatcher nil))
14620 (setq todomatcher (cons 'or orlist))))
14622 ;; Return the string and function of the matcher. If no
14623 ;; tags-specific or todo-specific matcher exists, match
14624 ;; everything.
14625 (let ((matcher (if (and tagsmatcher todomatcher)
14626 `(and ,tagsmatcher ,todomatcher)
14627 (or tagsmatcher todomatcher t))))
14628 (when org--matcher-tags-todo-only
14629 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14630 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14632 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14633 "Expand group tags in MATCH.
14635 This replaces every group tag in MATCH with a regexp tag search.
14636 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14637 will be replaced like this:
14639 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14640 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14641 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14643 Replacing by a regexp preserves the structure of the match.
14644 E.g., this expansion
14646 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14648 will match anything tagged with \"Lab\" and \"Home\", or tagged
14649 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14651 A group tag in MATCH can contain regular expressions of its own.
14652 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14653 will be replaced like this:
14655 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14657 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14658 assumed to be a single group tag, and the function will return
14659 the list of tags in this group.
14661 When DOWNCASE is non-nil, expand downcased TAGS."
14662 (if org-group-tags
14663 (let* ((case-fold-search t)
14664 (stable org-mode-syntax-table)
14665 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14666 (taggroups (if downcased
14667 (mapcar (lambda (tg) (mapcar #'downcase tg))
14668 taggroups)
14669 taggroups))
14670 (taggroups-keys (mapcar #'car taggroups))
14671 (return-match (if downcased (downcase match) match))
14672 (count 0)
14673 (work-already-expanded tags-already-expanded)
14674 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14675 ;; @ and _ are allowed as word-components in tags.
14676 (modify-syntax-entry ?@ "w" stable)
14677 (modify-syntax-entry ?_ "w" stable)
14678 ;; Temporarily replace regexp-expressions in the match-expression.
14679 (while (string-match "{.+?}" return-match)
14680 (cl-incf count)
14681 (push (match-string 0 return-match) regexps-in-match)
14682 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14683 (while (and taggroups-keys
14684 (with-syntax-table stable
14685 (string-match
14686 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14687 (regexp-opt taggroups-keys) "\\>\\)")
14688 return-match)))
14689 (let* ((dir (match-string 1 return-match))
14690 (tag (match-string 2 return-match))
14691 (tag (if downcased (downcase tag) tag)))
14692 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14693 (member tag work-already-expanded))
14694 (setq tags-in-group (assoc tag taggroups))
14695 (push tag work-already-expanded)
14696 ;; Recursively expand each tag in the group, if the tag hasn't
14697 ;; already been expanded. Restore the match-data after all recursive calls.
14698 (save-match-data
14699 (let (tags-expanded)
14700 (dolist (x (cdr tags-in-group))
14701 (if (and (member x taggroups-keys)
14702 (not (member x work-already-expanded)))
14703 (setq tags-expanded
14704 (delete-dups
14705 (append
14706 (org-tags-expand x t downcased
14707 work-already-expanded)
14708 tags-expanded)))
14709 (setq tags-expanded
14710 (append (list x) tags-expanded)))
14711 (setq work-already-expanded
14712 (delete-dups
14713 (append tags-expanded
14714 work-already-expanded))))
14715 (setq tags-in-group
14716 (delete-dups (cons (car tags-in-group)
14717 tags-expanded)))))
14718 ;; Filter tag-regexps from tags.
14719 (setq regexp-in-group-escaped
14720 (delq nil (mapcar (lambda (x)
14721 (if (stringp x)
14722 (and (equal "{" (substring x 0 1))
14723 (equal "}" (substring x -1))
14726 tags-in-group))
14727 regexp-in-group
14728 (mapcar (lambda (x)
14729 (substring x 1 -1))
14730 regexp-in-group-escaped)
14731 tags-in-group
14732 (delq nil (mapcar (lambda (x)
14733 (if (stringp x)
14734 (and (not (equal "{" (substring x 0 1)))
14735 (not (equal "}" (substring x -1)))
14738 tags-in-group)))
14739 ;; If single-as-list, do no more in the while-loop.
14740 (if (not single-as-list)
14741 (progn
14742 (when regexp-in-group
14743 (setq regexp-in-group
14744 (concat "\\|"
14745 (mapconcat 'identity regexp-in-group
14746 "\\|"))))
14747 (setq tags-in-group
14748 (concat dir
14749 "{\\<"
14750 (regexp-opt tags-in-group)
14751 "\\>"
14752 regexp-in-group
14753 "}"))
14754 (when (stringp tags-in-group)
14755 (org-add-props tags-in-group '(grouptag t)))
14756 (setq return-match
14757 (replace-match tags-in-group t t return-match)))
14758 (setq tags-in-group
14759 (append regexp-in-group-escaped tags-in-group))))
14760 (setq taggroups-keys (delete tag taggroups-keys))))
14761 ;; Add the regular expressions back into the match-expression again.
14762 (while regexps-in-match
14763 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14764 (pop regexps-in-match)
14765 return-match t t))
14766 (cl-decf count))
14767 (if single-as-list
14768 (if tags-in-group tags-in-group (list return-match))
14769 return-match))
14770 (if single-as-list
14771 (list (if downcased (downcase match) match))
14772 match)))
14774 (defun org-op-to-function (op &optional stringp)
14775 "Turn an operator into the appropriate function."
14776 (setq op
14777 (cond
14778 ((equal op "<" ) '(< string< org-time<))
14779 ((equal op ">" ) '(> org-string> org-time>))
14780 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14781 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14782 ((member op '("=" "==")) '(= string= org-time=))
14783 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14784 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14786 (defun org<> (a b) (not (= a b)))
14787 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14788 (defun org-string>= (a b) (not (string< a b)))
14789 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14790 (defun org-string<> (a b) (not (string= a b)))
14791 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14792 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14793 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14794 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14795 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14796 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14797 (defun org-2ft (s)
14798 "Convert S to a floating point time.
14799 If S is already a number, just return it. If it is a string, parse
14800 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14801 (cond
14802 ((numberp s) s)
14803 ((stringp s)
14804 (condition-case nil
14805 (float-time (apply 'encode-time (org-parse-time-string s)))
14806 (error 0.)))
14807 (t 0.)))
14809 (defun org-time-today ()
14810 "Time in seconds today at 0:00.
14811 Returns the float number of seconds since the beginning of the
14812 epoch to the beginning of today (00:00)."
14813 (float-time (apply 'encode-time
14814 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14816 (defun org-matcher-time (s)
14817 "Interpret a time comparison value."
14818 (save-match-data
14819 (cond
14820 ((string= s "<now>") (float-time))
14821 ((string= s "<today>") (org-time-today))
14822 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14823 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14824 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14825 (+ (org-time-today)
14826 (* (string-to-number (match-string 1 s))
14827 (cdr (assoc (match-string 2 s)
14828 '(("d" . 86400.0) ("w" . 604800.0)
14829 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14830 (t (org-2ft s)))))
14832 (defun org-match-any-p (re list)
14833 "Does re match any element of list?"
14834 (setq list (mapcar (lambda (x) (string-match re x)) list))
14835 (delq nil list))
14837 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14838 (defvar org-tags-overlay (make-overlay 1 1))
14839 (delete-overlay org-tags-overlay)
14841 (defun org-get-local-tags-at (&optional pos)
14842 "Get a list of tags defined in the current headline."
14843 (org-get-tags-at pos 'local))
14845 (defun org-get-local-tags ()
14846 "Get a list of tags defined in the current headline."
14847 (org-get-tags-at nil 'local))
14849 (defun org-get-tags-at (&optional pos local)
14850 "Get a list of all headline tags applicable at POS.
14851 POS defaults to point. If tags are inherited, the list contains
14852 the targets in the same sequence as the headlines appear, i.e.
14853 the tags of the current headline come last.
14854 When LOCAL is non-nil, only return tags from the current headline,
14855 ignore inherited ones."
14856 (interactive)
14857 (if (and org-trust-scanner-tags
14858 (or (not pos) (equal pos (point)))
14859 (not local))
14860 org-scanner-tags
14861 (let (tags ltags lastpos parent)
14862 (save-excursion
14863 (save-restriction
14864 (widen)
14865 (goto-char (or pos (point)))
14866 (save-match-data
14867 (catch 'done
14868 (condition-case nil
14869 (progn
14870 (org-back-to-heading t)
14871 (while (not (equal lastpos (point)))
14872 (setq lastpos (point))
14873 (when (looking-at ".+:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14874 (setq ltags (org-split-string
14875 (match-string-no-properties 1) ":"))
14876 (when parent
14877 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14878 (setq tags (append
14879 (if parent
14880 (org-remove-uninherited-tags ltags)
14881 ltags)
14882 tags)))
14883 (or org-use-tag-inheritance (throw 'done t))
14884 (when local (throw 'done t))
14885 (or (org-up-heading-safe) (error nil))
14886 (setq parent t)))
14887 (error nil)))))
14888 (if local
14889 tags
14890 (reverse (delete-dups
14891 (reverse (append
14892 (org-remove-uninherited-tags
14893 org-file-tags)
14894 tags)))))))))
14896 (defun org-add-prop-inherited (s)
14897 (add-text-properties 0 (length s) '(inherited t) s)
14900 (defun org-toggle-tag (tag &optional onoff)
14901 "Toggle the tag TAG for the current line.
14902 If ONOFF is `on' or `off', don't toggle but set to this state."
14903 (let (res current)
14904 (save-excursion
14905 (org-back-to-heading t)
14906 (if (re-search-forward "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$"
14907 (point-at-eol) t)
14908 (progn
14909 (setq current (match-string 1))
14910 (replace-match ""))
14911 (setq current ""))
14912 (setq current (nreverse (org-split-string current ":")))
14913 (cond
14914 ((eq onoff 'on)
14915 (setq res t)
14916 (or (member tag current) (push tag current)))
14917 ((eq onoff 'off)
14918 (or (not (member tag current)) (setq current (delete tag current))))
14919 (t (if (member tag current)
14920 (setq current (delete tag current))
14921 (setq res t)
14922 (push tag current))))
14923 (end-of-line 1)
14924 (if current
14925 (progn
14926 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14927 (org-set-tags nil t))
14928 (delete-horizontal-space))
14929 (run-hooks 'org-after-tags-change-hook))
14930 res))
14932 (defun org-align-tags-here (to-col)
14933 ;; Assumes that this is a headline
14934 "Align tags on the current headline to TO-COL."
14935 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14936 (beginning-of-line 1)
14937 (if (and (looking-at ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
14938 (< pos (match-beginning 2)))
14939 (progn
14940 (setq tags-l (- (match-end 2) (match-beginning 2)))
14941 (goto-char (match-beginning 1))
14942 (insert " ")
14943 (delete-region (point) (1+ (match-beginning 2)))
14944 (setq ncol (max (current-column)
14945 (1+ col)
14946 (if (> to-col 0)
14947 to-col
14948 (- (abs to-col) tags-l))))
14949 (setq p (point))
14950 (insert (make-string (- ncol (current-column)) ?\ ))
14951 (setq ncol (current-column))
14952 (when indent-tabs-mode (tabify p (point-at-eol)))
14953 (org-move-to-column (min ncol col)))
14954 (goto-char pos))))
14956 (defun org-set-tags-command (&optional arg just-align)
14957 "Call the set-tags command for the current entry."
14958 (interactive "P")
14959 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14960 (org-set-tags arg just-align)
14961 (save-excursion
14962 (unless (and (org-region-active-p)
14963 org-loop-over-headlines-in-active-region)
14964 (org-back-to-heading t))
14965 (org-set-tags arg just-align))))
14967 (defun org-set-tags-to (data)
14968 "Set the tags of the current entry to DATA, replacing the current tags.
14969 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14970 If DATA is nil or the empty string, any tags will be removed."
14971 (interactive "sTags: ")
14972 (setq data
14973 (cond
14974 ((eq data nil) "")
14975 ((equal data "") "")
14976 ((stringp data)
14977 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14978 ":"))
14979 ((listp data)
14980 (concat ":" (mapconcat 'identity data ":") ":"))))
14981 (when data
14982 (save-excursion
14983 (org-back-to-heading t)
14984 (when (looking-at org-complex-heading-regexp)
14985 (if (match-end 5)
14986 (progn
14987 (goto-char (match-beginning 5))
14988 (insert data)
14989 (delete-region (point) (point-at-eol))
14990 (org-set-tags nil 'align))
14991 (goto-char (point-at-eol))
14992 (insert " " data)
14993 (org-set-tags nil 'align)))
14994 (beginning-of-line 1)
14995 (when (looking-at ".*?\\([ \t]+\\)$")
14996 (delete-region (match-beginning 1) (match-end 1))))))
14998 (defun org-align-all-tags ()
14999 "Align the tags in all headings."
15000 (interactive)
15001 (save-excursion
15002 (or (ignore-errors (org-back-to-heading t))
15003 (outline-next-heading))
15004 (if (org-at-heading-p)
15005 (org-set-tags t)
15006 (message "No headings"))))
15008 (defvar org-indent-indentation-per-level)
15009 (defun org-set-tags (&optional arg just-align)
15010 "Set the tags for the current headline.
15011 With prefix ARG, realign all tags in headings in the current buffer.
15012 When JUST-ALIGN is non-nil, only align tags."
15013 (interactive "P")
15014 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
15015 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
15016 'region-start-level
15017 'region))
15018 org-loop-over-headlines-in-active-region)
15019 (org-map-entries
15020 ;; We don't use ARG and JUST-ALIGN here because these args
15021 ;; are not useful when looping over headlines.
15022 #'org-set-tags
15023 org-loop-over-headlines-in-active-region
15025 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
15026 (let ((org-setting-tags t))
15027 (if arg
15028 (save-excursion
15029 (goto-char (point-min))
15030 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
15031 (while (re-search-forward org-outline-regexp-bol nil t)
15032 (org-set-tags nil t)
15033 (end-of-line)))
15034 (message "All tags realigned to column %d" org-tags-column))
15035 (let* ((current (org-get-tags-string))
15036 (col (current-column))
15037 (tags
15038 (if just-align current
15039 ;; Get a new set of tags from the user.
15040 (save-excursion
15041 (let* ((seen)
15042 (table
15043 (setq
15044 org-last-tags-completion-table
15045 ;; Uniquify tags in alists, yet preserve
15046 ;; structure (i.e., keywords).
15047 (delq nil
15048 (mapcar
15049 (lambda (pair)
15050 (let ((head (car pair)))
15051 (cond ((symbolp head) pair)
15052 ((member head seen) nil)
15053 (t (push head seen)
15054 pair))))
15055 (append
15056 (or org-current-tag-alist
15057 (org-get-buffer-tags))
15058 (and
15059 org-complete-tags-always-offer-all-agenda-tags
15060 (org-global-tags-completion-table
15061 (org-agenda-files))))))))
15062 (current-tags (org-split-string current ":"))
15063 (inherited-tags
15064 (nreverse (nthcdr (length current-tags)
15065 (nreverse (org-get-tags-at))))))
15066 (replace-regexp-in-string
15067 "\\([-+&]+\\|,\\)"
15069 (if (or (eq t org-use-fast-tag-selection)
15070 (and org-use-fast-tag-selection
15071 (delq nil (mapcar #'cdr table))))
15072 (org-fast-tag-selection
15073 current-tags inherited-tags table
15074 (and org-fast-tag-selection-include-todo
15075 org-todo-key-alist))
15076 (let ((org-add-colon-after-tag-completion
15077 (< 1 (length table))))
15078 (org-trim
15079 (completing-read
15080 "Tags: "
15081 #'org-tags-completion-function
15082 nil nil current 'org-tags-history))))))))))
15084 (when org-tags-sort-function
15085 (setq tags
15086 (mapconcat
15087 #'identity
15088 (sort (org-split-string tags "[^[:alnum:]_@#%]+")
15089 org-tags-sort-function)
15090 ":")))
15092 (if (not (org-string-nw-p tags)) (setq tags "")
15093 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15094 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15096 ;; Insert new tags at the correct column
15097 (beginning-of-line)
15098 (let ((level (if (looking-at org-outline-regexp)
15099 (- (match-end 0) (point) 1)
15100 1)))
15101 (cond
15102 ((and (equal current "") (equal tags "")))
15103 ((re-search-forward
15104 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15105 (line-end-position)
15107 (if (equal tags "") (replace-match "" t t)
15108 (goto-char (match-beginning 0))
15109 (let* ((c0 (current-column))
15110 ;; Compute offset for the case of org-indent-mode
15111 ;; active.
15112 (di (if (org-bound-and-true-p org-indent-mode)
15113 (* (1- org-indent-indentation-per-level)
15114 (1- level))
15116 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15117 (tc (+ org-tags-column
15118 (if (> org-tags-column 0) (- di) di)))
15119 (c1 (max (1+ c0)
15120 (if (> tc 0) tc
15121 (- (- tc) (string-width tags)))))
15122 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15123 (replace-match rpl t t)
15124 (when indent-tabs-mode (tabify p0 (point))))))
15125 (t (error "Tags alignment failed"))))
15126 (org-move-to-column col))
15127 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15129 (defun org-change-tag-in-region (beg end tag off)
15130 "Add or remove TAG for each entry in the region.
15131 This works in the agenda, and also in an org-mode buffer."
15132 (interactive
15133 (list (region-beginning) (region-end)
15134 (let ((org-last-tags-completion-table
15135 (if (derived-mode-p 'org-mode)
15136 (org-uniquify
15137 (delq nil (append (org-get-buffer-tags)
15138 (org-global-tags-completion-table))))
15139 (org-global-tags-completion-table))))
15140 (completing-read
15141 "Tag: " 'org-tags-completion-function nil nil nil
15142 'org-tags-history))
15143 (progn
15144 (message "[s]et or [r]emove? ")
15145 (equal (read-char-exclusive) ?r))))
15146 (when (fboundp 'deactivate-mark) (deactivate-mark))
15147 (let ((agendap (equal major-mode 'org-agenda-mode))
15148 l1 l2 m buf pos newhead (cnt 0))
15149 (goto-char end)
15150 (setq l2 (1- (org-current-line)))
15151 (goto-char beg)
15152 (setq l1 (org-current-line))
15153 (cl-loop for l from l1 to l2 do
15154 (org-goto-line l)
15155 (setq m (get-text-property (point) 'org-hd-marker))
15156 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15157 (and agendap m))
15158 (setq buf (if agendap (marker-buffer m) (current-buffer))
15159 pos (if agendap m (point)))
15160 (with-current-buffer buf
15161 (save-excursion
15162 (save-restriction
15163 (goto-char pos)
15164 (setq cnt (1+ cnt))
15165 (org-toggle-tag tag (if off 'off 'on))
15166 (setq newhead (org-get-heading)))))
15167 (and agendap (org-agenda-change-all-lines newhead m))))
15168 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15170 (defun org-tags-completion-function (string _predicate &optional flag)
15171 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15172 (confirm (lambda (x) (stringp (car x)))))
15173 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15174 (setq s1 (match-string 1 string)
15175 s2 (match-string 2 string))
15176 (setq s1 "" s2 string))
15177 (cond
15178 ((eq flag nil)
15179 ;; try completion
15180 (setq rtn (try-completion s2 ctable confirm))
15181 (when (stringp rtn)
15182 (setq rtn
15183 (concat s1 s2 (substring rtn (length s2))
15184 (if (and org-add-colon-after-tag-completion
15185 (assoc rtn ctable))
15186 ":" ""))))
15187 rtn)
15188 ((eq flag t)
15189 ;; all-completions
15190 (all-completions s2 ctable confirm))
15191 ((eq flag 'lambda)
15192 ;; exact match?
15193 (assoc s2 ctable)))))
15195 (defun org-fast-tag-insert (kwd tags face &optional end)
15196 "Insert KDW, and the TAGS, the latter with face FACE.
15197 Also insert END."
15198 (insert (format "%-12s" (concat kwd ":"))
15199 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15200 (or end "")))
15202 (defun org-fast-tag-show-exit (flag)
15203 (save-excursion
15204 (org-goto-line 3)
15205 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15206 (replace-match ""))
15207 (when flag
15208 (end-of-line 1)
15209 (org-move-to-column (- (window-width) 19) t)
15210 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15212 (defun org-set-current-tags-overlay (current prefix)
15213 "Add an overlay to CURRENT tag with PREFIX."
15214 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15215 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15216 (org-overlay-display org-tags-overlay (concat prefix s))))
15218 (defvar org-last-tag-selection-key nil)
15219 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15220 "Fast tag selection with single keys.
15221 CURRENT is the current list of tags in the headline, INHERITED is the
15222 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15223 possibly with grouping information. TODO-TABLE is a similar table with
15224 TODO keywords, should these have keys assigned to them.
15225 If the keys are nil, a-z are automatically assigned.
15226 Returns the new tags string, or nil to not change the current settings."
15227 (let* ((fulltable (append table todo-table))
15228 (maxlen (apply 'max (mapcar
15229 (lambda (x)
15230 (if (stringp (car x)) (string-width (car x)) 0))
15231 fulltable)))
15232 (buf (current-buffer))
15233 (expert (eq org-fast-tag-selection-single-key 'expert))
15234 (buffer-tags nil)
15235 (fwidth (+ maxlen 3 1 3))
15236 (ncol (/ (- (window-width) 4) fwidth))
15237 (i-face 'org-done)
15238 (c-face 'org-todo)
15239 tg cnt e c char c1 c2 ntable tbl rtn
15240 ov-start ov-end ov-prefix
15241 (exit-after-next org-fast-tag-selection-single-key)
15242 (done-keywords org-done-keywords)
15243 groups ingroup intaggroup)
15244 (save-excursion
15245 (beginning-of-line 1)
15246 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15247 (setq ov-start (match-beginning 1)
15248 ov-end (match-end 1)
15249 ov-prefix "")
15250 (setq ov-start (1- (point-at-eol))
15251 ov-end (1+ ov-start))
15252 (skip-chars-forward "^\n\r")
15253 (setq ov-prefix
15254 (concat
15255 (buffer-substring (1- (point)) (point))
15256 (if (> (current-column) org-tags-column)
15258 (make-string (- org-tags-column (current-column)) ?\ ))))))
15259 (move-overlay org-tags-overlay ov-start ov-end)
15260 (save-window-excursion
15261 (if expert
15262 (set-buffer (get-buffer-create " *Org tags*"))
15263 (delete-other-windows)
15264 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15265 (org-switch-to-buffer-other-window " *Org tags*"))
15266 (erase-buffer)
15267 (setq-local org-done-keywords done-keywords)
15268 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15269 (org-fast-tag-insert "Current" current c-face "\n\n")
15270 (org-fast-tag-show-exit exit-after-next)
15271 (org-set-current-tags-overlay current ov-prefix)
15272 (setq tbl fulltable char ?a cnt 0)
15273 (while (setq e (pop tbl))
15274 (cond
15275 ((eq (car e) :startgroup)
15276 (push '() groups) (setq ingroup t)
15277 (unless (zerop cnt)
15278 (setq cnt 0)
15279 (insert "\n"))
15280 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15281 ((eq (car e) :endgroup)
15282 (setq ingroup nil cnt 0)
15283 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15284 ((eq (car e) :startgrouptag)
15285 (setq intaggroup t)
15286 (unless (zerop cnt)
15287 (setq cnt 0)
15288 (insert "\n"))
15289 (insert "[ "))
15290 ((eq (car e) :endgrouptag)
15291 (setq intaggroup nil cnt 0)
15292 (insert "]\n"))
15293 ((equal e '(:newline))
15294 (unless (zerop cnt)
15295 (setq cnt 0)
15296 (insert "\n")
15297 (setq e (car tbl))
15298 (while (equal (car tbl) '(:newline))
15299 (insert "\n")
15300 (setq tbl (cdr tbl)))))
15301 ((equal e '(:grouptags)) (insert " : "))
15303 (setq tg (copy-sequence (car e)) c2 nil)
15304 (if (cdr e)
15305 (setq c (cdr e))
15306 ;; automatically assign a character.
15307 (setq c1 (string-to-char
15308 (downcase (substring
15309 tg (if (= (string-to-char tg) ?@) 1 0)))))
15310 (if (or (rassoc c1 ntable) (rassoc c1 table))
15311 (while (or (rassoc char ntable) (rassoc char table))
15312 (setq char (1+ char)))
15313 (setq c2 c1))
15314 (setq c (or c2 char)))
15315 (when ingroup (push tg (car groups)))
15316 (setq tg (org-add-props tg nil 'face
15317 (cond
15318 ((not (assoc tg table))
15319 (org-get-todo-face tg))
15320 ((member tg current) c-face)
15321 ((member tg inherited) i-face))))
15322 (when (equal (caar tbl) :grouptags)
15323 (org-add-props tg nil 'face 'org-tag-group))
15324 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15325 (insert "[" c "] " tg (make-string
15326 (- fwidth 4 (length tg)) ?\ ))
15327 (push (cons tg c) ntable)
15328 (when (= (cl-incf cnt) ncol)
15329 (insert "\n")
15330 (when (or ingroup intaggroup) (insert " "))
15331 (setq cnt 0)))))
15332 (setq ntable (nreverse ntable))
15333 (insert "\n")
15334 (goto-char (point-min))
15335 (unless expert (org-fit-window-to-buffer))
15336 (setq rtn
15337 (catch 'exit
15338 (while t
15339 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15340 (if (not groups) "no " "")
15341 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15342 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15343 (setq org-last-tag-selection-key c)
15344 (cond
15345 ((= c ?\r) (throw 'exit t))
15346 ((= c ?!)
15347 (setq groups (not groups))
15348 (goto-char (point-min))
15349 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15350 ((= c ?\C-c)
15351 (if (not expert)
15352 (org-fast-tag-show-exit
15353 (setq exit-after-next (not exit-after-next)))
15354 (setq expert nil)
15355 (delete-other-windows)
15356 (set-window-buffer (split-window-vertically) " *Org tags*")
15357 (org-switch-to-buffer-other-window " *Org tags*")
15358 (org-fit-window-to-buffer)))
15359 ((or (= c ?\C-g)
15360 (and (= c ?q) (not (rassoc c ntable))))
15361 (delete-overlay org-tags-overlay)
15362 (setq quit-flag t))
15363 ((= c ?\ )
15364 (setq current nil)
15365 (when exit-after-next (setq exit-after-next 'now)))
15366 ((= c ?\t)
15367 (condition-case nil
15368 (setq tg (completing-read
15369 "Tag: "
15370 (or buffer-tags
15371 (with-current-buffer buf
15372 (setq buffer-tags
15373 (org-get-buffer-tags))))))
15374 (quit (setq tg "")))
15375 (when (string-match "\\S-" tg)
15376 (cl-pushnew (list tg) buffer-tags :test #'equal)
15377 (if (member tg current)
15378 (setq current (delete tg current))
15379 (push tg current)))
15380 (when exit-after-next (setq exit-after-next 'now)))
15381 ((setq e (rassoc c todo-table) tg (car e))
15382 (with-current-buffer buf
15383 (save-excursion (org-todo tg)))
15384 (when exit-after-next (setq exit-after-next 'now)))
15385 ((setq e (rassoc c ntable) tg (car e))
15386 (if (member tg current)
15387 (setq current (delete tg current))
15388 (cl-loop for g in groups do
15389 (when (member tg g)
15390 (dolist (x g) (setq current (delete x current)))))
15391 (push tg current))
15392 (when exit-after-next (setq exit-after-next 'now))))
15394 ;; Create a sorted list
15395 (setq current
15396 (sort current
15397 (lambda (a b)
15398 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15399 (when (eq exit-after-next 'now) (throw 'exit t))
15400 (goto-char (point-min))
15401 (beginning-of-line 2)
15402 (delete-region (point) (point-at-eol))
15403 (org-fast-tag-insert "Current" current c-face)
15404 (org-set-current-tags-overlay current ov-prefix)
15405 (while (re-search-forward "\\[.\\] \\([[:alnum:]_@#%]+\\)" nil t)
15406 (setq tg (match-string 1))
15407 (add-text-properties
15408 (match-beginning 1) (match-end 1)
15409 (list 'face
15410 (cond
15411 ((member tg current) c-face)
15412 ((member tg inherited) i-face)
15413 (t (get-text-property (match-beginning 1) 'face))))))
15414 (goto-char (point-min)))))
15415 (delete-overlay org-tags-overlay)
15416 (if rtn
15417 (mapconcat 'identity current ":")
15418 nil))))
15420 (defun org-get-tags-string ()
15421 "Get the TAGS string in the current headline."
15422 (unless (org-at-heading-p t)
15423 (user-error "Not on a heading"))
15424 (save-excursion
15425 (beginning-of-line 1)
15426 (if (looking-at ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$")
15427 (match-string-no-properties 1)
15428 "")))
15430 (defun org-get-tags ()
15431 "Get the list of tags specified in the current headline."
15432 (org-split-string (org-get-tags-string) ":"))
15434 (defun org-get-buffer-tags ()
15435 "Get a table of all tags used in the buffer, for completion."
15436 (org-with-wide-buffer
15437 (goto-char (point-min))
15438 (let ((tag-re (concat org-outline-regexp-bol
15439 "\\(?:.*?[ \t]\\)?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
15440 tags)
15441 (while (re-search-forward tag-re nil t)
15442 (dolist (tag (org-split-string (match-string-no-properties 1) ":"))
15443 (push tag tags)))
15444 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15446 ;;;; The mapping API
15448 (defvar org-agenda-skip-comment-trees)
15449 (defvar org-agenda-skip-function)
15450 (defun org-map-entries (func &optional match scope &rest skip)
15451 "Call FUNC at each headline selected by MATCH in SCOPE.
15453 FUNC is a function or a lisp form. The function will be called without
15454 arguments, with the cursor positioned at the beginning of the headline.
15455 The return values of all calls to the function will be collected and
15456 returned as a list.
15458 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15459 does not need to preserve point. After evaluation, the cursor will be
15460 moved to the end of the line (presumably of the headline of the
15461 processed entry) and search continues from there. Under some
15462 circumstances, this may not produce the wanted results. For example,
15463 if you have removed (e.g. archived) the current (sub)tree it could
15464 mean that the next entry will be skipped entirely. In such cases, you
15465 can specify the position from where search should continue by making
15466 FUNC set the variable `org-map-continue-from' to the desired buffer
15467 position.
15469 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15470 Only headlines that are matched by this query will be considered during
15471 the iteration. When MATCH is nil or t, all headlines will be
15472 visited by the iteration.
15474 SCOPE determines the scope of this command. It can be any of:
15476 nil The current buffer, respecting the restriction if any
15477 tree The subtree started with the entry at point
15478 region The entries within the active region, if any
15479 region-start-level
15480 The entries within the active region, but only those at
15481 the same level than the first one.
15482 file The current buffer, without restriction
15483 file-with-archives
15484 The current buffer, and any archives associated with it
15485 agenda All agenda files
15486 agenda-with-archives
15487 All agenda files with any archive files associated with them
15488 \(file1 file2 ...)
15489 If this is a list, all files in the list will be scanned
15491 The remaining args are treated as settings for the skipping facilities of
15492 the scanner. The following items can be given here:
15494 archive skip trees with the archive tag
15495 comment skip trees with the COMMENT keyword
15496 function or Emacs Lisp form:
15497 will be used as value for `org-agenda-skip-function', so
15498 whenever the function returns a position, FUNC will not be
15499 called for that entry and search will continue from the
15500 position returned
15502 If your function needs to retrieve the tags including inherited tags
15503 at the *current* entry, you can use the value of the variable
15504 `org-scanner-tags' which will be much faster than getting the value
15505 with `org-get-tags-at'. If your function gets properties with
15506 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15507 to t around the call to `org-entry-properties' to get the same speedup.
15508 Note that if your function moves around to retrieve tags and properties at
15509 a *different* entry, you cannot use these techniques."
15510 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15511 (not (org-region-active-p)))
15512 (let* ((org-agenda-archives-mode nil) ; just to make sure
15513 (org-agenda-skip-archived-trees (memq 'archive skip))
15514 (org-agenda-skip-comment-trees (memq 'comment skip))
15515 (org-agenda-skip-function
15516 (car (org-delete-all '(comment archive) skip)))
15517 (org-tags-match-list-sublevels t)
15518 (start-level (eq scope 'region-start-level))
15519 matcher res
15520 org-todo-keywords-for-agenda
15521 org-done-keywords-for-agenda
15522 org-todo-keyword-alist-for-agenda
15523 org-tag-alist-for-agenda
15524 org--matcher-tags-todo-only)
15526 (cond
15527 ((eq match t) (setq matcher t))
15528 ((eq match nil) (setq matcher t))
15529 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15531 (save-excursion
15532 (save-restriction
15533 (cond ((eq scope 'tree)
15534 (org-back-to-heading t)
15535 (org-narrow-to-subtree)
15536 (setq scope nil))
15537 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15538 (org-region-active-p))
15539 ;; If needed, set start-level to a string like "2"
15540 (when start-level
15541 (save-excursion
15542 (goto-char (region-beginning))
15543 (unless (org-at-heading-p) (outline-next-heading))
15544 (setq start-level (org-current-level))))
15545 (narrow-to-region (region-beginning)
15546 (save-excursion
15547 (goto-char (region-end))
15548 (unless (and (bolp) (org-at-heading-p))
15549 (outline-next-heading))
15550 (point)))
15551 (setq scope nil)))
15553 (if (not scope)
15554 (progn
15555 (org-agenda-prepare-buffers
15556 (and buffer-file-name (list buffer-file-name)))
15557 (setq res
15558 (org-scan-tags
15559 func matcher org--matcher-tags-todo-only start-level)))
15560 ;; Get the right scope
15561 (cond
15562 ((and scope (listp scope) (symbolp (car scope)))
15563 (setq scope (eval scope)))
15564 ((eq scope 'agenda)
15565 (setq scope (org-agenda-files t)))
15566 ((eq scope 'agenda-with-archives)
15567 (setq scope (org-agenda-files t))
15568 (setq scope (org-add-archive-files scope)))
15569 ((eq scope 'file)
15570 (setq scope (and buffer-file-name (list buffer-file-name))))
15571 ((eq scope 'file-with-archives)
15572 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15573 (org-agenda-prepare-buffers scope)
15574 (dolist (file scope)
15575 (with-current-buffer (org-find-base-buffer-visiting file)
15576 (save-excursion
15577 (save-restriction
15578 (widen)
15579 (goto-char (point-min))
15580 (setq res
15581 (append
15583 (org-scan-tags
15584 func matcher org--matcher-tags-todo-only))))))))))
15585 res)))
15587 ;;; Properties API
15589 (defconst org-special-properties
15590 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15591 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15592 "The special properties valid in Org mode.
15593 These are properties that are not defined in the property drawer,
15594 but in some other way.")
15596 (defconst org-default-properties
15597 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15598 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15599 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15600 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15601 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15602 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15603 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15604 "Some properties that are used by Org mode for various purposes.
15605 Being in this list makes sure that they are offered for completion.")
15607 (defun org--valid-property-p (property)
15608 "Non nil when string PROPERTY is a valid property name."
15609 (not
15610 (or (equal property "")
15611 (org-string-match-p "\\s-" property))))
15613 (defun org--update-property-plist (key val props)
15614 "Associate KEY to VAL in alist PROPS.
15615 Modifications are made by side-effect. Return new alist."
15616 (let* ((appending (string= (substring key -1) "+"))
15617 (key (if appending (substring key 0 -1) key))
15618 (old (assoc-string key props t)))
15619 (if (not old) (cons (cons key val) props)
15620 (setcdr old (if appending (concat (cdr old) " " val) val))
15621 props)))
15623 (defun org-get-property-block (&optional beg force)
15624 "Return the (beg . end) range of the body of the property drawer.
15625 BEG is the beginning of the current subtree, or of the part
15626 before the first headline. If it is not given, it will be found.
15627 If the drawer does not exist, create it if FORCE is non-nil, or
15628 return nil."
15629 (org-with-wide-buffer
15630 (when beg (goto-char beg))
15631 (unless (org-before-first-heading-p)
15632 (let ((beg (cond (beg)
15633 ((or (not (featurep 'org-inlinetask))
15634 (org-inlinetask-in-task-p))
15635 (org-back-to-heading t))
15636 (t (org-with-limited-levels (org-back-to-heading t))))))
15637 (forward-line)
15638 (when (looking-at-p org-planning-line-re) (forward-line))
15639 (cond ((looking-at org-property-drawer-re)
15640 (forward-line)
15641 (cons (point) (progn (goto-char (match-end 0))
15642 (line-beginning-position))))
15643 (force
15644 (goto-char beg)
15645 (org-insert-property-drawer)
15646 (let ((pos (save-excursion (search-forward ":END:")
15647 (line-beginning-position))))
15648 (cons pos pos))))))))
15650 (defun org-at-property-p ()
15651 "Non-nil when point is inside a property drawer.
15652 See `org-property-re' for match data, if applicable."
15653 (save-excursion
15654 (beginning-of-line)
15655 (and (looking-at org-property-re)
15656 (let ((property-drawer (save-match-data (org-get-property-block))))
15657 (and property-drawer
15658 (>= (point) (car property-drawer))
15659 (< (point) (cdr property-drawer)))))))
15661 (defun org-property-action ()
15662 "Do an action on properties."
15663 (interactive)
15664 (unless (org-at-property-p) (user-error "Not at a property"))
15665 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15666 (let ((c (read-char-exclusive)))
15667 (cl-case c
15668 (?s (call-interactively #'org-set-property))
15669 (?d (call-interactively #'org-delete-property))
15670 (?D (call-interactively #'org-delete-property-globally))
15671 (?c (call-interactively #'org-compute-property-at-point))
15672 (otherwise (user-error "No such property action %c" c)))))
15674 (defun org-inc-effort ()
15675 "Increment the value of the effort property in the current entry."
15676 (interactive)
15677 (org-set-effort nil t))
15679 (defvar org-clock-effort) ; Defined in org-clock.el.
15680 (defvar org-clock-current-task) ; Defined in org-clock.el.
15681 (defun org-set-effort (&optional value increment)
15682 "Set the effort property of the current entry.
15683 With numerical prefix arg, use the nth allowed value, 0 stands for the
15684 10th allowed value.
15686 When INCREMENT is non-nil, set the property to the next allowed value."
15687 (interactive "P")
15688 (when (equal value 0) (setq value 10))
15689 (let* ((completion-ignore-case t)
15690 (prop org-effort-property)
15691 (cur (org-entry-get nil prop))
15692 (allowed (org-property-get-allowed-values nil prop 'table))
15693 (existing (mapcar 'list (org-property-values prop)))
15694 (heading (nth 4 (org-heading-components)))
15696 (val (cond
15697 ((stringp value) value)
15698 ((and allowed (integerp value))
15699 (or (car (nth (1- value) allowed))
15700 (car (org-last allowed))))
15701 ((and allowed increment)
15702 (or (cl-caadr (member (list cur) allowed))
15703 (user-error "Allowed effort values are not set")))
15704 (allowed
15705 (message "Select 1-9,0, [RET%s]: %s"
15706 (if cur (concat "=" cur) "")
15707 (mapconcat 'car allowed " "))
15708 (setq rpl (read-char-exclusive))
15709 (if (equal rpl ?\r)
15711 (setq rpl (- rpl ?0))
15712 (when (equal rpl 0) (setq rpl 10))
15713 (if (and (> rpl 0) (<= rpl (length allowed)))
15714 (car (nth (1- rpl) allowed))
15715 (org-completing-read "Effort: " allowed nil))))
15717 (org-completing-read
15718 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15719 (concat "[" cur "]") "")
15720 ": ")
15721 existing nil nil "" nil cur)))))
15722 (unless (equal (org-entry-get nil prop) val)
15723 (org-entry-put nil prop val))
15724 (org-refresh-property
15725 '((effort . identity)
15726 (effort-minutes . org-duration-string-to-minutes))
15727 val)
15728 (when (string= heading org-clock-current-task)
15729 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15730 (org-clock-update-mode-line))
15731 (message "%s is now %s" prop val)))
15733 (defun org-entry-properties (&optional pom which)
15734 "Get all properties of the current entry.
15736 When POM is a buffer position, get all properties from the entry
15737 there instead.
15739 This includes the TODO keyword, the tags, time strings for
15740 deadline, scheduled, and clocking, and any additional properties
15741 defined in the entry.
15743 If WHICH is nil or `all', get all properties. If WHICH is
15744 `special' or `standard', only get that subclass. If WHICH is
15745 a string, only get that property.
15747 Return value is an alist. Keys are properties, as upcased
15748 strings."
15749 (org-with-point-at pom
15750 (when (and (derived-mode-p 'org-mode)
15751 (ignore-errors (org-back-to-heading t)))
15752 (catch 'exit
15753 (let* ((beg (point))
15754 (specific (and (stringp which) (upcase which)))
15755 (which (cond ((not specific) which)
15756 ((member specific org-special-properties) 'special)
15757 (t 'standard)))
15758 props)
15759 ;; Get the special properties, like TODO and TAGS.
15760 (when (memq which '(nil all special))
15761 (when (or (not specific) (string= specific "CLOCKSUM"))
15762 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15763 (when clocksum
15764 (push (cons "CLOCKSUM"
15765 (org-minutes-to-clocksum-string clocksum))
15766 props)))
15767 (when specific (throw 'exit props)))
15768 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15769 (let ((clocksumt (get-text-property (point)
15770 :org-clock-minutes-today)))
15771 (when clocksumt
15772 (push (cons "CLOCKSUM_T"
15773 (org-minutes-to-clocksum-string clocksumt))
15774 props)))
15775 (when specific (throw 'exit props)))
15776 (when (or (not specific) (string= specific "ITEM"))
15777 (when (looking-at org-complex-heading-regexp)
15778 (push (cons "ITEM"
15779 (let ((title (match-string-no-properties 4)))
15780 (if (org-string-nw-p title)
15781 (org-remove-tabs title)
15782 "")))
15783 props))
15784 (when specific (throw 'exit props)))
15785 (when (or (not specific) (string= specific "TODO"))
15786 (let ((case-fold-search nil))
15787 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15788 (push (cons "TODO" (match-string-no-properties 2)) props)))
15789 (when specific (throw 'exit props)))
15790 (when (or (not specific) (string= specific "PRIORITY"))
15791 (push (cons "PRIORITY"
15792 (if (looking-at org-priority-regexp)
15793 (match-string-no-properties 2)
15794 (char-to-string org-default-priority)))
15795 props)
15796 (when specific (throw 'exit props)))
15797 (when (or (not specific) (string= specific "FILE"))
15798 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15799 props)
15800 (when specific (throw 'exit props)))
15801 (when (or (not specific) (string= specific "TAGS"))
15802 (let ((value (org-string-nw-p (org-get-tags-string))))
15803 (when value (push (cons "TAGS" value) props)))
15804 (when specific (throw 'exit props)))
15805 (when (or (not specific) (string= specific "ALLTAGS"))
15806 (let ((value (org-get-tags-at)))
15807 (when value
15808 (push (cons "ALLTAGS"
15809 (format ":%s:" (mapconcat #'identity value ":")))
15810 props)))
15811 (when specific (throw 'exit props)))
15812 (when (or (not specific) (string= specific "BLOCKED"))
15813 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15814 (when specific (throw 'exit props)))
15815 (when (or (not specific)
15816 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15817 (forward-line)
15818 (when (looking-at-p org-planning-line-re)
15819 (end-of-line)
15820 (let ((bol (line-beginning-position))
15821 ;; Backward compatibility: time keywords used to
15822 ;; be configurable (before 8.3). Make sure we
15823 ;; get the correct keyword.
15824 (key-assoc `(("CLOSED" . ,org-closed-string)
15825 ("DEADLINE" . ,org-deadline-string)
15826 ("SCHEDULED" . ,org-scheduled-string))))
15827 (dolist (pair (if specific (list (assoc specific key-assoc))
15828 key-assoc))
15829 (save-excursion
15830 (when (search-backward (cdr pair) bol t)
15831 (goto-char (match-end 0))
15832 (skip-chars-forward " \t")
15833 (and (looking-at org-ts-regexp-both)
15834 (push (cons (car pair)
15835 (match-string-no-properties 0))
15836 props)))))))
15837 (when specific (throw 'exit props)))
15838 (when (or (not specific)
15839 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15840 (let ((find-ts
15841 (lambda (end ts)
15842 ;; Fix next time-stamp before END. TS is the
15843 ;; list of time-stamps found so far.
15844 (let ((ts ts)
15845 (regexp (cond
15846 ((string= specific "TIMESTAMP")
15847 org-ts-regexp)
15848 ((string= specific "TIMESTAMP_IA")
15849 org-ts-regexp-inactive)
15850 ((assoc "TIMESTAMP_IA" ts)
15851 org-ts-regexp)
15852 ((assoc "TIMESTAMP" ts)
15853 org-ts-regexp-inactive)
15854 (t org-ts-regexp-both))))
15855 (catch 'next
15856 (while (re-search-forward regexp end t)
15857 (backward-char)
15858 (let ((object (org-element-context)))
15859 ;; Accept to match timestamps in node
15860 ;; properties, too.
15861 (when (memq (org-element-type object)
15862 '(node-property timestamp))
15863 (let ((type
15864 (org-element-property :type object)))
15865 (cond
15866 ((and (memq type '(active active-range))
15867 (not (equal specific "TIMESTAMP_IA")))
15868 (unless (assoc "TIMESTAMP" ts)
15869 (push (cons "TIMESTAMP"
15870 (org-element-property
15871 :raw-value object))
15873 (when specific (throw 'exit ts))))
15874 ((and (memq type '(inactive inactive-range))
15875 (not (string= specific "TIMESTAMP")))
15876 (unless (assoc "TIMESTAMP_IA" ts)
15877 (push (cons "TIMESTAMP_IA"
15878 (org-element-property
15879 :raw-value object))
15881 (when specific (throw 'exit ts))))))
15882 ;; Both timestamp types are found,
15883 ;; move to next part.
15884 (when (= (length ts) 2) (throw 'next ts)))))
15885 ts)))))
15886 (goto-char beg)
15887 ;; First look for timestamps within headline.
15888 (let ((ts (funcall find-ts (line-end-position) nil)))
15889 (if (= (length ts) 2) (setq props (nconc ts props))
15890 (forward-line)
15891 ;; Then find timestamps in the section, skipping
15892 ;; planning line.
15893 (when (looking-at-p org-planning-line-re)
15894 (forward-line))
15895 (let ((end (save-excursion (outline-next-heading))))
15896 (setq props (nconc (funcall find-ts end ts) props))))))))
15897 ;; Get the standard properties, like :PROP:.
15898 (when (memq which '(nil all standard))
15899 ;; If we are looking after a specific property, delegate
15900 ;; to `org-entry-get', which is faster. However, make an
15901 ;; exception for "CATEGORY", since it can be also set
15902 ;; through keywords (i.e. #+CATEGORY).
15903 (if (and specific (not (equal specific "CATEGORY")))
15904 (let ((value (org-entry-get beg specific nil t)))
15905 (throw 'exit (and value (list (cons specific value)))))
15906 (let ((range (org-get-property-block beg)))
15907 (when range
15908 (let ((end (cdr range)) seen-base)
15909 (goto-char (car range))
15910 ;; Unlike to `org--update-property-plist', we
15911 ;; handle the case where base values is found
15912 ;; after its extension. We also forbid standard
15913 ;; properties to be named as special properties.
15914 (while (re-search-forward org-property-re end t)
15915 (let* ((key (upcase (match-string-no-properties 2)))
15916 (extendp (org-string-match-p "\\+\\'" key))
15917 (key-base (if extendp (substring key 0 -1) key))
15918 (value (match-string-no-properties 3)))
15919 (cond
15920 ((member-ignore-case key-base org-special-properties))
15921 (extendp
15922 (setq props
15923 (org--update-property-plist key value props)))
15924 ((member key seen-base))
15925 (t (push key seen-base)
15926 (let ((p (assoc-string key props t)))
15927 (if p (setcdr p (concat value " " (cdr p)))
15928 (push (cons key value) props))))))))))))
15929 (unless (assoc "CATEGORY" props)
15930 (push (cons "CATEGORY" (org-get-category beg)) props)
15931 (when (string= specific "CATEGORY") (throw 'exit props)))
15932 ;; Return value.
15933 props)))))
15935 (defun org-property--local-values (property literal-nil)
15936 "Return value for PROPERTY in current entry.
15937 Value is a list whose car is the base value for PROPERTY and cdr
15938 a list of accumulated values. Return nil if neither is found in
15939 the entry. Also return nil when PROPERTY is set to \"nil\",
15940 unless LITERAL-NIL is non-nil."
15941 (let ((range (org-get-property-block)))
15942 (when range
15943 (goto-char (car range))
15944 (let* ((case-fold-search t)
15945 (end (cdr range))
15946 (value
15947 ;; Base value.
15948 (save-excursion
15949 (let ((v (and (re-search-forward
15950 (org-re-property property nil t) end t)
15951 (match-string-no-properties 3))))
15952 (list (if literal-nil v (org-not-nil v)))))))
15953 ;; Find additional values.
15954 (let* ((property+ (org-re-property (concat property "+") nil t)))
15955 (while (re-search-forward property+ end t)
15956 (push (match-string-no-properties 3) value)))
15957 ;; Return final values.
15958 (and (not (equal value '(nil))) (nreverse value))))))
15960 (defun org-entry-get (pom property &optional inherit literal-nil)
15961 "Get value of PROPERTY for entry or content at point-or-marker POM.
15963 If INHERIT is non-nil and the entry does not have the property,
15964 then also check higher levels of the hierarchy. If INHERIT is
15965 the symbol `selective', use inheritance only if the setting in
15966 `org-use-property-inheritance' selects PROPERTY for inheritance.
15968 If the property is present but empty, the return value is the
15969 empty string. If the property is not present at all, nil is
15970 returned. In any other case, return the value as a string.
15971 Search is case-insensitive.
15973 If LITERAL-NIL is set, return the string value \"nil\" as
15974 a string, do not interpret it as the list atom nil. This is used
15975 for inheritance when a \"nil\" value can supersede a non-nil
15976 value higher up the hierarchy."
15977 (org-with-point-at pom
15978 (cond
15979 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15980 ;; We need a special property. Use `org-entry-properties' to
15981 ;; retrieve it, but specify the wanted property.
15982 (cdr (assoc-string property (org-entry-properties nil property))))
15983 ((and inherit
15984 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15985 (org-entry-get-with-inheritance property literal-nil))
15987 (let* ((local (org-property--local-values property literal-nil))
15988 (value (and local (mapconcat #'identity (delq nil local) " "))))
15989 (if literal-nil value (org-not-nil value)))))))
15991 (defun org-property-or-variable-value (var &optional inherit)
15992 "Check if there is a property fixing the value of VAR.
15993 If yes, return this value. If not, return the current value of the variable."
15994 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15995 (if (and prop (stringp prop) (string-match "\\S-" prop))
15996 (read prop)
15997 (symbol-value var))))
15999 (defun org-entry-delete (pom property)
16000 "Delete PROPERTY from entry at point-or-marker POM.
16001 Accumulated properties, i.e. PROPERTY+, are also removed. Return
16002 non-nil when a property was removed."
16003 (unless (member property org-special-properties)
16004 (org-with-point-at pom
16005 (let ((range (org-get-property-block)))
16006 (when range
16007 (let* ((begin (car range))
16008 (origin (cdr range))
16009 (end (copy-marker origin))
16010 (re (org-re-property
16011 (concat (regexp-quote property) "\\+?") t t)))
16012 (goto-char begin)
16013 (while (re-search-forward re end t)
16014 (delete-region (match-beginning 0) (line-beginning-position 2)))
16015 ;; If drawer is empty, remove it altogether.
16016 (when (= begin end)
16017 (delete-region (line-beginning-position 0)
16018 (line-beginning-position 2)))
16019 ;; Return non-nil if some property was removed.
16020 (prog1 (/= end origin) (set-marker end nil))))))))
16022 ;; Multi-values properties are properties that contain multiple values
16023 ;; These values are assumed to be single words, separated by whitespace.
16024 (defun org-entry-add-to-multivalued-property (pom property value)
16025 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
16026 (let* ((old (org-entry-get pom property))
16027 (values (and old (org-split-string old "[ \t]"))))
16028 (setq value (org-entry-protect-space value))
16029 (unless (member value values)
16030 (setq values (append values (list value)))
16031 (org-entry-put pom property
16032 (mapconcat 'identity values " ")))))
16034 (defun org-entry-remove-from-multivalued-property (pom property value)
16035 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
16036 (let* ((old (org-entry-get pom property))
16037 (values (and old (org-split-string old "[ \t]"))))
16038 (setq value (org-entry-protect-space value))
16039 (when (member value values)
16040 (setq values (delete value values))
16041 (org-entry-put pom property
16042 (mapconcat 'identity values " ")))))
16044 (defun org-entry-member-in-multivalued-property (pom property value)
16045 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
16046 (let* ((old (org-entry-get pom property))
16047 (values (and old (org-split-string old "[ \t]"))))
16048 (setq value (org-entry-protect-space value))
16049 (member value values)))
16051 (defun org-entry-get-multivalued-property (pom property)
16052 "Return a list of values in a multivalued property."
16053 (let* ((value (org-entry-get pom property))
16054 (values (and value (org-split-string value "[ \t]"))))
16055 (mapcar 'org-entry-restore-space values)))
16057 (defun org-entry-put-multivalued-property (pom property &rest values)
16058 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
16059 VALUES should be a list of strings. Spaces will be protected."
16060 (org-entry-put pom property
16061 (mapconcat 'org-entry-protect-space values " "))
16062 (let* ((value (org-entry-get pom property))
16063 (values (and value (org-split-string value "[ \t]"))))
16064 (mapcar 'org-entry-restore-space values)))
16066 (defun org-entry-protect-space (s)
16067 "Protect spaces and newline in string S."
16068 (while (string-match " " s)
16069 (setq s (replace-match "%20" t t s)))
16070 (while (string-match "\n" s)
16071 (setq s (replace-match "%0A" t t s)))
16074 (defun org-entry-restore-space (s)
16075 "Restore spaces and newline in string S."
16076 (while (string-match "%20" s)
16077 (setq s (replace-match " " t t s)))
16078 (while (string-match "%0A" s)
16079 (setq s (replace-match "\n" t t s)))
16082 (defvar org-entry-property-inherited-from (make-marker)
16083 "Marker pointing to the entry from where a property was inherited.
16084 Each call to `org-entry-get-with-inheritance' will set this marker to the
16085 location of the entry where the inheritance search matched. If there was
16086 no match, the marker will point nowhere.
16087 Note that also `org-entry-get' calls this function, if the INHERIT flag
16088 is set.")
16090 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16091 "Get PROPERTY of entry or content at point, search higher levels if needed.
16092 The search will stop at the first ancestor which has the property defined.
16093 If the value found is \"nil\", return nil to show that the property
16094 should be considered as undefined (this is the meaning of nil here).
16095 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16096 (move-marker org-entry-property-inherited-from nil)
16097 (org-with-wide-buffer
16098 (let (value)
16099 (catch 'exit
16100 (while t
16101 (let ((v (org-property--local-values property literal-nil)))
16102 (when v
16103 (setq value
16104 (concat (mapconcat #'identity (delq nil v) " ")
16105 (and value " ")
16106 value)))
16107 (cond
16108 ((car v)
16109 (org-back-to-heading t)
16110 (move-marker org-entry-property-inherited-from (point))
16111 (throw 'exit nil))
16112 ((org-up-heading-safe))
16114 (let ((global
16115 (cdr (or (assoc-string property org-file-properties t)
16116 (assoc-string property org-global-properties t)
16117 (assoc-string property org-global-properties-fixed t)))))
16118 (cond ((not global))
16119 (value (setq value (concat global " " value)))
16120 (t (setq value global))))
16121 (throw 'exit nil))))))
16122 (if literal-nil value (org-not-nil value)))))
16124 (defvar org-property-changed-functions nil
16125 "Hook called when the value of a property has changed.
16126 Each hook function should accept two arguments, the name of the property
16127 and the new value.")
16129 (defun org-entry-put (pom property value)
16130 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16132 If the value is nil, it is converted to the empty string. If it
16133 is not a string, an error is raised. Also raise an error on
16134 invalid property names.
16136 PROPERTY can be any regular property (see
16137 `org-special-properties'). It can also be \"TODO\",
16138 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16140 For the last two properties, VALUE may have any of the special
16141 values \"earlier\" and \"later\". The function then increases or
16142 decreases scheduled or deadline date by one day."
16143 (cond ((null value) (setq value ""))
16144 ((not (stringp value)) (error "Properties values should be strings"))
16145 ((not (org--valid-property-p property))
16146 (user-error "Invalid property name: \"%s\"" property)))
16147 (org-with-point-at pom
16148 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16149 (org-back-to-heading t)
16150 (org-with-limited-levels (org-back-to-heading t)))
16151 (let ((beg (point)))
16152 (cond
16153 ((equal property "TODO")
16154 (cond ((not (org-string-nw-p value)) (setq value 'none))
16155 ((not (member value org-todo-keywords-1))
16156 (user-error "\"%s\" is not a valid TODO state" value)))
16157 (org-todo value)
16158 (org-set-tags nil 'align))
16159 ((equal property "PRIORITY")
16160 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16161 (org-set-tags nil 'align))
16162 ((equal property "SCHEDULED")
16163 (forward-line)
16164 (if (and (looking-at-p org-planning-line-re)
16165 (re-search-forward
16166 org-scheduled-time-regexp (line-end-position) t))
16167 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16168 ((string= value "later") (org-timestamp-change 1 'day))
16169 ((string= value "") (org-schedule '(4)))
16170 (t (org-schedule nil value)))
16171 (if (member value '("earlier" "later" ""))
16172 (call-interactively #'org-schedule)
16173 (org-schedule nil value))))
16174 ((equal property "DEADLINE")
16175 (forward-line)
16176 (if (and (looking-at-p org-planning-line-re)
16177 (re-search-forward
16178 org-deadline-time-regexp (line-end-position) t))
16179 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16180 ((string= value "later") (org-timestamp-change 1 'day))
16181 ((string= value "") (org-deadline '(4)))
16182 (t (org-deadline nil value)))
16183 (if (member value '("earlier" "later" ""))
16184 (call-interactively #'org-deadline)
16185 (org-deadline nil value))))
16186 ((member property org-special-properties)
16187 (error "The %s property cannot be set with `org-entry-put'" property))
16189 (let* ((range (org-get-property-block beg 'force))
16190 (end (cdr range))
16191 (case-fold-search t))
16192 (goto-char (car range))
16193 (if (re-search-forward (org-re-property property nil t) end t)
16194 (progn (delete-region (match-beginning 0) (match-end 0))
16195 (goto-char (match-beginning 0)))
16196 (goto-char end)
16197 (insert "\n")
16198 (backward-char))
16199 (insert ":" property ":")
16200 (when value (insert " " value))
16201 (org-indent-line)))))
16202 (run-hook-with-args 'org-property-changed-functions property value)))
16204 (defun org-buffer-property-keys
16205 (&optional specials defaults columns ignore-malformed)
16206 "Get all property keys in the current buffer.
16208 When SPECIALS is non-nil, also list the special properties that
16209 reflect things like tags and TODO state.
16211 When DEFAULTS is non-nil, also include properties that has
16212 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16213 DESCRIPTION, LOCATION, and LOGGING and others.
16215 When COLUMNS in non-nil, also include property names given in
16216 COLUMN formats in the current buffer.
16218 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16219 automatically performed, such drawers will be silently ignored."
16220 (let ((case-fold-search t)
16221 (props (append
16222 (and specials org-special-properties)
16223 (and defaults (cons org-effort-property org-default-properties))
16224 nil)))
16225 (org-with-wide-buffer
16226 (goto-char (point-min))
16227 (while (re-search-forward org-property-start-re nil t)
16228 (let ((range (org-get-property-block)))
16229 (catch 'skip
16230 (unless range
16231 (when (and (not ignore-malformed)
16232 (not (org-before-first-heading-p))
16233 (y-or-n-p (format "Malformed drawer at %d, repair?"
16234 (line-beginning-position))))
16235 (org-get-property-block nil t))
16236 (throw 'skip nil))
16237 (goto-char (car range))
16238 (let ((begin (car range))
16239 (end (cdr range)))
16240 ;; Make sure that found property block is not located
16241 ;; before current point, as it would generate an infloop.
16242 ;; It can happen, for example, in the following
16243 ;; situation:
16245 ;; * Headline
16246 ;; :PROPERTIES:
16247 ;; ...
16248 ;; :END:
16249 ;; *************** Inlinetask
16250 ;; #+BEGIN_EXAMPLE
16251 ;; :PROPERTIES:
16252 ;; #+END_EXAMPLE
16254 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16255 (while (< (point) end)
16256 (let ((p (progn (looking-at org-property-re)
16257 (match-string-no-properties 2))))
16258 ;; Only add true property name, not extension symbol.
16259 (push (if (not (org-string-match-p "\\+\\'" p)) p
16260 (substring p 0 -1))
16261 props))
16262 (forward-line))))
16263 (outline-next-heading)))
16264 (when columns
16265 (goto-char (point-min))
16266 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16267 (let ((element (org-element-at-point)))
16268 (when (memq (org-element-type element) '(keyword node-property))
16269 (let ((value (org-element-property :value element))
16270 (start 0))
16271 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16272 (setq start (match-end 0))
16273 (let ((p (match-string-no-properties 1 value)))
16274 (unless (member-ignore-case p org-special-properties)
16275 (push p props))))))))))
16276 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16278 (defun org-property-values (key)
16279 "List all non-nil values of property KEY in current buffer."
16280 (org-with-wide-buffer
16281 (goto-char (point-min))
16282 (let ((case-fold-search t)
16283 (re (org-re-property key))
16284 values)
16285 (while (re-search-forward re nil t)
16286 (push (org-entry-get (point) key) values))
16287 (delete-dups values))))
16289 (defun org-insert-property-drawer ()
16290 "Insert a property drawer into the current entry."
16291 (org-with-wide-buffer
16292 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16293 (org-back-to-heading t)
16294 (org-with-limited-levels (org-back-to-heading t)))
16295 (forward-line)
16296 (when (looking-at-p org-planning-line-re) (forward-line))
16297 (unless (looking-at-p org-property-drawer-re)
16298 ;; Make sure we start editing a line from current entry, not from
16299 ;; next one. It prevents extending text properties or overlays
16300 ;; belonging to the latter.
16301 (when (bolp) (backward-char))
16302 (let ((begin (1+ (point)))
16303 (inhibit-read-only t))
16304 (insert "\n:PROPERTIES:\n:END:")
16305 (when (eobp) (insert "\n"))
16306 (org-indent-region begin (point))))))
16308 (defun org-insert-drawer (&optional arg drawer)
16309 "Insert a drawer at point.
16311 When optional argument ARG is non-nil, insert a property drawer.
16313 Optional argument DRAWER, when non-nil, is a string representing
16314 drawer's name. Otherwise, the user is prompted for a name.
16316 If a region is active, insert the drawer around that region
16317 instead.
16319 Point is left between drawer's boundaries."
16320 (interactive "P")
16321 (let* ((drawer (if arg "PROPERTIES"
16322 (or drawer (read-from-minibuffer "Drawer: ")))))
16323 (cond
16324 ;; With C-u, fall back on `org-insert-property-drawer'
16325 (arg (org-insert-property-drawer))
16326 ;; Check validity of suggested drawer's name.
16327 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16328 (user-error "Invalid drawer name"))
16329 ;; With an active region, insert a drawer at point.
16330 ((not (org-region-active-p))
16331 (progn
16332 (unless (bolp) (insert "\n"))
16333 (insert (format ":%s:\n\n:END:\n" drawer))
16334 (forward-line -2)))
16335 ;; Otherwise, insert the drawer at point
16337 (let ((rbeg (region-beginning))
16338 (rend (copy-marker (region-end))))
16339 (unwind-protect
16340 (progn
16341 (goto-char rbeg)
16342 (beginning-of-line)
16343 (when (save-excursion
16344 (re-search-forward org-outline-regexp-bol rend t))
16345 (user-error "Drawers cannot contain headlines"))
16346 ;; Position point at the beginning of the first
16347 ;; non-blank line in region. Insert drawer's opening
16348 ;; there, then indent it.
16349 (org-skip-whitespace)
16350 (beginning-of-line)
16351 (insert ":" drawer ":\n")
16352 (forward-line -1)
16353 (indent-for-tab-command)
16354 ;; Move point to the beginning of the first blank line
16355 ;; after the last non-blank line in region. Insert
16356 ;; drawer's closing, then indent it.
16357 (goto-char rend)
16358 (skip-chars-backward " \r\t\n")
16359 (insert "\n:END:")
16360 (deactivate-mark t)
16361 (indent-for-tab-command)
16362 (unless (eolp) (insert "\n")))
16363 ;; Clear marker, whatever the outcome of insertion is.
16364 (set-marker rend nil)))))))
16366 (defvar org-property-set-functions-alist nil
16367 "Property set function alist.
16368 Each entry should have the following format:
16370 (PROPERTY . READ-FUNCTION)
16372 The read function will be called with the same argument as
16373 `org-completing-read'.")
16375 (defun org-set-property-function (property)
16376 "Get the function that should be used to set PROPERTY.
16377 This is computed according to `org-property-set-functions-alist'."
16378 (or (cdr (assoc property org-property-set-functions-alist))
16379 'org-completing-read))
16381 (defun org-read-property-value (property)
16382 "Read PROPERTY value from user."
16383 (let* ((completion-ignore-case t)
16384 (allowed (org-property-get-allowed-values nil property 'table))
16385 (cur (org-entry-get nil property))
16386 (prompt (concat property " value"
16387 (if (and cur (string-match "\\S-" cur))
16388 (concat " [" cur "]") "") ": "))
16389 (set-function (org-set-property-function property))
16390 (val (if allowed
16391 (funcall set-function prompt allowed nil
16392 (not (get-text-property 0 'org-unrestricted
16393 (caar allowed))))
16394 (funcall set-function prompt
16395 (mapcar 'list (org-property-values property))
16396 nil nil "" nil cur))))
16397 (org-trim val)))
16399 (defvar org-last-set-property nil)
16400 (defvar org-last-set-property-value nil)
16401 (defun org-read-property-name ()
16402 "Read a property name."
16403 (let ((completion-ignore-case t)
16404 (default-prop (or (and (org-at-property-p)
16405 (match-string-no-properties 2))
16406 org-last-set-property)))
16407 (org-completing-read
16408 (concat "Property"
16409 (if default-prop (concat " [" default-prop "]") "")
16410 ": ")
16411 (mapcar #'list (org-buffer-property-keys nil t t))
16412 nil nil nil nil default-prop)))
16414 (defun org-set-property-and-value (use-last)
16415 "Allow to set [PROPERTY]: [value] direction from prompt.
16416 When use-default, don't even ask, just use the last
16417 \"[PROPERTY]: [value]\" string from the history."
16418 (interactive "P")
16419 (let* ((completion-ignore-case t)
16420 (pv (or (and use-last org-last-set-property-value)
16421 (org-completing-read
16422 "Enter a \"[Property]: [value]\" pair: "
16423 nil nil nil nil nil
16424 org-last-set-property-value)))
16425 prop val)
16426 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16427 (setq prop (match-string 1 pv)
16428 val (match-string 2 pv))
16429 (org-set-property prop val))))
16431 (defun org-set-property (property value)
16432 "In the current entry, set PROPERTY to VALUE.
16434 When called interactively, this will prompt for a property name, offering
16435 completion on existing and default properties. And then it will prompt
16436 for a value, offering completion either on allowed values (via an inherited
16437 xxx_ALL property) or on existing values in other instances of this property
16438 in the current file.
16440 Throw an error when trying to set a property with an invalid name."
16441 (interactive (list nil nil))
16442 (let ((property (or property (org-read-property-name))))
16443 ;; `org-entry-put' also makes the following check, but this one
16444 ;; avoids polluting `org-last-set-property' and
16445 ;; `org-last-set-property-value' needlessly.
16446 (unless (org--valid-property-p property)
16447 (user-error "Invalid property name: \"%s\"" property))
16448 (let ((value (or value (org-read-property-value property)))
16449 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16450 (setq org-last-set-property property)
16451 (setq org-last-set-property-value (concat property ": " value))
16452 ;; Possibly postprocess the inserted value:
16453 (when fn (setq value (funcall fn value)))
16454 (unless (equal (org-entry-get nil property) value)
16455 (org-entry-put nil property value)))))
16457 (defun org-find-property (property &optional value)
16458 "Find first entry in buffer that sets PROPERTY.
16460 When optional argument VALUE is non-nil, only consider an entry
16461 if it contains PROPERTY set to this value. If PROPERTY should be
16462 explicitly set to nil, use string \"nil\" for VALUE.
16464 Return position where the entry begins, or nil if there is no
16465 such entry. If narrowing is in effect, only search the visible
16466 part of the buffer."
16467 (save-excursion
16468 (goto-char (point-min))
16469 (let ((case-fold-search t)
16470 (re (org-re-property property nil (not value) value)))
16471 (catch 'exit
16472 (while (re-search-forward re nil t)
16473 (when (if value (org-at-property-p)
16474 (org-entry-get (point) property nil t))
16475 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16477 (defun org-delete-property (property)
16478 "In the current entry, delete PROPERTY."
16479 (interactive
16480 (let* ((completion-ignore-case t)
16481 (cat (org-entry-get (point) "CATEGORY"))
16482 (props0 (org-entry-properties nil 'standard))
16483 (props (if cat props0
16484 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16485 (prop (if (< 1 (length props))
16486 (completing-read "Property: " props nil t)
16487 (caar props))))
16488 (list prop)))
16489 (if (not property)
16490 (message "No property to delete in this entry")
16491 (org-entry-delete nil property)
16492 (message "Property \"%s\" deleted" property)))
16494 (defun org-delete-property-globally (property)
16495 "Remove PROPERTY globally, from all entries.
16496 This function ignores narrowing, if any."
16497 (interactive
16498 (let* ((completion-ignore-case t)
16499 (prop (completing-read
16500 "Globally remove property: "
16501 (mapcar #'list (org-buffer-property-keys)))))
16502 (list prop)))
16503 (org-with-wide-buffer
16504 (goto-char (point-min))
16505 (let ((count 0)
16506 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16507 (while (re-search-forward re nil t)
16508 (when (org-entry-delete (point) property) (cl-incf count)))
16509 (message "Property \"%s\" removed from %d entries" property count))))
16511 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16513 (defun org-compute-property-at-point ()
16514 "Compute the property at point.
16515 This looks for an enclosing column format, extracts the operator and
16516 then applies it to the property in the column format's scope."
16517 (interactive)
16518 (unless (org-at-property-p)
16519 (user-error "Not at a property"))
16520 (let ((prop (match-string-no-properties 2)))
16521 (org-columns-get-format-and-top-level)
16522 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16523 (user-error "No operator defined for property %s" prop))
16524 (org-columns-compute prop)))
16526 (defvar org-property-allowed-value-functions nil
16527 "Hook for functions supplying allowed values for a specific property.
16528 The functions must take a single argument, the name of the property, and
16529 return a flat list of allowed values. If \":ETC\" is one of
16530 the values, this means that these values are intended as defaults for
16531 completion, but that other values should be allowed too.
16532 The functions must return nil if they are not responsible for this
16533 property.")
16535 (defun org-property-get-allowed-values (pom property &optional table)
16536 "Get allowed values for the property PROPERTY.
16537 When TABLE is non-nil, return an alist that can directly be used for
16538 completion."
16539 (let (vals)
16540 (cond
16541 ((equal property "TODO")
16542 (setq vals (org-with-point-at pom
16543 (append org-todo-keywords-1 '("")))))
16544 ((equal property "PRIORITY")
16545 (let ((n org-lowest-priority))
16546 (while (>= n org-highest-priority)
16547 (push (char-to-string n) vals)
16548 (setq n (1- n)))))
16549 ((equal property "CATEGORY"))
16550 ((member property org-special-properties))
16551 ((setq vals (run-hook-with-args-until-success
16552 'org-property-allowed-value-functions property)))
16554 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16555 (when (and vals (string-match "\\S-" vals))
16556 (setq vals (car (read-from-string (concat "(" vals ")"))))
16557 (setq vals (mapcar (lambda (x)
16558 (cond ((stringp x) x)
16559 ((numberp x) (number-to-string x))
16560 ((symbolp x) (symbol-name x))
16561 (t "???")))
16562 vals)))))
16563 (when (member ":ETC" vals)
16564 (setq vals (remove ":ETC" vals))
16565 (org-add-props (car vals) '(org-unrestricted t)))
16566 (if table (mapcar 'list vals) vals)))
16568 (defun org-property-previous-allowed-value (&optional _previous)
16569 "Switch to the next allowed value for this property."
16570 (interactive)
16571 (org-property-next-allowed-value t))
16573 (defun org-property-next-allowed-value (&optional previous)
16574 "Switch to the next allowed value for this property."
16575 (interactive)
16576 (unless (org-at-property-p)
16577 (user-error "Not at a property"))
16578 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16579 (key (match-string 2))
16580 (value (match-string 3))
16581 (allowed (or (org-property-get-allowed-values (point) key)
16582 (and (member value '("[ ]" "[-]" "[X]"))
16583 '("[ ]" "[X]"))))
16584 (heading (save-match-data (nth 4 (org-heading-components))))
16585 nval)
16586 (unless allowed
16587 (user-error "Allowed values for this property have not been defined"))
16588 (when previous (setq allowed (reverse allowed)))
16589 (when (member value allowed)
16590 (setq nval (car (cdr (member value allowed)))))
16591 (setq nval (or nval (car allowed)))
16592 (when (equal nval value)
16593 (user-error "Only one allowed value for this property"))
16594 (org-at-property-p)
16595 (replace-match (concat " :" key ": " nval) t t)
16596 (org-indent-line)
16597 (beginning-of-line 1)
16598 (skip-chars-forward " \t")
16599 (when (equal prop org-effort-property)
16600 (org-refresh-property
16601 '((effort . identity)
16602 (effort-minutes . org-duration-string-to-minutes))
16603 nval)
16604 (when (string= org-clock-current-task heading)
16605 (setq org-clock-effort nval)
16606 (org-clock-update-mode-line)))
16607 (run-hook-with-args 'org-property-changed-functions key nval)))
16609 (defun org-find-olp (path &optional this-buffer)
16610 "Return a marker pointing to the entry at outline path OLP.
16611 If anything goes wrong, throw an error.
16612 You can wrap this call to catch the error like this:
16614 \(condition-case msg
16615 \(org-mobile-locate-entry (match-string 4))
16616 \(error (nth 1 msg)))
16618 The return value will then be either a string with the error message,
16619 or a marker if everything is OK.
16621 If THIS-BUFFER is set, the outline path does not contain a file,
16622 only headings."
16623 (let* ((file (if this-buffer buffer-file-name (pop path)))
16624 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16625 (level 1)
16626 (lmin 1)
16627 (lmax 1)
16628 end found flevel)
16629 (unless buffer (error "File not found :%s" file))
16630 (with-current-buffer buffer
16631 (org-with-wide-buffer
16632 (goto-char (point-min))
16633 (dolist (heading path)
16634 (let ((re (format org-complex-heading-regexp-format
16635 (regexp-quote heading)))
16636 (cnt 0))
16637 (while (re-search-forward re end t)
16638 (setq level (- (match-end 1) (match-beginning 1)))
16639 (when (and (>= level lmin) (<= level lmax))
16640 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16641 (when (= cnt 0)
16642 (error "Heading not found on level %d: %s" lmax heading))
16643 (when (> cnt 1)
16644 (error "Heading not unique on level %d: %s" lmax heading))
16645 (goto-char found)
16646 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16647 (setq end (save-excursion (org-end-of-subtree t t)))))
16648 (when (org-at-heading-p)
16649 (point-marker))))))
16651 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16652 "Find node HEADING in BUFFER.
16653 Return a marker to the heading if it was found, or nil if not.
16654 If POS-ONLY is set, return just the position instead of a marker.
16656 The heading text must match exact, but it may have a TODO keyword,
16657 a priority cookie and tags in the standard locations."
16658 (with-current-buffer (or buffer (current-buffer))
16659 (save-excursion
16660 (save-restriction
16661 (widen)
16662 (goto-char (point-min))
16663 (let (case-fold-search)
16664 (when (re-search-forward
16665 (format org-complex-heading-regexp-format
16666 (regexp-quote heading)) nil t)
16667 (if pos-only
16668 (match-beginning 0)
16669 (move-marker (make-marker) (match-beginning 0)))))))))
16671 (defun org-find-exact-heading-in-directory (heading &optional dir)
16672 "Find Org node headline HEADING in all .org files in directory DIR.
16673 When the target headline is found, return a marker to this location."
16674 (let ((files (directory-files (or dir default-directory)
16675 t "\\`[^.#].*\\.org\\'"))
16676 visiting m buffer)
16677 (catch 'found
16678 (dolist (file files)
16679 (message "trying %s" file)
16680 (setq visiting (org-find-base-buffer-visiting file))
16681 (setq buffer (or visiting (find-file-noselect file)))
16682 (setq m (org-find-exact-headline-in-buffer
16683 heading buffer))
16684 (when (and (not m) (not visiting)) (kill-buffer buffer))
16685 (and m (throw 'found m))))))
16687 (defun org-find-entry-with-id (ident)
16688 "Locate the entry that contains the ID property with exact value IDENT.
16689 IDENT can be a string, a symbol or a number, this function will search for
16690 the string representation of it.
16691 Return the position where this entry starts, or nil if there is no such entry."
16692 (interactive "sID: ")
16693 (let ((id (cond
16694 ((stringp ident) ident)
16695 ((symbolp ident) (symbol-name ident))
16696 ((numberp ident) (number-to-string ident))
16697 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16698 (org-with-wide-buffer (org-find-property "ID" id))))
16700 ;;;; Timestamps
16702 (defvar org-last-changed-timestamp nil)
16703 (defvar org-last-inserted-timestamp nil
16704 "The last time stamp inserted with `org-insert-time-stamp'.")
16705 (defvar org-ts-what) ; dynamically scoped parameter
16707 (defun org-time-stamp (arg &optional inactive)
16708 "Prompt for a date/time and insert a time stamp.
16710 If the user specifies a time like HH:MM or if this command is
16711 called with at least one prefix argument, the time stamp contains
16712 the date and the time. Otherwise, only the date is included.
16714 All parts of a date not specified by the user are filled in from
16715 the timestamp at point, if any, or the current date/time
16716 otherwise.
16718 If there is already a timestamp at the cursor, it is replaced.
16720 With two universal prefix arguments, insert an active timestamp
16721 with the current time without prompting the user.
16723 When called from lisp, the timestamp is inactive if INACTIVE is
16724 non-nil."
16725 (interactive "P")
16726 (let* ((ts (cond
16727 ((org-at-date-range-p t)
16728 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16729 ((org-at-timestamp-p t) (match-string 0))))
16730 ;; Default time is either the timestamp at point or today.
16731 ;; When entering a range, only the range start is considered.
16732 (default-time (if (not ts) (current-time)
16733 (apply #'encode-time (org-parse-time-string ts))))
16734 (default-input (and ts (org-get-compact-tod ts)))
16735 (repeater (and ts
16736 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16737 (match-string 0 ts)))
16738 org-time-was-given
16739 org-end-time-was-given
16740 (time
16741 (and (if (equal arg '(16)) (current-time)
16742 ;; Preserve `this-command' and `last-command'.
16743 (let ((this-command this-command)
16744 (last-command last-command))
16745 (org-read-date
16746 arg 'totime nil nil default-time default-input
16747 inactive))))))
16748 (cond
16749 ((and ts
16750 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16751 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16752 (insert "--")
16753 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16755 ;; Make sure we're on a timestamp. When in the middle of a date
16756 ;; range, move arbitrarily to range end.
16757 (unless (org-at-timestamp-p t)
16758 (skip-chars-forward "-")
16759 (org-at-timestamp-p t))
16760 (replace-match "")
16761 (setq org-last-changed-timestamp
16762 (org-insert-time-stamp
16763 time (or org-time-was-given arg)
16764 inactive nil nil (list org-end-time-was-given)))
16765 (when repeater
16766 (backward-char)
16767 (insert " " repeater)
16768 (setq org-last-changed-timestamp
16769 (concat (substring org-last-inserted-timestamp 0 -1)
16770 " " repeater ">")))
16771 (message "Timestamp updated"))
16772 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16773 (t (org-insert-time-stamp
16774 time (or org-time-was-given arg) inactive nil nil
16775 (list org-end-time-was-given))))))
16777 ;; FIXME: can we use this for something else, like computing time differences?
16778 (defun org-get-compact-tod (s)
16779 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16780 (let* ((t1 (match-string 1 s))
16781 (h1 (string-to-number (match-string 2 s)))
16782 (m1 (string-to-number (match-string 3 s)))
16783 (t2 (and (match-end 4) (match-string 5 s)))
16784 (h2 (and t2 (string-to-number (match-string 6 s))))
16785 (m2 (and t2 (string-to-number (match-string 7 s))))
16786 dh dm)
16787 (if (not t2)
16789 (setq dh (- h2 h1) dm (- m2 m1))
16790 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16791 (concat t1 "+" (number-to-string dh)
16792 (and (/= 0 dm) (format ":%02d" dm)))))))
16794 (defun org-time-stamp-inactive (&optional arg)
16795 "Insert an inactive time stamp.
16796 An inactive time stamp is enclosed in square brackets instead of angle
16797 brackets. It is inactive in the sense that it does not trigger agenda entries,
16798 does not link to the calendar and cannot be changed with the S-cursor keys.
16799 So these are more for recording a certain time/date."
16800 (interactive "P")
16801 (org-time-stamp arg 'inactive))
16803 (defvar org-date-ovl (make-overlay 1 1))
16804 (overlay-put org-date-ovl 'face 'org-date-selected)
16805 (delete-overlay org-date-ovl)
16807 (defvar org-ans1) ; dynamically scoped parameter
16808 (defvar org-ans2) ; dynamically scoped parameter
16810 (defvar org-plain-time-of-day-regexp) ; defined below
16812 (defvar org-overriding-default-time nil) ; dynamically scoped
16813 (defvar org-read-date-overlay nil)
16814 (defvar org-dcst nil) ; dynamically scoped
16815 (defvar org-read-date-history nil)
16816 (defvar org-read-date-final-answer nil)
16817 (defvar org-read-date-analyze-futurep nil)
16818 (defvar org-read-date-analyze-forced-year nil)
16819 (defvar org-read-date-inactive)
16821 (defvar org-read-date-minibuffer-local-map
16822 (let* ((map (make-sparse-keymap)))
16823 (set-keymap-parent map minibuffer-local-map)
16824 (org-defkey map (kbd ".")
16825 (lambda () (interactive)
16826 ;; Are we at the beginning of the prompt?
16827 (if (looking-back "^[^:]+: "
16828 (let ((inhibit-field-text-motion t))
16829 (line-beginning-position)))
16830 (org-eval-in-calendar '(calendar-goto-today))
16831 (insert "."))))
16832 (org-defkey map (kbd "C-.")
16833 (lambda () (interactive)
16834 (org-eval-in-calendar '(calendar-goto-today))))
16835 (org-defkey map [(meta shift left)]
16836 (lambda () (interactive)
16837 (org-eval-in-calendar '(calendar-backward-month 1))))
16838 (org-defkey map [(meta shift right)]
16839 (lambda () (interactive)
16840 (org-eval-in-calendar '(calendar-forward-month 1))))
16841 (org-defkey map [(meta shift up)]
16842 (lambda () (interactive)
16843 (org-eval-in-calendar '(calendar-backward-year 1))))
16844 (org-defkey map [(meta shift down)]
16845 (lambda () (interactive)
16846 (org-eval-in-calendar '(calendar-forward-year 1))))
16847 (org-defkey map [?\e (shift left)]
16848 (lambda () (interactive)
16849 (org-eval-in-calendar '(calendar-backward-month 1))))
16850 (org-defkey map [?\e (shift right)]
16851 (lambda () (interactive)
16852 (org-eval-in-calendar '(calendar-forward-month 1))))
16853 (org-defkey map [?\e (shift up)]
16854 (lambda () (interactive)
16855 (org-eval-in-calendar '(calendar-backward-year 1))))
16856 (org-defkey map [?\e (shift down)]
16857 (lambda () (interactive)
16858 (org-eval-in-calendar '(calendar-forward-year 1))))
16859 (org-defkey map [(shift up)]
16860 (lambda () (interactive)
16861 (org-eval-in-calendar '(calendar-backward-week 1))))
16862 (org-defkey map [(shift down)]
16863 (lambda () (interactive)
16864 (org-eval-in-calendar '(calendar-forward-week 1))))
16865 (org-defkey map [(shift left)]
16866 (lambda () (interactive)
16867 (org-eval-in-calendar '(calendar-backward-day 1))))
16868 (org-defkey map [(shift right)]
16869 (lambda () (interactive)
16870 (org-eval-in-calendar '(calendar-forward-day 1))))
16871 (org-defkey map "!"
16872 (lambda () (interactive)
16873 (org-eval-in-calendar '(diary-view-entries))
16874 (message "")))
16875 (org-defkey map ">"
16876 (lambda () (interactive)
16877 (org-eval-in-calendar '(calendar-scroll-left 1))))
16878 (org-defkey map "<"
16879 (lambda () (interactive)
16880 (org-eval-in-calendar '(calendar-scroll-right 1))))
16881 (org-defkey map "\C-v"
16882 (lambda () (interactive)
16883 (org-eval-in-calendar
16884 '(calendar-scroll-left-three-months 1))))
16885 (org-defkey map "\M-v"
16886 (lambda () (interactive)
16887 (org-eval-in-calendar
16888 '(calendar-scroll-right-three-months 1))))
16889 map)
16890 "Keymap for minibuffer commands when using `org-read-date'.")
16892 (defvar org-def)
16893 (defvar org-defdecode)
16894 (defvar org-with-time)
16896 (defvar calendar-setup) ; Dynamically scoped.
16897 (defun org-read-date (&optional with-time to-time from-string prompt
16898 default-time default-input inactive)
16899 "Read a date, possibly a time, and make things smooth for the user.
16900 The prompt will suggest to enter an ISO date, but you can also enter anything
16901 which will at least partially be understood by `parse-time-string'.
16902 Unrecognized parts of the date will default to the current day, month, year,
16903 hour and minute. If this command is called to replace a timestamp at point,
16904 or to enter the second timestamp of a range, the default time is taken
16905 from the existing stamp. Furthermore, the command prefers the future,
16906 so if you are giving a date where the year is not given, and the day-month
16907 combination is already past in the current year, it will assume you
16908 mean next year. For details, see the manual. A few examples:
16910 3-2-5 --> 2003-02-05
16911 feb 15 --> currentyear-02-15
16912 2/15 --> currentyear-02-15
16913 sep 12 9 --> 2009-09-12
16914 12:45 --> today 12:45
16915 22 sept 0:34 --> currentyear-09-22 0:34
16916 12 --> currentyear-currentmonth-12
16917 Fri --> nearest Friday after today
16918 -Tue --> last Tuesday
16919 etc.
16921 Furthermore you can specify a relative date by giving, as the *first* thing
16922 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16923 change in days weeks, months, years.
16924 With a single plus or minus, the date is relative to today. With a double
16925 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16926 +4d --> four days from today
16927 +4 --> same as above
16928 +2w --> two weeks from today
16929 ++5 --> five days from default date
16931 The function understands only English month and weekday abbreviations.
16933 While prompting, a calendar is popped up - you can also select the
16934 date with the mouse (button 1). The calendar shows a period of three
16935 months. To scroll it to other months, use the keys `>' and `<'.
16936 If you don't like the calendar, turn it off with
16937 (setq org-read-date-popup-calendar nil)
16939 With optional argument TO-TIME, the date will immediately be converted
16940 to an internal time.
16941 With an optional argument WITH-TIME, the prompt will suggest to
16942 also insert a time. Note that when WITH-TIME is not set, you can
16943 still enter a time, and this function will inform the calling routine
16944 about this change. The calling routine may then choose to change the
16945 format used to insert the time stamp into the buffer to include the time.
16946 With optional argument FROM-STRING, read from this string instead from
16947 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16948 the time/date that is used for everything that is not specified by the
16949 user."
16950 (require 'parse-time)
16951 (let* ((org-with-time with-time)
16952 (org-time-stamp-rounding-minutes
16953 (if (equal org-with-time '(16))
16954 '(0 0)
16955 org-time-stamp-rounding-minutes))
16956 (org-dcst org-display-custom-times)
16957 (ct (org-current-time))
16958 (org-def (or org-overriding-default-time default-time ct))
16959 (org-defdecode (decode-time org-def))
16960 (cur-frame (selected-frame))
16961 (mouse-autoselect-window nil) ; Don't let the mouse jump
16962 (calendar-setup
16963 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16964 (calendar-move-hook nil)
16965 (calendar-view-diary-initially-flag nil)
16966 (calendar-view-holidays-initially-flag nil)
16967 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16968 ;; Rationalize `org-def' and `org-defdecode', if required.
16969 (when (< (nth 2 org-defdecode) org-extend-today-until)
16970 (setf (nth 2 org-defdecode) -1)
16971 (setf (nth 1 org-defdecode) 59)
16972 (setq org-def (apply #'encode-time org-defdecode))
16973 (setq org-defdecode (decode-time org-def)))
16974 (let* ((timestr (format-time-string
16975 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16976 org-def))
16977 (prompt (concat (if prompt (concat prompt " ") "")
16978 (format "Date+time [%s]: " timestr))))
16979 (cond
16980 (from-string (setq ans from-string))
16981 (org-read-date-popup-calendar
16982 (save-excursion
16983 (save-window-excursion
16984 (calendar)
16985 (when (eq calendar-setup 'calendar-only)
16986 (setq cal-frame
16987 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16988 (select-frame cal-frame))
16989 (org-eval-in-calendar '(setq cursor-type nil) t)
16990 (unwind-protect
16991 (progn
16992 (calendar-forward-day (- (time-to-days org-def)
16993 (calendar-absolute-from-gregorian
16994 (calendar-current-date))))
16995 (org-eval-in-calendar nil t)
16996 (let* ((old-map (current-local-map))
16997 (map (copy-keymap calendar-mode-map))
16998 (minibuffer-local-map
16999 (copy-keymap org-read-date-minibuffer-local-map)))
17000 (org-defkey map (kbd "RET") 'org-calendar-select)
17001 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
17002 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
17003 (unwind-protect
17004 (progn
17005 (use-local-map map)
17006 (setq org-read-date-inactive inactive)
17007 (add-hook 'post-command-hook 'org-read-date-display)
17008 (setq org-ans0
17009 (read-string prompt
17010 default-input
17011 'org-read-date-history
17012 nil))
17013 ;; org-ans0: from prompt
17014 ;; org-ans1: from mouse click
17015 ;; org-ans2: from calendar motion
17016 (setq ans
17017 (concat org-ans0 " " (or org-ans1 org-ans2))))
17018 (remove-hook 'post-command-hook 'org-read-date-display)
17019 (use-local-map old-map)
17020 (when org-read-date-overlay
17021 (delete-overlay org-read-date-overlay)
17022 (setq org-read-date-overlay nil)))))
17023 (bury-buffer "*Calendar*")
17024 (when cal-frame
17025 (delete-frame cal-frame)
17026 (select-frame-set-input-focus cur-frame))))))
17028 (t ; Naked prompt only
17029 (unwind-protect
17030 (setq ans (read-string prompt default-input
17031 'org-read-date-history timestr))
17032 (when org-read-date-overlay
17033 (delete-overlay org-read-date-overlay)
17034 (setq org-read-date-overlay nil))))))
17036 (setq final (org-read-date-analyze ans org-def org-defdecode))
17038 (when org-read-date-analyze-forced-year
17039 (message "Year was forced into %s"
17040 (if org-read-date-force-compatible-dates
17041 "compatible range (1970-2037)"
17042 "range representable on this machine"))
17043 (ding))
17045 ;; One round trip to get rid of 34th of August and stuff like that....
17046 (setq final (decode-time (apply 'encode-time final)))
17048 (setq org-read-date-final-answer ans)
17050 (if to-time
17051 (apply 'encode-time final)
17052 (if (and (boundp 'org-time-was-given) org-time-was-given)
17053 (format "%04d-%02d-%02d %02d:%02d"
17054 (nth 5 final) (nth 4 final) (nth 3 final)
17055 (nth 2 final) (nth 1 final))
17056 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
17058 (defun org-read-date-display ()
17059 "Display the current date prompt interpretation in the minibuffer."
17060 (when org-read-date-display-live
17061 (when org-read-date-overlay
17062 (delete-overlay org-read-date-overlay))
17063 (when (minibufferp (current-buffer))
17064 (save-excursion
17065 (end-of-line 1)
17066 (while (not (equal (buffer-substring
17067 (max (point-min) (- (point) 4)) (point))
17068 " "))
17069 (insert " ")))
17070 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
17071 " " (or org-ans1 org-ans2)))
17072 (org-end-time-was-given nil)
17073 (f (org-read-date-analyze ans org-def org-defdecode))
17074 (fmts (if org-dcst
17075 org-time-stamp-custom-formats
17076 org-time-stamp-formats))
17077 (fmt (if (or org-with-time
17078 (and (boundp 'org-time-was-given) org-time-was-given))
17079 (cdr fmts)
17080 (car fmts)))
17081 (txt (format-time-string fmt (apply 'encode-time f)))
17082 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17083 (txt (concat "=> " txt)))
17084 (when (and org-end-time-was-given
17085 (string-match org-plain-time-of-day-regexp txt))
17086 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17087 org-end-time-was-given
17088 (substring txt (match-end 0)))))
17089 (when org-read-date-analyze-futurep
17090 (setq txt (concat txt " (=>F)")))
17091 (setq org-read-date-overlay
17092 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17093 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17095 (defun org-read-date-analyze (ans def defdecode)
17096 "Analyze the combined answer of the date prompt."
17097 ;; FIXME: cleanup and comment
17098 ;; Pass `current-time' result to `decode-time' (instead of calling
17099 ;; without arguments) so that only `current-time' has to be
17100 ;; overriden in tests.
17101 (let ((org-def def)
17102 (org-defdecode defdecode)
17103 (nowdecode (decode-time (current-time)))
17104 delta deltan deltaw deltadef year month day
17105 hour minute second wday pm h2 m2 tl wday1
17106 iso-year iso-weekday iso-week iso-date futurep kill-year)
17107 (setq org-read-date-analyze-futurep nil
17108 org-read-date-analyze-forced-year nil)
17109 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17110 (setq ans "+0"))
17112 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17113 (setq ans (replace-match "" t t ans)
17114 deltan (car delta)
17115 deltaw (nth 1 delta)
17116 deltadef (nth 2 delta)))
17118 ;; Check if there is an iso week date in there. If yes, store the
17119 ;; info and postpone interpreting it until the rest of the parsing
17120 ;; is done.
17121 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17122 (setq iso-year (when (match-end 1)
17123 (org-small-year-to-year
17124 (string-to-number (match-string 1 ans))))
17125 iso-weekday (when (match-end 3)
17126 (string-to-number (match-string 3 ans)))
17127 iso-week (string-to-number (match-string 2 ans)))
17128 (setq ans (replace-match "" t t ans)))
17130 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17131 (when (string-match
17132 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17133 (setq year (if (match-end 2)
17134 (string-to-number (match-string 2 ans))
17135 (progn (setq kill-year t)
17136 (string-to-number (format-time-string "%Y"))))
17137 month (string-to-number (match-string 3 ans))
17138 day (string-to-number (match-string 4 ans)))
17139 (setq year (org-small-year-to-year year))
17140 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17141 t nil ans)))
17143 ;; Help matching dotted european dates
17144 (when (string-match
17145 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17146 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17147 (setq kill-year t)
17148 (string-to-number (format-time-string "%Y")))
17149 day (string-to-number (match-string 1 ans))
17150 month (string-to-number (match-string 2 ans))
17151 ans (replace-match (format "%04d-%02d-%02d" year month day)
17152 t nil ans)))
17154 ;; Help matching american dates, like 5/30 or 5/30/7
17155 (when (string-match
17156 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17157 (setq year (if (match-end 4)
17158 (string-to-number (match-string 4 ans))
17159 (progn (setq kill-year t)
17160 (string-to-number (format-time-string "%Y"))))
17161 month (string-to-number (match-string 1 ans))
17162 day (string-to-number (match-string 2 ans)))
17163 (setq year (org-small-year-to-year year))
17164 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17165 t nil ans)))
17166 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17167 ;; If there is a time with am/pm, and *no* time without it, we convert
17168 ;; so that matching will be successful.
17169 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17170 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17171 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17172 (setq hour (string-to-number (match-string 1 ans))
17173 minute (if (match-end 3)
17174 (string-to-number (match-string 3 ans))
17176 pm (equal ?p
17177 (string-to-char (downcase (match-string 4 ans)))))
17178 (if (and (= hour 12) (not pm))
17179 (setq hour 0)
17180 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17181 (setq ans (replace-match (format "%02d:%02d" hour minute)
17182 t t ans))))
17184 ;; Check if a time range is given as a duration
17185 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17186 (setq hour (string-to-number (match-string 1 ans))
17187 h2 (+ hour (string-to-number (match-string 3 ans)))
17188 minute (string-to-number (match-string 2 ans))
17189 m2 (+ minute (if (match-end 5) (string-to-number
17190 (match-string 5 ans))0)))
17191 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17192 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17193 t t ans)))
17195 ;; Check if there is a time range
17196 (when (boundp 'org-end-time-was-given)
17197 (setq org-time-was-given nil)
17198 (when (and (string-match org-plain-time-of-day-regexp ans)
17199 (match-end 8))
17200 (setq org-end-time-was-given (match-string 8 ans))
17201 (setq ans (concat (substring ans 0 (match-beginning 7))
17202 (substring ans (match-end 7))))))
17204 (setq tl (parse-time-string ans)
17205 day (or (nth 3 tl) (nth 3 org-defdecode))
17206 month
17207 (cond ((nth 4 tl))
17208 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17209 ;; Day was specified. Make sure DAY+MONTH
17210 ;; combination happens in the future.
17211 ((nth 3 tl)
17212 (setq futurep t)
17213 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17214 (nth 4 nowdecode)))
17215 (t (nth 4 org-defdecode)))
17216 year
17217 (cond ((and (not kill-year) (nth 5 tl)))
17218 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17219 ;; Month was guessed in the future and is at least
17220 ;; equal to NOWDECODE's. Fix year accordingly.
17221 (futurep
17222 (if (or (> month (nth 4 nowdecode))
17223 (>= day (nth 3 nowdecode)))
17224 (nth 5 nowdecode)
17225 (1+ (nth 5 nowdecode))))
17226 ;; Month was specified. Make sure MONTH+YEAR
17227 ;; combination happens in the future.
17228 ((nth 4 tl)
17229 (setq futurep t)
17230 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17231 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17232 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17233 (t (nth 5 nowdecode))))
17234 (t (nth 5 org-defdecode)))
17235 hour (or (nth 2 tl) (nth 2 org-defdecode))
17236 minute (or (nth 1 tl) (nth 1 org-defdecode))
17237 second (or (nth 0 tl) 0)
17238 wday (nth 6 tl))
17240 (when (and (eq org-read-date-prefer-future 'time)
17241 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17242 (equal day (nth 3 nowdecode))
17243 (equal month (nth 4 nowdecode))
17244 (equal year (nth 5 nowdecode))
17245 (nth 2 tl)
17246 (or (< (nth 2 tl) (nth 2 nowdecode))
17247 (and (= (nth 2 tl) (nth 2 nowdecode))
17248 (nth 1 tl)
17249 (< (nth 1 tl) (nth 1 nowdecode)))))
17250 (setq day (1+ day)
17251 futurep t))
17253 ;; Special date definitions below
17254 (cond
17255 (iso-week
17256 ;; There was an iso week
17257 (require 'cal-iso)
17258 (setq futurep nil)
17259 (setq year (or iso-year year)
17260 day (or iso-weekday wday 1)
17261 wday nil ; to make sure that the trigger below does not match
17262 iso-date (calendar-gregorian-from-absolute
17263 (calendar-iso-to-absolute
17264 (list iso-week day year))))
17265 ; FIXME: Should we also push ISO weeks into the future?
17266 ; (when (and org-read-date-prefer-future
17267 ; (not iso-year)
17268 ; (< (calendar-absolute-from-gregorian iso-date)
17269 ; (time-to-days (current-time))))
17270 ; (setq year (1+ year)
17271 ; iso-date (calendar-gregorian-from-absolute
17272 ; (calendar-iso-to-absolute
17273 ; (list iso-week day year)))))
17274 (setq month (car iso-date)
17275 year (nth 2 iso-date)
17276 day (nth 1 iso-date)))
17277 (deltan
17278 (setq futurep nil)
17279 (unless deltadef
17280 ;; Pass `current-time' result to `decode-time' (instead of
17281 ;; calling without arguments) so that only `current-time' has
17282 ;; to be overriden in tests.
17283 (let ((now (decode-time (current-time))))
17284 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17285 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17286 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17287 ((equal deltaw "m") (setq month (+ month deltan)))
17288 ((equal deltaw "y") (setq year (+ year deltan)))))
17289 ((and wday (not (nth 3 tl)))
17290 ;; Weekday was given, but no day, so pick that day in the week
17291 ;; on or after the derived date.
17292 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17293 (unless (equal wday wday1)
17294 (setq day (+ day (% (- wday wday1 -7) 7))))))
17295 (when (and (boundp 'org-time-was-given)
17296 (nth 2 tl))
17297 (setq org-time-was-given t))
17298 (when (< year 100) (setq year (+ 2000 year)))
17299 ;; Check of the date is representable
17300 (if org-read-date-force-compatible-dates
17301 (progn
17302 (when (< year 1970)
17303 (setq year 1970 org-read-date-analyze-forced-year t))
17304 (when (> year 2037)
17305 (setq year 2037 org-read-date-analyze-forced-year t)))
17306 (condition-case nil
17307 (ignore (encode-time second minute hour day month year))
17308 (error
17309 (setq year (nth 5 org-defdecode))
17310 (setq org-read-date-analyze-forced-year t))))
17311 (setq org-read-date-analyze-futurep futurep)
17312 (list second minute hour day month year)))
17314 (defvar parse-time-weekdays)
17315 (defun org-read-date-get-relative (s today default)
17316 "Check string S for special relative date string.
17317 TODAY and DEFAULT are internal times, for today and for a default.
17318 Return shift list (N what def-flag)
17319 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17320 N is the number of WHATs to shift.
17321 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17322 the DEFAULT date rather than TODAY."
17323 (require 'parse-time)
17324 (when (and
17325 (string-match
17326 (concat
17327 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17328 "\\([0-9]+\\)?"
17329 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17330 "\\([ \t]\\|$\\)") s)
17331 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17332 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17333 (string-to-char (substring (match-string 1 s) -1))
17334 ?+))
17335 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17336 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17337 (what (if (match-end 3) (match-string 3 s) "d"))
17338 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17339 (date (if rel default today))
17340 (wday (nth 6 (decode-time date)))
17341 delta)
17342 (if wday1
17343 (progn
17344 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17345 (when (= delta 0) (setq delta 7))
17346 (when (= dir ?-)
17347 (setq delta (- delta 7))
17348 (when (= delta 0) (setq delta -7)))
17349 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17350 (list delta "d" rel))
17351 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17353 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17354 "Turn a user-specified date into the internal representation.
17355 The internal representation needed by the calendar is (month day year).
17356 This is a wrapper to handle the brain-dead convention in calendar that
17357 user function argument order change dependent on argument order."
17358 (if (boundp 'calendar-date-style)
17359 (cond
17360 ((eq calendar-date-style 'american)
17361 (list arg1 arg2 arg3))
17362 ((eq calendar-date-style 'european)
17363 (list arg2 arg1 arg3))
17364 ((eq calendar-date-style 'iso)
17365 (list arg2 arg3 arg1)))
17366 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17367 (if (org-bound-and-true-p european-calendar-style)
17368 (list arg2 arg1 arg3)
17369 (list arg1 arg2 arg3)))))
17371 (defun org-eval-in-calendar (form &optional keepdate)
17372 "Eval FORM in the calendar window and return to current window.
17373 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17374 (let ((sf (selected-frame))
17375 (sw (selected-window)))
17376 (select-window (get-buffer-window "*Calendar*" t))
17377 (eval form)
17378 (when (and (not keepdate) (calendar-cursor-to-date))
17379 (let* ((date (calendar-cursor-to-date))
17380 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17381 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17382 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17383 (select-window sw)
17384 (select-frame-set-input-focus sf)))
17386 (defun org-calendar-select ()
17387 "Return to `org-read-date' with the date currently selected.
17388 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17389 (interactive)
17390 (when (calendar-cursor-to-date)
17391 (let* ((date (calendar-cursor-to-date))
17392 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17393 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17394 (when (active-minibuffer-window) (exit-minibuffer))))
17396 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17397 "Insert a date stamp for the date given by the internal TIME.
17398 See `format-time-string' for the format of TIME.
17399 WITH-HM means use the stamp format that includes the time of the day.
17400 INACTIVE means use square brackets instead of angular ones, so that the
17401 stamp will not contribute to the agenda.
17402 PRE and POST are optional strings to be inserted before and after the
17403 stamp.
17404 The command returns the inserted time stamp."
17405 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17406 stamp)
17407 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17408 (insert-before-markers (or pre ""))
17409 (when (listp extra)
17410 (setq extra (car extra))
17411 (if (and (stringp extra)
17412 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17413 (setq extra (format "-%02d:%02d"
17414 (string-to-number (match-string 1 extra))
17415 (string-to-number (match-string 2 extra))))
17416 (setq extra nil)))
17417 (when extra
17418 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17419 (insert-before-markers (setq stamp (format-time-string fmt time)))
17420 (insert-before-markers (or post ""))
17421 (setq org-last-inserted-timestamp stamp)))
17423 (defun org-toggle-time-stamp-overlays ()
17424 "Toggle the use of custom time stamp formats."
17425 (interactive)
17426 (setq org-display-custom-times (not org-display-custom-times))
17427 (unless org-display-custom-times
17428 (let ((p (point-min)) (bmp (buffer-modified-p)))
17429 (while (setq p (next-single-property-change p 'display))
17430 (when (and (get-text-property p 'display)
17431 (eq (get-text-property p 'face) 'org-date))
17432 (remove-text-properties
17433 p (setq p (next-single-property-change p 'display))
17434 '(display t))))
17435 (set-buffer-modified-p bmp)))
17436 (org-restart-font-lock)
17437 (setq org-table-may-need-update t)
17438 (if org-display-custom-times
17439 (message "Time stamps are overlaid with custom format")
17440 (message "Time stamp overlays removed")))
17442 (defun org-display-custom-time (beg end)
17443 "Overlay modified time stamp format over timestamp between BEG and END."
17444 (let* ((ts (buffer-substring beg end))
17445 t1 w1 with-hm tf time str w2 (off 0))
17446 (save-match-data
17447 (setq t1 (org-parse-time-string ts t))
17448 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17449 (setq off (- (match-end 0) (match-beginning 0)))))
17450 (setq end (- end off))
17451 (setq w1 (- end beg)
17452 with-hm (and (nth 1 t1) (nth 2 t1))
17453 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17454 time (org-fix-decoded-time t1)
17455 str (org-add-props
17456 (format-time-string
17457 (substring tf 1 -1) (apply 'encode-time time))
17458 nil 'mouse-face 'highlight)
17459 w2 (length str))
17460 (unless (= w2 w1)
17461 (add-text-properties (1+ beg) (+ 2 beg)
17462 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17463 (put-text-property beg end 'display str)))
17465 (defun org-fix-decoded-time (time)
17466 "Set 0 instead of nil for the first 6 elements of time.
17467 Don't touch the rest."
17468 (let ((n 0))
17469 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17471 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17473 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17474 "Difference between TIMESTAMP-STRING and now in days.
17475 If SECONDS is non-nil, return the difference in seconds."
17476 (let ((fdiff (if seconds #'float-time #'time-to-days)))
17477 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17478 (funcall fdiff (current-time)))))
17480 (defun org-deadline-close (timestamp-string &optional ndays)
17481 "Is the time in TIMESTAMP-STRING close to the current date?"
17482 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17483 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17484 (not (org-entry-is-done-p))))
17486 (defun org-get-wdays (ts &optional delay zero-delay)
17487 "Get the deadline lead time appropriate for timestring TS.
17488 When DELAY is non-nil, get the delay time for scheduled items
17489 instead of the deadline lead time. When ZERO-DELAY is non-nil
17490 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17491 don't try to find the delay cookie in the scheduled timestamp."
17492 (let ((tv (if delay org-scheduled-delay-days
17493 org-deadline-warning-days)))
17494 (cond
17495 ((or (and delay (< tv 0))
17496 (and delay zero-delay (<= tv 0))
17497 (and (not delay) (<= tv 0)))
17498 ;; Enforce this value no matter what
17499 (- tv))
17500 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17501 ;; lead time is specified.
17502 (floor (* (string-to-number (match-string 1 ts))
17503 (cdr (assoc (match-string 2 ts)
17504 '(("d" . 1) ("w" . 7)
17505 ("m" . 30.4) ("y" . 365.25)
17506 ("h" . 0.041667)))))))
17507 ;; go for the default.
17508 (t tv))))
17510 (defun org-calendar-select-mouse (ev)
17511 "Return to `org-read-date' with the date currently selected.
17512 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17513 (interactive "e")
17514 (mouse-set-point ev)
17515 (when (calendar-cursor-to-date)
17516 (let* ((date (calendar-cursor-to-date))
17517 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17518 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17519 (when (active-minibuffer-window) (exit-minibuffer))))
17521 (defun org-check-deadlines (ndays)
17522 "Check if there are any deadlines due or past due.
17523 A deadline is considered due if it happens within `org-deadline-warning-days'
17524 days from today's date. If the deadline appears in an entry marked DONE,
17525 it is not shown. The prefix arg NDAYS can be used to test that many
17526 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17527 (interactive "P")
17528 (let* ((org-warn-days
17529 (cond
17530 ((equal ndays '(4)) 100000)
17531 (ndays (prefix-numeric-value ndays))
17532 (t (abs org-deadline-warning-days))))
17533 (case-fold-search nil)
17534 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17535 (callback
17536 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17537 (message "%d deadlines past-due or due within %d days"
17538 (org-occur regexp nil callback)
17539 org-warn-days)))
17541 (defsubst org-re-timestamp (type)
17542 "Return a regexp for timestamp TYPE.
17543 Allowed values for TYPE are:
17545 all: all timestamps
17546 active: only active timestamps (<...>)
17547 inactive: only inactive timestamps ([...])
17548 scheduled: only scheduled timestamps
17549 deadline: only deadline timestamps
17550 closed: only closed time-stamps
17552 When TYPE is nil, fall back on returning a regexp that matches
17553 both scheduled and deadline timestamps."
17554 (cl-case type
17555 (all org-ts-regexp-both)
17556 (active org-ts-regexp)
17557 (inactive org-ts-regexp-inactive)
17558 (scheduled org-scheduled-time-regexp)
17559 (deadline org-deadline-time-regexp)
17560 (closed org-closed-time-regexp)
17561 (otherwise
17562 (concat "\\<"
17563 (regexp-opt (list org-deadline-string org-scheduled-string))
17564 " *<\\([^>]+\\)>"))))
17566 (defun org-check-before-date (d)
17567 "Check if there are deadlines or scheduled entries before date D."
17568 (interactive (list (org-read-date)))
17569 (let* ((case-fold-search nil)
17570 (regexp (org-re-timestamp org-ts-type))
17571 (ts-type org-ts-type)
17572 (callback
17573 (lambda ()
17574 (let ((match (match-string 1)))
17575 (and (if (memq ts-type '(active inactive all))
17576 (eq (org-element-type (save-excursion
17577 (backward-char)
17578 (org-element-context)))
17579 'timestamp)
17580 (org-at-planning-p))
17581 (time-less-p
17582 (org-time-string-to-time match)
17583 (org-time-string-to-time d)))))))
17584 (message "%d entries before %s"
17585 (org-occur regexp nil callback)
17586 d)))
17588 (defun org-check-after-date (d)
17589 "Check if there are deadlines or scheduled entries after date D."
17590 (interactive (list (org-read-date)))
17591 (let* ((case-fold-search nil)
17592 (regexp (org-re-timestamp org-ts-type))
17593 (ts-type org-ts-type)
17594 (callback
17595 (lambda ()
17596 (let ((match (match-string 1)))
17597 (and (if (memq ts-type '(active inactive all))
17598 (eq (org-element-type (save-excursion
17599 (backward-char)
17600 (org-element-context)))
17601 'timestamp)
17602 (org-at-planning-p))
17603 (not (time-less-p
17604 (org-time-string-to-time match)
17605 (org-time-string-to-time d))))))))
17606 (message "%d entries after %s"
17607 (org-occur regexp nil callback)
17608 d)))
17610 (defun org-check-dates-range (start-date end-date)
17611 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17612 (interactive (list (org-read-date nil nil nil "Range starts")
17613 (org-read-date nil nil nil "Range end")))
17614 (let ((case-fold-search nil)
17615 (regexp (org-re-timestamp org-ts-type))
17616 (callback
17617 (let ((type org-ts-type))
17618 (lambda ()
17619 (let ((match (match-string 1)))
17620 (and
17621 (if (memq type '(active inactive all))
17622 (eq (org-element-type (save-excursion
17623 (backward-char)
17624 (org-element-context)))
17625 'timestamp)
17626 (org-at-planning-p))
17627 (not (time-less-p
17628 (org-time-string-to-time match)
17629 (org-time-string-to-time start-date)))
17630 (time-less-p
17631 (org-time-string-to-time match)
17632 (org-time-string-to-time end-date))))))))
17633 (message "%d entries between %s and %s"
17634 (org-occur regexp nil callback) start-date end-date)))
17636 (defun org-evaluate-time-range (&optional to-buffer)
17637 "Evaluate a time range by computing the difference between start and end.
17638 Normally the result is just printed in the echo area, but with prefix arg
17639 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17640 If the time range is actually in a table, the result is inserted into the
17641 next column.
17642 For time difference computation, a year is assumed to be exactly 365
17643 days in order to avoid rounding problems."
17644 (interactive "P")
17646 (org-clock-update-time-maybe)
17647 (save-excursion
17648 (unless (org-at-date-range-p t)
17649 (goto-char (point-at-bol))
17650 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17651 (unless (org-at-date-range-p t)
17652 (user-error "Not at a time-stamp range, and none found in current line")))
17653 (let* ((ts1 (match-string 1))
17654 (ts2 (match-string 2))
17655 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17656 (match-end (match-end 0))
17657 (time1 (org-time-string-to-time ts1))
17658 (time2 (org-time-string-to-time ts2))
17659 (t1 (float-time time1))
17660 (t2 (float-time time2))
17661 (diff (abs (- t2 t1)))
17662 (negative (< (- t2 t1) 0))
17663 ;; (ys (floor (* 365 24 60 60)))
17664 (ds (* 24 60 60))
17665 (hs (* 60 60))
17666 (fy "%dy %dd %02d:%02d")
17667 (fy1 "%dy %dd")
17668 (fd "%dd %02d:%02d")
17669 (fd1 "%dd")
17670 (fh "%02d:%02d")
17671 y d h m align)
17672 (if havetime
17673 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17675 d (floor (/ diff ds)) diff (mod diff ds)
17676 h (floor (/ diff hs)) diff (mod diff hs)
17677 m (floor (/ diff 60)))
17678 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17680 d (floor (+ (/ diff ds) 0.5))
17681 h 0 m 0))
17682 (if (not to-buffer)
17683 (message "%s" (org-make-tdiff-string y d h m))
17684 (if (org-at-table-p)
17685 (progn
17686 (goto-char match-end)
17687 (setq align t)
17688 (and (looking-at " *|") (goto-char (match-end 0))))
17689 (goto-char match-end))
17690 (when (looking-at
17691 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17692 (replace-match ""))
17693 (when negative (insert " -"))
17694 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17695 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17696 (insert " " (format fh h m))))
17697 (when align (org-table-align))
17698 (message "Time difference inserted")))))
17700 (defun org-make-tdiff-string (y d h m)
17701 (let ((fmt "")
17702 (l nil))
17703 (when (> y 0)
17704 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17705 (push y l))
17706 (when (> d 0)
17707 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17708 (push d l))
17709 (when (> h 0)
17710 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17711 (push h l))
17712 (when (> m 0)
17713 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17714 (push m l))
17715 (apply 'format fmt (nreverse l))))
17717 (defun org-time-string-to-time (s &optional buffer pos)
17718 "Convert a timestamp string into internal time."
17719 (condition-case errdata
17720 (apply 'encode-time (org-parse-time-string s))
17721 (error (error "Bad timestamp `%s'%s\nError was: %s"
17722 s (if (not (and buffer pos))
17724 (format-message " at %d in buffer `%s'" pos buffer))
17725 (cdr errdata)))))
17727 (defun org-time-string-to-seconds (s)
17728 "Convert a timestamp string to a number of seconds."
17729 (float-time (org-time-string-to-time s)))
17731 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17733 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17734 "Convert time stamp S to an absolute day number.
17736 If DAYNR in non-nil, and there is a specifier for a cyclic time
17737 stamp, get the closest date to DAYNR. If PREFER is
17738 `past' (respectively `future') return a date past (respectively
17739 after) or equal to DAYNR.
17741 POS is the location of time stamp S, as a buffer position in
17742 BUFFER.
17744 Diary sexp timestamps are matched against DAYNR, when non-nil.
17745 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17746 signalled."
17747 (cond
17748 ((string-match "\\`%%\\((.*)\\)" s)
17749 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17750 ;; only able to match individual dates. If it fails, raise an
17751 ;; error.
17752 (if (and daynr
17753 (org-diary-sexp-entry
17754 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17755 daynr
17756 (signal 'org-diary-sexp-no-match (list s))))
17757 ((and daynr show-all) (org-closest-date s daynr prefer))
17758 (t (time-to-days
17759 (condition-case errdata
17760 (apply #'encode-time (org-parse-time-string s))
17761 (error (error "Bad timestamp `%s'%s\nError was: %s"
17763 (if (not (and buffer pos)) ""
17764 (format-message " at %d in buffer `%s'" pos buffer))
17765 (cdr errdata))))))))
17767 (defun org-days-to-iso-week (days)
17768 "Return the iso week number."
17769 (require 'cal-iso)
17770 (car (calendar-iso-from-absolute days)))
17772 (defun org-small-year-to-year (year)
17773 "Convert 2-digit years into 4-digit years.
17774 YEAR is expanded into one of the 30 next years, if possible, or
17775 into a past one. Any year larger than 99 is returned unchanged."
17776 (if (>= year 100) year
17777 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17778 (century (/ current 100))
17779 (offset (- year (% current 100))))
17780 (cond ((> offset 30) (+ (* (1- century) 100) year))
17781 ((> offset -70) (+ (* century 100) year))
17782 (t (+ (* (1+ century) 100) year))))))
17784 (defun org-time-from-absolute (d)
17785 "Return the time corresponding to date D.
17786 D may be an absolute day number, or a calendar-type list (month day year)."
17787 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17788 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17790 (defvar org-agenda-current-date)
17791 (defun org-calendar-holiday ()
17792 "List of holidays, for Diary display in Org mode."
17793 (require 'holidays)
17794 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17795 (and hl (mapconcat #'identity hl "; "))))
17797 (defun org-diary-sexp-entry (sexp entry d)
17798 "Process a SEXP diary ENTRY for date D."
17799 (require 'diary-lib)
17800 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17801 ;; dynamically.
17802 (let* ((sexp `(let ((entry ,entry)
17803 (date ',d))
17804 ,(car (read-from-string sexp))))
17805 (result (if calendar-debug-sexp (eval sexp)
17806 (condition-case nil
17807 (eval sexp)
17808 (error
17809 (beep)
17810 (message "Bad sexp at line %d in %s: %s"
17811 (org-current-line)
17812 (buffer-file-name) sexp)
17813 (sleep-for 2))))))
17814 (cond ((stringp result) (split-string result "; "))
17815 ((and (consp result)
17816 (not (consp (cdr result)))
17817 (stringp (cdr result))) (cdr result))
17818 ((and (consp result)
17819 (stringp (car result))) result)
17820 (result entry))))
17822 (defun org-diary-to-ical-string (frombuf)
17823 "Get iCalendar entries from diary entries in buffer FROMBUF.
17824 This uses the icalendar.el library."
17825 (let* ((tmpdir temporary-file-directory)
17826 (tmpfile (make-temp-name
17827 (expand-file-name "orgics" tmpdir)))
17828 buf rtn b e)
17829 (with-current-buffer frombuf
17830 (icalendar-export-region (point-min) (point-max) tmpfile)
17831 (setq buf (find-buffer-visiting tmpfile))
17832 (set-buffer buf)
17833 (goto-char (point-min))
17834 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17835 (setq b (match-beginning 0)))
17836 (goto-char (point-max))
17837 (when (re-search-backward "^END:VEVENT" nil t)
17838 (setq e (match-end 0)))
17839 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17840 (kill-buffer buf)
17841 (delete-file tmpfile)
17842 rtn))
17844 (defun org-closest-date (start current prefer)
17845 "Return closest date to CURRENT starting from START.
17847 CURRENT and START are both time stamps.
17849 When PREFER is `past', return a date that is either CURRENT or
17850 past. When PREFER is `future', return a date that is either
17851 CURRENT or future.
17853 Only time stamps with a repeater are modified. Any other time
17854 stamp stay unchanged. In any case, return value is an absolute
17855 day number."
17856 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17857 ;; No repeater. Do not shift time stamp.
17858 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17859 (let ((value (string-to-number (match-string 1 start)))
17860 (type (match-string 2 start)))
17861 (if (= 0 value)
17862 ;; Repeater with a 0-value is considered as void.
17863 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17864 (let* ((base (org-date-to-gregorian start))
17865 (target (org-date-to-gregorian current))
17866 (sday (calendar-absolute-from-gregorian base))
17867 (cday (calendar-absolute-from-gregorian target))
17868 n1 n2)
17869 ;; If START is already past CURRENT, just return START.
17870 (if (<= cday sday) sday
17871 ;; Compute closest date before (N1) and closest date past
17872 ;; (N2) CURRENT.
17873 (pcase type
17874 ("h"
17875 (let ((missing-hours
17876 (mod (+ (- (* 24 (- cday sday))
17877 (nth 2 (org-parse-time-string start)))
17878 org-extend-today-until)
17879 value)))
17880 (setf n1 (if (= missing-hours 0) cday
17881 (- cday (1+ (/ missing-hours 24)))))
17882 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17883 ((or "d" "w")
17884 (let ((value (if (equal type "w") (* 7 value) value)))
17885 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17886 (setf n2 (+ n1 value))))
17887 ("m"
17888 (let* ((add-months
17889 (lambda (d n)
17890 ;; Add N months to gregorian date D, i.e.,
17891 ;; a list (MONTH DAY YEAR). Return a valid
17892 ;; gregorian date.
17893 (let ((m (+ (nth 0 d) n)))
17894 (list (mod m 12)
17895 (nth 1 d)
17896 (+ (/ m 12) (nth 2 d))))))
17897 (months ; Complete months to TARGET.
17898 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17899 (- (nth 0 target) (nth 0 base))
17900 ;; If START's day is greater than
17901 ;; TARGET's, remove incomplete month.
17902 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17903 value)
17904 value))
17905 (before (funcall add-months base months)))
17906 (setf n1 (calendar-absolute-from-gregorian before))
17907 (setf n2
17908 (calendar-absolute-from-gregorian
17909 (funcall add-months before value)))))
17911 (let* ((d (nth 1 base))
17912 (m (nth 0 base))
17913 (y (nth 2 base))
17914 (years ; Complete years to TARGET.
17915 (* (/ (- (nth 2 target)
17917 ;; If START's month and day are
17918 ;; greater than TARGET's, remove
17919 ;; incomplete year.
17920 (if (or (> (nth 0 target) m)
17921 (and (= (nth 0 target) m)
17922 (> (nth 1 target) d)))
17925 value)
17926 value))
17927 (before (list m d (+ y years))))
17928 (setf n1 (calendar-absolute-from-gregorian before))
17929 (setf n2 (calendar-absolute-from-gregorian
17930 (list m d (+ (nth 2 before) value)))))))
17931 ;; Handle PREFER parameter, if any.
17932 (cond
17933 ((eq prefer 'past) (if (= cday n2) n2 n1))
17934 ((eq prefer 'future) (if (= cday n1) n1 n2))
17935 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17937 (defun org-date-to-gregorian (d)
17938 "Turn any specification of date D into a Gregorian date for the calendar."
17939 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17940 ((and (listp d) (= (length d) 3)) d)
17941 ((stringp d)
17942 (let ((d (org-parse-time-string d)))
17943 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17944 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17946 (defun org-parse-time-string (s &optional nodefault)
17947 "Parse the standard Org-mode time string.
17948 This should be a lot faster than the normal `parse-time-string'.
17949 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17950 hour and minute fields will be nil if not given."
17951 (cond ((string-match org-ts-regexp0 s)
17952 (list 0
17953 (when (or (match-beginning 8) (not nodefault))
17954 (string-to-number (or (match-string 8 s) "0")))
17955 (when (or (match-beginning 7) (not nodefault))
17956 (string-to-number (or (match-string 7 s) "0")))
17957 (string-to-number (match-string 4 s))
17958 (string-to-number (match-string 3 s))
17959 (string-to-number (match-string 2 s))
17960 nil nil nil))
17961 ((string-match "^<[^>]+>$" s)
17962 (decode-time (seconds-to-time (org-matcher-time s))))
17963 (t (error "Not a standard Org-mode time string: %s" s))))
17965 (defun org-timestamp-up (&optional arg)
17966 "Increase the date item at the cursor by one.
17967 If the cursor is on the year, change the year. If it is on the month,
17968 the day or the time, change that.
17969 With prefix ARG, change by that many units."
17970 (interactive "p")
17971 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17973 (defun org-timestamp-down (&optional arg)
17974 "Decrease the date item at the cursor by one.
17975 If the cursor is on the year, change the year. If it is on the month,
17976 the day or the time, change that.
17977 With prefix ARG, change by that many units."
17978 (interactive "p")
17979 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17981 (defun org-timestamp-up-day (&optional arg)
17982 "Increase the date in the time stamp by one day.
17983 With prefix ARG, change that many days."
17984 (interactive "p")
17985 (if (and (not (org-at-timestamp-p t))
17986 (org-at-heading-p))
17987 (org-todo 'up)
17988 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17990 (defun org-timestamp-down-day (&optional arg)
17991 "Decrease the date in the time stamp by one day.
17992 With prefix ARG, change that many days."
17993 (interactive "p")
17994 (if (and (not (org-at-timestamp-p t))
17995 (org-at-heading-p))
17996 (org-todo 'down)
17997 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17999 (defun org-at-timestamp-p (&optional inactive-ok)
18000 "Non-nil if point is inside a timestamp.
18002 When optional argument INACTIVE-OK is non-nil, also consider
18003 inactive timestamps.
18005 When this function returns a non-nil value, match data is set
18006 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
18007 INACTIVE-OK."
18008 (interactive)
18009 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
18010 (pos (point))
18011 (ans (or (looking-at tsr)
18012 (save-excursion
18013 (skip-chars-backward "^[<\n\r\t")
18014 (when (> (point) (point-min)) (backward-char 1))
18015 (and (looking-at tsr)
18016 (> (- (match-end 0) pos) -1))))))
18017 (and ans
18018 (boundp 'org-ts-what)
18019 (setq org-ts-what
18020 (cond
18021 ((= pos (match-beginning 0)) 'bracket)
18022 ;; Point is considered to be "on the bracket" whether
18023 ;; it's really on it or right after it.
18024 ((= pos (1- (match-end 0))) 'bracket)
18025 ((= pos (match-end 0)) 'after)
18026 ((org-pos-in-match-range pos 2) 'year)
18027 ((org-pos-in-match-range pos 3) 'month)
18028 ((org-pos-in-match-range pos 7) 'hour)
18029 ((org-pos-in-match-range pos 8) 'minute)
18030 ((or (org-pos-in-match-range pos 4)
18031 (org-pos-in-match-range pos 5)) 'day)
18032 ((and (> pos (or (match-end 8) (match-end 5)))
18033 (< pos (match-end 0)))
18034 (- pos (or (match-end 8) (match-end 5))))
18035 (t 'day))))
18036 ans))
18038 (defun org-toggle-timestamp-type ()
18039 "Toggle the type (<active> or [inactive]) of a time stamp."
18040 (interactive)
18041 (when (org-at-timestamp-p t)
18042 (let ((beg (match-beginning 0)) (end (match-end 0))
18043 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
18044 (save-excursion
18045 (goto-char beg)
18046 (while (re-search-forward "[][<>]" end t)
18047 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
18048 t t)))
18049 (message "Timestamp is now %sactive"
18050 (if (equal (char-after beg) ?<) "" "in")))))
18052 (defun org-at-clock-log-p nil
18053 "Is the cursor on the clock log line?"
18054 (save-excursion
18055 (move-beginning-of-line 1)
18056 (looking-at org-clock-line-re)))
18058 (defvar org-clock-history) ; defined in org-clock.el
18059 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
18060 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
18061 "Change the date in the time stamp at point.
18062 The date will be changed by N times WHAT. WHAT can be `day', `month',
18063 `year', `minute', `second'. If WHAT is not given, the cursor position
18064 in the timestamp determines what will be changed.
18065 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
18066 (let ((origin (point)) origin-cat
18067 with-hm inactive
18068 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
18069 org-ts-what
18070 extra rem
18071 ts time time0 fixnext clrgx)
18072 (unless (org-at-timestamp-p t)
18073 (user-error "Not at a timestamp"))
18074 (if (and (not what) (eq org-ts-what 'bracket))
18075 (org-toggle-timestamp-type)
18076 ;; Point isn't on brackets. Remember the part of the time-stamp
18077 ;; the point was in. Indeed, size of time-stamps may change,
18078 ;; but point must be kept in the same category nonetheless.
18079 (setq origin-cat org-ts-what)
18080 (when (and (not what) (not (eq org-ts-what 'day))
18081 org-display-custom-times
18082 (get-text-property (point) 'display)
18083 (not (get-text-property (1- (point)) 'display)))
18084 (setq org-ts-what 'day))
18085 (setq org-ts-what (or what org-ts-what)
18086 inactive (= (char-after (match-beginning 0)) ?\[)
18087 ts (match-string 0))
18088 (replace-match "")
18089 (when (string-match
18090 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18092 (setq extra (match-string 1 ts))
18093 (when suppress-tmp-delay
18094 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18095 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18096 (setq with-hm t))
18097 (setq time0 (org-parse-time-string ts))
18098 (when (and updown
18099 (eq org-ts-what 'minute)
18100 (not current-prefix-arg))
18101 ;; This looks like s-up and s-down. Change by one rounding step.
18102 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18103 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18104 (setcar (cdr time0) (+ (nth 1 time0)
18105 (if (> n 0) (- rem) (- dm rem))))))
18106 (setq time
18107 (apply #'encode-time
18108 (or (car time0) 0)
18109 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18110 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18111 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18112 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18113 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18114 (nthcdr 6 time0)))
18115 (when (and (member org-ts-what '(hour minute))
18116 extra
18117 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18118 (setq extra (org-modify-ts-extra
18119 extra
18120 (if (eq org-ts-what 'hour) 2 5)
18121 n dm)))
18122 (when (integerp org-ts-what)
18123 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18124 (when (eq what 'calendar)
18125 (let ((cal-date (org-get-date-from-calendar)))
18126 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18127 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18128 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18129 (setcar time0 (or (car time0) 0))
18130 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18131 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18132 (setq time (apply 'encode-time time0))))
18133 ;; Insert the new time-stamp, and ensure point stays in the same
18134 ;; category as before (i.e. not after the last position in that
18135 ;; category).
18136 (let ((pos (point)))
18137 ;; Stay before inserted string. `save-excursion' is of no use.
18138 (setq org-last-changed-timestamp
18139 (org-insert-time-stamp time with-hm inactive nil nil extra))
18140 (goto-char pos))
18141 (save-match-data
18142 (looking-at org-ts-regexp3)
18143 (goto-char (cond
18144 ;; `day' category ends before `hour' if any, or at
18145 ;; the end of the day name.
18146 ((eq origin-cat 'day)
18147 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18148 ((eq origin-cat 'hour) (min (match-end 7) origin))
18149 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18150 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18151 ;; `year' and `month' have both fixed size: point
18152 ;; couldn't have moved into another part.
18153 (t origin))))
18154 ;; Update clock if on a CLOCK line.
18155 (org-clock-update-time-maybe)
18156 ;; Maybe adjust the closest clock in `org-clock-history'
18157 (when org-clock-adjust-closest
18158 (if (not (and (org-at-clock-log-p)
18159 (< 1 (length (delq nil (mapcar 'marker-position
18160 org-clock-history))))))
18161 (message "No clock to adjust")
18162 (cond ((save-excursion ; fix previous clock?
18163 (re-search-backward org-ts-regexp0 nil t)
18164 (looking-back (concat org-clock-string " \\[")
18165 (line-beginning-position)))
18166 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18167 ((save-excursion ; fix next clock?
18168 (re-search-backward org-ts-regexp0 nil t)
18169 (looking-at (concat org-ts-regexp0 "\\] =>")))
18170 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18171 (save-window-excursion
18172 ;; Find closest clock to point, adjust the previous/next one in history
18173 (let* ((p (save-excursion (org-back-to-heading t)))
18174 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18175 (clfixnth
18176 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18177 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18178 (if (not clfixpos)
18179 (message "No clock to adjust")
18180 (save-excursion
18181 (org-goto-marker-or-bmk clfixpos)
18182 (org-show-subtree)
18183 (when (re-search-forward clrgx nil t)
18184 (goto-char (match-beginning 1))
18185 (let (org-clock-adjust-closest)
18186 (org-timestamp-change n org-ts-what updown))
18187 (message "Clock adjusted in %s for heading: %s"
18188 (file-name-nondirectory (buffer-file-name))
18189 (org-get-heading t t)))))))))
18190 ;; Try to recenter the calendar window, if any.
18191 (when (and org-calendar-follow-timestamp-change
18192 (get-buffer-window "*Calendar*" t)
18193 (memq org-ts-what '(day month year)))
18194 (org-recenter-calendar (time-to-days time))))))
18196 (defun org-modify-ts-extra (s pos n dm)
18197 "Change the different parts of the lead-time and repeat fields in timestamp."
18198 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18199 ng h m new rem)
18200 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18201 (cond
18202 ((or (org-pos-in-match-range pos 2)
18203 (org-pos-in-match-range pos 3))
18204 (setq m (string-to-number (match-string 3 s))
18205 h (string-to-number (match-string 2 s)))
18206 (if (org-pos-in-match-range pos 2)
18207 (setq h (+ h n))
18208 (setq n (* dm (org-no-warnings (signum n))))
18209 (unless (= 0 (setq rem (% m dm)))
18210 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18211 (setq m (+ m n)))
18212 (when (< m 0) (setq m (+ m 60) h (1- h)))
18213 (when (> m 59) (setq m (- m 60) h (1+ h)))
18214 (setq h (mod h 24))
18215 (setq ng 1 new (format "-%02d:%02d" h m)))
18216 ((org-pos-in-match-range pos 6)
18217 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18218 ((org-pos-in-match-range pos 5)
18219 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18221 ((org-pos-in-match-range pos 9)
18222 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18223 ((org-pos-in-match-range pos 8)
18224 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18226 (when ng
18227 (setq s (concat
18228 (substring s 0 (match-beginning ng))
18230 (substring s (match-end ng))))))
18233 (defun org-recenter-calendar (d)
18234 "If the calendar is visible, recenter it to date D."
18235 (let ((cwin (get-buffer-window "*Calendar*" t)))
18236 (when cwin
18237 (let ((calendar-move-hook nil))
18238 (with-selected-window cwin
18239 (calendar-goto-date
18240 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18242 (defun org-goto-calendar (&optional arg)
18243 "Go to the Emacs calendar at the current date.
18244 If there is a time stamp in the current line, go to that date.
18245 A prefix ARG can be used to force the current date."
18246 (interactive "P")
18247 (let ((tsr org-ts-regexp) diff
18248 (calendar-move-hook nil)
18249 (calendar-view-holidays-initially-flag nil)
18250 (calendar-view-diary-initially-flag nil))
18251 (when (or (org-at-timestamp-p)
18252 (save-excursion
18253 (beginning-of-line 1)
18254 (looking-at (concat ".*" tsr))))
18255 (let ((d1 (time-to-days (current-time)))
18256 (d2 (time-to-days
18257 (org-time-string-to-time (match-string 1)))))
18258 (setq diff (- d2 d1))))
18259 (calendar)
18260 (calendar-goto-today)
18261 (when (and diff (not arg)) (calendar-forward-day diff))))
18263 (defun org-get-date-from-calendar ()
18264 "Return a list (month day year) of date at point in calendar."
18265 (with-current-buffer "*Calendar*"
18266 (save-match-data
18267 (calendar-cursor-to-date))))
18269 (defun org-date-from-calendar ()
18270 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18271 If there is already a time stamp at the cursor position, update it."
18272 (interactive)
18273 (if (org-at-timestamp-p t)
18274 (org-timestamp-change 0 'calendar)
18275 (let ((cal-date (org-get-date-from-calendar)))
18276 (org-insert-time-stamp
18277 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18279 (defcustom org-effort-durations
18280 `(("min" . 1)
18281 ("h" . 60)
18282 ("d" . ,(* 60 8))
18283 ("w" . ,(* 60 8 5))
18284 ("m" . ,(* 60 8 5 4))
18285 ("y" . ,(* 60 8 5 40)))
18286 "Conversion factor to minutes for an effort modifier.
18288 Each entry has the form (MODIFIER . MINUTES).
18290 In an effort string, a number followed by MODIFIER is multiplied
18291 by the specified number of MINUTES to obtain an effort in
18292 minutes.
18294 For example, if the value of this variable is ((\"hours\" . 60)), then an
18295 effort string \"2hours\" is equivalent to 120 minutes."
18296 :group 'org-agenda
18297 :version "25.1"
18298 :package-version '(Org . "8.3")
18299 :type '(alist :key-type (string :tag "Modifier")
18300 :value-type (number :tag "Minutes")))
18302 (defun org-minutes-to-clocksum-string (m)
18303 "Format number of minutes as a clocksum string.
18304 The format is determined by `org-time-clocksum-format',
18305 `org-time-clocksum-use-fractional' and
18306 `org-time-clocksum-fractional-format' and
18307 `org-time-clocksum-use-effort-durations'."
18308 (let ((clocksum "")
18309 (m (round m)) ; Don't allow fractions of minutes
18310 h d w mo y fmt n)
18311 (setq h (if org-time-clocksum-use-effort-durations
18312 (cdr (assoc "h" org-effort-durations)) 60)
18313 d (if org-time-clocksum-use-effort-durations
18314 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18315 w (if org-time-clocksum-use-effort-durations
18316 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18317 mo (if org-time-clocksum-use-effort-durations
18318 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18319 y (if org-time-clocksum-use-effort-durations
18320 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18321 ;; fractional format
18322 (if org-time-clocksum-use-fractional
18323 (cond
18324 ;; single format string
18325 ((stringp org-time-clocksum-fractional-format)
18326 (format org-time-clocksum-fractional-format (/ m (float h))))
18327 ;; choice of fractional formats for different time units
18328 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18329 (> (/ (truncate m) (* y d h)) 0))
18330 (format fmt (/ m (* y d (float h)))))
18331 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18332 (> (/ (truncate m) (* mo d h)) 0))
18333 (format fmt (/ m (* mo d (float h)))))
18334 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18335 (> (/ (truncate m) (* w d h)) 0))
18336 (format fmt (/ m (* w d (float h)))))
18337 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18338 (> (/ (truncate m) (* d h)) 0))
18339 (format fmt (/ m (* d (float h)))))
18340 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18341 (> (/ (truncate m) h) 0))
18342 (format fmt (/ m (float h))))
18343 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18344 (format fmt m))
18345 ;; fall back to smallest time unit with a format
18346 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18347 (format fmt (/ m (float h))))
18348 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18349 (format fmt (/ m (* d (float h)))))
18350 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18351 (format fmt (/ m (* w d (float h)))))
18352 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18353 (format fmt (/ m (* mo d (float h)))))
18354 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18355 (format fmt (/ m (* y d (float h))))))
18356 ;; standard (non-fractional) format, with single format string
18357 (if (stringp org-time-clocksum-format)
18358 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18359 ;; separate formats components
18360 (and (setq fmt (plist-get org-time-clocksum-format :years))
18361 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18362 (plist-get org-time-clocksum-format :require-years))
18363 (setq clocksum (concat clocksum (format fmt n))
18364 m (- m (* n y d h))))
18365 (and (setq fmt (plist-get org-time-clocksum-format :months))
18366 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18367 (plist-get org-time-clocksum-format :require-months))
18368 (setq clocksum (concat clocksum (format fmt n))
18369 m (- m (* n mo d h))))
18370 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18371 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18372 (plist-get org-time-clocksum-format :require-weeks))
18373 (setq clocksum (concat clocksum (format fmt n))
18374 m (- m (* n w d h))))
18375 (and (setq fmt (plist-get org-time-clocksum-format :days))
18376 (or (> (setq n (/ (truncate m) (* d h))) 0)
18377 (plist-get org-time-clocksum-format :require-days))
18378 (setq clocksum (concat clocksum (format fmt n))
18379 m (- m (* n d h))))
18380 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18381 (or (> (setq n (/ (truncate m) h)) 0)
18382 (plist-get org-time-clocksum-format :require-hours))
18383 (setq clocksum (concat clocksum (format fmt n))
18384 m (- m (* n h))))
18385 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18386 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18387 (setq clocksum (concat clocksum (format fmt m))))
18388 ;; return formatted time duration
18389 clocksum))))
18391 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18392 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18393 "Org mode version 8.0")
18395 (defun org-hours-to-clocksum-string (n)
18396 (org-minutes-to-clocksum-string (* n 60)))
18398 (defun org-hh:mm-string-to-minutes (s)
18399 "Convert a string H:MM to a number of minutes.
18400 If the string is just a number, interpret it as minutes.
18401 In fact, the first hh:mm or number in the string will be taken,
18402 there can be extra stuff in the string.
18403 If no number is found, the return value is 0."
18404 (cond
18405 ((integerp s) s)
18406 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18407 (+ (* (string-to-number (match-string 1 s)) 60)
18408 (string-to-number (match-string 2 s))))
18409 ((string-match "\\([0-9]+\\)" s)
18410 (string-to-number (match-string 1 s)))
18411 (t 0)))
18413 (defcustom org-image-actual-width t
18414 "Should we use the actual width of images when inlining them?
18416 When set to t, always use the image width.
18418 When set to a number, use imagemagick (when available) to set
18419 the image's width to this value.
18421 When set to a number in a list, try to get the width from any
18422 #+ATTR.* keyword if it matches a width specification like
18424 #+ATTR_HTML: :width 300px
18426 and fall back on that number if none is found.
18428 When set to nil, try to get the width from an #+ATTR.* keyword
18429 and fall back on the original width if none is found.
18431 This requires Emacs >= 24.1, build with imagemagick support."
18432 :group 'org-appearance
18433 :version "24.4"
18434 :package-version '(Org . "8.0")
18435 :type '(choice
18436 (const :tag "Use the image width" t)
18437 (integer :tag "Use a number of pixels")
18438 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18439 (const :tag "Use #+ATTR* or don't resize" nil)))
18441 (defcustom org-agenda-inhibit-startup nil
18442 "Inhibit startup when preparing agenda buffers.
18443 When this variable is t, the initialization of the Org agenda
18444 buffers is inhibited: e.g. the visibility state is not set, the
18445 tables are not re-aligned, etc."
18446 :type 'boolean
18447 :version "24.3"
18448 :group 'org-agenda)
18450 (define-obsolete-variable-alias
18451 'org-agenda-ignore-drawer-properties
18452 'org-agenda-ignore-properties "25.1")
18454 (defcustom org-agenda-ignore-properties nil
18455 "Avoid updating text properties when building the agenda.
18456 Properties are used to prepare buffers for effort estimates,
18457 appointments, statistics and subtree-local categories.
18458 If you don't use these in the agenda, you can add them to this
18459 list and agenda building will be a bit faster.
18460 The value is a list, with zero or more of the symbols `effort', `appt',
18461 `stats' or `category'."
18462 :type '(set :greedy t
18463 (const effort)
18464 (const appt)
18465 (const stats)
18466 (const category))
18467 :version "25.1"
18468 :package-version '(Org . "8.3")
18469 :group 'org-agenda)
18471 (defun org-duration-string-to-minutes (s &optional output-to-string)
18472 "Convert a duration string S to minutes.
18474 A bare number is interpreted as minutes, modifiers can be set by
18475 customizing `org-effort-durations' (which see).
18477 Entries containing a colon are interpreted as H:MM by
18478 `org-hh:mm-string-to-minutes'."
18479 (let ((result 0)
18480 (re (concat "\\([0-9.]+\\) *\\("
18481 (regexp-opt (mapcar 'car org-effort-durations))
18482 "\\)")))
18483 (while (string-match re s)
18484 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18485 (string-to-number (match-string 1 s))))
18486 (setq s (replace-match "" nil t s)))
18487 (setq result (floor result))
18488 (cl-incf result (org-hh:mm-string-to-minutes s))
18489 (if output-to-string (number-to-string result) result)))
18491 ;;;; Files
18493 (defun org-save-all-org-buffers ()
18494 "Save all Org-mode buffers without user confirmation."
18495 (interactive)
18496 (message "Saving all Org-mode buffers...")
18497 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18498 (when (featurep 'org-id) (org-id-locations-save))
18499 (message "Saving all Org-mode buffers... done"))
18501 (defun org-revert-all-org-buffers ()
18502 "Revert all Org-mode buffers.
18503 Prompt for confirmation when there are unsaved changes.
18504 Be sure you know what you are doing before letting this function
18505 overwrite your changes.
18507 This function is useful in a setup where one tracks org files
18508 with a version control system, to revert on one machine after pulling
18509 changes from another. I believe the procedure must be like this:
18511 1. M-x org-save-all-org-buffers
18512 2. Pull changes from the other machine, resolve conflicts
18513 3. M-x org-revert-all-org-buffers"
18514 (interactive)
18515 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18516 (user-error "Abort"))
18517 (save-excursion
18518 (save-window-excursion
18519 (dolist (b (buffer-list))
18520 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18521 (with-current-buffer b buffer-file-name))
18522 (org-pop-to-buffer-same-window b)
18523 (revert-buffer t 'no-confirm)))
18524 (when (and (featurep 'org-id) org-id-track-globally)
18525 (org-id-locations-load)))))
18527 ;;;; Agenda files
18529 ;;;###autoload
18530 (defun org-switchb (&optional arg)
18531 "Switch between Org buffers.
18533 With \\[universal-argument] prefix, restrict available buffers to files.
18535 With \\[universal-argument] \\[universal-argument] \
18536 prefix, restrict available buffers to agenda files."
18537 (interactive "P")
18538 (let ((blist (org-buffer-list
18539 (cond ((equal arg '(4)) 'files)
18540 ((equal arg '(16)) 'agenda)))))
18541 (org-pop-to-buffer-same-window
18542 (completing-read "Org buffer: "
18543 (mapcar #'list (mapcar #'buffer-name blist))
18544 nil t))))
18546 (defun org-buffer-list (&optional predicate exclude-tmp)
18547 "Return a list of Org buffers.
18548 PREDICATE can be `export', `files' or `agenda'.
18550 export restrict the list to Export buffers.
18551 files restrict the list to buffers visiting Org files.
18552 agenda restrict the list to buffers visiting agenda files.
18554 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18555 (let* ((bfn nil)
18556 (agenda-files (and (eq predicate 'agenda)
18557 (mapcar 'file-truename (org-agenda-files t))))
18558 (filter
18559 (cond
18560 ((eq predicate 'files)
18561 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18562 ((eq predicate 'export)
18563 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18564 ((eq predicate 'agenda)
18565 (lambda (b)
18566 (with-current-buffer b
18567 (and (derived-mode-p 'org-mode)
18568 (setq bfn (buffer-file-name b))
18569 (member (file-truename bfn) agenda-files)))))
18570 (t (lambda (b) (with-current-buffer b
18571 (or (derived-mode-p 'org-mode)
18572 (string-match "\\*Org .*Export"
18573 (buffer-name b)))))))))
18574 (delq nil
18575 (mapcar
18576 (lambda(b)
18577 (if (and (funcall filter b)
18578 (or (not exclude-tmp)
18579 (not (string-match "tmp" (buffer-name b)))))
18581 nil))
18582 (buffer-list)))))
18584 (defun org-agenda-files (&optional unrestricted archives)
18585 "Get the list of agenda files.
18586 Optional UNRESTRICTED means return the full list even if a restriction
18587 is currently in place.
18588 When ARCHIVES is t, include all archive files that are really being
18589 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18590 `org-agenda-archives-mode' is t."
18591 (let ((files
18592 (cond
18593 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18594 ((stringp org-agenda-files) (org-read-agenda-file-list))
18595 ((listp org-agenda-files) org-agenda-files)
18596 (t (error "Invalid value of `org-agenda-files'")))))
18597 (setq files (apply 'append
18598 (mapcar (lambda (f)
18599 (if (file-directory-p f)
18600 (directory-files
18601 f t org-agenda-file-regexp)
18602 (list f)))
18603 files)))
18604 (when org-agenda-skip-unavailable-files
18605 (setq files (delq nil
18606 (mapcar (function
18607 (lambda (file)
18608 (and (file-readable-p file) file)))
18609 files))))
18610 (when (or (eq archives t)
18611 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18612 (setq files (org-add-archive-files files)))
18613 files))
18615 (defun org-agenda-file-p (&optional file)
18616 "Return non-nil, if FILE is an agenda file.
18617 If FILE is omitted, use the file associated with the current
18618 buffer."
18619 (let ((fname (or file (buffer-file-name))))
18620 (and fname
18621 (member (file-truename fname)
18622 (mapcar #'file-truename (org-agenda-files t))))))
18624 (defun org-edit-agenda-file-list ()
18625 "Edit the list of agenda files.
18626 Depending on setup, this either uses customize to edit the variable
18627 `org-agenda-files', or it visits the file that is holding the list. In the
18628 latter case, the buffer is set up in a way that saving it automatically kills
18629 the buffer and restores the previous window configuration."
18630 (interactive)
18631 (if (stringp org-agenda-files)
18632 (let ((cw (current-window-configuration)))
18633 (find-file org-agenda-files)
18634 (setq-local org-window-configuration cw)
18635 (add-hook 'after-save-hook
18636 (lambda ()
18637 (set-window-configuration
18638 (prog1 org-window-configuration
18639 (kill-buffer (current-buffer))))
18640 (org-install-agenda-files-menu)
18641 (message "New agenda file list installed"))
18642 nil 'local)
18643 (message "%s" (substitute-command-keys
18644 "Edit list and finish with \\[save-buffer]")))
18645 (customize-variable 'org-agenda-files)))
18647 (defun org-store-new-agenda-file-list (list)
18648 "Set new value for the agenda file list and save it correctly."
18649 (if (stringp org-agenda-files)
18650 (let ((fe (org-read-agenda-file-list t)) b u)
18651 (while (setq b (find-buffer-visiting org-agenda-files))
18652 (kill-buffer b))
18653 (with-temp-file org-agenda-files
18654 (insert
18655 (mapconcat
18656 (lambda (f) ;; Keep un-expanded entries.
18657 (if (setq u (assoc f fe))
18658 (cdr u)
18660 list "\n")
18661 "\n")))
18662 (let ((org-mode-hook nil) (org-inhibit-startup t)
18663 (org-insert-mode-line-in-empty-file nil))
18664 (setq org-agenda-files list)
18665 (customize-save-variable 'org-agenda-files org-agenda-files))))
18667 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18668 "Read the list of agenda files from a file.
18669 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18670 filenames, used by `org-store-new-agenda-file-list' to write back
18671 un-expanded file names."
18672 (when (file-directory-p org-agenda-files)
18673 (error "`org-agenda-files' cannot be a single directory"))
18674 (when (stringp org-agenda-files)
18675 (with-temp-buffer
18676 (insert-file-contents org-agenda-files)
18677 (mapcar
18678 (lambda (f)
18679 (let ((e (expand-file-name (substitute-in-file-name f)
18680 org-directory)))
18681 (if pair-with-expansion
18682 (cons e f)
18683 e)))
18684 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18686 ;;;###autoload
18687 (defun org-cycle-agenda-files ()
18688 "Cycle through the files in `org-agenda-files'.
18689 If the current buffer visits an agenda file, find the next one in the list.
18690 If the current buffer does not, find the first agenda file."
18691 (interactive)
18692 (let* ((fs (or (org-agenda-files t)
18693 (user-error "No agenda files")))
18694 (files (copy-sequence fs))
18695 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18696 file)
18697 (when tcf
18698 (while (and (setq file (pop files))
18699 (not (equal (file-truename file) tcf)))))
18700 (find-file (car (or files fs)))
18701 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18703 (defun org-agenda-file-to-front (&optional to-end)
18704 "Move/add the current file to the top of the agenda file list.
18705 If the file is not present in the list, it is added to the front. If it is
18706 present, it is moved there. With optional argument TO-END, add/move to the
18707 end of the list."
18708 (interactive "P")
18709 (let ((org-agenda-skip-unavailable-files nil)
18710 (file-alist (mapcar (lambda (x)
18711 (cons (file-truename x) x))
18712 (org-agenda-files t)))
18713 (ctf (file-truename
18714 (or buffer-file-name
18715 (user-error "Please save the current buffer to a file"))))
18716 x had)
18717 (setq x (assoc ctf file-alist) had x)
18719 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18720 (if to-end
18721 (setq file-alist (append (delq x file-alist) (list x)))
18722 (setq file-alist (cons x (delq x file-alist))))
18723 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18724 (org-install-agenda-files-menu)
18725 (message "File %s to %s of agenda file list"
18726 (if had "moved" "added") (if to-end "end" "front"))))
18728 (defun org-remove-file (&optional file)
18729 "Remove current file from the list of files in variable `org-agenda-files'.
18730 These are the files which are being checked for agenda entries.
18731 Optional argument FILE means use this file instead of the current."
18732 (interactive)
18733 (let* ((org-agenda-skip-unavailable-files nil)
18734 (file (or file buffer-file-name
18735 (user-error "Current buffer does not visit a file")))
18736 (true-file (file-truename file))
18737 (afile (abbreviate-file-name file))
18738 (files (delq nil (mapcar
18739 (lambda (x)
18740 (unless (equal true-file
18741 (file-truename x))
18743 (org-agenda-files t)))))
18744 (if (not (= (length files) (length (org-agenda-files t))))
18745 (progn
18746 (org-store-new-agenda-file-list files)
18747 (org-install-agenda-files-menu)
18748 (message "Removed from Org Agenda list: %s" afile))
18749 (message "File was not in list: %s (not removed)" afile))))
18751 (defun org-file-menu-entry (file)
18752 (vector file (list 'find-file file) t))
18754 (defun org-check-agenda-file (file)
18755 "Make sure FILE exists. If not, ask user what to do."
18756 (unless (file-exists-p file)
18757 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18758 (abbreviate-file-name file))
18759 (let ((r (downcase (read-char-exclusive))))
18760 (cond
18761 ((equal r ?r)
18762 (org-remove-file file)
18763 (throw 'nextfile t))
18764 (t (user-error "Abort"))))))
18766 (defun org-get-agenda-file-buffer (file)
18767 "Get an agenda buffer visiting FILE.
18768 If the buffer needs to be created, add it to the list of buffers
18769 which might be released later."
18770 (let ((buf (org-find-base-buffer-visiting file)))
18771 (if buf
18772 buf ; just return it
18773 ;; Make a new buffer and remember it
18774 (setq buf (find-file-noselect file))
18775 (when buf (push buf org-agenda-new-buffers))
18776 buf)))
18778 (defun org-release-buffers (blist)
18779 "Release all buffers in list, asking the user for confirmation when needed.
18780 When a buffer is unmodified, it is just killed. When modified, it is saved
18781 \(if the user agrees) and then killed."
18782 (let (file)
18783 (dolist (buf blist)
18784 (setq file (buffer-file-name buf))
18785 (when (and (buffer-modified-p buf)
18786 file
18787 (y-or-n-p (format "Save file %s? " file)))
18788 (with-current-buffer buf (save-buffer)))
18789 (kill-buffer buf))))
18791 (defun org-agenda-prepare-buffers (files)
18792 "Create buffers for all agenda files, protect archived trees and comments."
18793 (interactive)
18794 (let ((pa '(:org-archived t))
18795 (pc '(:org-comment t))
18796 (pall '(:org-archived t :org-comment t))
18797 (inhibit-read-only t)
18798 (org-inhibit-startup org-agenda-inhibit-startup)
18799 (rea (concat ":" org-archive-tag ":"))
18800 re pos)
18801 (setq org-tag-alist-for-agenda nil
18802 org-tag-groups-alist-for-agenda nil)
18803 (save-excursion
18804 (save-restriction
18805 (dolist (file files)
18806 (catch 'nextfile
18807 (if (bufferp file)
18808 (set-buffer file)
18809 (org-check-agenda-file file)
18810 (set-buffer (org-get-agenda-file-buffer file)))
18811 (widen)
18812 (org-set-regexps-and-options 'tags-only)
18813 (setq pos (point))
18814 (or (memq 'category org-agenda-ignore-properties)
18815 (org-refresh-category-properties))
18816 (or (memq 'stats org-agenda-ignore-properties)
18817 (org-refresh-stats-properties))
18818 (or (memq 'effort org-agenda-ignore-properties)
18819 (org-refresh-effort-properties))
18820 (or (memq 'appt org-agenda-ignore-properties)
18821 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18822 (setq org-todo-keywords-for-agenda
18823 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18824 (setq org-done-keywords-for-agenda
18825 (append org-done-keywords-for-agenda org-done-keywords))
18826 (setq org-todo-keyword-alist-for-agenda
18827 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18828 (setq org-tag-alist-for-agenda
18829 (org-uniquify
18830 (append org-tag-alist-for-agenda
18831 org-current-tag-alist)))
18832 ;; Merge current file's tag groups into global
18833 ;; `org-tag-groups-alist-for-agenda'.
18834 (when org-group-tags
18835 (dolist (alist org-tag-groups-alist)
18836 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18837 (if old
18838 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18839 (push alist org-tag-groups-alist-for-agenda)))))
18840 (org-with-silent-modifications
18841 (save-excursion
18842 (remove-text-properties (point-min) (point-max) pall)
18843 (when org-agenda-skip-archived-trees
18844 (goto-char (point-min))
18845 (while (re-search-forward rea nil t)
18846 (when (org-at-heading-p t)
18847 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18848 (goto-char (point-min))
18849 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18850 (while (re-search-forward re nil t)
18851 (when (save-match-data (org-in-commented-heading-p t))
18852 (add-text-properties
18853 (match-beginning 0) (org-end-of-subtree t) pc)))))
18854 (goto-char pos)))))
18855 (setq org-todo-keywords-for-agenda
18856 (org-uniquify org-todo-keywords-for-agenda))
18857 (setq org-todo-keyword-alist-for-agenda
18858 (org-uniquify org-todo-keyword-alist-for-agenda))))
18861 ;;;; CDLaTeX minor mode
18863 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18864 "Keymap for the minor `org-cdlatex-mode'.")
18866 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18867 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18868 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18869 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18870 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18872 (defvar org-cdlatex-texmathp-advice-is-done nil
18873 "Flag remembering if we have applied the advice to texmathp already.")
18875 (define-minor-mode org-cdlatex-mode
18876 "Toggle the minor `org-cdlatex-mode'.
18877 This mode supports entering LaTeX environment and math in LaTeX fragments
18878 in Org-mode.
18879 \\{org-cdlatex-mode-map}"
18880 nil " OCDL" nil
18881 (when org-cdlatex-mode
18882 (require 'cdlatex)
18883 (run-hooks 'cdlatex-mode-hook)
18884 (cdlatex-compute-tables))
18885 (unless org-cdlatex-texmathp-advice-is-done
18886 (setq org-cdlatex-texmathp-advice-is-done t)
18887 (defadvice texmathp (around org-math-always-on activate)
18888 "Always return t in org-mode buffers.
18889 This is because we want to insert math symbols without dollars even outside
18890 the LaTeX math segments. If Orgmode thinks that point is actually inside
18891 an embedded LaTeX fragment, let texmathp do its job.
18892 \\[org-cdlatex-mode-map]"
18893 (interactive)
18894 (let (p)
18895 (cond
18896 ((not (derived-mode-p 'org-mode)) ad-do-it)
18897 ((eq this-command 'cdlatex-math-symbol)
18898 (setq ad-return-value t
18899 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18901 (let ((p (org-inside-LaTeX-fragment-p)))
18902 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18903 (setq ad-return-value t
18904 texmathp-why '("Org-mode embedded math" . 0))
18905 (when p ad-do-it)))))))))
18907 (defun turn-on-org-cdlatex ()
18908 "Unconditionally turn on `org-cdlatex-mode'."
18909 (org-cdlatex-mode 1))
18911 (defun org-try-cdlatex-tab ()
18912 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18913 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18914 - inside a LaTeX fragment, or
18915 - after the first word in a line, where an abbreviation expansion could
18916 insert a LaTeX environment."
18917 (when org-cdlatex-mode
18918 (cond
18919 ;; Before any word on the line: No expansion possible.
18920 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18921 ;; Just after first word on the line: Expand it. Make sure it
18922 ;; cannot happen on headlines, though.
18923 ((save-excursion
18924 (skip-chars-backward "a-zA-Z0-9*")
18925 (skip-chars-backward " \t")
18926 (and (bolp) (not (org-at-heading-p))))
18927 (cdlatex-tab) t)
18928 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18930 (defun org-cdlatex-underscore-caret (&optional _arg)
18931 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18932 Revert to the normal definition outside of these fragments."
18933 (interactive "P")
18934 (if (org-inside-LaTeX-fragment-p)
18935 (call-interactively 'cdlatex-sub-superscript)
18936 (let (org-cdlatex-mode)
18937 (call-interactively (key-binding (vector last-input-event))))))
18939 (defun org-cdlatex-math-modify (&optional _arg)
18940 "Execute `cdlatex-math-modify' in LaTeX fragments.
18941 Revert to the normal definition outside of these fragments."
18942 (interactive "P")
18943 (if (org-inside-LaTeX-fragment-p)
18944 (call-interactively 'cdlatex-math-modify)
18945 (let (org-cdlatex-mode)
18946 (call-interactively (key-binding (vector last-input-event))))))
18948 (defun org-cdlatex-environment-indent (&optional environment item)
18949 "Execute `cdlatex-environment' and indent the inserted environment.
18951 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18953 The inserted environment is indented to current indentation
18954 unless point is at the beginning of the line, in which the
18955 environment remains unintended."
18956 (interactive)
18957 ;; cdlatex-environment always return nil. Therefore, capture output
18958 ;; first and determine if an environment was selected.
18959 (let* ((beg (point-marker))
18960 (end (copy-marker (point) t))
18961 (inserted (progn
18962 (ignore-errors (cdlatex-environment environment item))
18963 (< beg end)))
18964 ;; Figure out how many lines to move forward after the
18965 ;; environment has been inserted.
18966 (lines (when inserted
18967 (save-excursion
18968 (- (cl-loop while (< beg (point))
18969 with x = 0
18970 do (forward-line -1)
18971 (cl-incf x)
18972 finally return x)
18973 (if (progn (goto-char beg)
18974 (and (progn (skip-chars-forward " \t") (eolp))
18975 (progn (skip-chars-backward " \t") (bolp))))
18976 1 0)))))
18977 (env (org-trim (delete-and-extract-region beg end))))
18978 (when inserted
18979 ;; Get indentation of next line unless at column 0.
18980 (let ((ind (if (bolp) 0
18981 (save-excursion
18982 (org-return-indent)
18983 (prog1 (org-get-indentation)
18984 (when (progn (skip-chars-forward " \t") (eolp))
18985 (delete-region beg (point)))))))
18986 (bol (progn (skip-chars-backward " \t") (bolp))))
18987 ;; Insert a newline before environment unless at column zero
18988 ;; to "escape" the current line. Insert a newline if
18989 ;; something is one the same line as \end{ENVIRONMENT}.
18990 (insert
18991 (concat (unless bol "\n") env
18992 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18993 (unless (zerop ind)
18994 (save-excursion
18995 (goto-char beg)
18996 (while (< (point) end)
18997 (unless (eolp) (indent-line-to ind))
18998 (forward-line))))
18999 (goto-char beg)
19000 (forward-line lines)
19001 (indent-line-to ind)))
19002 (set-marker beg nil)
19003 (set-marker end nil)))
19006 ;;;; LaTeX fragments
19008 (defun org-inside-LaTeX-fragment-p ()
19009 "Test if point is inside a LaTeX fragment.
19010 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
19011 sequence appearing also before point.
19012 Even though the matchers for math are configurable, this function assumes
19013 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
19014 delimiters are skipped when they have been removed by customization.
19015 The return value is nil, or a cons cell with the delimiter and the
19016 position of this delimiter.
19018 This function does a reasonably good job, but can locally be fooled by
19019 for example currency specifications. For example it will assume being in
19020 inline math after \"$22.34\". The LaTeX fragment formatter will only format
19021 fragments that are properly closed, but during editing, we have to live
19022 with the uncertainty caused by missing closing delimiters. This function
19023 looks only before point, not after."
19024 (catch 'exit
19025 (let ((pos (point))
19026 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
19027 (lim (progn
19028 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
19029 (point)))
19030 dd-on str (start 0) m re)
19031 (goto-char pos)
19032 (when dodollar
19033 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
19034 re (nth 1 (assoc "$" org-latex-regexps)))
19035 (while (string-match re str start)
19036 (cond
19037 ((= (match-end 0) (length str))
19038 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
19039 ((= (match-end 0) (- (length str) 5))
19040 (throw 'exit nil))
19041 (t (setq start (match-end 0))))))
19042 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
19043 (goto-char pos)
19044 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
19045 (and (match-beginning 2) (throw 'exit nil))
19046 ;; count $$
19047 (while (re-search-backward "\\$\\$" lim t)
19048 (setq dd-on (not dd-on)))
19049 (goto-char pos)
19050 (when dd-on (cons "$$" m))))))
19052 (defun org-inside-latex-macro-p ()
19053 "Is point inside a LaTeX macro or its arguments?"
19054 (save-match-data
19055 (org-in-regexp
19056 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
19058 (defun org--format-latex-make-overlay (beg end image &optional imagetype)
19059 "Build an overlay between BEG and END using IMAGE file.
19060 Argument IMAGETYPE is the extension of the displayed image,
19061 as a string. It defaults to \"png\"."
19062 (let ((ov (make-overlay beg end))
19063 (imagetype (or (intern imagetype) 'png)))
19064 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
19065 (overlay-put ov 'evaporate t)
19066 (overlay-put ov
19067 'modification-hooks
19068 (list (lambda (o _flag _beg _end &optional _l)
19069 (delete-overlay o))))
19070 (overlay-put ov
19071 'display
19072 (list 'image :type imagetype :file image :ascent 'center))))
19074 (defun org--list-latex-overlays (&optional beg end)
19075 "List all Org LaTeX overlays in current buffer.
19076 Limit to overlays between BEG and END when those are provided."
19077 (cl-remove-if-not
19078 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19079 (overlays-in (or beg (point-min)) (or end (point-max)))))
19081 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19082 "Remove all overlays with LaTeX fragment images in current buffer.
19083 When optional arguments BEG and END are non-nil, remove all
19084 overlays between them instead. Return a non-nil value when some
19085 overlays were removed, nil otherwise."
19086 (let ((overlays (org--list-latex-overlays beg end)))
19087 (mapc #'delete-overlay overlays)
19088 overlays))
19090 (define-obsolete-function-alias
19091 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
19092 (defun org-toggle-latex-fragment (&optional arg)
19093 "Preview the LaTeX fragment at point, or all locally or globally.
19095 If the cursor is on a LaTeX fragment, create the image and overlay
19096 it over the source code, if there is none. Remove it otherwise.
19097 If there is no fragment at point, display all fragments in the
19098 current section.
19100 With prefix ARG, preview or clear image for all fragments in the
19101 current subtree or in the whole buffer when used before the first
19102 headline. With a double prefix ARG \\[universal-argument] \
19103 \\[universal-argument] preview or clear images
19104 for all fragments in the buffer."
19105 (interactive "P")
19106 (when (display-graphic-p)
19107 (catch 'exit
19108 (save-excursion
19109 (let ((window-start (window-start)) msg)
19110 (save-restriction
19111 (cond
19112 ((or (equal arg '(16))
19113 (and (equal arg '(4))
19114 (org-with-limited-levels (org-before-first-heading-p))))
19115 (if (org-remove-latex-fragment-image-overlays)
19116 (progn (message "LaTeX fragments images removed from buffer")
19117 (throw 'exit nil))
19118 (setq msg "Creating images for buffer...")))
19119 ((equal arg '(4))
19120 (org-with-limited-levels (org-back-to-heading t))
19121 (let ((beg (point))
19122 (end (progn (org-end-of-subtree t) (point))))
19123 (if (org-remove-latex-fragment-image-overlays beg end)
19124 (progn
19125 (message "LaTeX fragment images removed from subtree")
19126 (throw 'exit nil))
19127 (setq msg "Creating images for subtree...")
19128 (narrow-to-region beg end))))
19129 ((let ((datum (org-element-context)))
19130 (when (memq (org-element-type datum)
19131 '(latex-environment latex-fragment))
19132 (let* ((beg (org-element-property :begin datum))
19133 (end (org-element-property :end datum)))
19134 (if (org-remove-latex-fragment-image-overlays beg end)
19135 (progn (message "LaTeX fragment image removed")
19136 (throw 'exit nil))
19137 (narrow-to-region beg end)
19138 (setq msg "Creating image..."))))))
19140 (org-with-limited-levels
19141 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19142 (outline-previous-heading)
19143 (point)))
19144 (end (progn (outline-next-heading) (point))))
19145 (if (org-remove-latex-fragment-image-overlays beg end)
19146 (progn
19147 (message "LaTeX fragment images removed from section")
19148 (throw 'exit nil))
19149 (setq msg "Creating images for section...")
19150 (narrow-to-region beg end))))))
19151 (let ((file (buffer-file-name (buffer-base-buffer))))
19152 (org-format-latex
19153 (concat org-preview-latex-image-directory "org-ltximg")
19154 ;; Emacs cannot overlay images from remote hosts.
19155 ;; Create it in `temporary-file-directory' instead.
19156 (if (or (not file) (file-remote-p file))
19157 temporary-file-directory
19158 default-directory)
19159 'overlays msg 'forbuffer org-preview-latex-default-process)))
19160 ;; Work around a bug that doesn't restore window's start
19161 ;; when widening back the buffer.
19162 (set-window-start nil window-start)
19163 (message (concat msg "done")))))))
19165 (defun org-format-latex
19166 (prefix &optional dir overlays msg forbuffer processing-type)
19167 "Replace LaTeX fragments with links to an image, and produce images.
19169 When optional argument OVERLAYS is non-nil, display the image on
19170 top of the fragment instead of replacing it.
19172 PROCESSING-TYPE is the conversion method to use, as a symbol.
19174 Some of the options can be changed using the variable
19175 `org-format-latex-options', which see."
19176 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19177 (unless (eq processing-type 'verbatim)
19178 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19179 (cnt 0)
19180 checkdir-flag)
19181 (goto-char (point-min))
19182 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19183 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19184 (overlay-recenter (point-max)))
19185 (while (re-search-forward math-regexp nil t)
19186 (unless (and overlays
19187 (eq (get-char-property (point) 'org-overlay-type)
19188 'org-latex-overlay))
19189 (let* ((context (org-element-context))
19190 (type (org-element-type context)))
19191 (when (memq type '(latex-environment latex-fragment))
19192 (let ((block-type (eq type 'latex-environment))
19193 (value (org-element-property :value context))
19194 (beg (org-element-property :begin context))
19195 (end (save-excursion
19196 (goto-char (org-element-property :end context))
19197 (skip-chars-backward " \r\t\n")
19198 (point))))
19199 (cond
19200 ((eq processing-type 'mathjax)
19201 ;; Prepare for MathJax processing.
19202 (if (not (string-match "\\`\\$\\$?" value))
19203 (goto-char end)
19204 (delete-region beg end)
19205 (if (string= (match-string 0 value) "$$")
19206 (insert "\\[" (substring value 2 -2) "\\]")
19207 (insert "\\(" (substring value 1 -1) "\\)"))))
19208 ((assq processing-type org-preview-latex-process-alist)
19209 ;; Process to an image.
19210 (cl-incf cnt)
19211 (goto-char beg)
19212 (let* ((processing-info
19213 (cdr (assq processing-type org-preview-latex-process-alist)))
19214 (face (face-at-point))
19215 ;; Get the colors from the face at point.
19217 (let ((color (plist-get org-format-latex-options
19218 :foreground)))
19219 (if (and forbuffer (eq color 'auto))
19220 (face-attribute face :foreground nil 'default)
19221 color)))
19223 (let ((color (plist-get org-format-latex-options
19224 :background)))
19225 (if (and forbuffer (eq color 'auto))
19226 (face-attribute face :background nil 'default)
19227 color)))
19228 (hash (sha1 (prin1-to-string
19229 (list org-format-latex-header
19230 org-latex-default-packages-alist
19231 org-latex-packages-alist
19232 org-format-latex-options
19233 forbuffer value fg bg))))
19234 (imagetype (or (plist-get processing-info :image-output-type) "png"))
19235 (absprefix (expand-file-name prefix dir))
19236 (linkfile (format "%s_%s.%s" prefix hash imagetype))
19237 (movefile (format "%s_%s.%s" absprefix hash imagetype))
19238 (sep (and block-type "\n\n"))
19239 (link (concat sep "[[file:" linkfile "]]" sep))
19240 (options
19241 (org-combine-plists
19242 org-format-latex-options
19243 `(:foreground ,fg :background ,bg))))
19244 (when msg (message msg cnt))
19245 (unless checkdir-flag ; Ensure the directory exists.
19246 (setq checkdir-flag t)
19247 (let ((todir (file-name-directory absprefix)))
19248 (unless (file-directory-p todir)
19249 (make-directory todir t))))
19250 (unless (file-exists-p movefile)
19251 (org-create-formula-image
19252 value movefile options forbuffer processing-type))
19253 (if overlays
19254 (progn
19255 (dolist (o (overlays-in beg end))
19256 (when (eq (overlay-get o 'org-overlay-type)
19257 'org-latex-overlay)
19258 (delete-overlay o)))
19259 (org--format-latex-make-overlay beg end movefile imagetype)
19260 (goto-char end))
19261 (delete-region beg end)
19262 (insert
19263 (org-add-props link
19264 (list 'org-latex-src
19265 (replace-regexp-in-string "\"" "" value)
19266 'org-latex-src-embed-type
19267 (if block-type 'paragraph 'character)))))))
19268 ((eq processing-type 'mathml)
19269 ;; Process to MathML.
19270 (unless (org-format-latex-mathml-available-p)
19271 (user-error "LaTeX to MathML converter not configured"))
19272 (cl-incf cnt)
19273 (when msg (message msg cnt))
19274 (goto-char beg)
19275 (delete-region beg end)
19276 (insert (org-format-latex-as-mathml
19277 value block-type prefix dir)))
19279 (error "Unknown conversion process %s for LaTeX fragments"
19280 processing-type)))))))))))
19282 (defun org-create-math-formula (latex-frag &optional mathml-file)
19283 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19284 Use `org-latex-to-mathml-convert-command'. If the conversion is
19285 sucessful, return the portion between \"<math...> </math>\"
19286 elements otherwise return nil. When MATHML-FILE is specified,
19287 write the results in to that file. When invoked as an
19288 interactive command, prompt for LATEX-FRAG, with initial value
19289 set to the current active region and echo the results for user
19290 inspection."
19291 (interactive (list (let ((frag (when (org-region-active-p)
19292 (buffer-substring-no-properties
19293 (region-beginning) (region-end)))))
19294 (read-string "LaTeX Fragment: " frag nil frag))))
19295 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19296 (let* ((tmp-in-file
19297 (let ((file (file-relative-name
19298 (make-temp-name (expand-file-name "ltxmathml-in")))))
19299 (write-region latex-frag nil file)
19300 file))
19301 (tmp-out-file (file-relative-name
19302 (make-temp-name (expand-file-name "ltxmathml-out"))))
19303 (cmd (format-spec
19304 org-latex-to-mathml-convert-command
19305 `((?j . ,(and org-latex-to-mathml-jar-file
19306 (shell-quote-argument
19307 (expand-file-name
19308 org-latex-to-mathml-jar-file))))
19309 (?I . ,(shell-quote-argument tmp-in-file))
19310 (?i . ,latex-frag)
19311 (?o . ,(shell-quote-argument tmp-out-file)))))
19312 mathml shell-command-output)
19313 (when (org-called-interactively-p 'any)
19314 (unless (org-format-latex-mathml-available-p)
19315 (user-error "LaTeX to MathML converter not configured")))
19316 (message "Running %s" cmd)
19317 (setq shell-command-output (shell-command-to-string cmd))
19318 (setq mathml
19319 (when (file-readable-p tmp-out-file)
19320 (with-current-buffer (find-file-noselect tmp-out-file t)
19321 (goto-char (point-min))
19322 (when (re-search-forward
19323 (concat
19324 (regexp-quote
19325 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19326 "[^>]*?>"
19327 "\\(.\\|\n\\)*"
19328 "</math>")
19329 nil t)
19330 (prog1 (match-string 0) (kill-buffer))))))
19331 (cond
19332 (mathml
19333 (setq mathml
19334 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19335 (when mathml-file
19336 (write-region mathml nil mathml-file))
19337 (when (org-called-interactively-p 'any)
19338 (message mathml)))
19339 ((message "LaTeX to MathML conversion failed")
19340 (message shell-command-output)))
19341 (delete-file tmp-in-file)
19342 (when (file-exists-p tmp-out-file)
19343 (delete-file tmp-out-file))
19344 mathml))
19346 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19347 prefix &optional dir)
19348 "Use `org-create-math-formula' but check local cache first."
19349 (let* ((absprefix (expand-file-name prefix dir))
19350 (print-length nil) (print-level nil)
19351 (formula-id (concat
19352 "formula-"
19353 (sha1
19354 (prin1-to-string
19355 (list latex-frag
19356 org-latex-to-mathml-convert-command)))))
19357 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19358 (formula-cache-dir (file-name-directory formula-cache)))
19360 (unless (file-directory-p formula-cache-dir)
19361 (make-directory formula-cache-dir t))
19363 (unless (file-exists-p formula-cache)
19364 (org-create-math-formula latex-frag formula-cache))
19366 (if (file-exists-p formula-cache)
19367 ;; Successful conversion. Return the link to MathML file.
19368 (org-add-props
19369 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19370 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19371 'org-latex-src-embed-type (if latex-frag-type
19372 'paragraph 'character)))
19373 ;; Failed conversion. Return the LaTeX fragment verbatim
19374 latex-frag)))
19376 (declare-function org-export-get-backend "ox" (name))
19377 (declare-function org-export--get-global-options "ox" (&optional backend))
19378 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19379 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19380 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19381 (defun org-create-formula--latex-header ()
19382 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19383 (let ((info (org-combine-plists (org-export--get-global-options
19384 (org-export-get-backend 'latex))
19385 (org-export--get-inbuffer-options
19386 (org-export-get-backend 'latex)))))
19387 (org-latex-guess-babel-language
19388 (org-latex-guess-inputenc
19389 (org-splice-latex-header
19390 org-format-latex-header
19391 org-latex-default-packages-alist
19392 org-latex-packages-alist t
19393 (plist-get info :latex-header)))
19394 info)))
19396 (defun org--get-display-dpi ()
19397 "Get the DPI of the display.
19399 Assumes that the display has the same pixel width in the
19400 horizontal and vertical directions."
19401 (if (display-graphic-p)
19402 (round (/ (display-pixel-height)
19403 (/ (display-mm-height) 25.4)))
19404 (error "Attempt to calculate the dpi of a non-graphic display")))
19406 (defun org-create-formula-image
19407 (string tofile options buffer &optional processing-type)
19408 "Create an image from LaTeX source using external processes.
19410 The LaTeX STRING is saved to a temporary LaTeX file, then
19411 converted to an image file by process PROCESSING-TYPE defined in
19412 `org-preview-latex-process-alist'. A nil value defaults to
19413 `org-preview-latex-default-process'.
19415 The generated image file is eventually moved to TOFILE.
19417 The OPTIONS argument controls the size, foreground color and
19418 background color of the generated image.
19420 When BUFFER non-nil, this function is used for LaTeX previewing.
19421 Otherwise, it is used to deal with LaTeX snippets showed in
19422 a HTML file."
19423 (let* ((processing-type (or processing-type
19424 org-preview-latex-default-process))
19425 (processing-info
19426 (cdr (assq processing-type org-preview-latex-process-alist)))
19427 (programs (plist-get processing-info :programs))
19428 (error-message (or (plist-get processing-info :message) ""))
19429 (use-xcolor (plist-get processing-info :use-xcolor))
19430 (image-input-type (plist-get processing-info :image-input-type))
19431 (image-output-type (plist-get processing-info :image-output-type))
19432 (post-clean (or (plist-get processing-info :post-clean)
19433 '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log"
19434 ".svg" ".png" ".jpg" ".jpeg" ".out")))
19435 (latex-header (or (plist-get processing-info :latex-header)
19436 (org-create-formula--latex-header)))
19437 (latex-compiler (plist-get processing-info :latex-compiler))
19438 (image-converter (plist-get processing-info :image-converter))
19439 (tmpdir temporary-file-directory)
19440 (texfilebase (make-temp-name
19441 (expand-file-name "orgtex" tmpdir)))
19442 (texfile (concat texfilebase ".tex"))
19443 (font-height (face-attribute 'default :height nil))
19444 (image-size-adjust (or (plist-get processing-info :image-size-adjust)
19445 '(1.0 . 1.0)))
19446 (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust))
19447 (or (plist-get options (if buffer :scale :html-scale)) 1.0)))
19448 (dpi (* scale (floor (if buffer font-height 140.0))))
19449 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19450 "Black"))
19451 (bg (or (plist-get options (if buffer :background :html-background))
19452 "Transparent"))
19453 (log-buf (get-buffer-create "*Org Preview LaTeX Output*"))
19454 (resize-mini-windows nil)) ;Fix Emacs flicker when creating image.
19455 (dolist (program programs)
19456 (org-check-external-command program error-message))
19457 (if use-xcolor
19458 (progn (if (eq fg 'default)
19459 (setq fg (org-latex-color :foreground))
19460 (setq fg (org-latex-color-format fg)))
19461 (if (eq bg 'default)
19462 (setq bg (org-latex-color :background))
19463 (setq bg (org-latex-color-format
19464 (if (string= bg "Transparent") "white" bg))))
19465 (with-temp-file texfile
19466 (insert latex-header)
19467 (insert "\n\\begin{document}\n"
19468 "\\definecolor{fg}{rgb}{" fg "}\n"
19469 "\\definecolor{bg}{rgb}{" bg "}\n"
19470 "\n\\pagecolor{bg}\n"
19471 "\n{\\color{fg}\n"
19472 string
19473 "\n}\n"
19474 "\n\\end{document}\n")))
19475 (if (eq fg 'default)
19476 (setq fg (org-dvipng-color :foreground))
19477 (unless (string= fg "Transparent")
19478 (setq fg (org-dvipng-color-format fg))))
19479 (if (eq bg 'default)
19480 (setq bg (org-dvipng-color :background))
19481 (unless (string= bg "Transparent")
19482 (setq bg (org-dvipng-color-format bg))))
19483 (with-temp-file texfile
19484 (insert latex-header)
19485 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19487 (let* ((err-msg (format "Please adjust '%s' part of \
19488 `org-preview-latex-process-alist'."
19489 processing-type))
19490 (image-input-file
19491 (org-compile-file
19492 texfile latex-compiler image-input-type err-msg log-buf))
19493 (image-output-file
19494 (org-compile-file
19495 image-input-file image-converter image-output-type err-msg log-buf
19496 `((?F . ,(shell-quote-argument fg))
19497 (?B . ,(shell-quote-argument bg))
19498 (?D . ,(shell-quote-argument (format "%s" dpi)))
19499 (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0))))))))
19500 (copy-file image-output-file tofile 'replace)
19501 (dolist (e post-clean)
19502 (when (file-exists-p (concat texfilebase e))
19503 (delete-file (concat texfilebase e))))
19504 image-output-file)))
19506 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19507 "Fill a LaTeX header template TPL.
19508 In the template, the following place holders will be recognized:
19510 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19511 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19512 [PACKAGES] \\usepackage statements for PKG
19513 [NO-PACKAGES] do not include PKG
19514 [EXTRA] the string EXTRA
19515 [NO-EXTRA] do not include EXTRA
19517 For backward compatibility, if both the positive and the negative place
19518 holder is missing, the positive one (without the \"NO-\") will be
19519 assumed to be present at the end of the template.
19520 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19521 EXTRA is a string.
19522 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19523 (let (rpl (end ""))
19524 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19525 (setq rpl (if (or (match-end 1) (not def-pkg))
19526 "" (org-latex-packages-to-string def-pkg snippets-p t))
19527 tpl (replace-match rpl t t tpl))
19528 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19530 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19531 (setq rpl (if (or (match-end 1) (not pkg))
19532 "" (org-latex-packages-to-string pkg snippets-p t))
19533 tpl (replace-match rpl t t tpl))
19534 (when pkg (setq end
19535 (concat end "\n"
19536 (org-latex-packages-to-string pkg snippets-p)))))
19538 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19539 (setq rpl (if (or (match-end 1) (not extra))
19540 "" (concat extra "\n"))
19541 tpl (replace-match rpl t t tpl))
19542 (when (and extra (string-match "\\S-" extra))
19543 (setq end (concat end "\n" extra))))
19545 (if (string-match "\\S-" end)
19546 (concat tpl "\n" end)
19547 tpl)))
19549 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19550 "Turn an alist of packages into a string with the \\usepackage macros."
19551 (setq pkg (mapconcat (lambda(p)
19552 (cond
19553 ((stringp p) p)
19554 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19555 (format "%% Package %s omitted" (cadr p)))
19556 ((equal "" (car p))
19557 (format "\\usepackage{%s}" (cadr p)))
19559 (format "\\usepackage[%s]{%s}"
19560 (car p) (cadr p)))))
19562 "\n"))
19563 (if newline (concat pkg "\n") pkg))
19565 (defun org-dvipng-color (attr)
19566 "Return a RGB color specification for dvipng."
19567 (apply #'format "rgb %s %s %s"
19568 (mapcar #'org-normalize-color
19569 (color-values (face-attribute 'default attr nil)))))
19571 (defun org-dvipng-color-format (color-name)
19572 "Convert COLOR-NAME to a RGB color value for dvipng."
19573 (apply 'format "rgb %s %s %s"
19574 (mapcar 'org-normalize-color
19575 (color-values color-name))))
19577 (defun org-latex-color (attr)
19578 "Return a RGB color for the LaTeX color package."
19579 (apply #'format "%s,%s,%s"
19580 (mapcar #'org-normalize-color
19581 (color-values (face-attribute 'default attr nil)))))
19583 (defun org-latex-color-format (color-name)
19584 "Convert COLOR-NAME to a RGB color value."
19585 (apply 'format "%s,%s,%s"
19586 (mapcar 'org-normalize-color
19587 (color-values color-name))))
19589 (defun org-normalize-color (value)
19590 "Return string to be used as color value for an RGB component."
19591 (format "%g" (/ value 65535.0)))
19595 ;; Image display
19597 (defvar-local org-inline-image-overlays nil)
19599 (defun org-toggle-inline-images (&optional include-linked)
19600 "Toggle the display of inline images.
19601 INCLUDE-LINKED is passed to `org-display-inline-images'."
19602 (interactive "P")
19603 (if org-inline-image-overlays
19604 (progn
19605 (org-remove-inline-images)
19606 (when (org-called-interactively-p 'interactive)
19607 (message "Inline image display turned off")))
19608 (org-display-inline-images include-linked)
19609 (when (org-called-interactively-p 'interactive)
19610 (message (if org-inline-image-overlays
19611 (format "%d images displayed inline"
19612 (length org-inline-image-overlays))
19613 "No images to display inline")))))
19615 (defun org-redisplay-inline-images ()
19616 "Refresh the display of inline images."
19617 (interactive)
19618 (if (not org-inline-image-overlays)
19619 (org-toggle-inline-images)
19620 (org-toggle-inline-images)
19621 (org-toggle-inline-images)))
19623 (defun org-display-inline-images (&optional include-linked refresh beg end)
19624 "Display inline images.
19626 An inline image is a link which follows either of these
19627 conventions:
19629 1. Its path is a file with an extension matching return value
19630 from `image-file-name-regexp' and it has no contents.
19632 2. Its description consists in a single link of the previous
19633 type.
19635 When optional argument INCLUDE-LINKED is non-nil, also links with
19636 a text description part will be inlined. This can be nice for
19637 a quick look at those images, but it does not reflect what
19638 exported files will look like.
19640 When optional argument REFRESH is non-nil, refresh existing
19641 images between BEG and END. This will create new image displays
19642 only if necessary. BEG and END default to the buffer
19643 boundaries."
19644 (interactive "P")
19645 (when (display-graphic-p)
19646 (unless refresh
19647 (org-remove-inline-images)
19648 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19649 (org-with-wide-buffer
19650 (goto-char (or beg (point-min)))
19651 (let ((case-fold-search t)
19652 (file-extension-re (image-file-name-regexp)))
19653 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19654 (let ((link (save-match-data (org-element-context))))
19655 ;; Check if we're at an inline image.
19656 (when (and (equal (org-element-property :type link) "file")
19657 (or include-linked
19658 (not (org-element-property :contents-begin link)))
19659 (let ((parent (org-element-property :parent link)))
19660 (or (not (eq (org-element-type parent) 'link))
19661 (not (cdr (org-element-contents parent)))))
19662 (org-string-match-p file-extension-re
19663 (org-element-property :path link)))
19664 (let ((file (expand-file-name
19665 (org-link-unescape
19666 (org-element-property :path link)))))
19667 (when (file-exists-p file)
19668 (let ((width
19669 ;; Apply `org-image-actual-width' specifications.
19670 (cond
19671 ((not (image-type-available-p 'imagemagick)) nil)
19672 ((eq org-image-actual-width t) nil)
19673 ((listp org-image-actual-width)
19675 ;; First try to find a width among
19676 ;; attributes associated to the paragraph
19677 ;; containing link.
19678 (let ((paragraph
19679 (let ((e link))
19680 (while (and (setq e (org-element-property
19681 :parent e))
19682 (not (eq (org-element-type e)
19683 'paragraph))))
19684 e)))
19685 (when paragraph
19686 (save-excursion
19687 (goto-char (org-element-property :begin paragraph))
19688 (when
19689 (re-search-forward
19690 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19691 (org-element-property
19692 :post-affiliated paragraph)
19694 (string-to-number (match-string 1))))))
19695 ;; Otherwise, fall-back to provided number.
19696 (car org-image-actual-width)))
19697 ((numberp org-image-actual-width)
19698 org-image-actual-width)))
19699 (old (get-char-property-and-overlay
19700 (org-element-property :begin link)
19701 'org-image-overlay)))
19702 (if (and (car-safe old) refresh)
19703 (image-refresh (overlay-get (cdr old) 'display))
19704 (let ((image (create-image file
19705 (and width 'imagemagick)
19707 :width width)))
19708 (when image
19709 (let* ((link
19710 ;; If inline image is the description
19711 ;; of another link, be sure to
19712 ;; consider the latter as the one to
19713 ;; apply the overlay on.
19714 (let ((parent
19715 (org-element-property :parent link)))
19716 (if (eq (org-element-type parent) 'link)
19717 parent
19718 link)))
19719 (ov (make-overlay
19720 (org-element-property :begin link)
19721 (progn
19722 (goto-char
19723 (org-element-property :end link))
19724 (skip-chars-backward " \t")
19725 (point)))))
19726 (overlay-put ov 'display image)
19727 (overlay-put ov 'face 'default)
19728 (overlay-put ov 'org-image-overlay t)
19729 (overlay-put
19730 ov 'modification-hooks
19731 (list 'org-display-inline-remove-overlay))
19732 (push ov org-inline-image-overlays)))))))))))))))
19734 (define-obsolete-function-alias
19735 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19737 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19738 "Remove inline-display overlay if a corresponding region is modified."
19739 (let ((inhibit-modification-hooks t))
19740 (when (and ov after)
19741 (delete ov org-inline-image-overlays)
19742 (delete-overlay ov))))
19744 (defun org-remove-inline-images ()
19745 "Remove inline display of images."
19746 (interactive)
19747 (mapc #'delete-overlay org-inline-image-overlays)
19748 (setq org-inline-image-overlays nil))
19750 ;;;; Key bindings
19752 ;; Outline functions from `outline-mode-prefix-map'
19753 ;; that can be remapped in Org:
19754 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19755 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19756 (define-key org-mode-map [remap outline-forward-same-level]
19757 'org-forward-heading-same-level)
19758 (define-key org-mode-map [remap outline-backward-same-level]
19759 'org-backward-heading-same-level)
19760 (define-key org-mode-map [remap outline-show-branches]
19761 'org-kill-note-or-show-branches)
19762 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19763 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19764 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19765 (define-key org-mode-map [remap outline-next-visible-heading]
19766 'org-next-visible-heading)
19767 (define-key org-mode-map [remap outline-previous-visible-heading]
19768 'org-previous-visible-heading)
19769 (define-key org-mode-map [remap show-children] 'org-show-children)
19771 ;; Outline functions from `outline-mode-prefix-map' that can not
19772 ;; be remapped in Org:
19774 ;; - the column "key binding" shows whether the Outline function is still
19775 ;; available in Org mode on the same key that it has been bound to in
19776 ;; Outline mode:
19777 ;; - "overridden": key used for a different functionality in Org mode
19778 ;; - else: key still bound to the same Outline function in Org mode
19780 ;; | Outline function | key binding | Org replacement |
19781 ;; |------------------------------------+-------------+--------------------------|
19782 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19783 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19784 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19785 ;; | `show-entry' | overridden | no replacement |
19786 ;; | `show-branches' | `C-c C-k' | still same function |
19787 ;; | `show-subtree' | overridden | visibility cycling |
19788 ;; | `show-all' | overridden | no replacement |
19789 ;; | `hide-subtree' | overridden | visibility cycling |
19790 ;; | `hide-body' | overridden | no replacement |
19791 ;; | `hide-entry' | overridden | visibility cycling |
19792 ;; | `hide-leaves' | overridden | no replacement |
19793 ;; | `hide-sublevels' | overridden | no replacement |
19794 ;; | `hide-other' | overridden | no replacement |
19796 ;; Make `C-c C-x' a prefix key
19797 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19799 ;; TAB key with modifiers
19800 (org-defkey org-mode-map "\C-i" 'org-cycle)
19801 (org-defkey org-mode-map [(tab)] 'org-cycle)
19802 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19803 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19804 ;; The following line is necessary under Suse GNU/Linux
19805 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab)
19806 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19807 (define-key org-mode-map [backtab] 'org-shifttab)
19809 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19810 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19811 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19813 ;; Cursor keys with modifiers
19814 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19815 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19816 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19817 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19819 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19820 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19821 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19822 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19823 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19824 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19826 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19827 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19828 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19829 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19831 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19832 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19833 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19834 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19836 ;; Babel keys
19837 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19838 (dolist (pair org-babel-key-bindings)
19839 (define-key org-babel-map (car pair) (cdr pair)))
19841 ;;; Extra keys for tty access.
19842 ;; We only set them when really needed because otherwise the
19843 ;; menus don't show the simple keys
19845 (when (or org-use-extra-keys (not window-system))
19846 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19847 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19848 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19849 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19850 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19851 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19852 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19853 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19854 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19855 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19856 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19857 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19858 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19859 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19860 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19861 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19862 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19863 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19864 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19865 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19866 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19867 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19868 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19869 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19870 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19871 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19872 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19873 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19875 ;; All the other keys
19877 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19878 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19879 (if (boundp 'narrow-map)
19880 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19881 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19882 (if (boundp 'narrow-map)
19883 (org-defkey narrow-map "b" 'org-narrow-to-block)
19884 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19885 (if (boundp 'narrow-map)
19886 (org-defkey narrow-map "e" 'org-narrow-to-element)
19887 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19888 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19889 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19890 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19891 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19892 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19893 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19894 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19895 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19896 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19897 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19898 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19899 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19900 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19901 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19902 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19903 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19904 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19905 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19906 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19907 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19908 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19909 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19910 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19911 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19912 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19913 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19914 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19915 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19916 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19917 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19918 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19919 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19920 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19921 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19922 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19923 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19924 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19925 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19926 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19927 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19928 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19929 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19930 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19931 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19932 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19933 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19934 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19935 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19936 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19937 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19938 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19939 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19940 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19941 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19942 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19943 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19944 (org-defkey org-mode-map "\C-c^" 'org-sort)
19945 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19946 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19947 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19948 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19949 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19950 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19951 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19952 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19953 (org-defkey org-mode-map "\C-m" 'org-return)
19954 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19955 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19956 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19957 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19958 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19959 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19960 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19961 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19962 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19963 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19964 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19965 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19966 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19967 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19968 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19969 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19970 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19971 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19972 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19973 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19974 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19975 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19976 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19977 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19978 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19980 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19981 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19982 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19984 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19985 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19986 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19987 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19988 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19989 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19990 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19991 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19992 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19993 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19994 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19995 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19996 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19997 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19998 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19999 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
20000 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
20001 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
20002 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
20003 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
20004 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
20005 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
20007 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20008 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20009 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20010 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20011 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20013 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20015 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20017 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20018 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20020 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20023 (defconst org-speed-commands-default
20025 ("Outline Navigation")
20026 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20027 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20028 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20029 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20030 ("F" . org-next-block)
20031 ("B" . org-previous-block)
20032 ("u" . (org-speed-move-safe 'outline-up-heading))
20033 ("j" . org-goto)
20034 ("g" . (org-refile t))
20035 ("Outline Visibility")
20036 ("c" . org-cycle)
20037 ("C" . org-shifttab)
20038 (" " . org-display-outline-path)
20039 ("s" . org-narrow-to-subtree)
20040 ("=" . org-columns)
20041 ("Outline Structure Editing")
20042 ("U" . org-metaup)
20043 ("D" . org-metadown)
20044 ("r" . org-metaright)
20045 ("l" . org-metaleft)
20046 ("R" . org-shiftmetaright)
20047 ("L" . org-shiftmetaleft)
20048 ("i" . (progn (forward-char 1) (call-interactively
20049 'org-insert-heading-respect-content)))
20050 ("^" . org-sort)
20051 ("w" . org-refile)
20052 ("a" . org-archive-subtree-default-with-confirmation)
20053 ("@" . org-mark-subtree)
20054 ("#" . org-toggle-comment)
20055 ("Clock Commands")
20056 ("I" . org-clock-in)
20057 ("O" . org-clock-out)
20058 ("Meta Data Editing")
20059 ("t" . org-todo)
20060 ("," . (org-priority))
20061 ("0" . (org-priority ?\ ))
20062 ("1" . (org-priority ?A))
20063 ("2" . (org-priority ?B))
20064 ("3" . (org-priority ?C))
20065 (":" . org-set-tags-command)
20066 ("e" . org-set-effort)
20067 ("E" . org-inc-effort)
20068 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20069 (org-entry-put (point) "APPT_WARNTIME" m)))
20070 ("Agenda Views etc")
20071 ("v" . org-agenda)
20072 ("/" . org-sparse-tree)
20073 ("Misc")
20074 ("o" . org-open-at-point)
20075 ("?" . org-speed-command-help)
20076 ("<" . (org-agenda-set-restriction-lock 'subtree))
20077 (">" . (org-agenda-remove-restriction-lock))
20079 "The default speed commands.")
20081 (defun org-print-speed-command (e)
20082 (if (> (length (car e)) 1)
20083 (progn
20084 (princ "\n")
20085 (princ (car e))
20086 (princ "\n")
20087 (princ (make-string (length (car e)) ?-))
20088 (princ "\n"))
20089 (princ (car e))
20090 (princ " ")
20091 (if (symbolp (cdr e))
20092 (princ (symbol-name (cdr e)))
20093 (prin1 (cdr e)))
20094 (princ "\n")))
20096 (defun org-speed-command-help ()
20097 "Show the available speed commands."
20098 (interactive)
20099 (if (not org-use-speed-commands)
20100 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20101 (with-output-to-temp-buffer "*Help*"
20102 (princ "User-defined Speed commands\n===========================\n")
20103 (mapc #'org-print-speed-command org-speed-commands-user)
20104 (princ "\n")
20105 (princ "Built-in Speed commands\n=======================\n")
20106 (mapc #'org-print-speed-command org-speed-commands-default))
20107 (with-current-buffer "*Help*"
20108 (setq truncate-lines t))))
20110 (defun org-speed-move-safe (cmd)
20111 "Execute CMD, but make sure that the cursor always ends up in a headline.
20112 If not, return to the original position and throw an error."
20113 (interactive)
20114 (let ((pos (point)))
20115 (call-interactively cmd)
20116 (unless (and (bolp) (org-at-heading-p))
20117 (goto-char pos)
20118 (error "Boundary reached while executing %s" cmd))))
20120 (defvar org-self-insert-command-undo-counter 0)
20122 (defvar org-table-auto-blank-field) ; defined in org-table.el
20123 (defvar org-speed-command nil)
20125 (define-obsolete-function-alias
20126 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20128 (defun org-speed-command-activate (keys)
20129 "Hook for activating single-letter speed commands.
20130 `org-speed-commands-default' specifies a minimal command set.
20131 Use `org-speed-commands-user' for further customization."
20132 (when (or (and (bolp) (looking-at org-outline-regexp))
20133 (and (functionp org-use-speed-commands)
20134 (funcall org-use-speed-commands)))
20135 (cdr (assoc keys (append org-speed-commands-user
20136 org-speed-commands-default)))))
20138 (define-obsolete-function-alias
20139 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20141 (defun org-babel-speed-command-activate (keys)
20142 "Hook for activating single-letter code block commands."
20143 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20144 (cdr (assoc keys org-babel-key-bindings))))
20146 (defcustom org-speed-command-hook
20147 '(org-speed-command-default-hook org-babel-speed-command-hook)
20148 "Hook for activating speed commands at strategic locations.
20149 Hook functions are called in sequence until a valid handler is
20150 found.
20152 Each hook takes a single argument, a user-pressed command key
20153 which is also a `self-insert-command' from the global map.
20155 Within the hook, examine the cursor position and the command key
20156 and return nil or a valid handler as appropriate. Handler could
20157 be one of an interactive command, a function, or a form.
20159 Set `org-use-speed-commands' to non-nil value to enable this
20160 hook. The default setting is `org-speed-command-activate'."
20161 :group 'org-structure
20162 :version "24.1"
20163 :type 'hook)
20165 (defun org-self-insert-command (N)
20166 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20167 If the cursor is in a table looking at whitespace, the whitespace is
20168 overwritten, and the table is not marked as requiring realignment."
20169 (interactive "p")
20170 (org-check-before-invisible-edit 'insert)
20171 (cond
20172 ((and org-use-speed-commands
20173 (let ((kv (this-command-keys-vector)))
20174 (setq org-speed-command
20175 (run-hook-with-args-until-success
20176 'org-speed-command-hook
20177 (make-string 1 (aref kv (1- (length kv))))))))
20178 (cond
20179 ((commandp org-speed-command)
20180 (setq this-command org-speed-command)
20181 (call-interactively org-speed-command))
20182 ((functionp org-speed-command)
20183 (funcall org-speed-command))
20184 ((and org-speed-command (listp org-speed-command))
20185 (eval org-speed-command))
20186 (t (let (org-use-speed-commands)
20187 (call-interactively 'org-self-insert-command)))))
20188 ((and
20189 (org-at-table-p)
20190 (progn
20191 ;; Check if we blank the field, and if that triggers align.
20192 (and (featurep 'org-table) org-table-auto-blank-field
20193 (memq last-command
20194 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20195 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20196 ;; Got extra space, this field does not determine
20197 ;; column width.
20198 (let (org-table-may-need-update) (org-table-blank-field))
20199 ;; No extra space, this field may determine column
20200 ;; width.
20201 (org-table-blank-field)))
20203 (eq N 1)
20204 (looking-at "[^|\n]* \\( \\)|"))
20205 ;; There is room for insertion without re-aligning the table.
20206 (delete-region (match-beginning 1) (match-end 1))
20207 (self-insert-command N))
20209 (setq org-table-may-need-update t)
20210 (self-insert-command N)
20211 (org-fix-tags-on-the-fly)
20212 (when org-self-insert-cluster-for-undo
20213 (if (not (eq last-command 'org-self-insert-command))
20214 (setq org-self-insert-command-undo-counter 1)
20215 (if (>= org-self-insert-command-undo-counter 20)
20216 (setq org-self-insert-command-undo-counter 1)
20217 (and (> org-self-insert-command-undo-counter 0)
20218 buffer-undo-list (listp buffer-undo-list)
20219 (not (cadr buffer-undo-list)) ; remove nil entry
20220 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20221 (setq org-self-insert-command-undo-counter
20222 (1+ org-self-insert-command-undo-counter))))))))
20224 (defun org-check-before-invisible-edit (kind)
20225 "Check is editing if kind KIND would be dangerous with invisible text around.
20226 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20227 ;; First, try to get out of here as quickly as possible, to reduce overhead
20228 (when (and org-catch-invisible-edits
20229 (or (not (boundp 'visible-mode)) (not visible-mode))
20230 (or (get-char-property (point) 'invisible)
20231 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20232 ;; OK, we need to take a closer look
20233 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20234 (invisible-before-point (unless (bobp) (get-char-property
20235 (1- (point)) 'invisible)))
20236 (border-and-ok-direction
20238 ;; Check if we are acting predictably before invisible text
20239 (and invisible-at-point (not invisible-before-point)
20240 (memq kind '(insert delete-backward)))
20241 ;; Check if we are acting predictably after invisible text
20242 ;; This works not well, and I have turned it off. It seems
20243 ;; better to always show and stop after invisible text.
20244 ;; (and (not invisible-at-point) invisible-before-point
20245 ;; (memq kind '(insert delete)))
20247 (when (or (memq invisible-at-point '(outline org-hide-block t))
20248 (memq invisible-before-point '(outline org-hide-block t)))
20249 (when (eq org-catch-invisible-edits 'error)
20250 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20251 (if (and org-custom-properties-overlays
20252 (y-or-n-p "Display invisible properties in this buffer? "))
20253 (org-toggle-custom-properties-visibility)
20254 ;; Make the area visible
20255 (save-excursion
20256 (when invisible-before-point
20257 (goto-char (previous-single-char-property-change
20258 (point) 'invisible)))
20259 (outline-show-subtree))
20260 (cond
20261 ((eq org-catch-invisible-edits 'show)
20262 ;; That's it, we do the edit after showing
20263 (message
20264 "Unfolding invisible region around point before editing")
20265 (sit-for 1))
20266 ((and (eq org-catch-invisible-edits 'smart)
20267 border-and-ok-direction)
20268 (message "Unfolding invisible region around point before editing"))
20270 ;; Don't do the edit, make the user repeat it in full visibility
20271 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20273 (defun org-fix-tags-on-the-fly ()
20274 (when (and (equal (char-after (point-at-bol)) ?*)
20275 (org-at-heading-p))
20276 (org-align-tags-here org-tags-column)))
20278 (defun org-delete-backward-char (N)
20279 "Like `delete-backward-char', insert whitespace at field end in tables.
20280 When deleting backwards, in tables this function will insert whitespace in
20281 front of the next \"|\" separator, to keep the table aligned. The table will
20282 still be marked for re-alignment if the field did fill the entire column,
20283 because, in this case the deletion might narrow the column."
20284 (interactive "p")
20285 (save-match-data
20286 (org-check-before-invisible-edit 'delete-backward)
20287 (if (and (org-at-table-p)
20288 (eq N 1)
20289 (string-match "|" (buffer-substring (point-at-bol) (point)))
20290 (looking-at ".*?|"))
20291 (let ((pos (point))
20292 (noalign (looking-at "[^|\n\r]* |"))
20293 (c org-table-may-need-update))
20294 (backward-delete-char N)
20295 (unless overwrite-mode
20296 (skip-chars-forward "^|")
20297 (insert " ")
20298 (goto-char (1- pos)))
20299 ;; noalign: if there were two spaces at the end, this field
20300 ;; does not determine the width of the column.
20301 (when noalign (setq org-table-may-need-update c)))
20302 (backward-delete-char N)
20303 (org-fix-tags-on-the-fly))))
20305 (defun org-delete-char (N)
20306 "Like `delete-char', but insert whitespace at field end in tables.
20307 When deleting characters, in tables this function will insert whitespace in
20308 front of the next \"|\" separator, to keep the table aligned. The table will
20309 still be marked for re-alignment if the field did fill the entire column,
20310 because, in this case the deletion might narrow the column."
20311 (interactive "p")
20312 (save-match-data
20313 (org-check-before-invisible-edit 'delete)
20314 (if (and (org-at-table-p)
20315 (not (bolp))
20316 (not (= (char-after) ?|))
20317 (eq N 1))
20318 (if (looking-at ".*?|")
20319 (let ((pos (point))
20320 (noalign (looking-at "[^|\n\r]* |"))
20321 (c org-table-may-need-update))
20322 (replace-match
20323 (concat (substring (match-string 0) 1 -1) " |") nil t)
20324 (goto-char pos)
20325 ;; noalign: if there were two spaces at the end, this field
20326 ;; does not determine the width of the column.
20327 (when noalign (setq org-table-may-need-update c)))
20328 (delete-char N))
20329 (delete-char N)
20330 (org-fix-tags-on-the-fly))))
20332 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20333 (put 'org-self-insert-command 'delete-selection
20334 (lambda ()
20335 (not (run-hook-with-args-until-success
20336 'self-insert-uses-region-functions))))
20337 (put 'orgtbl-self-insert-command 'delete-selection
20338 (lambda ()
20339 (not (run-hook-with-args-until-success
20340 'self-insert-uses-region-functions))))
20341 (put 'org-delete-char 'delete-selection 'supersede)
20342 (put 'org-delete-backward-char 'delete-selection 'supersede)
20343 (put 'org-yank 'delete-selection 'yank)
20345 ;; Make `flyspell-mode' delay after some commands
20346 (put 'org-self-insert-command 'flyspell-delayed t)
20347 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20348 (put 'org-delete-char 'flyspell-delayed t)
20349 (put 'org-delete-backward-char 'flyspell-delayed t)
20351 ;; Make pabbrev-mode expand after org-mode commands
20352 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20353 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20355 (defun org-remap (map &rest commands)
20356 "In MAP, remap the functions given in COMMANDS.
20357 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20358 (let (new old)
20359 (while commands
20360 (setq old (pop commands) new (pop commands))
20361 (if (fboundp 'command-remapping)
20362 (org-defkey map (vector 'remap old) new)
20363 (substitute-key-definition old new map global-map)))))
20365 (defun org-transpose-words ()
20366 "Transpose words for Org.
20367 This uses the `org-mode-transpose-word-syntax-table' syntax
20368 table, which interprets characters in `org-emphasis-alist' as
20369 word constituents."
20370 (interactive)
20371 (with-syntax-table org-mode-transpose-word-syntax-table
20372 (call-interactively 'transpose-words)))
20373 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20375 (when (eq org-enable-table-editor 'optimized)
20376 ;; If the user wants maximum table support, we need to hijack
20377 ;; some standard editing functions
20378 (org-remap org-mode-map
20379 'self-insert-command 'org-self-insert-command
20380 'delete-char 'org-delete-char
20381 'delete-backward-char 'org-delete-backward-char)
20382 (org-defkey org-mode-map "|" 'org-force-self-insert))
20384 (defvar org-ctrl-c-ctrl-c-hook nil
20385 "Hook for functions attaching themselves to `C-c C-c'.
20387 This can be used to add additional functionality to the C-c C-c
20388 key which executes context-dependent commands. This hook is run
20389 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20390 run after the last test.
20392 Each function will be called with no arguments. The function
20393 must check if the context is appropriate for it to act. If yes,
20394 it should do its thing and then return a non-nil value. If the
20395 context is wrong, just do nothing and return nil.")
20397 (defvar org-ctrl-c-ctrl-c-final-hook nil
20398 "Hook for functions attaching themselves to `C-c C-c'.
20400 This can be used to add additional functionality to the C-c C-c
20401 key which executes context-dependent commands. This hook is run
20402 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20403 before the first test.
20405 Each function will be called with no arguments. The function
20406 must check if the context is appropriate for it to act. If yes,
20407 it should do its thing and then return a non-nil value. If the
20408 context is wrong, just do nothing and return nil.")
20410 (defvar org-tab-first-hook nil
20411 "Hook for functions to attach themselves to TAB.
20412 See `org-ctrl-c-ctrl-c-hook' for more information.
20413 This hook runs as the first action when TAB is pressed, even before
20414 `org-cycle' messes around with the `outline-regexp' to cater for
20415 inline tasks and plain list item folding.
20416 If any function in this hook returns t, any other actions that
20417 would have been caused by TAB (such as table field motion or visibility
20418 cycling) will not occur.")
20420 (defvar org-tab-after-check-for-table-hook nil
20421 "Hook for functions to attach themselves to TAB.
20422 See `org-ctrl-c-ctrl-c-hook' for more information.
20423 This hook runs after it has been established that the cursor is not in a
20424 table, but before checking if the cursor is in a headline or if global cycling
20425 should be done.
20426 If any function in this hook returns t, not other actions like visibility
20427 cycling will be done.")
20429 (defvar org-tab-after-check-for-cycling-hook nil
20430 "Hook for functions to attach themselves to TAB.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.
20432 This hook runs after it has been established that not table field motion and
20433 not visibility should be done because of current context. This is probably
20434 the place where a package like yasnippets can hook in.")
20436 (defvar org-tab-before-tab-emulation-hook nil
20437 "Hook for functions to attach themselves to TAB.
20438 See `org-ctrl-c-ctrl-c-hook' for more information.
20439 This hook runs after every other options for TAB have been exhausted, but
20440 before indentation and \t insertion takes place.")
20442 (defvar org-metaleft-hook nil
20443 "Hook for functions attaching themselves to `M-left'.
20444 See `org-ctrl-c-ctrl-c-hook' for more information.")
20445 (defvar org-metaright-hook nil
20446 "Hook for functions attaching themselves to `M-right'.
20447 See `org-ctrl-c-ctrl-c-hook' for more information.")
20448 (defvar org-metaup-hook nil
20449 "Hook for functions attaching themselves to `M-up'.
20450 See `org-ctrl-c-ctrl-c-hook' for more information.")
20451 (defvar org-metadown-hook nil
20452 "Hook for functions attaching themselves to `M-down'.
20453 See `org-ctrl-c-ctrl-c-hook' for more information.")
20454 (defvar org-shiftmetaleft-hook nil
20455 "Hook for functions attaching themselves to `M-S-left'.
20456 See `org-ctrl-c-ctrl-c-hook' for more information.")
20457 (defvar org-shiftmetaright-hook nil
20458 "Hook for functions attaching themselves to `M-S-right'.
20459 See `org-ctrl-c-ctrl-c-hook' for more information.")
20460 (defvar org-shiftmetaup-hook nil
20461 "Hook for functions attaching themselves to `M-S-up'.
20462 See `org-ctrl-c-ctrl-c-hook' for more information.")
20463 (defvar org-shiftmetadown-hook nil
20464 "Hook for functions attaching themselves to `M-S-down'.
20465 See `org-ctrl-c-ctrl-c-hook' for more information.")
20466 (defvar org-metareturn-hook nil
20467 "Hook for functions attaching themselves to `M-RET'.
20468 See `org-ctrl-c-ctrl-c-hook' for more information.")
20469 (defvar org-shiftup-hook nil
20470 "Hook for functions attaching themselves to `S-up'.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.")
20472 (defvar org-shiftup-final-hook nil
20473 "Hook for functions attaching themselves to `S-up'.
20474 This one runs after all other options except shift-select have been excluded.
20475 See `org-ctrl-c-ctrl-c-hook' for more information.")
20476 (defvar org-shiftdown-hook nil
20477 "Hook for functions attaching themselves to `S-down'.
20478 See `org-ctrl-c-ctrl-c-hook' for more information.")
20479 (defvar org-shiftdown-final-hook nil
20480 "Hook for functions attaching themselves to `S-down'.
20481 This one runs after all other options except shift-select have been excluded.
20482 See `org-ctrl-c-ctrl-c-hook' for more information.")
20483 (defvar org-shiftleft-hook nil
20484 "Hook for functions attaching themselves to `S-left'.
20485 See `org-ctrl-c-ctrl-c-hook' for more information.")
20486 (defvar org-shiftleft-final-hook nil
20487 "Hook for functions attaching themselves to `S-left'.
20488 This one runs after all other options except shift-select have been excluded.
20489 See `org-ctrl-c-ctrl-c-hook' for more information.")
20490 (defvar org-shiftright-hook nil
20491 "Hook for functions attaching themselves to `S-right'.
20492 See `org-ctrl-c-ctrl-c-hook' for more information.")
20493 (defvar org-shiftright-final-hook nil
20494 "Hook for functions attaching themselves to `S-right'.
20495 This one runs after all other options except shift-select have been excluded.
20496 See `org-ctrl-c-ctrl-c-hook' for more information.")
20498 (defun org-modifier-cursor-error ()
20499 "Throw an error, a modified cursor command was applied in wrong context."
20500 (user-error "This command is active in special context like tables, headlines or items"))
20502 (defun org-shiftselect-error ()
20503 "Throw an error because Shift-Cursor command was applied in wrong context."
20504 (if (and (boundp 'shift-select-mode) shift-select-mode)
20505 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20506 (user-error "This command works only in special context like headlines or timestamps")))
20508 (defun org-call-for-shift-select (cmd)
20509 (let ((this-command-keys-shift-translated t))
20510 (call-interactively cmd)))
20512 (defun org-shifttab (&optional arg)
20513 "Global visibility cycling or move to previous table field.
20514 Call `org-table-previous-field' within a table.
20515 When ARG is nil, cycle globally through visibility states.
20516 When ARG is a numeric prefix, show contents of this level."
20517 (interactive "P")
20518 (cond
20519 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20520 ((integerp arg)
20521 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20522 (message "Content view to level: %d" arg)
20523 (org-content (prefix-numeric-value arg2))
20524 (org-cycle-show-empty-lines t)
20525 (setq org-cycle-global-status 'overview)))
20526 (t (call-interactively 'org-global-cycle))))
20528 (defun org-shiftmetaleft ()
20529 "Promote subtree or delete table column.
20530 Calls `org-promote-subtree', `org-outdent-item-tree', or
20531 `org-table-delete-column', depending on context. See the
20532 individual commands for more information."
20533 (interactive)
20534 (cond
20535 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20536 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20537 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20538 ((if (not (org-region-active-p)) (org-at-item-p)
20539 (save-excursion (goto-char (region-beginning))
20540 (org-at-item-p)))
20541 (call-interactively 'org-outdent-item-tree))
20542 (t (org-modifier-cursor-error))))
20544 (defun org-shiftmetaright ()
20545 "Demote subtree or insert table column.
20546 Calls `org-demote-subtree', `org-indent-item-tree', or
20547 `org-table-insert-column', depending on context. See the
20548 individual commands for more information."
20549 (interactive)
20550 (cond
20551 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20552 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20553 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20554 ((if (not (org-region-active-p)) (org-at-item-p)
20555 (save-excursion (goto-char (region-beginning))
20556 (org-at-item-p)))
20557 (call-interactively 'org-indent-item-tree))
20558 (t (org-modifier-cursor-error))))
20560 (defun org-shiftmetaup (&optional _arg)
20561 "Drag the line at point up.
20562 In a table, kill the current row.
20563 On a clock timestamp, update the value of the timestamp like `S-<up>'
20564 but also adjust the previous clocked item in the clock history.
20565 Everywhere else, drag the line at point up."
20566 (interactive "P")
20567 (cond
20568 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20569 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20570 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20571 (call-interactively 'org-timestamp-up)))
20572 (t (call-interactively 'org-drag-line-backward))))
20574 (defun org-shiftmetadown (&optional _arg)
20575 "Drag the line at point down.
20576 In a table, insert an empty row at the current line.
20577 On a clock timestamp, update the value of the timestamp like `S-<down>'
20578 but also adjust the previous clocked item in the clock history.
20579 Everywhere else, drag the line at point down."
20580 (interactive "P")
20581 (cond
20582 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20583 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20584 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20585 (call-interactively 'org-timestamp-down)))
20586 (t (call-interactively 'org-drag-line-forward))))
20588 (defsubst org-hidden-tree-error ()
20589 (user-error
20590 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20592 (defun org-metaleft (&optional _arg)
20593 "Promote heading, list item at point or move table column left.
20595 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20596 depending on context. With no specific context, calls the Emacs
20597 default `backward-word'. See the individual commands for more
20598 information.
20600 This function runs the hook `org-metaleft-hook' as a first step,
20601 and returns at first non-nil value."
20602 (interactive "P")
20603 (cond
20604 ((run-hook-with-args-until-success 'org-metaleft-hook))
20605 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20606 ((org-with-limited-levels
20607 (or (org-at-heading-p)
20608 (and (org-region-active-p)
20609 (save-excursion
20610 (goto-char (region-beginning))
20611 (org-at-heading-p)))))
20612 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20613 (call-interactively 'org-do-promote))
20614 ;; At an inline task.
20615 ((org-at-heading-p)
20616 (call-interactively 'org-inlinetask-promote))
20617 ((or (org-at-item-p)
20618 (and (org-region-active-p)
20619 (save-excursion
20620 (goto-char (region-beginning))
20621 (org-at-item-p))))
20622 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20623 (call-interactively 'org-outdent-item))
20624 (t (call-interactively 'backward-word))))
20626 (defun org-metaright (&optional _arg)
20627 "Demote heading, list item at point or move table column right.
20629 In front of a drawer or a block keyword, indent it correctly.
20631 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20632 `org-indnet-drawer' or `org-indent-block' depending on context.
20633 With no specific context, calls the Emacs default `forward-word'.
20634 See the individual commands for more information.
20636 This function runs the hook `org-metaright-hook' as a first step,
20637 and returns at first non-nil value."
20638 (interactive "P")
20639 (cond
20640 ((run-hook-with-args-until-success 'org-metaright-hook))
20641 ((org-at-table-p) (call-interactively 'org-table-move-column))
20642 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20643 ((org-at-block-p) (call-interactively 'org-indent-block))
20644 ((org-with-limited-levels
20645 (or (org-at-heading-p)
20646 (and (org-region-active-p)
20647 (save-excursion
20648 (goto-char (region-beginning))
20649 (org-at-heading-p)))))
20650 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20651 (call-interactively 'org-do-demote))
20652 ;; At an inline task.
20653 ((org-at-heading-p)
20654 (call-interactively 'org-inlinetask-demote))
20655 ((or (org-at-item-p)
20656 (and (org-region-active-p)
20657 (save-excursion
20658 (goto-char (region-beginning))
20659 (org-at-item-p))))
20660 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20661 (call-interactively 'org-indent-item))
20662 (t (call-interactively 'forward-word))))
20664 (defun org-check-for-hidden (what)
20665 "Check if there are hidden headlines/items in the current visual line.
20666 WHAT can be either `headlines' or `items'. If the current line is
20667 an outline or item heading and it has a folded subtree below it,
20668 this function returns t, nil otherwise."
20669 (let ((re (cond
20670 ((eq what 'headlines) org-outline-regexp-bol)
20671 ((eq what 'items) (org-item-beginning-re))
20672 (t (error "This should not happen"))))
20673 beg end)
20674 (save-excursion
20675 (catch 'exit
20676 (unless (org-region-active-p)
20677 (setq beg (point-at-bol))
20678 (beginning-of-line 2)
20679 (while (and (not (eobp)) ;; this is like `next-line'
20680 (get-char-property (1- (point)) 'invisible))
20681 (beginning-of-line 2))
20682 (setq end (point))
20683 (goto-char beg)
20684 (goto-char (point-at-eol))
20685 (setq end (max end (point)))
20686 (while (re-search-forward re end t)
20687 (when (get-char-property (match-beginning 0) 'invisible)
20688 (throw 'exit t))))
20689 nil))))
20691 (defun org-metaup (&optional _arg)
20692 "Move subtree up or move table row up.
20693 Calls `org-move-subtree-up' or `org-table-move-row' or
20694 `org-move-item-up', depending on context. See the individual commands
20695 for more information."
20696 (interactive "P")
20697 (cond
20698 ((run-hook-with-args-until-success 'org-metaup-hook))
20699 ((org-region-active-p)
20700 (let* ((a (min (region-beginning) (region-end)))
20701 (b (1- (max (region-beginning) (region-end))))
20702 (c (save-excursion (goto-char a)
20703 (move-beginning-of-line 0)))
20704 (d (save-excursion (goto-char a)
20705 (move-end-of-line 0) (point))))
20706 (transpose-regions a b c d)
20707 (goto-char c)))
20708 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20709 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20710 ((org-at-item-p) (call-interactively 'org-move-item-up))
20711 (t (org-drag-element-backward))))
20713 (defun org-metadown (&optional _arg)
20714 "Move subtree down or move table row down.
20715 Calls `org-move-subtree-down' or `org-table-move-row' or
20716 `org-move-item-down', depending on context. See the individual
20717 commands for more information."
20718 (interactive "P")
20719 (cond
20720 ((run-hook-with-args-until-success 'org-metadown-hook))
20721 ((org-region-active-p)
20722 (let* ((a (min (region-beginning) (region-end)))
20723 (b (max (region-beginning) (region-end)))
20724 (c (save-excursion (goto-char b)
20725 (move-beginning-of-line 1)))
20726 (d (save-excursion (goto-char b)
20727 (move-end-of-line 1) (1+ (point)))))
20728 (transpose-regions a b c d)
20729 (goto-char d)))
20730 ((org-at-table-p) (call-interactively 'org-table-move-row))
20731 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20732 ((org-at-item-p) (call-interactively 'org-move-item-down))
20733 (t (org-drag-element-forward))))
20735 (defun org-shiftup (&optional arg)
20736 "Increase item in timestamp or increase priority of current headline.
20737 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20738 depending on context. See the individual commands for more information."
20739 (interactive "P")
20740 (cond
20741 ((run-hook-with-args-until-success 'org-shiftup-hook))
20742 ((and org-support-shift-select (org-region-active-p))
20743 (org-call-for-shift-select 'previous-line))
20744 ((org-at-timestamp-p t)
20745 (call-interactively (if org-edit-timestamp-down-means-later
20746 'org-timestamp-down 'org-timestamp-up)))
20747 ((and (not (eq org-support-shift-select 'always))
20748 org-enable-priority-commands
20749 (org-at-heading-p))
20750 (call-interactively 'org-priority-up))
20751 ((and (not org-support-shift-select) (org-at-item-p))
20752 (call-interactively 'org-previous-item))
20753 ((org-clocktable-try-shift 'up arg))
20754 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20755 (org-support-shift-select
20756 (org-call-for-shift-select 'previous-line))
20757 (t (org-shiftselect-error))))
20759 (defun org-shiftdown (&optional arg)
20760 "Decrease item in timestamp or decrease priority of current headline.
20761 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20762 depending on context. See the individual commands for more information."
20763 (interactive "P")
20764 (cond
20765 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20766 ((and org-support-shift-select (org-region-active-p))
20767 (org-call-for-shift-select 'next-line))
20768 ((org-at-timestamp-p t)
20769 (call-interactively (if org-edit-timestamp-down-means-later
20770 'org-timestamp-up 'org-timestamp-down)))
20771 ((and (not (eq org-support-shift-select 'always))
20772 org-enable-priority-commands
20773 (org-at-heading-p))
20774 (call-interactively 'org-priority-down))
20775 ((and (not org-support-shift-select) (org-at-item-p))
20776 (call-interactively 'org-next-item))
20777 ((org-clocktable-try-shift 'down arg))
20778 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20779 (org-support-shift-select
20780 (org-call-for-shift-select 'next-line))
20781 (t (org-shiftselect-error))))
20783 (defun org-shiftright (&optional arg)
20784 "Cycle the thing at point or in the current line, depending on context.
20785 Depending on context, this does one of the following:
20787 - switch a timestamp at point one day into the future
20788 - on a headline, switch to the next TODO keyword.
20789 - on an item, switch entire list to the next bullet type
20790 - on a property line, switch to the next allowed value
20791 - on a clocktable definition line, move time block into the future"
20792 (interactive "P")
20793 (cond
20794 ((run-hook-with-args-until-success 'org-shiftright-hook))
20795 ((and org-support-shift-select (org-region-active-p))
20796 (org-call-for-shift-select 'forward-char))
20797 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20798 ((and (not (eq org-support-shift-select 'always))
20799 (org-at-heading-p))
20800 (let ((org-inhibit-logging
20801 (not org-treat-S-cursor-todo-selection-as-state-change))
20802 (org-inhibit-blocking
20803 (not org-treat-S-cursor-todo-selection-as-state-change)))
20804 (org-call-with-arg 'org-todo 'right)))
20805 ((or (and org-support-shift-select
20806 (not (eq org-support-shift-select 'always))
20807 (org-at-item-bullet-p))
20808 (and (not org-support-shift-select) (org-at-item-p)))
20809 (org-call-with-arg 'org-cycle-list-bullet nil))
20810 ((and (not (eq org-support-shift-select 'always))
20811 (org-at-property-p))
20812 (call-interactively 'org-property-next-allowed-value))
20813 ((org-clocktable-try-shift 'right arg))
20814 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20815 (org-support-shift-select
20816 (org-call-for-shift-select 'forward-char))
20817 (t (org-shiftselect-error))))
20819 (defun org-shiftleft (&optional arg)
20820 "Cycle the thing at point or in the current line, depending on context.
20821 Depending on context, this does one of the following:
20823 - switch a timestamp at point one day into the past
20824 - on a headline, switch to the previous TODO keyword.
20825 - on an item, switch entire list to the previous bullet type
20826 - on a property line, switch to the previous allowed value
20827 - on a clocktable definition line, move time block into the past"
20828 (interactive "P")
20829 (cond
20830 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20831 ((and org-support-shift-select (org-region-active-p))
20832 (org-call-for-shift-select 'backward-char))
20833 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20834 ((and (not (eq org-support-shift-select 'always))
20835 (org-at-heading-p))
20836 (let ((org-inhibit-logging
20837 (not org-treat-S-cursor-todo-selection-as-state-change))
20838 (org-inhibit-blocking
20839 (not org-treat-S-cursor-todo-selection-as-state-change)))
20840 (org-call-with-arg 'org-todo 'left)))
20841 ((or (and org-support-shift-select
20842 (not (eq org-support-shift-select 'always))
20843 (org-at-item-bullet-p))
20844 (and (not org-support-shift-select) (org-at-item-p)))
20845 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20846 ((and (not (eq org-support-shift-select 'always))
20847 (org-at-property-p))
20848 (call-interactively 'org-property-previous-allowed-value))
20849 ((org-clocktable-try-shift 'left arg))
20850 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20851 (org-support-shift-select
20852 (org-call-for-shift-select 'backward-char))
20853 (t (org-shiftselect-error))))
20855 (defun org-shiftcontrolright ()
20856 "Switch to next TODO set."
20857 (interactive)
20858 (cond
20859 ((and org-support-shift-select (org-region-active-p))
20860 (org-call-for-shift-select 'forward-word))
20861 ((and (not (eq org-support-shift-select 'always))
20862 (org-at-heading-p))
20863 (org-call-with-arg 'org-todo 'nextset))
20864 (org-support-shift-select
20865 (org-call-for-shift-select 'forward-word))
20866 (t (org-shiftselect-error))))
20868 (defun org-shiftcontrolleft ()
20869 "Switch to previous TODO set."
20870 (interactive)
20871 (cond
20872 ((and org-support-shift-select (org-region-active-p))
20873 (org-call-for-shift-select 'backward-word))
20874 ((and (not (eq org-support-shift-select 'always))
20875 (org-at-heading-p))
20876 (org-call-with-arg 'org-todo 'previousset))
20877 (org-support-shift-select
20878 (org-call-for-shift-select 'backward-word))
20879 (t (org-shiftselect-error))))
20881 (defun org-shiftcontrolup (&optional n)
20882 "Change timestamps synchronously up in CLOCK log lines.
20883 Optional argument N tells to change by that many units."
20884 (interactive "P")
20885 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20886 (let (org-support-shift-select)
20887 (org-clock-timestamps-up n))
20888 (user-error "Not at a clock log")))
20890 (defun org-shiftcontroldown (&optional n)
20891 "Change timestamps synchronously down in CLOCK log lines.
20892 Optional argument N tells to change by that many units."
20893 (interactive "P")
20894 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20895 (let (org-support-shift-select)
20896 (org-clock-timestamps-down n))
20897 (user-error "Not at a clock log")))
20899 (defun org-increase-number-at-point (&optional inc)
20900 "Increment the number at point.
20901 With an optional prefix numeric argument INC, increment using
20902 this numeric value."
20903 (interactive "p")
20904 (if (not (number-at-point))
20905 (user-error "Not on a number")
20906 (unless inc (setq inc 1))
20907 (let ((pos (point))
20908 (beg (skip-chars-backward "-+^/*0-9eE."))
20909 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20910 (setq nap (buffer-substring-no-properties
20911 (+ pos beg) (+ pos beg end)))
20912 (delete-region (+ pos beg) (+ pos beg end))
20913 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20914 (when (org-at-table-p)
20915 (org-table-align)
20916 (org-table-end-of-field 1))))
20918 (defun org-decrease-number-at-point (&optional inc)
20919 "Decrement the number at point.
20920 With an optional prefix numeric argument INC, decrement using
20921 this numeric value."
20922 (interactive "p")
20923 (org-increase-number-at-point (- (or inc 1))))
20925 (defun org-ctrl-c-ret ()
20926 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20927 (interactive)
20928 (cond
20929 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20930 (t (call-interactively 'org-insert-heading))))
20932 (defun org-find-visible ()
20933 (let ((s (point)))
20934 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20935 (get-char-property s 'invisible)))
20937 (defun org-find-invisible ()
20938 (let ((s (point)))
20939 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20940 (not (get-char-property s 'invisible))))
20943 (defun org-copy-visible (beg end)
20944 "Copy the visible parts of the region."
20945 (interactive "r")
20946 (let (snippets s)
20947 (save-excursion
20948 (save-restriction
20949 (narrow-to-region beg end)
20950 (setq s (goto-char (point-min)))
20951 (while (not (= (point) (point-max)))
20952 (goto-char (org-find-invisible))
20953 (push (buffer-substring s (point)) snippets)
20954 (setq s (goto-char (org-find-visible))))))
20955 (kill-new (apply 'concat (nreverse snippets)))))
20957 (defun org-copy-special ()
20958 "Copy region in table or copy current subtree.
20959 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20960 See the individual commands for more information."
20961 (interactive)
20962 (call-interactively
20963 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20965 (defun org-cut-special ()
20966 "Cut region in table or cut current subtree.
20967 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20968 See the individual commands for more information."
20969 (interactive)
20970 (call-interactively
20971 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20973 (defun org-paste-special (arg)
20974 "Paste rectangular region into table, or past subtree relative to level.
20975 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20976 See the individual commands for more information."
20977 (interactive "P")
20978 (if (org-at-table-p)
20979 (org-table-paste-rectangle)
20980 (org-paste-subtree arg)))
20982 (defsubst org-in-fixed-width-region-p ()
20983 "Is point in a fixed-width region?"
20984 (save-match-data
20985 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20987 (defun org-edit-special (&optional arg)
20988 "Call a special editor for the element at point.
20989 When at a table, call the formula editor with `org-table-edit-formulas'.
20990 When in a source code block, call `org-edit-src-code'.
20991 When in a fixed-width region, call `org-edit-fixed-width-region'.
20992 When in an export block, call `org-edit-export-block'.
20993 When at an #+INCLUDE keyword, visit the included file.
20994 When at a footnote reference, call `org-edit-footnote-reference'
20995 On a link, call `ffap' to visit the link at point.
20996 Otherwise, return a user error."
20997 (interactive "P")
20998 (let ((element (org-element-at-point)))
20999 (cl-assert (not buffer-read-only) nil
21000 "Buffer is read-only: %s" (buffer-name))
21001 (pcase (org-element-type element)
21002 (`src-block
21003 (if (not arg) (org-edit-src-code)
21004 (let* ((info (org-babel-get-src-block-info))
21005 (lang (nth 0 info))
21006 (params (nth 2 info))
21007 (session (cdr (assq :session params))))
21008 (if (not session) (org-edit-src-code)
21009 ;; At a src-block with a session and function called with
21010 ;; an ARG: switch to the buffer related to the inferior
21011 ;; process.
21012 (switch-to-buffer
21013 (funcall (intern (concat "org-babel-prep-session:" lang))
21014 session params))))))
21015 (`keyword
21016 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21017 (org-open-link-from-string
21018 (format "[[%s]]"
21019 (expand-file-name
21020 (let ((value (org-element-property :value element)))
21021 (cond ((not (org-string-nw-p value))
21022 (user-error "No file to edit"))
21023 ((string-match "\\`\"\\(.*?\\)\"" value)
21024 (match-string 1 value))
21025 ((string-match "\\`[^ \t\"]\\S-*" value)
21026 (match-string 0 value))
21027 (t (user-error "No valid file specified")))))))
21028 (user-error "No special environment to edit here")))
21029 (`table
21030 (if (eq (org-element-property :type element) 'table.el)
21031 (org-edit-table.el)
21032 (call-interactively 'org-table-edit-formulas)))
21033 ;; Only Org tables contain `table-row' type elements.
21034 (`table-row (call-interactively 'org-table-edit-formulas))
21035 (`example-block (org-edit-src-code))
21036 (`export-block (org-edit-export-block))
21037 (`fixed-width (org-edit-fixed-width-region))
21039 ;; No notable element at point. Though, we may be at a link or
21040 ;; a footnote reference, which are objects. Thus, scan deeper.
21041 (let ((context (org-element-context element)))
21042 (pcase (org-element-type context)
21043 (`footnote-reference (org-edit-footnote-reference))
21044 (`inline-src-block (org-edit-inline-src-code))
21045 (`link (call-interactively #'ffap))
21046 (_ (user-error "No special environment to edit here"))))))))
21048 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21049 (defun org-ctrl-c-ctrl-c (&optional arg)
21050 "Set tags in headline, or update according to changed information at point.
21052 This command does many different things, depending on context:
21054 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21055 this is what we do.
21057 - If the cursor is on a statistics cookie, update it.
21059 - If the cursor is in a headline, prompt for tags and insert them
21060 into the current line, aligned to `org-tags-column'. When called
21061 with prefix arg, realign all tags in the current buffer.
21063 - If the cursor is in one of the special #+KEYWORD lines, this
21064 triggers scanning the buffer for these lines and updating the
21065 information.
21067 - If the cursor is inside a table, realign the table. This command
21068 works even if the automatic table editor has been turned off.
21070 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21071 the entire table.
21073 - If the cursor is at a footnote reference or definition, jump to
21074 the corresponding definition or references, respectively.
21076 - If the cursor is a the beginning of a dynamic block, update it.
21078 - If the current buffer is a capture buffer, close note and file it.
21080 - If the cursor is on a <<<target>>>, update radio targets and
21081 corresponding links in this buffer.
21083 - If the cursor is on a numbered item in a plain list, renumber the
21084 ordered list.
21086 - If the cursor is on a checkbox, toggle it.
21088 - If the cursor is on a code block, evaluate it. The variable
21089 `org-confirm-babel-evaluate' can be used to control prompting
21090 before code block evaluation, by default every code block
21091 evaluation requires confirmation. Code block evaluation can be
21092 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21093 (interactive "P")
21094 (cond
21095 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21096 org-occur-highlights)
21097 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21098 (org-remove-occur-highlights)
21099 (message "Temporary highlights/overlays removed from current buffer"))
21100 ((and (local-variable-p 'org-finish-function (current-buffer))
21101 (fboundp org-finish-function))
21102 (funcall org-finish-function))
21103 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21105 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21106 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21107 (user-error "C-c C-c can do nothing useful at this location"))
21108 (let* ((context (org-element-context))
21109 (type (org-element-type context)))
21110 (cl-case type
21111 ;; When at a link, act according to the parent instead.
21112 (link (setq context (org-element-property :parent context))
21113 (setq type (org-element-type context)))
21114 ;; Unsupported object types: refer to the first supported
21115 ;; element or object containing it.
21116 ((bold code entity export-snippet inline-babel-call inline-src-block
21117 italic latex-fragment line-break macro strike-through subscript
21118 superscript underline verbatim)
21119 (setq context
21120 (org-element-lineage
21121 context '(radio-target paragraph verse-block table-cell)))))
21122 ;; For convenience: at the first line of a paragraph on the
21123 ;; same line as an item, apply function on that item instead.
21124 (when (eq type 'paragraph)
21125 (let ((parent (org-element-property :parent context)))
21126 (when (and (eq (org-element-type parent) 'item)
21127 (= (line-beginning-position)
21128 (org-element-property :begin parent)))
21129 (setq context parent type 'item))))
21130 ;; Act according to type of element or object at point.
21131 (cl-case type
21132 (clock (org-clock-update-time-maybe))
21133 (dynamic-block
21134 (save-excursion
21135 (goto-char (org-element-property :post-affiliated context))
21136 (org-update-dblock)))
21137 (footnote-definition
21138 (goto-char (org-element-property :post-affiliated context))
21139 (call-interactively 'org-footnote-action))
21140 (footnote-reference (call-interactively 'org-footnote-action))
21141 ((headline inlinetask)
21142 (save-excursion (goto-char (org-element-property :begin context))
21143 (call-interactively 'org-set-tags)))
21144 (item
21145 ;; At an item: a double C-u set checkbox to "[-]"
21146 ;; unconditionally, whereas a single one will toggle its
21147 ;; presence. Without a universal argument, if the item
21148 ;; has a checkbox, toggle it. Otherwise repair the list.
21149 (let* ((box (org-element-property :checkbox context))
21150 (struct (org-element-property :structure context))
21151 (old-struct (copy-tree struct))
21152 (parents (org-list-parents-alist struct))
21153 (prevs (org-list-prevs-alist struct))
21154 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21155 (org-list-set-checkbox
21156 (org-element-property :begin context) struct
21157 (cond ((equal arg '(16)) "[-]")
21158 ((and (not box) (equal arg '(4))) "[ ]")
21159 ((or (not box) (equal arg '(4))) nil)
21160 ((eq box 'on) "[ ]")
21161 (t "[X]")))
21162 ;; Mimic `org-list-write-struct' but with grabbing
21163 ;; a return value from `org-list-struct-fix-box'.
21164 (org-list-struct-fix-ind struct parents 2)
21165 (org-list-struct-fix-item-end struct)
21166 (org-list-struct-fix-bul struct prevs)
21167 (org-list-struct-fix-ind struct parents)
21168 (let ((block-item
21169 (org-list-struct-fix-box struct parents prevs orderedp)))
21170 (if (and box (equal struct old-struct))
21171 (if (equal arg '(16))
21172 (message "Checkboxes already reset")
21173 (user-error "Cannot toggle this checkbox: %s"
21174 (if (eq box 'on)
21175 "all subitems checked"
21176 "unchecked subitems")))
21177 (org-list-struct-apply-struct struct old-struct)
21178 (org-update-checkbox-count-maybe))
21179 (when block-item
21180 (message "Checkboxes were removed due to empty box at line %d"
21181 (org-current-line block-item))))))
21182 (keyword
21183 (let ((org-inhibit-startup-visibility-stuff t)
21184 (org-startup-align-all-tables nil))
21185 (when (boundp 'org-table-coordinate-overlays)
21186 (mapc #'delete-overlay org-table-coordinate-overlays)
21187 (setq org-table-coordinate-overlays nil))
21188 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21189 (message "Local setup has been refreshed"))
21190 (plain-list
21191 ;; At a plain list, with a double C-u argument, set
21192 ;; checkboxes of each item to "[-]", whereas a single one
21193 ;; will toggle their presence according to the state of the
21194 ;; first item in the list. Without an argument, repair the
21195 ;; list.
21196 (let* ((begin (org-element-property :contents-begin context))
21197 (beginm (move-marker (make-marker) begin))
21198 (struct (org-element-property :structure context))
21199 (old-struct (copy-tree struct))
21200 (first-box (save-excursion
21201 (goto-char begin)
21202 (looking-at org-list-full-item-re)
21203 (match-string-no-properties 3)))
21204 (new-box (cond ((equal arg '(16)) "[-]")
21205 ((equal arg '(4)) (unless first-box "[ ]"))
21206 ((equal first-box "[X]") "[ ]")
21207 (t "[X]"))))
21208 (cond
21209 (arg
21210 (dolist (pos
21211 (org-list-get-all-items
21212 begin struct (org-list-prevs-alist struct)))
21213 (org-list-set-checkbox pos struct new-box)))
21214 ((and first-box (eq (point) begin))
21215 ;; For convenience, when point is at bol on the first
21216 ;; item of the list and no argument is provided, simply
21217 ;; toggle checkbox of that item, if any.
21218 (org-list-set-checkbox begin struct new-box)))
21219 (org-list-write-struct
21220 struct (org-list-parents-alist struct) old-struct)
21221 (org-update-checkbox-count-maybe)
21222 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21223 ((property-drawer node-property)
21224 (call-interactively 'org-property-action))
21225 ((radio-target target)
21226 (call-interactively 'org-update-radio-target-regexp))
21227 (statistics-cookie
21228 (call-interactively 'org-update-statistics-cookies))
21229 ((table table-cell table-row)
21230 ;; At a table, recalculate every field and align it. Also
21231 ;; send the table if necessary. If the table has
21232 ;; a `table.el' type, just give up. At a table row or
21233 ;; cell, maybe recalculate line but always align table.
21234 (if (eq (org-element-property :type context) 'table.el)
21235 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21236 Use \\[org-edit-special] to edit table.el tables"))
21237 (let ((org-enable-table-editor t))
21238 (if (or (eq type 'table)
21239 ;; Check if point is at a TBLFM line.
21240 (and (eq type 'table-row)
21241 (= (point) (org-element-property :end context))))
21242 (save-excursion
21243 (if (org-at-TBLFM-p)
21244 (progn (require 'org-table)
21245 (org-table-calc-current-TBLFM))
21246 (goto-char (org-element-property :contents-begin context))
21247 (org-call-with-arg 'org-table-recalculate (or arg t))
21248 (orgtbl-send-table 'maybe)))
21249 (org-table-maybe-eval-formula)
21250 (cond (arg (call-interactively 'org-table-recalculate))
21251 ((org-table-maybe-recalculate-line))
21252 (t (org-table-align)))))))
21253 (timestamp (org-timestamp-change 0 'day))
21254 (otherwise
21255 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21256 (user-error
21257 "C-c C-c can do nothing useful at this location")))))))))
21259 (defun org-mode-restart ()
21260 (interactive)
21261 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21262 (funcall major-mode)
21263 (hack-local-variables)
21264 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21265 (org-indent-mode -1)))
21266 (message "%s restarted" major-mode))
21268 (defun org-kill-note-or-show-branches ()
21269 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21270 (interactive)
21271 (if (not org-finish-function)
21272 (progn
21273 (outline-hide-subtree)
21274 (call-interactively 'outline-show-branches))
21275 (let ((org-note-abort t))
21276 (funcall org-finish-function))))
21278 (defun org-delete-indentation (&optional ARG)
21279 "Join current line to previous and fix whitespace at join.
21281 If previous line is a headline add to headline title. Otherwise
21282 the function calls `delete-indentation'.
21284 With argument, join this line to following line."
21285 (interactive "*P")
21286 (if (save-excursion
21287 (if ARG (beginning-of-line)
21288 (forward-line -1))
21289 (looking-at org-complex-heading-regexp))
21290 ;; At headline.
21291 (let ((tags-column (when (match-beginning 5)
21292 (save-excursion (goto-char (match-beginning 5))
21293 (current-column))))
21294 (string (concat " " (progn (when ARG (forward-line 1))
21295 (org-trim (delete-and-extract-region
21296 (line-beginning-position)
21297 (line-end-position)))))))
21298 (unless (bobp) (delete-region (point) (1- (point))))
21299 (goto-char (or (match-end 4)
21300 (match-beginning 5)
21301 (match-end 0)))
21302 (skip-chars-backward " \t")
21303 (save-excursion (insert string))
21304 ;; Adjust alignment of tags.
21305 (when tags-column
21306 (org-align-tags-here (if org-auto-align-tags
21307 org-tags-column
21308 tags-column))))
21309 (delete-indentation ARG)))
21311 (defun org-open-line (n)
21312 "Insert a new row in tables, call `open-line' elsewhere.
21313 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21314 (interactive "*p")
21315 (cond
21316 ((not org-special-ctrl-o)
21317 (open-line n))
21318 ((org-at-table-p)
21319 (org-table-insert-row))
21321 (open-line n))))
21323 (defun org-return (&optional indent)
21324 "Goto next table row or insert a newline.
21326 Calls `org-table-next-row' or `newline', depending on context.
21328 When optional INDENT argument is non-nil, call
21329 `newline-and-indent' instead of `newline'.
21331 When `org-return-follows-link' is non-nil and point is on
21332 a timestamp or a link, call `org-open-at-point'. However, it
21333 will not happen if point is in a table or on a \"dead\"
21334 object (e.g., within a comment). In these case, you need to use
21335 `org-open-at-point' directly."
21336 (interactive)
21337 (let ((context (if org-return-follows-link (org-element-context)
21338 (org-element-at-point))))
21339 (cond
21340 ;; In a table, call `org-table-next-row'.
21341 ((or (and (eq (org-element-type context) 'table)
21342 (>= (point) (org-element-property :contents-begin context))
21343 (< (point) (org-element-property :contents-end context)))
21344 (org-element-lineage context '(table-row table-cell) t))
21345 (org-table-justify-field-maybe)
21346 (call-interactively #'org-table-next-row))
21347 ;; On a link or a timestamp, call `org-open-at-point' if
21348 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21349 ;; locations, e.g., in a comment, as `org-open-at-point'.
21350 ((and org-return-follows-link
21351 (or (org-in-regexp org-ts-regexp-both nil t)
21352 (org-in-regexp org-tsr-regexp-both nil t)
21353 (org-in-regexp org-any-link-re nil t)))
21354 (call-interactively #'org-open-at-point))
21355 ;; Insert newline in heading, but preserve tags.
21356 ((and (not (bolp))
21357 (save-excursion (beginning-of-line)
21358 (looking-at org-complex-heading-regexp)))
21359 ;; At headline. Split line. However, if point is on keyword,
21360 ;; priority cookie or tags, do not break any of them: add
21361 ;; a newline after the headline instead.
21362 (let ((tags-column (and (match-beginning 5)
21363 (save-excursion (goto-char (match-beginning 5))
21364 (current-column))))
21365 (string
21366 (when (and (match-end 4)
21367 (>= (point)
21368 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21369 (<= (point) (match-end 4)))
21370 (delete-and-extract-region (point) (match-end 4)))))
21371 (when (and tags-column string) ; Adjust tag alignment.
21372 (org-align-tags-here
21373 (if org-auto-align-tags org-tags-column tags-column)))
21374 (end-of-line)
21375 (org-show-entry)
21376 (if indent (newline-and-indent) (newline))
21377 (when string (save-excursion (insert (org-trim string))))))
21378 ;; In a list, make sure indenting keeps trailing text within.
21379 ((and indent
21380 (not (eolp))
21381 (org-element-lineage context '(item)))
21382 (let ((trailing-data
21383 (delete-and-extract-region (point) (line-end-position))))
21384 (newline-and-indent)
21385 (save-excursion (insert trailing-data))))
21386 (t (if indent (newline-and-indent) (newline))))))
21388 (defun org-return-indent ()
21389 "Goto next table row or insert a newline and indent.
21390 Calls `org-table-next-row' or `newline-and-indent', depending on
21391 context. See the individual commands for more information."
21392 (interactive)
21393 (org-return t))
21395 (defun org-ctrl-c-star ()
21396 "Compute table, or change heading status of lines.
21397 Calls `org-table-recalculate' or `org-toggle-heading',
21398 depending on context."
21399 (interactive)
21400 (cond
21401 ((org-at-table-p)
21402 (call-interactively 'org-table-recalculate))
21404 ;; Convert all lines in region to list items
21405 (call-interactively 'org-toggle-heading))))
21407 (defun org-ctrl-c-minus ()
21408 "Insert separator line in table or modify bullet status of line.
21409 Also turns a plain line or a region of lines into list items.
21410 Calls `org-table-insert-hline', `org-toggle-item', or
21411 `org-cycle-list-bullet', depending on context."
21412 (interactive)
21413 (cond
21414 ((org-at-table-p)
21415 (call-interactively 'org-table-insert-hline))
21416 ((org-region-active-p)
21417 (call-interactively 'org-toggle-item))
21418 ((org-in-item-p)
21419 (call-interactively 'org-cycle-list-bullet))
21421 (call-interactively 'org-toggle-item))))
21423 (defun org-toggle-item (arg)
21424 "Convert headings or normal lines to items, items to normal lines.
21425 If there is no active region, only the current line is considered.
21427 If the first non blank line in the region is a headline, convert
21428 all headlines to items, shifting text accordingly.
21430 If it is an item, convert all items to normal lines.
21432 If it is normal text, change region into a list of items.
21433 With a prefix argument ARG, change the region in a single item."
21434 (interactive "P")
21435 (let ((shift-text
21436 (function
21437 ;; Shift text in current section to IND, from point to END.
21438 ;; The function leaves point to END line.
21439 (lambda (ind end)
21440 (let ((min-i 1000) (end (copy-marker end)))
21441 ;; First determine the minimum indentation (MIN-I) of
21442 ;; the text.
21443 (save-excursion
21444 (catch 'exit
21445 (while (< (point) end)
21446 (let ((i (org-get-indentation)))
21447 (cond
21448 ;; Skip blank lines and inline tasks.
21449 ((looking-at "^[ \t]*$"))
21450 ((looking-at org-outline-regexp-bol))
21451 ;; We can't find less than 0 indentation.
21452 ((zerop i) (throw 'exit (setq min-i 0)))
21453 ((< i min-i) (setq min-i i))))
21454 (forward-line))))
21455 ;; Then indent each line so that a line indented to
21456 ;; MIN-I becomes indented to IND. Ignore blank lines
21457 ;; and inline tasks in the process.
21458 (let ((delta (- ind min-i)))
21459 (while (< (point) end)
21460 (unless (or (looking-at "^[ \t]*$")
21461 (looking-at org-outline-regexp-bol))
21462 (indent-line-to (+ (org-get-indentation) delta)))
21463 (forward-line)))))))
21464 (skip-blanks
21465 (function
21466 ;; Return beginning of first non-blank line, starting from
21467 ;; line at POS.
21468 (lambda (pos)
21469 (save-excursion
21470 (goto-char pos)
21471 (skip-chars-forward " \r\t\n")
21472 (point-at-bol)))))
21473 beg end)
21474 ;; Determine boundaries of changes.
21475 (if (org-region-active-p)
21476 (setq beg (funcall skip-blanks (region-beginning))
21477 end (copy-marker (region-end)))
21478 (setq beg (funcall skip-blanks (point-at-bol))
21479 end (copy-marker (point-at-eol))))
21480 ;; Depending on the starting line, choose an action on the text
21481 ;; between BEG and END.
21482 (org-with-limited-levels
21483 (save-excursion
21484 (goto-char beg)
21485 (cond
21486 ;; Case 1. Start at an item: de-itemize. Note that it only
21487 ;; happens when a region is active: `org-ctrl-c-minus'
21488 ;; would call `org-cycle-list-bullet' otherwise.
21489 ((org-at-item-p)
21490 (while (< (point) end)
21491 (when (org-at-item-p)
21492 (skip-chars-forward " \t")
21493 (delete-region (point) (match-end 0)))
21494 (forward-line)))
21495 ;; Case 2. Start at an heading: convert to items.
21496 ((org-at-heading-p)
21497 (let* ((bul (org-list-bullet-string "-"))
21498 (bul-len (length bul))
21499 (done (org-entry-is-done-p))
21500 (todo (org-entry-is-todo-p))
21501 ;; Indentation of the first heading. It should be
21502 ;; relative to the indentation of its parent, if any.
21503 (start-ind (save-excursion
21504 (cond
21505 ((not org-adapt-indentation) 0)
21506 ((not (outline-previous-heading)) 0)
21507 (t (length (match-string 0))))))
21508 ;; Level of first heading. Further headings will be
21509 ;; compared to it to determine hierarchy in the list.
21510 (ref-level (org-reduced-level (org-outline-level))))
21511 (when (or done todo) (org-todo ""))
21512 (while (< (point) end)
21513 (let* ((level (org-reduced-level (org-outline-level)))
21514 (delta (max 0 (- level ref-level))))
21515 ;; If current headline is less indented than the first
21516 ;; one, set it as reference, in order to preserve
21517 ;; subtrees.
21518 (when (< level ref-level) (setq ref-level level))
21519 (replace-match bul t t)
21520 (indent-line-to (+ start-ind (* delta bul-len)))
21521 (when (or done todo)
21522 (let* ((struct (org-list-struct))
21523 (old (copy-tree struct)))
21524 (org-list-set-checkbox (line-beginning-position)
21525 struct
21526 (if done "[X]" "[ ]"))
21527 (org-list-write-struct struct
21528 (org-list-parents-alist struct)
21529 old)))
21530 ;; Ensure all text down to END (or SECTION-END) belongs
21531 ;; to the newly created item.
21532 (let ((section-end (save-excursion
21533 (or (outline-next-heading) (point)))))
21534 (forward-line)
21535 (funcall shift-text
21536 (+ start-ind (* (1+ delta) bul-len))
21537 (min end section-end)))))))
21538 ;; Case 3. Normal line with ARG: make the first line of region
21539 ;; an item, and shift indentation of others lines to
21540 ;; set them as item's body.
21541 (arg (let* ((bul (org-list-bullet-string "-"))
21542 (bul-len (length bul))
21543 (ref-ind (org-get-indentation)))
21544 (skip-chars-forward " \t")
21545 (insert bul)
21546 (forward-line)
21547 (while (< (point) end)
21548 ;; Ensure that lines less indented than first one
21549 ;; still get included in item body.
21550 (funcall shift-text
21551 (+ ref-ind bul-len)
21552 (min end (save-excursion (or (outline-next-heading)
21553 (point)))))
21554 (forward-line))))
21555 ;; Case 4. Normal line without ARG: turn each non-item line
21556 ;; into an item.
21558 (while (< (point) end)
21559 (unless (or (org-at-heading-p) (org-at-item-p))
21560 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21561 (replace-match
21562 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21563 (forward-line))))))))
21565 (defun org-toggle-heading (&optional nstars)
21566 "Convert headings to normal text, or items or text to headings.
21567 If there is no active region, only convert the current line.
21569 With a \\[universal-argument] prefix, convert the whole list at
21570 point into heading.
21572 In a region:
21574 - If the first non blank line is a headline, remove the stars
21575 from all headlines in the region.
21577 - If it is a normal line, turn each and every normal line (i.e.,
21578 not an heading or an item) in the region into headings. If you
21579 want to convert only the first line of this region, use one
21580 universal prefix argument.
21582 - If it is a plain list item, turn all plain list items into headings.
21584 When converting a line into a heading, the number of stars is chosen
21585 such that the lines become children of the current entry. However,
21586 when a numeric prefix argument is given, its value determines the
21587 number of stars to add."
21588 (interactive "P")
21589 (let ((skip-blanks
21590 (function
21591 ;; Return beginning of first non-blank line, starting from
21592 ;; line at POS.
21593 (lambda (pos)
21594 (save-excursion
21595 (goto-char pos)
21596 (while (org-at-comment-p) (forward-line))
21597 (skip-chars-forward " \r\t\n")
21598 (point-at-bol)))))
21599 beg end toggled)
21600 ;; Determine boundaries of changes. If a universal prefix has
21601 ;; been given, put the list in a region. If region ends at a bol,
21602 ;; do not consider the last line to be in the region.
21604 (when (and current-prefix-arg (org-at-item-p))
21605 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21606 (org-mark-element))
21608 (if (org-region-active-p)
21609 (setq beg (funcall skip-blanks (region-beginning))
21610 end (copy-marker (save-excursion
21611 (goto-char (region-end))
21612 (if (bolp) (point) (point-at-eol)))))
21613 (setq beg (funcall skip-blanks (point-at-bol))
21614 end (copy-marker (point-at-eol))))
21615 ;; Ensure inline tasks don't count as headings.
21616 (org-with-limited-levels
21617 (save-excursion
21618 (goto-char beg)
21619 (cond
21620 ;; Case 1. Started at an heading: de-star headings.
21621 ((org-at-heading-p)
21622 (while (< (point) end)
21623 (when (org-at-heading-p t)
21624 (looking-at org-outline-regexp) (replace-match "")
21625 (setq toggled t))
21626 (forward-line)))
21627 ;; Case 2. Started at an item: change items into headlines.
21628 ;; One star will be added by `org-list-to-subtree'.
21629 ((org-at-item-p)
21630 (while (< (point) end)
21631 (when (org-at-item-p)
21632 ;; Pay attention to cases when region ends before list.
21633 (let* ((struct (org-list-struct))
21634 (list-end
21635 (min (org-list-get-bottom-point struct) (1+ end))))
21636 (save-restriction
21637 (narrow-to-region (point) list-end)
21638 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21639 (setq toggled t))
21640 (forward-line)))
21641 ;; Case 3. Started at normal text: make every line an heading,
21642 ;; skipping headlines and items.
21643 (t (let* ((stars
21644 (make-string
21645 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21646 (add-stars
21647 (cond (nstars "") ; stars from prefix only
21648 ((equal stars "") "*") ; before first heading
21649 (org-odd-levels-only "**") ; inside heading, odd
21650 (t "*"))) ; inside heading, oddeven
21651 (rpl (concat stars add-stars " "))
21652 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21653 (while (< (point) (if (equal nstars '(4)) lend end))
21654 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21655 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21656 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21657 (forward-line)))))))
21658 (unless toggled (message "Cannot toggle heading from here"))))
21660 (defun org-meta-return (&optional _arg)
21661 "Insert a new heading or wrap a region in a table.
21662 Calls `org-insert-heading' or `org-table-wrap-region', depending
21663 on context. See the individual commands for more information."
21664 (interactive)
21665 (org-check-before-invisible-edit 'insert)
21666 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21667 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21668 #'org-insert-heading))))
21670 ;;; Menu entries
21672 (defsubst org-in-subtree-not-table-p ()
21673 "Are we in a subtree and not in a table?"
21674 (and (not (org-before-first-heading-p))
21675 (not (org-at-table-p))))
21677 ;; Define the Org-mode menus
21678 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21679 '("Tbl"
21680 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21681 ["Next Field" org-cycle (org-at-table-p)]
21682 ["Previous Field" org-shifttab (org-at-table-p)]
21683 ["Next Row" org-return (org-at-table-p)]
21684 "--"
21685 ["Blank Field" org-table-blank-field (org-at-table-p)]
21686 ["Edit Field" org-table-edit-field (org-at-table-p)]
21687 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21688 "--"
21689 ("Column"
21690 ["Move Column Left" org-metaleft (org-at-table-p)]
21691 ["Move Column Right" org-metaright (org-at-table-p)]
21692 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21693 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21694 ("Row"
21695 ["Move Row Up" org-metaup (org-at-table-p)]
21696 ["Move Row Down" org-metadown (org-at-table-p)]
21697 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21698 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21699 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21700 "--"
21701 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21702 ("Rectangle"
21703 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21704 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21705 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21706 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21707 "--"
21708 ("Calculate"
21709 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21710 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21711 ["Edit Formulas" org-edit-special (org-at-table-p)]
21712 "--"
21713 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21714 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21715 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21716 "--"
21717 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21718 "--"
21719 ["Sum Column/Rectangle" org-table-sum
21720 (or (org-at-table-p) (org-region-active-p))]
21721 ["Which Column?" org-table-current-column (org-at-table-p)])
21722 ["Debug Formulas"
21723 org-table-toggle-formula-debugger
21724 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21725 ["Show Col/Row Numbers"
21726 org-table-toggle-coordinate-overlays
21727 :style toggle
21728 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21729 "--"
21730 ["Create" org-table-create (and (not (org-at-table-p))
21731 org-enable-table-editor)]
21732 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21733 ["Import from File" org-table-import (not (org-at-table-p))]
21734 ["Export to File" org-table-export (org-at-table-p)]
21735 "--"
21736 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21737 "--"
21738 ("Plot"
21739 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21740 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21742 (easy-menu-define org-org-menu org-mode-map "Org menu"
21743 '("Org"
21744 ("Show/Hide"
21745 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21746 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21747 ["Sparse Tree..." org-sparse-tree t]
21748 ["Reveal Context" org-reveal t]
21749 ["Show All" outline-show-all t]
21750 "--"
21751 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21752 "--"
21753 ["New Heading" org-insert-heading t]
21754 ("Navigate Headings"
21755 ["Up" outline-up-heading t]
21756 ["Next" outline-next-visible-heading t]
21757 ["Previous" outline-previous-visible-heading t]
21758 ["Next Same Level" outline-forward-same-level t]
21759 ["Previous Same Level" outline-backward-same-level t]
21760 "--"
21761 ["Jump" org-goto t])
21762 ("Edit Structure"
21763 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21764 "--"
21765 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21766 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21767 "--"
21768 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21769 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21770 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21771 "--"
21772 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21773 "--"
21774 ["Copy visible text" org-copy-visible t]
21775 "--"
21776 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21777 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21778 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21779 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21780 "--"
21781 ["Sort Region/Children" org-sort t]
21782 "--"
21783 ["Convert to odd levels" org-convert-to-odd-levels t]
21784 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21785 ("Editing"
21786 ["Emphasis..." org-emphasize t]
21787 ["Edit Source Example" org-edit-special t]
21788 "--"
21789 ["Footnote new/jump" org-footnote-action t]
21790 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21791 ("Archive"
21792 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21793 "--"
21794 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21795 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21796 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21798 "--"
21799 ("Hyperlinks"
21800 ["Store Link (Global)" org-store-link t]
21801 ["Find existing link to here" org-occur-link-in-agenda-files t]
21802 ["Insert Link" org-insert-link t]
21803 ["Follow Link" org-open-at-point t]
21804 "--"
21805 ["Next link" org-next-link t]
21806 ["Previous link" org-previous-link t]
21807 "--"
21808 ["Descriptive Links"
21809 org-toggle-link-display
21810 :style radio
21811 :selected org-descriptive-links
21813 ["Literal Links"
21814 org-toggle-link-display
21815 :style radio
21816 :selected (not org-descriptive-links)])
21817 "--"
21818 ("TODO Lists"
21819 ["TODO/DONE/-" org-todo t]
21820 ("Select keyword"
21821 ["Next keyword" org-shiftright (org-at-heading-p)]
21822 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21823 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21824 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21825 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21826 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21827 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21828 "--"
21829 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21830 :selected org-enforce-todo-dependencies :style toggle :active t]
21831 "Settings for tree at point"
21832 ["Do Children sequentially" org-toggle-ordered-property :style radio
21833 :selected (org-entry-get nil "ORDERED")
21834 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21835 ["Do Children parallel" org-toggle-ordered-property :style radio
21836 :selected (not (org-entry-get nil "ORDERED"))
21837 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21838 "--"
21839 ["Set Priority" org-priority t]
21840 ["Priority Up" org-shiftup t]
21841 ["Priority Down" org-shiftdown t]
21842 "--"
21843 ["Get news from all feeds" org-feed-update-all t]
21844 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21845 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21846 ("TAGS and Properties"
21847 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21848 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21849 "--"
21850 ["Set property" org-set-property (not (org-before-first-heading-p))]
21851 ["Column view of properties" org-columns t]
21852 ["Insert Column View DBlock" org-columns-insert-dblock t])
21853 ("Dates and Scheduling"
21854 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21855 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21856 ("Change Date"
21857 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21858 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21859 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21860 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21861 ["Compute Time Range" org-evaluate-time-range t]
21862 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21863 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21864 "--"
21865 ["Custom time format" org-toggle-time-stamp-overlays
21866 :style radio :selected org-display-custom-times]
21867 "--"
21868 ["Goto Calendar" org-goto-calendar t]
21869 ["Date from Calendar" org-date-from-calendar t]
21870 "--"
21871 ["Start/Restart Timer" org-timer-start t]
21872 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21873 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21874 ["Insert Timer String" org-timer t]
21875 ["Insert Timer Item" org-timer-item t])
21876 ("Logging work"
21877 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21878 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21879 ["Clock out" org-clock-out t]
21880 ["Clock cancel" org-clock-cancel t]
21881 "--"
21882 ["Mark as default task" org-clock-mark-default-task t]
21883 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21884 ["Goto running clock" org-clock-goto t]
21885 "--"
21886 ["Display times" org-clock-display t]
21887 ["Create clock table" org-clock-report t]
21888 "--"
21889 ["Record DONE time"
21890 (progn (setq org-log-done (not org-log-done))
21891 (message "Switching to %s will %s record a timestamp"
21892 (car org-done-keywords)
21893 (if org-log-done "automatically" "not")))
21894 :style toggle :selected org-log-done])
21895 "--"
21896 ["Agenda Command..." org-agenda t]
21897 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21898 ("File List for Agenda")
21899 ("Special views current file"
21900 ["TODO Tree" org-show-todo-tree t]
21901 ["Check Deadlines" org-check-deadlines t]
21902 ["Timeline" org-timeline t]
21903 ["Tags/Property tree" org-match-sparse-tree t])
21904 "--"
21905 ["Export/Publish..." org-export-dispatch t]
21906 ("LaTeX"
21907 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21908 :selected org-cdlatex-mode]
21909 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21910 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21911 ["Modify math symbol" org-cdlatex-math-modify
21912 (org-inside-LaTeX-fragment-p)]
21913 ["Insert citation" org-reftex-citation t]
21914 "--"
21915 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21916 "--"
21917 ("MobileOrg"
21918 ["Push Files and Views" org-mobile-push t]
21919 ["Get Captured and Flagged" org-mobile-pull t]
21920 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21921 "--"
21922 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21923 "--"
21924 ("Documentation"
21925 ["Show Version" org-version t]
21926 ["Info Documentation" org-info t])
21927 ("Customize"
21928 ["Browse Org Group" org-customize t]
21929 "--"
21930 ["Expand This Menu" org-create-customize-menu
21931 (fboundp 'customize-menu-create)])
21932 ["Send bug report" org-submit-bug-report t]
21933 "--"
21934 ("Refresh/Reload"
21935 ["Refresh setup current buffer" org-mode-restart t]
21936 ["Reload Org (after update)" org-reload t]
21937 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21940 (defun org-info (&optional node)
21941 "Read documentation for Org-mode in the info system.
21942 With optional NODE, go directly to that node."
21943 (interactive)
21944 (info (format "(org)%s" (or node ""))))
21946 ;;;###autoload
21947 (defun org-submit-bug-report ()
21948 "Submit a bug report on Org-mode via mail.
21950 Don't hesitate to report any problems or inaccurate documentation.
21952 If you don't have setup sending mail from (X)Emacs, please copy the
21953 output buffer into your mail program, as it gives us important
21954 information about your Org-mode version and configuration."
21955 (interactive)
21956 (require 'reporter)
21957 (defvar reporter-prompt-for-summary-p)
21958 (org-load-modules-maybe)
21959 (org-require-autoloaded-modules)
21960 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21961 (reporter-submit-bug-report
21962 "emacs-orgmode@gnu.org"
21963 (org-version nil 'full)
21964 (let (list)
21965 (save-window-excursion
21966 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21967 (delete-other-windows)
21968 (erase-buffer)
21969 (insert "You are about to submit a bug report to the Org-mode mailing list.
21971 We would like to add your full Org-mode and Outline configuration to the
21972 bug report. This greatly simplifies the work of the maintainer and
21973 other experts on the mailing list.
21975 HOWEVER, some variables you have customized may contain private
21976 information. The names of customers, colleagues, or friends, might
21977 appear in the form of file names, tags, todo states, or search strings.
21978 If you answer yes to the prompt, you might want to check and remove
21979 such private information before sending the email.")
21980 (add-text-properties (point-min) (point-max) '(face org-warning))
21981 (when (yes-or-no-p "Include your Org-mode configuration ")
21982 (mapatoms
21983 (lambda (v)
21984 (and (boundp v)
21985 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21986 (or (and (symbol-value v)
21987 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21988 (and
21989 (get v 'custom-type) (get v 'standard-value)
21990 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21991 (push v list)))))
21992 (kill-buffer (get-buffer "*Warn about privacy*"))
21993 list))
21994 nil nil
21995 "Remember to cover the basics, that is, what you expected to happen and
21996 what in fact did happen. You don't know how to make a good report? See
21998 http://orgmode.org/manual/Feedback.html#Feedback
22000 Your bug report will be posted to the Org-mode mailing list.
22001 ------------------------------------------------------------------------")
22002 (save-excursion
22003 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
22004 (replace-match "\\1Bug: \\3 [\\2]")))))
22007 (defun org-install-agenda-files-menu ()
22008 (let ((bl (buffer-list)))
22009 (save-excursion
22010 (while bl
22011 (set-buffer (pop bl))
22012 (when (derived-mode-p 'org-mode) (setq bl nil)))
22013 (when (derived-mode-p 'org-mode)
22014 (easy-menu-change
22015 '("Org") "File List for Agenda"
22016 (append
22017 (list
22018 ["Edit File List" (org-edit-agenda-file-list) t]
22019 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
22020 ["Remove Current File from List" org-remove-file t]
22021 ["Cycle through agenda files" org-cycle-agenda-files t]
22022 ["Occur in all agenda files" org-occur-in-agenda-files t]
22023 "--")
22024 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22026 ;;;; Documentation
22028 (defun org-require-autoloaded-modules ()
22029 (interactive)
22030 (mapc #'require
22031 '(org-agenda org-archive org-attach org-clock org-colview org-id
22032 org-table org-timer)))
22034 ;;;###autoload
22035 (defun org-reload (&optional uncompiled)
22036 "Reload all org lisp files.
22037 With prefix arg UNCOMPILED, load the uncompiled versions."
22038 (interactive "P")
22039 (require 'loadhist)
22040 (let* ((org-dir (org-find-library-dir "org"))
22041 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22042 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22043 (remove-re (format "\\`%s\\'"
22044 (regexp-opt '("org" "org-loaddefs" "org-version"))))
22045 (feats (delete-dups
22046 (mapcar 'file-name-sans-extension
22047 (mapcar 'file-name-nondirectory
22048 (delq nil
22049 (mapcar 'feature-file
22050 features))))))
22051 (lfeat (append
22052 (sort
22053 (setq feats
22054 (delq nil (mapcar
22055 (lambda (f)
22056 (if (and (string-match feature-re f)
22057 (not (string-match remove-re f)))
22058 f nil))
22059 feats)))
22060 'string-lessp)
22061 (list "org-version" "org")))
22062 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22063 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22064 load-uncore load-misses)
22065 (setq load-misses
22066 (delq 't
22067 (mapcar (lambda (f)
22068 (or (org-load-noerror-mustsuffix (concat org-dir f))
22069 (and (string= org-dir contrib-dir)
22070 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22071 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22072 (add-to-list 'load-uncore f 'append)
22075 lfeat)))
22076 (when load-uncore
22077 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22078 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22079 (if load-misses
22080 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22081 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22082 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22084 ;;;###autoload
22085 (defun org-customize ()
22086 "Call the customize function with org as argument."
22087 (interactive)
22088 (org-load-modules-maybe)
22089 (org-require-autoloaded-modules)
22090 (customize-browse 'org))
22092 (defun org-create-customize-menu ()
22093 "Create a full customization menu for Org-mode, insert it into the menu."
22094 (interactive)
22095 (org-load-modules-maybe)
22096 (org-require-autoloaded-modules)
22097 (if (fboundp 'customize-menu-create)
22098 (progn
22099 (easy-menu-change
22100 '("Org") "Customize"
22101 `(["Browse Org group" org-customize t]
22102 "--"
22103 ,(customize-menu-create 'org)
22104 ["Set" Custom-set t]
22105 ["Save" Custom-save t]
22106 ["Reset to Current" Custom-reset-current t]
22107 ["Reset to Saved" Custom-reset-saved t]
22108 ["Reset to Standard Settings" Custom-reset-standard t]))
22109 (message "\"Org\"-menu now contains full customization menu"))
22110 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22112 ;;;; Miscellaneous stuff
22114 ;;; Generally useful functions
22116 (defun org-get-at-eol (property n)
22117 "Get text property PROPERTY at the end of line less N characters."
22118 (get-text-property (- (point-at-eol) n) property))
22120 (defun org-find-text-property-in-string (prop s)
22121 "Return the first non-nil value of property PROP in string S."
22122 (or (get-text-property 0 prop s)
22123 (get-text-property (or (next-single-property-change 0 prop s) 0)
22124 prop s)))
22126 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22127 "Display the given MESSAGE as a warning."
22128 (if (fboundp 'display-warning)
22129 (display-warning 'org message :warning)
22130 (let ((buf (get-buffer-create "*Org warnings*")))
22131 (with-current-buffer buf
22132 (goto-char (point-max))
22133 (insert "Warning (Org): " message)
22134 (unless (bolp)
22135 (newline)))
22136 (display-buffer buf)
22137 (sit-for 0))))
22139 (defun org-eval (form)
22140 "Eval FORM and return result."
22141 (condition-case error
22142 (eval form)
22143 (error (format "%%![Error: %s]" error))))
22145 (defun org-in-clocktable-p ()
22146 "Check if the cursor is in a clocktable."
22147 (let ((pos (point)) start)
22148 (save-excursion
22149 (end-of-line 1)
22150 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22151 (setq start (match-beginning 0))
22152 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22153 (>= (match-end 0) pos)
22154 start))))
22156 (defun org-in-verbatim-emphasis ()
22157 (save-match-data
22158 (and (org-in-regexp org-emph-re 2)
22159 (>= (point) (match-beginning 3))
22160 (<= (point) (match-end 4))
22161 (member (match-string 3) '("=" "~")))))
22163 (defun org-overlay-display (ovl text &optional face evap)
22164 "Make overlay OVL display TEXT with face FACE."
22165 (overlay-put ovl 'display text)
22166 (if face (overlay-put ovl 'face face))
22167 (if evap (overlay-put ovl 'evaporate t)))
22169 (defun org-overlay-before-string (ovl text &optional face evap)
22170 "Make overlay OVL display TEXT with face FACE."
22171 (if face (org-add-props text nil 'face face))
22172 (overlay-put ovl 'before-string text)
22173 (if evap (overlay-put ovl 'evaporate t)))
22175 (defun org-find-overlays (prop &optional pos delete)
22176 "Find all overlays specifying PROP at POS or point.
22177 If DELETE is non-nil, delete all those overlays."
22178 (let (found)
22179 (dolist (ov (overlays-at (or pos (point))) found)
22180 (cond ((not (overlay-get ov prop)))
22181 (delete (delete-overlay ov))
22182 (t (push ov found))))))
22184 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22185 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22186 (if (and marker (marker-buffer marker)
22187 (buffer-live-p (marker-buffer marker)))
22188 (progn
22189 (org-pop-to-buffer-same-window (marker-buffer marker))
22190 (when (or (> marker (point-max)) (< marker (point-min)))
22191 (widen))
22192 (goto-char marker)
22193 (org-show-context 'org-goto))
22194 (if bookmark
22195 (bookmark-jump bookmark)
22196 (error "Cannot find location"))))
22198 (defun org-quote-csv-field (s)
22199 "Quote field for inclusion in CSV material."
22200 (if (string-match "[\",]" s)
22201 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22204 (defun org-force-self-insert (N)
22205 "Needed to enforce self-insert under remapping."
22206 (interactive "p")
22207 (self-insert-command N))
22209 (defun org-string-width (s)
22210 "Compute width of string, ignoring invisible characters.
22211 This ignores character with invisibility property `org-link', and also
22212 characters with property `org-cwidth', because these will become invisible
22213 upon the next fontification round."
22214 (let (b l)
22215 (when (or (eq t buffer-invisibility-spec)
22216 (assq 'org-link buffer-invisibility-spec))
22217 (while (setq b (text-property-any 0 (length s)
22218 'invisible 'org-link s))
22219 (setq s (concat (substring s 0 b)
22220 (substring s (or (next-single-property-change
22221 b 'invisible s)
22222 (length s)))))))
22223 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22224 (setq s (concat (substring s 0 b)
22225 (substring s (or (next-single-property-change
22226 b 'org-cwidth s)
22227 (length s))))))
22228 (setq l (string-width s) b -1)
22229 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22230 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22233 (defun org-shorten-string (s maxlength)
22234 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22235 If the string is shorter or has length MAXLENGTH, just return the
22236 original string. If it is longer, the functions finds a space in the
22237 string, breaks this string off at that locations and adds three dots
22238 as ellipsis. Including the ellipsis, the string will not be longer
22239 than MAXLENGTH. If finding a good breaking point in the string does
22240 not work, the string is just chopped off in the middle of a word
22241 if necessary."
22242 (if (<= (length s) maxlength)
22244 (let* ((n (max (- maxlength 4) 1))
22245 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22246 (if (string-match re s)
22247 (concat (match-string 1 s) "...")
22248 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22250 (defun org-get-indentation (&optional line)
22251 "Get the indentation of the current line, interpreting tabs.
22252 When LINE is given, assume it represents a line and compute its indentation."
22253 (if line
22254 (when (string-match "^ *" (org-remove-tabs line))
22255 (match-end 0))
22256 (save-excursion
22257 (beginning-of-line 1)
22258 (skip-chars-forward " \t")
22259 (current-column))))
22261 (defun org-get-string-indentation (s)
22262 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22263 (let ((n -1) (i 0) (w tab-width) c)
22264 (catch 'exit
22265 (while (< (setq n (1+ n)) (length s))
22266 (setq c (aref s n))
22267 (cond ((= c ?\ ) (setq i (1+ i)))
22268 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22269 (t (throw 'exit t)))))
22272 (defun org-remove-tabs (s &optional width)
22273 "Replace tabulators in S with spaces.
22274 Assumes that s is a single line, starting in column 0."
22275 (setq width (or width tab-width))
22276 (while (string-match "\t" s)
22277 (setq s (replace-match
22278 (make-string
22279 (- (* width (/ (+ (match-beginning 0) width) width))
22280 (match-beginning 0)) ?\ )
22281 t t s)))
22284 (defun org-fix-indentation (line ind)
22285 "Fix indentation in LINE.
22286 IND is a cons cell with target and minimum indentation.
22287 If the current indentation in LINE is smaller than the minimum,
22288 leave it alone. If it is larger than ind, set it to the target."
22289 (let* ((l (org-remove-tabs line))
22290 (i (org-get-indentation l))
22291 (i1 (car ind)) (i2 (cdr ind)))
22292 (when (>= i i2) (setq l (substring line i2)))
22293 (if (> i1 0)
22294 (concat (make-string i1 ?\ ) l)
22295 l)))
22297 (defun org-remove-indentation (code &optional n)
22298 "Remove maximum common indentation in string CODE and return it.
22299 N may optionally be the number of columns to remove. Return CODE
22300 as-is if removal failed."
22301 (with-temp-buffer
22302 (insert code)
22303 (if (org-do-remove-indentation n) (buffer-string) code)))
22305 (defun org-do-remove-indentation (&optional n)
22306 "Remove the maximum common indentation from the buffer.
22307 When optional argument N is a positive integer, remove exactly
22308 that much characters from indentation, if possible. Return nil
22309 if it fails."
22310 (catch :exit
22311 (goto-char (point-min))
22312 ;; Find maximum common indentation, if not specified.
22313 (let ((n (or n
22314 (let ((min-ind (point-max)))
22315 (save-excursion
22316 (while (re-search-forward "^[ \t]*\\S-" nil t)
22317 (let ((ind (1- (current-column))))
22318 (if (zerop ind) (throw :exit nil)
22319 (setq min-ind (min min-ind ind))))))
22320 min-ind))))
22321 (if (zerop n) (throw :exit nil)
22322 ;; Remove exactly N indentation, but give up if not possible.
22323 (while (not (eobp))
22324 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22325 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22326 ((< ind n) (throw :exit nil))
22327 (t (indent-line-to (- ind n))))
22328 (forward-line)))
22329 ;; Signal success.
22330 t))))
22332 (defun org-fill-template (template alist)
22333 "Find each %key of ALIST in TEMPLATE and replace it."
22334 (let ((case-fold-search nil))
22335 (dolist (entry (sort (copy-sequence alist)
22336 (lambda (a b) (< (length (car a)) (length (car b))))))
22337 (setq template
22338 (replace-regexp-in-string
22339 (concat "%" (regexp-quote (car entry)))
22340 (or (cdr entry) "") template t t)))
22341 template))
22343 (defun org-base-buffer (buffer)
22344 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22345 (if (not buffer)
22346 buffer
22347 (or (buffer-base-buffer buffer)
22348 buffer)))
22350 (defun org-wrap (string &optional width lines)
22351 "Wrap string to either a number of lines, or a width in characters.
22352 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22353 that costs. If there is a word longer than WIDTH, the text is actually
22354 wrapped to the length of that word.
22355 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22356 many lines, whatever width that takes.
22357 The return value is a list of lines, without newlines at the end."
22358 (let* ((words (org-split-string string "[ \t\n]+"))
22359 (maxword (apply 'max (mapcar 'org-string-width words)))
22360 w ll)
22361 (cond (width
22362 (org-do-wrap words (max maxword width)))
22363 (lines
22364 (setq w maxword)
22365 (setq ll (org-do-wrap words maxword))
22366 (if (<= (length ll) lines)
22368 (setq ll words)
22369 (while (> (length ll) lines)
22370 (setq w (1+ w))
22371 (setq ll (org-do-wrap words w)))
22372 ll))
22373 (t (error "Cannot wrap this")))))
22375 (defun org-do-wrap (words width)
22376 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22377 (let (lines line)
22378 (while words
22379 (setq line (pop words))
22380 (while (and words (< (+ (length line) (length (car words))) width))
22381 (setq line (concat line " " (pop words))))
22382 (setq lines (push line lines)))
22383 (nreverse lines)))
22385 (defun org-split-string (string &optional separators)
22386 "Splits STRING into substrings at SEPARATORS.
22387 SEPARATORS is a regular expression.
22388 No empty strings are returned if there are matches at the beginning
22389 and end of string."
22390 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22391 (let ((start 0) notfirst list)
22392 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22393 (if (and notfirst
22394 (= start (match-beginning 0))
22395 (< start (length string)))
22396 (1+ start) start))
22397 (< (match-beginning 0) (length string)))
22398 (setq notfirst t)
22399 (or (eq (match-beginning 0) 0)
22400 (and (eq (match-beginning 0) (match-end 0))
22401 (eq (match-beginning 0) start))
22402 (push (substring string start (match-beginning 0)) list))
22403 (setq start (match-end 0)))
22404 (or (eq start (length string))
22405 (push (substring string start) list))
22406 (nreverse list)))
22408 (defun org-quote-vert (s)
22409 "Replace \"|\" with \"\\vert\"."
22410 (while (string-match "|" s)
22411 (setq s (replace-match "\\vert" t t s)))
22414 (defun org-uuidgen-p (s)
22415 "Is S an ID created by UUIDGEN?"
22416 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22418 (defun org-in-src-block-p (&optional inside)
22419 "Whether point is in a code source block.
22420 When INSIDE is non-nil, don't consider we are within a src block
22421 when point is at #+BEGIN_SRC or #+END_SRC."
22422 (let ((case-fold-search t))
22423 (or (and (eq (get-char-property (point) 'src-block) t))
22424 (and (not inside)
22425 (save-match-data
22426 (save-excursion
22427 (beginning-of-line)
22428 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22430 (defun org-context ()
22431 "Return a list of contexts of the current cursor position.
22432 If several contexts apply, all are returned.
22433 Each context entry is a list with a symbol naming the context, and
22434 two positions indicating start and end of the context. Possible
22435 contexts are:
22437 :headline anywhere in a headline
22438 :headline-stars on the leading stars in a headline
22439 :todo-keyword on a TODO keyword (including DONE) in a headline
22440 :tags on the TAGS in a headline
22441 :priority on the priority cookie in a headline
22442 :item on the first line of a plain list item
22443 :item-bullet on the bullet/number of a plain list item
22444 :checkbox on the checkbox in a plain list item
22445 :table in an org-mode table
22446 :table-special on a special filed in a table
22447 :table-table in a table.el table
22448 :clocktable in a clocktable
22449 :src-block in a source block
22450 :link on a hyperlink
22451 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22452 :target on a <<target>>
22453 :radio-target on a <<<radio-target>>>
22454 :latex-fragment on a LaTeX fragment
22455 :latex-preview on a LaTeX fragment with overlaid preview image
22457 This function expects the position to be visible because it uses font-lock
22458 faces as a help to recognize the following contexts: :table-special, :link,
22459 and :keyword."
22460 (let* ((f (get-text-property (point) 'face))
22461 (faces (if (listp f) f (list f)))
22462 (case-fold-search t)
22463 (p (point)) clist o)
22464 ;; First the large context
22465 (cond
22466 ((org-at-heading-p t)
22467 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22468 (when (progn
22469 (beginning-of-line 1)
22470 (looking-at org-todo-line-tags-regexp))
22471 (push (org-point-in-group p 1 :headline-stars) clist)
22472 (push (org-point-in-group p 2 :todo-keyword) clist)
22473 (push (org-point-in-group p 4 :tags) clist))
22474 (goto-char p)
22475 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22476 (when (looking-at "\\[#[A-Z0-9]\\]")
22477 (push (org-point-in-group p 0 :priority) clist)))
22479 ((org-at-item-p)
22480 (push (org-point-in-group p 2 :item-bullet) clist)
22481 (push (list :item (point-at-bol)
22482 (save-excursion (org-end-of-item) (point)))
22483 clist)
22484 (and (org-at-item-checkbox-p)
22485 (push (org-point-in-group p 0 :checkbox) clist)))
22487 ((org-at-table-p)
22488 (push (list :table (org-table-begin) (org-table-end)) clist)
22489 (when (memq 'org-formula faces)
22490 (push (list :table-special
22491 (previous-single-property-change p 'face)
22492 (next-single-property-change p 'face)) clist)))
22493 ((org-at-table-p 'any)
22494 (push (list :table-table) clist)))
22495 (goto-char p)
22497 (let ((case-fold-search t))
22498 ;; New the "medium" contexts: clocktables, source blocks
22499 (cond ((org-in-clocktable-p)
22500 (push (list :clocktable
22501 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22502 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22503 (match-beginning 1))
22504 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22505 (match-end 0))) clist))
22506 ((org-in-src-block-p)
22507 (push (list :src-block
22508 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22509 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22510 (match-beginning 1))
22511 (and (search-forward "#+END_SRC" nil t)
22512 (match-beginning 0))) clist))))
22513 (goto-char p)
22515 ;; Now the small context
22516 (cond
22517 ((org-at-timestamp-p)
22518 (push (org-point-in-group p 0 :timestamp) clist))
22519 ((memq 'org-link faces)
22520 (push (list :link
22521 (previous-single-property-change p 'face)
22522 (next-single-property-change p 'face)) clist))
22523 ((memq 'org-special-keyword faces)
22524 (push (list :keyword
22525 (previous-single-property-change p 'face)
22526 (next-single-property-change p 'face)) clist))
22527 ((org-at-target-p)
22528 (push (org-point-in-group p 0 :target) clist)
22529 (goto-char (1- (match-beginning 0)))
22530 (when (looking-at org-radio-target-regexp)
22531 (push (org-point-in-group p 0 :radio-target) clist))
22532 (goto-char p))
22533 ((setq o (cl-some
22534 (lambda (o)
22535 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22537 (overlays-at (point))))
22538 (push (list :latex-fragment
22539 (overlay-start o) (overlay-end o)) clist)
22540 (push (list :latex-preview
22541 (overlay-start o) (overlay-end o)) clist))
22542 ((org-inside-LaTeX-fragment-p)
22543 ;; FIXME: positions wrong.
22544 (push (list :latex-fragment (point) (point)) clist)))
22546 (setq clist (nreverse (delq nil clist)))
22547 clist))
22549 (defun org-in-regexp (regexp &optional nlines visually)
22550 "Check if point is inside a match of REGEXP.
22552 Normally only the current line is checked, but you can include
22553 NLINES extra lines around point into the search. If VISUALLY is
22554 set, require that the cursor is not after the match but really
22555 on, so that the block visually is on the match.
22557 Return nil or a cons cell (BEG . END) where BEG and END are,
22558 respectively, the positions at the beginning and the end of the
22559 match."
22560 (catch :exit
22561 (let ((pos (point))
22562 (eol (line-end-position (if nlines (1+ nlines) 1))))
22563 (save-excursion
22564 (beginning-of-line (- 1 (or nlines 0)))
22565 (while (and (re-search-forward regexp eol t)
22566 (<= (match-beginning 0) pos))
22567 (let ((end (match-end 0)))
22568 (when (or (> end pos) (and (= end pos) (not visually)))
22569 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22570 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22571 "Org mode 8.3")
22573 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22574 "Non-nil when point is between matches of START-RE and END-RE.
22576 Also return a non-nil value when point is on one of the matches.
22578 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22579 buffer positions. Default values are the positions of headlines
22580 surrounding the point.
22582 The functions returns a cons cell whose car (resp. cdr) is the
22583 position before START-RE (resp. after END-RE)."
22584 (save-match-data
22585 (let ((pos (point))
22586 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22587 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22588 beg end)
22589 (save-excursion
22590 ;; Point is on a block when on START-RE or if START-RE can be
22591 ;; found before it...
22592 (and (or (org-in-regexp start-re)
22593 (re-search-backward start-re limit-up t))
22594 (setq beg (match-beginning 0))
22595 ;; ... and END-RE after it...
22596 (goto-char (match-end 0))
22597 (re-search-forward end-re limit-down t)
22598 (> (setq end (match-end 0)) pos)
22599 ;; ... without another START-RE in-between.
22600 (goto-char (match-beginning 0))
22601 (not (re-search-backward start-re (1+ beg) t))
22602 ;; Return value.
22603 (cons beg end))))))
22605 (defun org-in-block-p (names)
22606 "Non-nil when point belongs to a block whose name belongs to NAMES.
22608 NAMES is a list of strings containing names of blocks.
22610 Return first block name matched, or nil. Beware that in case of
22611 nested blocks, the returned name may not belong to the closest
22612 block from point."
22613 (save-match-data
22614 (catch 'exit
22615 (let ((case-fold-search t)
22616 (lim-up (save-excursion (outline-previous-heading)))
22617 (lim-down (save-excursion (outline-next-heading))))
22618 (dolist (name names)
22619 (let ((n (regexp-quote name)))
22620 (when (org-between-regexps-p
22621 (concat "^[ \t]*#\\+begin_" n)
22622 (concat "^[ \t]*#\\+end_" n)
22623 lim-up lim-down)
22624 (throw 'exit n)))))
22625 nil)))
22627 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22628 "Call `multi-occur' with buffers for all agenda files."
22629 (interactive "sOrg-files matching: ")
22630 (let* ((files (org-agenda-files))
22631 (tnames (mapcar #'file-truename files))
22632 (extra org-agenda-text-search-extra-files))
22633 (when (eq (car extra) 'agenda-archives)
22634 (setq extra (cdr extra))
22635 (setq files (org-add-archive-files files)))
22636 (dolist (f extra)
22637 (unless (member (file-truename f) tnames)
22638 (unless (member f files) (setq files (append files (list f))))
22639 (setq tnames (append tnames (list (file-truename f))))))
22640 (multi-occur
22641 (mapcar (lambda (x)
22642 (with-current-buffer
22643 ;; FIXME: Why not just (find-file-noselect x)?
22644 ;; Is it to avoid the "revert buffer" prompt?
22645 (or (get-file-buffer x) (find-file-noselect x))
22646 (widen)
22647 (current-buffer)))
22648 files)
22649 regexp)))
22651 (if (boundp 'occur-mode-find-occurrence-hook)
22652 ;; Emacs 23
22653 (add-hook 'occur-mode-find-occurrence-hook
22654 (lambda ()
22655 (when (derived-mode-p 'org-mode)
22656 (org-reveal))))
22657 ;; Emacs 22
22658 (defadvice occur-mode-goto-occurrence
22659 (after org-occur-reveal activate)
22660 (and (derived-mode-p 'org-mode) (org-reveal)))
22661 (defadvice occur-mode-goto-occurrence-other-window
22662 (after org-occur-reveal activate)
22663 (and (derived-mode-p 'org-mode) (org-reveal)))
22664 (defadvice occur-mode-display-occurrence
22665 (after org-occur-reveal activate)
22666 (when (derived-mode-p 'org-mode)
22667 (let ((pos (occur-mode-find-occurrence)))
22668 (with-current-buffer (marker-buffer pos)
22669 (save-excursion
22670 (goto-char pos)
22671 (org-reveal)))))))
22673 (defun org-occur-link-in-agenda-files ()
22674 "Create a link and search for it in the agendas.
22675 The link is not stored in `org-stored-links', it is just created
22676 for the search purpose."
22677 (interactive)
22678 (let ((link (condition-case nil
22679 (org-store-link nil)
22680 (error "Unable to create a link to here"))))
22681 (org-occur-in-agenda-files (regexp-quote link))))
22683 (defun org-reverse-string (string)
22684 "Return the reverse of STRING."
22685 (apply 'string (reverse (string-to-list string))))
22687 ;; defsubst org-uniquify must be defined before first use
22689 (defun org-uniquify-alist (alist)
22690 "Merge elements of ALIST with the same key.
22692 For example, in this alist:
22694 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22695 => \\='((a 1 3) (b 2))
22697 merge (a 1) and (a 3) into (a 1 3).
22699 The function returns the new ALIST."
22700 (let (rtn)
22701 (dolist (e alist rtn)
22702 (let (n)
22703 (if (not (assoc (car e) rtn))
22704 (push e rtn)
22705 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22706 (setq rtn (assq-delete-all (car e) rtn))
22707 (push n rtn))))))
22709 (defun org-delete-all (elts list)
22710 "Remove all elements in ELTS from LIST."
22711 (while elts
22712 (setq list (delete (pop elts) list)))
22713 list)
22715 (defun org-back-over-empty-lines ()
22716 "Move backwards over whitespace, to the beginning of the first empty line.
22717 Returns the number of empty lines passed."
22718 (let ((pos (point)))
22719 (if (cdr (assoc 'heading org-blank-before-new-entry))
22720 (skip-chars-backward " \t\n\r")
22721 (unless (eobp)
22722 (forward-line -1)))
22723 (beginning-of-line 2)
22724 (goto-char (min (point) pos))
22725 (count-lines (point) pos)))
22727 (defun org-skip-whitespace ()
22728 (skip-chars-forward " \t\n\r"))
22730 (defun org-point-in-group (point group &optional context)
22731 "Check if POINT is in match-group GROUP.
22732 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22733 match. If the match group does not exist or point is not inside it,
22734 return nil."
22735 (and (match-beginning group)
22736 (>= point (match-beginning group))
22737 (<= point (match-end group))
22738 (if context
22739 (list context (match-beginning group) (match-end group))
22740 t)))
22742 (defun org-switch-to-buffer-other-window (&rest args)
22743 "Switch to buffer in a second window on the current frame.
22744 In particular, do not allow pop-up frames.
22745 Returns the newly created buffer."
22746 (org-no-popups
22747 (apply 'switch-to-buffer-other-window args)))
22749 (defun org-combine-plists (&rest plists)
22750 "Create a single property list from all plists in PLISTS.
22751 The process starts by copying the first list, and then setting properties
22752 from the other lists. Settings in the last list are the most significant
22753 ones and overrule settings in the other lists."
22754 (let ((rtn (copy-sequence (pop plists)))
22755 p v ls)
22756 (while plists
22757 (setq ls (pop plists))
22758 (while ls
22759 (setq p (pop ls) v (pop ls))
22760 (setq rtn (plist-put rtn p v))))
22761 rtn))
22763 (defun org-replace-escapes (string table)
22764 "Replace %-escapes in STRING with values in TABLE.
22765 TABLE is an association list with keys like \"%a\" and string values.
22766 The sequences in STRING may contain normal field width and padding information,
22767 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22768 so values can contain further %-escapes if they are define later in TABLE."
22769 (let ((tbl (copy-alist table))
22770 (case-fold-search nil)
22771 (pchg 0)
22772 re rpl)
22773 (dolist (e tbl)
22774 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22775 (when (and (cdr e) (string-match re (cdr e)))
22776 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22777 (safe "SREF"))
22778 (add-text-properties 0 3 (list 'sref sref) safe)
22779 (setcdr e (replace-match safe t t (cdr e)))))
22780 (while (string-match re string)
22781 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22782 (cdr e)))
22783 (setq string (replace-match rpl t t string))))
22784 (while (setq pchg (next-property-change pchg string))
22785 (let ((sref (get-text-property pchg 'sref string)))
22786 (when (and sref (string-match "SREF" string pchg))
22787 (setq string (replace-match sref t t string)))))
22788 string))
22790 (defun org-sublist (list start end)
22791 "Return a section of LIST, from START to END.
22793 Counting starts at 1."
22794 (cl-subseq list (1- start) end))
22795 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22797 (defun org-find-base-buffer-visiting (file)
22798 "Like `find-buffer-visiting' but always return the base buffer and
22799 not an indirect buffer."
22800 (let ((buf (or (get-file-buffer file)
22801 (find-buffer-visiting file))))
22802 (if buf
22803 (or (buffer-base-buffer buf) buf)
22804 nil)))
22806 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22807 "Org 9.0")
22809 ;;; TODO: Only called once, from ox-odt which should probably use
22810 ;;; org-export-inline-image-p or something.
22811 (defun org-file-image-p (file)
22812 "Return non-nil if FILE is an image."
22813 (save-match-data
22814 (string-match (image-file-name-regexp) file)))
22816 (defun org-get-cursor-date (&optional with-time)
22817 "Return the date at cursor in as a time.
22818 This works in the calendar and in the agenda, anywhere else it just
22819 returns the current time.
22820 If WITH-TIME is non-nil, returns the time of the event at point (in
22821 the agenda) or the current time of the day."
22822 (let (date day defd tp hod mod)
22823 (when with-time
22824 (setq tp (get-text-property (point) 'time))
22825 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22826 (setq hod (string-to-number (match-string 1 tp))
22827 mod (string-to-number (match-string 2 tp))))
22828 (or tp (let ((now (decode-time)))
22829 (setq hod (nth 2 now)
22830 mod (nth 1 now)))))
22831 (cond
22832 ((eq major-mode 'calendar-mode)
22833 (setq date (calendar-cursor-to-date)
22834 defd (encode-time 0 (or mod 0) (or hod 0)
22835 (nth 1 date) (nth 0 date) (nth 2 date))))
22836 ((eq major-mode 'org-agenda-mode)
22837 (setq day (get-text-property (point) 'day))
22838 (when day
22839 (setq date (calendar-gregorian-from-absolute day)
22840 defd (encode-time 0 (or mod 0) (or hod 0)
22841 (nth 1 date) (nth 0 date) (nth 2 date))))))
22842 (or defd (current-time))))
22844 (defun org-mark-subtree (&optional up)
22845 "Mark the current subtree.
22846 This puts point at the start of the current subtree, and mark at
22847 the end. If a numeric prefix UP is given, move up into the
22848 hierarchy of headlines by UP levels before marking the subtree."
22849 (interactive "P")
22850 (org-with-limited-levels
22851 (cond ((org-at-heading-p) (beginning-of-line))
22852 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22853 (t (outline-previous-visible-heading 1))))
22854 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22855 (if (org-called-interactively-p 'any)
22856 (call-interactively 'org-mark-element)
22857 (org-mark-element)))
22859 (defun org-file-newer-than-p (file time)
22860 "Non-nil if FILE is newer than TIME.
22861 FILE is a filename, as a string, TIME is a list of integers, as
22862 returned by, e.g., `current-time'."
22863 (and (file-exists-p file)
22864 ;; Only compare times up to whole seconds as some file-systems
22865 ;; (e.g. HFS+) do not retain any finer granularity. As
22866 ;; a consequence, make sure we return non-nil when the two
22867 ;; times are equal.
22868 (not (time-less-p (cl-subseq (nth 5 (file-attributes file)) 0 2)
22869 (cl-subseq time 0 2)))))
22871 (defun org-compile-file (source process ext &optional err-msg log-buf spec)
22872 "Compile a SOURCE file using PROCESS.
22874 PROCESS is either a function or a list of shell commands, as
22875 strings. EXT is a file extension, without the leading dot, as
22876 a string. It is used to check if the process actually succeeded.
22878 PROCESS must create a file with the same base name and directory
22879 as SOURCE, but ending with EXT. The function then returns its
22880 filename. Otherwise, it raises an error. The error message can
22881 then be refined by providing string ERR-MSG, which is appended to
22882 the standard message.
22884 If PROCESS is a function, it is called with a single argument:
22885 the SOURCE file.
22887 If it is a list of commands, each of them is called using
22888 `shell-command'. By default, in each command, %b, %f, %F and %o
22889 are replaced with, respectively, SOURCE base name, name, full
22890 name and directory. It is possible, however, to use more
22891 place-holders by specifying them in optional argument SPEC, as an
22892 alist following the pattern (CHARACTER . REPLACEMENT-STRING).
22894 When PROCESS is a list of commands, optional argument LOG-BUF can
22895 be set to a buffer or a buffer name. `shell-command' then uses
22896 it for output.
22898 `default-directory' is set to SOURCE directory during the whole
22899 process."
22900 (let* ((source-name (file-name-nondirectory source))
22901 (base-name (file-name-sans-extension source-name))
22902 (full-name (file-truename source))
22903 (out-dir (file-name-directory source))
22904 ;; Properly set working directory for compilation.
22905 (default-directory (file-name-directory full-name))
22906 (time (current-time))
22907 (err-msg (if (stringp err-msg) (concat ". " err-msg) "")))
22908 (save-window-excursion
22909 (pcase process
22910 ((pred functionp) (funcall process (shell-quote-argument source)))
22911 ((pred consp)
22912 (let ((log-buf (and log-buf (get-buffer-create log-buf)))
22913 (spec (append spec
22914 `((?b . ,(shell-quote-argument base-name))
22915 (?f . ,(shell-quote-argument source-name))
22916 (?F . ,(shell-quote-argument full-name))
22917 (?o . ,(shell-quote-argument out-dir))))))
22918 (dolist (command process)
22919 (shell-command (format-spec command spec) log-buf))))
22920 (_ (error "No valid command to process %S%s" source err-msg)))
22921 ;; Check for process failure.
22922 (let ((output (concat out-dir base-name "." ext)))
22923 (unless (org-file-newer-than-p output time)
22924 (error (format "File %S wasn't produced%s" output err-msg)))
22925 output))))
22927 ;;; Indentation
22929 (defun org--get-expected-indentation (element contentsp)
22930 "Expected indentation column for current line, according to ELEMENT.
22931 ELEMENT is an element containing point. CONTENTSP is non-nil
22932 when indentation is to be computed according to contents of
22933 ELEMENT."
22934 (let ((type (org-element-type element))
22935 (start (org-element-property :begin element))
22936 (post-affiliated (org-element-property :post-affiliated element)))
22937 (org-with-wide-buffer
22938 (cond
22939 (contentsp
22940 (cl-case type
22941 ((diary-sexp footnote-definition) 0)
22942 ((headline inlinetask nil)
22943 (if (not org-adapt-indentation) 0
22944 (let ((level (org-current-level)))
22945 (if level (1+ level) 0))))
22946 ((item plain-list) (org-list-item-body-column post-affiliated))
22948 (goto-char start)
22949 (org-get-indentation))))
22950 ((memq type '(headline inlinetask nil))
22951 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22952 (org--get-expected-indentation element t)
22954 ((memq type '(diary-sexp footnote-definition)) 0)
22955 ;; First paragraph of a footnote definition or an item.
22956 ;; Indent like parent.
22957 ((< (line-beginning-position) start)
22958 (org--get-expected-indentation
22959 (org-element-property :parent element) t))
22960 ;; At first line: indent according to previous sibling, if any,
22961 ;; ignoring footnote definitions and inline tasks, or parent's
22962 ;; contents.
22963 ((= (line-beginning-position) start)
22964 (catch 'exit
22965 (while t
22966 (if (= (point-min) start) (throw 'exit 0)
22967 (goto-char (1- start))
22968 (let* ((previous (org-element-at-point))
22969 (parent previous))
22970 (while (and parent (<= (org-element-property :end parent) start))
22971 (setq previous parent
22972 parent (org-element-property :parent parent)))
22973 (cond
22974 ((not previous) (throw 'exit 0))
22975 ((> (org-element-property :end previous) start)
22976 (throw 'exit (org--get-expected-indentation previous t)))
22977 ((memq (org-element-type previous)
22978 '(footnote-definition inlinetask))
22979 (setq start (org-element-property :begin previous)))
22980 (t (goto-char (org-element-property :begin previous))
22981 (throw 'exit
22982 (if (bolp) (org-get-indentation)
22983 ;; At first paragraph in an item or
22984 ;; a footnote definition.
22985 (org--get-expected-indentation
22986 (org-element-property :parent previous) t))))))))))
22987 ;; Otherwise, move to the first non-blank line above.
22989 (beginning-of-line)
22990 (let ((pos (point)))
22991 (skip-chars-backward " \r\t\n")
22992 (cond
22993 ;; Two blank lines end a footnote definition or a plain
22994 ;; list. When we indent an empty line after them, the
22995 ;; containing list or footnote definition is over, so it
22996 ;; qualifies as a previous sibling. Therefore, we indent
22997 ;; like its first line.
22998 ((and (memq type '(footnote-definition plain-list))
22999 (> (count-lines (point) pos) 2))
23000 (goto-char start)
23001 (org-get-indentation))
23002 ;; Line above is the first one of a paragraph at the
23003 ;; beginning of an item or a footnote definition. Indent
23004 ;; like parent.
23005 ((< (line-beginning-position) start)
23006 (org--get-expected-indentation
23007 (org-element-property :parent element) t))
23008 ;; Line above is the beginning of an element, i.e., point
23009 ;; was originally on the blank lines between element's start
23010 ;; and contents.
23011 ((= (line-beginning-position) post-affiliated)
23012 (org--get-expected-indentation element t))
23013 ;; POS is after contents in a greater element. Indent like
23014 ;; the beginning of the element.
23016 ;; As a special case, if point is at the end of a footnote
23017 ;; definition or an item, indent like the very last element
23018 ;; within. If that last element is an item, indent like its
23019 ;; contents.
23020 ((and (not (eq type 'paragraph))
23021 (let ((cend (org-element-property :contents-end element)))
23022 (and cend (<= cend pos))))
23023 (if (memq type '(footnote-definition item plain-list))
23024 (let ((last (org-element-at-point)))
23025 (org--get-expected-indentation
23026 last (eq (org-element-type last) 'item)))
23027 (goto-char start)
23028 (org-get-indentation)))
23029 ;; In any other case, indent like the current line.
23030 (t (org-get-indentation)))))))))
23032 (defun org--align-node-property ()
23033 "Align node property at point.
23034 Alignment is done according to `org-property-format', which see."
23035 (when (save-excursion
23036 (beginning-of-line)
23037 (looking-at org-property-re))
23038 (replace-match
23039 (concat (match-string 4)
23040 (org-trim
23041 (format org-property-format (match-string 1) (match-string 3))))
23042 t t)))
23044 (defun org-indent-line ()
23045 "Indent line depending on context.
23047 Indentation is done according to the following rules:
23049 - Footnote definitions, diary sexps, headlines and inline tasks
23050 have to start at column 0.
23052 - On the very first line of an element, consider, in order, the
23053 next rules until one matches:
23055 1. If there's a sibling element before, ignoring footnote
23056 definitions and inline tasks, indent like its first line.
23058 2. If element has a parent, indent like its contents. More
23059 precisely, if parent is an item, indent after the
23060 description part, if any, or the bullet (see
23061 `org-list-description-max-indent'). Else, indent like
23062 parent's first line.
23064 3. Otherwise, indent relatively to current level, if
23065 `org-adapt-indentation' is non-nil, or to left margin.
23067 - On a blank line at the end of an element, indent according to
23068 the type of the element. More precisely
23070 1. If element is a plain list, an item, or a footnote
23071 definition, indent like the very last element within.
23073 2. If element is a paragraph, indent like its last non blank
23074 line.
23076 3. Otherwise, indent like its very first line.
23078 - In the code part of a source block, use language major mode
23079 to indent current line if `org-src-tab-acts-natively' is
23080 non-nil. If it is nil, do nothing.
23082 - Otherwise, indent like the first non-blank line above.
23084 The function doesn't indent an item as it could break the whole
23085 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
23086 \\[org-shiftmetaright].
23088 Also align node properties according to `org-property-format'."
23089 (interactive)
23090 (cond
23091 (orgstruct-is-++
23092 (let ((indent-line-function
23093 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
23094 (indent-according-to-mode)))
23095 ((org-at-heading-p) 'noindent)
23097 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
23098 (type (org-element-type element)))
23099 (cond ((and (memq type '(plain-list item))
23100 (= (line-beginning-position)
23101 (org-element-property :post-affiliated element)))
23102 'noindent)
23103 ((and (eq type 'src-block)
23104 org-src-tab-acts-natively
23105 (> (line-beginning-position)
23106 (org-element-property :post-affiliated element))
23107 (< (line-beginning-position)
23108 (org-with-wide-buffer
23109 (goto-char (org-element-property :end element))
23110 (skip-chars-backward " \r\t\n")
23111 (line-beginning-position))))
23112 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23114 (let ((column (org--get-expected-indentation element nil)))
23115 ;; Preserve current column.
23116 (if (<= (current-column) (current-indentation))
23117 (indent-line-to column)
23118 (save-excursion (indent-line-to column))))
23119 ;; Align node property. Also preserve current column.
23120 (when (eq type 'node-property)
23121 (let ((column (current-column)))
23122 (org--align-node-property)
23123 (org-move-to-column column)))))))))
23125 (defun org-indent-region (start end)
23126 "Indent each non-blank line in the region.
23127 Called from a program, START and END specify the region to
23128 indent. The function will not indent contents of example blocks,
23129 verse blocks and export blocks as leading white spaces are
23130 assumed to be significant there."
23131 (interactive "r")
23132 (save-excursion
23133 (goto-char start)
23134 (skip-chars-forward " \r\t\n")
23135 (unless (eobp) (beginning-of-line))
23136 (let ((indent-to
23137 (lambda (ind pos)
23138 ;; Set IND as indentation for all lines between point and
23139 ;; POS. Blank lines are ignored. Leave point after POS
23140 ;; once done.
23141 (let ((limit (copy-marker pos)))
23142 (while (< (point) limit)
23143 (unless (looking-at-p "[ \t]*$") (indent-line-to ind))
23144 (forward-line))
23145 (set-marker limit nil))))
23146 (end (copy-marker end)))
23147 (while (< (point) end)
23148 (if (or (looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23149 (let* ((element (org-element-at-point))
23150 (type (org-element-type element))
23151 (element-end (copy-marker (org-element-property :end element)))
23152 (ind (org--get-expected-indentation element nil)))
23153 (cond
23154 ((or (memq type '(paragraph table table-row))
23155 (not (or (org-element-property :contents-begin element)
23156 (memq type
23157 '(example-block export-block src-block)))))
23158 ;; Elements here are indented as a single block. Also
23159 ;; align node properties.
23160 (when (eq type 'node-property)
23161 (org--align-node-property)
23162 (beginning-of-line))
23163 (funcall indent-to ind (min element-end end)))
23165 ;; Elements in this category consist of three parts:
23166 ;; before the contents, the contents, and after the
23167 ;; contents. The contents are treated specially,
23168 ;; according to the element type, or not indented at
23169 ;; all. Other parts are indented as a single block.
23170 (let* ((post (copy-marker
23171 (org-element-property :post-affiliated element)))
23172 (cbeg
23173 (copy-marker
23174 (cond
23175 ((not (org-element-property :contents-begin element))
23176 ;; Fake contents for source blocks.
23177 (org-with-wide-buffer
23178 (goto-char post)
23179 (forward-line)
23180 (point)))
23181 ((memq type '(footnote-definition item plain-list))
23182 ;; Contents in these elements could start on
23183 ;; the same line as the beginning of the
23184 ;; element. Make sure we start indenting
23185 ;; from the second line.
23186 (org-with-wide-buffer
23187 (goto-char post)
23188 (end-of-line)
23189 (skip-chars-forward " \r\t\n")
23190 (if (eobp) (point) (line-beginning-position))))
23191 (t (org-element-property :contents-begin element)))))
23192 (cend (copy-marker
23193 (or (org-element-property :contents-end element)
23194 ;; Fake contents for source blocks.
23195 (org-with-wide-buffer
23196 (goto-char element-end)
23197 (skip-chars-backward " \r\t\n")
23198 (line-beginning-position)))
23199 t)))
23200 ;; Do not change items indentation individually as it
23201 ;; might break the list as a whole. On the other
23202 ;; hand, when at a plain list, indent it as a whole.
23203 (cond ((eq type 'plain-list)
23204 (let ((offset (- ind (org-get-indentation))))
23205 (unless (zerop offset)
23206 (indent-rigidly (org-element-property :begin element)
23207 (org-element-property :end element)
23208 offset))
23209 (goto-char cbeg)))
23210 ((eq type 'item) (goto-char cbeg))
23211 (t (funcall indent-to ind (min cbeg end))))
23212 (when (< (point) end)
23213 (cl-case type
23214 ((example-block export-block verse-block))
23215 (src-block
23216 ;; In a source block, indent source code
23217 ;; according to language major mode, but only if
23218 ;; `org-src-tab-acts-natively' is non-nil.
23219 (when (and (< (point) end) org-src-tab-acts-natively)
23220 (ignore-errors
23221 (org-babel-do-in-edit-buffer
23222 (indent-region (point-min) (point-max))))))
23223 (t (org-indent-region (point) (min cend end))))
23224 (goto-char (min cend end))
23225 (when (< (point) end)
23226 (funcall indent-to ind (min element-end end))))
23227 (set-marker post nil)
23228 (set-marker cbeg nil)
23229 (set-marker cend nil))))
23230 (set-marker element-end nil))))
23231 (set-marker end nil))))
23233 (defun org-indent-drawer ()
23234 "Indent the drawer at point."
23235 (interactive)
23236 (unless (save-excursion
23237 (beginning-of-line)
23238 (looking-at-p org-drawer-regexp))
23239 (user-error "Not at a drawer"))
23240 (let ((element (org-element-at-point)))
23241 (unless (memq (org-element-type element) '(drawer property-drawer))
23242 (user-error "Not at a drawer"))
23243 (org-with-wide-buffer
23244 (org-indent-region (org-element-property :begin element)
23245 (org-element-property :end element))))
23246 (message "Drawer at point indented"))
23248 (defun org-indent-block ()
23249 "Indent the block at point."
23250 (interactive)
23251 (unless (save-excursion
23252 (beginning-of-line)
23253 (let ((case-fold-search t))
23254 (looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23255 (user-error "Not at a block"))
23256 (let ((element (org-element-at-point)))
23257 (unless (memq (org-element-type element)
23258 '(comment-block center-block dynamic-block example-block
23259 export-block quote-block special-block
23260 src-block verse-block))
23261 (user-error "Not at a block"))
23262 (org-with-wide-buffer
23263 (org-indent-region (org-element-property :begin element)
23264 (org-element-property :end element))))
23265 (message "Block at point indented"))
23268 ;;; Filling
23270 ;; We use our own fill-paragraph and auto-fill functions.
23272 ;; `org-fill-paragraph' relies on adaptive filling and context
23273 ;; checking. Appropriate `fill-prefix' is computed with
23274 ;; `org-adaptive-fill-function'.
23276 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23277 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23278 ;; `org-adaptive-fill-function' value. Internally,
23279 ;; `org-comment-line-break-function' breaks the line.
23281 ;; `org-setup-filling' installs filling and auto-filling related
23282 ;; variables during `org-mode' initialization.
23284 (defvar org-element-paragraph-separate) ; org-element.el
23285 (defun org-setup-filling ()
23286 (require 'org-element)
23287 ;; Prevent auto-fill from inserting unwanted new items.
23288 (when (boundp 'fill-nobreak-predicate)
23289 (setq-local
23290 fill-nobreak-predicate
23291 (org-uniquify
23292 (append fill-nobreak-predicate
23293 '(org-fill-line-break-nobreak-p
23294 org-fill-paragraph-with-timestamp-nobreak-p)))))
23295 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23296 (setq-local paragraph-start paragraph-ending)
23297 (setq-local paragraph-separate paragraph-ending))
23298 (setq-local fill-paragraph-function 'org-fill-paragraph)
23299 (setq-local auto-fill-inhibit-regexp nil)
23300 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23301 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23302 (setq-local comment-line-break-function 'org-comment-line-break-function))
23304 (defun org-fill-line-break-nobreak-p ()
23305 "Non-nil when a new line at point would create an Org line break."
23306 (save-excursion
23307 (skip-chars-backward "[ \t]")
23308 (skip-chars-backward "\\\\")
23309 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23311 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23312 "Non-nil when a new line at point would split a timestamp."
23313 (and (org-at-timestamp-p t)
23314 (not (looking-at org-ts-regexp-both))))
23316 (declare-function message-in-body-p "message" ())
23317 (defvar orgtbl-line-start-regexp) ; From org-table.el
23318 (defun org-adaptive-fill-function ()
23319 "Compute a fill prefix for the current line.
23320 Return fill prefix, as a string, or nil if current line isn't
23321 meant to be filled. For convenience, if `adaptive-fill-regexp'
23322 matches in paragraphs or comments, use it."
23323 (catch 'exit
23324 (when (derived-mode-p 'message-mode)
23325 (save-excursion
23326 (beginning-of-line)
23327 (cond ((not (message-in-body-p)) (throw 'exit nil))
23328 ((looking-at-p org-table-line-regexp) (throw 'exit nil))
23329 ((looking-at message-cite-prefix-regexp)
23330 (throw 'exit (match-string-no-properties 0)))
23331 ((looking-at org-outline-regexp)
23332 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23333 (org-with-wide-buffer
23334 (unless (org-at-heading-p)
23335 (let* ((p (line-beginning-position))
23336 (element (save-excursion
23337 (beginning-of-line)
23338 (org-element-at-point)))
23339 (type (org-element-type element))
23340 (post-affiliated (org-element-property :post-affiliated element)))
23341 (unless (< p post-affiliated)
23342 (cl-case type
23343 (comment
23344 (save-excursion
23345 (beginning-of-line)
23346 (looking-at "[ \t]*")
23347 (concat (match-string 0) "# ")))
23348 (footnote-definition "")
23349 ((item plain-list)
23350 (make-string (org-list-item-body-column post-affiliated) ?\s))
23351 (paragraph
23352 ;; Fill prefix is usually the same as the current line,
23353 ;; unless the paragraph is at the beginning of an item.
23354 (let ((parent (org-element-property :parent element)))
23355 (save-excursion
23356 (beginning-of-line)
23357 (cond ((eq (org-element-type parent) 'item)
23358 (make-string (org-list-item-body-column
23359 (org-element-property :begin parent))
23360 ?\s))
23361 ((and adaptive-fill-regexp
23362 ;; Locally disable
23363 ;; `adaptive-fill-function' to let
23364 ;; `fill-context-prefix' handle
23365 ;; `adaptive-fill-regexp' variable.
23366 (let (adaptive-fill-function)
23367 (fill-context-prefix
23368 post-affiliated
23369 (org-element-property :end element)))))
23370 ((looking-at "[ \t]+") (match-string 0))
23371 (t "")))))
23372 (comment-block
23373 ;; Only fill contents if P is within block boundaries.
23374 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23375 (forward-line)
23376 (point)))
23377 (cend (save-excursion
23378 (goto-char (org-element-property :end element))
23379 (skip-chars-backward " \r\t\n")
23380 (line-beginning-position))))
23381 (when (and (>= p cbeg) (< p cend))
23382 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23383 (match-string 0)
23384 "")))))))))))
23386 (declare-function message-goto-body "message" ())
23387 (defvar message-cite-prefix-regexp) ; From message.el
23388 (defun org-fill-paragraph (&optional justify)
23389 "Fill element at point, when applicable.
23391 This function only applies to comment blocks, comments, example
23392 blocks and paragraphs. Also, as a special case, re-align table
23393 when point is at one.
23395 If JUSTIFY is non-nil (interactively, with prefix argument),
23396 justify as well. If `sentence-end-double-space' is non-nil, then
23397 period followed by one space does not end a sentence, so don't
23398 break a line there. The variable `fill-column' controls the
23399 width for filling.
23401 For convenience, when point is at a plain list, an item or
23402 a footnote definition, try to fill the first paragraph within."
23403 (interactive)
23404 (if (and (derived-mode-p 'message-mode)
23405 (or (not (message-in-body-p))
23406 (save-excursion (move-beginning-of-line 1)
23407 (looking-at message-cite-prefix-regexp))))
23408 ;; First ensure filling is correct in message-mode.
23409 (let ((fill-paragraph-function
23410 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23411 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23412 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23413 (paragraph-separate
23414 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23415 (fill-paragraph nil))
23416 (with-syntax-table org-mode-transpose-word-syntax-table
23417 ;; Move to end of line in order to get the first paragraph
23418 ;; within a plain list or a footnote definition.
23419 (let ((element (save-excursion
23420 (end-of-line)
23421 (or (ignore-errors (org-element-at-point))
23422 (user-error "An element cannot be parsed line %d"
23423 (line-number-at-pos (point)))))))
23424 ;; First check if point is in a blank line at the beginning of
23425 ;; the buffer. In that case, ignore filling.
23426 (cl-case (org-element-type element)
23427 ;; Use major mode filling function is src blocks.
23428 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23429 ;; Align Org tables, leave table.el tables as-is.
23430 (table-row (org-table-align) t)
23431 (table
23432 (when (eq (org-element-property :type element) 'org)
23433 (save-excursion
23434 (goto-char (org-element-property :post-affiliated element))
23435 (org-table-align)))
23437 (paragraph
23438 ;; Paragraphs may contain `line-break' type objects.
23439 (let ((beg (max (point-min)
23440 (org-element-property :contents-begin element)))
23441 (end (min (point-max)
23442 (org-element-property :contents-end element))))
23443 ;; Do nothing if point is at an affiliated keyword.
23444 (if (< (line-end-position) beg) t
23445 (when (derived-mode-p 'message-mode)
23446 ;; In `message-mode', do not fill following citation
23447 ;; in current paragraph nor text before message body.
23448 (let ((body-start (save-excursion (message-goto-body))))
23449 (when body-start (setq beg (max body-start beg))))
23450 (when (save-excursion
23451 (re-search-forward
23452 (concat "^" message-cite-prefix-regexp) end t))
23453 (setq end (match-beginning 0))))
23454 ;; Fill paragraph, taking line breaks into account.
23455 (save-excursion
23456 (goto-char beg)
23457 (let ((cuts (list beg)))
23458 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23459 (when (eq 'line-break
23460 (org-element-type
23461 (save-excursion (backward-char)
23462 (org-element-context))))
23463 (push (point) cuts)))
23464 (dolist (c (delq end cuts))
23465 (fill-region-as-paragraph c end justify)
23466 (setq end c))))
23467 t)))
23468 ;; Contents of `comment-block' type elements should be
23469 ;; filled as plain text, but only if point is within block
23470 ;; markers.
23471 (comment-block
23472 (let* ((case-fold-search t)
23473 (beg (save-excursion
23474 (goto-char (org-element-property :begin element))
23475 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23476 (forward-line)
23477 (point)))
23478 (end (save-excursion
23479 (goto-char (org-element-property :end element))
23480 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23481 (line-beginning-position))))
23482 (if (or (< (point) beg) (> (point) end)) t
23483 (fill-region-as-paragraph
23484 (save-excursion (end-of-line)
23485 (re-search-backward "^[ \t]*$" beg 'move)
23486 (line-beginning-position))
23487 (save-excursion (beginning-of-line)
23488 (re-search-forward "^[ \t]*$" end 'move)
23489 (line-beginning-position))
23490 justify))))
23491 ;; Fill comments.
23492 (comment
23493 (let ((begin (org-element-property :post-affiliated element))
23494 (end (org-element-property :end element)))
23495 (when (and (>= (point) begin) (<= (point) end))
23496 (let ((begin (save-excursion
23497 (end-of-line)
23498 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23499 (progn (forward-line) (point))
23500 begin)))
23501 (end (save-excursion
23502 (end-of-line)
23503 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23504 (1- (line-beginning-position))
23505 (skip-chars-backward " \r\t\n")
23506 (line-end-position)))))
23507 ;; Do not fill comments when at a blank line.
23508 (when (> end begin)
23509 (let ((fill-prefix
23510 (save-excursion
23511 (beginning-of-line)
23512 (looking-at "[ \t]*#")
23513 (let ((comment-prefix (match-string 0)))
23514 (goto-char (match-end 0))
23515 (if (looking-at adaptive-fill-regexp)
23516 (concat comment-prefix (match-string 0))
23517 (concat comment-prefix " "))))))
23518 (save-excursion
23519 (fill-region-as-paragraph begin end justify))))))
23521 ;; Ignore every other element.
23522 (otherwise t))))))
23524 (defun org-auto-fill-function ()
23525 "Auto-fill function."
23526 ;; Check if auto-filling is meaningful.
23527 (let ((fc (current-fill-column)))
23528 (when (and fc (> (current-column) fc))
23529 (let* ((fill-prefix (org-adaptive-fill-function))
23530 ;; Enforce empty fill prefix, if required. Otherwise, it
23531 ;; will be computed again.
23532 (adaptive-fill-mode (not (equal fill-prefix ""))))
23533 (when fill-prefix (do-auto-fill))))))
23535 (defun org-comment-line-break-function (&optional soft)
23536 "Break line at point and indent, continuing comment if within one.
23537 The inserted newline is marked hard if variable
23538 `use-hard-newlines' is true, unless optional argument SOFT is
23539 non-nil."
23540 (if soft (insert-and-inherit ?\n) (newline 1))
23541 (save-excursion (forward-char -1) (delete-horizontal-space))
23542 (delete-horizontal-space)
23543 (indent-to-left-margin)
23544 (insert-before-markers-and-inherit fill-prefix))
23547 ;;; Fixed Width Areas
23549 (defun org-toggle-fixed-width ()
23550 "Toggle fixed-width markup.
23552 Add or remove fixed-width markup on current line, whenever it
23553 makes sense. Return an error otherwise.
23555 If a region is active and if it contains only fixed-width areas
23556 or blank lines, remove all fixed-width markup in it. If the
23557 region contains anything else, convert all non-fixed-width lines
23558 to fixed-width ones.
23560 Blank lines at the end of the region are ignored unless the
23561 region only contains such lines."
23562 (interactive)
23563 (if (not (org-region-active-p))
23564 ;; No region:
23566 ;; Remove fixed width marker only in a fixed-with element.
23568 ;; Add fixed width maker in paragraphs, in blank lines after
23569 ;; elements or at the beginning of a headline or an inlinetask,
23570 ;; and before any one-line elements (e.g., a clock).
23571 (progn
23572 (beginning-of-line)
23573 (let* ((element (org-element-at-point))
23574 (type (org-element-type element)))
23575 (cond
23576 ((and (eq type 'fixed-width)
23577 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23578 (replace-match
23579 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23580 ((and (memq type '(babel-call clock comment diary-sexp headline
23581 horizontal-rule keyword paragraph
23582 planning))
23583 (<= (org-element-property :post-affiliated element) (point)))
23584 (skip-chars-forward " \t")
23585 (insert ": "))
23586 ((and (looking-at-p "[ \t]*$")
23587 (or (eq type 'inlinetask)
23588 (save-excursion
23589 (skip-chars-forward " \r\t\n")
23590 (<= (org-element-property :end element) (point)))))
23591 (delete-region (point) (line-end-position))
23592 (org-indent-line)
23593 (insert ": "))
23594 (t (user-error "Cannot insert a fixed-width line here")))))
23595 ;; Region active.
23596 (let* ((begin (save-excursion
23597 (goto-char (region-beginning))
23598 (line-beginning-position)))
23599 (end (copy-marker
23600 (save-excursion
23601 (goto-char (region-end))
23602 (unless (eolp) (beginning-of-line))
23603 (if (save-excursion (re-search-backward "\\S-" begin t))
23604 (progn (skip-chars-backward " \r\t\n") (point))
23605 (point)))))
23606 (all-fixed-width-p
23607 (catch 'not-all-p
23608 (save-excursion
23609 (goto-char begin)
23610 (skip-chars-forward " \r\t\n")
23611 (when (eobp) (throw 'not-all-p nil))
23612 (while (< (point) end)
23613 (let ((element (org-element-at-point)))
23614 (if (eq (org-element-type element) 'fixed-width)
23615 (goto-char (org-element-property :end element))
23616 (throw 'not-all-p nil))))
23617 t))))
23618 (if all-fixed-width-p
23619 (save-excursion
23620 (goto-char begin)
23621 (while (< (point) end)
23622 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23623 (replace-match
23624 "" nil nil nil
23625 (if (= (line-end-position) (match-end 0)) 0 1)))
23626 (forward-line)))
23627 (let ((min-ind (point-max)))
23628 ;; Find minimum indentation across all lines.
23629 (save-excursion
23630 (goto-char begin)
23631 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23632 (setq min-ind 0)
23633 (catch 'zerop
23634 (while (< (point) end)
23635 (unless (looking-at-p "[ \t]*$")
23636 (let ((ind (org-get-indentation)))
23637 (setq min-ind (min min-ind ind))
23638 (when (zerop ind) (throw 'zerop t))))
23639 (forward-line)))))
23640 ;; Loop over all lines and add fixed-width markup everywhere
23641 ;; but in fixed-width lines.
23642 (save-excursion
23643 (goto-char begin)
23644 (while (< (point) end)
23645 (cond
23646 ((org-at-heading-p)
23647 (insert ": ")
23648 (forward-line)
23649 (while (and (< (point) end) (looking-at-p "[ \t]*$"))
23650 (insert ":")
23651 (forward-line)))
23652 ((looking-at-p "[ \t]*:\\( \\|$\\)")
23653 (let* ((element (org-element-at-point))
23654 (element-end (org-element-property :end element)))
23655 (if (eq (org-element-type element) 'fixed-width)
23656 (progn (goto-char element-end)
23657 (skip-chars-backward " \r\t\n")
23658 (forward-line))
23659 (let ((limit (min end element-end)))
23660 (while (< (point) limit)
23661 (org-move-to-column min-ind t)
23662 (insert ": ")
23663 (forward-line))))))
23665 (org-move-to-column min-ind t)
23666 (insert ": ")
23667 (forward-line)))))))
23668 (set-marker end nil))))
23671 ;;; Comments
23673 ;; Org comments syntax is quite complex. It requires the entire line
23674 ;; to be just a comment. Also, even with the right syntax at the
23675 ;; beginning of line, some some elements (i.e. verse-block or
23676 ;; example-block) don't accept comments. Usual Emacs comment commands
23677 ;; cannot cope with those requirements. Therefore, Org replaces them.
23679 ;; Org still relies on `comment-dwim', but cannot trust
23680 ;; `comment-only-p'. So, `comment-region-function' and
23681 ;; `uncomment-region-function' both point
23682 ;; to`org-comment-or-uncomment-region'. Eventually,
23683 ;; `org-insert-comment' takes care of insertion of comments at the
23684 ;; beginning of line.
23686 ;; `org-setup-comments-handling' install comments related variables
23687 ;; during `org-mode' initialization.
23689 (defun org-setup-comments-handling ()
23690 (interactive)
23691 (setq-local comment-use-syntax nil)
23692 (setq-local comment-start "# ")
23693 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23694 (setq-local comment-insert-comment-function 'org-insert-comment)
23695 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23696 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23698 (defun org-insert-comment ()
23699 "Insert an empty comment above current line.
23700 If the line is empty, insert comment at its beginning. When
23701 point is within a source block, comment according to the related
23702 major mode."
23703 (if (let ((element (org-element-at-point)))
23704 (and (eq (org-element-type element) 'src-block)
23705 (< (save-excursion
23706 (goto-char (org-element-property :post-affiliated element))
23707 (line-end-position))
23708 (point))
23709 (> (save-excursion
23710 (goto-char (org-element-property :end element))
23711 (skip-chars-backward " \r\t\n")
23712 (line-beginning-position))
23713 (point))))
23714 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23715 (beginning-of-line)
23716 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23717 (open-line 1))
23718 (org-indent-line)
23719 (insert "# ")))
23721 (defvar comment-empty-lines) ; From newcomment.el.
23722 (defun org-comment-or-uncomment-region (beg end &rest _)
23723 "Comment or uncomment each non-blank line in the region.
23724 Uncomment each non-blank line between BEG and END if it only
23725 contains commented lines. Otherwise, comment them. If region is
23726 strictly within a source block, use appropriate comment syntax."
23727 (if (let ((element (org-element-at-point)))
23728 (and (eq (org-element-type element) 'src-block)
23729 (< (save-excursion
23730 (goto-char (org-element-property :post-affiliated element))
23731 (line-end-position))
23732 beg)
23733 (>= (save-excursion
23734 (goto-char (org-element-property :end element))
23735 (skip-chars-backward " \r\t\n")
23736 (line-beginning-position))
23737 end)))
23738 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23739 (save-restriction
23740 ;; Restrict region
23741 (narrow-to-region (save-excursion (goto-char beg)
23742 (skip-chars-forward " \r\t\n" end)
23743 (line-beginning-position))
23744 (save-excursion (goto-char end)
23745 (skip-chars-backward " \r\t\n" beg)
23746 (line-end-position)))
23747 (let ((uncommentp
23748 ;; UNCOMMENTP is non-nil when every non blank line between
23749 ;; BEG and END is a comment.
23750 (save-excursion
23751 (goto-char (point-min))
23752 (while (and (not (eobp))
23753 (let ((element (org-element-at-point)))
23754 (and (eq (org-element-type element) 'comment)
23755 (goto-char (min (point-max)
23756 (org-element-property
23757 :end element)))))))
23758 (eobp))))
23759 (if uncommentp
23760 ;; Only blank lines and comments in region: uncomment it.
23761 (save-excursion
23762 (goto-char (point-min))
23763 (while (not (eobp))
23764 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23765 (replace-match "" nil nil nil 1))
23766 (forward-line)))
23767 ;; Comment each line in region.
23768 (let ((min-indent (point-max)))
23769 ;; First find the minimum indentation across all lines.
23770 (save-excursion
23771 (goto-char (point-min))
23772 (while (and (not (eobp)) (not (zerop min-indent)))
23773 (unless (looking-at "[ \t]*$")
23774 (setq min-indent (min min-indent (current-indentation))))
23775 (forward-line)))
23776 ;; Then loop over all lines.
23777 (save-excursion
23778 (goto-char (point-min))
23779 (while (not (eobp))
23780 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23781 ;; Don't get fooled by invisible text (e.g. link path)
23782 ;; when moving to column MIN-INDENT.
23783 (let ((buffer-invisibility-spec nil))
23784 (org-move-to-column min-indent t))
23785 (insert comment-start))
23786 (forward-line)))))))))
23788 (defun org-comment-dwim (_arg)
23789 "Call `comment-dwim' within a source edit buffer if needed."
23790 (interactive "*P")
23791 (if (org-in-src-block-p)
23792 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23793 (call-interactively 'comment-dwim)))
23796 ;;; Timestamps API
23798 ;; This section contains tools to operate on timestamp objects, as
23799 ;; returned by, e.g. `org-element-context'.
23801 (defun org-timestamp--to-internal-time (timestamp &optional end)
23802 "Encode TIMESTAMP object into Emacs internal time.
23803 Use end of date range or time range when END is non-nil."
23804 (apply #'encode-time
23805 (cons 0
23806 (mapcar
23807 (lambda (prop) (or (org-element-property prop timestamp) 0))
23808 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23809 '(:minute-start :hour-start :day-start :month-start
23810 :year-start))))))
23812 (defun org-timestamp-has-time-p (timestamp)
23813 "Non-nil when TIMESTAMP has a time specified."
23814 (org-element-property :hour-start timestamp))
23816 (defun org-timestamp-format (timestamp format &optional end utc)
23817 "Format a TIMESTAMP object into a string.
23819 FORMAT is a format specifier to be passed to
23820 `format-time-string'.
23822 When optional argument END is non-nil, use end of date-range or
23823 time-range, if possible.
23825 When optional argument UTC is non-nil, time will be expressed as
23826 Universal Time."
23827 (format-time-string
23828 format (org-timestamp--to-internal-time timestamp end)
23829 (and utc t)))
23831 (defun org-timestamp-split-range (timestamp &optional end)
23832 "Extract a TIMESTAMP object from a date or time range.
23834 END, when non-nil, means extract the end of the range.
23835 Otherwise, extract its start.
23837 Return a new timestamp object."
23838 (let ((type (org-element-property :type timestamp)))
23839 (if (memq type '(active inactive diary)) timestamp
23840 (let ((split-ts (org-element-copy timestamp)))
23841 ;; Set new type.
23842 (org-element-put-property
23843 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23844 ;; Copy start properties over end properties if END is
23845 ;; non-nil. Otherwise, copy end properties over `start' ones.
23846 (let ((p-alist '((:minute-start . :minute-end)
23847 (:hour-start . :hour-end)
23848 (:day-start . :day-end)
23849 (:month-start . :month-end)
23850 (:year-start . :year-end))))
23851 (dolist (p-cell p-alist)
23852 (org-element-put-property
23853 split-ts
23854 (funcall (if end #'car #'cdr) p-cell)
23855 (org-element-property
23856 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23857 ;; Eventually refresh `:raw-value'.
23858 (org-element-put-property split-ts :raw-value nil)
23859 (org-element-put-property
23860 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23862 (defun org-timestamp-translate (timestamp &optional boundary)
23863 "Translate TIMESTAMP object to custom format.
23865 Format string is defined in `org-time-stamp-custom-formats',
23866 which see.
23868 When optional argument BOUNDARY is non-nil, it is either the
23869 symbol `start' or `end'. In this case, only translate the
23870 starting or ending part of TIMESTAMP if it is a date or time
23871 range. Otherwise, translate both parts.
23873 Return timestamp as-is if `org-display-custom-times' is nil or if
23874 it has a `diary' type."
23875 (let ((type (org-element-property :type timestamp)))
23876 (if (or (not org-display-custom-times) (eq type 'diary))
23877 (org-element-interpret-data timestamp)
23878 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23879 org-time-stamp-custom-formats)))
23880 (if (and (not boundary) (memq type '(active-range inactive-range)))
23881 (concat (org-timestamp-format timestamp fmt)
23882 "--"
23883 (org-timestamp-format timestamp fmt t))
23884 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23888 ;;; Other stuff.
23890 (defvar reftex-docstruct-symbol)
23891 (defvar reftex-cite-format)
23892 (defvar org--rds)
23894 (defun org-reftex-citation ()
23895 "Use reftex-citation to insert a citation into the buffer.
23896 This looks for a line like
23898 #+BIBLIOGRAPHY: foo plain option:-d
23900 and derives from it that foo.bib is the bibliography file relevant
23901 for this document. It then installs the necessary environment for RefTeX
23902 to work in this buffer and calls `reftex-citation' to insert a citation
23903 into the buffer.
23905 Export of such citations to both LaTeX and HTML is handled by the contributed
23906 package ox-bibtex by Taru Karttunen."
23907 (interactive)
23908 (let ((reftex-docstruct-symbol 'org--rds)
23909 (reftex-cite-format "\\cite{%l}")
23910 org--rds bib)
23911 (save-excursion
23912 (save-restriction
23913 (widen)
23914 (let ((case-fold-search t)
23915 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23916 (if (not (save-excursion
23917 (or (re-search-forward re nil t)
23918 (re-search-backward re nil t))))
23919 (user-error "No bibliography defined in file")
23920 (setq bib (concat (match-string 1) ".bib")
23921 org--rds (list (list 'bib bib)))))))
23922 (call-interactively 'reftex-citation)))
23924 ;;;; Functions extending outline functionality
23926 (defun org-beginning-of-line (&optional arg)
23927 "Go to the beginning of the current line. If that is invisible, continue
23928 to a visible line beginning. This makes the function of C-a more intuitive.
23929 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23930 first attempt, and only move to after the tags when the cursor is already
23931 beyond the end of the headline."
23932 (interactive "P")
23933 (let ((pos (point))
23934 (special (if (consp org-special-ctrl-a/e)
23935 (car org-special-ctrl-a/e)
23936 org-special-ctrl-a/e))
23937 deactivate-mark refpos)
23938 (call-interactively (if (org-bound-and-true-p visual-line-mode)
23939 #'beginning-of-visual-line
23940 #'move-beginning-of-line))
23941 (cond
23942 ((or arg (not special)))
23943 ((and (looking-at org-complex-heading-regexp)
23944 (eq (char-after (match-end 1)) ?\s))
23945 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23946 (point-at-eol)))
23947 (goto-char
23948 (if (eq special t)
23949 (cond ((> pos refpos) refpos)
23950 ((= pos (point)) refpos)
23951 (t (point)))
23952 (cond ((> pos (point)) (point))
23953 ((not (eq last-command this-command)) (point))
23954 (t refpos)))))
23955 ((org-at-item-p)
23956 ;; Being at an item and not looking at an the item means point
23957 ;; was previously moved to beginning of a visual line, which
23958 ;; doesn't contain the item. Therefore, do nothing special,
23959 ;; just stay here.
23960 (when (looking-at org-list-full-item-re)
23961 ;; Set special position at first white space character after
23962 ;; bullet, and check-box, if any.
23963 (let ((after-bullet
23964 (let ((box (match-end 3)))
23965 (if (not box) (match-end 1)
23966 (let ((after (char-after box)))
23967 (if (and after (= after ? )) (1+ box) box))))))
23968 ;; Special case: Move point to special position when
23969 ;; currently after it or at beginning of line.
23970 (if (eq special t)
23971 (when (or (> pos after-bullet) (= (point) pos))
23972 (goto-char after-bullet))
23973 ;; Reversed case: Move point to special position when
23974 ;; point was already at beginning of line and command is
23975 ;; repeated.
23976 (when (and (= (point) pos) (eq last-command this-command))
23977 (goto-char after-bullet))))))))
23978 (setq disable-point-adjustment
23979 (or (not (invisible-p (point)))
23980 (not (invisible-p (max (point-min) (1- (point))))))))
23982 (defun org-end-of-line (&optional arg)
23983 "Go to the end of the line.
23984 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23985 tags on the first attempt, and only move to after the tags when
23986 the cursor is already beyond the end of the headline."
23987 (interactive "P")
23988 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23989 org-special-ctrl-a/e))
23990 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23991 'end-of-visual-line)
23992 ((fboundp 'move-end-of-line) 'move-end-of-line)
23993 (t 'end-of-line)))
23994 deactivate-mark)
23995 (if (or (not special) arg) (call-interactively move-fun)
23996 (let* ((element (save-excursion (beginning-of-line)
23997 (org-element-at-point)))
23998 (type (org-element-type element)))
23999 (cond
24000 ((memq type '(headline inlinetask))
24001 (let ((pos (point)))
24002 (beginning-of-line 1)
24003 (if (looking-at ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$")
24004 (if (eq special t)
24005 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
24006 (goto-char (match-beginning 1))
24007 (goto-char (match-end 0)))
24008 (if (or (< pos (match-end 0))
24009 (not (eq this-command last-command)))
24010 (goto-char (match-end 0))
24011 (goto-char (match-beginning 1))))
24012 (call-interactively move-fun))))
24013 ((outline-invisible-p (line-end-position))
24014 ;; If element is hidden, `move-end-of-line' would put point
24015 ;; after it. Use `end-of-line' to stay on current line.
24016 (call-interactively 'end-of-line))
24017 (t (call-interactively move-fun))))))
24018 (setq disable-point-adjustment
24019 (or (not (invisible-p (point)))
24020 (not (invisible-p (max (point-min) (1- (point))))))))
24022 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
24023 (define-key org-mode-map "\C-e" 'org-end-of-line)
24025 (defun org-backward-sentence (&optional _arg)
24026 "Go to beginning of sentence, or beginning of table field.
24027 This will call `backward-sentence' or `org-table-beginning-of-field',
24028 depending on context."
24029 (interactive)
24030 (let* ((element (org-element-at-point))
24031 (contents-begin (org-element-property :contents-begin element))
24032 (table (org-element-lineage element '(table) t)))
24033 (if (and table
24034 (> (point) contents-begin)
24035 (<= (point) (org-element-property :contents-end table)))
24036 (call-interactively #'org-table-beginning-of-field)
24037 (save-restriction
24038 (when (and contents-begin
24039 (< (point-min) contents-begin)
24040 (> (point) contents-begin))
24041 (narrow-to-region contents-begin
24042 (org-element-property :contents-end element)))
24043 (call-interactively #'backward-sentence)))))
24045 (defun org-forward-sentence (&optional _arg)
24046 "Go to end of sentence, or end of table field.
24047 This will call `forward-sentence' or `org-table-end-of-field',
24048 depending on context."
24049 (interactive)
24050 (let* ((element (org-element-at-point))
24051 (contents-end (org-element-property :contents-end element))
24052 (table (org-element-lineage element '(table) t)))
24053 (if (and table
24054 (>= (point) (org-element-property :contents-begin table))
24055 (< (point) contents-end))
24056 (call-interactively #'org-table-end-of-field)
24057 (save-restriction
24058 (when (and contents-end
24059 (> (point-max) contents-end)
24060 ;; Skip blank lines between elements.
24061 (< (org-element-property :end element)
24062 (save-excursion (goto-char contents-end)
24063 (skip-chars-forward " \r\t\n"))))
24064 (narrow-to-region (org-element-property :contents-begin element)
24065 contents-end))
24066 (call-interactively #'forward-sentence)))))
24068 (define-key org-mode-map "\M-a" 'org-backward-sentence)
24069 (define-key org-mode-map "\M-e" 'org-forward-sentence)
24071 (defun org-kill-line (&optional _arg)
24072 "Kill line, to tags or end of line."
24073 (interactive)
24074 (cond
24075 ((or (not org-special-ctrl-k)
24076 (bolp)
24077 (not (org-at-heading-p)))
24078 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
24079 org-ctrl-k-protect-subtree
24080 (or (eq org-ctrl-k-protect-subtree 'error)
24081 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
24082 (user-error "C-k aborted as it would kill a hidden subtree"))
24083 (call-interactively
24084 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
24085 ((looking-at ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$")
24086 (kill-region (point) (match-beginning 1))
24087 (org-set-tags nil t))
24088 (t (kill-region (point) (point-at-eol)))))
24090 (define-key org-mode-map "\C-k" 'org-kill-line)
24092 (defun org-yank (&optional arg)
24093 "Yank. If the kill is a subtree, treat it specially.
24094 This command will look at the current kill and check if is a single
24095 subtree, or a series of subtrees[1]. If it passes the test, and if the
24096 cursor is at the beginning of a line or after the stars of a currently
24097 empty headline, then the yank is handled specially. How exactly depends
24098 on the value of the following variables.
24100 `org-yank-folded-subtrees'
24101 By default, this variable is non-nil, which results in subtree(s)
24102 being folded after insertion, but only if doing so would now
24103 swallow text after the yanked text.
24105 `org-yank-adjusted-subtrees'
24106 When non-nil (the default value is nil), the subtree will be
24107 promoted or demoted in order to fit into the local outline tree
24108 structure, which means that the level will be adjusted so that it
24109 becomes the smaller one of the two *visible* surrounding headings.
24111 Any prefix to this command will cause `yank' to be called directly with
24112 no special treatment. In particular, a simple \\[universal-argument] prefix \
24113 will just
24114 plainly yank the text as it is.
24116 \[1] The test checks if the first non-white line is a heading
24117 and if there are no other headings with fewer stars."
24118 (interactive "P")
24119 (org-yank-generic 'yank arg))
24121 (defun org-yank-generic (command arg)
24122 "Perform some yank-like command.
24124 This function implements the behavior described in the `org-yank'
24125 documentation. However, it has been generalized to work for any
24126 interactive command with similar behavior."
24128 ;; pretend to be command COMMAND
24129 (setq this-command command)
24131 (if arg
24132 (call-interactively command)
24134 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24135 (and (org-kill-is-subtree-p)
24136 (or (bolp)
24137 (and (looking-at "[ \t]*$")
24138 (string-match
24139 "\\`\\*+\\'"
24140 (buffer-substring (point-at-bol) (point)))))))
24141 swallowp)
24142 (cond
24143 ((and subtreep org-yank-folded-subtrees)
24144 (let ((beg (point))
24145 end)
24146 (if (and subtreep org-yank-adjusted-subtrees)
24147 (org-paste-subtree nil nil 'for-yank)
24148 (call-interactively command))
24150 (setq end (point))
24151 (goto-char beg)
24152 (when (and (bolp) subtreep
24153 (not (setq swallowp
24154 (org-yank-folding-would-swallow-text beg end))))
24155 (org-with-limited-levels
24156 (or (looking-at org-outline-regexp)
24157 (re-search-forward org-outline-regexp-bol end t))
24158 (while (and (< (point) end) (looking-at org-outline-regexp))
24159 (outline-hide-subtree)
24160 (org-cycle-show-empty-lines 'folded)
24161 (condition-case nil
24162 (outline-forward-same-level 1)
24163 (error (goto-char end))))))
24164 (when swallowp
24165 (message
24166 "Inserted text not folded because that would swallow text"))
24168 (goto-char end)
24169 (skip-chars-forward " \t\n\r")
24170 (beginning-of-line 1)
24171 (push-mark beg 'nomsg)))
24172 ((and subtreep org-yank-adjusted-subtrees)
24173 (let ((beg (point-at-bol)))
24174 (org-paste-subtree nil nil 'for-yank)
24175 (push-mark beg 'nomsg)))
24177 (call-interactively command))))))
24179 (defun org-yank-folding-would-swallow-text (beg end)
24180 "Would hide-subtree at BEG swallow any text after END?"
24181 (let (level)
24182 (org-with-limited-levels
24183 (save-excursion
24184 (goto-char beg)
24185 (when (or (looking-at org-outline-regexp)
24186 (re-search-forward org-outline-regexp-bol end t))
24187 (setq level (org-outline-level)))
24188 (goto-char end)
24189 (skip-chars-forward " \t\r\n\v\f")
24190 (not (or (eobp)
24191 (and (bolp) (looking-at-p org-outline-regexp)
24192 (<= (org-outline-level) level))))))))
24194 (define-key org-mode-map "\C-y" 'org-yank)
24196 (defun org-truely-invisible-p ()
24197 "Check if point is at a character currently not visible.
24198 This version does not only check the character property, but also
24199 `visible-mode'."
24200 ;; Early versions of noutline don't have `outline-invisible-p'.
24201 (unless (org-bound-and-true-p visible-mode)
24202 (outline-invisible-p)))
24204 (defun org-invisible-p2 ()
24205 "Check if point is at a character currently not visible."
24206 (save-excursion
24207 (when (and (eolp) (not (bobp))) (backward-char 1))
24208 ;; Early versions of noutline don't have `outline-invisible-p'.
24209 (outline-invisible-p)))
24211 (defun org-back-to-heading (&optional invisible-ok)
24212 "Call `outline-back-to-heading', but provide a better error message."
24213 (condition-case nil
24214 (outline-back-to-heading invisible-ok)
24215 (error (error "Before first headline at position %d in buffer %s"
24216 (point) (current-buffer)))))
24218 (defun org-before-first-heading-p ()
24219 "Before first heading?"
24220 (save-excursion
24221 (end-of-line)
24222 (null (re-search-backward org-outline-regexp-bol nil t))))
24224 (defun org-at-heading-p (&optional ignored)
24225 (outline-on-heading-p t))
24226 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24227 ;;; warning was only added in Org 9.0, which should be taken into
24228 ;;; account when deciding when to remove the alias.
24229 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24231 (defun org-in-commented-heading-p (&optional no-inheritance)
24232 "Non-nil if point is under a commented heading.
24233 This function also checks ancestors of the current headline,
24234 unless optional argument NO-INHERITANCE is non-nil."
24235 (cond
24236 ((org-before-first-heading-p) nil)
24237 ((let ((headline (nth 4 (org-heading-components))))
24238 (and headline
24239 (let ((case-fold-search nil))
24240 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24241 headline)))))
24242 (no-inheritance nil)
24244 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24246 (defun org-at-comment-p nil
24247 "Is cursor in a commented line?"
24248 (save-excursion
24249 (save-match-data
24250 (beginning-of-line)
24251 (looking-at "^[ \t]*# "))))
24253 (defun org-at-drawer-p nil
24254 "Is cursor at a drawer keyword?"
24255 (save-excursion
24256 (move-beginning-of-line 1)
24257 (looking-at org-drawer-regexp)))
24259 (defun org-at-block-p nil
24260 "Is cursor at a block keyword?"
24261 (save-excursion
24262 (move-beginning-of-line 1)
24263 (looking-at org-block-regexp)))
24265 (defun org-point-at-end-of-empty-headline ()
24266 "If point is at the end of an empty headline, return t, else nil.
24267 If the heading only contains a TODO keyword, it is still still considered
24268 empty."
24269 (and (looking-at "[ \t]*$")
24270 (when org-todo-line-regexp
24271 (save-excursion
24272 (beginning-of-line 1)
24273 (let ((case-fold-search nil))
24274 (looking-at org-todo-line-regexp)
24275 (string= (match-string 3) ""))))))
24277 (defun org-at-heading-or-item-p ()
24278 (or (org-at-heading-p) (org-at-item-p)))
24280 (defun org-at-target-p ()
24281 (or (org-in-regexp org-radio-target-regexp)
24282 (org-in-regexp org-target-regexp)))
24283 ;; Compatibility alias with Org versions < 7.8.03
24284 (defalias 'org-on-target-p 'org-at-target-p)
24286 (defun org-up-heading-all (arg)
24287 "Move to the heading line of which the present line is a subheading.
24288 This function considers both visible and invisible heading lines.
24289 With argument, move up ARG levels."
24290 (if (fboundp 'outline-up-heading-all)
24291 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24292 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24294 (defun org-up-heading-safe ()
24295 "Move to the heading line of which the present line is a subheading.
24296 This version will not throw an error. It will return the level of the
24297 headline found, or nil if no higher level is found.
24299 Also, this function will be a lot faster than `outline-up-heading',
24300 because it relies on stars being the outline starters. This can really
24301 make a significant difference in outlines with very many siblings."
24302 (when (ignore-errors (org-back-to-heading t))
24303 (let ((level-up (1- (funcall outline-level))))
24304 (and (> level-up 0)
24305 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24306 (funcall outline-level)))))
24308 (defun org-first-sibling-p ()
24309 "Is this heading the first child of its parents?"
24310 (interactive)
24311 (let ((re org-outline-regexp-bol)
24312 level l)
24313 (unless (org-at-heading-p t)
24314 (user-error "Not at a heading"))
24315 (setq level (funcall outline-level))
24316 (save-excursion
24317 (if (not (re-search-backward re nil t))
24319 (setq l (funcall outline-level))
24320 (< l level)))))
24322 (defun org-goto-sibling (&optional previous)
24323 "Goto the next sibling, even if it is invisible.
24324 When PREVIOUS is set, go to the previous sibling instead. Returns t
24325 when a sibling was found. When none is found, return nil and don't
24326 move point."
24327 (let ((fun (if previous 're-search-backward 're-search-forward))
24328 (pos (point))
24329 (re org-outline-regexp-bol)
24330 level l)
24331 (when (ignore-errors (org-back-to-heading t))
24332 (setq level (funcall outline-level))
24333 (catch 'exit
24334 (or previous (forward-char 1))
24335 (while (funcall fun re nil t)
24336 (setq l (funcall outline-level))
24337 (when (< l level) (goto-char pos) (throw 'exit nil))
24338 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24339 (goto-char pos)
24340 nil))))
24342 (defun org-show-siblings ()
24343 "Show all siblings of the current headline."
24344 (save-excursion
24345 (while (org-goto-sibling) (org-flag-heading nil)))
24346 (save-excursion
24347 (while (org-goto-sibling 'previous)
24348 (org-flag-heading nil))))
24350 (defun org-goto-first-child ()
24351 "Goto the first child, even if it is invisible.
24352 Return t when a child was found. Otherwise don't move point and
24353 return nil."
24354 (let (level (pos (point)) (re org-outline-regexp-bol))
24355 (when (ignore-errors (org-back-to-heading t))
24356 (setq level (outline-level))
24357 (forward-char 1)
24358 (if (and (re-search-forward re nil t) (> (outline-level) level))
24359 (progn (goto-char (match-beginning 0)) t)
24360 (goto-char pos) nil))))
24362 (defun org-show-hidden-entry ()
24363 "Show an entry where even the heading is hidden."
24364 (save-excursion
24365 (org-show-entry)))
24367 (defun org-flag-heading (flag &optional entry)
24368 "Flag the current heading. FLAG non-nil means make invisible.
24369 When ENTRY is non-nil, show the entire entry."
24370 (save-excursion
24371 (org-back-to-heading t)
24372 ;; Check if we should show the entire entry
24373 (if entry
24374 (progn
24375 (org-show-entry)
24376 (save-excursion
24377 (and (outline-next-heading)
24378 (org-flag-heading nil))))
24379 (outline-flag-region (max (point-min) (1- (point)))
24380 (save-excursion (outline-end-of-heading) (point))
24381 flag))))
24383 (defun org-get-next-sibling ()
24384 "Move to next heading of the same level, and return point.
24385 If there is no such heading, return nil.
24386 This is like outline-next-sibling, but invisible headings are ok."
24387 (let ((level (funcall outline-level)))
24388 (outline-next-heading)
24389 (while (and (not (eobp)) (> (funcall outline-level) level))
24390 (outline-next-heading))
24391 (unless (or (eobp) (< (funcall outline-level) level))
24392 (point))))
24394 (defun org-get-last-sibling ()
24395 "Move to previous heading of the same level, and return point.
24396 If there is no such heading, return nil."
24397 (let ((opoint (point))
24398 (level (funcall outline-level)))
24399 (outline-previous-heading)
24400 (when (and (/= (point) opoint) (outline-on-heading-p t))
24401 (while (and (> (funcall outline-level) level)
24402 (not (bobp)))
24403 (outline-previous-heading))
24404 (unless (< (funcall outline-level) level)
24405 (point)))))
24407 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24408 "Goto to the end of a subtree."
24409 ;; This contains an exact copy of the original function, but it uses
24410 ;; `org-back-to-heading', to make it work also in invisible
24411 ;; trees. And is uses an invisible-ok argument.
24412 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24413 ;; Furthermore, when used inside Org, finding the end of a large subtree
24414 ;; with many children and grandchildren etc, this can be much faster
24415 ;; than the outline version.
24416 (org-back-to-heading invisible-ok)
24417 (let ((first t)
24418 (level (funcall outline-level)))
24419 (if (and (derived-mode-p 'org-mode) (< level 1000))
24420 ;; A true heading (not a plain list item), in Org-mode
24421 ;; This means we can easily find the end by looking
24422 ;; only for the right number of stars. Using a regexp to do
24423 ;; this is so much faster than using a Lisp loop.
24424 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24425 (forward-char 1)
24426 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24427 ;; something else, do it the slow way
24428 (while (and (not (eobp))
24429 (or first (> (funcall outline-level) level)))
24430 (setq first nil)
24431 (outline-next-heading)))
24432 (unless to-heading
24433 (when (memq (preceding-char) '(?\n ?\^M))
24434 ;; Go to end of line before heading
24435 (forward-char -1)
24436 (when (memq (preceding-char) '(?\n ?\^M))
24437 ;; leave blank line before heading
24438 (forward-char -1)))))
24439 (point))
24441 (defun org-end-of-meta-data (&optional full)
24442 "Skip planning line and properties drawer in current entry.
24443 When optional argument FULL is non-nil, also skip empty lines,
24444 clocking lines and regular drawers at the beginning of the
24445 entry."
24446 (org-back-to-heading t)
24447 (forward-line)
24448 (when (looking-at-p org-planning-line-re) (forward-line))
24449 (when (looking-at org-property-drawer-re)
24450 (goto-char (match-end 0))
24451 (forward-line))
24452 (when (and full (not (org-at-heading-p)))
24453 (catch 'exit
24454 (let ((end (save-excursion (outline-next-heading) (point)))
24455 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24456 (while (not (eobp))
24457 (cond ((looking-at-p org-drawer-regexp)
24458 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24459 (forward-line)
24460 (throw 'exit t)))
24461 ((looking-at-p re) (forward-line))
24462 (t (throw 'exit t))))))))
24464 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24465 "Move forward to the ARG'th subheading at same level as this one.
24466 Stop at the first and last subheadings of a superior heading.
24467 Normally this only looks at visible headings, but when INVISIBLE-OK is
24468 non-nil it will also look at invisible ones."
24469 (interactive "p")
24470 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24471 (if (and arg (< arg 0))
24472 (goto-char (point-min))
24473 (outline-next-heading))
24474 (org-at-heading-p)
24475 (let ((level (- (match-end 0) (match-beginning 0) 1))
24476 (f (if (and arg (< arg 0))
24477 're-search-backward
24478 're-search-forward))
24479 (count (if arg (abs arg) 1))
24480 (result (point)))
24481 (while (and (prog1 (> count 0)
24482 (forward-char (if (and arg (< arg 0)) -1 1)))
24483 (funcall f org-outline-regexp-bol nil 'move))
24484 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24485 (cond ((< l level) (setq count 0))
24486 ((and (= l level)
24487 (or invisible-ok
24488 (progn
24489 (goto-char (line-beginning-position))
24490 (not (outline-invisible-p)))))
24491 (setq count (1- count))
24492 (when (eq l level)
24493 (setq result (point)))))))
24494 (goto-char result))
24495 (beginning-of-line 1)))
24497 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24498 "Move backward to the ARG'th subheading at same level as this one.
24499 Stop at the first and last subheadings of a superior heading."
24500 (interactive "p")
24501 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24503 (defun org-next-visible-heading (arg)
24504 "Move to the next visible heading.
24506 This function wraps `outline-next-visible-heading' with
24507 `org-with-limited-levels' in order to skip over inline tasks and
24508 respect customization of `org-odd-levels-only'."
24509 (interactive "p")
24510 (org-with-limited-levels
24511 (outline-next-visible-heading arg)))
24513 (defun org-previous-visible-heading (arg)
24514 "Move to the previous visible heading.
24516 This function wraps `outline-previous-visible-heading' with
24517 `org-with-limited-levels' in order to skip over inline tasks and
24518 respect customization of `org-odd-levels-only'."
24519 (interactive "p")
24520 (org-with-limited-levels
24521 (outline-previous-visible-heading arg)))
24523 (defun org-next-block (arg &optional backward block-regexp)
24524 "Jump to the next block.
24526 With a prefix argument ARG, jump forward ARG many blocks.
24528 When BACKWARD is non-nil, jump to the previous block.
24530 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24531 Match data is set according to this regexp when the function
24532 returns.
24534 Return point at beginning of the opening line of found block.
24535 Throw an error if no block is found."
24536 (interactive "p")
24537 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24538 (case-fold-search t)
24539 (search-fn (if backward #'re-search-backward #'re-search-forward))
24540 (count (or arg 1))
24541 (origin (point))
24542 last-element)
24543 (if backward (beginning-of-line) (end-of-line))
24544 (while (and (> count 0) (funcall search-fn re nil t))
24545 (let ((element (save-excursion
24546 (goto-char (match-beginning 0))
24547 (save-match-data (org-element-at-point)))))
24548 (when (and (memq (org-element-type element)
24549 '(center-block comment-block dynamic-block
24550 example-block export-block quote-block
24551 special-block src-block verse-block))
24552 (<= (match-beginning 0)
24553 (org-element-property :post-affiliated element)))
24554 (setq last-element element)
24555 (cl-decf count))))
24556 (if (= count 0)
24557 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24558 (save-match-data (org-show-context)))
24559 (goto-char origin)
24560 (user-error "No %s code blocks" (if backward "previous" "further")))))
24562 (defun org-previous-block (arg &optional block-regexp)
24563 "Jump to the previous block.
24564 With a prefix argument ARG, jump backward ARG many source blocks.
24565 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24566 (interactive "p")
24567 (org-next-block arg t block-regexp))
24569 (defun org-forward-paragraph ()
24570 "Move forward to beginning of next paragraph or equivalent.
24572 The function moves point to the beginning of the next visible
24573 structural element, which can be a paragraph, a table, a list
24574 item, etc. It also provides some special moves for convenience:
24576 - On an affiliated keyword, jump to the beginning of the
24577 relative element.
24578 - On an item or a footnote definition, move to the second
24579 element inside, if any.
24580 - On a table or a property drawer, jump after it.
24581 - On a verse or source block, stop after blank lines."
24582 (interactive)
24583 (when (eobp) (user-error "Cannot move further down"))
24584 (let* ((deactivate-mark nil)
24585 (element (org-element-at-point))
24586 (type (org-element-type element))
24587 (post-affiliated (org-element-property :post-affiliated element))
24588 (contents-begin (org-element-property :contents-begin element))
24589 (contents-end (org-element-property :contents-end element))
24590 (end (let ((end (org-element-property :end element)) (parent element))
24591 (while (and (setq parent (org-element-property :parent parent))
24592 (= (org-element-property :contents-end parent) end))
24593 (setq end (org-element-property :end parent)))
24594 end)))
24595 (cond ((not element)
24596 (skip-chars-forward " \r\t\n")
24597 (or (eobp) (beginning-of-line)))
24598 ;; On affiliated keywords, move to element's beginning.
24599 ((< (point) post-affiliated)
24600 (goto-char post-affiliated))
24601 ;; At a table row, move to the end of the table. Similarly,
24602 ;; at a node property, move to the end of the property
24603 ;; drawer.
24604 ((memq type '(node-property table-row))
24605 (goto-char (org-element-property
24606 :end (org-element-property :parent element))))
24607 ((memq type '(property-drawer table)) (goto-char end))
24608 ;; Consider blank lines as separators in verse and source
24609 ;; blocks to ease editing.
24610 ((memq type '(src-block verse-block))
24611 (when (eq type 'src-block)
24612 (setq contents-end
24613 (save-excursion (goto-char end)
24614 (skip-chars-backward " \r\t\n")
24615 (line-beginning-position))))
24616 (beginning-of-line)
24617 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24618 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24619 (goto-char end)
24620 (skip-chars-forward " \r\t\n")
24621 (if (= (point) contents-end) (goto-char end)
24622 (beginning-of-line))))
24623 ;; With no contents, just skip element.
24624 ((not contents-begin) (goto-char end))
24625 ;; If contents are invisible, skip the element altogether.
24626 ((outline-invisible-p (line-end-position))
24627 (cl-case type
24628 (headline
24629 (org-with-limited-levels (outline-next-visible-heading 1)))
24630 ;; At a plain list, make sure we move to the next item
24631 ;; instead of skipping the whole list.
24632 (plain-list (forward-char)
24633 (org-forward-paragraph))
24634 (otherwise (goto-char end))))
24635 ((>= (point) contents-end) (goto-char end))
24636 ((>= (point) contents-begin)
24637 ;; This can only happen on paragraphs and plain lists.
24638 (cl-case type
24639 (paragraph (goto-char end))
24640 ;; At a plain list, try to move to second element in
24641 ;; first item, if possible.
24642 (plain-list (end-of-line)
24643 (org-forward-paragraph))))
24644 ;; When contents start on the middle of a line (e.g. in
24645 ;; items and footnote definitions), try to reach first
24646 ;; element starting after current line.
24647 ((> (line-end-position) contents-begin)
24648 (end-of-line)
24649 (org-forward-paragraph))
24650 (t (goto-char contents-begin)))))
24652 (defun org-backward-paragraph ()
24653 "Move backward to start of previous paragraph or equivalent.
24655 The function moves point to the beginning of the current
24656 structural element, which can be a paragraph, a table, a list
24657 item, etc., or to the beginning of the previous visible one if
24658 point is already there. It also provides some special moves for
24659 convenience:
24661 - On an affiliated keyword, jump to the first one.
24662 - On a table or a property drawer, move to its beginning.
24663 - On a verse or source block, stop before blank lines."
24664 (interactive)
24665 (when (bobp) (user-error "Cannot move further up"))
24666 (let* ((deactivate-mark nil)
24667 (element (org-element-at-point))
24668 (type (org-element-type element))
24669 (contents-begin (org-element-property :contents-begin element))
24670 (contents-end (org-element-property :contents-end element))
24671 (post-affiliated (org-element-property :post-affiliated element))
24672 (begin (org-element-property :begin element)))
24673 (cond
24674 ((not element) (goto-char (point-min)))
24675 ((= (point) begin)
24676 (backward-char)
24677 (org-backward-paragraph))
24678 ((<= (point) post-affiliated) (goto-char begin))
24679 ((memq type '(node-property table-row))
24680 (goto-char (org-element-property
24681 :post-affiliated (org-element-property :parent element))))
24682 ((memq type '(property-drawer table)) (goto-char begin))
24683 ((memq type '(src-block verse-block))
24684 (when (eq type 'src-block)
24685 (setq contents-begin
24686 (save-excursion (goto-char begin) (forward-line) (point))))
24687 (if (= (point) contents-begin) (goto-char post-affiliated)
24688 ;; Inside a verse block, see blank lines as paragraph
24689 ;; separators.
24690 (let ((origin (point)))
24691 (skip-chars-backward " \r\t\n" contents-begin)
24692 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24693 (skip-chars-forward " \r\t\n" origin)
24694 (if (= (point) origin) (goto-char contents-begin)
24695 (beginning-of-line))))))
24696 ((not contents-begin) (goto-char (or post-affiliated begin)))
24697 ((eq type 'paragraph)
24698 (goto-char contents-begin)
24699 ;; When at first paragraph in an item or a footnote definition,
24700 ;; move directly to beginning of line.
24701 (let ((parent-contents
24702 (org-element-property
24703 :contents-begin (org-element-property :parent element))))
24704 (when (and parent-contents (= parent-contents contents-begin))
24705 (beginning-of-line))))
24706 ;; At the end of a greater element, move to the beginning of the
24707 ;; last element within.
24708 ((>= (point) contents-end)
24709 (goto-char (1- contents-end))
24710 (org-backward-paragraph))
24711 (t (goto-char (or post-affiliated begin))))
24712 ;; Ensure we never leave point invisible.
24713 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24715 (defun org-forward-element ()
24716 "Move forward by one element.
24717 Move to the next element at the same level, when possible."
24718 (interactive)
24719 (cond ((eobp) (user-error "Cannot move further down"))
24720 ((org-with-limited-levels (org-at-heading-p))
24721 (let ((origin (point)))
24722 (goto-char (org-end-of-subtree nil t))
24723 (unless (org-with-limited-levels (org-at-heading-p))
24724 (goto-char origin)
24725 (user-error "Cannot move further down"))))
24727 (let* ((elem (org-element-at-point))
24728 (end (org-element-property :end elem))
24729 (parent (org-element-property :parent elem)))
24730 (cond ((and parent (= (org-element-property :contents-end parent) end))
24731 (goto-char (org-element-property :end parent)))
24732 ((integer-or-marker-p end) (goto-char end))
24733 (t (message "No element at point")))))))
24735 (defun org-backward-element ()
24736 "Move backward by one element.
24737 Move to the previous element at the same level, when possible."
24738 (interactive)
24739 (cond ((bobp) (user-error "Cannot move further up"))
24740 ((org-with-limited-levels (org-at-heading-p))
24741 ;; At a headline, move to the previous one, if any, or stay
24742 ;; here.
24743 (let ((origin (point)))
24744 (org-with-limited-levels (org-backward-heading-same-level 1))
24745 ;; When current headline has no sibling above, move to its
24746 ;; parent.
24747 (when (= (point) origin)
24748 (or (org-with-limited-levels (org-up-heading-safe))
24749 (progn (goto-char origin)
24750 (user-error "Cannot move further up"))))))
24752 (let* ((elem (org-element-at-point))
24753 (beg (org-element-property :begin elem)))
24754 (cond
24755 ;; Move to beginning of current element if point isn't
24756 ;; there already.
24757 ((null beg) (message "No element at point"))
24758 ((/= (point) beg) (goto-char beg))
24759 (t (goto-char beg)
24760 (skip-chars-backward " \r\t\n")
24761 (unless (bobp)
24762 (let ((prev (org-element-at-point)))
24763 (goto-char (org-element-property :begin prev))
24764 (while (and (setq prev (org-element-property :parent prev))
24765 (<= (org-element-property :end prev) beg))
24766 (goto-char (org-element-property :begin prev)))))))))))
24768 (defun org-up-element ()
24769 "Move to upper element."
24770 (interactive)
24771 (if (org-with-limited-levels (org-at-heading-p))
24772 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24773 (let* ((elem (org-element-at-point))
24774 (parent (org-element-property :parent elem)))
24775 (if parent (goto-char (org-element-property :begin parent))
24776 (if (org-with-limited-levels (org-before-first-heading-p))
24777 (user-error "No surrounding element")
24778 (org-with-limited-levels (org-back-to-heading)))))))
24780 (defvar org-element-greater-elements)
24781 (defun org-down-element ()
24782 "Move to inner element."
24783 (interactive)
24784 (let ((element (org-element-at-point)))
24785 (cond
24786 ((memq (org-element-type element) '(plain-list table))
24787 (goto-char (org-element-property :contents-begin element))
24788 (forward-char))
24789 ((memq (org-element-type element) org-element-greater-elements)
24790 ;; If contents are hidden, first disclose them.
24791 (when (outline-invisible-p (line-end-position)) (org-cycle))
24792 (goto-char (or (org-element-property :contents-begin element)
24793 (user-error "No content for this element"))))
24794 (t (user-error "No inner element")))))
24796 (defun org-drag-element-backward ()
24797 "Move backward element at point."
24798 (interactive)
24799 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24800 (let* ((elem (org-element-at-point))
24801 (prev-elem
24802 (save-excursion
24803 (goto-char (org-element-property :begin elem))
24804 (skip-chars-backward " \r\t\n")
24805 (unless (bobp)
24806 (let* ((beg (org-element-property :begin elem))
24807 (prev (org-element-at-point))
24808 (up prev))
24809 (while (and (setq up (org-element-property :parent up))
24810 (<= (org-element-property :end up) beg))
24811 (setq prev up))
24812 prev)))))
24813 ;; Error out if no previous element or previous element is
24814 ;; a parent of the current one.
24815 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24816 (user-error "Cannot drag element backward")
24817 (let ((pos (point)))
24818 (org-element-swap-A-B prev-elem elem)
24819 (goto-char (+ (org-element-property :begin prev-elem)
24820 (- pos (org-element-property :begin elem)))))))))
24822 (defun org-drag-element-forward ()
24823 "Move forward element at point."
24824 (interactive)
24825 (let* ((pos (point))
24826 (elem (org-element-at-point)))
24827 (when (= (point-max) (org-element-property :end elem))
24828 (user-error "Cannot drag element forward"))
24829 (goto-char (org-element-property :end elem))
24830 (let ((next-elem (org-element-at-point)))
24831 (when (or (org-element-nested-p elem next-elem)
24832 (and (eq (org-element-type next-elem) 'headline)
24833 (not (eq (org-element-type elem) 'headline))))
24834 (goto-char pos)
24835 (user-error "Cannot drag element forward"))
24836 ;; Compute new position of point: it's shifted by NEXT-ELEM
24837 ;; body's length (without final blanks) and by the length of
24838 ;; blanks between ELEM and NEXT-ELEM.
24839 (let ((size-next (- (save-excursion
24840 (goto-char (org-element-property :end next-elem))
24841 (skip-chars-backward " \r\t\n")
24842 (forward-line)
24843 ;; Small correction if buffer doesn't end
24844 ;; with a newline character.
24845 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24846 (org-element-property :begin next-elem)))
24847 (size-blank (- (org-element-property :end elem)
24848 (save-excursion
24849 (goto-char (org-element-property :end elem))
24850 (skip-chars-backward " \r\t\n")
24851 (forward-line)
24852 (point)))))
24853 (org-element-swap-A-B elem next-elem)
24854 (goto-char (+ pos size-next size-blank))))))
24856 (defun org-drag-line-forward (arg)
24857 "Drag the line at point ARG lines forward."
24858 (interactive "p")
24859 (dotimes (_ (abs arg))
24860 (let ((c (current-column)))
24861 (if (< 0 arg)
24862 (progn
24863 (beginning-of-line 2)
24864 (transpose-lines 1)
24865 (beginning-of-line 0))
24866 (transpose-lines 1)
24867 (beginning-of-line -1))
24868 (org-move-to-column c))))
24870 (defun org-drag-line-backward (arg)
24871 "Drag the line at point ARG lines backward."
24872 (interactive "p")
24873 (org-drag-line-forward (- arg)))
24875 (defun org-mark-element ()
24876 "Put point at beginning of this element, mark at end.
24878 Interactively, if this command is repeated or (in Transient Mark
24879 mode) if the mark is active, it marks the next element after the
24880 ones already marked."
24881 (interactive)
24882 (let (deactivate-mark)
24883 (if (and (org-called-interactively-p 'any)
24884 (or (and (eq last-command this-command) (mark t))
24885 (and transient-mark-mode mark-active)))
24886 (set-mark
24887 (save-excursion
24888 (goto-char (mark))
24889 (goto-char (org-element-property :end (org-element-at-point)))))
24890 (let ((element (org-element-at-point)))
24891 (end-of-line)
24892 (push-mark (org-element-property :end element) t t)
24893 (goto-char (org-element-property :begin element))))))
24895 (defun org-narrow-to-element ()
24896 "Narrow buffer to current element."
24897 (interactive)
24898 (let ((elem (org-element-at-point)))
24899 (cond
24900 ((eq (car elem) 'headline)
24901 (narrow-to-region
24902 (org-element-property :begin elem)
24903 (org-element-property :end elem)))
24904 ((memq (car elem) org-element-greater-elements)
24905 (narrow-to-region
24906 (org-element-property :contents-begin elem)
24907 (org-element-property :contents-end elem)))
24909 (narrow-to-region
24910 (org-element-property :begin elem)
24911 (org-element-property :end elem))))))
24913 (defun org-transpose-element ()
24914 "Transpose current and previous elements, keeping blank lines between.
24915 Point is moved after both elements."
24916 (interactive)
24917 (org-skip-whitespace)
24918 (let ((end (org-element-property :end (org-element-at-point))))
24919 (org-drag-element-backward)
24920 (goto-char end)))
24922 (defun org-unindent-buffer ()
24923 "Un-indent the visible part of the buffer.
24924 Relative indentation (between items, inside blocks, etc.) isn't
24925 modified."
24926 (interactive)
24927 (unless (eq major-mode 'org-mode)
24928 (user-error "Cannot un-indent a buffer not in Org mode"))
24929 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24930 (unindent-tree
24931 (lambda (contents)
24932 (dolist (element (reverse contents))
24933 (if (memq (org-element-type element) '(headline section))
24934 (funcall unindent-tree (org-element-contents element))
24935 (save-excursion
24936 (save-restriction
24937 (narrow-to-region
24938 (org-element-property :begin element)
24939 (org-element-property :end element))
24940 (org-do-remove-indentation))))))))
24941 (funcall unindent-tree (org-element-contents parse-tree))))
24943 (defun org-show-children (&optional level)
24944 "Show all direct subheadings of this heading.
24945 Prefix arg LEVEL is how many levels below the current level
24946 should be shown. Default is enough to cause the following
24947 heading to appear."
24948 (interactive "p")
24949 ;; If `orgstruct-mode' is active, use the slower version.
24950 (if orgstruct-mode (call-interactively #'outline-show-children)
24951 (save-excursion
24952 (org-back-to-heading t)
24953 (let* ((current-level (funcall outline-level))
24954 (max-level (org-get-valid-level
24955 current-level
24956 (if level (prefix-numeric-value level) 1)))
24957 (end (save-excursion (org-end-of-subtree t t)))
24958 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24959 (past-first-child nil)
24960 ;; Make sure to skip inlinetasks.
24961 (re (format regexp-fmt
24962 current-level
24963 (cond
24964 ((not (featurep 'org-inlinetask)) "")
24965 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24967 (t (1- org-inlinetask-min-level))))))
24968 ;; Display parent heading.
24969 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24970 (forward-line)
24971 ;; Display children. First child may be deeper than expected
24972 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24973 ;; MAX-LEVEL accordingly.
24974 (while (re-search-forward re end t)
24975 (unless past-first-child
24976 (setq re (format regexp-fmt
24977 current-level
24978 (max (funcall outline-level) max-level)))
24979 (setq past-first-child t))
24980 (outline-flag-region
24981 (line-end-position 0) (line-end-position) nil))))))
24983 (defun org-show-subtree ()
24984 "Show everything after this heading at deeper levels."
24985 (interactive)
24986 (outline-flag-region
24987 (point)
24988 (save-excursion
24989 (org-end-of-subtree t t))
24990 nil))
24992 (defun org-show-entry ()
24993 "Show the body directly following this heading.
24994 Show the heading too, if it is currently invisible."
24995 (interactive)
24996 (save-excursion
24997 (ignore-errors
24998 (org-back-to-heading t)
24999 (outline-flag-region
25000 (max (point-min) (1- (point)))
25001 (save-excursion
25002 (if (re-search-forward
25003 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
25004 (match-beginning 1)
25005 (point-max)))
25006 nil)
25007 (org-cycle-hide-drawers 'children))))
25009 (defun org-make-options-regexp (kwds &optional extra)
25010 "Make a regular expression for keyword lines.
25011 KWDS is a list of keywords, as strings. Optional argument EXTRA,
25012 when non-nil, is a regexp matching keywords names."
25013 (concat "^[ \t]*#\\+\\("
25014 (regexp-opt kwds)
25015 (and extra (concat (and kwds "\\|") extra))
25016 "\\):[ \t]*\\(.*\\)"))
25018 ;;;; Integration with and fixes for other packages
25020 ;;; Imenu support
25022 (defvar-local org-imenu-markers nil
25023 "All markers currently used by Imenu.")
25025 (defun org-imenu-new-marker (&optional pos)
25026 "Return a new marker for use by Imenu, and remember the marker."
25027 (let ((m (make-marker)))
25028 (move-marker m (or pos (point)))
25029 (push m org-imenu-markers)
25032 (defun org-imenu-get-tree ()
25033 "Produce the index for Imenu."
25034 (dolist (x org-imenu-markers) (move-marker x nil))
25035 (setq org-imenu-markers nil)
25036 (let* ((case-fold-search nil)
25037 (n org-imenu-depth)
25038 (re (concat "^" (org-get-limited-outline-regexp)))
25039 (subs (make-vector (1+ n) nil))
25040 (last-level 0)
25041 m level head0 head)
25042 (save-excursion
25043 (save-restriction
25044 (widen)
25045 (goto-char (point-max))
25046 (while (re-search-backward re nil t)
25047 (setq level (org-reduced-level (funcall outline-level)))
25048 (when (and (<= level n)
25049 (looking-at org-complex-heading-regexp)
25050 (setq head0 (match-string-no-properties 4)))
25051 (setq head (org-link-display-format head0)
25052 m (org-imenu-new-marker))
25053 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
25054 (if (>= level last-level)
25055 (push (cons head m) (aref subs level))
25056 (push (cons head (aref subs (1+ level))) (aref subs level))
25057 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
25058 (setq last-level level)))))
25059 (aref subs 1)))
25061 (eval-after-load "imenu"
25062 '(progn
25063 (add-hook 'imenu-after-jump-hook
25064 (lambda ()
25065 (when (derived-mode-p 'org-mode)
25066 (org-show-context 'org-goto))))))
25068 (defun org-link-display-format (s)
25069 "Replace links in string S with their description.
25070 If there is no description, use the link target."
25071 (save-match-data
25072 (replace-regexp-in-string
25073 org-bracket-link-analytic-regexp
25074 (lambda (m)
25075 (if (match-end 5) (match-string 5 m)
25076 (concat (match-string 1 m) (match-string 3 m))))
25077 s nil t)))
25079 (defun org-toggle-link-display ()
25080 "Toggle the literal or descriptive display of links."
25081 (interactive)
25082 (if org-descriptive-links
25083 (progn (org-remove-from-invisibility-spec '(org-link))
25084 (org-restart-font-lock)
25085 (setq org-descriptive-links nil))
25086 (progn (add-to-invisibility-spec '(org-link))
25087 (org-restart-font-lock)
25088 (setq org-descriptive-links t))))
25090 ;; Speedbar support
25092 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25093 "Overlay marking the agenda restriction line in speedbar.")
25094 (overlay-put org-speedbar-restriction-lock-overlay
25095 'face 'org-agenda-restriction-lock)
25096 (overlay-put org-speedbar-restriction-lock-overlay
25097 'help-echo "Agendas are currently limited to this item.")
25098 (delete-overlay org-speedbar-restriction-lock-overlay)
25100 (defun org-speedbar-set-agenda-restriction ()
25101 "Restrict future agenda commands to the location at point in speedbar.
25102 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25103 (interactive)
25104 (require 'org-agenda)
25105 (let (p m tp np dir txt)
25106 (cond
25107 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25108 'org-imenu t))
25109 (setq m (get-text-property p 'org-imenu-marker))
25110 (with-current-buffer (marker-buffer m)
25111 (goto-char m)
25112 (org-agenda-set-restriction-lock 'subtree)))
25113 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25114 'speedbar-function 'speedbar-find-file))
25115 (setq tp (previous-single-property-change
25116 (1+ p) 'speedbar-function)
25117 np (next-single-property-change
25118 tp 'speedbar-function)
25119 dir (speedbar-line-directory)
25120 txt (buffer-substring-no-properties (or tp (point-min))
25121 (or np (point-max))))
25122 (with-current-buffer (find-file-noselect
25123 (let ((default-directory dir))
25124 (expand-file-name txt)))
25125 (unless (derived-mode-p 'org-mode)
25126 (user-error "Cannot restrict to non-Org-mode file"))
25127 (org-agenda-set-restriction-lock 'file)))
25128 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25129 (move-overlay org-speedbar-restriction-lock-overlay
25130 (point-at-bol) (point-at-eol))
25131 (setq current-prefix-arg nil)
25132 (org-agenda-maybe-redo)))
25134 (defvar speedbar-file-key-map)
25135 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25136 (eval-after-load "speedbar"
25137 '(progn
25138 (speedbar-add-supported-extension ".org")
25139 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25140 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25141 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25142 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25143 (add-hook 'speedbar-visiting-tag-hook
25144 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25146 ;;; Fixes and Hacks for problems with other packages
25148 (defun org--flyspell-object-check-p (element)
25149 "Non-nil when Flyspell can check object at point.
25150 ELEMENT is the element at point."
25151 (let ((object (save-excursion
25152 (when (looking-at-p "\\>") (backward-char))
25153 (org-element-context element))))
25154 (cl-case (org-element-type object)
25155 ;; Prevent checks in links due to keybinding conflict with
25156 ;; Flyspell.
25157 ((code entity export-snippet inline-babel-call
25158 inline-src-block line-break latex-fragment link macro
25159 statistics-cookie target timestamp verbatim)
25160 nil)
25161 (footnote-reference
25162 ;; Only in inline footnotes, within the definition.
25163 (and (eq (org-element-property :type object) 'inline)
25164 (< (save-excursion
25165 (goto-char (org-element-property :begin object))
25166 (search-forward ":" nil t 2))
25167 (point))))
25168 (otherwise t))))
25170 (defun org-mode-flyspell-verify ()
25171 "Function used for `flyspell-generic-check-word-predicate'."
25172 (if (org-at-heading-p)
25173 ;; At a headline or an inlinetask, check title only. This is
25174 ;; faster than relying on `org-element-at-point'.
25175 (and (save-excursion (beginning-of-line)
25176 (and (let ((case-fold-search t))
25177 (not (looking-at "\\*+ END[ \t]*$")))
25178 (looking-at org-complex-heading-regexp)))
25179 (match-beginning 4)
25180 (>= (point) (match-beginning 4))
25181 (or (not (match-beginning 5))
25182 (< (point) (match-beginning 5))))
25183 (let* ((element (org-element-at-point))
25184 (post-affiliated (org-element-property :post-affiliated element)))
25185 (cond
25186 ;; Ignore checks in all affiliated keywords but captions.
25187 ((< (point) post-affiliated)
25188 (and (save-excursion
25189 (beginning-of-line)
25190 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25191 (> (point) (match-end 0))
25192 (org--flyspell-object-check-p element)))
25193 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25194 ((let ((log (org-log-into-drawer)))
25195 (and log
25196 (let ((drawer (org-element-lineage element '(drawer))))
25197 (and drawer
25198 (eq (compare-strings
25199 log nil nil
25200 (org-element-property :drawer-name drawer) nil nil t)
25201 t)))))
25202 nil)
25204 (cl-case (org-element-type element)
25205 ((comment quote-section) t)
25206 (comment-block
25207 ;; Allow checks between block markers, not on them.
25208 (and (> (line-beginning-position) post-affiliated)
25209 (save-excursion
25210 (end-of-line)
25211 (skip-chars-forward " \r\t\n")
25212 (< (point) (org-element-property :end element)))))
25213 ;; Arbitrary list of keywords where checks are meaningful.
25214 ;; Make sure point is on the value part of the element.
25215 (keyword
25216 (and (member (org-element-property :key element)
25217 '("DESCRIPTION" "TITLE"))
25218 (save-excursion
25219 (search-backward ":" (line-beginning-position) t))))
25220 ;; Check is globally allowed in paragraphs verse blocks and
25221 ;; table rows (after affiliated keywords) but some objects
25222 ;; must not be affected.
25223 ((paragraph table-row verse-block)
25224 (let ((cbeg (org-element-property :contents-begin element))
25225 (cend (org-element-property :contents-end element)))
25226 (and cbeg (>= (point) cbeg) (< (point) cend)
25227 (org--flyspell-object-check-p element))))))))))
25228 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25230 (defun org-remove-flyspell-overlays-in (beg end)
25231 "Remove flyspell overlays in region."
25232 (and (org-bound-and-true-p flyspell-mode)
25233 (fboundp 'flyspell-delete-region-overlays)
25234 (flyspell-delete-region-overlays beg end)))
25236 (defvar flyspell-delayed-commands)
25237 (eval-after-load "flyspell"
25238 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25240 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25241 (eval-after-load "bookmark"
25242 '(if (boundp 'bookmark-after-jump-hook)
25243 ;; We can use the hook
25244 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25245 ;; Hook not available, use advice
25246 (defadvice bookmark-jump (after org-make-visible activate)
25247 "Make the position visible."
25248 (org-bookmark-jump-unhide))))
25250 ;; Make sure saveplace shows the location if it was hidden
25251 (eval-after-load "saveplace"
25252 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25253 "Make the position visible."
25254 (org-bookmark-jump-unhide)))
25256 ;; Make sure ecb shows the location if it was hidden
25257 (eval-after-load "ecb"
25258 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25259 "Make hierarchy visible when jumping into location from ECB tree buffer."
25260 (when (derived-mode-p 'org-mode)
25261 (org-show-context))))
25263 (defun org-bookmark-jump-unhide ()
25264 "Unhide the current position, to show the bookmark location."
25265 (and (derived-mode-p 'org-mode)
25266 (or (outline-invisible-p)
25267 (save-excursion (goto-char (max (point-min) (1- (point))))
25268 (outline-invisible-p)))
25269 (org-show-context 'bookmark-jump)))
25271 (defun org-mark-jump-unhide ()
25272 "Make the point visible with `org-show-context' after jumping to the mark."
25273 (when (and (derived-mode-p 'org-mode)
25274 (outline-invisible-p))
25275 (org-show-context 'mark-goto)))
25277 (eval-after-load "simple"
25278 '(defadvice pop-to-mark-command (after org-make-visible activate)
25279 "Make the point visible with `org-show-context'."
25280 (org-mark-jump-unhide)))
25282 (eval-after-load "simple"
25283 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25284 "Make the point visible with `org-show-context'."
25285 (org-mark-jump-unhide)))
25287 (eval-after-load "simple"
25288 '(defadvice pop-global-mark (after org-make-visible activate)
25289 "Make the point visible with `org-show-context'."
25290 (org-mark-jump-unhide)))
25292 ;; Make session.el ignore our circular variable
25293 (defvar session-globals-exclude)
25294 (eval-after-load "session"
25295 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25297 ;;;; Finish up
25299 (provide 'org)
25301 (run-hooks 'org-load-hook)
25303 ;;; org.el ends here