Handle correctly `shift-select-mode'
[org-mode.git] / lisp / org.el
blobf8b5f03a44c32d10305759ebe32325c424339c28
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" (&optional date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocktable-shift "org-clock" (dir n))
130 (declare-function org-element-at-point "org-element" ())
131 (declare-function org-element-cache-refresh "org-element" (pos))
132 (declare-function org-element-cache-reset "org-element" (&optional all))
133 (declare-function org-element-contents "org-element" (element))
134 (declare-function org-element-context "org-element" (&optional element))
135 (declare-function org-element-copy "org-element" (datum))
136 (declare-function org-element-interpret-data "org-element" (data &optional parent))
137 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
138 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
139 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
140 (declare-function org-element-property "org-element" (property element))
141 (declare-function org-element-put-property "org-element" (element property value))
142 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
143 (declare-function org-element-type "org-element" (element))
144 (declare-function org-element-update-syntax "org-element" ())
145 (declare-function org-id-find-id-file "org-id" (id))
146 (declare-function org-id-get-create "org-id" (&optional force))
147 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
148 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
149 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
150 (declare-function org-plot/gnuplot "org-plot" (&optional params))
151 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
152 (declare-function org-table-align "org-table" ())
153 (declare-function org-table-begin "org-table" (&optional table-type))
154 (declare-function org-table-beginning-of-field "org-table" (&optional n))
155 (declare-function org-table-blank-field "org-table" ())
156 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
157 (declare-function org-table-edit-field "org-table" (arg))
158 (declare-function org-table-end "org-table" (&optional table-type))
159 (declare-function org-table-end-of-field "org-table" (&optional n))
160 (declare-function org-table-insert-row "org-table" (&optional arg))
161 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
162 (declare-function org-table-maybe-eval-formula "org-table" ())
163 (declare-function org-table-maybe-recalculate-line "org-table" ())
164 (declare-function org-table-next-row "org-table" ())
165 (declare-function org-table-paste-rectangle "org-table" ())
166 (declare-function org-table-wrap-region "org-table" (arg))
167 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
168 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
169 (declare-function orgtbl-mode "org-table" (&optional arg))
171 (defsubst org-uniquify (list)
172 "Non-destructively remove duplicate elements from LIST."
173 (let ((res (copy-sequence list))) (delete-dups res)))
175 (defsubst org-get-at-bol (property)
176 "Get text property PROPERTY at the beginning of line."
177 (get-text-property (point-at-bol) property))
179 (defsubst org-trim (s)
180 "Remove whitespace at the beginning and the end of string S."
181 (replace-regexp-in-string
182 "\\`[ \t\n\r]+" ""
183 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
185 ;; load languages based on value of `org-babel-load-languages'
186 (defvar org-babel-load-languages)
188 ;;;###autoload
189 (defun org-babel-do-load-languages (sym value)
190 "Load the languages defined in `org-babel-load-languages'."
191 (set-default sym value)
192 (dolist (pair org-babel-load-languages)
193 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
194 (if active
195 (require (intern (concat "ob-" lang)))
196 (funcall 'fmakunbound
197 (intern (concat "org-babel-execute:" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-expand-body:" lang)))))))
201 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
202 ;;;###autoload
203 (defun org-babel-load-file (file &optional compile)
204 "Load Emacs Lisp source code blocks in the Org-mode FILE.
205 This function exports the source code using `org-babel-tangle'
206 and then loads the resulting file using `load-file'. With prefix
207 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
208 file to byte-code before it is loaded."
209 (interactive "fFile to load: \nP")
210 (let* ((age (lambda (file)
211 (float-time
212 (time-subtract (current-time)
213 (nth 5 (or (file-attributes (file-truename file))
214 (file-attributes file)))))))
215 (base-name (file-name-sans-extension file))
216 (exported-file (concat base-name ".el")))
217 ;; tangle if the org-mode file is newer than the elisp file
218 (unless (and (file-exists-p exported-file)
219 (> (funcall age file) (funcall age exported-file)))
220 ;; Tangle-file traversal returns reversed list of tangled files
221 ;; and we want to evaluate the first target.
222 (setq exported-file
223 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
224 (message "%s %s"
225 (if compile
226 (progn (byte-compile-file exported-file 'load)
227 "Compiled and loaded")
228 (progn (load-file exported-file) "Loaded"))
229 exported-file)))
231 (defcustom org-babel-load-languages '((emacs-lisp . t))
232 "Languages which can be evaluated in Org-mode buffers.
233 This list can be used to load support for any of the languages
234 below, note that each language will depend on a different set of
235 system executables and/or Emacs modes. When a language is
236 \"loaded\", then code blocks in that language can be evaluated
237 with `org-babel-execute-src-block' bound by default to C-c
238 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
239 be set to remove code block evaluation from the C-c C-c
240 keybinding. By default only Emacs Lisp (which has no
241 requirements) is loaded."
242 :group 'org-babel
243 :set 'org-babel-do-load-languages
244 :version "24.1"
245 :type '(alist :tag "Babel Languages"
246 :key-type
247 (choice
248 (const :tag "Awk" awk)
249 (const :tag "C" C)
250 (const :tag "R" R)
251 (const :tag "Asymptote" asymptote)
252 (const :tag "Calc" calc)
253 (const :tag "Clojure" clojure)
254 (const :tag "CSS" css)
255 (const :tag "Ditaa" ditaa)
256 (const :tag "Dot" dot)
257 (const :tag "Emacs Lisp" emacs-lisp)
258 (const :tag "Forth" forth)
259 (const :tag "Fortran" fortran)
260 (const :tag "Gnuplot" gnuplot)
261 (const :tag "Haskell" haskell)
262 (const :tag "IO" io)
263 (const :tag "J" J)
264 (const :tag "Java" java)
265 (const :tag "Javascript" js)
266 (const :tag "LaTeX" latex)
267 (const :tag "Ledger" ledger)
268 (const :tag "Lilypond" lilypond)
269 (const :tag "Lisp" lisp)
270 (const :tag "Makefile" makefile)
271 (const :tag "Maxima" maxima)
272 (const :tag "Matlab" matlab)
273 (const :tag "Mscgen" mscgen)
274 (const :tag "Ocaml" ocaml)
275 (const :tag "Octave" octave)
276 (const :tag "Org" org)
277 (const :tag "Perl" perl)
278 (const :tag "Pico Lisp" picolisp)
279 (const :tag "PlantUML" plantuml)
280 (const :tag "Python" python)
281 (const :tag "Ruby" ruby)
282 (const :tag "Sass" sass)
283 (const :tag "Scala" scala)
284 (const :tag "Scheme" scheme)
285 (const :tag "Screen" screen)
286 (const :tag "Shell Script" shell)
287 (const :tag "Shen" shen)
288 (const :tag "Sql" sql)
289 (const :tag "Sqlite" sqlite)
290 (const :tag "Stan" stan)
291 (const :tag "ebnf2ps" ebnf2ps))
292 :value-type (boolean :tag "Activate" :value t)))
294 ;;;; Customization variables
295 (defcustom org-clone-delete-id nil
296 "Remove ID property of clones of a subtree.
297 When non-nil, clones of a subtree don't inherit the ID property.
298 Otherwise they inherit the ID property with a new unique
299 identifier."
300 :type 'boolean
301 :version "24.1"
302 :group 'org-id)
304 ;;; Version
305 (org-check-version)
307 ;;;###autoload
308 (defun org-version (&optional here full message)
309 "Show the org-mode version.
310 Interactively, or when MESSAGE is non-nil, show it in echo area.
311 With prefix argument, or when HERE is non-nil, insert it at point.
312 In non-interactive uses, a reduced version string is output unless
313 FULL is given."
314 (interactive (list current-prefix-arg t (not current-prefix-arg)))
315 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
316 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
317 (load-suffixes (list ".el"))
318 (org-install-dir
319 (ignore-errors (org-find-library-dir "org-loaddefs"))))
320 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
321 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
322 (let* ((load-suffixes save-load-suffixes)
323 (release (org-release))
324 (git-version (org-git-version))
325 (version (format "Org-mode version %s (%s @ %s)"
326 release
327 git-version
328 (if org-install-dir
329 (if (string= org-dir org-install-dir)
330 org-install-dir
331 (concat "mixed installation! "
332 org-install-dir
333 " and "
334 org-dir))
335 "org-loaddefs.el can not be found!")))
336 (version1 (if full version release)))
337 (when here (insert version1))
338 (when message (message "%s" version1))
339 version1)))
341 (defconst org-version (org-version))
344 ;;; Syntax Constants
346 ;;;; Block
348 (defconst org-block-regexp
349 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
350 "Regular expression for hiding blocks.")
352 (defconst org-dblock-start-re
353 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
354 "Matches the start line of a dynamic block, with parameters.")
356 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
357 "Matches the end of a dynamic block.")
359 ;;;; Clock and Planning
361 (defconst org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item.")
364 (defvar org-closed-string "CLOSED:"
365 "String used as the prefix for timestamps logging closing a TODO entry.")
367 (defvar org-deadline-string "DEADLINE:"
368 "String to mark deadline entries.
369 A deadline is this string, followed by a time stamp. Should be a word,
370 terminated by a colon. You can insert a schedule keyword and
371 a timestamp with \\[org-deadline].")
373 (defvar org-scheduled-string "SCHEDULED:"
374 "String to mark scheduled TODO entries.
375 A schedule is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-schedule].")
379 (defconst org-ds-keyword-length
380 (+ 2
381 (apply #'max
382 (mapcar #'length
383 (list org-deadline-string org-scheduled-string
384 org-clock-string org-closed-string))))
385 "Maximum length of the DEADLINE and SCHEDULED keywords.")
387 (defconst org-planning-line-re
388 (concat "^[ \t]*"
389 (regexp-opt
390 (list org-closed-string org-deadline-string org-scheduled-string)
392 "Matches a line with planning info.
393 Matched keyword is in group 1.")
395 (defconst org-clock-line-re
396 (concat "^[ \t]*" org-clock-string)
397 "Matches a line with clock info.")
399 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
400 "Matches the DEADLINE keyword.")
402 (defconst org-deadline-time-regexp
403 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
404 "Matches the DEADLINE keyword together with a time stamp.")
406 (defconst org-deadline-time-hour-regexp
407 (concat "\\<" org-deadline-string
408 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
409 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
411 (defconst org-deadline-line-regexp
412 (concat "\\<\\(" org-deadline-string "\\).*")
413 "Matches the DEADLINE keyword and the rest of the line.")
415 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
416 "Matches the SCHEDULED keyword.")
418 (defconst org-scheduled-time-regexp
419 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
420 "Matches the SCHEDULED keyword together with a time stamp.")
422 (defconst org-scheduled-time-hour-regexp
423 (concat "\\<" org-scheduled-string
424 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
425 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
427 (defconst org-closed-time-regexp
428 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
429 "Matches the CLOSED keyword together with a time stamp.")
431 (defconst org-keyword-time-regexp
432 (concat "\\<"
433 (regexp-opt
434 (list org-scheduled-string org-deadline-string org-closed-string
435 org-clock-string)
437 " *[[<]\\([^]>]+\\)[]>]")
438 "Matches any of the 4 keywords, together with the time stamp.")
440 (defconst org-keyword-time-not-clock-regexp
441 (concat
442 "\\<"
443 (regexp-opt
444 (list org-scheduled-string org-deadline-string org-closed-string) t)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 3 keywords, together with the time stamp.")
448 (defconst org-maybe-keyword-time-regexp
449 (concat "\\(\\<"
450 (regexp-opt
451 (list org-scheduled-string org-deadline-string org-closed-string
452 org-clock-string)
454 "\\)?"
455 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
456 "\\|"
457 "<%%([^\r\n>]*>\\)")
458 "Matches a timestamp, possibly preceded by a keyword.")
460 (defconst org-all-time-keywords
461 (mapcar (lambda (w) (substring w 0 -1))
462 (list org-scheduled-string org-deadline-string
463 org-clock-string org-closed-string))
464 "List of time keywords.")
466 ;;;; Drawer
468 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
469 "Matches first or last line of a hidden block.
470 Group 1 contains drawer's name or \"END\".")
472 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
473 "Regular expression matching the first line of a property drawer.")
475 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
476 "Regular expression matching the last line of a property drawer.")
478 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
479 "Regular expression matching the first line of a clock drawer.")
481 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a clock drawer.")
484 (defconst org-property-drawer-re
485 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
486 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
487 "[ \t]*:END:[ \t]*$")
488 "Matches an entire property drawer.")
490 (defconst org-clock-drawer-re
491 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
492 org-clock-drawer-end-re "\\)\n?")
493 "Matches an entire clock drawer.")
495 ;;;; Headline
497 (defconst org-heading-keyword-regexp-format
498 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
499 "Printf format for a regexp matching a headline with some keyword.
500 This regexp will match the headline of any node which has the
501 exact keyword that is put into the format. The keyword isn't in
502 any group by default, but the stars and the body are.")
504 (defconst org-heading-keyword-maybe-regexp-format
505 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
506 "Printf format for a regexp matching a headline, possibly with some keyword.
507 This regexp can match any headline with the specified keyword, or
508 without a keyword. The keyword isn't in any group by default,
509 but the stars and the body are.")
511 (defconst org-archive-tag "ARCHIVE"
512 "The tag that marks a subtree as archived.
513 An archived subtree does not open during visibility cycling, and does
514 not contribute to the agenda listings.")
516 (defconst org-comment-string "COMMENT"
517 "Entries starting with this keyword will never be exported.
518 An entry can be toggled between COMMENT and normal with
519 \\[org-toggle-comment].")
522 ;;;; LaTeX Environments and Fragments
524 (defconst org-latex-regexps
525 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
526 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
527 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
528 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
529 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
530 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
531 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
532 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
533 "Regular expressions for matching embedded LaTeX.")
535 ;;;; Node Property
537 (defconst org-effort-property "Effort"
538 "The property that is being used to keep track of effort estimates.
539 Effort estimates given in this property need to have the format H:MM.")
541 ;;;; Table
543 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
544 "Detect an org-type or table-type table.")
546 (defconst org-table-line-regexp "^[ \t]*|"
547 "Detect an org-type table line.")
549 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
550 "Detect an org-type table line.")
552 (defconst org-table-hline-regexp "^[ \t]*|-"
553 "Detect an org-type table hline.")
555 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
556 "Detect a table-type table hline.")
558 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
559 "Detect the first line outside a table when searching from within it.
560 This works for both table types.")
562 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
563 "Detect a #+TBLFM line.")
565 ;;;; Timestamp
567 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
568 "Regular expression for fast time stamp matching.")
570 (defconst org-ts-regexp-inactive
571 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
572 "Regular expression for fast inactive time stamp matching.")
574 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
575 "Regular expression for fast time stamp matching.")
577 (defconst org-ts-regexp0
578 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
579 "Regular expression matching time strings for analysis.
580 This one does not require the space after the date, so it can be used
581 on a string that terminates immediately after the date.")
583 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
584 "Regular expression matching time strings for analysis.")
586 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
587 "Regular expression matching time stamps, with groups.")
589 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
590 "Regular expression matching time stamps (also [..]), with groups.")
592 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
593 "Regular expression matching a time stamp range.")
595 (defconst org-tr-regexp-both
596 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
597 "Regular expression matching a time stamp range.")
599 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
600 org-ts-regexp "\\)?")
601 "Regular expression matching a time stamp or time stamp range.")
603 (defconst org-tsr-regexp-both
604 (concat org-ts-regexp-both "\\(--?-?"
605 org-ts-regexp-both "\\)?")
606 "Regular expression matching a time stamp or time stamp range.
607 The time stamps may be either active or inactive.")
609 (defconst org-repeat-re
610 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
611 "Regular expression for specifying repeated events.
612 After a match, group 1 contains the repeat expression.")
614 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
615 "Formats for `format-time-string' which are used for time stamps.")
618 ;;; The custom variables
620 (defgroup org nil
621 "Outline-based notes management and organizer."
622 :tag "Org"
623 :group 'outlines
624 :group 'calendar)
626 (defcustom org-mode-hook nil
627 "Mode hook for Org-mode, run after the mode was turned on."
628 :group 'org
629 :type 'hook)
631 (defcustom org-load-hook nil
632 "Hook that is run after org.el has been loaded."
633 :group 'org
634 :type 'hook)
636 (defcustom org-log-buffer-setup-hook nil
637 "Hook that is run after an Org log buffer is created."
638 :group 'org
639 :version "24.1"
640 :type 'hook)
642 (defvar org-modules) ; defined below
643 (defvar org-modules-loaded nil
644 "Have the modules been loaded already?")
646 (defun org-load-modules-maybe (&optional force)
647 "Load all extensions listed in `org-modules'."
648 (when (or force (not org-modules-loaded))
649 (dolist (ext org-modules)
650 (condition-case nil (require ext)
651 (error (message "Problems while trying to load feature `%s'" ext))))
652 (setq org-modules-loaded t)))
654 (defun org-set-modules (var value)
655 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
656 (set var value)
657 (when (featurep 'org)
658 (org-load-modules-maybe 'force)
659 (org-element-cache-reset 'all)))
661 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
662 "Modules that should always be loaded together with org.el.
664 If a description starts with <C>, the file is not part of Emacs
665 and loading it will require that you have downloaded and properly
666 installed the Org mode distribution.
668 You can also use this system to load external packages (i.e. neither Org
669 core modules, nor modules from the CONTRIB directory). Just add symbols
670 to the end of the list. If the package is called org-xyz.el, then you need
671 to add the symbol `xyz', and the package must have a call to:
673 (provide \\='org-xyz)
675 For export specific modules, see also `org-export-backends'."
676 :group 'org
677 :set 'org-set-modules
678 :version "24.4"
679 :package-version '(Org . "8.0")
680 :type
681 '(set :greedy t
682 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
683 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
684 (const :tag " crypt: Encryption of subtrees" org-crypt)
685 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
686 (const :tag " docview: Links to doc-view buffers" org-docview)
687 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
688 (const :tag " habit: Track your consistency with habits" org-habit)
689 (const :tag " id: Global IDs for identifying entries" org-id)
690 (const :tag " info: Links to Info nodes" org-info)
691 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
692 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
693 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
694 (const :tag " mouse: Additional mouse support" org-mouse)
695 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
696 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
697 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
699 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
700 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
701 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
702 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
703 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
704 (const :tag "C collector: Collect properties into tables" org-collector)
705 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
706 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
707 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
708 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
709 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
710 (const :tag "C eval: Include command output as text" org-eval)
711 (const :tag "C eww: Store link to url of eww" org-eww)
712 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
713 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
714 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
715 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
716 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
717 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
718 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
719 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
720 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
721 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
722 (const :tag "C mew: Links to Mew folders/messages" org-mew)
723 (const :tag "C mtags: Support for muse-like tags" org-mtags)
724 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
725 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
726 (const :tag "C registry: A registry for Org-mode links" org-registry)
727 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
728 (const :tag "C secretary: Team management with org-mode" org-secretary)
729 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
730 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
731 (const :tag "C track: Keep up with Org-mode development" org-track)
732 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
733 (const :tag "C vm: Links to VM folders/messages" org-vm)
734 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
735 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
736 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
738 (defvar org-export-registered-backends) ; From ox.el.
739 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
740 (declare-function org-export-backend-name "ox" (backend))
741 (defcustom org-export-backends '(ascii html icalendar latex odt)
742 "List of export back-ends that should be always available.
744 If a description starts with <C>, the file is not part of Emacs
745 and loading it will require that you have downloaded and properly
746 installed the Org mode distribution.
748 Unlike to `org-modules', libraries in this list will not be
749 loaded along with Org, but only once the export framework is
750 needed.
752 This variable needs to be set before org.el is loaded. If you
753 need to make a change while Emacs is running, use the customize
754 interface or run the following code, where VAL stands for the new
755 value of the variable, after updating it:
757 (progn
758 (setq org-export-registered-backends
759 (cl-remove-if-not
760 (lambda (backend)
761 (let ((name (org-export-backend-name backend)))
762 (or (memq name val)
763 (catch \\='parentp
764 (dolist (b val)
765 (and (org-export-derived-backend-p b name)
766 (throw \\='parentp t)))))))
767 org-export-registered-backends))
768 (let ((new-list (mapcar #\\='org-export-backend-name
769 org-export-registered-backends)))
770 (dolist (backend val)
771 (cond
772 ((not (load (format \"ox-%s\" backend) t t))
773 (message \"Problems while trying to load export back-end \\=`%s\\='\"
774 backend))
775 ((not (memq backend new-list)) (push backend new-list))))
776 (set-default \\='org-export-backends new-list)))
778 Adding a back-end to this list will also pull the back-end it
779 depends on, if any."
780 :group 'org
781 :group 'org-export
782 :version "25.1"
783 :package-version '(Org . "9.0")
784 :initialize 'custom-initialize-set
785 :set (lambda (var val)
786 (if (not (featurep 'ox)) (set-default var val)
787 ;; Any back-end not required anymore (not present in VAL and not
788 ;; a parent of any back-end in the new value) is removed from the
789 ;; list of registered back-ends.
790 (setq org-export-registered-backends
791 (cl-remove-if-not
792 (lambda (backend)
793 (let ((name (org-export-backend-name backend)))
794 (or (memq name val)
795 (catch 'parentp
796 (dolist (b val)
797 (and (org-export-derived-backend-p b name)
798 (throw 'parentp t)))))))
799 org-export-registered-backends))
800 ;; Now build NEW-LIST of both new back-ends and required
801 ;; parents.
802 (let ((new-list (mapcar #'org-export-backend-name
803 org-export-registered-backends)))
804 (dolist (backend val)
805 (cond
806 ((not (load (format "ox-%s" backend) t t))
807 (message "Problems while trying to load export back-end `%s'"
808 backend))
809 ((not (memq backend new-list)) (push backend new-list))))
810 ;; Set VAR to that list with fixed dependencies.
811 (set-default var new-list))))
812 :type '(set :greedy t
813 (const :tag " ascii Export buffer to ASCII format" ascii)
814 (const :tag " beamer Export buffer to Beamer presentation" beamer)
815 (const :tag " html Export buffer to HTML format" html)
816 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
817 (const :tag " latex Export buffer to LaTeX format" latex)
818 (const :tag " man Export buffer to MAN format" man)
819 (const :tag " md Export buffer to Markdown format" md)
820 (const :tag " odt Export buffer to ODT format" odt)
821 (const :tag " org Export buffer to Org format" org)
822 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
823 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
824 (const :tag "C deck Export buffer to deck.js presentations" deck)
825 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
826 (const :tag "C groff Export buffer to Groff format" groff)
827 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
828 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
829 (const :tag "C s5 Export buffer to s5 presentations" s5)
830 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
832 (eval-after-load 'ox
833 '(dolist (backend org-export-backends)
834 (condition-case nil (require (intern (format "ox-%s" backend)))
835 (error (message "Problems while trying to load export back-end `%s'"
836 backend)))))
838 (defcustom org-support-shift-select nil
839 "Non-nil means make shift-cursor commands select text when possible.
840 \\<org-mode-map>\
842 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
843 start selecting a region, or enlarge regions started in this way.
844 In Org-mode, in special contexts, these same keys are used for
845 other purposes, important enough to compete with shift selection.
846 Org tries to balance these needs by supporting `shift-select-mode'
847 outside these special contexts, under control of this variable.
849 The default of this variable is nil, to avoid confusing behavior. Shifted
850 cursor keys will then execute Org commands in the following contexts:
851 - on a headline, changing TODO state (left/right) and priority (up/down)
852 - on a time stamp, changing the time
853 - in a plain list item, changing the bullet type
854 - in a property definition line, switching between allowed values
855 - in the BEGIN line of a clock table (changing the time block).
856 Outside these contexts, the commands will throw an error.
858 When this variable is t and the cursor is not in a special
859 context, Org-mode will support shift-selection for making and
860 enlarging regions. To make this more effective, the bullet
861 cycling will no longer happen anywhere in an item line, but only
862 if the cursor is exactly on the bullet.
864 If you set this variable to the symbol `always', then the keys
865 will not be special in headlines, property lines, and item lines,
866 to make shift selection work there as well. If this is what you
867 want, you can use the following alternative commands:
868 `\\[org-todo]' and `\\[org-priority]' \
869 to change TODO state and priority,
870 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
871 can be used to switch TODO sets,
872 `\\[org-ctrl-c-minus]' to cycle item bullet types,
873 and properties can be edited by hand or in column view.
875 However, when the cursor is on a timestamp, shift-cursor commands
876 will still edit the time stamp - this is just too good to give up.
878 XEmacs user should have this variable set to nil, because
879 `shift-select-mode' is in Emacs 23 or later only."
880 :group 'org
881 :type '(choice
882 (const :tag "Never" nil)
883 (const :tag "When outside special context" t)
884 (const :tag "Everywhere except timestamps" always)))
886 (defcustom org-loop-over-headlines-in-active-region nil
887 "Shall some commands act upon headlines in the active region?
889 When set to t, some commands will be performed in all headlines
890 within the active region.
892 When set to `start-level', some commands will be performed in all
893 headlines within the active region, provided that these headlines
894 are of the same level than the first one.
896 When set to a string, those commands will be performed on the
897 matching headlines within the active region. Such string must be
898 a tags/property/todo match as it is used in the agenda tags view.
900 The list of commands is: `org-schedule', `org-deadline',
901 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
902 `org-archive-to-archive-sibling'. The archiving commands skip
903 already archived entries."
904 :type '(choice (const :tag "Don't loop" nil)
905 (const :tag "All headlines in active region" t)
906 (const :tag "In active region, headlines at the same level than the first one" start-level)
907 (string :tag "Tags/Property/Todo matcher"))
908 :version "24.1"
909 :group 'org-todo
910 :group 'org-archive)
912 (defgroup org-startup nil
913 "Options concerning startup of Org-mode."
914 :tag "Org Startup"
915 :group 'org)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org-mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 By default, this option is ignored when Org opens agenda files
928 for the first time. If you want the agenda to honor the startup
929 option, set `org-agenda-inhibit-startup' to nil."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org-mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped."
941 :group 'org-startup
942 :type 'boolean)
944 (defcustom org-startup-indented nil
945 "Non-nil means turn on `org-indent-mode' on startup.
946 This can also be configured on a per-file basis by adding one of
947 the following lines anywhere in the buffer:
949 #+STARTUP: indent
950 #+STARTUP: noindent"
951 :group 'org-structure
952 :type '(choice
953 (const :tag "Not" nil)
954 (const :tag "Globally (slow on startup in large files)" t)))
956 (defcustom org-use-sub-superscripts t
957 "Non-nil means interpret \"_\" and \"^\" for display.
959 If you want to control how Org exports those characters, see
960 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
961 used to be an alias for `org-export-with-sub-superscripts' in
962 Org <8.0, it is not anymore.
964 When this option is turned on, you can use TeX-like syntax for
965 sub- and superscripts within the buffer. Several characters after
966 \"_\" or \"^\" will be considered as a single item - so grouping
967 with {} is normally not needed. For example, the following things
968 will be parsed as single sub- or superscripts:
970 10^24 or 10^tau several digits will be considered 1 item.
971 10^-12 or 10^-tau a leading sign with digits or a word
972 x^2-y^3 will be read as x^2 - y^3, because items are
973 terminated by almost any nonword/nondigit char.
974 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
976 Still, ambiguity is possible. So when in doubt, use {} to enclose
977 the sub/superscript. If you set this variable to the symbol `{}',
978 the braces are *required* in order to trigger interpretations as
979 sub/superscript. This can be helpful in documents that need \"_\"
980 frequently in plain text."
981 :group 'org-startup
982 :version "24.4"
983 :package-version '(Org . "8.0")
984 :type '(choice
985 (const :tag "Always interpret" t)
986 (const :tag "Only with braces" {})
987 (const :tag "Never interpret" nil)))
989 (defcustom org-startup-with-beamer-mode nil
990 "Non-nil means turn on `org-beamer-mode' on startup.
991 This can also be configured on a per-file basis by adding one of
992 the following lines anywhere in the buffer:
994 #+STARTUP: beamer"
995 :group 'org-startup
996 :version "24.1"
997 :type 'boolean)
999 (defcustom org-startup-align-all-tables nil
1000 "Non-nil means align all tables when visiting a file.
1001 This is useful when the column width in tables is forced with <N> cookies
1002 in table fields. Such tables will look correct only after the first re-align.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1005 #+STARTUP: align
1006 #+STARTUP: noalign"
1007 :group 'org-startup
1008 :type 'boolean)
1010 (defcustom org-startup-with-inline-images nil
1011 "Non-nil means show inline images when loading a new Org file.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: inlineimages
1015 #+STARTUP: noinlineimages"
1016 :group 'org-startup
1017 :version "24.1"
1018 :type 'boolean)
1020 (defcustom org-startup-with-latex-preview nil
1021 "Non-nil means preview LaTeX fragments when loading a new Org file.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: latexpreview
1026 #+STARTUP: nolatexpreview"
1027 :group 'org-startup
1028 :version "24.4"
1029 :package-version '(Org . "8.0")
1030 :type 'boolean)
1032 (defcustom org-insert-mode-line-in-empty-file nil
1033 "Non-nil means insert the first line setting Org-mode in empty files.
1034 When the function `org-mode' is called interactively in an empty file, this
1035 normally means that the file name does not automatically trigger Org-mode.
1036 To ensure that the file will always be in Org-mode in the future, a
1037 line enforcing Org-mode will be inserted into the buffer, if this option
1038 has been set."
1039 :group 'org-startup
1040 :type 'boolean)
1042 (defcustom org-replace-disputed-keys nil
1043 "Non-nil means use alternative key bindings for some keys.
1044 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1045 These keys are also used by other packages like shift-selection-mode'
1046 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1047 If you want to use Org-mode together with one of these other modes,
1048 or more generally if you would like to move some Org-mode commands to
1049 other keys, set this variable and configure the keys with the variable
1050 `org-disputed-keys'.
1052 This option is only relevant at load-time of Org-mode, and must be set
1053 *before* org.el is loaded. Changing it requires a restart of Emacs to
1054 become effective."
1055 :group 'org-startup
1056 :type 'boolean)
1058 (defcustom org-use-extra-keys nil
1059 "Non-nil means use extra key sequence definitions for certain commands.
1060 This happens automatically if you run XEmacs or if `window-system'
1061 is nil. This variable lets you do the same manually. You must
1062 set it before loading org.
1064 Example: on Carbon Emacs 22 running graphically, with an external
1065 keyboard on a Powerbook, the default way of setting M-left might
1066 not work for either Alt or ESC. Setting this variable will make
1067 it work for ESC."
1068 :group 'org-startup
1069 :type 'boolean)
1071 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1073 (defcustom org-disputed-keys
1074 '(([(shift up)] . [(meta p)])
1075 ([(shift down)] . [(meta n)])
1076 ([(shift left)] . [(meta -)])
1077 ([(shift right)] . [(meta +)])
1078 ([(control shift right)] . [(meta shift +)])
1079 ([(control shift left)] . [(meta shift -)]))
1080 "Keys for which Org-mode and other modes compete.
1081 This is an alist, cars are the default keys, second element specifies
1082 the alternative to use when `org-replace-disputed-keys' is t.
1084 Keys can be specified in any syntax supported by `define-key'.
1085 The value of this option takes effect only at Org-mode's startup,
1086 therefore you'll have to restart Emacs to apply it after changing."
1087 :group 'org-startup
1088 :type 'alist)
1090 (defun org-key (key)
1091 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1092 Or return the original if not disputed.
1093 Also apply the translations defined in `org-xemacs-key-equivalents'."
1094 (when org-replace-disputed-keys
1095 (let* ((nkey (key-description key))
1096 (x (org-find-if (lambda (x)
1097 (equal (key-description (car x)) nkey))
1098 org-disputed-keys)))
1099 (setq key (if x (cdr x) key))))
1100 (when (featurep 'xemacs)
1101 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1102 key)
1104 (defun org-find-if (predicate seq)
1105 (catch 'exit
1106 (while seq
1107 (if (funcall predicate (car seq))
1108 (throw 'exit (car seq))
1109 (pop seq)))))
1111 (defun org-defkey (keymap key def)
1112 "Define a key, possibly translated, as returned by `org-key'."
1113 (define-key keymap (org-key key) def))
1115 (defcustom org-ellipsis nil
1116 "The ellipsis to use in the Org-mode outline.
1117 When nil, just use the standard three dots.
1118 When a string, use that string instead.
1119 When a face, use the standard 3 dots, but with the specified face.
1120 The change affects only Org-mode (which will then use its own display table).
1121 Changing this requires executing \\[org-mode] in a buffer to become
1122 effective."
1123 :group 'org-startup
1124 :type '(choice (const :tag "Default" nil)
1125 (face :tag "Face" :value org-warning)
1126 (string :tag "String" :value "...#")))
1128 (defvar org-display-table nil
1129 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1131 (defgroup org-keywords nil
1132 "Keywords in Org-mode."
1133 :tag "Org Keywords"
1134 :group 'org)
1136 (defcustom org-closed-keep-when-no-todo nil
1137 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1138 :group 'org-todo
1139 :group 'org-keywords
1140 :version "24.4"
1141 :package-version '(Org . "8.0")
1142 :type 'boolean)
1144 (defgroup org-structure nil
1145 "Options concerning the general structure of Org-mode files."
1146 :tag "Org Structure"
1147 :group 'org)
1149 (defgroup org-reveal-location nil
1150 "Options about how to make context of a location visible."
1151 :tag "Org Reveal Location"
1152 :group 'org-structure)
1154 (defcustom org-show-context-detail '((isearch . lineage)
1155 (bookmark-jump . lineage)
1156 (default . ancestors))
1157 "Alist between context and visibility span when revealing a location.
1159 \\<org-mode-map>Some actions may move point into invisible
1160 locations. As a consequence, Org always expose a neighborhood
1161 around point. How much is shown depends on the initial action,
1162 or context. Valid contexts are
1164 agenda when exposing an entry from the agenda
1165 org-goto when using the command `org-goto' (\\[org-goto])
1166 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1167 tags-tree when constructing a sparse tree based on tags matches
1168 link-search when exposing search matches associated with a link
1169 mark-goto when exposing the jump goal of a mark
1170 bookmark-jump when exposing a bookmark location
1171 isearch when exiting from an incremental search
1172 default default for all contexts not set explicitly
1174 Allowed visibility spans are
1176 minimal show current headline; if point is not on headline,
1177 also show entry
1179 local show current headline, entry and next headline
1181 ancestors show current headline and its direct ancestors; if
1182 point is not on headline, also show entry
1184 lineage show current headline, its direct ancestors and all
1185 their children; if point is not on headline, also show
1186 entry and first child
1188 tree show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and all children
1192 canonical show current headline, its direct ancestors along with
1193 their entries and children; if point is not located on
1194 the headline, also show current entry and all children
1196 As special cases, a nil or t value means show all contexts in
1197 `minimal' or `canonical' view, respectively.
1199 Some views can make displayed information very compact, but also
1200 make it harder to edit the location of the match. In such
1201 a case, use the command `org-reveal' (\\[org-reveal]) to show
1202 more context."
1203 :group 'org-reveal-location
1204 :version "25.1"
1205 :package-version '(Org . "8.3")
1206 :type '(choice
1207 (const :tag "Canonical" t)
1208 (const :tag "Minimal" nil)
1209 (repeat :greedy t :tag "Individual contexts"
1210 (cons
1211 (choice :tag "Context"
1212 (const agenda)
1213 (const org-goto)
1214 (const occur-tree)
1215 (const tags-tree)
1216 (const link-search)
1217 (const mark-goto)
1218 (const bookmark-jump)
1219 (const isearch)
1220 (const default))
1221 (choice :tag "Detail level"
1222 (const minimal)
1223 (const local)
1224 (const ancestors)
1225 (const lineage)
1226 (const tree)
1227 (const canonical))))))
1229 (defcustom org-indirect-buffer-display 'other-window
1230 "How should indirect tree buffers be displayed?
1231 This applies to indirect buffers created with the commands
1232 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1233 Valid values are:
1234 current-window Display in the current window
1235 other-window Just display in another window.
1236 dedicated-frame Create one new frame, and re-use it each time.
1237 new-frame Make a new frame each time. Note that in this case
1238 previously-made indirect buffers are kept, and you need to
1239 kill these buffers yourself."
1240 :group 'org-structure
1241 :group 'org-agenda-windows
1242 :type '(choice
1243 (const :tag "In current window" current-window)
1244 (const :tag "In current frame, other window" other-window)
1245 (const :tag "Each time a new frame" new-frame)
1246 (const :tag "One dedicated frame" dedicated-frame)))
1248 (defcustom org-use-speed-commands nil
1249 "Non-nil means activate single letter commands at beginning of a headline.
1250 This may also be a function to test for appropriate locations where speed
1251 commands should be active.
1253 For example, to activate speed commands when the point is on any
1254 star at the beginning of the headline, you can do this:
1256 (setq org-use-speed-commands
1257 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1258 :group 'org-structure
1259 :type '(choice
1260 (const :tag "Never" nil)
1261 (const :tag "At beginning of headline stars" t)
1262 (function)))
1264 (defcustom org-speed-commands-user nil
1265 "Alist of additional speed commands.
1266 This list will be checked before `org-speed-commands-default'
1267 when the variable `org-use-speed-commands' is non-nil
1268 and when the cursor is at the beginning of a headline.
1269 The car if each entry is a string with a single letter, which must
1270 be assigned to `self-insert-command' in the global map.
1271 The cdr is either a command to be called interactively, a function
1272 to be called, or a form to be evaluated.
1273 An entry that is just a list with a single string will be interpreted
1274 as a descriptive headline that will be added when listing the speed
1275 commands in the Help buffer using the `?' speed command."
1276 :group 'org-structure
1277 :type '(repeat :value ("k" . ignore)
1278 (choice :value ("k" . ignore)
1279 (list :tag "Descriptive Headline" (string :tag "Headline"))
1280 (cons :tag "Letter and Command"
1281 (string :tag "Command letter")
1282 (choice
1283 (function)
1284 (sexp))))))
1286 (defcustom org-bookmark-names-plist
1287 '(:last-capture "org-capture-last-stored"
1288 :last-refile "org-refile-last-stored"
1289 :last-capture-marker "org-capture-last-stored-marker")
1290 "Names for bookmarks automatically set by some Org commands.
1291 This can provide strings as names for a number of bookmarks Org sets
1292 automatically. The following keys are currently implemented:
1293 :last-capture
1294 :last-capture-marker
1295 :last-refile
1296 When a key does not show up in the property list, the corresponding bookmark
1297 is not set."
1298 :group 'org-structure
1299 :type 'plist)
1301 (defgroup org-cycle nil
1302 "Options concerning visibility cycling in Org-mode."
1303 :tag "Org Cycle"
1304 :group 'org-structure)
1306 (defcustom org-cycle-skip-children-state-if-no-children t
1307 "Non-nil means skip CHILDREN state in entries that don't have any."
1308 :group 'org-cycle
1309 :type 'boolean)
1311 (defcustom org-cycle-max-level nil
1312 "Maximum level which should still be subject to visibility cycling.
1313 Levels higher than this will, for cycling, be treated as text, not a headline.
1314 When `org-odd-levels-only' is set, a value of N in this variable actually
1315 means 2N-1 stars as the limiting headline.
1316 When nil, cycle all levels.
1317 Note that the limiting level of cycling is also influenced by
1318 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1319 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1320 than its value."
1321 :group 'org-cycle
1322 :type '(choice
1323 (const :tag "No limit" nil)
1324 (integer :tag "Maximum level")))
1326 (defcustom org-hide-block-startup nil
1327 "Non-nil means entering Org-mode will fold all blocks.
1328 This can also be set in on a per-file basis with
1330 #+STARTUP: hideblocks
1331 #+STARTUP: showblocks"
1332 :group 'org-startup
1333 :group 'org-cycle
1334 :type 'boolean)
1336 (defcustom org-cycle-global-at-bob nil
1337 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1338 This makes it possible to do global cycling without having to use S-TAB or
1339 \\[universal-argument] TAB. For this special case to work, the first line
1340 of the buffer must not be a headline -- it may be empty or some other text.
1341 When used in this way, `org-cycle-hook' is disabled temporarily to make
1342 sure the cursor stays at the beginning of the buffer. When this option is
1343 nil, don't do anything special at the beginning of the buffer."
1344 :group 'org-cycle
1345 :type 'boolean)
1347 (defcustom org-cycle-level-after-item/entry-creation t
1348 "Non-nil means cycle entry level or item indentation in new empty entries.
1350 When the cursor is at the end of an empty headline, i.e., with only stars
1351 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1352 and then all possible ancestor states, before returning to the original state.
1353 This makes data entry extremely fast: M-RET to create a new headline,
1354 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1356 When the cursor is at the end of an empty plain list item, one TAB will
1357 make it a subitem, two or more tabs will back up to make this an item
1358 higher up in the item hierarchy."
1359 :group 'org-cycle
1360 :type 'boolean)
1362 (defcustom org-cycle-emulate-tab t
1363 "Where should `org-cycle' emulate TAB.
1364 nil Never
1365 white Only in completely white lines
1366 whitestart Only at the beginning of lines, before the first non-white char
1367 t Everywhere except in headlines
1368 exc-hl-bol Everywhere except at the start of a headline
1369 If TAB is used in a place where it does not emulate TAB, the current subtree
1370 visibility is cycled."
1371 :group 'org-cycle
1372 :type '(choice (const :tag "Never" nil)
1373 (const :tag "Only in completely white lines" white)
1374 (const :tag "Before first char in a line" whitestart)
1375 (const :tag "Everywhere except in headlines" t)
1376 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1378 (defcustom org-cycle-separator-lines 2
1379 "Number of empty lines needed to keep an empty line between collapsed trees.
1380 If you leave an empty line between the end of a subtree and the following
1381 headline, this empty line is hidden when the subtree is folded.
1382 Org-mode will leave (exactly) one empty line visible if the number of
1383 empty lines is equal or larger to the number given in this variable.
1384 So the default 2 means at least 2 empty lines after the end of a subtree
1385 are needed to produce free space between a collapsed subtree and the
1386 following headline.
1388 If the number is negative, and the number of empty lines is at least -N,
1389 all empty lines are shown.
1391 Special case: when 0, never leave empty lines in collapsed view."
1392 :group 'org-cycle
1393 :type 'integer)
1394 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1396 (defcustom org-pre-cycle-hook nil
1397 "Hook that is run before visibility cycling is happening.
1398 The function(s) in this hook must accept a single argument which indicates
1399 the new state that will be set right after running this hook. The
1400 argument is a symbol. Before a global state change, it can have the values
1401 `overview', `content', or `all'. Before a local state change, it can have
1402 the values `folded', `children', or `subtree'."
1403 :group 'org-cycle
1404 :type 'hook)
1406 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1407 org-cycle-hide-drawers
1408 org-cycle-show-empty-lines
1409 org-optimize-window-after-visibility-change)
1410 "Hook that is run after `org-cycle' has changed the buffer visibility.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that was set by the most recent `org-cycle' command. The
1413 argument is a symbol. After a global state change, it can have the values
1414 `overview', `contents', or `all'. After a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook
1418 :version "25.1"
1419 :package-version '(Org . "8.3"))
1421 (defgroup org-edit-structure nil
1422 "Options concerning structure editing in Org-mode."
1423 :tag "Org Edit Structure"
1424 :group 'org-structure)
1426 (defcustom org-odd-levels-only nil
1427 "Non-nil means skip even levels and only use odd levels for the outline.
1428 This has the effect that two stars are being added/taken away in
1429 promotion/demotion commands. It also influences how levels are
1430 handled by the exporters.
1431 Changing it requires restart of `font-lock-mode' to become effective
1432 for fontification also in regions already fontified.
1433 You may also set this on a per-file basis by adding one of the following
1434 lines to the buffer:
1436 #+STARTUP: odd
1437 #+STARTUP: oddeven"
1438 :group 'org-edit-structure
1439 :group 'org-appearance
1440 :type 'boolean)
1442 (defcustom org-adapt-indentation t
1443 "Non-nil means adapt indentation to outline node level.
1445 When this variable is set, Org assumes that you write outlines by
1446 indenting text in each node to align with the headline (after the
1447 stars). The following issues are influenced by this variable:
1449 - The indentation is increased by one space in a demotion
1450 command, and decreased by one in a promotion command. However,
1451 in the latter case, if shifting some line in the entry body
1452 would alter document structure (e.g., insert a new headline),
1453 indentation is not changed at all.
1455 - Property drawers and planning information is inserted indented
1456 when this variable is set. When nil, they will not be indented.
1458 - TAB indents a line relative to current level. The lines below
1459 a headline will be indented when this variable is set.
1461 Note that this is all about true indentation, by adding and
1462 removing space characters. See also `org-indent.el' which does
1463 level-dependent indentation in a virtual way, i.e. at display
1464 time in Emacs."
1465 :group 'org-edit-structure
1466 :type 'boolean)
1468 (defcustom org-special-ctrl-a/e nil
1469 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1471 When t, `C-a' will bring back the cursor to the beginning of the
1472 headline text, i.e. after the stars and after a possible TODO
1473 keyword. In an item, this will be the position after bullet and
1474 check-box, if any. When the cursor is already at that position,
1475 another `C-a' will bring it to the beginning of the line.
1477 `C-e' will jump to the end of the headline, ignoring the presence
1478 of tags in the headline. A second `C-e' will then jump to the
1479 true end of the line, after any tags. This also means that, when
1480 this variable is non-nil, `C-e' also will never jump beyond the
1481 end of the heading of a folded section, i.e. not after the
1482 ellipses.
1484 When set to the symbol `reversed', the first `C-a' or `C-e' works
1485 normally, going to the true line boundary first. Only a directly
1486 following, identical keypress will bring the cursor to the
1487 special positions.
1489 This may also be a cons cell where the behavior for `C-a' and
1490 `C-e' is set separately."
1491 :group 'org-edit-structure
1492 :type '(choice
1493 (const :tag "off" nil)
1494 (const :tag "on: after stars/bullet and before tags first" t)
1495 (const :tag "reversed: true line boundary first" reversed)
1496 (cons :tag "Set C-a and C-e separately"
1497 (choice :tag "Special C-a"
1498 (const :tag "off" nil)
1499 (const :tag "on: after stars/bullet first" t)
1500 (const :tag "reversed: before stars/bullet first" reversed))
1501 (choice :tag "Special C-e"
1502 (const :tag "off" nil)
1503 (const :tag "on: before tags first" t)
1504 (const :tag "reversed: after tags first" reversed)))))
1505 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1507 (defcustom org-special-ctrl-k nil
1508 "Non-nil means `C-k' will behave specially in headlines.
1509 When nil, `C-k' will call the default `kill-line' command.
1510 When t, the following will happen while the cursor is in the headline:
1512 - When the cursor is at the beginning of a headline, kill the entire
1513 line and possible the folded subtree below the line.
1514 - When in the middle of the headline text, kill the headline up to the tags.
1515 - When after the headline text, kill the tags."
1516 :group 'org-edit-structure
1517 :type 'boolean)
1519 (defcustom org-ctrl-k-protect-subtree nil
1520 "Non-nil means, do not delete a hidden subtree with C-k.
1521 When set to the symbol `error', simply throw an error when C-k is
1522 used to kill (part-of) a headline that has hidden text behind it.
1523 Any other non-nil value will result in a query to the user, if it is
1524 OK to kill that hidden subtree. When nil, kill without remorse."
1525 :group 'org-edit-structure
1526 :version "24.1"
1527 :type '(choice
1528 (const :tag "Do not protect hidden subtrees" nil)
1529 (const :tag "Protect hidden subtrees with a security query" t)
1530 (const :tag "Never kill a hidden subtree with C-k" error)))
1532 (defcustom org-special-ctrl-o t
1533 "Non-nil means, make `C-o' insert a row in tables."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-catch-invisible-edits nil
1538 "Check if in invisible region before inserting or deleting a character.
1539 Valid values are:
1541 nil Do not check, so just do invisible edits.
1542 error Throw an error and do nothing.
1543 show Make point visible, and do the requested edit.
1544 show-and-error Make point visible, then throw an error and abort the edit.
1545 smart Make point visible, and do insertion/deletion if it is
1546 adjacent to visible text and the change feels predictable.
1547 Never delete a previously invisible character or add in the
1548 middle or right after an invisible region. Basically, this
1549 allows insertion and backward-delete right before ellipses.
1550 FIXME: maybe in this case we should not even show?"
1551 :group 'org-edit-structure
1552 :version "24.1"
1553 :type '(choice
1554 (const :tag "Do not check" nil)
1555 (const :tag "Throw error when trying to edit" error)
1556 (const :tag "Unhide, but do not do the edit" show-and-error)
1557 (const :tag "Show invisible part and do the edit" show)
1558 (const :tag "Be smart and do the right thing" smart)))
1560 (defcustom org-yank-folded-subtrees t
1561 "Non-nil means when yanking subtrees, fold them.
1562 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1563 it starts with a heading and all other headings in it are either children
1564 or siblings, then fold all the subtrees. However, do this only if no
1565 text after the yank would be swallowed into a folded tree by this action."
1566 :group 'org-edit-structure
1567 :type 'boolean)
1569 (defcustom org-yank-adjusted-subtrees nil
1570 "Non-nil means when yanking subtrees, adjust the level.
1571 With this setting, `org-paste-subtree' is used to insert the subtree, see
1572 this function for details."
1573 :group 'org-edit-structure
1574 :type 'boolean)
1576 (defcustom org-M-RET-may-split-line '((default . t))
1577 "Non-nil means M-RET will split the line at the cursor position.
1578 When nil, it will go to the end of the line before making a
1579 new line.
1580 You may also set this option in a different way for different
1581 contexts. Valid contexts are:
1583 headline when creating a new headline
1584 item when creating a new item
1585 table in a table field
1586 default the value to be used for all contexts not explicitly
1587 customized"
1588 :group 'org-structure
1589 :group 'org-table
1590 :type '(choice
1591 (const :tag "Always" t)
1592 (const :tag "Never" nil)
1593 (repeat :greedy t :tag "Individual contexts"
1594 (cons
1595 (choice :tag "Context"
1596 (const headline)
1597 (const item)
1598 (const table)
1599 (const default))
1600 (boolean)))))
1603 (defcustom org-insert-heading-respect-content nil
1604 "Non-nil means insert new headings after the current subtree.
1605 When nil, the new heading is created directly after the current line.
1606 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1607 this variable on for the duration of the command."
1608 :group 'org-structure
1609 :type 'boolean)
1611 (defcustom org-blank-before-new-entry '((heading . auto)
1612 (plain-list-item . auto))
1613 "Should `org-insert-heading' leave a blank line before new heading/item?
1614 The value is an alist, with `heading' and `plain-list-item' as CAR,
1615 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1616 which case Org will look at the surrounding headings/items and try to
1617 make an intelligent decision whether to insert a blank line or not."
1618 :group 'org-edit-structure
1619 :type '(list
1620 (cons (const heading)
1621 (choice (const :tag "Never" nil)
1622 (const :tag "Always" t)
1623 (const :tag "Auto" auto)))
1624 (cons (const plain-list-item)
1625 (choice (const :tag "Never" nil)
1626 (const :tag "Always" t)
1627 (const :tag "Auto" auto)))))
1629 (defcustom org-insert-heading-hook nil
1630 "Hook being run after inserting a new heading."
1631 :group 'org-edit-structure
1632 :type 'hook)
1634 (defcustom org-enable-fixed-width-editor t
1635 "Non-nil means lines starting with \":\" are treated as fixed-width.
1636 This currently only means they are never auto-wrapped.
1637 When nil, such lines will be treated like ordinary lines."
1638 :group 'org-edit-structure
1639 :type 'boolean)
1641 (defcustom org-goto-auto-isearch t
1642 "Non-nil means typing characters in `org-goto' starts incremental search.
1643 When nil, you can use these keybindings to navigate the buffer:
1645 q Quit the org-goto interface
1646 n Go to the next visible heading
1647 p Go to the previous visible heading
1648 f Go one heading forward on same level
1649 b Go one heading backward on same level
1650 u Go one heading up"
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defgroup org-sparse-trees nil
1655 "Options concerning sparse trees in Org-mode."
1656 :tag "Org Sparse Trees"
1657 :group 'org-structure)
1659 (defcustom org-highlight-sparse-tree-matches t
1660 "Non-nil means highlight all matches that define a sparse tree.
1661 The highlights will automatically disappear the next time the buffer is
1662 changed by an edit command."
1663 :group 'org-sparse-trees
1664 :type 'boolean)
1666 (defcustom org-remove-highlights-with-change t
1667 "Non-nil means any change to the buffer will remove temporary highlights.
1668 \\<org-mode-map>\
1669 Such highlights are created by `org-occur' and `org-clock-display'.
1670 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1671 to get rid of the highlights.
1672 The highlights created by `org-toggle-latex-fragment' always need
1673 `\\[org-toggle-latex-fragment]' to be removed."
1674 :group 'org-sparse-trees
1675 :group 'org-time
1676 :type 'boolean)
1679 (defcustom org-occur-hook '(org-first-headline-recenter)
1680 "Hook that is run after `org-occur' has constructed a sparse tree.
1681 This can be used to recenter the window to show as much of the structure
1682 as possible."
1683 :group 'org-sparse-trees
1684 :type 'hook)
1686 (defgroup org-imenu-and-speedbar nil
1687 "Options concerning imenu and speedbar in Org-mode."
1688 :tag "Org Imenu and Speedbar"
1689 :group 'org-structure)
1691 (defcustom org-imenu-depth 2
1692 "The maximum level for Imenu access to Org-mode headlines.
1693 This also applied for speedbar access."
1694 :group 'org-imenu-and-speedbar
1695 :type 'integer)
1697 (defgroup org-table nil
1698 "Options concerning tables in Org-mode."
1699 :tag "Org Table"
1700 :group 'org)
1702 (defcustom org-enable-table-editor 'optimized
1703 "Non-nil means lines starting with \"|\" are handled by the table editor.
1704 When nil, such lines will be treated like ordinary lines.
1706 When equal to the symbol `optimized', the table editor will be optimized to
1707 do the following:
1708 - Automatic overwrite mode in front of whitespace in table fields.
1709 This makes the structure of the table stay in tact as long as the edited
1710 field does not exceed the column width.
1711 - Minimize the number of realigns. Normally, the table is aligned each time
1712 TAB or RET are pressed to move to another field. With optimization this
1713 happens only if changes to a field might have changed the column width.
1714 Optimization requires replacing the functions `self-insert-command',
1715 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1716 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1717 very good at guessing when a re-align will be necessary, but you can always
1718 force one with \\[org-ctrl-c-ctrl-c].
1720 If you would like to use the optimized version in Org-mode, but the
1721 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1723 This variable can be used to turn on and off the table editor during a session,
1724 but in order to toggle optimization, a restart is required.
1726 See also the variable `org-table-auto-blank-field'."
1727 :group 'org-table
1728 :type '(choice
1729 (const :tag "off" nil)
1730 (const :tag "on" t)
1731 (const :tag "on, optimized" optimized)))
1733 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1734 (version<= emacs-version "24.1"))
1735 "Non-nil means cluster self-insert commands for undo when possible.
1736 If this is set, then, like in the Emacs command loop, 20 consecutive
1737 characters will be undone together.
1738 This is configurable, because there is some impact on typing performance."
1739 :group 'org-table
1740 :type 'boolean)
1742 (defcustom org-table-tab-recognizes-table.el t
1743 "Non-nil means TAB will automatically notice a table.el table.
1744 When it sees such a table, it moves point into it and - if necessary -
1745 calls `table-recognize-table'."
1746 :group 'org-table-editing
1747 :type 'boolean)
1749 (defgroup org-link nil
1750 "Options concerning links in Org-mode."
1751 :tag "Org Link"
1752 :group 'org)
1754 (defvar-local org-link-abbrev-alist-local nil
1755 "Buffer-local version of `org-link-abbrev-alist', which see.
1756 The value of this is taken from the #+LINK lines.")
1758 (defcustom org-link-abbrev-alist nil
1759 "Alist of link abbreviations.
1760 The car of each element is a string, to be replaced at the start of a link.
1761 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1762 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1764 [[linkkey:tag][description]]
1766 The `linkkey' must be a word word, starting with a letter, followed
1767 by letters, numbers, `-' or `_'.
1769 If REPLACE is a string, the tag will simply be appended to create the link.
1770 If the string contains \"%s\", the tag will be inserted there. If the string
1771 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1772 at that point (see the function `url-hexify-string'). If the string contains
1773 the specifier \"%(my-function)\", then the custom function `my-function' will
1774 be invoked: this function takes the tag as its only argument and must return
1775 a string.
1777 REPLACE may also be a function that will be called with the tag as the
1778 only argument to create the link, which should be returned as a string.
1780 See the manual for examples."
1781 :group 'org-link
1782 :type '(repeat
1783 (cons
1784 (string :tag "Protocol")
1785 (choice
1786 (string :tag "Format")
1787 (function)))))
1789 (defcustom org-descriptive-links t
1790 "Non-nil means Org will display descriptive links.
1791 E.g. [[http://orgmode.org][Org website]] will be displayed as
1792 \"Org Website\", hiding the link itself and just displaying its
1793 description. When set to nil, Org will display the full links
1794 literally.
1796 You can interactively set the value of this variable by calling
1797 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1798 :group 'org-link
1799 :type 'boolean)
1801 (defcustom org-link-file-path-type 'adaptive
1802 "How the path name in file links should be stored.
1803 Valid values are:
1805 relative Relative to the current directory, i.e. the directory of the file
1806 into which the link is being inserted.
1807 absolute Absolute path, if possible with ~ for home directory.
1808 noabbrev Absolute path, no abbreviation of home directory.
1809 adaptive Use relative path for files in the current directory and sub-
1810 directories of it. For other files, use an absolute path."
1811 :group 'org-link
1812 :type '(choice
1813 (const relative)
1814 (const absolute)
1815 (const noabbrev)
1816 (const adaptive)))
1818 (defvaralias 'org-activate-links 'org-highlight-links)
1819 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1820 "Types of links that should be highlighted in Org-mode files.
1822 This is a list of symbols, each one of them leading to the
1823 highlighting of a certain link type.
1825 You can still open links that are not highlighted.
1827 In principle, it does not hurt to turn on highlighting for all
1828 link types. There may be a small gain when turning off unused
1829 link types. The types are:
1831 bracket The recommended [[link][description]] or [[link]] links with hiding.
1832 angle Links in angular brackets that may contain whitespace like
1833 <bbdb:Carsten Dominik>.
1834 plain Plain links in normal text, no whitespace, like http://google.com.
1835 radio Text that is matched by a radio target, see manual for details.
1836 tag Tag settings in a headline (link to tag search).
1837 date Time stamps (link to calendar).
1838 footnote Footnote labels.
1840 If you set this variable during an Emacs session, use `org-mode-restart'
1841 in the Org buffer so that the change takes effect."
1842 :group 'org-link
1843 :group 'org-appearance
1844 :type '(set :greedy t
1845 (const :tag "Double bracket links" bracket)
1846 (const :tag "Angular bracket links" angle)
1847 (const :tag "Plain text links" plain)
1848 (const :tag "Radio target matches" radio)
1849 (const :tag "Tags" tag)
1850 (const :tag "Timestamps" date)
1851 (const :tag "Footnotes" footnote)))
1853 (defcustom org-make-link-description-function nil
1854 "Function to use for generating link descriptions from links.
1855 When nil, the link location will be used. This function must take
1856 two parameters: the first one is the link, the second one is the
1857 description generated by `org-insert-link'. The function should
1858 return the description to use."
1859 :group 'org-link
1860 :type '(choice (const nil) (function)))
1862 (defgroup org-link-store nil
1863 "Options concerning storing links in Org-mode."
1864 :tag "Org Store Link"
1865 :group 'org-link)
1867 (defcustom org-url-hexify-p t
1868 "When non-nil, hexify URL when creating a link."
1869 :type 'boolean
1870 :version "24.3"
1871 :group 'org-link-store)
1873 (defcustom org-email-link-description-format "Email %c: %.30s"
1874 "Format of the description part of a link to an email or usenet message.
1875 The following %-escapes will be replaced by corresponding information:
1877 %F full \"From\" field
1878 %f name, taken from \"From\" field, address if no name
1879 %T full \"To\" field
1880 %t first name in \"To\" field, address if no name
1881 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1882 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1883 %s subject
1884 %d date
1885 %m message-id.
1887 You may use normal field width specification between the % and the letter.
1888 This is for example useful to limit the length of the subject.
1890 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1891 :group 'org-link-store
1892 :type 'string)
1894 (defcustom org-from-is-user-regexp
1895 (let (r1 r2)
1896 (when (and user-mail-address (not (string= user-mail-address "")))
1897 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1898 (when (and user-full-name (not (string= user-full-name "")))
1899 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1900 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1901 "Regexp matched against the \"From:\" header of an email or usenet message.
1902 It should match if the message is from the user him/herself."
1903 :group 'org-link-store
1904 :type 'regexp)
1906 (defcustom org-context-in-file-links t
1907 "Non-nil means file links from `org-store-link' contain context.
1908 A search string will be added to the file name with :: as separator and
1909 used to find the context when the link is activated by the command
1910 `org-open-at-point'. When this option is t, the entire active region
1911 will be placed in the search string of the file link. If set to a
1912 positive integer, only the first n lines of context will be stored.
1914 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1915 negates this setting for the duration of the command."
1916 :group 'org-link-store
1917 :type '(choice boolean integer))
1919 (defcustom org-keep-stored-link-after-insertion nil
1920 "Non-nil means keep link in list for entire session.
1922 The command `org-store-link' adds a link pointing to the current
1923 location to an internal list. These links accumulate during a session.
1924 The command `org-insert-link' can be used to insert links into any
1925 Org-mode file (offering completion for all stored links). When this
1926 option is nil, every link which has been inserted once using \\[org-insert-link]
1927 will be removed from the list, to make completing the unused links
1928 more efficient."
1929 :group 'org-link-store
1930 :type 'boolean)
1932 (defgroup org-link-follow nil
1933 "Options concerning following links in Org-mode."
1934 :tag "Org Follow Link"
1935 :group 'org-link)
1937 (defcustom org-link-translation-function nil
1938 "Function to translate links with different syntax to Org syntax.
1939 This can be used to translate links created for example by the Planner
1940 or emacs-wiki packages to Org syntax.
1941 The function must accept two parameters, a TYPE containing the link
1942 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1943 which is everything after the link protocol. It should return a cons
1944 with possibly modified values of type and path.
1945 Org contains a function for this, so if you set this variable to
1946 `org-translate-link-from-planner', you should be able follow many
1947 links created by planner."
1948 :group 'org-link-follow
1949 :type '(choice (const nil) (function)))
1951 (defcustom org-follow-link-hook nil
1952 "Hook that is run after a link has been followed."
1953 :group 'org-link-follow
1954 :type 'hook)
1956 (defcustom org-tab-follows-link nil
1957 "Non-nil means on links TAB will follow the link.
1958 Needs to be set before org.el is loaded.
1959 This really should not be used, it does not make sense, and the
1960 implementation is bad."
1961 :group 'org-link-follow
1962 :type 'boolean)
1964 (defcustom org-return-follows-link nil
1965 "Non-nil means on links RET will follow the link.
1966 In tables, the special behavior of RET has precedence."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-mouse-1-follows-link
1971 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1972 "Non-nil means mouse-1 on a link will follow the link.
1973 A longer mouse click will still set point. Does not work on XEmacs.
1974 Needs to be set before org.el is loaded."
1975 :group 'org-link-follow
1976 :version "24.4"
1977 :package-version '(Org . "8.3")
1978 :type '(choice
1979 (const :tag "A double click follows the link" double)
1980 (const :tag "Unconditionally follow the link with mouse-1" t)
1981 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1983 (defcustom org-mark-ring-length 4
1984 "Number of different positions to be recorded in the ring.
1985 Changing this requires a restart of Emacs to work correctly."
1986 :group 'org-link-follow
1987 :type 'integer)
1989 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1990 "Non-nil means internal links in Org files must exactly match a headline.
1991 When nil, the link search tries to match a phrase with all words
1992 in the search text."
1993 :group 'org-link-follow
1994 :version "24.1"
1995 :type '(choice
1996 (const :tag "Use fuzzy text search" nil)
1997 (const :tag "Match only exact headline" t)
1998 (const :tag "Match exact headline or query to create it"
1999 query-to-create)))
2001 (defcustom org-link-frame-setup
2002 '((vm . vm-visit-folder-other-frame)
2003 (vm-imap . vm-visit-imap-folder-other-frame)
2004 (gnus . org-gnus-no-new-news)
2005 (file . find-file-other-window)
2006 (wl . wl-other-frame))
2007 "Setup the frame configuration for following links.
2008 When following a link with Emacs, it may often be useful to display
2009 this link in another window or frame. This variable can be used to
2010 set this up for the different types of links.
2011 For VM, use any of
2012 `vm-visit-folder'
2013 `vm-visit-folder-other-window'
2014 `vm-visit-folder-other-frame'
2015 For Gnus, use any of
2016 `gnus'
2017 `gnus-other-frame'
2018 `org-gnus-no-new-news'
2019 For FILE, use any of
2020 `find-file'
2021 `find-file-other-window'
2022 `find-file-other-frame'
2023 For Wanderlust use any of
2024 `wl'
2025 `wl-other-frame'
2026 For the calendar, use the variable `calendar-setup'.
2027 For BBDB, it is currently only possible to display the matches in
2028 another window."
2029 :group 'org-link-follow
2030 :type '(list
2031 (cons (const vm)
2032 (choice
2033 (const vm-visit-folder)
2034 (const vm-visit-folder-other-window)
2035 (const vm-visit-folder-other-frame)))
2036 (cons (const vm-imap)
2037 (choice
2038 (const vm-visit-imap-folder)
2039 (const vm-visit-imap-folder-other-window)
2040 (const vm-visit-imap-folder-other-frame)))
2041 (cons (const gnus)
2042 (choice
2043 (const gnus)
2044 (const gnus-other-frame)
2045 (const org-gnus-no-new-news)))
2046 (cons (const file)
2047 (choice
2048 (const find-file)
2049 (const find-file-other-window)
2050 (const find-file-other-frame)))
2051 (cons (const wl)
2052 (choice
2053 (const wl)
2054 (const wl-other-frame)))))
2056 (defcustom org-display-internal-link-with-indirect-buffer nil
2057 "Non-nil means use indirect buffer to display infile links.
2058 Activating internal links (from one location in a file to another location
2059 in the same file) normally just jumps to the location. When the link is
2060 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2061 is displayed in
2062 another window. When this option is set, the other window actually displays
2063 an indirect buffer clone of the current buffer, to avoid any visibility
2064 changes to the current buffer."
2065 :group 'org-link-follow
2066 :type 'boolean)
2068 (defcustom org-open-non-existing-files nil
2069 "Non-nil means `org-open-file' will open non-existing files.
2070 When nil, an error will be generated.
2071 This variable applies only to external applications because they
2072 might choke on non-existing files. If the link is to a file that
2073 will be opened in Emacs, the variable is ignored."
2074 :group 'org-link-follow
2075 :type 'boolean)
2077 (defcustom org-open-directory-means-index-dot-org nil
2078 "Non-nil means a link to a directory really means to index.org.
2079 When nil, following a directory link will run dired or open a finder/explorer
2080 window on that directory."
2081 :group 'org-link-follow
2082 :type 'boolean)
2084 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2085 "Non-nil means ask for confirmation before executing shell links.
2086 Shell links can be dangerous: just think about a link
2088 [[shell:rm -rf ~/*][Google Search]]
2090 This link would show up in your Org-mode document as \"Google Search\",
2091 but really it would remove your entire home directory.
2092 Therefore we advise against setting this variable to nil.
2093 Just change it to `y-or-n-p' if you want to confirm with a
2094 single keystroke rather than having to type \"yes\"."
2095 :group 'org-link-follow
2096 :type '(choice
2097 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2098 (const :tag "with y-or-n (faster)" y-or-n-p)
2099 (const :tag "no confirmation (dangerous)" nil)))
2100 (put 'org-confirm-shell-link-function
2101 'safe-local-variable
2102 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2104 (defcustom org-confirm-shell-link-not-regexp ""
2105 "A regexp to skip confirmation for shell links."
2106 :group 'org-link-follow
2107 :version "24.1"
2108 :type 'regexp)
2110 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2111 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2112 Elisp links can be dangerous: just think about a link
2114 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2116 This link would show up in your Org-mode document as \"Google Search\",
2117 but really it would remove your entire home directory.
2118 Therefore we advise against setting this variable to nil.
2119 Just change it to `y-or-n-p' if you want to confirm with a
2120 single keystroke rather than having to type \"yes\"."
2121 :group 'org-link-follow
2122 :type '(choice
2123 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2124 (const :tag "with y-or-n (faster)" y-or-n-p)
2125 (const :tag "no confirmation (dangerous)" nil)))
2126 (put 'org-confirm-shell-link-function
2127 'safe-local-variable
2128 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2130 (defcustom org-confirm-elisp-link-not-regexp ""
2131 "A regexp to skip confirmation for Elisp links."
2132 :group 'org-link-follow
2133 :version "24.1"
2134 :type 'regexp)
2136 (defconst org-file-apps-defaults-gnu
2137 '((remote . emacs)
2138 (system . mailcap)
2139 (t . mailcap))
2140 "Default file applications on a UNIX or GNU/Linux system.
2141 See `org-file-apps'.")
2143 (defconst org-file-apps-defaults-macosx
2144 '((remote . emacs)
2145 (system . "open %s")
2146 ("ps.gz" . "gv %s")
2147 ("eps.gz" . "gv %s")
2148 ("dvi" . "xdvi %s")
2149 ("fig" . "xfig %s")
2150 (t . "open %s"))
2151 "Default file applications on a MacOS X system.
2152 The system \"open\" is known as a default, but we use X11 applications
2153 for some files for which the OS does not have a good default.
2154 See `org-file-apps'.")
2156 (defconst org-file-apps-defaults-windowsnt
2157 (list '(remote . emacs)
2158 (cons 'system (lambda (file _path)
2159 (with-no-warnings (w32-shell-execute "open" file))))
2160 (cons t (lambda (file _path)
2161 (with-no-warnings (w32-shell-execute "open" file)))))
2162 "Default file applications on a Windows NT system.
2163 The system \"open\" is used for most files.
2164 See `org-file-apps'.")
2166 (defcustom org-file-apps
2167 '((auto-mode . emacs)
2168 ("\\.mm\\'" . default)
2169 ("\\.x?html?\\'" . default)
2170 ("\\.pdf\\'" . default))
2171 "External applications for opening `file:path' items in a document.
2172 \\<org-mode-map>\
2173 Org mode uses system defaults for different file types, but
2174 you can use this variable to set the application for a given file
2175 extension. The entries in this list are cons cells where the car identifies
2176 files and the cdr the corresponding command. Possible values for the
2177 file identifier are
2178 \"string\" A string as a file identifier can be interpreted in different
2179 ways, depending on its contents:
2181 - Alphanumeric characters only:
2182 Match links with this file extension.
2183 Example: (\"pdf\" . \"evince %s\")
2184 to open PDFs with evince.
2186 - Regular expression: Match links where the
2187 filename matches the regexp. If you want to
2188 use groups here, use shy groups.
2190 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2191 \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2192 to open *.html and *.xhtml with firefox.
2194 - Regular expression which contains (non-shy) groups:
2195 Match links where the whole link, including \"::\", and
2196 anything after that, matches the regexp.
2197 In a custom command string, %1, %2, etc. are replaced with
2198 the parts of the link that were matched by the groups.
2199 For backwards compatibility, if a command string is given
2200 that does not use any of the group matches, this case is
2201 handled identically to the second one (i.e. match against
2202 file name only).
2203 In a custom function, you can access the group matches with
2204 \(match-string n link).
2206 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2207 to open [[file:document.pdf::5]] with evince at page 5.
2209 `directory' Matches a directory
2210 `remote' Matches a remote file, accessible through tramp or efs.
2211 Remote files most likely should be visited through Emacs
2212 because external applications cannot handle such paths.
2213 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2214 so all files Emacs knows how to handle. Using this with
2215 command `emacs' will open most files in Emacs. Beware that this
2216 will also open html files inside Emacs, unless you add
2217 \(\"html\" . default) to the list as well.
2218 `system' The system command to open files, like `open' on Windows
2219 and Mac OS X, and mailcap under GNU/Linux. This is the command
2220 that will be selected if you call \\[org-open-at-point] with a double
2221 \\[universal-argument] \\[universal-argument] prefix.
2222 t Default for files not matched by any of the other options.
2224 Possible values for the command are:
2225 `emacs' The file will be visited by the current Emacs process.
2226 `default' Use the default application for this file type, which is the
2227 association for t in the list, most likely in the system-specific
2228 part. This can be used to overrule an unwanted setting in the
2229 system-specific variable.
2230 `system' Use the system command for opening files, like \"open\".
2231 This command is specified by the entry whose car is `system'.
2232 Most likely, the system-specific version of this variable
2233 does define this command, but you can overrule/replace it
2234 here.
2235 `mailcap' Use command specified in the mailcaps.
2236 string A command to be executed by a shell; %s will be replaced
2237 by the path to the file.
2239 function A Lisp function, which will be called with two arguments:
2240 the file path and the original link string, without the
2241 \"file:\" prefix.
2243 For more examples, see the system specific constants
2244 `org-file-apps-defaults-macosx'
2245 `org-file-apps-defaults-windowsnt'
2246 `org-file-apps-defaults-gnu'."
2247 :group 'org-link-follow
2248 :type '(repeat
2249 (cons (choice :value ""
2250 (string :tag "Extension")
2251 (const :tag "System command to open files" system)
2252 (const :tag "Default for unrecognized files" t)
2253 (const :tag "Remote file" remote)
2254 (const :tag "Links to a directory" directory)
2255 (const :tag "Any files that have Emacs modes"
2256 auto-mode))
2257 (choice :value ""
2258 (const :tag "Visit with Emacs" emacs)
2259 (const :tag "Use default" default)
2260 (const :tag "Use the system command" system)
2261 (string :tag "Command")
2262 (function :tag "Function")))))
2264 (defcustom org-doi-server-url "http://dx.doi.org/"
2265 "The URL of the DOI server."
2266 :type 'string
2267 :version "24.3"
2268 :group 'org-link-follow)
2270 (defgroup org-refile nil
2271 "Options concerning refiling entries in Org-mode."
2272 :tag "Org Refile"
2273 :group 'org)
2275 (defcustom org-directory "~/org"
2276 "Directory with Org files.
2277 This is just a default location to look for Org files. There is no need
2278 at all to put your files into this directory. It is used in the
2279 following situations:
2281 1. When a capture template specifies a target file that is not an
2282 absolute path. The path will then be interpreted relative to
2283 `org-directory'
2284 2. When the value of variable `org-agenda-files' is a single file, any
2285 relative paths in this file will be taken as relative to
2286 `org-directory'."
2287 :group 'org-refile
2288 :group 'org-capture
2289 :type 'directory)
2291 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2292 "Default target for storing notes.
2293 Used as a fall back file for org-capture.el, for templates that
2294 do not specify a target file."
2295 :group 'org-refile
2296 :group 'org-capture
2297 :type 'file)
2299 (defcustom org-goto-interface 'outline
2300 "The default interface to be used for `org-goto'.
2301 Allowed values are:
2302 outline The interface shows an outline of the relevant file
2303 and the correct heading is found by moving through
2304 the outline or by searching with incremental search.
2305 outline-path-completion Headlines in the current buffer are offered via
2306 completion. This is the interface also used by
2307 the refile command."
2308 :group 'org-refile
2309 :type '(choice
2310 (const :tag "Outline" outline)
2311 (const :tag "Outline-path-completion" outline-path-completion)))
2313 (defcustom org-goto-max-level 5
2314 "Maximum target level when running `org-goto' with refile interface."
2315 :group 'org-refile
2316 :type 'integer)
2318 (defcustom org-reverse-note-order nil
2319 "Non-nil means store new notes at the beginning of a file or entry.
2320 When nil, new notes will be filed to the end of a file or entry.
2321 This can also be a list with cons cells of regular expressions that
2322 are matched against file names, and values."
2323 :group 'org-capture
2324 :group 'org-refile
2325 :type '(choice
2326 (const :tag "Reverse always" t)
2327 (const :tag "Reverse never" nil)
2328 (repeat :tag "By file name regexp"
2329 (cons regexp boolean))))
2331 (defcustom org-log-refile nil
2332 "Information to record when a task is refiled.
2334 Possible values are:
2336 nil Don't add anything
2337 time Add a time stamp to the task
2338 note Prompt for a note and add it with template `org-log-note-headings'
2340 This option can also be set with on a per-file-basis with
2342 #+STARTUP: nologrefile
2343 #+STARTUP: logrefile
2344 #+STARTUP: lognoterefile
2346 You can have local logging settings for a subtree by setting the LOGGING
2347 property to one or more of these keywords.
2349 When bulk-refiling from the agenda, the value `note' is forbidden and
2350 will temporarily be changed to `time'."
2351 :group 'org-refile
2352 :group 'org-progress
2353 :version "24.1"
2354 :type '(choice
2355 (const :tag "No logging" nil)
2356 (const :tag "Record timestamp" time)
2357 (const :tag "Record timestamp with note." note)))
2359 (defcustom org-refile-targets nil
2360 "Targets for refiling entries with \\[org-refile].
2361 This is a list of cons cells. Each cell contains:
2362 - a specification of the files to be considered, either a list of files,
2363 or a symbol whose function or variable value will be used to retrieve
2364 a file name or a list of file names. If you use `org-agenda-files' for
2365 that, all agenda files will be scanned for targets. Nil means consider
2366 headings in the current buffer.
2367 - A specification of how to find candidate refile targets. This may be
2368 any of:
2369 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2370 This tag has to be present in all target headlines, inheritance will
2371 not be considered.
2372 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2373 todo keyword.
2374 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2375 headlines that are refiling targets.
2376 - a cons cell (:level . N). Any headline of level N is considered a target.
2377 Note that, when `org-odd-levels-only' is set, level corresponds to
2378 order in hierarchy, not to the number of stars.
2379 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2380 Note that, when `org-odd-levels-only' is set, level corresponds to
2381 order in hierarchy, not to the number of stars.
2383 Each element of this list generates a set of possible targets.
2384 The union of these sets is presented (with completion) to
2385 the user by `org-refile'.
2387 You can set the variable `org-refile-target-verify-function' to a function
2388 to verify each headline found by the simple criteria above.
2390 When this variable is nil, all top-level headlines in the current buffer
2391 are used, equivalent to the value `((nil . (:level . 1))'."
2392 :group 'org-refile
2393 :type '(repeat
2394 (cons
2395 (choice :value org-agenda-files
2396 (const :tag "All agenda files" org-agenda-files)
2397 (const :tag "Current buffer" nil)
2398 (function) (variable) (file))
2399 (choice :tag "Identify target headline by"
2400 (cons :tag "Specific tag" (const :value :tag) (string))
2401 (cons :tag "TODO keyword" (const :value :todo) (string))
2402 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2403 (cons :tag "Level number" (const :value :level) (integer))
2404 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2406 (defcustom org-refile-target-verify-function nil
2407 "Function to verify if the headline at point should be a refile target.
2408 The function will be called without arguments, with point at the
2409 beginning of the headline. It should return t and leave point
2410 where it is if the headline is a valid target for refiling.
2412 If the target should not be selected, the function must return nil.
2413 In addition to this, it may move point to a place from where the search
2414 should be continued. For example, the function may decide that the entire
2415 subtree of the current entry should be excluded and move point to the end
2416 of the subtree."
2417 :group 'org-refile
2418 :type '(choice
2419 (const nil)
2420 (function)))
2422 (defcustom org-refile-use-cache nil
2423 "Non-nil means cache refile targets to speed up the process.
2424 \\<org-mode-map>\
2425 The cache for a particular file will be updated automatically when
2426 the buffer has been killed, or when any of the marker used for flagging
2427 refile targets no longer points at a live buffer.
2428 If you have added new entries to a buffer that might themselves be targets,
2429 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2430 if you find that easier, \
2431 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2432 \\[org-refile]'."
2433 :group 'org-refile
2434 :version "24.1"
2435 :type 'boolean)
2437 (defcustom org-refile-use-outline-path nil
2438 "Non-nil means provide refile targets as paths.
2439 So a level 3 headline will be available as level1/level2/level3.
2441 When the value is `file', also include the file name (without directory)
2442 into the path. In this case, you can also stop the completion after
2443 the file name, to get entries inserted as top level in the file.
2445 When `full-file-path', include the full file path."
2446 :group 'org-refile
2447 :type '(choice
2448 (const :tag "Not" nil)
2449 (const :tag "Yes" t)
2450 (const :tag "Start with file name" file)
2451 (const :tag "Start with full file path" full-file-path)))
2453 (defcustom org-outline-path-complete-in-steps t
2454 "Non-nil means complete the outline path in hierarchical steps.
2455 When Org-mode uses the refile interface to select an outline path
2456 \(see variable `org-refile-use-outline-path'), the completion of
2457 the path can be done in a single go, or it can be done in steps down
2458 the headline hierarchy. Going in steps is probably the best if you
2459 do not use a special completion package like `ido' or `icicles'.
2460 However, when using these packages, going in one step can be very
2461 fast, while still showing the whole path to the entry."
2462 :group 'org-refile
2463 :type 'boolean)
2465 (defcustom org-refile-allow-creating-parent-nodes nil
2466 "Non-nil means allow the creation of new nodes as refile targets.
2467 New nodes are then created by adding \"/new node name\" to the completion
2468 of an existing node. When the value of this variable is `confirm',
2469 new node creation must be confirmed by the user (recommended).
2470 When nil, the completion must match an existing entry.
2472 Note that, if the new heading is not seen by the criteria
2473 listed in `org-refile-targets', multiple instances of the same
2474 heading would be created by trying again to file under the new
2475 heading."
2476 :group 'org-refile
2477 :type '(choice
2478 (const :tag "Never" nil)
2479 (const :tag "Always" t)
2480 (const :tag "Prompt for confirmation" confirm)))
2482 (defcustom org-refile-active-region-within-subtree nil
2483 "Non-nil means also refile active region within a subtree.
2485 By default `org-refile' doesn't allow refiling regions if they
2486 don't contain a set of subtrees, but it might be convenient to
2487 do so sometimes: in that case, the first line of the region is
2488 converted to a headline before refiling."
2489 :group 'org-refile
2490 :version "24.1"
2491 :type 'boolean)
2493 (defgroup org-todo nil
2494 "Options concerning TODO items in Org-mode."
2495 :tag "Org TODO"
2496 :group 'org)
2498 (defgroup org-progress nil
2499 "Options concerning Progress logging in Org-mode."
2500 :tag "Org Progress"
2501 :group 'org-time)
2503 (defvar org-todo-interpretation-widgets
2504 '((:tag "Sequence (cycling hits every state)" sequence)
2505 (:tag "Type (cycling directly to DONE)" type))
2506 "The available interpretation symbols for customizing `org-todo-keywords'.
2507 Interested libraries should add to this list.")
2509 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2510 "List of TODO entry keyword sequences and their interpretation.
2511 \\<org-mode-map>This is a list of sequences.
2513 Each sequence starts with a symbol, either `sequence' or `type',
2514 indicating if the keywords should be interpreted as a sequence of
2515 action steps, or as different types of TODO items. The first
2516 keywords are states requiring action - these states will select a headline
2517 for inclusion into the global TODO list Org-mode produces. If one of
2518 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2519 signify that no further action is necessary. If \"|\" is not found,
2520 the last keyword is treated as the only DONE state of the sequence.
2522 The command \\[org-todo] cycles an entry through these states, and one
2523 additional state where no keyword is present. For details about this
2524 cycling, see the manual.
2526 TODO keywords and interpretation can also be set on a per-file basis with
2527 the special #+SEQ_TODO and #+TYP_TODO lines.
2529 Each keyword can optionally specify a character for fast state selection
2530 \(in combination with the variable `org-use-fast-todo-selection')
2531 and specifiers for state change logging, using the same syntax that
2532 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2533 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2534 indicates to record a time stamp each time this state is selected.
2536 Each keyword may also specify if a timestamp or a note should be
2537 recorded when entering or leaving the state, by adding additional
2538 characters in the parenthesis after the keyword. This looks like this:
2539 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2540 record only the time of the state change. With X and Y being either
2541 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2542 Y when leaving the state if and only if the *target* state does not
2543 define X. You may omit any of the fast-selection key or X or /Y,
2544 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2546 For backward compatibility, this variable may also be just a list
2547 of keywords. In this case the interpretation (sequence or type) will be
2548 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2549 :group 'org-todo
2550 :group 'org-keywords
2551 :type '(choice
2552 (repeat :tag "Old syntax, just keywords"
2553 (string :tag "Keyword"))
2554 (repeat :tag "New syntax"
2555 (cons
2556 (choice
2557 :tag "Interpretation"
2558 ;;Quick and dirty way to see
2559 ;;`org-todo-interpretations'. This takes the
2560 ;;place of item arguments
2561 :convert-widget
2562 (lambda (widget)
2563 (widget-put widget
2564 :args (mapcar
2565 (lambda (x)
2566 (widget-convert
2567 (cons 'const x)))
2568 org-todo-interpretation-widgets))
2569 widget))
2570 (repeat
2571 (string :tag "Keyword"))))))
2573 (defvar-local org-todo-keywords-1 nil
2574 "All TODO and DONE keywords active in a buffer.")
2575 (defvar org-todo-keywords-for-agenda nil)
2576 (defvar org-done-keywords-for-agenda nil)
2577 (defvar org-todo-keyword-alist-for-agenda nil)
2578 (defvar org-tag-alist-for-agenda nil
2579 "Alist of all tags from all agenda files.")
2580 (defvar org-tag-groups-alist-for-agenda nil
2581 "Alist of all groups tags from all current agenda files.")
2582 (defvar-local org-tag-groups-alist nil)
2583 (defvar org-agenda-contributing-files nil)
2584 (defvar-local org-current-tag-alist nil
2585 "Alist of all tag groups in current buffer.
2586 This variable takes into consideration `org-tag-alist',
2587 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2588 (defvar-local org-not-done-keywords nil)
2589 (defvar-local org-done-keywords nil)
2590 (defvar-local org-todo-heads nil)
2591 (defvar-local org-todo-sets nil)
2592 (defvar-local org-todo-log-states nil)
2593 (defvar-local org-todo-kwd-alist nil)
2594 (defvar-local org-todo-key-alist nil)
2595 (defvar-local org-todo-key-trigger nil)
2597 (defcustom org-todo-interpretation 'sequence
2598 "Controls how TODO keywords are interpreted.
2599 This variable is in principle obsolete and is only used for
2600 backward compatibility, if the interpretation of todo keywords is
2601 not given already in `org-todo-keywords'. See that variable for
2602 more information."
2603 :group 'org-todo
2604 :group 'org-keywords
2605 :type '(choice (const sequence)
2606 (const type)))
2608 (defcustom org-use-fast-todo-selection t
2609 "\\<org-mode-map>\
2610 Non-nil means use the fast todo selection scheme with \\[org-todo].
2611 This variable describes if and under what circumstances the cycling
2612 mechanism for TODO keywords will be replaced by a single-key, direct
2613 selection scheme.
2615 When nil, fast selection is never used.
2617 When the symbol `prefix', it will be used when `org-todo' is called
2618 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2619 in an Org-mode buffer, and
2620 `\\[universal-argument] t' in an agenda buffer.
2622 When t, fast selection is used by default. In this case, the prefix
2623 argument forces cycling instead.
2625 In all cases, the special interface is only used if access keys have
2626 actually been assigned by the user, i.e. if keywords in the configuration
2627 are followed by a letter in parenthesis, like TODO(t)."
2628 :group 'org-todo
2629 :type '(choice
2630 (const :tag "Never" nil)
2631 (const :tag "By default" t)
2632 (const :tag "Only with C-u C-c C-t" prefix)))
2634 (defcustom org-provide-todo-statistics t
2635 "Non-nil means update todo statistics after insert and toggle.
2636 ALL-HEADLINES means update todo statistics by including headlines
2637 with no TODO keyword as well, counting them as not done.
2638 A list of TODO keywords means the same, but skip keywords that are
2639 not in this list.
2640 When set to a list of two lists, the first list contains keywords
2641 to consider as TODO keywords, the second list contains keywords
2642 to consider as DONE keywords.
2644 When this is set, todo statistics is updated in the parent of the
2645 current entry each time a todo state is changed."
2646 :group 'org-todo
2647 :type '(choice
2648 (const :tag "Yes, only for TODO entries" t)
2649 (const :tag "Yes, including all entries" all-headlines)
2650 (repeat :tag "Yes, for TODOs in this list"
2651 (string :tag "TODO keyword"))
2652 (list :tag "Yes, for TODOs and DONEs in these lists"
2653 (repeat (string :tag "TODO keyword"))
2654 (repeat (string :tag "DONE keyword")))
2655 (other :tag "No TODO statistics" nil)))
2657 (defcustom org-hierarchical-todo-statistics t
2658 "Non-nil means TODO statistics covers just direct children.
2659 When nil, all entries in the subtree are considered.
2660 This has only an effect if `org-provide-todo-statistics' is set.
2661 To set this to nil for only a single subtree, use a COOKIE_DATA
2662 property and include the word \"recursive\" into the value."
2663 :group 'org-todo
2664 :type 'boolean)
2666 (defcustom org-after-todo-state-change-hook nil
2667 "Hook which is run after the state of a TODO item was changed.
2668 The new state (a string with a TODO keyword, or nil) is available in the
2669 Lisp variable `org-state'."
2670 :group 'org-todo
2671 :type 'hook)
2673 (defvar org-blocker-hook nil
2674 "Hook for functions that are allowed to block a state change.
2676 Functions in this hook should not modify the buffer.
2677 Each function gets as its single argument a property list,
2678 see `org-trigger-hook' for more information about this list.
2680 If any of the functions in this hook returns nil, the state change
2681 is blocked.")
2683 (defvar org-trigger-hook nil
2684 "Hook for functions that are triggered by a state change.
2686 Each function gets as its single argument a property list with at
2687 least the following elements:
2689 (:type type-of-change :position pos-at-entry-start
2690 :from old-state :to new-state)
2692 Depending on the type, more properties may be present.
2694 This mechanism is currently implemented for:
2696 TODO state changes
2697 ------------------
2698 :type todo-state-change
2699 :from previous state (keyword as a string), or nil, or a symbol
2700 `todo' or `done', to indicate the general type of state.
2701 :to new state, like in :from")
2703 (defcustom org-enforce-todo-dependencies nil
2704 "Non-nil means undone TODO entries will block switching the parent to DONE.
2705 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2706 be blocked if any prior sibling is not yet done.
2707 Finally, if the parent is blocked because of ordered siblings of its own,
2708 the child will also be blocked."
2709 :set (lambda (var val)
2710 (set var val)
2711 (if val
2712 (add-hook 'org-blocker-hook
2713 'org-block-todo-from-children-or-siblings-or-parent)
2714 (remove-hook 'org-blocker-hook
2715 'org-block-todo-from-children-or-siblings-or-parent)))
2716 :group 'org-todo
2717 :type 'boolean)
2719 (defcustom org-enforce-todo-checkbox-dependencies nil
2720 "Non-nil means unchecked boxes will block switching the parent to DONE.
2721 When this is nil, checkboxes have no influence on switching TODO states.
2722 When non-nil, you first need to check off all check boxes before the TODO
2723 entry can be switched to DONE.
2724 This variable needs to be set before org.el is loaded, and you need to
2725 restart Emacs after a change to make the change effective. The only way
2726 to change is while Emacs is running is through the customize interface."
2727 :set (lambda (var val)
2728 (set var val)
2729 (if val
2730 (add-hook 'org-blocker-hook
2731 'org-block-todo-from-checkboxes)
2732 (remove-hook 'org-blocker-hook
2733 'org-block-todo-from-checkboxes)))
2734 :group 'org-todo
2735 :type 'boolean)
2737 (defcustom org-treat-insert-todo-heading-as-state-change nil
2738 "Non-nil means inserting a TODO heading is treated as state change.
2739 So when the command \\[org-insert-todo-heading] is used, state change
2740 logging will apply if appropriate. When nil, the new TODO item will
2741 be inserted directly, and no logging will take place."
2742 :group 'org-todo
2743 :type 'boolean)
2745 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2746 "Non-nil means switching TODO states with S-cursor counts as state change.
2747 This is the default behavior. However, setting this to nil allows a
2748 convenient way to select a TODO state and bypass any logging associated
2749 with that."
2750 :group 'org-todo
2751 :type 'boolean)
2753 (defcustom org-todo-state-tags-triggers nil
2754 "Tag changes that should be triggered by TODO state changes.
2755 This is a list. Each entry is
2757 (state-change (tag . flag) .......)
2759 State-change can be a string with a state, and empty string to indicate the
2760 state that has no TODO keyword, or it can be one of the symbols `todo'
2761 or `done', meaning any not-done or done state, respectively."
2762 :group 'org-todo
2763 :group 'org-tags
2764 :type '(repeat
2765 (cons (choice :tag "When changing to"
2766 (const :tag "Not-done state" todo)
2767 (const :tag "Done state" done)
2768 (string :tag "State"))
2769 (repeat
2770 (cons :tag "Tag action"
2771 (string :tag "Tag")
2772 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2774 (defcustom org-log-done nil
2775 "Information to record when a task moves to the DONE state.
2777 Possible values are:
2779 nil Don't add anything, just change the keyword
2780 time Add a time stamp to the task
2781 note Prompt for a note and add it with template `org-log-note-headings'
2783 This option can also be set with on a per-file-basis with
2785 #+STARTUP: nologdone
2786 #+STARTUP: logdone
2787 #+STARTUP: lognotedone
2789 You can have local logging settings for a subtree by setting the LOGGING
2790 property to one or more of these keywords."
2791 :group 'org-todo
2792 :group 'org-progress
2793 :type '(choice
2794 (const :tag "No logging" nil)
2795 (const :tag "Record CLOSED timestamp" time)
2796 (const :tag "Record CLOSED timestamp with note." note)))
2798 ;; Normalize old uses of org-log-done.
2799 (cond
2800 ((eq org-log-done t) (setq org-log-done 'time))
2801 ((and (listp org-log-done) (memq 'done org-log-done))
2802 (setq org-log-done 'note)))
2804 (defcustom org-log-reschedule nil
2805 "Information to record when the scheduling date of a tasks is modified.
2807 Possible values are:
2809 nil Don't add anything, just change the date
2810 time Add a time stamp to the task
2811 note Prompt for a note and add it with template `org-log-note-headings'
2813 This option can also be set with on a per-file-basis with
2815 #+STARTUP: nologreschedule
2816 #+STARTUP: logreschedule
2817 #+STARTUP: lognotereschedule"
2818 :group 'org-todo
2819 :group 'org-progress
2820 :type '(choice
2821 (const :tag "No logging" nil)
2822 (const :tag "Record timestamp" time)
2823 (const :tag "Record timestamp with note." note)))
2825 (defcustom org-log-redeadline nil
2826 "Information to record when the deadline date of a tasks is modified.
2828 Possible values are:
2830 nil Don't add anything, just change the date
2831 time Add a time stamp to the task
2832 note Prompt for a note and add it with template `org-log-note-headings'
2834 This option can also be set with on a per-file-basis with
2836 #+STARTUP: nologredeadline
2837 #+STARTUP: logredeadline
2838 #+STARTUP: lognoteredeadline
2840 You can have local logging settings for a subtree by setting the LOGGING
2841 property to one or more of these keywords."
2842 :group 'org-todo
2843 :group 'org-progress
2844 :type '(choice
2845 (const :tag "No logging" nil)
2846 (const :tag "Record timestamp" time)
2847 (const :tag "Record timestamp with note." note)))
2849 (defcustom org-log-note-clock-out nil
2850 "Non-nil means record a note when clocking out of an item.
2851 This can also be configured on a per-file basis by adding one of
2852 the following lines anywhere in the buffer:
2854 #+STARTUP: lognoteclock-out
2855 #+STARTUP: nolognoteclock-out"
2856 :group 'org-todo
2857 :group 'org-progress
2858 :type 'boolean)
2860 (defcustom org-log-done-with-time t
2861 "Non-nil means the CLOSED time stamp will contain date and time.
2862 When nil, only the date will be recorded."
2863 :group 'org-progress
2864 :type 'boolean)
2866 (defcustom org-log-note-headings
2867 '((done . "CLOSING NOTE %t")
2868 (state . "State %-12s from %-12S %t")
2869 (note . "Note taken on %t")
2870 (reschedule . "Rescheduled from %S on %t")
2871 (delschedule . "Not scheduled, was %S on %t")
2872 (redeadline . "New deadline from %S on %t")
2873 (deldeadline . "Removed deadline, was %S on %t")
2874 (refile . "Refiled on %t")
2875 (clock-out . ""))
2876 "Headings for notes added to entries.
2878 The value is an alist, with the car being a symbol indicating the
2879 note context, and the cdr is the heading to be used. The heading
2880 may also be the empty string. The following placeholders can be
2881 used:
2883 %t a time stamp.
2884 %T an active time stamp instead the default inactive one
2885 %d a short-format time stamp.
2886 %D an active short-format time stamp.
2887 %s the new TODO state or time stamp (inactive), in double quotes.
2888 %S the old TODO state or time stamp (inactive), in double quotes.
2889 %u the user name.
2890 %U full user name.
2892 In fact, it is not a good idea to change the `state' entry,
2893 because Agenda Log mode depends on the format of these entries."
2894 :group 'org-todo
2895 :group 'org-progress
2896 :type '(list :greedy t
2897 (cons (const :tag "Heading when closing an item" done) string)
2898 (cons (const :tag
2899 "Heading when changing todo state (todo sequence only)"
2900 state) string)
2901 (cons (const :tag "Heading when just taking a note" note) string)
2902 (cons (const :tag "Heading when rescheduling" reschedule) string)
2903 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2904 (cons (const :tag "Heading when changing deadline" redeadline) string)
2905 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2906 (cons (const :tag "Heading when refiling" refile) string)
2907 (cons (const :tag "Heading when clocking out" clock-out) string)))
2909 (unless (assq 'note org-log-note-headings)
2910 (push '(note . "%t") org-log-note-headings))
2912 (defcustom org-log-into-drawer nil
2913 "Non-nil means insert state change notes and time stamps into a drawer.
2914 When nil, state changes notes will be inserted after the headline and
2915 any scheduling and clock lines, but not inside a drawer.
2917 The value of this variable should be the name of the drawer to use.
2918 LOGBOOK is proposed as the default drawer for this purpose, you can
2919 also set this to a string to define the drawer of your choice.
2921 A value of t is also allowed, representing \"LOGBOOK\".
2923 A value of t or nil can also be set with on a per-file-basis with
2925 #+STARTUP: logdrawer
2926 #+STARTUP: nologdrawer
2928 If this variable is set, `org-log-state-notes-insert-after-drawers'
2929 will be ignored.
2931 You can set the property LOG_INTO_DRAWER to overrule this setting for
2932 a subtree.
2934 Do not check directly this variable in a Lisp program. Call
2935 function `org-log-into-drawer' instead."
2936 :group 'org-todo
2937 :group 'org-progress
2938 :type '(choice
2939 (const :tag "Not into a drawer" nil)
2940 (const :tag "LOGBOOK" t)
2941 (string :tag "Other")))
2943 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2945 (defun org-log-into-drawer ()
2946 "Name of the log drawer, as a string, or nil.
2947 This is the value of `org-log-into-drawer'. However, if the
2948 current entry has or inherits a LOG_INTO_DRAWER property, it will
2949 be used instead of the default value."
2950 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2951 (cond ((equal p "nil") nil)
2952 ((equal p "t") "LOGBOOK")
2953 ((stringp p) p)
2954 (p "LOGBOOK")
2955 ((stringp org-log-into-drawer) org-log-into-drawer)
2956 (org-log-into-drawer "LOGBOOK"))))
2958 (defcustom org-log-state-notes-insert-after-drawers nil
2959 "Non-nil means insert state change notes after any drawers in entry.
2960 Only the drawers that *immediately* follow the headline and the
2961 deadline/scheduled line are skipped.
2962 When nil, insert notes right after the heading and perhaps the line
2963 with deadline/scheduling if present.
2965 This variable will have no effect if `org-log-into-drawer' is
2966 set."
2967 :group 'org-todo
2968 :group 'org-progress
2969 :type 'boolean)
2971 (defcustom org-log-states-order-reversed t
2972 "Non-nil means the latest state note will be directly after heading.
2973 When nil, the state change notes will be ordered according to time.
2975 This option can also be set with on a per-file-basis with
2977 #+STARTUP: logstatesreversed
2978 #+STARTUP: nologstatesreversed"
2979 :group 'org-todo
2980 :group 'org-progress
2981 :type 'boolean)
2983 (defcustom org-todo-repeat-to-state nil
2984 "The TODO state to which a repeater should return the repeating task.
2985 By default this is the first task in a TODO sequence, or the previous state
2986 in a TODO_TYP set. But you can specify another task here.
2987 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2988 :group 'org-todo
2989 :version "24.1"
2990 :type '(choice (const :tag "Head of sequence" nil)
2991 (string :tag "Specific state")))
2993 (defcustom org-log-repeat 'time
2994 "Non-nil means record moving through the DONE state when triggering repeat.
2995 An auto-repeating task is immediately switched back to TODO when
2996 marked DONE. If you are not logging state changes (by adding \"@\"
2997 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2998 record a closing note, there will be no record of the task moving
2999 through DONE. This variable forces taking a note anyway.
3001 nil Don't force a record
3002 time Record a time stamp
3003 note Prompt for a note and add it with template `org-log-note-headings'
3005 This option can also be set with on a per-file-basis with
3007 #+STARTUP: nologrepeat
3008 #+STARTUP: logrepeat
3009 #+STARTUP: lognoterepeat
3011 You can have local logging settings for a subtree by setting the LOGGING
3012 property to one or more of these keywords."
3013 :group 'org-todo
3014 :group 'org-progress
3015 :type '(choice
3016 (const :tag "Don't force a record" nil)
3017 (const :tag "Force recording the DONE state" time)
3018 (const :tag "Force recording a note with the DONE state" note)))
3021 (defgroup org-priorities nil
3022 "Priorities in Org-mode."
3023 :tag "Org Priorities"
3024 :group 'org-todo)
3026 (defcustom org-enable-priority-commands t
3027 "Non-nil means priority commands are active.
3028 When nil, these commands will be disabled, so that you never accidentally
3029 set a priority."
3030 :group 'org-priorities
3031 :type 'boolean)
3033 (defcustom org-highest-priority ?A
3034 "The highest priority of TODO items. A character like ?A, ?B etc.
3035 Must have a smaller ASCII number than `org-lowest-priority'."
3036 :group 'org-priorities
3037 :type 'character)
3039 (defcustom org-lowest-priority ?C
3040 "The lowest priority of TODO items. A character like ?A, ?B etc.
3041 Must have a larger ASCII number than `org-highest-priority'."
3042 :group 'org-priorities
3043 :type 'character)
3045 (defcustom org-default-priority ?B
3046 "The default priority of TODO items.
3047 This is the priority an item gets if no explicit priority is given.
3048 When starting to cycle on an empty priority the first step in the cycle
3049 depends on `org-priority-start-cycle-with-default'. The resulting first
3050 step priority must not exceed the range from `org-highest-priority' to
3051 `org-lowest-priority' which means that `org-default-priority' has to be
3052 in this range exclusive or inclusive the range boundaries. Else the
3053 first step refuses to set the default and the second will fall back
3054 to (depending on the command used) the highest or lowest priority."
3055 :group 'org-priorities
3056 :type 'character)
3058 (defcustom org-priority-start-cycle-with-default t
3059 "Non-nil means start with default priority when starting to cycle.
3060 When this is nil, the first step in the cycle will be (depending on the
3061 command used) one higher or lower than the default priority.
3062 See also `org-default-priority'."
3063 :group 'org-priorities
3064 :type 'boolean)
3066 (defcustom org-get-priority-function nil
3067 "Function to extract the priority from a string.
3068 The string is normally the headline. If this is nil Org computes the
3069 priority from the priority cookie like [#A] in the headline. It returns
3070 an integer, increasing by 1000 for each priority level.
3071 The user can set a different function here, which should take a string
3072 as an argument and return the numeric priority."
3073 :group 'org-priorities
3074 :version "24.1"
3075 :type '(choice
3076 (const nil)
3077 (function)))
3079 (defgroup org-time nil
3080 "Options concerning time stamps and deadlines in Org-mode."
3081 :tag "Org Time"
3082 :group 'org)
3084 (defcustom org-time-stamp-rounding-minutes '(0 5)
3085 "Number of minutes to round time stamps to.
3086 \\<org-mode-map>\
3087 These are two values, the first applies when first creating a time stamp.
3088 The second applies when changing it with the commands `S-up' and `S-down'.
3089 When changing the time stamp, this means that it will change in steps
3090 of N minutes, as given by the second value.
3092 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3093 numbers should be factors of 60, so for example 5, 10, 15.
3095 When this is larger than 1, you can still force an exact time stamp by using
3096 a double prefix argument to a time stamp command like \
3097 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3098 and by using a prefix arg to `S-up/down' to specify the exact number
3099 of minutes to shift."
3100 :group 'org-time
3101 :get (lambda (var) ; Make sure both elements are there
3102 (if (integerp (default-value var))
3103 (list (default-value var) 5)
3104 (default-value var)))
3105 :type '(list
3106 (integer :tag "when inserting times")
3107 (integer :tag "when modifying times")))
3109 ;; Normalize old customizations of this variable.
3110 (when (integerp org-time-stamp-rounding-minutes)
3111 (setq org-time-stamp-rounding-minutes
3112 (list org-time-stamp-rounding-minutes
3113 org-time-stamp-rounding-minutes)))
3115 (defcustom org-display-custom-times nil
3116 "Non-nil means overlay custom formats over all time stamps.
3117 The formats are defined through the variable `org-time-stamp-custom-formats'.
3118 To turn this on on a per-file basis, insert anywhere in the file:
3119 #+STARTUP: customtime"
3120 :group 'org-time
3121 :set 'set-default
3122 :type 'sexp)
3123 (make-variable-buffer-local 'org-display-custom-times)
3125 (defcustom org-time-stamp-custom-formats
3126 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3127 "Custom formats for time stamps. See `format-time-string' for the syntax.
3128 These are overlaid over the default ISO format if the variable
3129 `org-display-custom-times' is set. Time like %H:%M should be at the
3130 end of the second format. The custom formats are also honored by export
3131 commands, if custom time display is turned on at the time of export."
3132 :group 'org-time
3133 :type 'sexp)
3135 (defun org-time-stamp-format (&optional long inactive)
3136 "Get the right format for a time string."
3137 (let ((f (if long (cdr org-time-stamp-formats)
3138 (car org-time-stamp-formats))))
3139 (if inactive
3140 (concat "[" (substring f 1 -1) "]")
3141 f)))
3143 (defcustom org-time-clocksum-format
3144 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3145 "The format string used when creating CLOCKSUM lines.
3146 This is also used when Org mode generates a time duration.
3148 The value can be a single format string containing two
3149 %-sequences, which will be filled with the number of hours and
3150 minutes in that order.
3152 Alternatively, the value can be a plist associating any of the
3153 keys :years, :months, :weeks, :days, :hours or :minutes with
3154 format strings. The time duration is formatted using only the
3155 time components that are needed and concatenating the results.
3156 If a time unit in absent, it falls back to the next smallest
3157 unit.
3159 The keys :require-years, :require-months, :require-days,
3160 :require-weeks, :require-hours, :require-minutes are also
3161 meaningful. A non-nil value for these keys indicates that the
3162 corresponding time component should always be included, even if
3163 its value is 0.
3166 For example,
3168 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3169 :require-minutes t)
3171 means durations longer than a day will be expressed in days,
3172 hours and minutes, and durations less than a day will always be
3173 expressed in hours and minutes (even for durations less than an
3174 hour).
3176 The value
3178 (:days \"%dd\" :minutes \"%dm\")
3180 means durations longer than a day will be expressed in days and
3181 minutes, and durations less than a day will be expressed entirely
3182 in minutes (even for durations longer than an hour)."
3183 :group 'org-time
3184 :group 'org-clock
3185 :version "24.4"
3186 :package-version '(Org . "8.0")
3187 :type '(choice (string :tag "Format string")
3188 (set :tag "Plist"
3189 (group :inline t (const :tag "Years" :years)
3190 (string :tag "Format string"))
3191 (group :inline t
3192 (const :tag "Always show years" :require-years)
3193 (const t))
3194 (group :inline t (const :tag "Months" :months)
3195 (string :tag "Format string"))
3196 (group :inline t
3197 (const :tag "Always show months" :require-months)
3198 (const t))
3199 (group :inline t (const :tag "Weeks" :weeks)
3200 (string :tag "Format string"))
3201 (group :inline t
3202 (const :tag "Always show weeks" :require-weeks)
3203 (const t))
3204 (group :inline t (const :tag "Days" :days)
3205 (string :tag "Format string"))
3206 (group :inline t
3207 (const :tag "Always show days" :require-days)
3208 (const t))
3209 (group :inline t (const :tag "Hours" :hours)
3210 (string :tag "Format string"))
3211 (group :inline t
3212 (const :tag "Always show hours" :require-hours)
3213 (const t))
3214 (group :inline t (const :tag "Minutes" :minutes)
3215 (string :tag "Format string"))
3216 (group :inline t
3217 (const :tag "Always show minutes" :require-minutes)
3218 (const t)))))
3220 (defcustom org-time-clocksum-use-fractional nil
3221 "When non-nil, \\[org-clock-display] uses fractional times.
3222 See `org-time-clocksum-format' for more on time clock formats."
3223 :group 'org-time
3224 :group 'org-clock
3225 :version "24.3"
3226 :type 'boolean)
3228 (defcustom org-time-clocksum-use-effort-durations nil
3229 "When non-nil, \\[org-clock-display] uses effort durations.
3230 E.g. by default, one day is considered to be a 8 hours effort,
3231 so a task that has been clocked for 16 hours will be displayed
3232 as during 2 days in the clock display or in the clocktable.
3234 See `org-effort-durations' on how to set effort durations
3235 and `org-time-clocksum-format' for more on time clock formats."
3236 :group 'org-time
3237 :group 'org-clock
3238 :version "24.4"
3239 :package-version '(Org . "8.0")
3240 :type 'boolean)
3242 (defcustom org-time-clocksum-fractional-format "%.2f"
3243 "The format string used when creating CLOCKSUM lines,
3244 or when Org mode generates a time duration, if
3245 `org-time-clocksum-use-fractional' is enabled.
3247 The value can be a single format string containing one
3248 %-sequence, which will be filled with the number of hours as
3249 a float.
3251 Alternatively, the value can be a plist associating any of the
3252 keys :years, :months, :weeks, :days, :hours or :minutes with
3253 a format string. The time duration is formatted using the
3254 largest time unit which gives a non-zero integer part. If all
3255 specified formats have zero integer part, the smallest time unit
3256 is used."
3257 :group 'org-time
3258 :type '(choice (string :tag "Format string")
3259 (set (group :inline t (const :tag "Years" :years)
3260 (string :tag "Format string"))
3261 (group :inline t (const :tag "Months" :months)
3262 (string :tag "Format string"))
3263 (group :inline t (const :tag "Weeks" :weeks)
3264 (string :tag "Format string"))
3265 (group :inline t (const :tag "Days" :days)
3266 (string :tag "Format string"))
3267 (group :inline t (const :tag "Hours" :hours)
3268 (string :tag "Format string"))
3269 (group :inline t (const :tag "Minutes" :minutes)
3270 (string :tag "Format string")))))
3272 (defcustom org-deadline-warning-days 14
3273 "Number of days before expiration during which a deadline becomes active.
3274 This variable governs the display in sparse trees and in the agenda.
3275 When 0 or negative, it means use this number (the absolute value of it)
3276 even if a deadline has a different individual lead time specified.
3278 Custom commands can set this variable in the options section."
3279 :group 'org-time
3280 :group 'org-agenda-daily/weekly
3281 :type 'integer)
3283 (defcustom org-scheduled-delay-days 0
3284 "Number of days before a scheduled item becomes active.
3285 This variable governs the display in sparse trees and in the agenda.
3286 The default value (i.e. 0) means: don't delay scheduled item.
3287 When negative, it means use this number (the absolute value of it)
3288 even if a scheduled item has a different individual delay time
3289 specified.
3291 Custom commands can set this variable in the options section."
3292 :group 'org-time
3293 :group 'org-agenda-daily/weekly
3294 :version "24.4"
3295 :package-version '(Org . "8.0")
3296 :type 'integer)
3298 (defcustom org-read-date-prefer-future t
3299 "Non-nil means assume future for incomplete date input from user.
3300 This affects the following situations:
3301 1. The user gives a month but not a year.
3302 For example, if it is April and you enter \"feb 2\", this will be read
3303 as Feb 2, *next* year. \"May 5\", however, will be this year.
3304 2. The user gives a day, but no month.
3305 For example, if today is the 15th, and you enter \"3\", Org-mode will
3306 read this as the third of *next* month. However, if you enter \"17\",
3307 it will be considered as *this* month.
3309 If you set this variable to the symbol `time', then also the following
3310 will work:
3312 3. If the user gives a time.
3313 If the time is before now, it will be interpreted as tomorrow.
3315 Currently none of this works for ISO week specifications.
3317 When this option is nil, the current day, month and year will always be
3318 used as defaults.
3320 See also `org-agenda-jump-prefer-future'."
3321 :group 'org-time
3322 :type '(choice
3323 (const :tag "Never" nil)
3324 (const :tag "Check month and day" t)
3325 (const :tag "Check month, day, and time" time)))
3327 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3328 "Should the agenda jump command prefer the future for incomplete dates?
3329 The default is to do the same as configured in `org-read-date-prefer-future'.
3330 But you can also set a deviating value here.
3331 This may t or nil, or the symbol `org-read-date-prefer-future'."
3332 :group 'org-agenda
3333 :group 'org-time
3334 :version "24.1"
3335 :type '(choice
3336 (const :tag "Use org-read-date-prefer-future"
3337 org-read-date-prefer-future)
3338 (const :tag "Never" nil)
3339 (const :tag "Always" t)))
3341 (defcustom org-read-date-force-compatible-dates t
3342 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3344 Depending on the system Emacs is running on, certain dates cannot
3345 be represented with the type used internally to represent time.
3346 Dates between 1970-1-1 and 2038-1-1 can always be represented
3347 correctly. Some systems allow for earlier dates, some for later,
3348 some for both. One way to find out it to insert any date into an
3349 Org buffer, putting the cursor on the year and hitting S-up and
3350 S-down to test the range.
3352 When this variable is set to t, the date/time prompt will not let
3353 you specify dates outside the 1970-2037 range, so it is certain that
3354 these dates will work in whatever version of Emacs you are
3355 running, and also that you can move a file from one Emacs implementation
3356 to another. WHenever Org is forcing the year for you, it will display
3357 a message and beep.
3359 When this variable is nil, Org will check if the date is
3360 representable in the specific Emacs implementation you are using.
3361 If not, it will force a year, usually the current year, and beep
3362 to remind you. Currently this setting is not recommended because
3363 the likelihood that you will open your Org files in an Emacs that
3364 has limited date range is not negligible.
3366 A workaround for this problem is to use diary sexp dates for time
3367 stamps outside of this range."
3368 :group 'org-time
3369 :version "24.1"
3370 :type 'boolean)
3372 (defcustom org-read-date-display-live t
3373 "Non-nil means display current interpretation of date prompt live.
3374 This display will be in an overlay, in the minibuffer."
3375 :group 'org-time
3376 :type 'boolean)
3378 (defcustom org-read-date-popup-calendar t
3379 "Non-nil means pop up a calendar when prompting for a date.
3380 In the calendar, the date can be selected with mouse-1. However, the
3381 minibuffer will also be active, and you can simply enter the date as well.
3382 When nil, only the minibuffer will be available."
3383 :group 'org-time
3384 :type 'boolean)
3385 (org-defvaralias 'org-popup-calendar-for-date-prompt
3386 'org-read-date-popup-calendar)
3388 (make-obsolete-variable
3389 'org-read-date-minibuffer-setup-hook
3390 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3391 (defcustom org-read-date-minibuffer-setup-hook nil
3392 "Hook to be used to set up keys for the date/time interface.
3393 Add key definitions to `minibuffer-local-map', which will be a
3394 temporary copy.
3396 WARNING: This option is obsolete, you should use
3397 `org-read-date-minibuffer-local-map' to set up keys."
3398 :group 'org-time
3399 :type 'hook)
3401 (defcustom org-extend-today-until 0
3402 "The hour when your day really ends. Must be an integer.
3403 This has influence for the following applications:
3404 - When switching the agenda to \"today\". It it is still earlier than
3405 the time given here, the day recognized as TODAY is actually yesterday.
3406 - When a date is read from the user and it is still before the time given
3407 here, the current date and time will be assumed to be yesterday, 23:59.
3408 Also, timestamps inserted in capture templates follow this rule.
3410 IMPORTANT: This is a feature whose implementation is and likely will
3411 remain incomplete. Really, it is only here because past midnight seems to
3412 be the favorite working time of John Wiegley :-)"
3413 :group 'org-time
3414 :type 'integer)
3416 (defcustom org-use-effective-time nil
3417 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3418 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3419 \"effective time\" of any timestamps between midnight and 8am will be
3420 23:59 of the previous day."
3421 :group 'org-time
3422 :version "24.1"
3423 :type 'boolean)
3425 (defcustom org-use-last-clock-out-time-as-effective-time nil
3426 "When non-nil, use the last clock out time for `org-todo'.
3427 Note that this option has precedence over the combined use of
3428 `org-use-effective-time' and `org-extend-today-until'."
3429 :group 'org-time
3430 :version "24.4"
3431 :package-version '(Org . "8.0")
3432 :type 'boolean)
3434 (defcustom org-edit-timestamp-down-means-later nil
3435 "Non-nil means S-down will increase the time in a time stamp.
3436 When nil, S-up will increase."
3437 :group 'org-time
3438 :type 'boolean)
3440 (defcustom org-calendar-follow-timestamp-change t
3441 "Non-nil means make the calendar window follow timestamp changes.
3442 When a timestamp is modified and the calendar window is visible, it will be
3443 moved to the new date."
3444 :group 'org-time
3445 :type 'boolean)
3447 (defgroup org-tags nil
3448 "Options concerning tags in Org-mode."
3449 :tag "Org Tags"
3450 :group 'org)
3452 (defcustom org-tag-alist nil
3453 "Default tags available in Org files.
3455 The value of this variable is an alist. Associations either:
3457 (TAG)
3458 (TAG . SELECT)
3459 (SPECIAL)
3461 where TAG is a tag as a string, SELECT is a character, used to
3462 select that tag through the fast tag selection interface, and
3463 SPECIAL is one of the following keywords: `:startgroup',
3464 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3465 `:newline'. These keywords are used to define a hierarchy of
3466 tags. See manual for details.
3468 When this variable is nil, Org mode bases tag input on what is
3469 already in the buffer. The value can be overridden locally by
3470 using a TAGS keyword, e.g.,
3472 #+TAGS: tag1 tag2
3474 See also `org-tag-persistent-alist' to sidestep this behavior."
3475 :group 'org-tags
3476 :type '(repeat
3477 (choice
3478 (cons (string :tag "Tag name")
3479 (character :tag "Access char"))
3480 (const :tag "Start radio group" (:startgroup))
3481 (const :tag "Start tag group, non distinct" (:startgrouptag))
3482 (const :tag "Group tags delimiter" (:grouptags))
3483 (const :tag "End radio group" (:endgroup))
3484 (const :tag "End tag group, non distinct" (:endgrouptag))
3485 (const :tag "New line" (:newline)))))
3487 (defcustom org-tag-persistent-alist nil
3488 "Tags always available in Org files.
3490 The value of this variable is an alist. Associations either:
3492 (TAG)
3493 (TAG . SELECT)
3494 (SPECIAL)
3496 where TAG is a tag as a string, SELECT is a character, used to
3497 select that tag through the fast tag selection interface, and
3498 SPECIAL is one of the following keywords: `:startgroup',
3499 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3500 `:newline'. These keywords are used to define a hierarchy of
3501 tags. See manual for details.
3503 Unlike to `org-tag-alist', tags defined in this variable do not
3504 depend on a local TAGS keyword. Instead, to disable these tags
3505 on a per-file basis, insert anywhere in the file:
3507 #+STARTUP: noptag"
3508 :group 'org-tags
3509 :type '(repeat
3510 (choice
3511 (cons (string :tag "Tag name")
3512 (character :tag "Access char"))
3513 (const :tag "Start radio group" (:startgroup))
3514 (const :tag "Start tag group, non distinct" (:startgrouptag))
3515 (const :tag "Group tags delimiter" (:grouptags))
3516 (const :tag "End radio group" (:endgroup))
3517 (const :tag "End tag group, non distinct" (:endgrouptag))
3518 (const :tag "New line" (:newline)))))
3520 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3521 "If non-nil, always offer completion for all tags of all agenda files.
3522 Instead of customizing this variable directly, you might want to
3523 set it locally for capture buffers, because there no list of
3524 tags in that file can be created dynamically (there are none).
3526 (add-hook \\='org-capture-mode-hook
3527 (lambda ()
3528 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3529 :group 'org-tags
3530 :version "24.1"
3531 :type 'boolean)
3533 (defvar org-file-tags nil
3534 "List of tags that can be inherited by all entries in the file.
3535 The tags will be inherited if the variable `org-use-tag-inheritance'
3536 says they should be.
3537 This variable is populated from #+FILETAGS lines.")
3539 (defcustom org-use-fast-tag-selection 'auto
3540 "Non-nil means use fast tag selection scheme.
3541 This is a special interface to select and deselect tags with single keys.
3542 When nil, fast selection is never used.
3543 When the symbol `auto', fast selection is used if and only if selection
3544 characters for tags have been configured, either through the variable
3545 `org-tag-alist' or through a #+TAGS line in the buffer.
3546 When t, fast selection is always used and selection keys are assigned
3547 automatically if necessary."
3548 :group 'org-tags
3549 :type '(choice
3550 (const :tag "Always" t)
3551 (const :tag "Never" nil)
3552 (const :tag "When selection characters are configured" auto)))
3554 (defcustom org-fast-tag-selection-single-key nil
3555 "Non-nil means fast tag selection exits after first change.
3556 When nil, you have to press RET to exit it.
3557 During fast tag selection, you can toggle this flag with `C-c'.
3558 This variable can also have the value `expert'. In this case, the window
3559 displaying the tags menu is not even shown, until you press C-c again."
3560 :group 'org-tags
3561 :type '(choice
3562 (const :tag "No" nil)
3563 (const :tag "Yes" t)
3564 (const :tag "Expert" expert)))
3566 (defvar org-fast-tag-selection-include-todo nil
3567 "Non-nil means fast tags selection interface will also offer TODO states.
3568 This is an undocumented feature, you should not rely on it.")
3570 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3571 "The column to which tags should be indented in a headline.
3572 If this number is positive, it specifies the column. If it is negative,
3573 it means that the tags should be flushright to that column. For example,
3574 -80 works well for a normal 80 character screen.
3575 When 0, place tags directly after headline text, with only one space in
3576 between."
3577 :group 'org-tags
3578 :type 'integer)
3580 (defcustom org-auto-align-tags t
3581 "Non-nil keeps tags aligned when modifying headlines.
3582 Some operations (i.e. demoting) change the length of a headline and
3583 therefore shift the tags around. With this option turned on, after
3584 each such operation the tags are again aligned to `org-tags-column'."
3585 :group 'org-tags
3586 :type 'boolean)
3588 (defcustom org-use-tag-inheritance t
3589 "Non-nil means tags in levels apply also for sublevels.
3590 When nil, only the tags directly given in a specific line apply there.
3591 This may also be a list of tags that should be inherited, or a regexp that
3592 matches tags that should be inherited. Additional control is possible
3593 with the variable `org-tags-exclude-from-inheritance' which gives an
3594 explicit list of tags to be excluded from inheritance, even if the value of
3595 `org-use-tag-inheritance' would select it for inheritance.
3597 If this option is t, a match early-on in a tree can lead to a large
3598 number of matches in the subtree when constructing the agenda or creating
3599 a sparse tree. If you only want to see the first match in a tree during
3600 a search, check out the variable `org-tags-match-list-sublevels'."
3601 :group 'org-tags
3602 :type '(choice
3603 (const :tag "Not" nil)
3604 (const :tag "Always" t)
3605 (repeat :tag "Specific tags" (string :tag "Tag"))
3606 (regexp :tag "Tags matched by regexp")))
3608 (defcustom org-tags-exclude-from-inheritance nil
3609 "List of tags that should never be inherited.
3610 This is a way to exclude a few tags from inheritance. For way to do
3611 the opposite, to actively allow inheritance for selected tags,
3612 see the variable `org-use-tag-inheritance'."
3613 :group 'org-tags
3614 :type '(repeat (string :tag "Tag")))
3616 (defun org-tag-inherit-p (tag)
3617 "Check if TAG is one that should be inherited."
3618 (cond
3619 ((member tag org-tags-exclude-from-inheritance) nil)
3620 ((eq org-use-tag-inheritance t) t)
3621 ((not org-use-tag-inheritance) nil)
3622 ((stringp org-use-tag-inheritance)
3623 (string-match org-use-tag-inheritance tag))
3624 ((listp org-use-tag-inheritance)
3625 (member tag org-use-tag-inheritance))
3626 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3628 (defcustom org-tags-match-list-sublevels t
3629 "Non-nil means list also sublevels of headlines matching a search.
3630 This variable applies to tags/property searches, and also to stuck
3631 projects because this search is based on a tags match as well.
3633 When set to the symbol `indented', sublevels are indented with
3634 leading dots.
3636 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3637 the sublevels of a headline matching a tag search often also match
3638 the same search. Listing all of them can create very long lists.
3639 Setting this variable to nil causes subtrees of a match to be skipped.
3641 This variable is semi-obsolete and probably should always be true. It
3642 is better to limit inheritance to certain tags using the variables
3643 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3644 :group 'org-tags
3645 :type '(choice
3646 (const :tag "No, don't list them" nil)
3647 (const :tag "Yes, do list them" t)
3648 (const :tag "List them, indented with leading dots" indented)))
3650 (defcustom org-tags-sort-function nil
3651 "When set, tags are sorted using this function as a comparator."
3652 :group 'org-tags
3653 :type '(choice
3654 (const :tag "No sorting" nil)
3655 (const :tag "Alphabetical" string<)
3656 (const :tag "Reverse alphabetical" string>)
3657 (function :tag "Custom function" nil)))
3659 (defvar org-tags-history nil
3660 "History of minibuffer reads for tags.")
3661 (defvar org-last-tags-completion-table nil
3662 "The last used completion table for tags.")
3663 (defvar org-after-tags-change-hook nil
3664 "Hook that is run after the tags in a line have changed.")
3666 (defgroup org-properties nil
3667 "Options concerning properties in Org-mode."
3668 :tag "Org Properties"
3669 :group 'org)
3671 (defcustom org-property-format "%-10s %s"
3672 "How property key/value pairs should be formatted by `indent-line'.
3673 When `indent-line' hits a property definition, it will format the line
3674 according to this format, mainly to make sure that the values are
3675 lined-up with respect to each other."
3676 :group 'org-properties
3677 :type 'string)
3679 (defcustom org-properties-postprocess-alist nil
3680 "Alist of properties and functions to adjust inserted values.
3681 Elements of this alist must be of the form
3683 ([string] [function])
3685 where [string] must be a property name and [function] must be a
3686 lambda expression: this lambda expression must take one argument,
3687 the value to adjust, and return the new value as a string.
3689 For example, this element will allow the property \"Remaining\"
3690 to be updated wrt the relation between the \"Effort\" property
3691 and the clock summary:
3693 ((\"Remaining\" (lambda(value)
3694 (let ((clocksum (org-clock-sum-current-item))
3695 (effort (org-duration-string-to-minutes
3696 (org-entry-get (point) \"Effort\"))))
3697 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3698 :group 'org-properties
3699 :version "24.1"
3700 :type '(alist :key-type (string :tag "Property")
3701 :value-type (function :tag "Function")))
3703 (defcustom org-use-property-inheritance nil
3704 "Non-nil means properties apply also for sublevels.
3706 This setting is chiefly used during property searches. Turning it on can
3707 cause significant overhead when doing a search, which is why it is not
3708 on by default.
3710 When nil, only the properties directly given in the current entry count.
3711 When t, every property is inherited. The value may also be a list of
3712 properties that should have inheritance, or a regular expression matching
3713 properties that should be inherited.
3715 However, note that some special properties use inheritance under special
3716 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3717 and the properties ending in \"_ALL\" when they are used as descriptor
3718 for valid values of a property.
3720 Note for programmers:
3721 When querying an entry with `org-entry-get', you can control if inheritance
3722 should be used. By default, `org-entry-get' looks only at the local
3723 properties. You can request inheritance by setting the inherit argument
3724 to t (to force inheritance) or to `selective' (to respect the setting
3725 in this variable)."
3726 :group 'org-properties
3727 :type '(choice
3728 (const :tag "Not" nil)
3729 (const :tag "Always" t)
3730 (repeat :tag "Specific properties" (string :tag "Property"))
3731 (regexp :tag "Properties matched by regexp")))
3733 (defun org-property-inherit-p (property)
3734 "Check if PROPERTY is one that should be inherited."
3735 (cond
3736 ((eq org-use-property-inheritance t) t)
3737 ((not org-use-property-inheritance) nil)
3738 ((stringp org-use-property-inheritance)
3739 (string-match org-use-property-inheritance property))
3740 ((listp org-use-property-inheritance)
3741 (member property org-use-property-inheritance))
3742 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3744 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3745 "The default column format, if no other format has been defined.
3746 This variable can be set on the per-file basis by inserting a line
3748 #+COLUMNS: %25ITEM ....."
3749 :group 'org-properties
3750 :type 'string)
3752 (defcustom org-columns-ellipses ".."
3753 "The ellipses to be used when a field in column view is truncated.
3754 When this is the empty string, as many characters as possible are shown,
3755 but then there will be no visual indication that the field has been truncated.
3756 When this is a string of length N, the last N characters of a truncated
3757 field are replaced by this string. If the column is narrower than the
3758 ellipses string, only part of the ellipses string will be shown."
3759 :group 'org-properties
3760 :type 'string)
3762 (defconst org-global-properties-fixed
3763 '(("VISIBILITY_ALL" . "folded children content all")
3764 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3765 "List of property/value pairs that can be inherited by any entry.
3767 These are fixed values, for the preset properties. The user variable
3768 that can be used to add to this list is `org-global-properties'.
3770 The entries in this list are cons cells where the car is a property
3771 name and cdr is a string with the value. If the value represents
3772 multiple items like an \"_ALL\" property, separate the items by
3773 spaces.")
3775 (defcustom org-global-properties nil
3776 "List of property/value pairs that can be inherited by any entry.
3778 This list will be combined with the constant `org-global-properties-fixed'.
3780 The entries in this list are cons cells where the car is a property
3781 name and cdr is a string with the value.
3783 You can set buffer-local values for the same purpose in the variable
3784 `org-file-properties' this by adding lines like
3786 #+PROPERTY: NAME VALUE"
3787 :group 'org-properties
3788 :type '(repeat
3789 (cons (string :tag "Property")
3790 (string :tag "Value"))))
3792 (defvar-local org-file-properties nil
3793 "List of property/value pairs that can be inherited by any entry.
3794 Valid for the current buffer.
3795 This variable is populated from #+PROPERTY lines.")
3797 (defgroup org-agenda nil
3798 "Options concerning agenda views in Org-mode."
3799 :tag "Org Agenda"
3800 :group 'org)
3802 (defvar-local org-category nil
3803 "Variable used by org files to set a category for agenda display.
3804 Such files should use a file variable to set it, for example
3806 # -*- mode: org; org-category: \"ELisp\"
3808 or contain a special line
3810 #+CATEGORY: ELisp
3812 If the file does not specify a category, then file's base name
3813 is used instead.")
3814 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3816 (defcustom org-agenda-files nil
3817 "The files to be used for agenda display.
3818 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3819 \\[org-remove-file]. You can also use customize to edit the list.
3821 If an entry is a directory, all files in that directory that are matched by
3822 `org-agenda-file-regexp' will be part of the file list.
3824 If the value of the variable is not a list but a single file name, then
3825 the list of agenda files is actually stored and maintained in that file, one
3826 agenda file per line. In this file paths can be given relative to
3827 `org-directory'. Tilde expansion and environment variable substitution
3828 are also made."
3829 :group 'org-agenda
3830 :type '(choice
3831 (repeat :tag "List of files and directories" file)
3832 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3834 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3835 "Regular expression to match files for `org-agenda-files'.
3836 If any element in the list in that variable contains a directory instead
3837 of a normal file, all files in that directory that are matched by this
3838 regular expression will be included."
3839 :group 'org-agenda
3840 :type 'regexp)
3842 (defcustom org-agenda-text-search-extra-files nil
3843 "List of extra files to be searched by text search commands.
3844 These files will be searched in addition to the agenda files by the
3845 commands `org-search-view' (`\\[org-agenda] s') \
3846 and `org-occur-in-agenda-files'.
3847 Note that these files will only be searched for text search commands,
3848 not for the other agenda views like todo lists, tag searches or the weekly
3849 agenda. This variable is intended to list notes and possibly archive files
3850 that should also be searched by these two commands.
3851 In fact, if the first element in the list is the symbol `agenda-archives',
3852 then all archive files of all agenda files will be added to the search
3853 scope."
3854 :group 'org-agenda
3855 :type '(set :greedy t
3856 (const :tag "Agenda Archives" agenda-archives)
3857 (repeat :inline t (file))))
3859 (org-defvaralias 'org-agenda-multi-occur-extra-files
3860 'org-agenda-text-search-extra-files)
3862 (defcustom org-agenda-skip-unavailable-files nil
3863 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3864 A nil value means to remove them, after a query, from the list."
3865 :group 'org-agenda
3866 :type 'boolean)
3868 (defcustom org-calendar-to-agenda-key [?c]
3869 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3870 The command `org-calendar-goto-agenda' will be bound to this key. The
3871 default is the character `c' because then `c' can be used to switch back and
3872 forth between agenda and calendar."
3873 :group 'org-agenda
3874 :type 'sexp)
3876 (defcustom org-calendar-insert-diary-entry-key [?i]
3877 "The key to be installed in `calendar-mode-map' for adding diary entries.
3878 This option is irrelevant until `org-agenda-diary-file' has been configured
3879 to point to an Org-mode file. When that is the case, the command
3880 `org-agenda-diary-entry' will be bound to the key given here, by default
3881 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3882 if you want to continue doing this, you need to change this to a different
3883 key."
3884 :group 'org-agenda
3885 :type 'sexp)
3887 (defcustom org-agenda-diary-file 'diary-file
3888 "File to which to add new entries with the `i' key in agenda and calendar.
3889 When this is the symbol `diary-file', the functionality in the Emacs
3890 calendar will be used to add entries to the `diary-file'. But when this
3891 points to a file, `org-agenda-diary-entry' will be used instead."
3892 :group 'org-agenda
3893 :type '(choice
3894 (const :tag "The standard Emacs diary file" diary-file)
3895 (file :tag "Special Org file diary entries")))
3897 (eval-after-load "calendar"
3898 '(progn
3899 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3900 'org-calendar-goto-agenda)
3901 (add-hook 'calendar-mode-hook
3902 (lambda ()
3903 (unless (eq org-agenda-diary-file 'diary-file)
3904 (define-key calendar-mode-map
3905 org-calendar-insert-diary-entry-key
3906 'org-agenda-diary-entry))))))
3908 (defgroup org-latex nil
3909 "Options for embedding LaTeX code into Org-mode."
3910 :tag "Org LaTeX"
3911 :group 'org)
3913 (defcustom org-format-latex-options
3914 '(:foreground default :background default :scale 1.0
3915 :html-foreground "Black" :html-background "Transparent"
3916 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3917 "Options for creating images from LaTeX fragments.
3918 This is a property list with the following properties:
3919 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3920 `default' means use the foreground of the default face.
3921 `auto' means use the foreground from the text face.
3922 :background the background color, or \"Transparent\".
3923 `default' means use the background of the default face.
3924 `auto' means use the background from the text face.
3925 :scale a scaling factor for the size of the images, to get more pixels
3926 :html-foreground, :html-background, :html-scale
3927 the same numbers for HTML export.
3928 :matchers a list indicating which matchers should be used to
3929 find LaTeX fragments. Valid members of this list are:
3930 \"begin\" find environments
3931 \"$1\" find single characters surrounded by $.$
3932 \"$\" find math expressions surrounded by $...$
3933 \"$$\" find math expressions surrounded by $$....$$
3934 \"\\(\" find math expressions surrounded by \\(...\\)
3935 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3936 :group 'org-latex
3937 :type 'plist)
3939 (defcustom org-format-latex-signal-error t
3940 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3941 When nil, just push out a message."
3942 :group 'org-latex
3943 :version "24.1"
3944 :type 'boolean)
3946 (defcustom org-latex-to-mathml-jar-file nil
3947 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3948 Use this to specify additional executable file say a jar file.
3950 When using MathToWeb as the converter, specify the full-path to
3951 your mathtoweb.jar file."
3952 :group 'org-latex
3953 :version "24.1"
3954 :type '(choice
3955 (const :tag "None" nil)
3956 (file :tag "JAR file" :must-match t)))
3958 (defcustom org-latex-to-mathml-convert-command nil
3959 "Command to convert LaTeX fragments to MathML.
3960 Replace format-specifiers in the command as noted below and use
3961 `shell-command' to convert LaTeX to MathML.
3962 %j: Executable file in fully expanded form as specified by
3963 `org-latex-to-mathml-jar-file'.
3964 %I: Input LaTeX file in fully expanded form.
3965 %i: The latex fragment to be converted.
3966 %o: Output MathML file.
3968 This command is used by `org-create-math-formula'.
3970 When using MathToWeb as the converter, set this option to
3971 \"java -jar %j -unicode -force -df %o %I\".
3973 When using LaTeXML set this option to
3974 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3975 :group 'org-latex
3976 :version "24.1"
3977 :type '(choice
3978 (const :tag "None" nil)
3979 (string :tag "\nShell command")))
3981 (defcustom org-latex-create-formula-image-program 'dvipng
3982 "Program to convert LaTeX fragments with.
3984 dvipng Process the LaTeX fragments to dvi file, then convert
3985 dvi files to png files using dvipng.
3986 This will also include processing of non-math environments.
3987 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3988 to convert pdf files to png files"
3989 :group 'org-latex
3990 :version "24.1"
3991 :type '(choice
3992 (const :tag "dvipng" dvipng)
3993 (const :tag "imagemagick" imagemagick)))
3995 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3996 "Path to store latex preview images.
3997 A relative path here creates many directories relative to the
3998 processed org files paths. An absolute path puts all preview
3999 images at the same place."
4000 :group 'org-latex
4001 :version "24.3"
4002 :type 'string)
4004 (defun org-format-latex-mathml-available-p ()
4005 "Return t if `org-latex-to-mathml-convert-command' is usable."
4006 (save-match-data
4007 (when (and (boundp 'org-latex-to-mathml-convert-command)
4008 org-latex-to-mathml-convert-command)
4009 (let ((executable (car (split-string
4010 org-latex-to-mathml-convert-command))))
4011 (when (executable-find executable)
4012 (if (string-match
4013 "%j" org-latex-to-mathml-convert-command)
4014 (file-readable-p org-latex-to-mathml-jar-file)
4015 t))))))
4017 (defcustom org-format-latex-header "\\documentclass{article}
4018 \\usepackage[usenames]{color}
4019 \[PACKAGES]
4020 \[DEFAULT-PACKAGES]
4021 \\pagestyle{empty} % do not remove
4022 % The settings below are copied from fullpage.sty
4023 \\setlength{\\textwidth}{\\paperwidth}
4024 \\addtolength{\\textwidth}{-3cm}
4025 \\setlength{\\oddsidemargin}{1.5cm}
4026 \\addtolength{\\oddsidemargin}{-2.54cm}
4027 \\setlength{\\evensidemargin}{\\oddsidemargin}
4028 \\setlength{\\textheight}{\\paperheight}
4029 \\addtolength{\\textheight}{-\\headheight}
4030 \\addtolength{\\textheight}{-\\headsep}
4031 \\addtolength{\\textheight}{-\\footskip}
4032 \\addtolength{\\textheight}{-3cm}
4033 \\setlength{\\topmargin}{1.5cm}
4034 \\addtolength{\\topmargin}{-2.54cm}"
4035 "The document header used for processing LaTeX fragments.
4036 It is imperative that this header make sure that no page number
4037 appears on the page. The package defined in the variables
4038 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4039 will either replace the placeholder \"[PACKAGES]\" in this
4040 header, or they will be appended."
4041 :group 'org-latex
4042 :type 'string)
4044 (defun org-set-packages-alist (var val)
4045 "Set the packages alist and make sure it has 3 elements per entry."
4046 (set var (mapcar (lambda (x)
4047 (if (and (consp x) (= (length x) 2))
4048 (list (car x) (nth 1 x) t)
4050 val)))
4052 (defun org-get-packages-alist (var)
4053 "Get the packages alist and make sure it has 3 elements per entry."
4054 (mapcar (lambda (x)
4055 (if (and (consp x) (= (length x) 2))
4056 (list (car x) (nth 1 x) t)
4058 (default-value var)))
4060 (defcustom org-latex-default-packages-alist
4061 '(("AUTO" "inputenc" t ("pdflatex"))
4062 ("T1" "fontenc" t ("pdflatex"))
4063 ("" "graphicx" t)
4064 ("" "grffile" t)
4065 ("" "longtable" nil)
4066 ("" "wrapfig" nil)
4067 ("" "rotating" nil)
4068 ("normalem" "ulem" t)
4069 ("" "amsmath" t)
4070 ("" "textcomp" t)
4071 ("" "amssymb" t)
4072 ("" "capt-of" nil)
4073 ("" "hyperref" nil))
4074 "Alist of default packages to be inserted in the header.
4076 Change this only if one of the packages here causes an
4077 incompatibility with another package you are using.
4079 The packages in this list are needed by one part or another of
4080 Org mode to function properly:
4082 - inputenc, fontenc: for basic font and character selection
4083 - graphicx: for including images
4084 - grffile: allow periods and spaces in graphics file names
4085 - longtable: For multipage tables
4086 - wrapfig: for figure placement
4087 - rotating: for sideways figures and tables
4088 - ulem: for underline and strike-through
4089 - amsmath: for subscript and superscript and math environments
4090 - textcomp, amssymb: for various symbols used
4091 for interpreting the entities in `org-entities'. You can skip
4092 some of these packages if you don't use any of their symbols.
4093 - capt-of: for captions outside of floats
4094 - hyperref: for cross references
4096 Therefore you should not modify this variable unless you know
4097 what you are doing. The one reason to change it anyway is that
4098 you might be loading some other package that conflicts with one
4099 of the default packages. Each element is either a cell or
4100 a string.
4102 A cell is of the format
4104 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4106 If SNIPPET-FLAG is non-nil, the package also needs to be included
4107 when compiling LaTeX snippets into images for inclusion into
4108 non-LaTeX output. COMPILERS is a list of compilers that should
4109 include the package, see `org-latex-compiler'. If the document
4110 compiler is not in the list, and the list is non-nil, the package
4111 will not be inserted in the final document.
4113 A string will be inserted as-is in the header of the document."
4114 :group 'org-latex
4115 :group 'org-export-latex
4116 :set 'org-set-packages-alist
4117 :get 'org-get-packages-alist
4118 :version "25.1"
4119 :package-version '(Org . "8.3")
4120 :type '(repeat
4121 (choice
4122 (list :tag "options/package pair"
4123 (string :tag "options")
4124 (string :tag "package")
4125 (boolean :tag "Snippet"))
4126 (string :tag "A line of LaTeX"))))
4128 (defcustom org-latex-packages-alist nil
4129 "Alist of packages to be inserted in every LaTeX header.
4131 These will be inserted after `org-latex-default-packages-alist'.
4132 Each element is either a cell or a string.
4134 A cell is of the format:
4136 (\"options\" \"package\" SNIPPET-FLAG)
4138 SNIPPET-FLAG, when non-nil, indicates that this package is also
4139 needed when turning LaTeX snippets into images for inclusion into
4140 non-LaTeX output.
4142 A string will be inserted as-is in the header of the document.
4144 Make sure that you only list packages here which:
4146 - you want in every file;
4147 - do not conflict with the setup in `org-format-latex-header';
4148 - do not conflict with the default packages in
4149 `org-latex-default-packages-alist'."
4150 :group 'org-latex
4151 :group 'org-export-latex
4152 :set 'org-set-packages-alist
4153 :get 'org-get-packages-alist
4154 :type '(repeat
4155 (choice
4156 (list :tag "options/package pair"
4157 (string :tag "options")
4158 (string :tag "package")
4159 (boolean :tag "Snippet"))
4160 (string :tag "A line of LaTeX"))))
4162 (defgroup org-appearance nil
4163 "Settings for Org-mode appearance."
4164 :tag "Org Appearance"
4165 :group 'org)
4167 (defcustom org-level-color-stars-only nil
4168 "Non-nil means fontify only the stars in each headline.
4169 When nil, the entire headline is fontified.
4170 Changing it requires restart of `font-lock-mode' to become effective
4171 also in regions already fontified."
4172 :group 'org-appearance
4173 :type 'boolean)
4175 (defcustom org-hide-leading-stars nil
4176 "Non-nil means hide the first N-1 stars in a headline.
4177 This works by using the face `org-hide' for these stars. This
4178 face is white for a light background, and black for a dark
4179 background. You may have to customize the face `org-hide' to
4180 make this work.
4181 Changing it requires restart of `font-lock-mode' to become effective
4182 also in regions already fontified.
4183 You may also set this on a per-file basis by adding one of the following
4184 lines to the buffer:
4186 #+STARTUP: hidestars
4187 #+STARTUP: showstars"
4188 :group 'org-appearance
4189 :type 'boolean)
4191 (defcustom org-hidden-keywords nil
4192 "List of symbols corresponding to keywords to be hidden the org buffer.
4193 For example, a value \\='(title) for this list will make the document's title
4194 appear in the buffer without the initial #+TITLE: keyword."
4195 :group 'org-appearance
4196 :version "24.1"
4197 :type '(set (const :tag "#+AUTHOR" author)
4198 (const :tag "#+DATE" date)
4199 (const :tag "#+EMAIL" email)
4200 (const :tag "#+TITLE" title)))
4202 (defcustom org-custom-properties nil
4203 "List of properties (as strings) with a special meaning.
4204 The default use of these custom properties is to let the user
4205 hide them with `org-toggle-custom-properties-visibility'."
4206 :group 'org-properties
4207 :group 'org-appearance
4208 :version "24.3"
4209 :type '(repeat (string :tag "Property Name")))
4211 (defcustom org-fontify-done-headline nil
4212 "Non-nil means change the face of a headline if it is marked DONE.
4213 Normally, only the TODO/DONE keyword indicates the state of a headline.
4214 When this is non-nil, the headline after the keyword is set to the
4215 `org-headline-done' as an additional indication."
4216 :group 'org-appearance
4217 :type 'boolean)
4219 (defcustom org-fontify-emphasized-text t
4220 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4221 Changing this variable requires a restart of Emacs to take effect."
4222 :group 'org-appearance
4223 :type 'boolean)
4225 (defcustom org-fontify-whole-heading-line nil
4226 "Non-nil means fontify the whole line for headings.
4227 This is useful when setting a background color for the
4228 org-level-* faces."
4229 :group 'org-appearance
4230 :type 'boolean)
4232 (defcustom org-highlight-latex-and-related nil
4233 "Non-nil means highlight LaTeX related syntax in the buffer.
4234 When non nil, the value should be a list containing any of the
4235 following symbols:
4236 `latex' Highlight LaTeX snippets and environments.
4237 `script' Highlight subscript and superscript.
4238 `entities' Highlight entities."
4239 :group 'org-appearance
4240 :version "24.4"
4241 :package-version '(Org . "8.0")
4242 :type '(choice
4243 (const :tag "No highlighting" nil)
4244 (set :greedy t :tag "Highlight"
4245 (const :tag "LaTeX snippets and environments" latex)
4246 (const :tag "Subscript and superscript" script)
4247 (const :tag "Entities" entities))))
4249 (defcustom org-hide-emphasis-markers nil
4250 "Non-nil mean font-lock should hide the emphasis marker characters."
4251 :group 'org-appearance
4252 :type 'boolean)
4254 (defcustom org-hide-macro-markers nil
4255 "Non-nil mean font-lock should hide the brackets marking macro calls."
4256 :group 'org-appearance
4257 :type 'boolean)
4259 (defcustom org-pretty-entities nil
4260 "Non-nil means show entities as UTF8 characters.
4261 When nil, the \\name form remains in the buffer."
4262 :group 'org-appearance
4263 :version "24.1"
4264 :type 'boolean)
4266 (defcustom org-pretty-entities-include-sub-superscripts t
4267 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4268 :group 'org-appearance
4269 :version "24.1"
4270 :type 'boolean)
4272 (defvar org-emph-re nil
4273 "Regular expression for matching emphasis.
4274 After a match, the match groups contain these elements:
4275 0 The match of the full regular expression, including the characters
4276 before and after the proper match
4277 1 The character before the proper match, or empty at beginning of line
4278 2 The proper match, including the leading and trailing markers
4279 3 The leading marker like * or /, indicating the type of highlighting
4280 4 The text between the emphasis markers, not including the markers
4281 5 The character after the match, empty at the end of a line")
4282 (defvar org-verbatim-re nil
4283 "Regular expression for matching verbatim text.")
4284 (defvar org-emphasis-regexp-components) ; defined just below
4285 (defvar org-emphasis-alist) ; defined just below
4286 (defun org-set-emph-re (var val)
4287 "Set variable and compute the emphasis regular expression."
4288 (set var val)
4289 (when (and (boundp 'org-emphasis-alist)
4290 (boundp 'org-emphasis-regexp-components)
4291 org-emphasis-alist org-emphasis-regexp-components)
4292 (let* ((e org-emphasis-regexp-components)
4293 (pre (car e))
4294 (post (nth 1 e))
4295 (border (nth 2 e))
4296 (body (nth 3 e))
4297 (nl (nth 4 e))
4298 (body1 (concat body "*?"))
4299 (markers (mapconcat 'car org-emphasis-alist ""))
4300 (vmarkers (mapconcat
4301 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4302 org-emphasis-alist "")))
4303 ;; make sure special characters appear at the right position in the class
4304 (if (string-match "\\^" markers)
4305 (setq markers (concat (replace-match "" t t markers) "^")))
4306 (if (string-match "-" markers)
4307 (setq markers (concat (replace-match "" t t markers) "-")))
4308 (if (string-match "\\^" vmarkers)
4309 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4310 (if (string-match "-" vmarkers)
4311 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4312 (if (> nl 0)
4313 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4314 (int-to-string nl) "\\}")))
4315 ;; Make the regexp
4316 (setq org-emph-re
4317 (concat "\\([" pre "]\\|^\\)"
4318 "\\("
4319 "\\([" markers "]\\)"
4320 "\\("
4321 "[^" border "]\\|"
4322 "[^" border "]"
4323 body1
4324 "[^" border "]"
4325 "\\)"
4326 "\\3\\)"
4327 "\\([" post "]\\|$\\)"))
4328 (setq org-verbatim-re
4329 (concat "\\([" pre "]\\|^\\)"
4330 "\\("
4331 "\\([" vmarkers "]\\)"
4332 "\\("
4333 "[^" border "]\\|"
4334 "[^" border "]"
4335 body1
4336 "[^" border "]"
4337 "\\)"
4338 "\\3\\)"
4339 "\\([" post "]\\|$\\)")))))
4341 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4342 ;; set this option proved cumbersome. See this message/thread:
4343 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4344 (defvar org-emphasis-regexp-components
4345 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4346 "Components used to build the regular expression for emphasis.
4347 This is a list with five entries. Terminology: In an emphasis string
4348 like \" *strong word* \", we call the initial space PREMATCH, the final
4349 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4350 and \"trong wor\" is the body. The different components in this variable
4351 specify what is allowed/forbidden in each part:
4353 pre Chars allowed as prematch. Beginning of line will be allowed too.
4354 post Chars allowed as postmatch. End of line will be allowed too.
4355 border The chars *forbidden* as border characters.
4356 body-regexp A regexp like \".\" to match a body character. Don't use
4357 non-shy groups here, and don't allow newline here.
4358 newline The maximum number of newlines allowed in an emphasis exp.
4360 You need to reload Org or to restart Emacs after customizing this.")
4362 (defcustom org-emphasis-alist
4363 `(("*" bold)
4364 ("/" italic)
4365 ("_" underline)
4366 ("=" org-verbatim verbatim)
4367 ("~" org-code verbatim)
4368 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4369 "Alist of characters and faces to emphasize text.
4370 Text starting and ending with a special character will be emphasized,
4371 for example *bold*, _underlined_ and /italic/. This variable sets the
4372 marker characters and the face to be used by font-lock for highlighting
4373 in Org-mode Emacs buffers.
4375 You need to reload Org or to restart Emacs after customizing this."
4376 :group 'org-appearance
4377 :set 'org-set-emph-re
4378 :version "24.4"
4379 :package-version '(Org . "8.0")
4380 :type '(repeat
4381 (list
4382 (string :tag "Marker character")
4383 (choice
4384 (face :tag "Font-lock-face")
4385 (plist :tag "Face property list"))
4386 (option (const verbatim)))))
4388 (defvar org-protecting-blocks '("src" "example" "export")
4389 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4390 This is needed for font-lock setup.")
4392 ;;; Functions and variables from their packages
4393 ;; Declared here to avoid compiler warnings
4395 ;; XEmacs only
4396 (defvar outline-mode-menu-heading)
4397 (defvar outline-mode-menu-show)
4398 (defvar outline-mode-menu-hide)
4399 (defvar zmacs-regions) ; XEmacs regions
4401 ;; Emacs only
4402 (defvar mark-active)
4404 ;; Various packages
4405 (declare-function calc-eval "calc" (str &optional separator &rest args))
4406 (declare-function calendar-forward-day "cal-move" (arg))
4407 (declare-function calendar-goto-date "cal-move" (date))
4408 (declare-function calendar-goto-today "cal-move" ())
4409 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4410 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4411 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4412 (declare-function cdlatex-tab "ext:cdlatex" ())
4413 (declare-function dired-get-filename
4414 "dired"
4415 (&optional localp no-error-if-not-filep))
4416 (declare-function iswitchb-read-buffer
4417 "iswitchb"
4418 (prompt &optional default require-match start matches-set))
4419 (declare-function org-agenda-change-all-lines
4420 "org-agenda"
4421 (newhead hdmarker &optional fixface just-this))
4422 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4423 "org-agenda"
4424 (&optional end))
4425 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4426 (declare-function org-agenda-format-item
4427 "org-agenda"
4428 (extra txt &optional level category tags dotime noprefix
4429 remove-re habitp))
4430 (declare-function org-agenda-maybe-redo "org-agenda" ())
4431 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4432 (declare-function org-agenda-save-markers-for-cut-and-paste
4433 "org-agenda"
4434 (beg end))
4435 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4436 (declare-function org-agenda-skip "org-agenda" ())
4437 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4438 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4439 (declare-function org-indent-mode "org-indent" (&optional arg))
4440 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4441 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4442 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4443 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4444 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4445 (declare-function parse-time-string "parse-time" (string))
4446 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4447 (declare-function table--at-cell-p
4448 "table"
4449 (position &optional object at-column))
4451 (defvar align-mode-rules-list)
4452 (defvar calc-embedded-close-formula)
4453 (defvar calc-embedded-open-formula)
4454 (defvar calc-embedded-open-mode)
4455 (defvar font-lock-unfontify-region-function)
4456 (defvar iswitchb-temp-buflist)
4457 (defvar org-agenda-tags-todo-honor-ignore-options)
4458 (defvar remember-data-file)
4459 (defvar texmathp-why)
4461 ;;;###autoload
4462 (defun turn-on-orgtbl ()
4463 "Unconditionally turn on `orgtbl-mode'."
4464 (require 'org-table)
4465 (orgtbl-mode 1))
4467 (defun org-at-table-p (&optional table-type)
4468 "Non-nil if the cursor is inside an Org table.
4469 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4470 If `org-enable-table-editor' is nil, return nil unconditionally."
4471 (and
4472 org-enable-table-editor
4473 (save-excursion
4474 (beginning-of-line)
4475 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4476 (or (not (derived-mode-p 'org-mode))
4477 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4478 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4479 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4481 (defun org-at-table.el-p ()
4482 "Non-nil when point is at a table.el table."
4483 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4484 (let ((element (org-element-at-point)))
4485 (and (eq (org-element-type element) 'table)
4486 (eq (org-element-property :type element) 'table.el)))))
4488 (defun org-table-recognize-table.el ()
4489 "If there is a table.el table nearby, recognize it and move into it."
4490 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4491 (beginning-of-line)
4492 (unless (or (looking-at org-table-dataline-regexp)
4493 (not (looking-at org-table1-hline-regexp)))
4494 (forward-line)
4495 (when (looking-at org-table-any-border-regexp)
4496 (forward-line -2)))
4497 (if (re-search-forward "|" (org-table-end t) t)
4498 (progn
4499 (require 'table)
4500 (if (table--at-cell-p (point)) t
4501 (message "recognizing table.el table...")
4502 (table-recognize-table)
4503 (message "recognizing table.el table...done")))
4504 (error "This should not happen"))))
4505 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4506 (make-obsolete 'org-table-recognize-table.el
4507 "please notify the org mailing list if you use this function."
4508 "Org 9.0")
4510 (defun org-at-table-hline-p ()
4511 "Non-nil when point is inside a hline in a table.
4512 Assume point is already in a table. If `org-enable-table-editor'
4513 is nil, return nil unconditionally."
4514 (and org-enable-table-editor
4515 (save-excursion
4516 (beginning-of-line)
4517 (looking-at org-table-hline-regexp))))
4519 (defun org-table-map-tables (function &optional quietly)
4520 "Apply FUNCTION to the start of all tables in the buffer."
4521 (save-excursion
4522 (save-restriction
4523 (widen)
4524 (goto-char (point-min))
4525 (while (re-search-forward org-table-any-line-regexp nil t)
4526 (unless quietly
4527 (message "Mapping tables: %d%%"
4528 (floor (* 100.0 (point)) (buffer-size))))
4529 (beginning-of-line 1)
4530 (when (and (looking-at org-table-line-regexp)
4531 ;; Exclude tables in src/example/verbatim/clocktable blocks
4532 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4533 (save-excursion (funcall function))
4534 (or (looking-at org-table-line-regexp)
4535 (forward-char 1)))
4536 (re-search-forward org-table-any-border-regexp nil 1))))
4537 (unless quietly (message "Mapping tables: done")))
4539 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4540 (declare-function org-clock-update-mode-line "org-clock" ())
4541 (declare-function org-resolve-clocks "org-clock"
4542 (&optional also-non-dangling-p prompt last-valid))
4544 (defun org-at-TBLFM-p (&optional pos)
4545 "Non-nil when point (or POS) is in #+TBLFM line."
4546 (save-excursion
4547 (goto-char (or pos (point)))
4548 (beginning-of-line)
4549 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4550 (eq (org-element-type (org-element-at-point)) 'table))))
4552 (defvar org-clock-start-time)
4553 (defvar org-clock-marker (make-marker)
4554 "Marker recording the last clock-in.")
4555 (defvar org-clock-hd-marker (make-marker)
4556 "Marker recording the last clock-in, but the headline position.")
4557 (defvar org-clock-heading ""
4558 "The heading of the current clock entry.")
4559 (defun org-clock-is-active ()
4560 "Return the buffer where the clock is currently running.
4561 Return nil if no clock is running."
4562 (marker-buffer org-clock-marker))
4564 (defun org-check-running-clock ()
4565 "Check if the current buffer contains the running clock.
4566 If yes, offer to stop it and to save the buffer with the changes."
4567 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4568 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4569 (buffer-name))))
4570 (org-clock-out)
4571 (when (y-or-n-p "Save changed buffer?")
4572 (save-buffer))))
4574 (defun org-clocktable-try-shift (dir n)
4575 "Check if this line starts a clock table, if yes, shift the time block."
4576 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4577 (org-clocktable-shift dir n)))
4579 ;;;###autoload
4580 (defun org-clock-persistence-insinuate ()
4581 "Set up hooks for clock persistence."
4582 (require 'org-clock)
4583 (add-hook 'org-mode-hook 'org-clock-load)
4584 (add-hook 'kill-emacs-hook 'org-clock-save))
4586 (defgroup org-archive nil
4587 "Options concerning archiving in Org-mode."
4588 :tag "Org Archive"
4589 :group 'org-structure)
4591 (defcustom org-archive-location "%s_archive::"
4592 "The location where subtrees should be archived.
4594 The value of this variable is a string, consisting of two parts,
4595 separated by a double-colon. The first part is a filename and
4596 the second part is a headline.
4598 When the filename is omitted, archiving happens in the same file.
4599 %s in the filename will be replaced by the current file
4600 name (without the directory part). Archiving to a different file
4601 is useful to keep archived entries from contributing to the
4602 Org-mode Agenda.
4604 The archived entries will be filed as subtrees of the specified
4605 headline. When the headline is omitted, the subtrees are simply
4606 filed away at the end of the file, as top-level entries. Also in
4607 the heading you can use %s to represent the file name, this can be
4608 useful when using the same archive for a number of different files.
4610 Here are a few examples:
4611 \"%s_archive::\"
4612 If the current file is Projects.org, archive in file
4613 Projects.org_archive, as top-level trees. This is the default.
4615 \"::* Archived Tasks\"
4616 Archive in the current file, under the top-level headline
4617 \"* Archived Tasks\".
4619 \"~/org/archive.org::\"
4620 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4622 \"~/org/archive.org::* From %s\"
4623 Archive in file ~/org/archive.org (absolute path), under headlines
4624 \"From FILENAME\" where file name is the current file name.
4626 \"~/org/datetree.org::datetree/* Finished Tasks\"
4627 The \"datetree/\" string is special, signifying to archive
4628 items to the datetree. Items are placed in either the CLOSED
4629 date of the item, or the current date if there is no CLOSED date.
4630 The heading will be a subentry to the current date. There doesn't
4631 need to be a heading, but there always needs to be a slash after
4632 datetree. For example, to store archived items directly in the
4633 datetree, use \"~/org/datetree.org::datetree/\".
4635 \"basement::** Finished Tasks\"
4636 Archive in file ./basement (relative path), as level 3 trees
4637 below the level 2 heading \"** Finished Tasks\".
4639 You may set this option on a per-file basis by adding to the buffer a
4640 line like
4642 #+ARCHIVE: basement::** Finished Tasks
4644 You may also define it locally for a subtree by setting an ARCHIVE property
4645 in the entry. If such a property is found in an entry, or anywhere up
4646 the hierarchy, it will be used."
4647 :group 'org-archive
4648 :type 'string)
4650 (defcustom org-agenda-skip-archived-trees t
4651 "Non-nil means the agenda will skip any items located in archived trees.
4652 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4653 variable is no longer recommended, you should leave it at the value t.
4654 Instead, use the key `v' to cycle the archives-mode in the agenda."
4655 :group 'org-archive
4656 :group 'org-agenda-skip
4657 :type 'boolean)
4659 (defcustom org-columns-skip-archived-trees t
4660 "Non-nil means ignore archived trees when creating column view."
4661 :group 'org-archive
4662 :group 'org-properties
4663 :type 'boolean)
4665 (defcustom org-cycle-open-archived-trees nil
4666 "Non-nil means `org-cycle' will open archived trees.
4667 An archived tree is a tree marked with the tag ARCHIVE.
4668 When nil, archived trees will stay folded. You can still open them with
4669 normal outline commands like `show-all', but not with the cycling commands."
4670 :group 'org-archive
4671 :group 'org-cycle
4672 :type 'boolean)
4674 (defcustom org-sparse-tree-open-archived-trees nil
4675 "Non-nil means sparse tree construction shows matches in archived trees.
4676 When nil, matches in these trees are highlighted, but the trees are kept in
4677 collapsed state."
4678 :group 'org-archive
4679 :group 'org-sparse-trees
4680 :type 'boolean)
4682 (defcustom org-sparse-tree-default-date-type nil
4683 "The default date type when building a sparse tree.
4684 When this is nil, a date is a scheduled or a deadline timestamp.
4685 Otherwise, these types are allowed:
4687 all: all timestamps
4688 active: only active timestamps (<...>)
4689 inactive: only inactive timestamps ([...])
4690 scheduled: only scheduled timestamps
4691 deadline: only deadline timestamps"
4692 :type '(choice (const :tag "Scheduled or deadline" nil)
4693 (const :tag "All timestamps" all)
4694 (const :tag "Only active timestamps" active)
4695 (const :tag "Only inactive timestamps" inactive)
4696 (const :tag "Only scheduled timestamps" scheduled)
4697 (const :tag "Only deadline timestamps" deadline)
4698 (const :tag "Only closed timestamps" closed))
4699 :version "25.1"
4700 :package-version '(Org . "8.3")
4701 :group 'org-sparse-trees)
4703 (defun org-cycle-hide-archived-subtrees (state)
4704 "Re-hide all archived subtrees after a visibility state change."
4705 (when (and (not org-cycle-open-archived-trees)
4706 (not (memq state '(overview folded))))
4707 (save-excursion
4708 (let* ((globalp (memq state '(contents all)))
4709 (beg (if globalp (point-min) (point)))
4710 (end (if globalp (point-max) (org-end-of-subtree t))))
4711 (org-hide-archived-subtrees beg end)
4712 (goto-char beg)
4713 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4714 (message "%s" (substitute-command-keys
4715 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4717 (defun org-force-cycle-archived ()
4718 "Cycle subtree even if it is archived."
4719 (interactive)
4720 (setq this-command 'org-cycle)
4721 (let ((org-cycle-open-archived-trees t))
4722 (call-interactively 'org-cycle)))
4724 (defun org-hide-archived-subtrees (beg end)
4725 "Re-hide all archived subtrees after a visibility state change."
4726 (org-with-wide-buffer
4727 (let ((case-fold-search nil)
4728 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4729 (goto-char beg)
4730 ;; Include headline point is currently on.
4731 (beginning-of-line)
4732 (while (and (< (point) end) (re-search-forward re end t))
4733 (when (member org-archive-tag (org-get-tags))
4734 (org-flag-subtree t)
4735 (org-end-of-subtree t))))))
4737 (declare-function outline-end-of-heading "outline" ())
4738 (declare-function outline-flag-region "outline" (from to flag))
4739 (defun org-flag-subtree (flag)
4740 (save-excursion
4741 (org-back-to-heading t)
4742 (outline-end-of-heading)
4743 (outline-flag-region (point)
4744 (progn (org-end-of-subtree t) (point))
4745 flag)))
4747 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4749 ;; Declare Column View Code
4751 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4752 (declare-function org-columns-compute "org-colview" (property))
4754 ;; Declare ID code
4756 (declare-function org-id-store-link "org-id")
4757 (declare-function org-id-locations-load "org-id")
4758 (declare-function org-id-locations-save "org-id")
4759 (defvar org-id-track-globally)
4761 ;;; Variables for pre-computed regular expressions, all buffer local
4763 (defvar-local org-todo-regexp nil
4764 "Matches any of the TODO state keywords.")
4765 (defvar-local org-not-done-regexp nil
4766 "Matches any of the TODO state keywords except the last one.")
4767 (defvar-local org-not-done-heading-regexp nil
4768 "Matches a TODO headline that is not done.")
4769 (defvar-local org-todo-line-regexp nil
4770 "Matches a headline and puts TODO state into group 2 if present.")
4771 (defvar-local org-complex-heading-regexp nil
4772 "Matches a headline and puts everything into groups:
4773 group 1: the stars
4774 group 2: The todo keyword, maybe
4775 group 3: Priority cookie
4776 group 4: True headline
4777 group 5: Tags")
4778 (defvar-local org-complex-heading-regexp-format nil
4779 "Printf format to make regexp to match an exact headline.
4780 This regexp will match the headline of any node which has the
4781 exact headline text that is put into the format, but may have any
4782 TODO state, priority and tags.")
4783 (defvar-local org-todo-line-tags-regexp nil
4784 "Matches a headline and puts TODO state into group 2 if present.
4785 Also put tags into group 4 if tags are present.")
4787 (defconst org-plain-time-of-day-regexp
4788 (concat
4789 "\\(\\<[012]?[0-9]"
4790 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4791 "\\(--?"
4792 "\\(\\<[012]?[0-9]"
4793 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4794 "\\)?")
4795 "Regular expression to match a plain time or time range.
4796 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4797 groups carry important information:
4798 0 the full match
4799 1 the first time, range or not
4800 8 the second time, if it is a range.")
4802 (defconst org-plain-time-extension-regexp
4803 (concat
4804 "\\(\\<[012]?[0-9]"
4805 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4806 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4807 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4808 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4809 groups carry important information:
4810 0 the full match
4811 7 hours of duration
4812 9 minutes of duration")
4814 (defconst org-stamp-time-of-day-regexp
4815 (concat
4816 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4817 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4818 "\\(--?"
4819 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4820 "Regular expression to match a timestamp time or time range.
4821 After a match, the following groups carry important information:
4822 0 the full match
4823 1 date plus weekday, for back referencing to make sure both times are on the same day
4824 2 the first time, range or not
4825 4 the second time, if it is a range.")
4827 (defconst org-startup-options
4828 '(("fold" org-startup-folded t)
4829 ("overview" org-startup-folded t)
4830 ("nofold" org-startup-folded nil)
4831 ("showall" org-startup-folded nil)
4832 ("showeverything" org-startup-folded showeverything)
4833 ("content" org-startup-folded content)
4834 ("indent" org-startup-indented t)
4835 ("noindent" org-startup-indented nil)
4836 ("hidestars" org-hide-leading-stars t)
4837 ("showstars" org-hide-leading-stars nil)
4838 ("odd" org-odd-levels-only t)
4839 ("oddeven" org-odd-levels-only nil)
4840 ("align" org-startup-align-all-tables t)
4841 ("noalign" org-startup-align-all-tables nil)
4842 ("inlineimages" org-startup-with-inline-images t)
4843 ("noinlineimages" org-startup-with-inline-images nil)
4844 ("latexpreview" org-startup-with-latex-preview t)
4845 ("nolatexpreview" org-startup-with-latex-preview nil)
4846 ("customtime" org-display-custom-times t)
4847 ("logdone" org-log-done time)
4848 ("lognotedone" org-log-done note)
4849 ("nologdone" org-log-done nil)
4850 ("lognoteclock-out" org-log-note-clock-out t)
4851 ("nolognoteclock-out" org-log-note-clock-out nil)
4852 ("logrepeat" org-log-repeat state)
4853 ("lognoterepeat" org-log-repeat note)
4854 ("logdrawer" org-log-into-drawer t)
4855 ("nologdrawer" org-log-into-drawer nil)
4856 ("logstatesreversed" org-log-states-order-reversed t)
4857 ("nologstatesreversed" org-log-states-order-reversed nil)
4858 ("nologrepeat" org-log-repeat nil)
4859 ("logreschedule" org-log-reschedule time)
4860 ("lognotereschedule" org-log-reschedule note)
4861 ("nologreschedule" org-log-reschedule nil)
4862 ("logredeadline" org-log-redeadline time)
4863 ("lognoteredeadline" org-log-redeadline note)
4864 ("nologredeadline" org-log-redeadline nil)
4865 ("logrefile" org-log-refile time)
4866 ("lognoterefile" org-log-refile note)
4867 ("nologrefile" org-log-refile nil)
4868 ("fninline" org-footnote-define-inline t)
4869 ("nofninline" org-footnote-define-inline nil)
4870 ("fnlocal" org-footnote-section nil)
4871 ("fnauto" org-footnote-auto-label t)
4872 ("fnprompt" org-footnote-auto-label nil)
4873 ("fnconfirm" org-footnote-auto-label confirm)
4874 ("fnplain" org-footnote-auto-label plain)
4875 ("fnadjust" org-footnote-auto-adjust t)
4876 ("nofnadjust" org-footnote-auto-adjust nil)
4877 ("constcgs" constants-unit-system cgs)
4878 ("constSI" constants-unit-system SI)
4879 ("noptag" org-tag-persistent-alist nil)
4880 ("hideblocks" org-hide-block-startup t)
4881 ("nohideblocks" org-hide-block-startup nil)
4882 ("beamer" org-startup-with-beamer-mode t)
4883 ("entitiespretty" org-pretty-entities t)
4884 ("entitiesplain" org-pretty-entities nil))
4885 "Variable associated with STARTUP options for org-mode.
4886 Each element is a list of three items: the startup options (as written
4887 in the #+STARTUP line), the corresponding variable, and the value to set
4888 this variable to if the option is found. An optional forth element PUSH
4889 means to push this value onto the list in the variable.")
4891 (defcustom org-group-tags t
4892 "When non-nil (the default), use group tags.
4893 This can be turned on/off through `org-toggle-tags-groups'."
4894 :group 'org-tags
4895 :group 'org-startup
4896 :type 'boolean)
4898 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4900 (defun org-toggle-tags-groups ()
4901 "Toggle support for group tags.
4902 Support for group tags is controlled by the option
4903 `org-group-tags', which is non-nil by default."
4904 (interactive)
4905 (setq org-group-tags (not org-group-tags))
4906 (cond ((and (derived-mode-p 'org-agenda-mode)
4907 org-group-tags)
4908 (org-agenda-redo))
4909 ((derived-mode-p 'org-mode)
4910 (let ((org-inhibit-startup t)) (org-mode))))
4911 (message "Groups tags support has been turned %s"
4912 (if org-group-tags "on" "off")))
4914 (defun org-set-regexps-and-options (&optional tags-only)
4915 "Precompute regular expressions used in the current buffer.
4916 When optional argument TAGS-ONLY is non-nil, only compute tags
4917 related expressions."
4918 (when (derived-mode-p 'org-mode)
4919 (let ((alist (org--setup-collect-keywords
4920 (org-make-options-regexp
4921 (append '("FILETAGS" "TAGS" "SETUPFILE")
4922 (and (not tags-only)
4923 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4924 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4925 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4926 ;; Startup options. Get this early since it does change
4927 ;; behavior for other options (e.g., tags).
4928 (let ((startup (cdr (assq 'startup alist))))
4929 (dolist (option startup)
4930 (let ((entry (assoc-string option org-startup-options t)))
4931 (when entry
4932 (let ((var (nth 1 entry))
4933 (val (nth 2 entry)))
4934 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4935 (unless (listp (symbol-value var))
4936 (set (make-local-variable var) nil))
4937 (add-to-list var val)))))))
4938 (setq-local org-file-tags
4939 (mapcar #'org-add-prop-inherited
4940 (cdr (assq 'filetags alist))))
4941 (setq org-current-tag-alist
4942 (append org-tag-persistent-alist
4943 (let ((tags (cdr (assq 'tags alist))))
4944 (if tags (org-tag-string-to-alist tags)
4945 org-tag-alist))))
4946 (setq org-tag-groups-alist
4947 (org-tag-alist-to-groups org-current-tag-alist))
4948 (unless tags-only
4949 ;; File properties.
4950 (setq-local org-file-properties (cdr (assq 'property alist)))
4951 ;; Archive location.
4952 (let ((archive (cdr (assq 'archive alist))))
4953 (when archive (setq-local org-archive-location archive)))
4954 ;; Category.
4955 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4956 (when cat
4957 (setq-local org-category (intern cat))
4958 (setq-local org-file-properties
4959 (org--update-property-plist
4960 "CATEGORY" cat org-file-properties))))
4961 ;; Columns.
4962 (let ((column (cdr (assq 'columns alist))))
4963 (when column (setq-local org-columns-default-format column)))
4964 ;; Constants.
4965 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4966 ;; Link abbreviations.
4967 (let ((links (cdr (assq 'link alist))))
4968 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4969 ;; Priorities.
4970 (let ((priorities (cdr (assq 'priorities alist))))
4971 (when priorities
4972 (setq-local org-highest-priority (nth 0 priorities))
4973 (setq-local org-lowest-priority (nth 1 priorities))
4974 (setq-local org-default-priority (nth 2 priorities))))
4975 ;; Scripts.
4976 (let ((scripts (assq 'scripts alist)))
4977 (when scripts
4978 (setq-local org-use-sub-superscripts (cdr scripts))))
4979 ;; TODO keywords.
4980 (setq-local org-todo-kwd-alist nil)
4981 (setq-local org-todo-key-alist nil)
4982 (setq-local org-todo-key-trigger nil)
4983 (setq-local org-todo-keywords-1 nil)
4984 (setq-local org-done-keywords nil)
4985 (setq-local org-todo-heads nil)
4986 (setq-local org-todo-sets nil)
4987 (setq-local org-todo-log-states nil)
4988 (let ((todo-sequences
4989 (or (nreverse (cdr (assq 'todo alist)))
4990 (let ((d (default-value 'org-todo-keywords)))
4991 (if (not (stringp (car d))) d
4992 ;; XXX: Backward compatibility code.
4993 (list (cons org-todo-interpretation d)))))))
4994 (dolist (sequence todo-sequences)
4995 (let* ((sequence (or (run-hook-with-args-until-success
4996 'org-todo-setup-filter-hook sequence)
4997 sequence))
4998 (sequence-type (car sequence))
4999 (keywords (cdr sequence))
5000 (sep (member "|" keywords))
5001 names alist)
5002 (dolist (k (remove "|" keywords))
5003 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5005 (error "Invalid TODO keyword %s" k))
5006 (let ((name (match-string 1 k))
5007 (key (match-string 2 k))
5008 (log (org-extract-log-state-settings k)))
5009 (push name names)
5010 (push (cons name (and key (string-to-char key))) alist)
5011 (when log (push log org-todo-log-states))))
5012 (let* ((names (nreverse names))
5013 (done (if sep (org-remove-keyword-keys (cdr sep))
5014 (last names)))
5015 (head (car names))
5016 (tail (list sequence-type head (car done) (org-last done))))
5017 (add-to-list 'org-todo-heads head 'append)
5018 (push names org-todo-sets)
5019 (setq org-done-keywords (append org-done-keywords done nil))
5020 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5021 (setq org-todo-key-alist
5022 (append org-todo-key-alist
5023 (and alist
5024 (append '((:startgroup))
5025 (nreverse alist)
5026 '((:endgroup))))))
5027 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5028 (setq org-todo-sets (nreverse org-todo-sets)
5029 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5030 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5031 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5032 ;; Compute the regular expressions and other local variables.
5033 ;; Using `org-outline-regexp-bol' would complicate them much,
5034 ;; because of the fixed white space at the end of that string.
5035 (unless org-done-keywords
5036 (setq org-done-keywords
5037 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5038 (setq org-not-done-keywords
5039 (org-delete-all org-done-keywords
5040 (copy-sequence org-todo-keywords-1))
5041 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5042 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5043 org-not-done-heading-regexp
5044 (format org-heading-keyword-regexp-format org-not-done-regexp)
5045 org-todo-line-regexp
5046 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5047 org-complex-heading-regexp
5048 (concat "^\\(\\*+\\)"
5049 "\\(?: +" org-todo-regexp "\\)?"
5050 "\\(?: +\\(\\[#.\\]\\)\\)?"
5051 "\\(?: +\\(.*?\\)\\)??"
5052 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5053 "[ \t]*$")
5054 org-complex-heading-regexp-format
5055 (concat "^\\(\\*+\\)"
5056 "\\(?: +" org-todo-regexp "\\)?"
5057 "\\(?: +\\(\\[#.\\]\\)\\)?"
5058 "\\(?: +"
5059 ;; Stats cookies can be stuck to body.
5060 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5061 "\\(%s\\)"
5062 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5063 "\\)"
5064 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5065 "[ \t]*$")
5066 org-todo-line-tags-regexp
5067 (concat "^\\(\\*+\\)"
5068 "\\(?: +" org-todo-regexp "\\)?"
5069 "\\(?: +\\(.*?\\)\\)??"
5070 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5071 "[ \t]*$"))
5072 (org-compute-latex-and-related-regexp)))))
5074 (defun org--setup-collect-keywords (regexp &optional files alist)
5075 "Return setup keywords values as an alist.
5077 REGEXP matches a subset of setup keywords. FILES is a list of
5078 file names already visited. It is used to avoid circular setup
5079 files. ALIST, when non-nil, is the alist computed so far.
5081 Return value contains the following keys: `archive', `category',
5082 `columns', `constants', `filetags', `link', `priorities',
5083 `property', `scripts', `startup', `tags' and `todo'."
5084 (org-with-wide-buffer
5085 (goto-char (point-min))
5086 (let ((case-fold-search t))
5087 (while (re-search-forward regexp nil t)
5088 (let ((element (org-element-at-point)))
5089 (when (eq (org-element-type element) 'keyword)
5090 (let ((key (org-element-property :key element))
5091 (value (org-element-property :value element)))
5092 (cond
5093 ((equal key "ARCHIVE")
5094 (when (org-string-nw-p value)
5095 (push (cons 'archive value) alist)))
5096 ((equal key "CATEGORY") (push (cons 'category value) alist))
5097 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5098 ((equal key "CONSTANTS")
5099 (let* ((constants (assq 'constants alist))
5100 (store (cdr constants)))
5101 (dolist (pair (org-split-string value))
5102 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5103 pair)
5104 (let* ((name (match-string 1 pair))
5105 (value (match-string 2 pair))
5106 (old (assoc name store)))
5107 (if old (setcdr old value)
5108 (push (cons name value) store)))))
5109 (if constants (setcdr constants store)
5110 (push (cons 'constants store) alist))))
5111 ((equal key "FILETAGS")
5112 (when (org-string-nw-p value)
5113 (let ((old (assq 'filetags alist))
5114 (new (apply #'nconc
5115 (mapcar (lambda (x) (org-split-string x ":"))
5116 (org-split-string value)))))
5117 (if old (setcdr old (append new (cdr old)))
5118 (push (cons 'filetags new) alist)))))
5119 ((equal key "LINK")
5120 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5121 (let ((links (assq 'link alist))
5122 (pair (cons (org-match-string-no-properties 1 value)
5123 (org-match-string-no-properties 2 value))))
5124 (if links (push pair (cdr links))
5125 (push (list 'link pair) alist)))))
5126 ((equal key "OPTIONS")
5127 (when (and (org-string-nw-p value)
5128 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5129 (push (cons 'scripts (read (match-string 1 value))) alist)))
5130 ((equal key "PRIORITIES")
5131 (push (cons 'priorities
5132 (let ((prio (org-split-string value)))
5133 (if (< (length prio) 3) '(?A ?C ?B)
5134 (mapcar #'string-to-char prio))))
5135 alist))
5136 ((equal key "PROPERTY")
5137 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5138 (let* ((property (assq 'property alist))
5139 (value (org--update-property-plist
5140 (org-match-string-no-properties 1 value)
5141 (org-match-string-no-properties 2 value)
5142 (cdr property))))
5143 (if property (setcdr property value)
5144 (push (cons 'property value) alist)))))
5145 ((equal key "STARTUP")
5146 (let ((startup (assq 'startup alist)))
5147 (if startup
5148 (setcdr startup
5149 (append (cdr startup) (org-split-string value)))
5150 (push (cons 'startup (org-split-string value)) alist))))
5151 ((equal key "TAGS")
5152 (let ((tag-cell (assq 'tags alist)))
5153 (if tag-cell
5154 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5155 (push (cons 'tags value) alist))))
5156 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5157 (let ((todo (assq 'todo alist))
5158 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5159 (org-split-string value))))
5160 (if todo (push value (cdr todo))
5161 (push (list 'todo value) alist))))
5162 ((equal key "SETUPFILE")
5163 (unless buffer-read-only ; Do not check in Gnus messages.
5164 (let ((f (and (org-string-nw-p value)
5165 (expand-file-name
5166 (org-remove-double-quotes value)))))
5167 (when (and f (file-readable-p f) (not (member f files)))
5168 (with-temp-buffer
5169 (setq default-directory (file-name-directory f))
5170 (insert-file-contents f)
5171 (setq alist
5172 ;; Fake Org mode to benefit from cache
5173 ;; without recurring needlessly.
5174 (let ((major-mode 'org-mode))
5175 (org--setup-collect-keywords
5176 regexp (cons f files) alist)))))))))))))))
5177 alist)
5179 (defun org-tag-string-to-alist (s)
5180 "Return tag alist associated to string S.
5181 S is a value for TAGS keyword or produced with
5182 `org-tag-alist-to-string'. Return value is an alist suitable for
5183 `org-tag-alist' or `org-tag-persistent-alist'."
5184 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5185 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5186 "\\|{.+?}\\)" ; regular expression
5187 "\\(?:(\\(.\\))\\)?\\'"))
5188 alist group-flag)
5189 (dolist (tokens lines (cdr (nreverse alist)))
5190 (push '(:newline) alist)
5191 (while tokens
5192 (let ((token (pop tokens)))
5193 (pcase token
5194 ("{"
5195 (push '(:startgroup) alist)
5196 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5197 ("}"
5198 (push '(:endgroup) alist)
5199 (setq group-flag nil))
5200 ("["
5201 (push '(:startgrouptag) alist)
5202 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5203 ("]"
5204 (push '(:endgrouptag) alist)
5205 (setq group-flag nil))
5206 (":"
5207 (push '(:grouptags) alist))
5208 ((guard (string-match tag-re token))
5209 (let ((tag (match-string 1 token))
5210 (key (and (match-beginning 2)
5211 (string-to-char (match-string 2 token)))))
5212 ;; Push all tags in groups, no matter if they already
5213 ;; appear somewhere else in the list.
5214 (when (or group-flag (not (assoc tag alist)))
5215 (push (cons tag key) alist))))))))))
5217 (defun org-tag-alist-to-string (alist &optional skip-key)
5218 "Return tag string associated to ALIST.
5220 ALIST is an alist, as defined in `org-tag-alist' or
5221 `org-tag-persistent-alist', or produced with
5222 `org-tag-string-to-alist'.
5224 Return value is a string suitable as a value for \"TAGS\"
5225 keyword.
5227 When optional argument SKIP-KEY is non-nil, skip selection keys
5228 next to tags."
5229 (mapconcat (lambda (token)
5230 (pcase token
5231 (`(:startgroup) "{")
5232 (`(:endgroup) "}")
5233 (`(:startgrouptag) "[")
5234 (`(:endgrouptag) "]")
5235 (`(:grouptags) ":")
5236 (`(:newline) "\\n")
5237 ((and
5238 (guard (not skip-key))
5239 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5240 (format "%s(%c)" tag key))
5241 (`(,(and tag (pred stringp)) . ,_) tag)
5242 (_ (user-error "Invalid tag token: %S" token))))
5243 alist
5244 " "))
5246 (defun org-tag-alist-to-groups (alist)
5247 "Return group alist from tag ALIST.
5248 ALIST is an alist, as defined in `org-tag-alist' or
5249 `org-tag-persistent-alist', or produced with
5250 `org-tag-string-to-alist'. Return value is an alist following
5251 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5252 a string, summarizing TAGS, as a list of strings."
5253 (let (groups group-status current-group)
5254 (dolist (token alist (nreverse groups))
5255 (pcase token
5256 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5257 (`(,(or :endgroup :endgrouptag))
5258 (when (eq group-status 'append)
5259 (push (nreverse current-group) groups))
5260 (setq group-status nil))
5261 (`(:grouptags) (setq group-status 'append))
5262 ((and `(,tag . ,_) (guard group-status))
5263 (if (eq group-status 'append) (push tag current-group)
5264 (setq current-group (list tag))))
5265 (_ nil)))))
5267 (defun org-file-contents (file &optional noerror)
5268 "Return the contents of FILE, as a string."
5269 (if (and file (file-readable-p file))
5270 (with-temp-buffer
5271 (insert-file-contents file)
5272 (buffer-string))
5273 (funcall (if noerror 'message 'error)
5274 "Cannot read file \"%s\"%s"
5275 file
5276 (let ((from (buffer-file-name (buffer-base-buffer))))
5277 (if from (concat " (referenced in file \"" from "\")") "")))))
5279 (defun org-extract-log-state-settings (x)
5280 "Extract the log state setting from a TODO keyword string.
5281 This will extract info from a string like \"WAIT(w@/!)\"."
5282 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5283 (let ((kw (match-string 1 x))
5284 (log1 (and (match-end 3) (match-string 3 x)))
5285 (log2 (and (match-end 4) (match-string 4 x))))
5286 (and (or log1 log2)
5287 (list kw
5288 (and log1 (if (equal log1 "!") 'time 'note))
5289 (and log2 (if (equal log2 "!") 'time 'note)))))))
5291 (defun org-remove-keyword-keys (list)
5292 "Remove a pair of parenthesis at the end of each string in LIST."
5293 (mapcar (lambda (x)
5294 (if (string-match "(.*)$" x)
5295 (substring x 0 (match-beginning 0))
5297 list))
5299 (defun org-assign-fast-keys (alist)
5300 "Assign fast keys to a keyword-key alist.
5301 Respect keys that are already there."
5302 (let (new e (alt ?0))
5303 (while (setq e (pop alist))
5304 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5305 (cdr e)) ;; Key already assigned.
5306 (push e new)
5307 (let ((clist (string-to-list (downcase (car e))))
5308 (used (append new alist)))
5309 (when (= (car clist) ?@)
5310 (pop clist))
5311 (while (and clist (rassoc (car clist) used))
5312 (pop clist))
5313 (unless clist
5314 (while (rassoc alt used)
5315 (cl-incf alt)))
5316 (push (cons (car e) (or (car clist) alt)) new))))
5317 (nreverse new)))
5319 ;;; Some variables used in various places
5321 (defvar org-window-configuration nil
5322 "Used in various places to store a window configuration.")
5323 (defvar org-selected-window nil
5324 "Used in various places to store a window configuration.")
5325 (defvar org-finish-function nil
5326 "Function to be called when `C-c C-c' is used.
5327 This is for getting out of special buffers like capture.")
5328 (defvar org-last-state)
5330 ;; Defined somewhere in this file, but used before definition.
5331 (defvar org-entities) ;; defined in org-entities.el
5332 (defvar org-struct-menu)
5333 (defvar org-org-menu)
5334 (defvar org-tbl-menu)
5336 ;;;; Define the Org-mode
5338 ;; We use a before-change function to check if a table might need
5339 ;; an update.
5340 (defvar org-table-may-need-update t
5341 "Indicates that a table might need an update.
5342 This variable is set by `org-before-change-function'.
5343 `org-table-align' sets it back to nil.")
5344 (defun org-before-change-function (_beg _end)
5345 "Every change indicates that a table might need an update."
5346 (setq org-table-may-need-update t))
5347 (defvar org-mode-map)
5348 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5349 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5350 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5351 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5352 (defvar org-table-buffer-is-an nil)
5354 (defvar bidi-paragraph-direction)
5355 (defvar buffer-face-mode-face)
5357 (require 'outline)
5358 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5359 (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"))
5360 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5362 ;; Other stuff we need.
5363 (require 'time-date)
5364 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5365 (require 'easymenu)
5366 (autoload 'easy-menu-add "easymenu")
5367 (require 'overlay)
5369 ;; (require 'org-macs) moved higher up in the file before it is first used
5370 (require 'org-entities)
5371 ;; (require 'org-compat) moved higher up in the file before it is first used
5372 (require 'org-faces)
5373 (require 'org-list)
5374 (require 'org-pcomplete)
5375 (require 'org-src)
5376 (require 'org-footnote)
5377 (require 'org-macro)
5379 ;; babel
5380 (require 'ob)
5382 ;;;###autoload
5383 (define-derived-mode org-mode outline-mode "Org"
5384 "Outline-based notes management and organizer, alias
5385 \"Carsten's outline-mode for keeping track of everything.\"
5387 Org-mode develops organizational tasks around a NOTES file which
5388 contains information about projects as plain text. Org-mode is
5389 implemented on top of outline-mode, which is ideal to keep the content
5390 of large files well structured. It supports ToDo items, deadlines and
5391 time stamps, which magically appear in the diary listing of the Emacs
5392 calendar. Tables are easily created with a built-in table editor.
5393 Plain text URL-like links connect to websites, emails (VM), Usenet
5394 messages (Gnus), BBDB entries, and any files related to the project.
5395 For printing and sharing of notes, an Org-mode file (or a part of it)
5396 can be exported as a structured ASCII or HTML file.
5398 The following commands are available:
5400 \\{org-mode-map}"
5402 ;; Get rid of Outline menus, they are not needed
5403 ;; Need to do this here because define-derived-mode sets up
5404 ;; the keymap so late. Still, it is a waste to call this each time
5405 ;; we switch another buffer into org-mode.
5406 (if (featurep 'xemacs)
5407 (when (boundp 'outline-mode-menu-heading)
5408 ;; Assume this is Greg's port, it uses easymenu
5409 (easy-menu-remove outline-mode-menu-heading)
5410 (easy-menu-remove outline-mode-menu-show)
5411 (easy-menu-remove outline-mode-menu-hide))
5412 (define-key org-mode-map [menu-bar headings] 'undefined)
5413 (define-key org-mode-map [menu-bar hide] 'undefined)
5414 (define-key org-mode-map [menu-bar show] 'undefined))
5416 (org-load-modules-maybe)
5417 (when (featurep 'xemacs)
5418 (easy-menu-add org-org-menu)
5419 (easy-menu-add org-tbl-menu))
5420 (org-install-agenda-files-menu)
5421 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5422 (add-to-invisibility-spec '(org-cwidth))
5423 (add-to-invisibility-spec '(org-hide-block . t))
5424 (when (featurep 'xemacs)
5425 (setq-local line-move-ignore-invisible t))
5426 (setq-local outline-regexp org-outline-regexp)
5427 (setq-local outline-level 'org-outline-level)
5428 (setq bidi-paragraph-direction 'left-to-right)
5429 (when (and org-ellipsis
5430 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5431 (fboundp 'make-glyph-code))
5432 (unless org-display-table
5433 (setq org-display-table (make-display-table)))
5434 (set-display-table-slot
5435 org-display-table 4
5436 (vconcat (mapcar
5437 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5438 org-ellipsis)))
5439 (if (stringp org-ellipsis) org-ellipsis "..."))))
5440 (setq buffer-display-table org-display-table))
5441 (org-set-regexps-and-options)
5442 (org-set-font-lock-defaults)
5443 (when (and org-tag-faces (not org-tags-special-faces-re))
5444 ;; tag faces set outside customize.... force initialization.
5445 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5446 ;; Calc embedded
5447 (setq-local calc-embedded-open-mode "# ")
5448 ;; Modify a few syntax entries
5449 (modify-syntax-entry ?@ "w")
5450 (modify-syntax-entry ?\" "\"")
5451 (modify-syntax-entry ?\\ "_")
5452 (modify-syntax-entry ?~ "_")
5453 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5454 ;; Activate before-change-function
5455 (setq-local org-table-may-need-update t)
5456 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5457 ;; Check for running clock before killing a buffer
5458 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5459 ;; Initialize macros templates.
5460 (org-macro-initialize-templates)
5461 ;; Initialize radio targets.
5462 (org-update-radio-target-regexp)
5463 ;; Indentation.
5464 (setq-local indent-line-function 'org-indent-line)
5465 (setq-local indent-region-function 'org-indent-region)
5466 ;; Filling and auto-filling.
5467 (org-setup-filling)
5468 ;; Comments.
5469 (org-setup-comments-handling)
5470 ;; Initialize cache.
5471 (org-element-cache-reset)
5472 ;; Beginning/end of defun
5473 (setq-local beginning-of-defun-function 'org-backward-element)
5474 (setq-local end-of-defun-function
5475 (lambda ()
5476 (if (not (org-at-heading-p))
5477 (org-forward-element)
5478 (org-forward-element)
5479 (forward-char -1))))
5480 ;; Next error for sparse trees
5481 (setq-local next-error-function 'org-occur-next-match)
5482 ;; Make sure dependence stuff works reliably, even for users who set it
5483 ;; too late :-(
5484 (if org-enforce-todo-dependencies
5485 (add-hook 'org-blocker-hook
5486 'org-block-todo-from-children-or-siblings-or-parent)
5487 (remove-hook 'org-blocker-hook
5488 'org-block-todo-from-children-or-siblings-or-parent))
5489 (if org-enforce-todo-checkbox-dependencies
5490 (add-hook 'org-blocker-hook
5491 'org-block-todo-from-checkboxes)
5492 (remove-hook 'org-blocker-hook
5493 'org-block-todo-from-checkboxes))
5495 ;; Align options lines
5496 (setq-local
5497 align-mode-rules-list
5498 '((org-in-buffer-settings
5499 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5500 (modes . '(org-mode)))))
5502 ;; Imenu
5503 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5505 ;; Make isearch reveal context
5506 (setq-local outline-isearch-open-invisible-function
5507 (lambda (&rest _) (org-show-context 'isearch)))
5509 ;; Setup the pcomplete hooks
5510 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5511 (setq-local pcomplete-command-name-function 'org-command-at-point)
5512 (setq-local pcomplete-default-completion-function 'ignore)
5513 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5514 (setq-local pcomplete-termination-string "")
5515 (setq-local buffer-face-mode-face 'org-default)
5517 ;; If empty file that did not turn on Org mode automatically, make
5518 ;; it to.
5519 (when (and org-insert-mode-line-in-empty-file
5520 (org-called-interactively-p 'any)
5521 (= (point-min) (point-max)))
5522 (insert "# -*- mode: org -*-\n\n"))
5523 (unless org-inhibit-startup
5524 (org-unmodified
5525 (when org-startup-with-beamer-mode (org-beamer-mode))
5526 (when org-startup-align-all-tables
5527 (org-table-map-tables #'org-table-align t))
5528 (when org-startup-with-inline-images (org-display-inline-images))
5529 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5530 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5531 (when org-startup-truncated (setq truncate-lines t))
5532 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5533 (org-refresh-effort-properties)))
5534 ;; Try to set `org-hide' face correctly.
5535 (let ((foreground (org-find-invisible-foreground)))
5536 (when foreground
5537 (set-face-foreground 'org-hide foreground))))
5539 ;; Update `customize-package-emacs-version-alist'
5540 (add-to-list 'customize-package-emacs-version-alist
5541 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5542 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5543 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5545 (defvar org-mode-transpose-word-syntax-table
5546 (let ((st (make-syntax-table text-mode-syntax-table)))
5547 (dolist (c org-emphasis-alist st)
5548 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5550 (when (fboundp 'abbrev-table-put)
5551 (abbrev-table-put org-mode-abbrev-table
5552 :parents (list text-mode-abbrev-table)))
5554 (defun org-find-invisible-foreground ()
5555 (let ((candidates (remove
5556 "unspecified-bg"
5557 (nconc
5558 (list (face-background 'default)
5559 (face-background 'org-default))
5560 (mapcar
5561 (lambda (alist)
5562 (when (boundp alist)
5563 (cdr (assoc 'background-color (symbol-value alist)))))
5564 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5565 (list (face-foreground 'org-hide))))))
5566 (car (remove nil candidates))))
5568 (defun org-current-time (&optional rounding-minutes past)
5569 "Current time, possibly rounded to ROUNDING-MINUTES.
5570 When ROUNDING-MINUTES is not an integer, fall back on the car of
5571 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5572 the rounding returns a past time."
5573 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5574 (car org-time-stamp-rounding-minutes)))
5575 (time (decode-time)) res)
5576 (if (< r 1)
5577 (current-time)
5578 (setq res
5579 (apply 'encode-time
5580 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5581 (nthcdr 2 time))))
5582 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5583 (seconds-to-time (- (org-float-time res) (* r 60)))
5584 res))))
5586 (defun org-today ()
5587 "Return today date, considering `org-extend-today-until'."
5588 (time-to-days
5589 (time-subtract (current-time)
5590 (list 0 (* 3600 org-extend-today-until) 0))))
5592 ;;;; Font-Lock stuff, including the activators
5594 (defvar org-mouse-map (make-sparse-keymap))
5595 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5596 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5597 (when org-mouse-1-follows-link
5598 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5599 (when org-tab-follows-link
5600 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5601 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5603 (require 'font-lock)
5605 (defconst org-non-link-chars "]\t\n\r<>")
5606 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5607 "file+sys" "news" "shell" "elisp" "doi" "message"
5608 "help"))
5609 (defvar org-link-types-re nil
5610 "Matches a link that has a url-like prefix like \"http:\"")
5611 (defvar org-link-re-with-space nil
5612 "Matches a link with spaces, optional angular brackets around it.")
5613 (defvar org-link-re-with-space2 nil
5614 "Matches a link with spaces, optional angular brackets around it.")
5615 (defvar org-link-re-with-space3 nil
5616 "Matches a link with spaces, only for internal part in bracket links.")
5617 (defvar org-angle-link-re nil
5618 "Matches link with angular brackets, spaces are allowed.")
5619 (defvar org-plain-link-re nil
5620 "Matches plain link, without spaces.")
5621 (defvar org-bracket-link-regexp nil
5622 "Matches a link in double brackets.")
5623 (defvar org-bracket-link-analytic-regexp nil
5624 "Regular expression used to analyze links.
5625 Here is what the match groups contain after a match:
5626 1: http:
5627 2: http
5628 3: path
5629 4: [desc]
5630 5: desc")
5631 (defvar org-bracket-link-analytic-regexp++ nil
5632 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5633 (defvar org-any-link-re nil
5634 "Regular expression matching any link.")
5636 (defconst org-match-sexp-depth 3
5637 "Number of stacked braces for sub/superscript matching.")
5639 (defun org-create-multibrace-regexp (left right n)
5640 "Create a regular expression which will match a balanced sexp.
5641 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5642 as single character strings.
5643 The regexp returned will match the entire expression including the
5644 delimiters. It will also define a single group which contains the
5645 match except for the outermost delimiters. The maximum depth of
5646 stacked delimiters is N. Escaping delimiters is not possible."
5647 (let* ((nothing (concat "[^" left right "]*?"))
5648 (or "\\|")
5649 (re nothing)
5650 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5651 (while (> n 1)
5652 (setq n (1- n)
5653 re (concat re or next)
5654 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5655 (concat left "\\(" re "\\)" right)))
5657 (defconst org-match-substring-regexp
5658 (concat
5659 "\\(\\S-\\)\\([_^]\\)\\("
5660 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5661 "\\|"
5662 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5663 "\\|"
5664 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5665 "The regular expression matching a sub- or superscript.")
5667 (defconst org-match-substring-with-braces-regexp
5668 (concat
5669 "\\(\\S-\\)\\([_^]\\)"
5670 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5671 "The regular expression matching a sub- or superscript, forcing braces.")
5673 (defun org-make-link-regexps ()
5674 "Update the link regular expressions.
5675 This should be called after the variable `org-link-types' has changed."
5676 (let ((types-re (regexp-opt org-link-types t)))
5677 (setq org-link-types-re
5678 (concat "\\`" types-re ":")
5679 org-link-re-with-space
5680 (concat "<?" types-re ":"
5681 "\\([^" org-non-link-chars " ]"
5682 "[^" org-non-link-chars "]*"
5683 "[^" org-non-link-chars " ]\\)>?")
5684 org-link-re-with-space2
5685 (concat "<?" types-re ":"
5686 "\\([^" org-non-link-chars " ]"
5687 "[^\t\n\r]*"
5688 "[^" org-non-link-chars " ]\\)>?")
5689 org-link-re-with-space3
5690 (concat "<?" types-re ":"
5691 "\\([^" org-non-link-chars " ]"
5692 "[^\t\n\r]*\\)")
5693 org-angle-link-re
5694 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5695 types-re)
5696 org-plain-link-re
5697 (concat
5698 "\\<" types-re ":"
5699 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5700 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5701 org-bracket-link-regexp
5702 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5703 org-bracket-link-analytic-regexp
5704 (concat
5705 "\\[\\["
5706 "\\(" types-re ":\\)?"
5707 "\\([^]]+\\)"
5708 "\\]"
5709 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5710 "\\]")
5711 org-bracket-link-analytic-regexp++
5712 (concat
5713 "\\[\\["
5714 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5715 "\\([^]]+\\)"
5716 "\\]"
5717 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5718 "\\]")
5719 org-any-link-re
5720 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5721 org-angle-link-re "\\)\\|\\("
5722 org-plain-link-re "\\)"))))
5724 (org-make-link-regexps)
5726 (defvar org-emph-face nil)
5728 (defun org-do-emphasis-faces (limit)
5729 "Run through the buffer and emphasize strings."
5730 (let (rtn a)
5731 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5732 (let* ((border (char-after (match-beginning 3)))
5733 (bre (regexp-quote (char-to-string border))))
5734 (when (and (not (= border (char-after (match-beginning 4))))
5735 (not (string-match-p (concat bre ".*" bre)
5736 (replace-regexp-in-string
5737 "\n" " "
5738 (substring (match-string 2) 1 -1)))))
5739 (setq rtn t)
5740 (setq a (assoc (match-string 3) org-emphasis-alist))
5741 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5742 'face
5743 (nth 1 a))
5744 (and (nth 2 a)
5745 (org-remove-flyspell-overlays-in
5746 (match-beginning 0) (match-end 0)))
5747 (add-text-properties (match-beginning 2) (match-end 2)
5748 '(font-lock-multiline t org-emphasis t))
5749 (when org-hide-emphasis-markers
5750 (add-text-properties (match-end 4) (match-beginning 5)
5751 '(invisible org-link))
5752 (add-text-properties (match-beginning 3) (match-end 3)
5753 '(invisible org-link)))))
5754 (goto-char (1+ (match-beginning 0))))
5755 rtn))
5757 (defun org-emphasize (&optional char)
5758 "Insert or change an emphasis, i.e. a font like bold or italic.
5759 If there is an active region, change that region to a new emphasis.
5760 If there is no region, just insert the marker characters and position
5761 the cursor between them.
5762 CHAR should be the marker character. If it is a space, it means to
5763 remove the emphasis of the selected region.
5764 If CHAR is not given (for example in an interactive call) it will be
5765 prompted for."
5766 (interactive)
5767 (let ((erc org-emphasis-regexp-components)
5768 (string "") beg end move s)
5769 (if (org-region-active-p)
5770 (setq beg (region-beginning)
5771 end (region-end)
5772 string (buffer-substring beg end))
5773 (setq move t))
5775 (unless char
5776 (message "Emphasis marker or tag: [%s]"
5777 (mapconcat #'car org-emphasis-alist ""))
5778 (setq char (read-char-exclusive)))
5779 (if (equal char ?\s)
5780 (setq s ""
5781 move nil)
5782 (unless (assoc (char-to-string char) org-emphasis-alist)
5783 (user-error "No such emphasis marker: \"%c\"" char))
5784 (setq s (char-to-string char)))
5785 (while (and (> (length string) 1)
5786 (equal (substring string 0 1) (substring string -1))
5787 (assoc (substring string 0 1) org-emphasis-alist))
5788 (setq string (substring string 1 -1)))
5789 (setq string (concat s string s))
5790 (when beg (delete-region beg end))
5791 (unless (or (bolp)
5792 (string-match (concat "[" (nth 0 erc) "\n]")
5793 (char-to-string (char-before (point)))))
5794 (insert " "))
5795 (unless (or (eobp)
5796 (string-match (concat "[" (nth 1 erc) "\n]")
5797 (char-to-string (char-after (point)))))
5798 (insert " ") (backward-char 1))
5799 (insert string)
5800 (and move (backward-char 1))))
5802 (defconst org-nonsticky-props
5803 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5805 (defsubst org-rear-nonsticky-at (pos)
5806 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5808 (defun org-activate-plain-links (limit)
5809 "Add link properties for plain links."
5810 (when (and (re-search-forward org-plain-link-re limit t)
5811 (not (org-in-src-block-p)))
5812 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5813 'face))
5814 (link (org-match-string-no-properties 0)))
5815 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5816 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5817 (add-text-properties (match-beginning 0) (match-end 0)
5818 (list 'mouse-face 'highlight
5819 'face 'org-link
5820 'htmlize-link `(:uri ,link)
5821 'keymap org-mouse-map))
5822 (org-rear-nonsticky-at (match-end 0))
5823 t))))
5825 (defun org-activate-code (limit)
5826 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5827 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5828 (remove-text-properties (match-beginning 0) (match-end 0)
5829 '(display t invisible t intangible t))
5832 (defcustom org-src-fontify-natively t
5833 "When non-nil, fontify code in code blocks."
5834 :type 'boolean
5835 :version "24.4"
5836 :package-version '(Org . "8.3")
5837 :group 'org-appearance
5838 :group 'org-babel)
5840 (defcustom org-allow-promoting-top-level-subtree nil
5841 "When non-nil, allow promoting a top level subtree.
5842 The leading star of the top level headline will be replaced
5843 by a #."
5844 :type 'boolean
5845 :version "24.1"
5846 :group 'org-appearance)
5848 (defun org-fontify-meta-lines-and-blocks (limit)
5849 (condition-case nil
5850 (org-fontify-meta-lines-and-blocks-1 limit)
5851 (error (message "org-mode fontification error in %S at %d"
5852 (current-buffer)
5853 (line-number-at-pos)))))
5855 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5856 "Fontify #+ lines and blocks."
5857 (let ((case-fold-search t))
5858 (when (re-search-forward
5859 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5860 limit t)
5861 (let ((beg (match-beginning 0))
5862 (block-start (match-end 0))
5863 (block-end nil)
5864 (lang (match-string 7))
5865 (beg1 (line-beginning-position 2))
5866 (dc1 (downcase (match-string 2)))
5867 (dc3 (downcase (match-string 3)))
5868 end end1 quoting block-type)
5869 (cond
5870 ((and (match-end 4) (equal dc3 "+begin"))
5871 ;; Truly a block
5872 (setq block-type (downcase (match-string 5))
5873 quoting (member block-type org-protecting-blocks))
5874 (when (re-search-forward
5875 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5876 nil t) ;; on purpose, we look further than LIMIT
5877 (setq end (min (point-max) (match-end 0))
5878 end1 (min (point-max) (1- (match-beginning 0))))
5879 (setq block-end (match-beginning 0))
5880 (when quoting
5881 (org-remove-flyspell-overlays-in beg1 end1)
5882 (remove-text-properties beg end
5883 '(display t invisible t intangible t)))
5884 (add-text-properties
5885 beg end '(font-lock-fontified t font-lock-multiline t))
5886 (add-text-properties beg beg1 '(face org-meta-line))
5887 (org-remove-flyspell-overlays-in beg beg1)
5888 (add-text-properties ; For end_src
5889 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5890 (org-remove-flyspell-overlays-in end1 end)
5891 (cond
5892 ((and lang (not (string= lang "")) org-src-fontify-natively)
5893 (org-src-font-lock-fontify-block lang block-start block-end)
5894 (add-text-properties beg1 block-end '(src-block t)))
5895 (quoting
5896 (add-text-properties beg1 (min (point-max) (1+ end1))
5897 '(face org-block))) ; end of source block
5898 ((not org-fontify-quote-and-verse-blocks))
5899 ((string= block-type "quote")
5900 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5901 ((string= block-type "verse")
5902 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5903 (add-text-properties beg beg1 '(face org-block-begin-line))
5904 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5905 '(face org-block-end-line))
5907 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5908 (org-remove-flyspell-overlays-in
5909 (match-beginning 0)
5910 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5911 (add-text-properties
5912 beg (match-end 3)
5913 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5914 '(font-lock-fontified t invisible t)
5915 '(font-lock-fontified t face org-document-info-keyword)))
5916 (add-text-properties
5917 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5918 (if (string-equal dc1 "+title:")
5919 '(font-lock-fontified t face org-document-title)
5920 '(font-lock-fontified t face org-document-info))))
5921 ((equal dc1 "+caption:")
5922 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5923 (remove-text-properties (match-beginning 0) (match-end 0)
5924 '(display t invisible t intangible t))
5925 (add-text-properties (match-beginning 1) (match-end 3)
5926 '(font-lock-fontified t face org-meta-line))
5927 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5928 '(font-lock-fontified t face org-block))
5930 ((member dc3 '(" " ""))
5931 (org-remove-flyspell-overlays-in beg (match-end 0))
5932 (add-text-properties
5933 beg (match-end 0)
5934 '(font-lock-fontified t face font-lock-comment-face)))
5935 (t ;; just any other in-buffer setting, but not indented
5936 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5937 (remove-text-properties (match-beginning 0) (match-end 0)
5938 '(display t invisible t intangible t))
5939 (add-text-properties beg (match-end 0)
5940 '(font-lock-fontified t face org-meta-line))
5941 t))))))
5943 (defun org-fontify-drawers (limit)
5944 "Fontify drawers."
5945 (when (re-search-forward org-drawer-regexp limit t)
5946 (add-text-properties
5947 (match-beginning 0) (match-end 0)
5948 '(font-lock-fontified t face org-special-keyword))
5949 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5952 (defun org-fontify-macros (limit)
5953 "Fontify macros."
5954 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5955 (add-text-properties
5956 (match-beginning 0) (match-end 0)
5957 '(font-lock-fontified t face org-macro))
5958 (when org-hide-macro-markers
5959 (add-text-properties (match-end 2) (match-beginning 2)
5960 '(invisible t))
5961 (add-text-properties (match-beginning 1) (match-end 1)
5962 '(invisible t)))
5963 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5966 (defun org-activate-angle-links (limit)
5967 "Add text properties for angle links."
5968 (when (and (re-search-forward org-angle-link-re limit t)
5969 (not (org-in-src-block-p)))
5970 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5971 (add-text-properties (match-beginning 0) (match-end 0)
5972 (list 'mouse-face 'highlight
5973 'keymap org-mouse-map
5974 'font-lock-multiline t))
5975 (org-rear-nonsticky-at (match-end 0))
5978 (defun org-activate-footnote-links (limit)
5979 "Add text properties for footnotes."
5980 (let ((fn (org-footnote-next-reference-or-definition limit)))
5981 (when fn
5982 (let* ((beg (nth 1 fn))
5983 (end (nth 2 fn))
5984 (label (car fn))
5985 (referencep (/= (line-beginning-position) beg)))
5986 (when (and referencep (nth 3 fn))
5987 (save-excursion
5988 (goto-char beg)
5989 (search-forward (or label "fn:"))
5990 (org-remove-flyspell-overlays-in beg (match-end 0))))
5991 (add-text-properties beg end
5992 (list 'mouse-face 'highlight
5993 'keymap org-mouse-map
5994 'help-echo
5995 (if referencep "Footnote reference"
5996 "Footnote definition")
5997 'font-lock-fontified t
5998 'font-lock-multiline t
5999 'face 'org-footnote))))))
6001 (defun org-activate-bracket-links (limit)
6002 "Add text properties for bracketed links."
6003 (when (and (re-search-forward org-bracket-link-regexp limit t)
6004 (not (org-in-src-block-p)))
6005 (let* ((hl (org-match-string-no-properties 1))
6006 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6007 (ip (org-maybe-intangible
6008 (list 'invisible 'org-link
6009 'keymap org-mouse-map 'mouse-face 'highlight
6010 'font-lock-multiline t 'help-echo help
6011 'htmlize-link `(:uri ,hl))))
6012 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6013 'font-lock-multiline t 'help-echo help
6014 'htmlize-link `(:uri ,hl))))
6015 ;; We need to remove the invisible property here. Table narrowing
6016 ;; may have made some of this invisible.
6017 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6018 (remove-text-properties (match-beginning 0) (match-end 0)
6019 '(invisible nil))
6020 (if (match-end 3)
6021 (progn
6022 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6023 (org-rear-nonsticky-at (match-beginning 3))
6024 (add-text-properties (match-beginning 3) (match-end 3) vp)
6025 (org-rear-nonsticky-at (match-end 3))
6026 (add-text-properties (match-end 3) (match-end 0) ip)
6027 (org-rear-nonsticky-at (match-end 0)))
6028 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6029 (org-rear-nonsticky-at (match-beginning 1))
6030 (add-text-properties (match-beginning 1) (match-end 1) vp)
6031 (org-rear-nonsticky-at (match-end 1))
6032 (add-text-properties (match-end 1) (match-end 0) ip)
6033 (org-rear-nonsticky-at (match-end 0)))
6034 t)))
6036 (defun org-activate-dates (limit)
6037 "Add text properties for dates."
6038 (when (and (re-search-forward org-tsr-regexp-both limit t)
6039 (not (equal (char-before (match-beginning 0)) 91)))
6040 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6041 (add-text-properties (match-beginning 0) (match-end 0)
6042 (list 'mouse-face 'highlight
6043 'keymap org-mouse-map))
6044 (org-rear-nonsticky-at (match-end 0))
6045 (when org-display-custom-times
6046 (if (match-end 3)
6047 (org-display-custom-time (match-beginning 3) (match-end 3))
6048 (org-display-custom-time (match-beginning 1) (match-end 1))))
6051 (defvar-local org-target-link-regexp nil
6052 "Regular expression matching radio targets in plain text.")
6054 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6055 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6056 border border border))
6057 "Regular expression matching a link target.")
6059 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6060 "Regular expression matching a radio target.")
6062 (defconst org-any-target-regexp
6063 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6064 "Regular expression matching any target.")
6066 (defun org-activate-target-links (limit)
6067 "Add text properties for target matches."
6068 (when org-target-link-regexp
6069 (let ((case-fold-search t))
6070 (when (re-search-forward org-target-link-regexp limit t)
6071 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6072 (add-text-properties (match-beginning 1) (match-end 1)
6073 (list 'mouse-face 'highlight
6074 'keymap org-mouse-map
6075 'help-echo "Radio target link"
6076 'org-linked-text t))
6077 (org-rear-nonsticky-at (match-end 1))
6078 t))))
6080 (defun org-update-radio-target-regexp ()
6081 "Find all radio targets in this file and update the regular expression.
6082 Also refresh fontification if needed."
6083 (interactive)
6084 (let ((old-regexp org-target-link-regexp)
6085 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6086 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6087 (targets
6088 (org-with-wide-buffer
6089 (goto-char (point-min))
6090 (let (rtn)
6091 (while (re-search-forward org-radio-target-regexp nil t)
6092 ;; Make sure point is really within the object.
6093 (backward-char)
6094 (let ((obj (org-element-context)))
6095 (when (eq (org-element-type obj) 'radio-target)
6096 (cl-pushnew (org-element-property :value obj) rtn
6097 :test #'equal))))
6098 rtn))))
6099 (setq org-target-link-regexp
6100 (and targets
6101 (concat before-re
6102 (mapconcat
6103 (lambda (x)
6104 (replace-regexp-in-string
6105 " +" "\\s-+" (regexp-quote x) t t))
6106 targets
6107 "\\|")
6108 after-re)))
6109 (unless (equal old-regexp org-target-link-regexp)
6110 ;; Clean-up cache.
6111 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6112 ((not org-target-link-regexp) old-regexp)
6114 (concat before-re
6115 (mapconcat
6116 (lambda (re)
6117 (substring re (length before-re)
6118 (- (length after-re))))
6119 (list old-regexp org-target-link-regexp)
6120 "\\|")
6121 after-re)))))
6122 (org-with-wide-buffer
6123 (goto-char (point-min))
6124 (while (re-search-forward regexp nil t)
6125 (org-element-cache-refresh (match-beginning 1)))))
6126 ;; Re fontify buffer.
6127 (when (memq 'radio org-highlight-links)
6128 (org-restart-font-lock)))))
6130 (defun org-hide-wide-columns (limit)
6131 (let (s e)
6132 (setq s (text-property-any (point) (or limit (point-max))
6133 'org-cwidth t))
6134 (when s
6135 (setq e (next-single-property-change s 'org-cwidth))
6136 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6137 (goto-char e)
6138 t)))
6140 (defvar org-latex-and-related-regexp nil
6141 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6143 (defun org-compute-latex-and-related-regexp ()
6144 "Compute regular expression for LaTeX, entities and sub/superscript.
6145 Result depends on variable `org-highlight-latex-and-related'."
6146 (setq-local
6147 org-latex-and-related-regexp
6148 (let* ((re-sub
6149 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6150 ((eq org-use-sub-superscripts '{})
6151 (list org-match-substring-with-braces-regexp))
6152 (org-use-sub-superscripts (list org-match-substring-regexp))))
6153 (re-latex
6154 (when (memq 'latex org-highlight-latex-and-related)
6155 (let ((matchers (plist-get org-format-latex-options :matchers)))
6156 (delq nil
6157 (mapcar (lambda (x)
6158 (and (member (car x) matchers) (nth 1 x)))
6159 org-latex-regexps)))))
6160 (re-entities
6161 (when (memq 'entities org-highlight-latex-and-related)
6162 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6163 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6165 (defun org-do-latex-and-related (limit)
6166 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6167 LIMIT bounds the search for syntax to highlight. Stop at first
6168 highlighted object, if any. Return t if some highlighting was
6169 done, nil otherwise."
6170 (when (org-string-nw-p org-latex-and-related-regexp)
6171 (catch 'found
6172 (while (re-search-forward org-latex-and-related-regexp limit t)
6173 (unless
6174 (cl-some
6175 (lambda (f)
6176 (memq f '(org-code org-verbatim underline org-special-keyword)))
6177 (save-excursion
6178 (goto-char (1+ (match-beginning 0)))
6179 (face-at-point nil t)))
6180 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6181 '(?_ ?^))
6183 0)))
6184 (font-lock-prepend-text-property
6185 (+ offset (match-beginning 0)) (match-end 0)
6186 'face 'org-latex-and-related)
6187 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6188 '(font-lock-multiline t)))
6189 (throw 'found t)))
6190 nil)))
6192 (defun org-restart-font-lock ()
6193 "Restart `font-lock-mode', to force refontification."
6194 (when (and (boundp 'font-lock-mode) font-lock-mode)
6195 (font-lock-mode -1)
6196 (font-lock-mode 1)))
6198 (defun org-activate-tags (limit)
6199 (when (re-search-forward
6200 (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") limit t)
6201 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6202 (add-text-properties (match-beginning 1) (match-end 1)
6203 (list 'mouse-face 'highlight
6204 'keymap org-mouse-map))
6205 (org-rear-nonsticky-at (match-end 1))
6208 (defun org-outline-level ()
6209 "Compute the outline level of the heading at point.
6211 If this is called at a normal headline, the level is the number
6212 of stars. Use `org-reduced-level' to remove the effect of
6213 `org-odd-levels'. Unlike to `org-current-level', this function
6214 takes into consideration inlinetasks."
6215 (org-with-wide-buffer
6216 (end-of-line)
6217 (if (re-search-backward org-outline-regexp-bol nil t)
6218 (1- (- (match-end 0) (match-beginning 0)))
6219 0)))
6221 (defvar org-font-lock-keywords nil)
6223 (defsubst org-re-property (property &optional literal allow-null value)
6224 "Return a regexp matching a PROPERTY line.
6226 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6227 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6228 non-nil, match properties even without a value.
6230 Match group 3 is set to the value when it exists. If there is no
6231 value and ALLOW-NULL is non-nil, it is set to the empty string.
6233 With optional argument VALUE, match only property lines with
6234 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6235 unless LITERAL is non-nil."
6236 (concat
6237 "^\\(?4:[ \t]*\\)"
6238 (format "\\(?1::\\(?2:%s\\):\\)"
6239 (if literal property (regexp-quote property)))
6240 (cond (value
6241 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6242 (if literal value (regexp-quote value))))
6243 (allow-null
6244 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6246 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6248 (defconst org-property-re
6249 (org-re-property "\\S-+" 'literal t)
6250 "Regular expression matching a property line.
6251 There are four matching groups:
6252 1: :PROPKEY: including the leading and trailing colon,
6253 2: PROPKEY without the leading and trailing colon,
6254 3: PROPVAL without leading or trailing spaces,
6255 4: the indentation of the current line,
6256 5: trailing whitespace.")
6258 (defvar org-font-lock-hook nil
6259 "Functions to be called for special font lock stuff.")
6261 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6263 (defvar org-font-lock-set-keywords-hook nil
6264 "Functions that can manipulate `org-font-lock-extra-keywords'.
6265 This is called after `org-font-lock-extra-keywords' is defined, but before
6266 it is installed to be used by font lock. This can be useful if something
6267 needs to be inserted at a specific position in the font-lock sequence.")
6269 (defun org-font-lock-hook (limit)
6270 "Run `org-font-lock-hook' within LIMIT."
6271 (run-hook-with-args 'org-font-lock-hook limit))
6273 (defun org-set-font-lock-defaults ()
6274 "Set font lock defaults for the current buffer."
6275 (let* ((em org-fontify-emphasized-text)
6276 (lk org-highlight-links)
6277 (org-font-lock-extra-keywords
6278 (list
6279 ;; Call the hook
6280 '(org-font-lock-hook)
6281 ;; Headlines
6282 `(,(if org-fontify-whole-heading-line
6283 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6284 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6285 (1 (org-get-level-face 1))
6286 (2 (org-get-level-face 2))
6287 (3 (org-get-level-face 3)))
6288 ;; Table lines
6289 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6290 (1 'org-table t))
6291 ;; Table internals
6292 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6293 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6294 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6295 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6296 ;; Drawers
6297 '(org-fontify-drawers)
6298 ;; Properties
6299 (list org-property-re
6300 '(1 'org-special-keyword t)
6301 '(3 'org-property-value t))
6302 ;; Links
6303 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6304 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6305 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6306 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6307 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6308 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6309 (when (memq 'footnote lk) '(org-activate-footnote-links))
6310 ;; Targets.
6311 (list org-any-target-regexp '(0 'org-target t))
6312 ;; Diary sexps.
6313 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6314 ;; Macro
6315 '(org-fontify-macros)
6316 '(org-hide-wide-columns (0 nil append))
6317 ;; TODO keyword
6318 (list (format org-heading-keyword-regexp-format
6319 org-todo-regexp)
6320 '(2 (org-get-todo-face 2) t))
6321 ;; DONE
6322 (if org-fontify-done-headline
6323 (list (format org-heading-keyword-regexp-format
6324 (concat
6325 "\\(?:"
6326 (mapconcat 'regexp-quote org-done-keywords "\\|")
6327 "\\)"))
6328 '(2 'org-headline-done t))
6329 nil)
6330 ;; Priorities
6331 '(org-font-lock-add-priority-faces)
6332 ;; Tags
6333 '(org-font-lock-add-tag-faces)
6334 ;; Tags groups
6335 (when (and org-group-tags org-tag-groups-alist)
6336 (list (concat org-outline-regexp-bol ".+\\(:"
6337 (regexp-opt (mapcar 'car org-tag-groups-alist))
6338 ":\\).*$")
6339 '(1 'org-tag-group prepend)))
6340 ;; Special keywords
6341 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6342 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6343 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6344 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6345 ;; Emphasis
6346 (when em
6347 (if (featurep 'xemacs)
6348 '(org-do-emphasis-faces (0 nil append))
6349 '(org-do-emphasis-faces)))
6350 ;; Checkboxes
6351 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6352 1 'org-checkbox prepend)
6353 (when (cdr (assq 'checkbox org-list-automatic-rules))
6354 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6355 (0 (org-get-checkbox-statistics-face) t)))
6356 ;; Description list items
6357 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6358 1 'org-list-dt prepend)
6359 ;; ARCHIVEd headings
6360 (list (concat
6361 org-outline-regexp-bol
6362 "\\(.*:" org-archive-tag ":.*\\)")
6363 '(1 'org-archived prepend))
6364 ;; Specials
6365 '(org-do-latex-and-related)
6366 '(org-fontify-entities)
6367 '(org-raise-scripts)
6368 ;; Code
6369 '(org-activate-code (1 'org-code t))
6370 ;; COMMENT
6371 (list (format
6372 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6373 org-todo-regexp
6374 org-comment-string)
6375 '(9 'org-special-keyword t))
6376 ;; Blocks and meta lines
6377 '(org-fontify-meta-lines-and-blocks))))
6378 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6379 (run-hooks 'org-font-lock-set-keywords-hook)
6380 ;; Now set the full font-lock-keywords
6381 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6382 (setq-local font-lock-defaults
6383 '(org-font-lock-keywords t nil nil backward-paragraph))
6384 (kill-local-variable 'font-lock-keywords) nil))
6386 (defun org-toggle-pretty-entities ()
6387 "Toggle the composition display of entities as UTF8 characters."
6388 (interactive)
6389 (setq-local org-pretty-entities (not org-pretty-entities))
6390 (org-restart-font-lock)
6391 (if org-pretty-entities
6392 (message "Entities are now displayed as UTF8 characters")
6393 (save-restriction
6394 (widen)
6395 (org-decompose-region (point-min) (point-max))
6396 (message "Entities are now displayed as plain text"))))
6398 (defvar-local org-custom-properties-overlays nil
6399 "List of overlays used for custom properties.")
6401 (defun org-toggle-custom-properties-visibility ()
6402 "Display or hide properties in `org-custom-properties'."
6403 (interactive)
6404 (if org-custom-properties-overlays
6405 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6406 (setq org-custom-properties-overlays nil))
6407 (when org-custom-properties
6408 (org-with-wide-buffer
6409 (goto-char (point-min))
6410 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6411 (while (re-search-forward regexp nil t)
6412 (let ((end (cdr (save-match-data (org-get-property-block)))))
6413 (when (and end (< (point) end))
6414 ;; Hide first custom property in current drawer.
6415 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6416 (overlay-put o 'invisible t)
6417 (overlay-put o 'org-custom-property t)
6418 (push o org-custom-properties-overlays))
6419 ;; Hide additional custom properties in the same drawer.
6420 (while (re-search-forward regexp end t)
6421 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6422 (overlay-put o 'invisible t)
6423 (overlay-put o 'org-custom-property t)
6424 (push o org-custom-properties-overlays)))))
6425 ;; Each entry is limited to a single property drawer.
6426 (outline-next-heading)))))))
6428 (defun org-fontify-entities (limit)
6429 "Find an entity to fontify."
6430 (let (ee)
6431 (when org-pretty-entities
6432 (catch 'match
6433 ;; "\_ "-family is left out on purpose. Only the first one,
6434 ;; i.e., "\_ ", could be fontified anyway, and it would be
6435 ;; confusing when adding a second white space character.
6436 (while (re-search-forward
6437 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6438 limit t)
6439 (when (and (not (org-at-comment-p))
6440 (setq ee (org-entity-get (match-string 1)))
6441 (= (length (nth 6 ee)) 1))
6442 (let* ((end (if (equal (match-string 2) "{}")
6443 (match-end 2)
6444 (match-end 1))))
6445 (add-text-properties
6446 (match-beginning 0) end
6447 (list 'font-lock-fontified t))
6448 (compose-region (match-beginning 0) end
6449 (nth 6 ee) nil)
6450 (backward-char 1)
6451 (throw 'match t))))
6452 nil))))
6454 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6455 "Fontify string S like in Org-mode."
6456 (with-temp-buffer
6457 (insert s)
6458 (let ((org-odd-levels-only odd-levels))
6459 (org-mode)
6460 (org-font-lock-ensure)
6461 (buffer-string))))
6463 (defvar org-m nil)
6464 (defvar org-l nil)
6465 (defvar org-f nil)
6466 (defun org-get-level-face (n)
6467 "Get the right face for match N in font-lock matching of headlines."
6468 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6469 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6470 (if org-cycle-level-faces
6471 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6472 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6473 (cond
6474 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6475 ((eq n 2) org-f)
6476 (t (unless org-level-color-stars-only org-f))))
6478 (defun org-face-from-face-or-color (context inherit face-or-color)
6479 "Create a face list that inherits INHERIT, but sets the foreground color.
6480 When FACE-OR-COLOR is not a string, just return it."
6481 (if (stringp face-or-color)
6482 (list :inherit inherit
6483 (cdr (assoc context org-faces-easy-properties))
6484 face-or-color)
6485 face-or-color))
6487 (defun org-get-todo-face (kwd)
6488 "Get the right face for a TODO keyword KWD.
6489 If KWD is a number, get the corresponding match group."
6490 (when (numberp kwd) (setq kwd (match-string kwd)))
6491 (or (org-face-from-face-or-color
6492 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6493 (and (member kwd org-done-keywords) 'org-done)
6494 'org-todo))
6496 (defun org-get-priority-face (priority)
6497 "Get the right face for PRIORITY.
6498 PRIORITY is a character."
6499 (or (org-face-from-face-or-color
6500 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6501 'org-priority))
6503 (defun org-get-tag-face (tag)
6504 "Get the right face for TAG.
6505 If TAG is a number, get the corresponding match group."
6506 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6507 (or (org-face-from-face-or-color
6508 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6509 'org-tag)))
6511 (defun org-font-lock-add-priority-faces (limit)
6512 "Add the special priority faces."
6513 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6514 (add-text-properties
6515 (match-beginning 1) (match-end 1)
6516 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6517 'font-lock-fontified t))))
6519 (defun org-font-lock-add-tag-faces (limit)
6520 "Add the special tag faces."
6521 (when (and org-tag-faces org-tags-special-faces-re)
6522 (while (re-search-forward org-tags-special-faces-re limit t)
6523 (add-text-properties (match-beginning 1) (match-end 1)
6524 (list 'face (org-get-tag-face 1)
6525 'font-lock-fontified t))
6526 (backward-char 1))))
6528 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6529 "Remove fontification and activation overlays from links."
6530 (font-lock-default-unfontify-region beg end)
6531 (let* ((buffer-undo-list t)
6532 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6533 (inhibit-modification-hooks t)
6534 deactivate-mark buffer-file-name buffer-file-truename)
6535 (org-decompose-region beg end)
6536 (remove-text-properties beg end
6537 '(mouse-face t keymap t org-linked-text t
6538 invisible t intangible t
6539 org-emphasis t))
6540 (org-remove-font-lock-display-properties beg end)))
6542 (defconst org-script-display '(((raise -0.3) (height 0.7))
6543 ((raise 0.3) (height 0.7))
6544 ((raise -0.5))
6545 ((raise 0.5)))
6546 "Display properties for showing superscripts and subscripts.")
6548 (defun org-remove-font-lock-display-properties (beg end)
6549 "Remove specific display properties that have been added by font lock.
6550 The will remove the raise properties that are used to show superscripts
6551 and subscripts."
6552 (let (next prop)
6553 (while (< beg end)
6554 (setq next (next-single-property-change beg 'display nil end)
6555 prop (get-text-property beg 'display))
6556 (when (member prop org-script-display)
6557 (put-text-property beg next 'display nil))
6558 (setq beg next))))
6560 (defun org-raise-scripts (limit)
6561 "Add raise properties to sub/superscripts."
6562 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6563 (re-search-forward
6564 (if (eq org-use-sub-superscripts t)
6565 org-match-substring-regexp
6566 org-match-substring-with-braces-regexp)
6567 limit t))
6568 (let* ((pos (point)) table-p comment-p
6569 (mpos (match-beginning 3))
6570 (emph-p (get-text-property mpos 'org-emphasis))
6571 (link-p (get-text-property mpos 'mouse-face))
6572 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6573 (goto-char (point-at-bol))
6574 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6575 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6576 (goto-char pos)
6577 ;; Handle a_b^c
6578 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6579 (unless (or comment-p emph-p link-p keyw-p)
6580 (put-text-property (match-beginning 3) (match-end 0)
6581 'display
6582 (if (equal (char-after (match-beginning 2)) ?^)
6583 (nth (if table-p 3 1) org-script-display)
6584 (nth (if table-p 2 0) org-script-display)))
6585 (add-text-properties (match-beginning 2) (match-end 2)
6586 (list 'invisible t
6587 'org-dwidth t 'org-dwidth-n 1))
6588 (if (and (eq (char-after (match-beginning 3)) ?{)
6589 (eq (char-before (match-end 3)) ?}))
6590 (progn
6591 (add-text-properties
6592 (match-beginning 3) (1+ (match-beginning 3))
6593 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6594 (add-text-properties
6595 (1- (match-end 3)) (match-end 3)
6596 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6597 t)))
6599 ;;;; Visibility cycling, including org-goto and indirect buffer
6601 ;;; Cycling
6603 (defvar-local org-cycle-global-status nil)
6604 (put 'org-cycle-global-status 'org-state t)
6605 (defvar-local org-cycle-subtree-status nil)
6606 (put 'org-cycle-subtree-status 'org-state t)
6608 (defvar org-inlinetask-min-level)
6610 (defun org-unlogged-message (&rest args)
6611 "Display a message, but avoid logging it in the *Messages* buffer."
6612 (let ((message-log-max nil))
6613 (apply 'message args)))
6615 ;;;###autoload
6616 (defun org-cycle (&optional arg)
6617 "TAB-action and visibility cycling for Org-mode.
6619 This is the command invoked in Org-mode by the TAB key. Its main purpose
6620 is outline visibility cycling, but it also invokes other actions
6621 in special contexts.
6623 - When this function is called with a prefix argument, rotate the entire
6624 buffer through 3 states (global cycling)
6625 1. OVERVIEW: Show only top-level headlines.
6626 2. CONTENTS: Show all headlines of all levels, but no body text.
6627 3. SHOW ALL: Show everything.
6628 With a double \\[universal-argument] prefix argument, \
6629 switch to the startup visibility,
6630 determined by the variable `org-startup-folded', and by any VISIBILITY
6631 properties in the buffer.
6632 With a triple \\[universal-argument] prefix argument, \
6633 show the entire buffer, including any drawers.
6635 - When inside a table, re-align the table and move to the next field.
6637 - When point is at the beginning of a headline, rotate the subtree started
6638 by this line through 3 different states (local cycling)
6639 1. FOLDED: Only the main headline is shown.
6640 2. CHILDREN: The main headline and the direct children are shown.
6641 From this state, you can move to one of the children
6642 and zoom in further.
6643 3. SUBTREE: Show the entire subtree, including body text.
6644 If there is no subtree, switch directly from CHILDREN to FOLDED.
6646 - When point is at the beginning of an empty headline and the variable
6647 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6648 of the headline by demoting and promoting it to likely levels. This
6649 speeds up creation document structure by pressing TAB once or several
6650 times right after creating a new headline.
6652 - When there is a numeric prefix, go up to a heading with level ARG, do
6653 a `show-subtree' and return to the previous cursor position. If ARG
6654 is negative, go up that many levels.
6656 - When point is not at the beginning of a headline, execute the global
6657 binding for TAB, which is re-indenting the line. See the option
6658 `org-cycle-emulate-tab' for details.
6660 - Special case: if point is at the beginning of the buffer and there is
6661 no headline in line 1, this function will act as if called with prefix arg
6662 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6663 But only if also the variable `org-cycle-global-at-bob' is t."
6664 (interactive "P")
6665 (org-load-modules-maybe)
6666 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6667 (and org-cycle-level-after-item/entry-creation
6668 (or (org-cycle-level)
6669 (org-cycle-item-indentation))))
6670 (let* ((limit-level
6671 (or org-cycle-max-level
6672 (and (boundp 'org-inlinetask-min-level)
6673 org-inlinetask-min-level
6674 (1- org-inlinetask-min-level))))
6675 (nstars (and limit-level
6676 (if org-odd-levels-only
6677 (and limit-level (1- (* limit-level 2)))
6678 limit-level)))
6679 (org-outline-regexp
6680 (if (not (derived-mode-p 'org-mode))
6681 outline-regexp
6682 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6683 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6684 (not (looking-at org-outline-regexp))))
6685 (org-cycle-hook
6686 (if bob-special
6687 (delq 'org-optimize-window-after-visibility-change
6688 (copy-sequence org-cycle-hook))
6689 org-cycle-hook))
6690 (pos (point)))
6692 (when (or bob-special (equal arg '(4)))
6693 ;; special case: use global cycling
6694 (setq arg t))
6696 (cond
6698 ((equal arg '(16))
6699 (setq last-command 'dummy)
6700 (org-set-startup-visibility)
6701 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6703 ((equal arg '(64))
6704 (outline-show-all)
6705 (org-unlogged-message "Entire buffer visible, including drawers"))
6707 ;; Try cdlatex TAB completion
6708 ((org-try-cdlatex-tab))
6710 ;; Table: enter it or move to the next field.
6711 ((org-at-table-p 'any)
6712 (if (org-at-table.el-p)
6713 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6714 Use \\[org-edit-special] to edit table.el tables"))
6715 (if arg (org-table-edit-field t)
6716 (org-table-justify-field-maybe)
6717 (call-interactively 'org-table-next-field))))
6719 ((run-hook-with-args-until-success
6720 'org-tab-after-check-for-table-hook))
6722 ;; Global cycling: delegate to `org-cycle-internal-global'.
6723 ((eq arg t) (org-cycle-internal-global))
6725 ;; Drawers: delegate to `org-flag-drawer'.
6726 ((save-excursion
6727 (beginning-of-line 1)
6728 (looking-at org-drawer-regexp))
6729 (org-flag-drawer ; toggle block visibility
6730 (not (get-char-property (match-end 0) 'invisible))))
6732 ;; Show-subtree, ARG levels up from here.
6733 ((integerp arg)
6734 (save-excursion
6735 (org-back-to-heading)
6736 (outline-up-heading (if (< arg 0) (- arg)
6737 (- (funcall outline-level) arg)))
6738 (org-show-subtree)))
6740 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6741 ((and (featurep 'org-inlinetask)
6742 (org-inlinetask-at-task-p)
6743 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6744 (org-inlinetask-toggle-visibility))
6746 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6747 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6748 (save-excursion (move-beginning-of-line 1)
6749 (looking-at org-outline-regexp)))
6750 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6751 (org-cycle-internal-local))
6753 ;; From there: TAB emulation and template completion.
6754 (buffer-read-only (org-back-to-heading))
6756 ((run-hook-with-args-until-success
6757 'org-tab-after-check-for-cycling-hook))
6759 ((org-try-structure-completion))
6761 ((run-hook-with-args-until-success
6762 'org-tab-before-tab-emulation-hook))
6764 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6765 (or (not (bolp))
6766 (not (looking-at org-outline-regexp))))
6767 (call-interactively (global-key-binding "\t")))
6769 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6770 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6771 (or (and (eq org-cycle-emulate-tab 'white)
6772 (= (match-end 0) (point-at-eol)))
6773 (and (eq org-cycle-emulate-tab 'whitestart)
6774 (>= (match-end 0) pos))))
6776 (eq org-cycle-emulate-tab t))
6777 (call-interactively (global-key-binding "\t")))
6779 (t (save-excursion
6780 (org-back-to-heading)
6781 (org-cycle)))))))
6783 (defun org-cycle-internal-global ()
6784 "Do the global cycling action."
6785 ;; Hack to avoid display of messages for .org attachments in Gnus
6786 (let ((ga (string-match "\\*fontification" (buffer-name))))
6787 (cond
6788 ((and (eq last-command this-command)
6789 (eq org-cycle-global-status 'overview))
6790 ;; We just created the overview - now do table of contents
6791 ;; This can be slow in very large buffers, so indicate action
6792 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6793 (unless ga (org-unlogged-message "CONTENTS..."))
6794 (org-content)
6795 (unless ga (org-unlogged-message "CONTENTS...done"))
6796 (setq org-cycle-global-status 'contents)
6797 (run-hook-with-args 'org-cycle-hook 'contents))
6799 ((and (eq last-command this-command)
6800 (eq org-cycle-global-status 'contents))
6801 ;; We just showed the table of contents - now show everything
6802 (run-hook-with-args 'org-pre-cycle-hook 'all)
6803 (outline-show-all)
6804 (unless ga (org-unlogged-message "SHOW ALL"))
6805 (setq org-cycle-global-status 'all)
6806 (run-hook-with-args 'org-cycle-hook 'all))
6809 ;; Default action: go to overview
6810 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6811 (org-overview)
6812 (unless ga (org-unlogged-message "OVERVIEW"))
6813 (setq org-cycle-global-status 'overview)
6814 (run-hook-with-args 'org-cycle-hook 'overview)))))
6816 (defvar org-called-with-limited-levels nil
6817 "Non-nil when `org-with-limited-levels' is currently active.")
6819 (defun org-cycle-internal-local ()
6820 "Do the local cycling action."
6821 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6822 ;; First, determine end of headline (EOH), end of subtree or item
6823 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6824 (save-excursion
6825 (if (org-at-item-p)
6826 (progn
6827 (beginning-of-line)
6828 (setq struct (org-list-struct))
6829 (setq eoh (point-at-eol))
6830 (setq eos (org-list-get-item-end-before-blank (point) struct))
6831 (setq has-children (org-list-has-child-p (point) struct)))
6832 (org-back-to-heading)
6833 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6834 (setq eos (save-excursion (org-end-of-subtree t t)
6835 (when (bolp) (backward-char)) (point)))
6836 (setq has-children
6837 (or (save-excursion
6838 (let ((level (funcall outline-level)))
6839 (outline-next-heading)
6840 (and (org-at-heading-p t)
6841 (> (funcall outline-level) level))))
6842 (save-excursion
6843 (org-list-search-forward (org-item-beginning-re) eos t)))))
6844 ;; Determine end invisible part of buffer (EOL)
6845 (beginning-of-line 2)
6846 ;; XEmacs doesn't have `next-single-char-property-change'
6847 (if (featurep 'xemacs)
6848 (while (and (not (eobp)) ;; this is like `next-line'
6849 (get-char-property (1- (point)) 'invisible))
6850 (beginning-of-line 2))
6851 (while (and (not (eobp)) ;; this is like `next-line'
6852 (get-char-property (1- (point)) 'invisible))
6853 (goto-char (next-single-char-property-change (point) 'invisible))
6854 (and (eolp) (beginning-of-line 2))))
6855 (setq eol (point)))
6856 ;; Find out what to do next and set `this-command'
6857 (cond
6858 ((= eos eoh)
6859 ;; Nothing is hidden behind this heading
6860 (unless (org-before-first-heading-p)
6861 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6862 (org-unlogged-message "EMPTY ENTRY")
6863 (setq org-cycle-subtree-status nil)
6864 (save-excursion
6865 (goto-char eos)
6866 (outline-next-heading)
6867 (when (outline-invisible-p) (org-flag-heading nil))))
6868 ((and (or (>= eol eos)
6869 (not (string-match "\\S-" (buffer-substring eol eos))))
6870 (or has-children
6871 (not (setq children-skipped
6872 org-cycle-skip-children-state-if-no-children))))
6873 ;; Entire subtree is hidden in one line: children view
6874 (unless (org-before-first-heading-p)
6875 (run-hook-with-args 'org-pre-cycle-hook 'children))
6876 (if (org-at-item-p)
6877 (org-list-set-item-visibility (point-at-bol) struct 'children)
6878 (org-show-entry)
6879 (org-with-limited-levels (org-show-children))
6880 ;; FIXME: This slows down the func way too much.
6881 ;; How keep drawers hidden in subtree anyway?
6882 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6883 ;; (org-cycle-hide-drawers 'subtree))
6885 ;; Fold every list in subtree to top-level items.
6886 (when (eq org-cycle-include-plain-lists 'integrate)
6887 (save-excursion
6888 (org-back-to-heading)
6889 (while (org-list-search-forward (org-item-beginning-re) eos t)
6890 (beginning-of-line 1)
6891 (let* ((struct (org-list-struct))
6892 (prevs (org-list-prevs-alist struct))
6893 (end (org-list-get-bottom-point struct)))
6894 (dolist (e (org-list-get-all-items (point) struct prevs))
6895 (org-list-set-item-visibility e struct 'folded))
6896 (goto-char (if (< end eos) end eos)))))))
6897 (org-unlogged-message "CHILDREN")
6898 (save-excursion
6899 (goto-char eos)
6900 (outline-next-heading)
6901 (when (outline-invisible-p) (org-flag-heading nil)))
6902 (setq org-cycle-subtree-status 'children)
6903 (unless (org-before-first-heading-p)
6904 (run-hook-with-args 'org-cycle-hook 'children)))
6905 ((or children-skipped
6906 (and (eq last-command this-command)
6907 (eq org-cycle-subtree-status 'children)))
6908 ;; We just showed the children, or no children are there,
6909 ;; now show everything.
6910 (unless (org-before-first-heading-p)
6911 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6912 (outline-flag-region eoh eos nil)
6913 (org-unlogged-message
6914 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6915 (setq org-cycle-subtree-status 'subtree)
6916 (unless (org-before-first-heading-p)
6917 (run-hook-with-args 'org-cycle-hook 'subtree)))
6919 ;; Default action: hide the subtree.
6920 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6921 (outline-flag-region eoh eos t)
6922 (org-unlogged-message "FOLDED")
6923 (setq org-cycle-subtree-status 'folded)
6924 (unless (org-before-first-heading-p)
6925 (run-hook-with-args 'org-cycle-hook 'folded))))))
6927 ;;;###autoload
6928 (defun org-global-cycle (&optional arg)
6929 "Cycle the global visibility. For details see `org-cycle'.
6930 With \\[universal-argument] prefix arg, switch to startup visibility.
6931 With a numeric prefix, show all headlines up to that level."
6932 (interactive "P")
6933 (let ((org-cycle-include-plain-lists
6934 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6935 (cond
6936 ((integerp arg)
6937 (outline-show-all)
6938 (outline-hide-sublevels arg)
6939 (setq org-cycle-global-status 'contents))
6940 ((equal arg '(4))
6941 (org-set-startup-visibility)
6942 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6944 (org-cycle '(4))))))
6946 (defun org-set-startup-visibility ()
6947 "Set the visibility required by startup options and properties."
6948 (cond
6949 ((eq org-startup-folded t)
6950 (org-overview))
6951 ((eq org-startup-folded 'content)
6952 (org-content))
6953 ((or (eq org-startup-folded 'showeverything)
6954 (eq org-startup-folded nil))
6955 (outline-show-all)))
6956 (unless (eq org-startup-folded 'showeverything)
6957 (when org-hide-block-startup (org-hide-block-all))
6958 (org-set-visibility-according-to-property 'no-cleanup)
6959 (org-cycle-hide-archived-subtrees 'all)
6960 (org-cycle-hide-drawers 'all)
6961 (org-cycle-show-empty-lines t)))
6963 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6964 "Switch subtree visibilities according to :VISIBILITY: property."
6965 (interactive)
6966 (org-with-wide-buffer
6967 (goto-char (point-min))
6968 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6969 (if (not (org-at-property-p)) (outline-next-heading)
6970 (let ((state (match-string 3)))
6971 (save-excursion
6972 (org-back-to-heading t)
6973 (outline-hide-subtree)
6974 (org-reveal)
6975 (cond
6976 ((equal state "folded")
6977 (outline-hide-subtree))
6978 ((equal state "children")
6979 (org-show-hidden-entry)
6980 (org-show-children))
6981 ((equal state "content")
6982 (save-excursion
6983 (save-restriction
6984 (org-narrow-to-subtree)
6985 (org-content))))
6986 ((member state '("all" "showall"))
6987 (outline-show-subtree)))))))
6988 (unless no-cleanup
6989 (org-cycle-hide-archived-subtrees 'all)
6990 (org-cycle-hide-drawers 'all)
6991 (org-cycle-show-empty-lines 'all))))
6993 ;; This function uses outline-regexp instead of the more fundamental
6994 ;; org-outline-regexp so that org-cycle-global works outside of Org
6995 ;; buffers, where outline-regexp is needed.
6996 (defun org-overview ()
6997 "Switch to overview mode, showing only top-level headlines.
6998 This shows all headlines with a level equal or greater than the level
6999 of the first headline in the buffer. This is important, because if the
7000 first headline is not level one, then (hide-sublevels 1) gives confusing
7001 results."
7002 (interactive)
7003 (save-excursion
7004 (let ((level
7005 (save-excursion
7006 (goto-char (point-min))
7007 (when (re-search-forward (concat "^" outline-regexp) nil t)
7008 (goto-char (match-beginning 0))
7009 (funcall outline-level)))))
7010 (and level (outline-hide-sublevels level)))))
7012 (defun org-content (&optional arg)
7013 "Show all headlines in the buffer, like a table of contents.
7014 With numerical argument N, show content up to level N."
7015 (interactive "P")
7016 (org-overview)
7017 (save-excursion
7018 ;; Visit all headings and show their offspring
7019 (and (integerp arg) (org-overview))
7020 (goto-char (point-max))
7021 (catch 'exit
7022 (while (and (progn (condition-case nil
7023 (outline-previous-visible-heading 1)
7024 (error (goto-char (point-min))))
7026 (looking-at org-outline-regexp))
7027 (if (integerp arg)
7028 (org-show-children (1- arg))
7029 (outline-show-branches))
7030 (when (bobp) (throw 'exit nil))))))
7032 (defun org-optimize-window-after-visibility-change (state)
7033 "Adjust the window after a change in outline visibility.
7034 This function is the default value of the hook `org-cycle-hook'."
7035 (when (get-buffer-window (current-buffer))
7036 (cond
7037 ((eq state 'content) nil)
7038 ((eq state 'all) nil)
7039 ((eq state 'folded) nil)
7040 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7041 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7043 (defun org-remove-empty-overlays-at (pos)
7044 "Remove outline overlays that do not contain non-white stuff."
7045 (dolist (o (overlays-at pos))
7046 (and (eq 'outline (overlay-get o 'invisible))
7047 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7048 (overlay-end o))))
7049 (delete-overlay o))))
7051 (defun org-clean-visibility-after-subtree-move ()
7052 "Fix visibility issues after moving a subtree."
7053 ;; First, find a reasonable region to look at:
7054 ;; Start two siblings above, end three below
7055 (let* ((beg (save-excursion
7056 (and (org-get-last-sibling)
7057 (org-get-last-sibling))
7058 (point)))
7059 (end (save-excursion
7060 (and (org-get-next-sibling)
7061 (org-get-next-sibling)
7062 (org-get-next-sibling))
7063 (if (org-at-heading-p)
7064 (point-at-eol)
7065 (point))))
7066 (level (looking-at "\\*+"))
7067 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7068 (save-excursion
7069 (save-restriction
7070 (narrow-to-region beg end)
7071 (when re
7072 ;; Properly fold already folded siblings
7073 (goto-char (point-min))
7074 (while (re-search-forward re nil t)
7075 (when (and (not (outline-invisible-p))
7076 (save-excursion
7077 (goto-char (point-at-eol)) (outline-invisible-p)))
7078 (outline-hide-entry))))
7079 (org-cycle-show-empty-lines 'overview)
7080 (org-cycle-hide-drawers 'overview)))))
7082 (defun org-cycle-show-empty-lines (state)
7083 "Show empty lines above all visible headlines.
7084 The region to be covered depends on STATE when called through
7085 `org-cycle-hook'. Lisp program can use t for STATE to get the
7086 entire buffer covered. Note that an empty line is only shown if there
7087 are at least `org-cycle-separator-lines' empty lines before the headline."
7088 (when (/= org-cycle-separator-lines 0)
7089 (save-excursion
7090 (let* ((n (abs org-cycle-separator-lines))
7091 (re (cond
7092 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7093 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7094 (t (let ((ns (number-to-string (- n 2))))
7095 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7096 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7097 beg end)
7098 (cond
7099 ((memq state '(overview contents t))
7100 (setq beg (point-min) end (point-max)))
7101 ((memq state '(children folded))
7102 (setq beg (point)
7103 end (progn (org-end-of-subtree t t)
7104 (line-beginning-position 2)))))
7105 (when beg
7106 (goto-char beg)
7107 (while (re-search-forward re end t)
7108 (unless (get-char-property (match-end 1) 'invisible)
7109 (let ((e (match-end 1))
7110 (b (if (>= org-cycle-separator-lines 0)
7111 (match-beginning 1)
7112 (save-excursion
7113 (goto-char (match-beginning 0))
7114 (skip-chars-backward " \t\n")
7115 (line-end-position)))))
7116 (outline-flag-region b e nil))))))))
7117 ;; Never hide empty lines at the end of the file.
7118 (save-excursion
7119 (goto-char (point-max))
7120 (outline-previous-heading)
7121 (outline-end-of-heading)
7122 (when (and (looking-at "[ \t\n]+")
7123 (= (match-end 0) (point-max)))
7124 (outline-flag-region (point) (match-end 0) nil))))
7126 (defun org-show-empty-lines-in-parent ()
7127 "Move to the parent and re-show empty lines before visible headlines."
7128 (save-excursion
7129 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7130 (org-cycle-show-empty-lines context))))
7132 (defun org-files-list ()
7133 "Return `org-agenda-files' list, plus all open org-mode files.
7134 This is useful for operations that need to scan all of a user's
7135 open and agenda-wise Org files."
7136 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7137 (dolist (buf (buffer-list))
7138 (with-current-buffer buf
7139 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7140 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7141 files))
7143 (defsubst org-entry-beginning-position ()
7144 "Return the beginning position of the current entry."
7145 (save-excursion (org-back-to-heading t) (point)))
7147 (defsubst org-entry-end-position ()
7148 "Return the end position of the current entry."
7149 (save-excursion (outline-next-heading) (point)))
7151 (defun org-cycle-hide-drawers (state &optional exceptions)
7152 "Re-hide all drawers after a visibility state change.
7153 When non-nil, optional argument EXCEPTIONS is a list of strings
7154 specifying which drawers should not be hidden."
7155 (when (and (derived-mode-p 'org-mode)
7156 (not (memq state '(overview folded contents))))
7157 (save-excursion
7158 (let* ((globalp (memq state '(contents all)))
7159 (beg (if globalp (point-min) (point)))
7160 (end (if globalp (point-max)
7161 (if (eq state 'children)
7162 (save-excursion (outline-next-heading) (point))
7163 (org-end-of-subtree t)))))
7164 (goto-char beg)
7165 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7166 (unless (member-ignore-case (match-string 1) exceptions)
7167 (let ((drawer (org-element-at-point)))
7168 (when (memq (org-element-type drawer) '(drawer property-drawer))
7169 (org-flag-drawer t drawer)
7170 ;; Make sure to skip drawer entirely or we might flag
7171 ;; it another time when matching its ending line with
7172 ;; `org-drawer-regexp'.
7173 (goto-char (org-element-property :end drawer))))))))))
7175 (defun org-flag-drawer (flag &optional element)
7176 "When FLAG is non-nil, hide the drawer we are at.
7177 Otherwise make it visible. When optional argument ELEMENT is
7178 a parsed drawer, as returned by `org-element-at-point', hide or
7179 show that drawer instead."
7180 (when (save-excursion
7181 (beginning-of-line)
7182 (org-looking-at-p org-drawer-regexp))
7183 (let ((drawer (or element (org-element-at-point))))
7184 (when (memq (org-element-type drawer) '(drawer property-drawer))
7185 (let ((post (org-element-property :post-affiliated drawer)))
7186 (save-excursion
7187 (outline-flag-region
7188 (progn (goto-char post) (line-end-position))
7189 (progn (goto-char (org-element-property :end drawer))
7190 (skip-chars-backward " \r\t\n")
7191 (line-end-position))
7192 flag))
7193 ;; When the drawer is hidden away, make sure point lies in
7194 ;; a visible part of the buffer.
7195 (when (and flag (> (line-beginning-position) post))
7196 (goto-char post)))))))
7198 (defun org-subtree-end-visible-p ()
7199 "Is the end of the current subtree visible?"
7200 (pos-visible-in-window-p
7201 (save-excursion (org-end-of-subtree t) (point))))
7203 (defun org-first-headline-recenter ()
7204 "Move cursor to the first headline and recenter the headline."
7205 (goto-char (point-min))
7206 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7207 (set-window-start (selected-window) (point-at-bol))))
7209 ;;; Saving and restoring visibility
7211 (defun org-outline-overlay-data (&optional use-markers)
7212 "Return a list of the locations of all outline overlays.
7213 These are overlays with the `invisible' property value `outline'.
7214 The return value is a list of cons cells, with start and stop
7215 positions for each overlay.
7216 If USE-MARKERS is set, return the positions as markers."
7217 (let (beg end)
7218 (save-excursion
7219 (save-restriction
7220 (widen)
7221 (delq nil
7222 (mapcar (lambda (o)
7223 (when (eq (overlay-get o 'invisible) 'outline)
7224 (setq beg (overlay-start o)
7225 end (overlay-end o))
7226 (and beg end (> end beg)
7227 (if use-markers
7228 (cons (copy-marker beg)
7229 (copy-marker end t))
7230 (cons beg end)))))
7231 (overlays-in (point-min) (point-max))))))))
7233 (defun org-set-outline-overlay-data (data)
7234 "Create visibility overlays for all positions in DATA.
7235 DATA should have been made by `org-outline-overlay-data'."
7236 (org-with-wide-buffer
7237 (outline-show-all)
7238 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7240 ;;; Folding of blocks
7242 (defvar-local org-hide-block-overlays nil
7243 "Overlays hiding blocks.")
7245 (defun org-block-map (function &optional start end)
7246 "Call FUNCTION at the head of all source blocks in the current buffer.
7247 Optional arguments START and END can be used to limit the range."
7248 (let ((start (or start (point-min)))
7249 (end (or end (point-max))))
7250 (save-excursion
7251 (goto-char start)
7252 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7253 (save-excursion
7254 (save-match-data
7255 (goto-char (match-beginning 0))
7256 (funcall function)))))))
7258 (defun org-hide-block-toggle-all ()
7259 "Toggle the visibility of all blocks in the current buffer."
7260 (org-block-map 'org-hide-block-toggle))
7262 (defun org-hide-block-all ()
7263 "Fold all blocks in the current buffer."
7264 (interactive)
7265 (org-show-block-all)
7266 (org-block-map 'org-hide-block-toggle-maybe))
7268 (defun org-show-block-all ()
7269 "Unfold all blocks in the current buffer."
7270 (interactive)
7271 (mapc #'delete-overlay org-hide-block-overlays)
7272 (setq org-hide-block-overlays nil))
7274 (defun org-hide-block-toggle-maybe ()
7275 "Toggle visibility of block at point.
7276 Unlike to `org-hide-block-toggle', this function does not throw
7277 an error. Return a non-nil value when toggling is successful."
7278 (interactive)
7279 (ignore-errors (org-hide-block-toggle)))
7281 (defun org-hide-block-toggle (&optional force)
7282 "Toggle the visibility of the current block.
7283 When optional argument FORCE is `off', make block visible. If it
7284 is non-nil, hide it unconditionally. Throw an error when not at
7285 a block. Return a non-nil value when toggling is successful."
7286 (interactive)
7287 (let ((element (org-element-at-point)))
7288 (unless (memq (org-element-type element)
7289 '(center-block comment-block dynamic-block example-block
7290 export-block quote-block special-block
7291 src-block verse-block))
7292 (user-error "Not at a block"))
7293 (let* ((start (save-excursion
7294 (goto-char (org-element-property :post-affiliated element))
7295 (line-end-position)))
7296 (end (save-excursion
7297 (goto-char (org-element-property :end element))
7298 (skip-chars-backward " \r\t\n")
7299 (line-end-position)))
7300 (overlays (overlays-at start)))
7301 (cond
7302 ;; Do nothing when not before or at the block opening line or
7303 ;; at the block closing line.
7304 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7305 ((and (not (eq force 'off))
7306 (not (memq t (mapcar
7307 (lambda (o)
7308 (eq (overlay-get o 'invisible) 'org-hide-block))
7309 overlays))))
7310 (let ((ov (make-overlay start end)))
7311 (overlay-put ov 'invisible 'org-hide-block)
7312 ;; Make the block accessible to `isearch'.
7313 (overlay-put
7314 ov 'isearch-open-invisible
7315 (lambda (ov)
7316 (when (memq ov org-hide-block-overlays)
7317 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7318 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7319 (delete-overlay ov))))
7320 (push ov org-hide-block-overlays)
7321 ;; When the block is hidden away, make sure point is left in
7322 ;; a visible part of the buffer.
7323 (when (> (line-beginning-position) start)
7324 (goto-char start)
7325 (beginning-of-line))
7326 ;; Signal successful toggling.
7328 ((or (not force) (eq force 'off))
7329 (dolist (ov overlays t)
7330 (when (memq ov org-hide-block-overlays)
7331 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7332 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7333 (delete-overlay ov))))))))
7335 ;; org-tab-after-check-for-cycling-hook
7336 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7337 ;; Remove overlays when changing major mode
7338 (add-hook 'org-mode-hook
7339 (lambda () (org-add-hook 'change-major-mode-hook
7340 'org-show-block-all 'append 'local)))
7342 ;;; Org-goto
7344 (defvar org-goto-window-configuration nil)
7345 (defvar org-goto-marker nil)
7346 (defvar org-goto-map)
7347 (defun org-goto-map ()
7348 "Set the keymap `org-goto'."
7349 (setq org-goto-map
7350 (let ((map (make-sparse-keymap)))
7351 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7352 mouse-drag-region universal-argument org-occur)))
7353 (dolist (cmd cmds)
7354 (substitute-key-definition cmd cmd map global-map)))
7355 (suppress-keymap map)
7356 (org-defkey map "\C-m" 'org-goto-ret)
7357 (org-defkey map [(return)] 'org-goto-ret)
7358 (org-defkey map [(left)] 'org-goto-left)
7359 (org-defkey map [(right)] 'org-goto-right)
7360 (org-defkey map [(control ?g)] 'org-goto-quit)
7361 (org-defkey map "\C-i" 'org-cycle)
7362 (org-defkey map [(tab)] 'org-cycle)
7363 (org-defkey map [(down)] 'outline-next-visible-heading)
7364 (org-defkey map [(up)] 'outline-previous-visible-heading)
7365 (if org-goto-auto-isearch
7366 (if (fboundp 'define-key-after)
7367 (define-key-after map [t] 'org-goto-local-auto-isearch)
7368 nil)
7369 (org-defkey map "q" 'org-goto-quit)
7370 (org-defkey map "n" 'outline-next-visible-heading)
7371 (org-defkey map "p" 'outline-previous-visible-heading)
7372 (org-defkey map "f" 'outline-forward-same-level)
7373 (org-defkey map "b" 'outline-backward-same-level)
7374 (org-defkey map "u" 'outline-up-heading))
7375 (org-defkey map "/" 'org-occur)
7376 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7377 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7378 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7379 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7380 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7381 map)))
7383 (defconst org-goto-help
7384 "Browse buffer copy, to find location or copy text.%s
7385 RET=jump to location C-g=quit and return to previous location
7386 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7388 (defvar org-goto-start-pos) ; dynamically scoped parameter
7390 (defun org-goto (&optional alternative-interface)
7391 "Look up a different location in the current file, keeping current visibility.
7393 When you want look-up or go to a different location in a
7394 document, the fastest way is often to fold the entire buffer and
7395 then dive into the tree. This method has the disadvantage, that
7396 the previous location will be folded, which may not be what you
7397 want.
7399 This command works around this by showing a copy of the current
7400 buffer in an indirect buffer, in overview mode. You can dive
7401 into the tree in that copy, use org-occur and incremental search
7402 to find a location. When pressing RET or `Q', the command
7403 returns to the original buffer in which the visibility is still
7404 unchanged. After RET it will also jump to the location selected
7405 in the indirect buffer and expose the headline hierarchy above.
7407 With a prefix argument, use the alternative interface: e.g., if
7408 `org-goto-interface' is `outline' use `outline-path-completion'."
7409 (interactive "P")
7410 (org-goto-map)
7411 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7412 (org-refile-use-outline-path t)
7413 (org-refile-target-verify-function nil)
7414 (interface
7415 (if (not alternative-interface)
7416 org-goto-interface
7417 (if (eq org-goto-interface 'outline)
7418 'outline-path-completion
7419 'outline)))
7420 (org-goto-start-pos (point))
7421 (selected-point
7422 (if (eq interface 'outline)
7423 (car (org-get-location (current-buffer) org-goto-help))
7424 (let ((pa (org-refile-get-location "Goto")))
7425 (org-refile-check-position pa)
7426 (nth 3 pa)))))
7427 (if selected-point
7428 (progn
7429 (org-mark-ring-push org-goto-start-pos)
7430 (goto-char selected-point)
7431 (when (or (outline-invisible-p) (org-invisible-p2))
7432 (org-show-context 'org-goto)))
7433 (message "Quit"))))
7435 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7436 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7437 (defvar org-goto-local-auto-isearch-map) ; defined below
7439 (defun org-get-location (_buf help)
7440 "Let the user select a location in current buffer.
7441 This function uses a recursive edit. It returns the selected position
7442 or nil."
7443 (org-no-popups
7444 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7445 (isearch-hide-immediately nil)
7446 (isearch-search-fun-function
7447 (lambda () 'org-goto-local-search-headings))
7448 (org-goto-selected-point org-goto-exit-command))
7449 (save-excursion
7450 (save-window-excursion
7451 (delete-other-windows)
7452 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7453 (org-pop-to-buffer-same-window
7454 (condition-case nil
7455 (make-indirect-buffer (current-buffer) "*org-goto*")
7456 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7457 (with-output-to-temp-buffer "*Org Help*"
7458 (princ (format help (if org-goto-auto-isearch
7459 " Just type for auto-isearch."
7460 " n/p/f/b/u to navigate, q to quit."))))
7461 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7462 (setq buffer-read-only nil)
7463 (let ((org-startup-truncated t)
7464 (org-startup-folded nil)
7465 (org-startup-align-all-tables nil))
7466 (org-mode)
7467 (org-overview))
7468 (setq buffer-read-only t)
7469 (if (and (boundp 'org-goto-start-pos)
7470 (integer-or-marker-p org-goto-start-pos))
7471 (progn (goto-char org-goto-start-pos)
7472 (when (outline-invisible-p)
7473 (org-show-set-visibility 'lineage)))
7474 (goto-char (point-min)))
7475 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7476 (message "Select location and press RET")
7477 (use-local-map org-goto-map)
7478 (recursive-edit)))
7479 (kill-buffer "*org-goto*")
7480 (cons org-goto-selected-point org-goto-exit-command))))
7482 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7483 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7484 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7485 (if (fboundp 'isearch-other-control-char)
7486 (progn
7487 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7488 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7489 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7490 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7491 (define-key org-goto-local-auto-isearch-map [return] nil))
7493 (defun org-goto-local-search-headings (string bound noerror)
7494 "Search and make sure that any matches are in headlines."
7495 (catch 'return
7496 (while (if isearch-forward
7497 (search-forward string bound noerror)
7498 (search-backward string bound noerror))
7499 (when (save-match-data
7500 (and (save-excursion
7501 (beginning-of-line)
7502 (looking-at org-complex-heading-regexp))
7503 (or (not (match-beginning 5))
7504 (< (point) (match-beginning 5)))))
7505 (throw 'return (point))))))
7507 (defun org-goto-local-auto-isearch ()
7508 "Start isearch."
7509 (interactive)
7510 (goto-char (point-min))
7511 (let ((keys (this-command-keys)))
7512 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7513 (isearch-mode t)
7514 (isearch-process-search-char (string-to-char keys)))))
7516 (defun org-goto-ret (&optional _arg)
7517 "Finish `org-goto' by going to the new location."
7518 (interactive "P")
7519 (setq org-goto-selected-point (point))
7520 (setq org-goto-exit-command 'return)
7521 (throw 'exit nil))
7523 (defun org-goto-left ()
7524 "Finish `org-goto' by going to the new location."
7525 (interactive)
7526 (if (org-at-heading-p)
7527 (progn
7528 (beginning-of-line 1)
7529 (setq org-goto-selected-point (point)
7530 org-goto-exit-command 'left)
7531 (throw 'exit nil))
7532 (user-error "Not on a heading")))
7534 (defun org-goto-right ()
7535 "Finish `org-goto' by going to the new location."
7536 (interactive)
7537 (if (org-at-heading-p)
7538 (progn
7539 (setq org-goto-selected-point (point)
7540 org-goto-exit-command 'right)
7541 (throw 'exit nil))
7542 (user-error "Not on a heading")))
7544 (defun org-goto-quit ()
7545 "Finish `org-goto' without cursor motion."
7546 (interactive)
7547 (setq org-goto-selected-point nil)
7548 (setq org-goto-exit-command 'quit)
7549 (throw 'exit nil))
7551 ;;; Indirect buffer display of subtrees
7553 (defvar org-indirect-dedicated-frame nil
7554 "This is the frame being used for indirect tree display.")
7555 (defvar org-last-indirect-buffer nil)
7557 (defun org-tree-to-indirect-buffer (&optional arg)
7558 "Create indirect buffer and narrow it to current subtree.
7559 With a numerical prefix ARG, go up to this level and then take that tree.
7560 If ARG is negative, go up that many levels.
7562 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7563 indirect buffer previously made with this command, to avoid proliferation of
7564 indirect buffers. However, when you call the command with a \
7565 \\[universal-argument] prefix, or
7566 when `org-indirect-buffer-display' is `new-frame', the last buffer
7567 is kept so that you can work with several indirect buffers at the same time.
7568 If `org-indirect-buffer-display' is `dedicated-frame', the \
7569 \\[universal-argument] prefix also
7570 requests that a new frame be made for the new buffer, so that the dedicated
7571 frame is not changed."
7572 (interactive "P")
7573 (let ((cbuf (current-buffer))
7574 (cwin (selected-window))
7575 (pos (point))
7576 beg end level heading ibuf)
7577 (save-excursion
7578 (org-back-to-heading t)
7579 (when (numberp arg)
7580 (setq level (org-outline-level))
7581 (when (< arg 0) (setq arg (+ level arg)))
7582 (while (> (setq level (org-outline-level)) arg)
7583 (org-up-heading-safe)))
7584 (setq beg (point)
7585 heading (org-get-heading 'no-tags))
7586 (org-end-of-subtree t t)
7587 (when (org-at-heading-p) (backward-char 1))
7588 (setq end (point)))
7589 (when (and (buffer-live-p org-last-indirect-buffer)
7590 (not (eq org-indirect-buffer-display 'new-frame))
7591 (not arg))
7592 (kill-buffer org-last-indirect-buffer))
7593 (setq ibuf (org-get-indirect-buffer cbuf heading)
7594 org-last-indirect-buffer ibuf)
7595 (cond
7596 ((or (eq org-indirect-buffer-display 'new-frame)
7597 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7598 (select-frame (make-frame))
7599 (delete-other-windows)
7600 (org-pop-to-buffer-same-window ibuf)
7601 (org-set-frame-title heading))
7602 ((eq org-indirect-buffer-display 'dedicated-frame)
7603 (raise-frame
7604 (select-frame (or (and org-indirect-dedicated-frame
7605 (frame-live-p org-indirect-dedicated-frame)
7606 org-indirect-dedicated-frame)
7607 (setq org-indirect-dedicated-frame (make-frame)))))
7608 (delete-other-windows)
7609 (org-pop-to-buffer-same-window ibuf)
7610 (org-set-frame-title (concat "Indirect: " heading)))
7611 ((eq org-indirect-buffer-display 'current-window)
7612 (org-pop-to-buffer-same-window ibuf))
7613 ((eq org-indirect-buffer-display 'other-window)
7614 (pop-to-buffer ibuf))
7615 (t (error "Invalid value")))
7616 (when (featurep 'xemacs)
7617 (save-excursion (org-mode) (turn-on-font-lock)))
7618 (narrow-to-region beg end)
7619 (outline-show-all)
7620 (goto-char pos)
7621 (run-hook-with-args 'org-cycle-hook 'all)
7622 (and (window-live-p cwin) (select-window cwin))))
7624 (defun org-get-indirect-buffer (&optional buffer heading)
7625 (setq buffer (or buffer (current-buffer)))
7626 (let ((n 1) (base (buffer-name buffer)) bname)
7627 (while (buffer-live-p
7628 (get-buffer
7629 (setq bname
7630 (concat base "-"
7631 (if heading (concat heading "-" (number-to-string n))
7632 (number-to-string n))))))
7633 (setq n (1+ n)))
7634 (condition-case nil
7635 (make-indirect-buffer buffer bname 'clone)
7636 (error (make-indirect-buffer buffer bname)))))
7638 (defun org-set-frame-title (title)
7639 "Set the title of the current frame to the string TITLE."
7640 ;; FIXME: how to name a single frame in XEmacs???
7641 (unless (featurep 'xemacs)
7642 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7644 ;;;; Structure editing
7646 ;;; Inserting headlines
7648 (defun org--line-empty-p (n)
7649 "Is the Nth next line empty?
7651 Counts the current line as N = 1 and the previous line as N = 0;
7652 see `beginning-of-line'."
7653 (save-excursion
7654 (and (not (bobp))
7655 (or (beginning-of-line n) t)
7656 (save-match-data
7657 (looking-at "[ \t]*$")))))
7659 (defun org-previous-line-empty-p ()
7660 "Is the previous line a blank line?
7661 When NEXT is non-nil, check the next line instead."
7662 (org--line-empty-p 0))
7664 (defun org-next-line-empty-p ()
7665 "Is the previous line a blank line?
7666 When NEXT is non-nil, check the next line instead."
7667 (org--line-empty-p 2))
7669 (defun org-insert-heading (&optional arg invisible-ok top)
7670 "Insert a new heading or an item with the same depth at point.
7672 If point is at the beginning of a heading or a list item, insert
7673 a new heading or a new item above the current one. If point is
7674 at the beginning of a normal line, turn the line into a heading.
7676 If point is in the middle of a headline or a list item, split the
7677 headline or the item and create a new headline/item with the text
7678 in the current line after point \(see `org-M-RET-may-split-line'
7679 on how to modify this behavior).
7681 With one universal prefix argument, set the user option
7682 `org-insert-heading-respect-content' to t for the duration of
7683 the command. This modifies the behavior described above in this
7684 ways: on list items and at the beginning of normal lines, force
7685 the insertion of a heading after the current subtree.
7687 With two universal prefix arguments, insert the heading at the
7688 end of the grandparent subtree. For example, if point is within
7689 a 2nd-level heading, then it will insert a 2nd-level heading at
7690 the end of the 1st-level parent heading.
7692 If point is at the beginning of a headline, insert a sibling
7693 before the current headline. If point is not at the beginning,
7694 split the line and create a new headline with the text in the
7695 current line after point \(see `org-M-RET-may-split-line' on how
7696 to modify this behavior).
7698 If point is at the beginning of a normal line, turn this line
7699 into a heading.
7701 When INVISIBLE-OK is set, stop at invisible headlines when going
7702 back. This is important for non-interactive uses of the
7703 command.
7705 When optional argument TOP is non-nil, insert a level 1 heading,
7706 unconditionally."
7707 (interactive "P")
7708 (when (org-called-interactively-p 'any) (org-reveal))
7709 (let ((itemp (and (not top) (org-in-item-p)))
7710 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7711 (respect-content (or org-insert-heading-respect-content
7712 (equal arg '(4))))
7713 (initial-content ""))
7715 (cond
7717 ((or (= (buffer-size) 0)
7718 (and (not (save-excursion
7719 (and (ignore-errors (org-back-to-heading invisible-ok))
7720 (org-at-heading-p))))
7721 (or arg (not itemp))))
7722 ;; At beginning of buffer or so high up that only a heading
7723 ;; makes sense.
7724 (cond ((and (bolp) (not respect-content)) (insert "* "))
7725 ((not respect-content)
7726 (unless may-split (end-of-line))
7727 (insert "\n* "))
7728 ((re-search-forward org-outline-regexp-bol nil t)
7729 (beginning-of-line)
7730 (insert "* \n")
7731 (backward-char))
7732 (t (goto-char (point-max))
7733 (insert "\n* ")))
7734 (run-hooks 'org-insert-heading-hook))
7736 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7739 ;; Maybe move at the end of the subtree
7740 (when (equal arg '(16))
7741 (org-up-heading-safe)
7742 (org-end-of-subtree t))
7743 ;; Insert a heading
7744 (save-restriction
7745 (widen)
7746 (let* ((level nil)
7747 (on-heading (org-at-heading-p))
7748 (empty-line-p (if on-heading
7749 (org-previous-line-empty-p)
7750 ;; We will decide later
7751 nil))
7752 ;; Get a level string to fall back on.
7753 (fix-level
7754 (if (org-before-first-heading-p) "*"
7755 (save-excursion
7756 (org-back-to-heading t)
7757 (when (org-previous-line-empty-p) (setq empty-line-p t))
7758 (looking-at org-outline-regexp)
7759 (make-string (1- (length (match-string 0))) ?*))))
7760 (stars
7761 (save-excursion
7762 (condition-case nil
7763 (if top "* "
7764 (org-back-to-heading invisible-ok)
7765 (when (and (not on-heading)
7766 (featurep 'org-inlinetask)
7767 (integerp org-inlinetask-min-level)
7768 (>= (length (match-string 0))
7769 org-inlinetask-min-level))
7770 ;; Find a heading level before the inline
7771 ;; task.
7772 (while (and (setq level (org-up-heading-safe))
7773 (>= level org-inlinetask-min-level)))
7774 (if (org-at-heading-p)
7775 (org-back-to-heading invisible-ok)
7776 (error "This should not happen")))
7777 (unless (and (save-excursion
7778 (save-match-data
7779 (org-backward-heading-same-level
7780 1 invisible-ok))
7781 (= (point) (match-beginning 0)))
7782 (not (org-next-line-empty-p)))
7783 (setq empty-line-p (or empty-line-p
7784 (org-previous-line-empty-p))))
7785 (match-string 0))
7786 (error (or fix-level "* ")))))
7787 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7788 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7790 ;; If we insert after content, move there and clean up
7791 ;; whitespace.
7792 (when (and respect-content
7793 (not (org-looking-at-p org-outline-regexp-bol)))
7794 (if (not (org-before-first-heading-p))
7795 (org-end-of-subtree nil t)
7796 (re-search-forward org-outline-regexp-bol)
7797 (beginning-of-line 0))
7798 (skip-chars-backward " \r\t\n")
7799 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7800 (looking-at "[ \t]+") (replace-match ""))
7801 (unless (eobp) (forward-char 1))
7802 (when (looking-at "^\\*")
7803 (unless (bobp) (backward-char 1))
7804 (insert "\n")))
7806 ;; If we are splitting, grab the text that should be moved
7807 ;; to the new headline.
7808 (when may-split
7809 (if (org-at-heading-p)
7810 ;; This is a heading: split intelligently (keeping
7811 ;; tags).
7812 (let ((pos (point)))
7813 (beginning-of-line)
7814 (unless (looking-at org-complex-heading-regexp)
7815 (error "This should not happen"))
7816 (when (and (match-beginning 4)
7817 (> pos (match-beginning 4))
7818 (< pos (match-end 4)))
7819 (setq initial-content (buffer-substring pos (match-end 4)))
7820 (goto-char pos)
7821 (delete-region (point) (match-end 4))
7822 (if (looking-at "[ \t]*$")
7823 (replace-match "")
7824 (insert (make-string (length initial-content) ?\s)))
7825 (setq initial-content (org-trim initial-content)))
7826 (goto-char pos))
7827 ;; A normal line.
7828 (setq initial-content
7829 (org-trim
7830 (delete-and-extract-region (point) (line-end-position))))))
7832 ;; If we are at the beginning of the line, insert before it.
7833 ;; Otherwise, after it.
7834 (cond
7835 ((and (bolp) (looking-at "[ \t]*$")))
7836 ((bolp) (save-excursion (insert "\n")))
7837 (t (end-of-line)
7838 (insert "\n")))
7840 ;; Insert the new heading
7841 (insert stars)
7842 (just-one-space)
7843 (insert initial-content)
7844 (unless (and blank (org-previous-line-empty-p))
7845 (org-N-empty-lines-before-current (if blank 1 0)))
7846 ;; Adjust visibility, which may be messed up if we removed
7847 ;; blank lines while previous entry was hidden.
7848 (let ((bol (line-beginning-position)))
7849 (dolist (o (overlays-at (1- bol)))
7850 (when (and (eq (overlay-get o 'invisible) 'outline)
7851 (eq (overlay-end o) bol))
7852 (move-overlay o (overlay-start o) (1- bol)))))
7853 (run-hooks 'org-insert-heading-hook)))))))
7855 (defun org-N-empty-lines-before-current (N)
7856 "Make the number of empty lines before current exactly N.
7857 So this will delete or add empty lines."
7858 (save-excursion
7859 (beginning-of-line)
7860 (let ((p (point)))
7861 (skip-chars-backward " \r\t\n")
7862 (unless (bolp) (forward-line))
7863 (delete-region (point) p))
7864 (when (> N 0) (insert (make-string N ?\n)))))
7866 (defun org-get-heading (&optional no-tags no-todo)
7867 "Return the heading of the current entry, without the stars.
7868 When NO-TAGS is non-nil, don't include tags.
7869 When NO-TODO is non-nil, don't include TODO keywords."
7870 (save-excursion
7871 (org-back-to-heading t)
7872 (cond
7873 ((and no-tags no-todo)
7874 (looking-at org-complex-heading-regexp)
7875 (match-string 4))
7876 (no-tags
7877 (looking-at (concat org-outline-regexp
7878 "\\(.*?\\)"
7879 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7880 (match-string 1))
7881 (no-todo
7882 (looking-at org-todo-line-regexp)
7883 (match-string 3))
7884 (t (looking-at org-heading-regexp)
7885 (match-string 2)))))
7887 (defvar orgstruct-mode) ; defined below
7889 (defun org-heading-components ()
7890 "Return the components of the current heading.
7891 This is a list with the following elements:
7892 - the level as an integer
7893 - the reduced level, different if `org-odd-levels-only' is set.
7894 - the TODO keyword, or nil
7895 - the priority character, like ?A, or nil if no priority is given
7896 - the headline text itself, or the tags string if no headline text
7897 - the tags string, or nil."
7898 (save-excursion
7899 (org-back-to-heading t)
7900 (when (let (case-fold-search)
7901 (looking-at
7902 (if orgstruct-mode
7903 org-heading-regexp
7904 org-complex-heading-regexp)))
7905 (if orgstruct-mode
7906 (list (length (match-string 1))
7907 (org-reduced-level (length (match-string 1)))
7910 (match-string 2)
7911 nil)
7912 (list (length (match-string 1))
7913 (org-reduced-level (length (match-string 1)))
7914 (org-match-string-no-properties 2)
7915 (and (match-end 3) (aref (match-string 3) 2))
7916 (org-match-string-no-properties 4)
7917 (org-match-string-no-properties 5))))))
7919 (defun org-get-entry ()
7920 "Get the entry text, after heading, entire subtree."
7921 (save-excursion
7922 (org-back-to-heading t)
7923 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7925 (defun org-edit-headline (&optional heading)
7926 "Edit the current headline.
7927 Set it to HEADING when provided."
7928 (interactive)
7929 (org-with-wide-buffer
7930 (org-back-to-heading t)
7931 (when (looking-at org-complex-heading-regexp)
7932 (let* ((old (match-string-no-properties 4))
7933 (new (org-trim (or heading (read-string "Edit: " old)))))
7934 (unless (equal old new)
7935 (if old (replace-match new t t nil 4)
7936 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7937 (insert " " new))
7938 (org-set-tags nil t)
7939 (when (looking-at "[ \t]*$") (replace-match "")))))))
7941 (defun org-insert-heading-after-current ()
7942 "Insert a new heading with same level as current, after current subtree."
7943 (interactive)
7944 (org-back-to-heading)
7945 (org-insert-heading)
7946 (org-move-subtree-down)
7947 (end-of-line 1))
7949 (defun org-insert-heading-respect-content (&optional invisible-ok)
7950 "Insert heading with `org-insert-heading-respect-content' set to t."
7951 (interactive)
7952 (org-insert-heading '(4) invisible-ok))
7954 (defun org-insert-todo-heading-respect-content (&optional force-state)
7955 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7956 (interactive)
7957 (org-insert-todo-heading force-state '(4)))
7959 (defun org-insert-todo-heading (arg &optional force-heading)
7960 "Insert a new heading with the same level and TODO state as current heading.
7961 If the heading has no TODO state, or if the state is DONE, use the first
7962 state (TODO by default). Also with one prefix arg, force first state. With
7963 two prefix args, force inserting at the end of the parent subtree."
7964 (interactive "P")
7965 (when (or force-heading (not (org-insert-item 'checkbox)))
7966 (org-insert-heading (or (and (equal arg '(16)) '(16))
7967 force-heading))
7968 (save-excursion
7969 (org-back-to-heading)
7970 (outline-previous-heading)
7971 (looking-at org-todo-line-regexp))
7972 (let*
7973 ((new-mark-x
7974 (if (or (equal arg '(4))
7975 (not (match-beginning 2))
7976 (member (match-string 2) org-done-keywords))
7977 (car org-todo-keywords-1)
7978 (match-string 2)))
7979 (new-mark
7981 (run-hook-with-args-until-success
7982 'org-todo-get-default-hook new-mark-x nil)
7983 new-mark-x)))
7984 (beginning-of-line 1)
7985 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7986 (if org-treat-insert-todo-heading-as-state-change
7987 (org-todo new-mark)
7988 (insert new-mark " "))))
7989 (when org-provide-todo-statistics
7990 (org-update-parent-todo-statistics))))
7992 (defun org-insert-subheading (arg)
7993 "Insert a new subheading and demote it.
7994 Works for outline headings and for plain lists alike."
7995 (interactive "P")
7996 (org-insert-heading arg)
7997 (cond
7998 ((org-at-heading-p) (org-do-demote))
7999 ((org-at-item-p) (org-indent-item))))
8001 (defun org-insert-todo-subheading (arg)
8002 "Insert a new subheading with TODO keyword or checkbox and demote it.
8003 Works for outline headings and for plain lists alike."
8004 (interactive "P")
8005 (org-insert-todo-heading arg)
8006 (cond
8007 ((org-at-heading-p) (org-do-demote))
8008 ((org-at-item-p) (org-indent-item))))
8010 ;;; Promotion and Demotion
8012 (defvar org-after-demote-entry-hook nil
8013 "Hook run after an entry has been demoted.
8014 The cursor will be at the beginning of the entry.
8015 When a subtree is being demoted, the hook will be called for each node.")
8017 (defvar org-after-promote-entry-hook nil
8018 "Hook run after an entry has been promoted.
8019 The cursor will be at the beginning of the entry.
8020 When a subtree is being promoted, the hook will be called for each node.")
8022 (defun org-promote-subtree ()
8023 "Promote the entire subtree.
8024 See also `org-promote'."
8025 (interactive)
8026 (save-excursion
8027 (org-with-limited-levels (org-map-tree 'org-promote)))
8028 (org-fix-position-after-promote))
8030 (defun org-demote-subtree ()
8031 "Demote the entire subtree.
8032 See `org-demote' and `org-promote'."
8033 (interactive)
8034 (save-excursion
8035 (org-with-limited-levels (org-map-tree 'org-demote)))
8036 (org-fix-position-after-promote))
8038 (defun org-do-promote ()
8039 "Promote the current heading higher up the tree.
8040 If the region is active in `transient-mark-mode', promote all
8041 headings in the region."
8042 (interactive)
8043 (save-excursion
8044 (if (org-region-active-p)
8045 (org-map-region 'org-promote (region-beginning) (region-end))
8046 (org-promote)))
8047 (org-fix-position-after-promote))
8049 (defun org-do-demote ()
8050 "Demote the current heading lower down the tree.
8051 If the region is active in `transient-mark-mode', demote all
8052 headings in the region."
8053 (interactive)
8054 (save-excursion
8055 (if (org-region-active-p)
8056 (org-map-region 'org-demote (region-beginning) (region-end))
8057 (org-demote)))
8058 (org-fix-position-after-promote))
8060 (defun org-fix-position-after-promote ()
8061 "Fix cursor position and indentation after demoting/promoting."
8062 (let ((pos (point)))
8063 (when (save-excursion
8064 (beginning-of-line 1)
8065 (looking-at org-todo-line-regexp)
8066 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8067 (cond ((eobp) (insert " "))
8068 ((eolp) (insert " "))
8069 ((equal (char-after) ?\ ) (forward-char 1))))))
8071 (defun org-current-level ()
8072 "Return the level of the current entry, or nil if before the first headline.
8073 The level is the number of stars at the beginning of the
8074 headline. Use `org-reduced-level' to remove the effect of
8075 `org-odd-levels'. Unlike to `org-outline-level', this function
8076 ignores inlinetasks."
8077 (let ((level (org-with-limited-levels (org-outline-level))))
8078 (and (> level 0) level)))
8080 (defun org-get-previous-line-level ()
8081 "Return the outline depth of the last headline before the current line.
8082 Returns 0 for the first headline in the buffer, and nil if before the
8083 first headline."
8084 (and (org-current-level)
8085 (or (and (/= (line-beginning-position) (point-min))
8086 (save-excursion (beginning-of-line 0) (org-current-level)))
8087 0)))
8089 (defun org-reduced-level (l)
8090 "Compute the effective level of a heading.
8091 This takes into account the setting of `org-odd-levels-only'."
8092 (cond
8093 ((zerop l) 0)
8094 (org-odd-levels-only (1+ (floor (/ l 2))))
8095 (t l)))
8097 (defun org-level-increment ()
8098 "Return the number of stars that will be added or removed at a
8099 time to headlines when structure editing, based on the value of
8100 `org-odd-levels-only'."
8101 (if org-odd-levels-only 2 1))
8103 (defun org-get-valid-level (level &optional change)
8104 "Rectify a level change under the influence of `org-odd-levels-only'
8105 LEVEL is a current level, CHANGE is by how much the level should be
8106 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8107 even level numbers will become the next higher odd number."
8108 (if org-odd-levels-only
8109 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8110 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8111 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8112 (max 1 (+ level (or change 0)))))
8113 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8115 (defun org-promote ()
8116 "Promote the current heading higher up the tree."
8117 (org-with-wide-buffer
8118 (org-back-to-heading t)
8119 (let* ((after-change-functions (remq 'flyspell-after-change-function
8120 after-change-functions))
8121 (level (save-match-data (funcall outline-level)))
8122 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8123 (diff (abs (- level (length up-head) -1))))
8124 (cond
8125 ((and (= level 1) org-allow-promoting-top-level-subtree)
8126 (replace-match "# " nil t))
8127 ((= level 1)
8128 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8129 (t (replace-match up-head nil t)))
8130 (unless (= level 1)
8131 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8132 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8133 (run-hooks 'org-after-promote-entry-hook))))
8135 (defun org-demote ()
8136 "Demote the current heading lower down the tree."
8137 (org-with-wide-buffer
8138 (org-back-to-heading t)
8139 (let* ((after-change-functions (remq 'flyspell-after-change-function
8140 after-change-functions))
8141 (level (save-match-data (funcall outline-level)))
8142 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8143 (diff (abs (- level (length down-head) -1))))
8144 (replace-match down-head nil t)
8145 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8146 (when org-adapt-indentation (org-fixup-indentation diff))
8147 (run-hooks 'org-after-demote-entry-hook))))
8149 (defun org-cycle-level ()
8150 "Cycle the level of an empty headline through possible states.
8151 This goes first to child, then to parent, level, then up the hierarchy.
8152 After top level, it switches back to sibling level."
8153 (interactive)
8154 (let ((org-adapt-indentation nil))
8155 (when (org-point-at-end-of-empty-headline)
8156 (setq this-command 'org-cycle-level) ; Only needed for caching
8157 (let ((cur-level (org-current-level))
8158 (prev-level (org-get-previous-line-level)))
8159 (cond
8160 ;; If first headline in file, promote to top-level.
8161 ((= prev-level 0)
8162 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8163 do (org-do-promote)))
8164 ;; If same level as prev, demote one.
8165 ((= prev-level cur-level)
8166 (org-do-demote))
8167 ;; If parent is top-level, promote to top level if not already.
8168 ((= prev-level 1)
8169 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8170 do (org-do-promote)))
8171 ;; If top-level, return to prev-level.
8172 ((= cur-level 1)
8173 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8174 do (org-do-demote)))
8175 ;; If less than prev-level, promote one.
8176 ((< cur-level prev-level)
8177 (org-do-promote))
8178 ;; If deeper than prev-level, promote until higher than
8179 ;; prev-level.
8180 ((> cur-level prev-level)
8181 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8182 do (org-do-promote))))
8183 t))))
8185 (defun org-map-tree (fun)
8186 "Call FUN for every heading underneath the current one."
8187 (org-back-to-heading)
8188 (let ((level (funcall outline-level)))
8189 (save-excursion
8190 (funcall fun)
8191 (while (and (progn
8192 (outline-next-heading)
8193 (> (funcall outline-level) level))
8194 (not (eobp)))
8195 (funcall fun)))))
8197 (defun org-map-region (fun beg end)
8198 "Call FUN for every heading between BEG and END."
8199 (let ((org-ignore-region t))
8200 (save-excursion
8201 (setq end (copy-marker end))
8202 (goto-char beg)
8203 (when (and (re-search-forward org-outline-regexp-bol nil t)
8204 (< (point) end))
8205 (funcall fun))
8206 (while (and (progn
8207 (outline-next-heading)
8208 (< (point) end))
8209 (not (eobp)))
8210 (funcall fun)))))
8212 (defun org-fixup-indentation (diff)
8213 "Change the indentation in the current entry by DIFF.
8215 DIFF is an integer. Indentation is done according to the
8216 following rules:
8218 - Planning information and property drawers are always indented
8219 according to the new level of the headline;
8221 - Footnote definitions and their contents are ignored;
8223 - Inlinetasks' boundaries are not shifted;
8225 - Empty lines are ignored;
8227 - Other lines' indentation are shifted by DIFF columns, unless
8228 it would introduce a structural change in the document, in
8229 which case no shifting is done at all.
8231 Assume point is at a heading or an inlinetask beginning."
8232 (org-with-wide-buffer
8233 (narrow-to-region (line-beginning-position)
8234 (save-excursion
8235 (if (org-with-limited-levels (org-at-heading-p))
8236 (org-with-limited-levels (outline-next-heading))
8237 (org-inlinetask-goto-end))
8238 (point)))
8239 (forward-line)
8240 ;; Indent properly planning info and property drawer.
8241 (when (org-looking-at-p org-planning-line-re)
8242 (org-indent-line)
8243 (forward-line))
8244 (when (looking-at org-property-drawer-re)
8245 (goto-char (match-end 0))
8246 (forward-line)
8247 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8248 (catch 'no-shift
8249 (when (zerop diff) (throw 'no-shift nil))
8250 ;; If DIFF is negative, first check if a shift is possible at all
8251 ;; (e.g., it doesn't break structure). This can only happen if
8252 ;; some contents are not properly indented.
8253 (let ((case-fold-search t))
8254 (when (< diff 0)
8255 (let ((diff (- diff))
8256 (forbidden-re (concat org-outline-regexp
8257 "\\|"
8258 (substring org-footnote-definition-re 1))))
8259 (save-excursion
8260 (while (not (eobp))
8261 (cond
8262 ((org-looking-at-p "[ \t]*$") (forward-line))
8263 ((and (org-looking-at-p org-footnote-definition-re)
8264 (let ((e (org-element-at-point)))
8265 (and (eq (org-element-type e) 'footnote-definition)
8266 (goto-char (org-element-property :end e))))))
8267 ((org-looking-at-p org-outline-regexp) (forward-line))
8268 ;; Give up if shifting would move before column 0 or
8269 ;; if it would introduce a headline or a footnote
8270 ;; definition.
8272 (skip-chars-forward " \t")
8273 (let ((ind (current-column)))
8274 (when (or (< ind diff)
8275 (and (= ind diff) (org-looking-at-p forbidden-re)))
8276 (throw 'no-shift nil)))
8277 ;; Ignore contents of example blocks and source
8278 ;; blocks if their indentation is meant to be
8279 ;; preserved. Jump to block's closing line.
8280 (beginning-of-line)
8281 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8282 (let ((e (org-element-at-point)))
8283 (and (memq (org-element-type e)
8284 '(example-block src-block))
8285 (or org-src-preserve-indentation
8286 (org-element-property :preserve-indent e))
8287 (goto-char (org-element-property :end e))
8288 (progn (skip-chars-backward " \r\t\n")
8289 (beginning-of-line)
8290 t))))
8291 (forward-line))))))))
8292 ;; Shift lines but footnote definitions, inlinetasks boundaries
8293 ;; by DIFF. Also skip contents of source or example blocks
8294 ;; when indentation is meant to be preserved.
8295 (while (not (eobp))
8296 (cond
8297 ((and (org-looking-at-p org-footnote-definition-re)
8298 (let ((e (org-element-at-point)))
8299 (and (eq (org-element-type e) 'footnote-definition)
8300 (goto-char (org-element-property :end e))))))
8301 ((org-looking-at-p org-outline-regexp) (forward-line))
8302 ((org-looking-at-p "[ \t]*$") (forward-line))
8304 (org-indent-line-to (+ (org-get-indentation) diff))
8305 (beginning-of-line)
8306 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8307 (let ((e (org-element-at-point)))
8308 (and (memq (org-element-type e)
8309 '(example-block src-block))
8310 (or org-src-preserve-indentation
8311 (org-element-property :preserve-indent e))
8312 (goto-char (org-element-property :end e))
8313 (progn (skip-chars-backward " \r\t\n")
8314 (beginning-of-line)
8315 t))))
8316 (forward-line)))))))))
8318 (defun org-convert-to-odd-levels ()
8319 "Convert an org-mode file with all levels allowed to one with odd levels.
8320 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8321 level 5 etc."
8322 (interactive)
8323 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8324 (let ((outline-level 'org-outline-level)
8325 (org-odd-levels-only nil) n)
8326 (save-excursion
8327 (goto-char (point-min))
8328 (while (re-search-forward "^\\*\\*+ " nil t)
8329 (setq n (- (length (match-string 0)) 2))
8330 (while (>= (setq n (1- n)) 0)
8331 (org-demote))
8332 (end-of-line 1))))))
8334 (defun org-convert-to-oddeven-levels ()
8335 "Convert an org-mode file with only odd levels to one with odd/even levels.
8336 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8337 file contains a section with an even level, conversion would
8338 destroy the structure of the file. An error is signaled in this
8339 case."
8340 (interactive)
8341 (goto-char (point-min))
8342 ;; First check if there are no even levels
8343 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8344 (org-show-set-visibility 'canonical)
8345 (error "Not all levels are odd in this file. Conversion not possible"))
8346 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8347 (let ((outline-regexp org-outline-regexp)
8348 (outline-level 'org-outline-level)
8349 (org-odd-levels-only nil) n)
8350 (save-excursion
8351 (goto-char (point-min))
8352 (while (re-search-forward "^\\*\\*+ " nil t)
8353 (setq n (/ (1- (length (match-string 0))) 2))
8354 (while (>= (setq n (1- n)) 0)
8355 (org-promote))
8356 (end-of-line 1))))))
8358 (defun org-tr-level (n)
8359 "Make N odd if required."
8360 (if org-odd-levels-only (1+ (/ n 2)) n))
8362 ;;; Vertical tree motion, cutting and pasting of subtrees
8364 (defun org-move-subtree-up (&optional arg)
8365 "Move the current subtree up past ARG headlines of the same level."
8366 (interactive "p")
8367 (org-move-subtree-down (- (prefix-numeric-value arg))))
8369 (defun org-move-subtree-down (&optional arg)
8370 "Move the current subtree down past ARG headlines of the same level."
8371 (interactive "p")
8372 (setq arg (prefix-numeric-value arg))
8373 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8374 'org-get-last-sibling))
8375 (ins-point (make-marker))
8376 (cnt (abs arg))
8377 (col (current-column))
8378 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8379 ;; Select the tree
8380 (org-back-to-heading)
8381 (setq beg0 (point))
8382 (save-excursion
8383 (setq ne-beg (org-back-over-empty-lines))
8384 (setq beg (point)))
8385 (save-match-data
8386 (save-excursion (outline-end-of-heading)
8387 (setq folded (outline-invisible-p)))
8388 (progn (org-end-of-subtree nil t)
8389 (unless (eobp) (backward-char))))
8390 (outline-next-heading)
8391 (setq ne-end (org-back-over-empty-lines))
8392 (setq end (point))
8393 (goto-char beg0)
8394 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8395 ;; include less whitespace
8396 (save-excursion
8397 (goto-char beg)
8398 (forward-line (- ne-beg ne-end))
8399 (setq beg (point))))
8400 ;; Find insertion point, with error handling
8401 (while (> cnt 0)
8402 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8403 (progn (goto-char beg0)
8404 (user-error "Cannot move past superior level or buffer limit")))
8405 (setq cnt (1- cnt)))
8406 (when (> arg 0)
8407 ;; Moving forward - still need to move over subtree
8408 (org-end-of-subtree t t)
8409 (save-excursion
8410 (org-back-over-empty-lines)
8411 (or (bolp) (newline))))
8412 (setq ne-ins (org-back-over-empty-lines))
8413 (move-marker ins-point (point))
8414 (setq txt (buffer-substring beg end))
8415 (org-save-markers-in-region beg end)
8416 (delete-region beg end)
8417 (org-remove-empty-overlays-at beg)
8418 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8419 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8420 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8421 (let ((bbb (point)))
8422 (insert-before-markers txt)
8423 (org-reinstall-markers-in-region bbb)
8424 (move-marker ins-point bbb))
8425 (or (bolp) (insert "\n"))
8426 (setq ins-end (point))
8427 (goto-char ins-point)
8428 (org-skip-whitespace)
8429 (when (and (< arg 0)
8430 (org-first-sibling-p)
8431 (> ne-ins ne-beg))
8432 ;; Move whitespace back to beginning
8433 (save-excursion
8434 (goto-char ins-end)
8435 (let ((kill-whole-line t))
8436 (kill-line (- ne-ins ne-beg)) (point)))
8437 (insert (make-string (- ne-ins ne-beg) ?\n)))
8438 (move-marker ins-point nil)
8439 (if folded
8440 (outline-hide-subtree)
8441 (org-show-entry)
8442 (org-show-children)
8443 (org-cycle-hide-drawers 'children))
8444 (org-clean-visibility-after-subtree-move)
8445 ;; move back to the initial column we were at
8446 (move-to-column col)))
8448 (defvar org-subtree-clip ""
8449 "Clipboard for cut and paste of subtrees.
8450 This is actually only a copy of the kill, because we use the normal kill
8451 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8453 (defvar org-subtree-clip-folded nil
8454 "Was the last copied subtree folded?
8455 This is used to fold the tree back after pasting.")
8457 (defun org-cut-subtree (&optional n)
8458 "Cut the current subtree into the clipboard.
8459 With prefix arg N, cut this many sequential subtrees.
8460 This is a short-hand for marking the subtree and then cutting it."
8461 (interactive "p")
8462 (org-copy-subtree n 'cut))
8464 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8465 "Copy the current subtree it in the clipboard.
8466 With prefix arg N, copy this many sequential subtrees.
8467 This is a short-hand for marking the subtree and then copying it.
8468 If CUT is non-nil, actually cut the subtree.
8469 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8470 of some markers in the region, even if CUT is non-nil. This is
8471 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8472 (interactive "p")
8473 (let (beg end folded (beg0 (point)))
8474 (if (org-called-interactively-p 'any)
8475 (org-back-to-heading nil) ; take what looks like a subtree
8476 (org-back-to-heading t)) ; take what is really there
8477 (setq beg (point))
8478 (skip-chars-forward " \t\r\n")
8479 (save-match-data
8480 (if nosubtrees
8481 (outline-next-heading)
8482 (save-excursion (outline-end-of-heading)
8483 (setq folded (outline-invisible-p)))
8484 (ignore-errors (org-forward-heading-same-level (1- n) t))
8485 (org-end-of-subtree t t)))
8486 ;; Include the end of an inlinetask
8487 (when (and (featurep 'org-inlinetask)
8488 (looking-at-p (concat (org-inlinetask-outline-regexp)
8489 "END[ \t]*$")))
8490 (end-of-line))
8491 (setq end (point))
8492 (goto-char beg0)
8493 (when (> end beg)
8494 (setq org-subtree-clip-folded folded)
8495 (when (or cut force-store-markers)
8496 (org-save-markers-in-region beg end))
8497 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8498 (setq org-subtree-clip (current-kill 0))
8499 (message "%s: Subtree(s) with %d characters"
8500 (if cut "Cut" "Copied")
8501 (length org-subtree-clip)))))
8503 (defun org-paste-subtree (&optional level tree for-yank remove)
8504 "Paste the clipboard as a subtree, with modification of headline level.
8505 The entire subtree is promoted or demoted in order to match a new headline
8506 level.
8508 If the cursor is at the beginning of a headline, the same level as
8509 that headline is used to paste the tree.
8511 If not, the new level is derived from the *visible* headings
8512 before and after the insertion point, and taken to be the inferior headline
8513 level of the two. So if the previous visible heading is level 3 and the
8514 next is level 4 (or vice versa), level 4 will be used for insertion.
8515 This makes sure that the subtree remains an independent subtree and does
8516 not swallow low level entries.
8518 You can also force a different level, either by using a numeric prefix
8519 argument, or by inserting the heading marker by hand. For example, if the
8520 cursor is after \"*****\", then the tree will be shifted to level 5.
8522 If optional TREE is given, use this text instead of the kill ring.
8524 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8525 move back over whitespace before inserting, and move point to the end of
8526 the inserted text when done.
8528 When REMOVE is non-nil, remove the subtree from the clipboard."
8529 (interactive "P")
8530 (setq tree (or tree (and kill-ring (current-kill 0))))
8531 (unless (org-kill-is-subtree-p tree)
8532 (user-error "%s"
8533 (substitute-command-keys
8534 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8535 (org-with-limited-levels
8536 (let* ((visp (not (outline-invisible-p)))
8537 (txt tree)
8538 (^re_ "\\(\\*+\\)[ \t]*")
8539 (old-level (if (string-match org-outline-regexp-bol txt)
8540 (- (match-end 0) (match-beginning 0) 1)
8541 -1))
8542 (force-level (cond (level (prefix-numeric-value level))
8543 ((and (looking-at "[ \t]*$")
8544 (string-match
8545 "^\\*+$" (buffer-substring
8546 (point-at-bol) (point))))
8547 (- (match-end 0) (match-beginning 0)))
8548 ((and (bolp)
8549 (looking-at org-outline-regexp))
8550 (- (match-end 0) (point) 1))))
8551 (previous-level (save-excursion
8552 (condition-case nil
8553 (progn
8554 (outline-previous-visible-heading 1)
8555 (if (looking-at ^re_)
8556 (- (match-end 0) (match-beginning 0) 1)
8558 (error 1))))
8559 (next-level (save-excursion
8560 (condition-case nil
8561 (progn
8562 (or (looking-at org-outline-regexp)
8563 (outline-next-visible-heading 1))
8564 (if (looking-at ^re_)
8565 (- (match-end 0) (match-beginning 0) 1)
8567 (error 1))))
8568 (new-level (or force-level (max previous-level next-level)))
8569 (shift (if (or (= old-level -1)
8570 (= new-level -1)
8571 (= old-level new-level))
8573 (- new-level old-level)))
8574 (delta (if (> shift 0) -1 1))
8575 (func (if (> shift 0) 'org-demote 'org-promote))
8576 (org-odd-levels-only nil)
8577 beg end newend)
8578 ;; Remove the forced level indicator
8579 (when force-level
8580 (delete-region (point-at-bol) (point)))
8581 ;; Paste
8582 (beginning-of-line (if (bolp) 1 2))
8583 (setq beg (point))
8584 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8585 (insert-before-markers txt)
8586 (unless (string-match "\n\\'" txt) (insert "\n"))
8587 (setq newend (point))
8588 (org-reinstall-markers-in-region beg)
8589 (setq end (point))
8590 (goto-char beg)
8591 (skip-chars-forward " \t\n\r")
8592 (setq beg (point))
8593 (when (and (outline-invisible-p) visp)
8594 (save-excursion (outline-show-heading)))
8595 ;; Shift if necessary
8596 (unless (= shift 0)
8597 (save-restriction
8598 (narrow-to-region beg end)
8599 (while (not (= shift 0))
8600 (org-map-region func (point-min) (point-max))
8601 (setq shift (+ delta shift)))
8602 (goto-char (point-min))
8603 (setq newend (point-max))))
8604 (when (or (org-called-interactively-p 'interactive) for-yank)
8605 (message "Clipboard pasted as level %d subtree" new-level))
8606 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8607 kill-ring
8608 (eq org-subtree-clip (current-kill 0))
8609 org-subtree-clip-folded)
8610 ;; The tree was folded before it was killed/copied
8611 (outline-hide-subtree))
8612 (and for-yank (goto-char newend))
8613 (and remove (setq kill-ring (cdr kill-ring))))))
8615 (defun org-kill-is-subtree-p (&optional txt)
8616 "Check if the current kill is an outline subtree, or a set of trees.
8617 Returns nil if kill does not start with a headline, or if the first
8618 headline level is not the largest headline level in the tree.
8619 So this will actually accept several entries of equal levels as well,
8620 which is OK for `org-paste-subtree'.
8621 If optional TXT is given, check this string instead of the current kill."
8622 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8623 (re (org-get-limited-outline-regexp))
8624 (^re (concat "^" re))
8625 (start-level (and kill
8626 (string-match
8627 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8628 kill)
8629 (- (match-end 2) (match-beginning 2) 1)))
8630 (start (1+ (or (match-beginning 2) -1))))
8631 (if (not start-level)
8632 (progn
8633 nil) ;; does not even start with a heading
8634 (catch 'exit
8635 (while (setq start (string-match ^re kill (1+ start)))
8636 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8637 (throw 'exit nil)))
8638 t))))
8640 (defvar org-markers-to-move nil
8641 "Markers that should be moved with a cut-and-paste operation.
8642 Those markers are stored together with their positions relative to
8643 the start of the region.")
8645 (defun org-save-markers-in-region (beg end)
8646 "Check markers in region.
8647 If these markers are between BEG and END, record their position relative
8648 to BEG, so that after moving the block of text, we can put the markers back
8649 into place.
8650 This function gets called just before an entry or tree gets cut from the
8651 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8652 called immediately, to move the markers with the entries."
8653 (setq org-markers-to-move nil)
8654 (when (featurep 'org-clock)
8655 (org-clock-save-markers-for-cut-and-paste beg end))
8656 (when (featurep 'org-agenda)
8657 (org-agenda-save-markers-for-cut-and-paste beg end)))
8659 (defun org-check-and-save-marker (marker beg end)
8660 "Check if MARKER is between BEG and END.
8661 If yes, remember the marker and the distance to BEG."
8662 (when (and (marker-buffer marker)
8663 (equal (marker-buffer marker) (current-buffer))
8664 (>= marker beg) (< marker end))
8665 (push (cons marker (- marker beg)) org-markers-to-move)))
8667 (defun org-reinstall-markers-in-region (beg)
8668 "Move all remembered markers to their position relative to BEG."
8669 (dolist (x org-markers-to-move)
8670 (move-marker (car x) (+ beg (cdr x))))
8671 (setq org-markers-to-move nil))
8673 (defun org-narrow-to-subtree ()
8674 "Narrow buffer to the current subtree."
8675 (interactive)
8676 (save-excursion
8677 (save-match-data
8678 (org-with-limited-levels
8679 (narrow-to-region
8680 (progn (org-back-to-heading t) (point))
8681 (progn (org-end-of-subtree t t)
8682 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8683 (point)))))))
8685 (defun org-narrow-to-block ()
8686 "Narrow buffer to the current block."
8687 (interactive)
8688 (let* ((case-fold-search t)
8689 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8690 "^[ \t]*#\\+end_.*")))
8691 (if blockp
8692 (narrow-to-region (car blockp) (cdr blockp))
8693 (user-error "Not in a block"))))
8695 (defun org-clone-subtree-with-time-shift (n &optional shift)
8696 "Clone the task (subtree) at point N times.
8697 The clones will be inserted as siblings.
8699 In interactive use, the user will be prompted for the number of
8700 clones to be produced. If the entry has a timestamp, the user
8701 will also be prompted for a time shift, which may be a repeater
8702 as used in time stamps, for example `+3d'. To disable this,
8703 you can call the function with a universal prefix argument.
8705 When a valid repeater is given and the entry contains any time
8706 stamps, the clones will become a sequence in time, with time
8707 stamps in the subtree shifted for each clone produced. If SHIFT
8708 is nil or the empty string, time stamps will be left alone. The
8709 ID property of the original subtree is removed.
8711 If the original subtree did contain time stamps with a repeater,
8712 the following will happen:
8713 - the repeater will be removed in each clone
8714 - an additional clone will be produced, with the current, unshifted
8715 date(s) in the entry.
8716 - the original entry will be placed *after* all the clones, with
8717 repeater intact.
8718 - the start days in the repeater in the original entry will be shifted
8719 to past the last clone.
8720 In this way you can spell out a number of instances of a repeating task,
8721 and still retain the repeater to cover future instances of the task.
8723 As described above, N+1 clones are produced when the original
8724 subtree has a repeater. Setting N to 0, then, can be used to
8725 remove the repeater from a subtree and create a shifted clone
8726 with the original repeater."
8727 (interactive "nNumber of clones to produce: ")
8728 (let ((shift
8729 (or shift
8730 (if (and (not (equal current-prefix-arg '(4)))
8731 (save-excursion
8732 (re-search-forward org-ts-regexp-both
8733 (save-excursion
8734 (org-end-of-subtree t)
8735 (point)) t)))
8736 (read-from-minibuffer
8737 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8738 ""))) ;; No time shift
8739 (n-no-remove -1)
8740 (drawer-re org-drawer-regexp)
8741 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8742 beg end template task idprop
8743 shift-n shift-what doshift nmin nmax)
8744 (unless (wholenump n)
8745 (user-error "Invalid number of replications %s" n))
8746 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8747 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8748 shift)))
8749 (user-error "Invalid shift specification %s" shift))
8750 (when doshift
8751 (setq shift-n (string-to-number (match-string 1 shift))
8752 shift-what (cdr (assoc (match-string 2 shift)
8753 '(("d" . day) ("w" . week)
8754 ("m" . month) ("y" . year))))))
8755 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8756 (setq nmin 1 nmax n)
8757 (org-back-to-heading t)
8758 (setq beg (point))
8759 (setq idprop (org-entry-get nil "ID"))
8760 (org-end-of-subtree t t)
8761 (or (bolp) (insert "\n"))
8762 (setq end (point))
8763 (setq template (buffer-substring beg end))
8764 (when (and doshift
8765 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8766 (delete-region beg end)
8767 (setq end beg)
8768 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8769 (goto-char end)
8770 (cl-loop for n from nmin to nmax do
8771 ;; prepare clone
8772 (with-temp-buffer
8773 (insert template)
8774 (org-mode)
8775 (goto-char (point-min))
8776 (org-show-subtree)
8777 (and idprop (if org-clone-delete-id
8778 (org-entry-delete nil "ID")
8779 (org-id-get-create t)))
8780 (unless (= n 0)
8781 (while (re-search-forward org-clock-re nil t)
8782 (kill-whole-line))
8783 (goto-char (point-min))
8784 (while (re-search-forward drawer-re nil t)
8785 (org-remove-empty-drawer-at (point))))
8786 (goto-char (point-min))
8787 (when doshift
8788 (while (re-search-forward org-ts-regexp-both nil t)
8789 (org-timestamp-change (* n shift-n) shift-what))
8790 (unless (= n n-no-remove)
8791 (goto-char (point-min))
8792 (while (re-search-forward org-ts-regexp nil t)
8793 (save-excursion
8794 (goto-char (match-beginning 0))
8795 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8796 (delete-region (match-beginning 1) (match-end 1)))))))
8797 (setq task (buffer-string)))
8798 (insert task))
8799 (goto-char beg)))
8801 ;;; Outline Sorting
8803 (defun org-sort (with-case)
8804 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8805 Optional argument WITH-CASE means sort case-sensitively."
8806 (interactive "P")
8807 (cond
8808 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8809 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8811 (org-call-with-arg 'org-sort-entries with-case))))
8813 (defun org-sort-remove-invisible (s)
8814 "Remove invisible links from string S."
8815 (remove-text-properties 0 (length s) org-rm-props s)
8816 (while (string-match org-bracket-link-regexp s)
8817 (setq s (replace-match (if (match-end 2)
8818 (match-string 3 s)
8819 (match-string 1 s))
8820 t t s)))
8821 (let ((st (format " %s " s)))
8822 (while (string-match org-emph-re st)
8823 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8824 (setq s (substring st 1 -1)))
8827 (defvar org-priority-regexp) ; defined later in the file
8829 (defvar org-after-sorting-entries-or-items-hook nil
8830 "Hook that is run after a bunch of entries or items have been sorted.
8831 When children are sorted, the cursor is in the parent line when this
8832 hook gets called. When a region or a plain list is sorted, the cursor
8833 will be in the first entry of the sorted region/list.")
8835 (defun org-sort-entries
8836 (&optional with-case sorting-type getkey-func compare-func property)
8837 "Sort entries on a certain level of an outline tree.
8838 If there is an active region, the entries in the region are sorted.
8839 Else, if the cursor is before the first entry, sort the top-level items.
8840 Else, the children of the entry at point are sorted.
8842 Sorting can be alphabetically, numerically, by date/time as given by
8843 a time stamp, by a property, by priority order, or by a custom function.
8845 The command prompts for the sorting type unless it has been given to the
8846 function through the SORTING-TYPE argument, which needs to be a character,
8847 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8848 the precise meaning of each character:
8850 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8851 c By creation time, which is assumed to be the first inactive time stamp
8852 at the beginning of a line.
8853 d By deadline date/time.
8854 k By clocking time.
8855 n Numerically, by converting the beginning of the entry/item to a number.
8856 o By order of TODO keywords.
8857 p By priority according to the cookie.
8858 r By the value of a property.
8859 s By scheduled date/time.
8860 t By date/time, either the first active time stamp in the entry, or, if
8861 none exist, by the first inactive one.
8863 Capital letters will reverse the sort order.
8865 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8866 called with point at the beginning of the record. It must return either
8867 a string or a number that should serve as the sorting key for that record.
8869 Comparing entries ignores case by default. However, with an optional argument
8870 WITH-CASE, the sorting considers case as well.
8872 Sorting is done against the visible part of the headlines, it ignores hidden
8873 links.
8875 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8876 (interactive "P")
8877 (let ((case-func (if with-case 'identity 'downcase))
8878 (cmstr
8879 ;; The clock marker is lost when using `sort-subr', let's
8880 ;; store the clocking string.
8881 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8882 (save-excursion
8883 (goto-char org-clock-marker)
8884 (buffer-substring-no-properties (line-beginning-position)
8885 (point)))))
8886 start beg end stars re re2
8887 txt what tmp)
8888 ;; Find beginning and end of region to sort
8889 (cond
8890 ((org-region-active-p)
8891 ;; we will sort the region
8892 (setq end (region-end)
8893 what "region")
8894 (goto-char (region-beginning))
8895 (unless (org-at-heading-p) (outline-next-heading))
8896 (setq start (point)))
8897 ((or (org-at-heading-p)
8898 (ignore-errors (progn (org-back-to-heading) t)))
8899 ;; we will sort the children of the current headline
8900 (org-back-to-heading)
8901 (setq start (point)
8902 end (progn (org-end-of-subtree t t)
8903 (or (bolp) (insert "\n"))
8904 (when (>= (org-back-over-empty-lines) 1)
8905 (forward-line 1))
8906 (point))
8907 what "children")
8908 (goto-char start)
8909 (outline-show-subtree)
8910 (outline-next-heading))
8912 ;; we will sort the top-level entries in this file
8913 (goto-char (point-min))
8914 (or (org-at-heading-p) (outline-next-heading))
8915 (setq start (point))
8916 (goto-char (point-max))
8917 (beginning-of-line 1)
8918 (when (looking-at ".*?\\S-")
8919 ;; File ends in a non-white line
8920 (end-of-line 1)
8921 (insert "\n"))
8922 (setq end (point-max))
8923 (setq what "top-level")
8924 (goto-char start)
8925 (outline-show-all)))
8927 (setq beg (point))
8928 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8930 (looking-at "\\(\\*+\\)")
8931 (setq stars (match-string 1)
8932 re (concat "^" (regexp-quote stars) " +")
8933 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8934 txt (buffer-substring beg end))
8935 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8936 (when (and (not (equal stars "*")) (string-match re2 txt))
8937 (user-error "Region to sort contains a level above the first entry"))
8939 (unless sorting-type
8940 (message
8941 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8942 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8943 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8944 what)
8945 (setq sorting-type (read-char-exclusive))
8947 (unless getkey-func
8948 (and (= (downcase sorting-type) ?f)
8949 (setq getkey-func
8950 (completing-read "Sort using function: "
8951 obarray 'fboundp t nil nil))
8952 (setq getkey-func (intern getkey-func))))
8954 (and (= (downcase sorting-type) ?r)
8955 (not property)
8956 (setq property
8957 (completing-read "Property: "
8958 (mapcar #'list (org-buffer-property-keys t))
8959 nil t))))
8961 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8962 (message "Sorting entries...")
8964 (save-restriction
8965 (narrow-to-region start end)
8966 (let ((dcst (downcase sorting-type))
8967 (case-fold-search nil)
8968 (now (current-time)))
8969 (sort-subr
8970 (/= dcst sorting-type)
8971 ;; This function moves to the beginning character of the "record" to
8972 ;; be sorted.
8973 (lambda nil
8974 (if (re-search-forward re nil t)
8975 (goto-char (match-beginning 0))
8976 (goto-char (point-max))))
8977 ;; This function moves to the last character of the "record" being
8978 ;; sorted.
8979 (lambda nil
8980 (save-match-data
8981 (condition-case nil
8982 (outline-forward-same-level 1)
8983 (error
8984 (goto-char (point-max))))))
8985 ;; This function returns the value that gets sorted against.
8986 (lambda nil
8987 (cond
8988 ((= dcst ?n)
8989 (if (looking-at org-complex-heading-regexp)
8990 (string-to-number (org-sort-remove-invisible (match-string 4)))
8991 nil))
8992 ((= dcst ?a)
8993 (if (looking-at org-complex-heading-regexp)
8994 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8995 nil))
8996 ((= dcst ?k)
8997 (or (get-text-property (point) :org-clock-minutes) 0))
8998 ((= dcst ?t)
8999 (let ((end (save-excursion (outline-next-heading) (point))))
9000 (if (or (re-search-forward org-ts-regexp end t)
9001 (re-search-forward org-ts-regexp-both end t))
9002 (org-time-string-to-seconds (match-string 0))
9003 (org-float-time now))))
9004 ((= dcst ?c)
9005 (let ((end (save-excursion (outline-next-heading) (point))))
9006 (if (re-search-forward
9007 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9008 end t)
9009 (org-time-string-to-seconds (match-string 0))
9010 (org-float-time now))))
9011 ((= dcst ?s)
9012 (let ((end (save-excursion (outline-next-heading) (point))))
9013 (if (re-search-forward org-scheduled-time-regexp end t)
9014 (org-time-string-to-seconds (match-string 1))
9015 (org-float-time now))))
9016 ((= dcst ?d)
9017 (let ((end (save-excursion (outline-next-heading) (point))))
9018 (if (re-search-forward org-deadline-time-regexp end t)
9019 (org-time-string-to-seconds (match-string 1))
9020 (org-float-time now))))
9021 ((= dcst ?p)
9022 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9023 (string-to-char (match-string 2))
9024 org-default-priority))
9025 ((= dcst ?r)
9026 (or (org-entry-get nil property) ""))
9027 ((= dcst ?o)
9028 (when (looking-at org-complex-heading-regexp)
9029 (let* ((m (match-string 2))
9030 (s (if (member m org-done-keywords) '- '+)))
9031 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9032 ((= dcst ?f)
9033 (if getkey-func
9034 (progn
9035 (setq tmp (funcall getkey-func))
9036 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9037 tmp)
9038 (error "Invalid key function `%s'" getkey-func)))
9039 (t (error "Invalid sorting type `%c'" sorting-type))))
9041 (cond
9042 ((= dcst ?a) 'string<)
9043 ((= dcst ?f) compare-func)
9044 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9045 (run-hooks 'org-after-sorting-entries-or-items-hook)
9046 ;; Reset the clock marker if needed
9047 (when cmstr
9048 (save-excursion
9049 (goto-char start)
9050 (search-forward cmstr nil t)
9051 (move-marker org-clock-marker (point))))
9052 (message "Sorting entries...done")))
9054 ;;; The orgstruct minor mode
9056 ;; Define a minor mode which can be used in other modes in order to
9057 ;; integrate the org-mode structure editing commands.
9059 ;; This is really a hack, because the org-mode structure commands use
9060 ;; keys which normally belong to the major mode. Here is how it
9061 ;; works: The minor mode defines all the keys necessary to operate the
9062 ;; structure commands, but wraps the commands into a function which
9063 ;; tests if the cursor is currently at a headline or a plain list
9064 ;; item. If that is the case, the structure command is used,
9065 ;; temporarily setting many Org-mode variables like regular
9066 ;; expressions for filling etc. However, when any of those keys is
9067 ;; used at a different location, function uses `key-binding' to look
9068 ;; up if the key has an associated command in another currently active
9069 ;; keymap (minor modes, major mode, global), and executes that
9070 ;; command. There might be problems if any of the keys is otherwise
9071 ;; used as a prefix key.
9073 (defcustom orgstruct-heading-prefix-regexp ""
9074 "Regexp that matches the custom prefix of Org headlines in
9075 orgstruct(++)-mode."
9076 :group 'org
9077 :version "24.4"
9078 :package-version '(Org . "8.3")
9079 :type 'regexp)
9080 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9082 (defcustom orgstruct-setup-hook nil
9083 "Hook run after orgstruct-mode-map is filled."
9084 :group 'org
9085 :version "24.4"
9086 :package-version '(Org . "8.0")
9087 :type 'hook)
9089 (defvar orgstruct-initialized nil)
9091 (defvar org-local-vars nil
9092 "List of local variables, for use by `orgstruct-mode'.")
9094 ;;;###autoload
9095 (define-minor-mode orgstruct-mode
9096 "Toggle the minor mode `orgstruct-mode'.
9097 This mode is for using Org-mode structure commands in other
9098 modes. The following keys behave as if Org-mode were active, if
9099 the cursor is on a headline, or on a plain list item (both as
9100 defined by Org-mode)."
9101 nil " OrgStruct" (make-sparse-keymap)
9102 (funcall (if orgstruct-mode
9103 'add-to-invisibility-spec
9104 'remove-from-invisibility-spec)
9105 '(outline . t))
9106 (when orgstruct-mode
9107 (org-load-modules-maybe)
9108 (unless orgstruct-initialized
9109 (orgstruct-setup)
9110 (setq orgstruct-initialized t))))
9112 ;;;###autoload
9113 (defun turn-on-orgstruct ()
9114 "Unconditionally turn on `orgstruct-mode'."
9115 (orgstruct-mode 1))
9117 (defvar-local orgstruct-is-++ nil
9118 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9119 (defvar-local org-fb-vars nil)
9120 (defun orgstruct++-mode (&optional arg)
9121 "Toggle `orgstruct-mode', the enhanced version of it.
9122 In addition to setting orgstruct-mode, this also exports all
9123 indentation and autofilling variables from org-mode into the
9124 buffer. It will also recognize item context in multiline items."
9125 (interactive "P")
9126 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9127 (if (< arg 1)
9128 (progn (orgstruct-mode -1)
9129 (dolist (v org-fb-vars)
9130 (set (make-local-variable (car v))
9131 (if (eq (car-safe (cadr v)) 'quote)
9132 (cl-cadadr v)
9133 (nth 1 v)))))
9134 (orgstruct-mode 1)
9135 (setq org-fb-vars nil)
9136 (unless org-local-vars
9137 (setq org-local-vars (org-get-local-variables)))
9138 (let (var val)
9139 (dolist (x org-local-vars)
9140 (when (string-match
9141 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9142 \\|fill-prefix\\|indent-\\)"
9143 (symbol-name (car x)))
9144 (setq var (car x) val (nth 1 x))
9145 (push (list var `(quote ,(eval var))) org-fb-vars)
9146 (set (make-local-variable var)
9147 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9148 (setq-local orgstruct-is-++ t))))
9150 ;;;###autoload
9151 (defun turn-on-orgstruct++ ()
9152 "Unconditionally turn on `orgstruct++-mode'."
9153 (orgstruct++-mode 1))
9155 (defun orgstruct-error ()
9156 "Error when there is no default binding for a structure key."
9157 (interactive)
9158 (funcall (if (fboundp 'user-error)
9159 'user-error
9160 'error)
9161 "This key has no function outside structure elements"))
9163 (defun orgstruct-setup ()
9164 "Setup orgstruct keymap."
9165 (dolist (cell '((org-demote . t)
9166 (org-metaleft . t)
9167 (org-metaright . t)
9168 (org-promote . t)
9169 (org-shiftmetaleft . t)
9170 (org-shiftmetaright . t)
9171 org-backward-element
9172 org-backward-heading-same-level
9173 org-ctrl-c-ret
9174 org-ctrl-c-minus
9175 org-ctrl-c-star
9176 org-cycle
9177 org-force-cycle-archived
9178 org-forward-heading-same-level
9179 org-insert-heading
9180 org-insert-heading-respect-content
9181 org-kill-note-or-show-branches
9182 org-mark-subtree
9183 org-meta-return
9184 org-metadown
9185 org-metaup
9186 org-narrow-to-subtree
9187 org-promote-subtree
9188 org-reveal
9189 org-shiftdown
9190 org-shiftleft
9191 org-shiftmetadown
9192 org-shiftmetaup
9193 org-shiftright
9194 org-shifttab
9195 org-shifttab
9196 org-shiftup
9197 org-show-children
9198 org-show-subtree
9199 org-sort
9200 org-up-element
9201 outline-demote
9202 outline-next-visible-heading
9203 outline-previous-visible-heading
9204 outline-promote
9205 outline-up-heading))
9206 (let ((f (or (car-safe cell) cell))
9207 (disable-when-heading-prefix (cdr-safe cell)))
9208 (when (fboundp f)
9209 (let ((new-bindings))
9210 (dolist (binding (nconc (where-is-internal f org-mode-map)
9211 (where-is-internal f outline-mode-map)))
9212 (push binding new-bindings)
9213 ;; TODO use local-function-key-map
9214 (dolist (rep '(("<tab>" . "TAB")
9215 ("<return>" . "RET")
9216 ("<escape>" . "ESC")
9217 ("<delete>" . "DEL")))
9218 (setq binding (read-kbd-macro
9219 (let ((case-fold-search))
9220 (replace-regexp-in-string
9221 (regexp-quote (cdr rep))
9222 (car rep)
9223 (key-description binding)))))
9224 (cl-pushnew binding new-bindings :test 'equal)))
9225 (dolist (binding new-bindings)
9226 (let ((key (lookup-key orgstruct-mode-map binding)))
9227 (when (or (not key) (numberp key))
9228 (ignore-errors
9229 (org-defkey orgstruct-mode-map
9230 binding
9231 (orgstruct-make-binding
9232 f binding disable-when-heading-prefix))))))))))
9233 (run-hooks 'orgstruct-setup-hook))
9235 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9236 "Create a function for binding in the structure minor mode.
9237 FUN is the command to call inside a table. KEY is the key that
9238 should be checked in for a command to execute outside of tables.
9239 Non-nil `disable-when-heading-prefix' means to disable the command
9240 if `orgstruct-heading-prefix-regexp' is not empty."
9241 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9242 (let ((nname name)
9243 (i 0))
9244 (while (fboundp (intern nname))
9245 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9246 (setq name (intern nname)))
9247 (eval
9248 (let ((bindings '((org-heading-regexp
9249 (concat "^"
9250 orgstruct-heading-prefix-regexp
9251 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9252 (org-outline-regexp
9253 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9254 (org-outline-regexp-bol
9255 (concat "^" org-outline-regexp))
9256 (outline-regexp org-outline-regexp)
9257 (outline-heading-end-regexp "\n")
9258 (outline-level 'org-outline-level)
9259 (outline-heading-alist))))
9260 `(defun ,name (arg)
9261 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9262 "Outside of structure, run the binding of `"
9263 (key-description key) "'."
9264 (when disable-when-heading-prefix
9265 (concat
9266 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9267 "back to the default binding due to limitations of Org's implementation of\n"
9268 "`" (symbol-name fun) "'.")))
9269 (interactive "p")
9270 (let* ((disable
9271 ,(and disable-when-heading-prefix
9272 '(not (string= orgstruct-heading-prefix-regexp ""))))
9273 (fallback
9274 (or disable
9275 (not
9276 (let* ,bindings
9277 (org-context-p 'headline 'item
9278 ,(when (memq fun
9279 '(org-insert-heading
9280 org-insert-heading-respect-content
9281 org-meta-return))
9282 '(when orgstruct-is-++
9283 'item-body))))))))
9284 (if fallback
9285 (let* ((orgstruct-mode)
9286 (binding
9287 (let ((key ,key))
9288 (catch 'exit
9289 (dolist
9290 (rep
9291 '(nil
9292 ("<\\([^>]*\\)tab>" . "\\1TAB")
9293 ("<\\([^>]*\\)return>" . "\\1RET")
9294 ("<\\([^>]*\\)escape>" . "\\1ESC")
9295 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9296 nil)
9297 (when rep
9298 (setq key (read-kbd-macro
9299 (let ((case-fold-search))
9300 (replace-regexp-in-string
9301 (car rep)
9302 (cdr rep)
9303 (key-description key))))))
9304 (when (key-binding key)
9305 (throw 'exit (key-binding key))))))))
9306 (if (keymapp binding)
9307 (org-set-transient-map binding)
9308 (let ((func (or binding
9309 (unless disable
9310 'orgstruct-error))))
9311 (when func
9312 (call-interactively func)))))
9313 (org-run-like-in-org-mode
9314 (lambda ()
9315 (interactive)
9316 (let* ,bindings
9317 (call-interactively ',fun)))))))))
9318 name))
9320 (defun org-contextualize-keys (alist contexts)
9321 "Return valid elements in ALIST depending on CONTEXTS.
9323 `org-agenda-custom-commands' or `org-capture-templates' are the
9324 values used for ALIST, and `org-agenda-custom-commands-contexts'
9325 or `org-capture-templates-contexts' are the associated contexts
9326 definitions."
9327 (let ((contexts
9328 ;; normalize contexts
9329 (mapcar
9330 (lambda(c) (cond ((listp (cadr c))
9331 (list (car c) (car c) (nth 1 c)))
9332 ((string= "" (cadr c))
9333 (list (car c) (car c) (nth 2 c)))
9334 (t c)))
9335 contexts))
9336 (a alist) r s)
9337 ;; loop over all commands or templates
9338 (dolist (c a)
9339 (let (vrules repl)
9340 (cond
9341 ((not (assoc (car c) contexts))
9342 (push c r))
9343 ((and (assoc (car c) contexts)
9344 (setq vrules (org-contextualize-validate-key
9345 (car c) contexts)))
9346 (mapc (lambda (vr)
9347 (unless (equal (car vr) (cadr vr))
9348 (setq repl vr)))
9349 vrules)
9350 (if (not repl) (push c r)
9351 (push (cadr repl) s)
9352 (push
9353 (cons (car c)
9354 (cdr (or (assoc (cadr repl) alist)
9355 (error "Undefined key `%s' as contextual replacement for `%s'"
9356 (cadr repl) (car c)))))
9357 r))))))
9358 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9359 (delq
9361 (delete-dups
9362 (mapcar (lambda (x)
9363 (let ((tpl (car x)))
9364 (unless (delq
9366 (mapcar (lambda (y)
9367 (equal y tpl))
9369 x)))
9370 (reverse r))))))
9372 (defun org-contextualize-validate-key (key contexts)
9373 "Check CONTEXTS for agenda or capture KEY."
9374 (let (res)
9375 (dolist (r contexts)
9376 (dolist (rr (car (last r)))
9377 (when
9378 (and (equal key (car r))
9379 (if (functionp rr) (funcall rr)
9380 (or (and (eq (car rr) 'in-file)
9381 (buffer-file-name)
9382 (string-match (cdr rr) (buffer-file-name)))
9383 (and (eq (car rr) 'in-mode)
9384 (string-match (cdr rr) (symbol-name major-mode)))
9385 (and (eq (car rr) 'in-buffer)
9386 (string-match (cdr rr) (buffer-name)))
9387 (when (and (eq (car rr) 'not-in-file)
9388 (buffer-file-name))
9389 (not (string-match (cdr rr) (buffer-file-name))))
9390 (when (eq (car rr) 'not-in-mode)
9391 (not (string-match (cdr rr) (symbol-name major-mode))))
9392 (when (eq (car rr) 'not-in-buffer)
9393 (not (string-match (cdr rr) (buffer-name)))))))
9394 (push r res))))
9395 (delete-dups (delq nil res))))
9397 (defun org-context-p (&rest contexts)
9398 "Check if local context is any of CONTEXTS.
9399 Possible values in the list of contexts are `table', `headline', and `item'."
9400 (let ((pos (point)))
9401 (goto-char (point-at-bol))
9402 (prog1 (or (and (memq 'table contexts)
9403 (looking-at "[ \t]*|"))
9404 (and (memq 'headline contexts)
9405 (looking-at org-outline-regexp))
9406 (and (memq 'item contexts)
9407 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9408 (and (memq 'item-body contexts)
9409 (org-in-item-p)))
9410 (goto-char pos))))
9412 (defconst org-unique-local-variables
9413 '(org-element--cache
9414 org-element--cache-objects
9415 org-element--cache-sync-keys
9416 org-element--cache-sync-requests
9417 org-element--cache-sync-timer)
9418 "List of local variables that cannot be transferred to another buffer.")
9420 (defun org-get-local-variables ()
9421 "Return a list of all local variables in an Org mode buffer."
9422 (delq nil
9423 (mapcar
9424 (lambda (x)
9425 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9426 (name (car binding)))
9427 (and (not (get name 'org-state))
9428 (not (memq name org-unique-local-variables))
9429 (string-match-p
9430 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9431 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9432 (symbol-name name))
9433 binding)))
9434 (with-temp-buffer
9435 (org-mode)
9436 (buffer-local-variables)))))
9438 (defun org-clone-local-variables (from-buffer &optional regexp)
9439 "Clone local variables from FROM-BUFFER.
9440 Optional argument REGEXP selects variables to clone."
9441 (dolist (pair (buffer-local-variables from-buffer))
9442 (let ((name (car pair)))
9443 (when (and (symbolp name)
9444 (not (memq name org-unique-local-variables))
9445 (or (null regexp) (string-match regexp (symbol-name name))))
9446 (set (make-local-variable name) (cdr pair))))))
9448 ;;;###autoload
9449 (defun org-run-like-in-org-mode (cmd)
9450 "Run a command, pretending that the current buffer is in Org-mode.
9451 This will temporarily bind local variables that are typically bound in
9452 Org-mode to the values they have in Org-mode, and then interactively
9453 call CMD."
9454 (org-load-modules-maybe)
9455 (unless org-local-vars
9456 (setq org-local-vars (org-get-local-variables)))
9457 (let (binds)
9458 (dolist (var org-local-vars)
9459 (when (or (not (boundp (car var)))
9460 (eq (symbol-value (car var))
9461 (default-value (car var))))
9462 (push (list (car var) `(quote ,(cadr var))) binds)))
9463 (eval `(let ,binds
9464 (call-interactively (quote ,cmd))))))
9466 (defun org-get-category (&optional pos force-refresh)
9467 "Get the category applying to position POS."
9468 (save-match-data
9469 (when force-refresh (org-refresh-category-properties))
9470 (let ((pos (or pos (point))))
9471 (or (get-text-property pos 'org-category)
9472 (progn (org-refresh-category-properties)
9473 (get-text-property pos 'org-category))))))
9475 ;;; Refresh properties
9477 (defun org-refresh-properties (dprop tprop)
9478 "Refresh buffer text properties.
9479 DPROP is the drawer property and TPROP is either the
9480 corresponding text property to set, or an alist with each element
9481 being a text property (as a symbol) and a function to apply to
9482 the value of the drawer property."
9483 (let ((case-fold-search t)
9484 (inhibit-read-only t))
9485 (org-with-silent-modifications
9486 (save-excursion
9487 (save-restriction
9488 (widen)
9489 (goto-char (point-min))
9490 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9491 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9493 (defun org-refresh-property (tprop p)
9494 "Refresh the buffer text property TPROP from the drawer property P.
9495 The refresh happens only for the current tree (not subtree)."
9496 (unless (org-before-first-heading-p)
9497 (save-excursion
9498 (org-back-to-heading t)
9499 (if (symbolp tprop)
9500 ;; TPROP is a text property symbol
9501 (put-text-property
9502 (point) (or (outline-next-heading) (point-max)) tprop p)
9503 ;; TPROP is an alist with (properties . function) elements
9504 (dolist (al tprop)
9505 (save-excursion
9506 (put-text-property
9507 (line-beginning-position) (or (outline-next-heading) (point-max))
9508 (car al)
9509 (funcall (cdr al) p))))))))
9511 (defun org-refresh-category-properties ()
9512 "Refresh category text properties in the buffer."
9513 (let ((case-fold-search t)
9514 (inhibit-read-only t)
9515 (default-category
9516 (cond ((null org-category)
9517 (if buffer-file-name
9518 (file-name-sans-extension
9519 (file-name-nondirectory buffer-file-name))
9520 "???"))
9521 ((symbolp org-category) (symbol-name org-category))
9522 (t org-category))))
9523 (org-with-silent-modifications
9524 (org-with-wide-buffer
9525 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9526 ;; This is the default category for the buffer. If none is
9527 ;; found, fall-back to `org-category' or buffer file name.
9528 (put-text-property
9529 (point-min) (point-max)
9530 'org-category
9531 (catch 'buffer-category
9532 (goto-char (point-max))
9533 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9534 (let ((element (org-element-at-point)))
9535 (when (eq (org-element-type element) 'keyword)
9536 (throw 'buffer-category
9537 (org-element-property :value element)))))
9538 default-category))
9539 ;; Set sub-tree specific categories.
9540 (goto-char (point-min))
9541 (let ((regexp (org-re-property "CATEGORY")))
9542 (while (re-search-forward regexp nil t)
9543 (let ((value (org-match-string-no-properties 3)))
9544 (when (org-at-property-p)
9545 (put-text-property
9546 (save-excursion (org-back-to-heading t) (point))
9547 (save-excursion (org-end-of-subtree t t) (point))
9548 'org-category
9549 value)))))))))
9551 (defun org-refresh-stats-properties ()
9552 "Refresh stats text properties in the buffer."
9553 (let (stats)
9554 (org-with-silent-modifications
9555 (save-excursion
9556 (save-restriction
9557 (widen)
9558 (goto-char (point-min))
9559 (while (re-search-forward
9560 (concat org-outline-regexp-bol ".*"
9561 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9562 nil t)
9563 (setq stats (cond ((equal (match-string 3) "0") 0)
9564 ((match-string 2)
9565 (/ (* (string-to-number (match-string 2)) 100)
9566 (string-to-number (match-string 3))))
9567 (t (string-to-number (match-string 1)))))
9568 (org-back-to-heading t)
9569 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9570 'org-stats stats)))))))
9572 (defun org-refresh-effort-properties ()
9573 "Refresh effort properties"
9574 (org-refresh-properties
9575 org-effort-property
9576 '((effort . identity)
9577 (effort-minutes . org-duration-string-to-minutes))))
9579 ;;;; Link Stuff
9581 ;;; Link abbreviations
9583 (defun org-link-expand-abbrev (link)
9584 "Apply replacements as defined in `org-link-abbrev-alist'."
9585 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9586 (let* ((key (match-string 1 link))
9587 (as (or (assoc key org-link-abbrev-alist-local)
9588 (assoc key org-link-abbrev-alist)))
9589 (tag (and (match-end 2) (match-string 3 link)))
9590 rpl)
9591 (if (not as)
9592 link
9593 (setq rpl (cdr as))
9594 (cond
9595 ((symbolp rpl) (funcall rpl tag))
9596 ((string-match "%(\\([^)]+\\))" rpl)
9597 (replace-match
9598 (save-match-data
9599 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9600 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9601 ((string-match "%h" rpl)
9602 (replace-match (url-hexify-string (or tag "")) t t rpl))
9603 (t (concat rpl tag)))))
9604 link))
9606 ;;; Storing and inserting links
9608 (defvar org-insert-link-history nil
9609 "Minibuffer history for links inserted with `org-insert-link'.")
9611 (defvar org-stored-links nil
9612 "Contains the links stored with `org-store-link'.")
9614 (defvar org-store-link-plist nil
9615 "Plist with info about the most recently link created with `org-store-link'.")
9617 (defvar org-link-protocols nil
9618 "Link protocols added to Org-mode using `org-add-link-type'.")
9620 (defvar org-store-link-functions nil
9621 "List of functions that are called to create and store a link.
9622 Each function will be called in turn until one returns a non-nil
9623 value. Each function should check if it is responsible for creating
9624 this link (for example by looking at the major mode).
9625 If not, it must exit and return nil.
9626 If yes, it should return a non-nil value after a calling
9627 `org-store-link-props' with a list of properties and values.
9628 Special properties are:
9630 :type The link prefix, like \"http\". This must be given.
9631 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9632 This is obligatory as well.
9633 :description Optional default description for the second pair
9634 of brackets in an Org-mode link. The user can still change
9635 this when inserting this link into an Org-mode buffer.
9637 In addition to these, any additional properties can be specified
9638 and then used in capture templates.")
9640 (defun org-add-link-type (type &optional follow export)
9641 "Add TYPE to the list of `org-link-types'.
9642 Re-compute all regular expressions depending on `org-link-types'
9644 FOLLOW and EXPORT are two functions.
9646 FOLLOW should take the link path as the single argument and do whatever
9647 is necessary to follow the link, for example find a file or display
9648 a mail message.
9650 EXPORT should format the link path for export to one of the export formats.
9651 It should be a function accepting three arguments:
9653 path the path of the link, the text after the prefix (like \"http:\")
9654 desc the description of the link, if any
9655 format the export format, a symbol like `html' or `latex' or `ascii'.
9657 The function may use the FORMAT information to return different values
9658 depending on the format. The return value will be put literally into
9659 the exported file. If the return value is nil, this means Org should
9660 do what it normally does with links which do not have EXPORT defined.
9662 Org mode has a built-in default for exporting links. If you are happy with
9663 this default, there is no need to define an export function for the link
9664 type. For a simple example of an export function, see `org-bbdb.el'."
9665 (add-to-list 'org-link-types type t)
9666 (org-make-link-regexps)
9667 (org-element-update-syntax)
9668 (if (assoc type org-link-protocols)
9669 (setcdr (assoc type org-link-protocols) (list follow export))
9670 (push (list type follow export) org-link-protocols)))
9672 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9673 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9675 ;;;###autoload
9676 (defun org-store-link (arg)
9677 "\\<org-mode-map>Store an org-link to the current location.
9678 This link is added to `org-stored-links' and can later be inserted
9679 into an Org buffer with \\[org-insert-link].
9681 For some link types, a prefix ARG is interpreted.
9682 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9683 For file links, ARG negates `org-context-in-file-links'.
9685 A double prefix ARG force skipping storing functions that are not
9686 part of Org's core.
9688 A triple prefix ARG force storing a link for each line in the
9689 active region."
9690 (interactive "P")
9691 (org-load-modules-maybe)
9692 (if (and (equal arg '(64)) (org-region-active-p))
9693 (save-excursion
9694 (let ((end (region-end)))
9695 (goto-char (region-beginning))
9696 (set-mark (point))
9697 (while (< (point-at-eol) end)
9698 (move-end-of-line 1) (activate-mark)
9699 (let (current-prefix-arg)
9700 (call-interactively 'org-store-link))
9701 (move-beginning-of-line 2)
9702 (set-mark (point)))))
9703 (org-with-limited-levels
9704 (setq org-store-link-plist nil)
9705 (let (link cpltxt desc description search
9706 txt custom-id agenda-link sfuns sfunsn)
9707 (cond
9709 ;; Store a link using an external link type
9710 ((and (not (equal arg '(16)))
9711 (setq sfuns
9712 (delq
9713 nil (mapcar (lambda (f)
9714 (let (fs) (if (funcall f) (push f fs))))
9715 org-store-link-functions))
9716 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9717 (or (and (cdr sfuns)
9718 (funcall (intern
9719 (completing-read
9720 "Which function for creating the link? "
9721 sfunsn nil t (car sfunsn)))))
9722 (funcall (caar sfuns)))
9723 (setq link (plist-get org-store-link-plist :link)
9724 desc (or (plist-get org-store-link-plist
9725 :description)
9726 link))))
9728 ;; Store a link from a source code buffer.
9729 ((org-src-edit-buffer-p)
9730 (cond
9731 ((save-excursion
9732 (beginning-of-line)
9733 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9734 "[ \t]*$")))
9735 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9736 ((org-called-interactively-p 'any)
9737 (let (label)
9738 (while (or (not label)
9739 (org-with-wide-buffer
9740 (goto-char (point-min))
9741 (re-search-forward
9742 (regexp-quote (format org-coderef-label-format label))
9743 nil t)))
9744 (when label (message "Label exists already") (sit-for 2))
9745 (setq label (read-string "Code line label: " label)))
9746 (end-of-line)
9747 (setq link (format org-coderef-label-format label))
9748 (let ((gc (- 79 (length link))))
9749 (if (< (current-column) gc) (org-move-to-column gc t)
9750 (insert " ")))
9751 (insert link)
9752 (setq link (concat "(" label ")") desc nil)))
9753 (t (setq link nil))))
9755 ;; We are in the agenda, link to referenced location
9756 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9757 (let ((m (or (get-text-property (point) 'org-hd-marker)
9758 (get-text-property (point) 'org-marker))))
9759 (when m
9760 (org-with-point-at m
9761 (setq agenda-link
9762 (if (org-called-interactively-p 'any)
9763 (call-interactively 'org-store-link)
9764 (org-store-link nil)))))))
9766 ((eq major-mode 'calendar-mode)
9767 (let ((cd (calendar-cursor-to-date)))
9768 (setq link
9769 (format-time-string
9770 (car org-time-stamp-formats)
9771 (apply 'encode-time
9772 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9773 nil nil nil))))
9774 (org-store-link-props :type "calendar" :date cd)))
9776 ((eq major-mode 'help-mode)
9777 (setq link (concat "help:" (save-excursion
9778 (goto-char (point-min))
9779 (looking-at "^[^ ]+")
9780 (match-string 0))))
9781 (org-store-link-props :type "help"))
9783 ((eq major-mode 'w3-mode)
9784 (setq cpltxt (if (and (buffer-name)
9785 (not (string-match "Untitled" (buffer-name))))
9786 (buffer-name)
9787 (url-view-url t))
9788 link (url-view-url t))
9789 (org-store-link-props :type "w3" :url (url-view-url t)))
9791 ((eq major-mode 'image-mode)
9792 (setq cpltxt (concat "file:"
9793 (abbreviate-file-name buffer-file-name))
9794 link cpltxt)
9795 (org-store-link-props :type "image" :file buffer-file-name))
9797 ;; In dired, store a link to the file of the current line
9798 ((derived-mode-p 'dired-mode)
9799 (let ((file (dired-get-filename nil t)))
9800 (setq file (if file
9801 (abbreviate-file-name
9802 (expand-file-name (dired-get-filename nil t)))
9803 ;; otherwise, no file so use current directory.
9804 default-directory))
9805 (setq cpltxt (concat "file:" file)
9806 link cpltxt)))
9808 ((setq search (run-hook-with-args-until-success
9809 'org-create-file-search-functions))
9810 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9811 "::" search))
9812 (setq cpltxt (or description link)))
9814 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9815 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9816 (cond
9817 ;; Store a link using the target at point
9818 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9819 (setq cpltxt
9820 (concat "file:"
9821 (abbreviate-file-name
9822 (buffer-file-name (buffer-base-buffer)))
9823 "::" (match-string 1))
9824 link cpltxt))
9825 ((and (featurep 'org-id)
9826 (or (eq org-id-link-to-org-use-id t)
9827 (and (org-called-interactively-p 'any)
9828 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9829 (and (eq org-id-link-to-org-use-id
9830 'create-if-interactive-and-no-custom-id)
9831 (not custom-id))))
9832 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9833 ;; Store a link using the ID at point
9834 (setq link (condition-case nil
9835 (prog1 (org-id-store-link)
9836 (setq desc (or (plist-get org-store-link-plist
9837 :description)
9838 "")))
9839 (error
9840 ;; Probably before first headline, link only to file
9841 (concat "file:"
9842 (abbreviate-file-name
9843 (buffer-file-name (buffer-base-buffer))))))))
9845 ;; Just link to current headline
9846 (setq cpltxt (concat "file:"
9847 (abbreviate-file-name
9848 (buffer-file-name (buffer-base-buffer)))))
9849 ;; Add a context search string
9850 (when (org-xor org-context-in-file-links arg)
9851 (let* ((element (org-element-at-point))
9852 (name (org-element-property :name element)))
9853 (setq txt (cond
9854 ((org-at-heading-p) nil)
9855 (name)
9856 ((org-region-active-p)
9857 (buffer-substring (region-beginning) (region-end)))))
9858 (when (or (null txt) (string-match "\\S-" txt))
9859 (setq cpltxt
9860 (concat cpltxt "::"
9861 (condition-case nil
9862 (org-make-org-heading-search-string txt)
9863 (error "")))
9864 desc (or name
9865 (nth 4 (ignore-errors (org-heading-components)))
9866 "NONE")))))
9867 (when (string-match "::\\'" cpltxt)
9868 (setq cpltxt (substring cpltxt 0 -2)))
9869 (setq link cpltxt))))
9871 ((buffer-file-name (buffer-base-buffer))
9872 ;; Just link to this file here.
9873 (setq cpltxt (concat "file:"
9874 (abbreviate-file-name
9875 (buffer-file-name (buffer-base-buffer)))))
9876 ;; Add a context string.
9877 (when (org-xor org-context-in-file-links arg)
9878 (setq txt (if (org-region-active-p)
9879 (buffer-substring (region-beginning) (region-end))
9880 (buffer-substring (point-at-bol) (point-at-eol))))
9881 ;; Only use search option if there is some text.
9882 (when (string-match "\\S-" txt)
9883 (setq cpltxt
9884 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9885 desc "NONE")))
9886 (setq link cpltxt))
9888 ((org-called-interactively-p 'interactive)
9889 (user-error "No method for storing a link from this buffer"))
9891 (t (setq link nil)))
9893 ;; We're done setting link and desc, clean up
9894 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9895 (setq link (or link cpltxt)
9896 desc (or desc cpltxt))
9897 (cond ((not desc))
9898 ((equal desc "NONE") (setq desc nil))
9899 (t (setq desc
9900 (replace-regexp-in-string
9901 org-bracket-link-analytic-regexp
9902 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9903 desc))))
9904 ;; Return the link
9905 (if (not (and (or (org-called-interactively-p 'any)
9906 executing-kbd-macro)
9907 link))
9908 (or agenda-link (and link (org-make-link-string link desc)))
9909 (push (list link desc) org-stored-links)
9910 (message "Stored: %s" (or desc link))
9911 (when custom-id
9912 (setq link (concat "file:" (abbreviate-file-name
9913 (buffer-file-name)) "::#" custom-id))
9914 (push (list link desc) org-stored-links))
9915 (car org-stored-links))))))
9917 (defun org-store-link-props (&rest plist)
9918 "Store link properties, extract names, addresses and dates."
9919 (let ((x (plist-get plist :from)))
9920 (when x
9921 (let ((adr (mail-extract-address-components x)))
9922 (setq plist (plist-put plist :fromname (car adr)))
9923 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9924 (let ((x (plist-get plist :to)))
9925 (when x
9926 (let ((adr (mail-extract-address-components x)))
9927 (setq plist (plist-put plist :toname (car adr)))
9928 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9929 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9930 (when x
9931 (setq plist (plist-put plist :date-timestamp
9932 (format-time-string
9933 (org-time-stamp-format t) x)))
9934 (setq plist (plist-put plist :date-timestamp-inactive
9935 (format-time-string
9936 (org-time-stamp-format t t) x)))))
9937 (let ((from (plist-get plist :from))
9938 (to (plist-get plist :to)))
9939 (when (and from to org-from-is-user-regexp)
9940 (setq plist
9941 (plist-put plist :fromto
9942 (if (string-match org-from-is-user-regexp from)
9943 (concat "to %t")
9944 (concat "from %f"))))))
9945 (setq org-store-link-plist plist))
9947 (defun org-add-link-props (&rest plist)
9948 "Add these properties to the link property list."
9949 (let (key value)
9950 (while plist
9951 (setq key (pop plist) value (pop plist))
9952 (setq org-store-link-plist
9953 (plist-put org-store-link-plist key value)))))
9955 (defun org-email-link-description (&optional fmt)
9956 "Return the description part of an email link.
9957 This takes information from `org-store-link-plist' and formats it
9958 according to FMT (default from `org-email-link-description-format')."
9959 (setq fmt (or fmt org-email-link-description-format))
9960 (let* ((p org-store-link-plist)
9961 (to (plist-get p :toaddress))
9962 (from (plist-get p :fromaddress))
9963 (table
9964 (list
9965 (cons "%c" (plist-get p :fromto))
9966 (cons "%F" (plist-get p :from))
9967 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9968 (cons "%T" (plist-get p :to))
9969 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9970 (cons "%s" (plist-get p :subject))
9971 (cons "%d" (plist-get p :date))
9972 (cons "%m" (plist-get p :message-id)))))
9973 (when (string-match "%c" fmt)
9974 ;; Check if the user wrote this message
9975 (if (and org-from-is-user-regexp from to
9976 (save-match-data (string-match org-from-is-user-regexp from)))
9977 (setq fmt (replace-match "to %t" t t fmt))
9978 (setq fmt (replace-match "from %f" t t fmt))))
9979 (org-replace-escapes fmt table)))
9981 (defun org-make-org-heading-search-string (&optional string)
9982 "Make search string for the current headline or STRING."
9983 (let ((s (or string
9984 (and (derived-mode-p 'org-mode)
9985 (save-excursion
9986 (org-back-to-heading t)
9987 (org-element-property :raw-value (org-element-at-point))))))
9988 (lines org-context-in-file-links))
9989 (or string (setq s (concat "*" s))) ; Add * for headlines
9990 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9991 (when (and string (integerp lines) (> lines 0))
9992 (let ((slines (org-split-string s "\n")))
9993 (when (< lines (length slines))
9994 (setq s (mapconcat
9995 'identity
9996 (reverse (nthcdr (- (length slines) lines)
9997 (reverse slines))) "\n")))))
9998 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10000 (defun org-make-link-string (link &optional description)
10001 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10002 (unless (org-string-nw-p link) (error "Empty link"))
10003 (let ((uri (cond ((string-match org-link-types-re link)
10004 (concat (match-string 1 link)
10005 (org-link-escape (substring link (match-end 1)))))
10006 ;; For readability, url-encode internal links only
10007 ;; when absolutely needed (i.e, when they contain
10008 ;; square brackets). File links however, are
10009 ;; encoded since, e.g., spaces are significant.
10010 ((or (file-name-absolute-p link)
10011 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10012 (org-link-escape link))
10013 (t link)))
10014 (description
10015 (and (org-string-nw-p description)
10016 ;; Remove brackets from description, as they are fatal.
10017 (replace-regexp-in-string
10018 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10019 (org-trim description)))))
10020 (format "[[%s]%s]"
10022 (if description (format "[%s]" description) ""))))
10024 (defconst org-link-escape-chars
10025 ;;%20 %5B %5D %25
10026 '(?\s ?\[ ?\] ?%)
10027 "List of characters that should be escaped in a link when stored to Org.
10028 This is the list that is used for internal purposes.")
10030 (defconst org-link-escape-chars-browser
10031 ;;%20 %22
10032 '(?\s ?\")
10033 "List of characters to be escaped before handing over to the browser.
10034 If you consider using this constant then you probably want to use
10035 the function `org-link-escape-browser' instead. See there why
10036 this constant is a candidate to be removed once Org drops support
10037 for Emacs 24.1 and 24.2.")
10039 (defun org-link-escape (text &optional table merge)
10040 "Return percent escaped representation of TEXT.
10041 TEXT is a string with the text to escape.
10042 Optional argument TABLE is a list with characters that should be
10043 escaped. When nil, `org-link-escape-chars' is used.
10044 If optional argument MERGE is set, merge TABLE into
10045 `org-link-escape-chars'."
10046 (let ((characters-to-encode
10047 (cond ((null table) org-link-escape-chars)
10048 (merge (append org-link-escape-chars table))
10049 (t table))))
10050 (mapconcat
10051 (lambda (c)
10052 (if (or (memq c characters-to-encode)
10053 (and org-url-hexify-p (or (< c 32) (> c 126))))
10054 (mapconcat (lambda (e) (format "%%%.2X" e))
10055 (or (encode-coding-char c 'utf-8)
10056 (error "Unable to percent escape character: %c" c))
10058 (char-to-string c)))
10059 text "")))
10061 (defun org-link-escape-browser (text)
10062 "Escape some characters before handing over to the browser.
10063 This function is a candidate to be removed together with the
10064 constant `org-link-escape-chars-browser' once Org drops support
10065 for Emacs 24.1 and 24.2. All calls to this function will have to
10066 be replaced with `url-encode-url' which is available since Emacs
10067 24.3.1."
10068 ;; Example with the Org link
10069 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10070 ;; to open the browser with +subject:"Release 8.2" filled into the
10071 ;; query field: In this case the variable TEXT contains the
10072 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10073 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10074 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10075 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10076 (if (fboundp 'url-encode-url)
10077 (url-encode-url text)
10078 (if (org-string-match-p
10079 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10080 text)
10081 (org-link-escape text org-link-escape-chars-browser)
10082 text)))
10084 (defun org-link-unescape (str)
10085 "Unhex hexified Unicode parts in string STR.
10086 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10087 reciprocal of `org-link-escape', which see."
10088 (if (org-string-nw-p str)
10089 (replace-regexp-in-string
10090 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10091 str))
10093 (defun org-link-unescape-compound (hex)
10094 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10095 Note: this function also decodes single byte encodings like
10096 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10097 (save-match-data
10098 (let* ((bytes (cdr (split-string hex "%")))
10099 (ret "")
10100 (eat 0)
10101 (sum 0))
10102 (while bytes
10103 (let* ((val (string-to-number (pop bytes) 16))
10104 (shift-xor
10105 (if (= 0 eat)
10106 (cond
10107 ((>= val 252) (cons 6 252))
10108 ((>= val 248) (cons 5 248))
10109 ((>= val 240) (cons 4 240))
10110 ((>= val 224) (cons 3 224))
10111 ((>= val 192) (cons 2 192))
10112 (t (cons 0 0)))
10113 (cons 6 128))))
10114 (when (>= val 192) (setq eat (car shift-xor)))
10115 (setq val (logxor val (cdr shift-xor)))
10116 (setq sum (+ (lsh sum (car shift-xor)) val))
10117 (when (> eat 0) (setq eat (- eat 1)))
10118 (cond
10119 ((= 0 eat) ;multi byte
10120 (setq ret (concat ret (org-char-to-string sum)))
10121 (setq sum 0))
10122 ((not bytes) ; single byte(s)
10123 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10124 ret)))
10126 (defun org-link-unescape-single-byte-sequence (hex)
10127 "Unhexify hex-encoded single byte character sequences."
10128 (mapconcat (lambda (byte)
10129 (char-to-string (string-to-number byte 16)))
10130 (cdr (split-string hex "%")) ""))
10132 (defun org-xor (a b)
10133 "Exclusive or."
10134 (if a (not b) b))
10136 (defun org-fixup-message-id-for-http (s)
10137 "Replace special characters in a message id, so it can be used in an http query."
10138 (when (string-match "%" s)
10139 (setq s (mapconcat (lambda (c)
10140 (if (eq c ?%)
10141 "%25"
10142 (char-to-string c)))
10143 s "")))
10144 (while (string-match "<" s)
10145 (setq s (replace-match "%3C" t t s)))
10146 (while (string-match ">" s)
10147 (setq s (replace-match "%3E" t t s)))
10148 (while (string-match "@" s)
10149 (setq s (replace-match "%40" t t s)))
10152 (defun org-link-prettify (link)
10153 "Return a human-readable representation of LINK.
10154 The car of LINK must be a raw link.
10155 The cdr of LINK must be either a link description or nil."
10156 (let ((desc (or (cadr link) "<no description>")))
10157 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10158 "<" (car link) ">")))
10160 ;;;###autoload
10161 (defun org-insert-link-global ()
10162 "Insert a link like Org-mode does.
10163 This command can be called in any mode to insert a link in Org-mode syntax."
10164 (interactive)
10165 (org-load-modules-maybe)
10166 (org-run-like-in-org-mode 'org-insert-link))
10168 (defun org-insert-all-links (arg &optional pre post)
10169 "Insert all links in `org-stored-links'.
10170 When a universal prefix, do not delete the links from `org-stored-links'.
10171 When `ARG' is a number, insert the last N link(s).
10172 `PRE' and `POST' are optional arguments to define a string to
10173 prepend or to append."
10174 (interactive "P")
10175 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10176 (links (copy-sequence org-stored-links))
10177 (pr (or pre "- "))
10178 (po (or post "\n"))
10179 (cnt 1) l)
10180 (if (null org-stored-links)
10181 (message "No link to insert")
10182 (while (and (or (listp arg) (>= arg cnt))
10183 (setq l (if (listp arg)
10184 (pop links)
10185 (pop org-stored-links))))
10186 (setq cnt (1+ cnt))
10187 (insert pr)
10188 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10189 (insert po)))))
10191 (defun org-insert-last-stored-link (arg)
10192 "Insert the last link stored in `org-stored-links'."
10193 (interactive "p")
10194 (org-insert-all-links arg "" "\n"))
10196 (defun org-link-fontify-links-to-this-file ()
10197 "Fontify links to the current file in `org-stored-links'."
10198 (let ((f (buffer-file-name)) a b)
10199 (setq a (mapcar (lambda(l)
10200 (let ((ll (car l)))
10201 (when (and (string-match "^file:\\(.+\\)::" ll)
10202 (equal f (expand-file-name (match-string 1 ll))))
10203 ll)))
10204 org-stored-links))
10205 (when (featurep 'org-id)
10206 (setq b (mapcar (lambda(l)
10207 (let ((ll (car l)))
10208 (when (and (string-match "^id:\\(.+\\)$" ll)
10209 (equal f (expand-file-name
10210 (or (org-id-find-id-file
10211 (match-string 1 ll)) ""))))
10212 ll)))
10213 org-stored-links)))
10214 (mapcar (lambda(l)
10215 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10216 (delq nil (append a b)))))
10218 (defvar org--links-history nil)
10219 (defun org-insert-link (&optional complete-file link-location default-description)
10220 "Insert a link. At the prompt, enter the link.
10222 Completion can be used to insert any of the link protocol prefixes like
10223 http or ftp in use.
10225 The history can be used to select a link previously stored with
10226 `org-store-link'. When the empty string is entered (i.e. if you just
10227 press RET at the prompt), the link defaults to the most recently
10228 stored link. As SPC triggers completion in the minibuffer, you need to
10229 use M-SPC or C-q SPC to force the insertion of a space character.
10231 You will also be prompted for a description, and if one is given, it will
10232 be displayed in the buffer instead of the link.
10234 If there is already a link at point, this command will allow you to edit link
10235 and description parts.
10237 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10238 be selected using completion. The path to the file will be relative to the
10239 current directory if the file is in the current directory or a subdirectory.
10240 Otherwise, the link will be the absolute path as completed in the minibuffer
10241 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10242 option `org-link-file-path-type'.
10244 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10245 the current directory or below.
10247 With three \\[universal-argument] prefixes, negate the meaning of
10248 `org-keep-stored-link-after-insertion'.
10250 If `org-make-link-description-function' is non-nil, this function will be
10251 called with the link target, and the result will be the default
10252 link description.
10254 If the LINK-LOCATION parameter is non-nil, this value will be
10255 used as the link location instead of reading one interactively.
10257 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10258 be used as the default description."
10259 (interactive "P")
10260 (let* ((wcf (current-window-configuration))
10261 (origbuf (current-buffer))
10262 (region (when (org-region-active-p)
10263 (buffer-substring (region-beginning) (region-end))))
10264 (remove (and region (list (region-beginning) (region-end))))
10265 (desc region)
10266 (link link-location)
10267 (abbrevs org-link-abbrev-alist-local)
10268 entry all-prefixes auto-desc)
10269 (cond
10270 (link-location) ; specified by arg, just use it.
10271 ((org-in-regexp org-bracket-link-regexp 1)
10272 ;; We do have a link at point, and we are going to edit it.
10273 (setq remove (list (match-beginning 0) (match-end 0)))
10274 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10275 (setq link (read-string "Link: "
10276 (org-link-unescape
10277 (org-match-string-no-properties 1)))))
10278 ((or (org-in-regexp org-angle-link-re)
10279 (org-in-regexp org-plain-link-re))
10280 ;; Convert to bracket link
10281 (setq remove (list (match-beginning 0) (match-end 0))
10282 link (read-string "Link: "
10283 (org-remove-angle-brackets (match-string 0)))))
10284 ((member complete-file '((4) (16)))
10285 ;; Completing read for file names.
10286 (setq link (org-file-complete-link complete-file)))
10288 ;; Read link, with completion for stored links.
10289 (org-link-fontify-links-to-this-file)
10290 (org-switch-to-buffer-other-window "*Org Links*")
10291 (with-current-buffer "*Org Links*"
10292 (erase-buffer)
10293 (insert "Insert a link.
10294 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10295 (when org-stored-links
10296 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10297 (insert (mapconcat 'org-link-prettify
10298 (reverse org-stored-links) "\n")))
10299 (goto-char (point-min)))
10300 (let ((cw (selected-window)))
10301 (select-window (get-buffer-window "*Org Links*" 'visible))
10302 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10303 (unless (pos-visible-in-window-p (point-max))
10304 (org-fit-window-to-buffer))
10305 (and (window-live-p cw) (select-window cw)))
10306 (setq all-prefixes (append (mapcar 'car abbrevs)
10307 (mapcar 'car org-link-abbrev-alist)
10308 org-link-types))
10309 (unwind-protect
10310 ;; Fake a link history, containing the stored links.
10311 (let ((org--links-history
10312 (append (mapcar #'car org-stored-links)
10313 org-insert-link-history)))
10314 (setq link
10315 (org-completing-read
10316 "Link: "
10317 (append
10318 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10319 (mapcar #'car org-stored-links))
10320 nil nil nil
10321 'org--links-history
10322 (caar org-stored-links)))
10323 (unless (org-string-nw-p link) (user-error "No link selected"))
10324 (dolist (l org-stored-links)
10325 (when (equal link (cadr l))
10326 (setq link (car l))
10327 (setq auto-desc t)))
10328 (when (or (member link all-prefixes)
10329 (and (equal ":" (substring link -1))
10330 (member (substring link 0 -1) all-prefixes)
10331 (setq link (substring link 0 -1))))
10332 (setq link (with-current-buffer origbuf
10333 (org-link-try-special-completion link)))))
10334 (set-window-configuration wcf)
10335 (kill-buffer "*Org Links*"))
10336 (setq entry (assoc link org-stored-links))
10337 (or entry (push link org-insert-link-history))
10338 (setq desc (or desc (nth 1 entry)))))
10340 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10341 (not org-keep-stored-link-after-insertion))
10342 (setq org-stored-links (delq (assoc link org-stored-links)
10343 org-stored-links)))
10345 (when (and (string-match org-plain-link-re link)
10346 (not (string-match org-ts-regexp link)))
10347 ;; URL-like link, normalize the use of angular brackets.
10348 (setq link (org-remove-angle-brackets link)))
10350 ;; Check if we are linking to the current file with a search
10351 ;; option If yes, simplify the link by using only the search
10352 ;; option.
10353 (when (and buffer-file-name
10354 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10355 (let* ((path (match-string 1 link))
10356 (case-fold-search nil)
10357 (search (match-string 2 link)))
10358 (save-match-data
10359 (when (equal (file-truename buffer-file-name) (file-truename path))
10360 ;; We are linking to this same file, with a search option
10361 (setq link search)))))
10363 ;; Check if we can/should use a relative path. If yes, simplify the link
10364 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10365 (let* ((type (match-string 1 link))
10366 (path (match-string 2 link))
10367 (origpath path)
10368 (case-fold-search nil))
10369 (cond
10370 ((or (eq org-link-file-path-type 'absolute)
10371 (equal complete-file '(16)))
10372 (setq path (abbreviate-file-name (expand-file-name path))))
10373 ((eq org-link-file-path-type 'noabbrev)
10374 (setq path (expand-file-name path)))
10375 ((eq org-link-file-path-type 'relative)
10376 (setq path (file-relative-name path)))
10378 (save-match-data
10379 (if (string-match (concat "^" (regexp-quote
10380 (expand-file-name
10381 (file-name-as-directory
10382 default-directory))))
10383 (expand-file-name path))
10384 ;; We are linking a file with relative path name.
10385 (setq path (substring (expand-file-name path)
10386 (match-end 0)))
10387 (setq path (abbreviate-file-name (expand-file-name path)))))))
10388 (setq link (concat type path))
10389 (when (equal desc origpath)
10390 (setq desc path))))
10392 (if org-make-link-description-function
10393 (setq desc
10394 (or (condition-case nil
10395 (funcall org-make-link-description-function link desc)
10396 (error (progn (message "Can't get link description from `%s'"
10397 (symbol-name org-make-link-description-function))
10398 (sit-for 2) nil)))
10399 (read-string "Description: " default-description)))
10400 (if default-description (setq desc default-description)
10401 (setq desc (or (and auto-desc desc)
10402 (read-string "Description: " desc)))))
10404 (unless (string-match "\\S-" desc) (setq desc nil))
10405 (when remove (apply 'delete-region remove))
10406 (insert (org-make-link-string link desc))
10407 ;; Redisplay so as the new link has proper invisible characters.
10408 (sit-for 0)))
10410 (defun org-link-try-special-completion (type)
10411 "If there is completion support for link type TYPE, offer it."
10412 (let ((fun (intern (concat "org-" type "-complete-link"))))
10413 (if (functionp fun)
10414 (funcall fun)
10415 (read-string "Link (no completion support): " (concat type ":")))))
10417 (defun org-file-complete-link (&optional arg)
10418 "Create a file link using completion."
10419 (let ((file (read-file-name "File: "))
10420 (pwd (file-name-as-directory (expand-file-name ".")))
10421 (pwd1 (file-name-as-directory (abbreviate-file-name
10422 (expand-file-name ".")))))
10423 (cond ((equal arg '(16))
10424 (concat "file:"
10425 (abbreviate-file-name (expand-file-name file))))
10426 ((string-match
10427 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10428 (concat "file:" (match-string 1 file)))
10429 ((string-match
10430 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10431 (expand-file-name file))
10432 (concat "file:"
10433 (match-string 1 (expand-file-name file))))
10434 (t (concat "file:" file)))))
10436 (defun org-completing-read (&rest args)
10437 "Completing-read with SPACE being a normal character."
10438 (let ((enable-recursive-minibuffers t)
10439 (minibuffer-local-completion-map
10440 (copy-keymap minibuffer-local-completion-map)))
10441 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10442 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10443 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10444 'org-time-stamp-inactive)
10445 (apply #'completing-read args)))
10447 (define-obsolete-function-alias
10448 'org-completing-read-no-i 'completing-read "Org 9.0")
10449 (define-obsolete-function-alias
10450 'org-icompleting-read 'completing-read "Org 9.0")
10451 (define-obsolete-function-alias
10452 'org-iread-file-name 'read-file-name "Org 9.0")
10454 ;;; Opening/following a link
10456 (defvar org-link-search-failed nil)
10458 (defvar org-open-link-functions nil
10459 "Hook for functions finding a plain text link.
10460 These functions must take a single argument, the link content.
10461 They will be called for links that look like [[link text][description]]
10462 when LINK TEXT does not have a protocol like \"http:\" and does not look
10463 like a filename (e.g. \"./blue.png\").
10465 These functions will be called *before* Org attempts to resolve the
10466 link by doing text searches in the current buffer - so if you want a
10467 link \"[[target]]\" to still find \"<<target>>\", your function should
10468 handle this as a special case.
10470 When the function does handle the link, it must return a non-nil value.
10471 If it decides that it is not responsible for this link, it must return
10472 nil to indicate that that Org-mode can continue with other options
10473 like exact and fuzzy text search.")
10475 (defun org-next-link (&optional search-backward)
10476 "Move forward to the next link.
10477 If the link is in hidden text, expose it."
10478 (interactive "P")
10479 (when (and org-link-search-failed (eq this-command last-command))
10480 (goto-char (point-min))
10481 (message "Link search wrapped back to beginning of buffer"))
10482 (setq org-link-search-failed nil)
10483 (let* ((pos (point))
10484 (ct (org-context))
10485 (a (assoc :link ct))
10486 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10487 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10488 ((looking-at org-any-link-re)
10489 ;; Don't stay stuck at link without an org-link face
10490 (forward-char (if search-backward -1 1))))
10491 (if (funcall srch-fun org-any-link-re nil t)
10492 (progn
10493 (goto-char (match-beginning 0))
10494 (when (outline-invisible-p) (org-show-context)))
10495 (goto-char pos)
10496 (setq org-link-search-failed t)
10497 (message "No further link found"))))
10499 (defun org-previous-link ()
10500 "Move backward to the previous link.
10501 If the link is in hidden text, expose it."
10502 (interactive)
10503 (funcall 'org-next-link t))
10505 (defun org-translate-link (s)
10506 "Translate a link string if a translation function has been defined."
10507 (with-temp-buffer
10508 (insert (org-trim s))
10509 (org-trim (org-element-interpret-data (org-element-context)))))
10511 (defun org-translate-link-from-planner (type path)
10512 "Translate a link from Emacs Planner syntax so that Org can follow it.
10513 This is still an experimental function, your mileage may vary."
10514 (cond
10515 ((member type '("http" "https" "news" "ftp"))
10516 ;; standard Internet links are the same.
10517 nil)
10518 ((and (equal type "irc") (string-match "^//" path))
10519 ;; Planner has two / at the beginning of an irc link, we have 1.
10520 ;; We should have zero, actually....
10521 (setq path (substring path 1)))
10522 ((and (equal type "lisp") (string-match "^/" path))
10523 ;; Planner has a slash, we do not.
10524 (setq type "elisp" path (substring path 1)))
10525 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10526 ;; A typical message link. Planner has the id after the final slash,
10527 ;; we separate it with a hash mark
10528 (setq path (concat (match-string 1 path) "#"
10529 (org-remove-angle-brackets (match-string 2 path))))))
10530 (cons type path))
10532 (defun org-find-file-at-mouse (ev)
10533 "Open file link or URL at mouse."
10534 (interactive "e")
10535 (mouse-set-point ev)
10536 (org-open-at-point 'in-emacs))
10538 (defun org-open-at-mouse (ev)
10539 "Open file link or URL at mouse.
10540 See the docstring of `org-open-file' for details."
10541 (interactive "e")
10542 (mouse-set-point ev)
10543 (when (eq major-mode 'org-agenda-mode)
10544 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10545 (org-open-at-point))
10547 (defvar org-window-config-before-follow-link nil
10548 "The window configuration before following a link.
10549 This is saved in case the need arises to restore it.")
10551 ;;;###autoload
10552 (defun org-open-at-point-global ()
10553 "Follow a link like Org-mode does.
10554 This command can be called in any mode to follow a link that has
10555 Org-mode syntax."
10556 (interactive)
10557 (org-run-like-in-org-mode 'org-open-at-point))
10559 ;;;###autoload
10560 (defun org-open-link-from-string (s &optional arg reference-buffer)
10561 "Open a link in the string S, as if it was in Org-mode."
10562 (interactive "sLink: \nP")
10563 (let ((reference-buffer (or reference-buffer (current-buffer))))
10564 (with-temp-buffer
10565 (let ((org-inhibit-startup (not reference-buffer)))
10566 (org-mode)
10567 (insert s)
10568 (goto-char (point-min))
10569 (when reference-buffer
10570 (setq org-link-abbrev-alist-local
10571 (with-current-buffer reference-buffer
10572 org-link-abbrev-alist-local)))
10573 (org-open-at-point arg reference-buffer)))))
10575 (defvar org-open-at-point-functions nil
10576 "Hook that is run when following a link at point.
10578 Functions in this hook must return t if they identify and follow
10579 a link at point. If they don't find anything interesting at point,
10580 they must return nil.")
10582 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10583 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10584 (defun org-open-at-point (&optional arg reference-buffer)
10585 "Open link, timestamp, footnote or tags at point.
10587 When point is on a link, follow it. Normally, files will be
10588 opened by an appropriate application. If the optional prefix
10589 argument ARG is non-nil, Emacs will visit the file. With
10590 a double prefix argument, try to open outside of Emacs, in the
10591 application the system uses for this file type.
10593 When point is on a timestamp, open the agenda at the day
10594 specified.
10596 When point is a footnote definition, move to the first reference
10597 found. If it is on a reference, move to the associated
10598 definition.
10600 When point is on a headline, display a list of every link in the
10601 entry, so it is possible to pick one, or all, of them. If point
10602 is on a tag, call `org-tags-view' instead.
10604 When optional argument REFERENCE-BUFFER is non-nil, it should
10605 specify a buffer from where the link search should happen. This
10606 is used internally by `org-open-link-from-string'.
10608 On top of syntactically correct links, this function will open
10609 the link at point in comments or comment blocks and the first
10610 link in a property drawer line."
10611 (interactive "P")
10612 ;; On a code block, open block's results.
10613 (unless (call-interactively 'org-babel-open-src-block-result)
10614 (org-load-modules-maybe)
10615 (setq org-window-config-before-follow-link (current-window-configuration))
10616 (org-remove-occur-highlights nil nil t)
10617 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10618 (let* ((context
10619 ;; Only consider supported types, even if they are not
10620 ;; the closest one.
10621 (org-element-lineage
10622 (org-element-context)
10623 '(clock comment comment-block footnote-definition
10624 footnote-reference headline inlinetask keyword link
10625 node-property timestamp)
10627 (type (org-element-type context))
10628 (value (org-element-property :value context)))
10629 (cond
10630 ((not context) (user-error "No link found"))
10631 ;; Exception: open timestamps and links in properties
10632 ;; drawers, keywords and comments.
10633 ((memq type '(comment comment-block keyword node-property))
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"))))
10640 ;; On a headline or an inlinetask, but not on a timestamp,
10641 ;; a link, a footnote reference or on tags.
10642 ((and (memq type '(headline inlinetask))
10643 ;; Not on tags.
10644 (progn (save-excursion (beginning-of-line)
10645 (looking-at org-complex-heading-regexp))
10646 (or (not (match-beginning 5))
10647 (< (point) (match-beginning 5)))))
10648 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10649 (links (car data))
10650 (links-end (cdr data)))
10651 (if links
10652 (dolist (link (if (stringp links) (list links) links))
10653 (search-forward link nil links-end)
10654 (goto-char (match-beginning 0))
10655 (org-open-at-point))
10656 (require 'org-attach)
10657 (org-attach-reveal 'if-exists))))
10658 ;; On a clock line, make sure point is on the timestamp
10659 ;; before opening it.
10660 ((and (eq type 'clock)
10661 value
10662 (>= (point) (org-element-property :begin value))
10663 (<= (point) (org-element-property :end value)))
10664 (org-follow-timestamp-link))
10665 ;; Do nothing on white spaces after an object.
10666 ((>= (point)
10667 (save-excursion
10668 (goto-char (org-element-property :end context))
10669 (skip-chars-backward " \t")
10670 (point)))
10671 (user-error "No link found"))
10672 ((eq type 'timestamp) (org-follow-timestamp-link))
10673 ;; On tags within a headline or an inlinetask.
10674 ((and (memq type '(headline inlinetask))
10675 (progn (save-excursion (beginning-of-line)
10676 (looking-at org-complex-heading-regexp))
10677 (and (match-beginning 5)
10678 (>= (point) (match-beginning 5)))))
10679 (org-tags-view arg (substring (match-string 5) 0 -1)))
10680 ((eq type 'link)
10681 ;; When link is located within the description of another
10682 ;; link (e.g., an inline image), always open the parent
10683 ;; link.
10684 (let*((link (let ((up (org-element-property :parent context)))
10685 (if (eq (org-element-type up) 'link) up context)))
10686 (type (org-element-property :type link))
10687 (path (org-link-unescape (org-element-property :path link))))
10688 ;; Switch back to REFERENCE-BUFFER needed when called in
10689 ;; a temporary buffer through `org-open-link-from-string'.
10690 (with-current-buffer (or reference-buffer (current-buffer))
10691 (cond
10692 ((equal type "file")
10693 (if (string-match "[*?{]" (file-name-nondirectory path))
10694 (dired path)
10695 ;; Look into `org-link-protocols' in order to find
10696 ;; a DEDICATED-FUNCTION to open file. The function
10697 ;; will be applied on raw link instead of parsed
10698 ;; link due to the limitation in `org-add-link-type'
10699 ;; ("open" function called with a single argument).
10700 ;; If no such function is found, fallback to
10701 ;; `org-open-file'.
10703 ;; Note : "file+emacs" and "file+sys" types are
10704 ;; hard-coded in order to escape the previous
10705 ;; limitation.
10706 (let* ((option (org-element-property :search-option link))
10707 (app (org-element-property :application link))
10708 (dedicated-function
10709 (nth 1 (assoc app org-link-protocols))))
10710 (if dedicated-function
10711 (funcall dedicated-function
10712 (concat path
10713 (and option (concat "::" option))))
10714 (apply #'org-open-file
10715 path
10716 (cond (arg)
10717 ((equal app "emacs") 'emacs)
10718 ((equal app "sys") 'system))
10719 (cond ((not option) nil)
10720 ((org-string-match-p "\\`[0-9]+\\'" option)
10721 (list (string-to-number option)))
10722 (t (list nil
10723 (org-link-unescape option)))))))))
10724 ((assoc type org-link-protocols)
10725 (funcall (nth 1 (assoc type org-link-protocols)) path))
10726 ((equal type "help")
10727 (let ((f-or-v (intern path)))
10728 (cond ((fboundp f-or-v) (describe-function f-or-v))
10729 ((boundp f-or-v) (describe-variable f-or-v))
10730 (t (error "Not a known function or variable")))))
10731 ((member type '("http" "https" "ftp" "mailto" "news"))
10732 (browse-url (org-link-escape-browser (concat type ":" path))))
10733 ((equal type "doi")
10734 (browse-url
10735 (org-link-escape-browser (concat org-doi-server-url path))))
10736 ((equal type "message") (browse-url (concat type ":" path)))
10737 ((equal type "shell")
10738 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10739 (cmd path))
10740 (if (or (and (org-string-nw-p
10741 org-confirm-shell-link-not-regexp)
10742 (string-match
10743 org-confirm-shell-link-not-regexp cmd))
10744 (not org-confirm-shell-link-function)
10745 (funcall org-confirm-shell-link-function
10746 (format "Execute \"%s\" in shell? "
10747 (org-add-props cmd nil
10748 'face 'org-warning))))
10749 (progn
10750 (message "Executing %s" cmd)
10751 (shell-command cmd buf)
10752 (when (featurep 'midnight)
10753 (setq clean-buffer-list-kill-buffer-names
10754 (cons (buffer-name buf)
10755 clean-buffer-list-kill-buffer-names))))
10756 (user-error "Abort"))))
10757 ((equal type "elisp")
10758 (let ((cmd path))
10759 (if (or (and (org-string-nw-p
10760 org-confirm-elisp-link-not-regexp)
10761 (org-string-match-p
10762 org-confirm-elisp-link-not-regexp cmd))
10763 (not org-confirm-elisp-link-function)
10764 (funcall org-confirm-elisp-link-function
10765 (format "Execute \"%s\" as elisp? "
10766 (org-add-props cmd nil
10767 'face 'org-warning))))
10768 (message "%s => %s" cmd
10769 (if (eq (string-to-char cmd) ?\()
10770 (eval (read cmd))
10771 (call-interactively (read cmd))))
10772 (user-error "Abort"))))
10773 ((equal type "id")
10774 (require 'org-id)
10775 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10776 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10777 (unless (run-hook-with-args-until-success
10778 'org-open-link-functions path)
10779 (if (not arg) (org-mark-ring-push)
10780 (switch-to-buffer-other-window
10781 (org-get-buffer-for-internal-link (current-buffer))))
10782 (let ((destination
10783 (org-with-wide-buffer
10784 (if (equal type "radio")
10785 (org-search-radio-target
10786 (org-element-property :path link))
10787 (org-link-search
10788 (if (member type '("custom-id" "coderef"))
10789 (org-element-property :raw-link link)
10790 path)
10791 ;; Prevent fuzzy links from matching
10792 ;; themselves.
10793 (and (equal type "fuzzy")
10794 (+ 2 (org-element-property :begin link)))))
10795 (point))))
10796 (unless (and (<= (point-min) destination)
10797 (>= (point-max) destination))
10798 (widen))
10799 (goto-char destination))))
10800 (t (browse-url-at-point))))))
10801 ;; On a footnote reference or at a footnote definition's label.
10802 ((or (eq type 'footnote-reference)
10803 (and (eq type 'footnote-definition)
10804 (save-excursion
10805 ;; Do not validate action when point is on the
10806 ;; spaces right after the footnote label, in
10807 ;; order to be on par with behaviour on links.
10808 (skip-chars-forward " \t")
10809 (let ((begin
10810 (org-element-property :contents-begin context)))
10811 (if begin (< (point) begin)
10812 (= (org-element-property :post-affiliated context)
10813 (line-beginning-position)))))))
10814 (org-footnote-action))
10815 (t (user-error "No link found")))))
10816 (run-hook-with-args 'org-follow-link-hook)))
10818 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10819 "Offer links in the current entry and return the selected link.
10820 If there is only one link, return it.
10821 If NTH is an integer, return the NTH link found.
10822 If ZERO is a string, check also this string for a link, and if
10823 there is one, return it."
10824 (with-current-buffer buffer
10825 (save-excursion
10826 (save-restriction
10827 (widen)
10828 (goto-char marker)
10829 (let ((cnt ?0)
10830 have-zero end links link c)
10831 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10832 (push (match-string 0 zero) links)
10833 (setq cnt (1- cnt) have-zero t))
10834 (save-excursion
10835 (org-back-to-heading t)
10836 (setq end (save-excursion (outline-next-heading) (point)))
10837 (while (re-search-forward org-any-link-re end t)
10838 (push (match-string 0) links))
10839 (setq links (org-uniquify (reverse links))))
10840 (cond
10841 ((null links)
10842 (message "No links"))
10843 ((equal (length links) 1)
10844 (setq link (car links)))
10845 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10846 (setq link (nth (if have-zero nth (1- nth)) links)))
10847 (t ; we have to select a link
10848 (save-excursion
10849 (save-window-excursion
10850 (delete-other-windows)
10851 (with-output-to-temp-buffer "*Select Link*"
10852 (dolist (l links)
10853 (cond
10854 ((not (string-match org-bracket-link-regexp l))
10855 (princ (format "[%c] %s\n" (cl-incf cnt)
10856 (org-remove-angle-brackets l))))
10857 ((match-end 3)
10858 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10859 (match-string 3 l) (match-string 1 l))))
10860 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10861 (match-string 1 l)))))))
10862 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10863 (message "Select link to open, RET to open all:")
10864 (setq c (read-char-exclusive))
10865 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10866 (when (equal c ?q) (user-error "Abort"))
10867 (if (equal c ?\C-m)
10868 (setq link links)
10869 (setq nth (- c ?0))
10870 (when have-zero (setq nth (1+ nth)))
10871 (unless (and (integerp nth) (>= (length links) nth))
10872 (user-error "Invalid link selection"))
10873 (setq link (nth (1- nth) links)))))
10874 (cons link end))))))
10876 ;; TODO: These functions are deprecated since `org-open-at-point'
10877 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10878 (defun org-open-file-with-system (path)
10879 "Open file at PATH using the system way of opening it."
10880 (org-open-file path 'system))
10881 (defun org-open-file-with-emacs (path)
10882 "Open file at PATH in Emacs."
10883 (org-open-file path 'emacs))
10886 ;;; File search
10888 (defvar org-create-file-search-functions nil
10889 "List of functions to construct the right search string for a file link.
10890 These functions are called in turn with point at the location to
10891 which the link should point.
10893 A function in the hook should first test if it would like to
10894 handle this file type, for example by checking the `major-mode'
10895 or the file extension. If it decides not to handle this file, it
10896 should just return nil to give other functions a chance. If it
10897 does handle the file, it must return the search string to be used
10898 when following the link. The search string will be part of the
10899 file link, given after a double colon, and `org-open-at-point'
10900 will automatically search for it. If special measures must be
10901 taken to make the search successful, another function should be
10902 added to the companion hook `org-execute-file-search-functions',
10903 which see.
10905 A function in this hook may also use `setq' to set the variable
10906 `description' to provide a suggestion for the descriptive text to
10907 be used for this link when it gets inserted into an Org-mode
10908 buffer with \\[org-insert-link].")
10910 (defvar org-execute-file-search-functions nil
10911 "List of functions to execute a file search triggered by a link.
10913 Functions added to this hook must accept a single argument, the
10914 search string that was part of the file link, the part after the
10915 double colon. The function must first check if it would like to
10916 handle this search, for example by checking the `major-mode' or
10917 the file extension. If it decides not to handle this search, it
10918 should just return nil to give other functions a chance. If it
10919 does handle the search, it must return a non-nil value to keep
10920 other functions from trying.
10922 Each function can access the current prefix argument through the
10923 variable `current-prefix-arg'. Note that a single prefix is used
10924 to force opening a link in Emacs, so it may be good to only use a
10925 numeric or double prefix to guide the search function.
10927 In case this is needed, a function in this hook can also restore
10928 the window configuration before `org-open-at-point' was called using:
10930 \(set-window-configuration org-window-config-before-follow-link)")
10932 (defun org-search-radio-target (target)
10933 "Search a radio target matching TARGET in current buffer.
10934 White spaces are not significant."
10935 (let ((re (format "<<<%s>>>"
10936 (mapconcat #'regexp-quote
10937 (org-split-string target "[ \t\n]+")
10938 "[ \t]+\\(?:\n[ \t]*\\)?")))
10939 (origin (point)))
10940 (goto-char (point-min))
10941 (catch :radio-match
10942 (while (re-search-forward re nil t)
10943 (backward-char)
10944 (let ((object (org-element-context)))
10945 (when (eq (org-element-type object) 'radio-target)
10946 (goto-char (org-element-property :begin object))
10947 (org-show-context 'link-search)
10948 (throw :radio-match nil))))
10949 (goto-char origin)
10950 (user-error "No match for radio target: %s" target))))
10952 (defun org-link-search (s &optional avoid-pos stealth)
10953 "Search for a search string S.
10955 If S starts with \"#\", it triggers a custom ID search.
10957 If S is enclosed within parenthesis, it initiates a coderef
10958 search.
10960 If S is surrounded by forward slashes, it is interpreted as
10961 a regular expression. In Org mode files, this will create an
10962 `org-occur' sparse tree. In ordinary files, `occur' will be used
10963 to list matches. If the current buffer is in `dired-mode', grep
10964 will be used to search in all files.
10966 When AVOID-POS is given, ignore matches near that position.
10968 When optional argument STEALTH is non-nil, do not modify
10969 visibility around point, thus ignoring `org-show-context-detail'
10970 variable.
10972 Search is case-insensitive and ignores white spaces. Return type
10973 of matched result, with is either `dedicated' or `fuzzy'."
10974 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10975 (let* ((case-fold-search t)
10976 (origin (point))
10977 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10978 (words (org-split-string s "[ \t\n]+"))
10979 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10980 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10981 type)
10982 (cond
10983 ;; Check if there are any special search functions.
10984 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10985 ((eq (string-to-char s) ?#)
10986 ;; Look for a custom ID S if S starts with "#".
10987 (let* ((id (substring normalized 1))
10988 (match (org-find-property "CUSTOM_ID" id)))
10989 (if match (progn (goto-char match) (setf type 'dedicated))
10990 (error "No match for custom ID: %s" id))))
10991 ((string-match "\\`(\\(.*\\))\\'" normalized)
10992 ;; Look for coderef targets if S is enclosed within parenthesis.
10993 (let ((coderef (match-string-no-properties 1 normalized))
10994 (re (substring s-single-re 1 -1)))
10995 (goto-char (point-min))
10996 (catch :coderef-match
10997 (while (re-search-forward re nil t)
10998 (let ((element (org-element-at-point)))
10999 (when (and (memq (org-element-type element)
11000 '(example-block src-block))
11001 ;; Build proper regexp according to current
11002 ;; block's label format.
11003 (let ((label-fmt
11004 (regexp-quote
11005 (or (org-element-property :label-fmt element)
11006 org-coderef-label-format))))
11007 (save-excursion
11008 (beginning-of-line)
11009 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11010 (format label-fmt coderef))))))
11011 (setq type 'dedicated)
11012 (goto-char (match-beginning 1))
11013 (throw :coderef-match nil))))
11014 (goto-char origin)
11015 (error "No match for coderef: %s" coderef))))
11016 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11017 ;; Look for a regular expression.
11018 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11019 (match-string 1 s)))
11020 ;; Fuzzy links.
11022 (let ((starred (eq (string-to-char normalized) ?*)))
11023 (cond
11024 ;; Look for targets, only if not in a headline search.
11025 ((and (not starred)
11026 (let ((target (format "<<%s>>" s-multi-re)))
11027 (catch :target-match
11028 (goto-char (point-min))
11029 (while (re-search-forward target nil t)
11030 (backward-char)
11031 (let ((context (org-element-context)))
11032 (when (eq (org-element-type context) 'target)
11033 (setq type 'dedicated)
11034 (goto-char (org-element-property :begin context))
11035 (throw :target-match t))))
11036 nil))))
11037 ;; Look for elements named after S, only if not in a headline
11038 ;; search.
11039 ((and (not starred)
11040 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11041 (catch :name-match
11042 (goto-char (point-min))
11043 (while (re-search-forward name nil t)
11044 (let ((element (org-element-at-point)))
11045 (when (equal (org-split-string
11046 (org-element-property :name element)
11047 "[ \t]+")
11048 words)
11049 (setq type 'dedicated)
11050 (beginning-of-line)
11051 (throw :name-match t))))
11052 nil))))
11053 ;; Regular text search. Prefer headlines in Org mode
11054 ;; buffers.
11055 ((and (derived-mode-p 'org-mode)
11056 (let* ((wspace "[ \t]")
11057 (wspaceopt (concat wspace "*"))
11058 (cookie (concat "\\(?:"
11059 wspaceopt
11060 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11061 wspaceopt
11062 "\\)"))
11063 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11064 (re (concat
11065 org-outline-regexp-bol
11066 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11067 "\\(?:\\[#.\\][ \t]+\\)?"
11068 "\\(?:" org-comment-string "[ \t]+\\)?"
11069 sep "?"
11070 (let ((title (mapconcat #'regexp-quote
11071 words
11072 sep)))
11073 (if starred (substring title 1) title))
11074 sep "?"
11075 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11076 "[ \t]*$")))
11077 (goto-char (point-min))
11078 (re-search-forward re nil t)))
11079 (goto-char (match-beginning 0))
11080 (setq type 'dedicated))
11081 ;; Offer to create non-existent headline depending on
11082 ;; `org-link-search-must-match-exact-headline'.
11083 ((and (derived-mode-p 'org-mode)
11084 (not org-link-search-inhibit-query)
11085 (eq org-link-search-must-match-exact-headline 'query-to-create)
11086 (yes-or-no-p "No match - create this as a new heading? "))
11087 (goto-char (point-max))
11088 (unless (bolp) (newline))
11089 (org-insert-heading nil t t)
11090 (insert s "\n")
11091 (beginning-of-line 0))
11092 ;; Only headlines are looked after. No need to process
11093 ;; further: throw an error.
11094 ((and (derived-mode-p 'org-mode)
11095 (or starred org-link-search-must-match-exact-headline))
11096 (goto-char origin)
11097 (error "No match for fuzzy expression: %s" normalized))
11098 ;; Regular text search.
11099 ((catch :fuzzy-match
11100 (goto-char (point-min))
11101 (while (re-search-forward s-multi-re nil t)
11102 ;; Skip match if it contains AVOID-POS or it is included
11103 ;; in a link with a description but outside the
11104 ;; description.
11105 (unless (or (and avoid-pos
11106 (<= (match-beginning 0) avoid-pos)
11107 (> (match-end 0) avoid-pos))
11108 (and (save-match-data
11109 (org-in-regexp org-bracket-link-regexp))
11110 (match-beginning 3)
11111 (or (> (match-beginning 3) (point))
11112 (<= (match-end 3) (point)))
11113 (org-element-lineage
11114 (save-match-data (org-element-context))
11115 '(link) t)))
11116 (goto-char (match-beginning 0))
11117 (setq type 'fuzzy)
11118 (throw :fuzzy-match t)))
11119 nil))
11120 ;; All failed. Throw an error.
11121 (t (goto-char origin)
11122 (error "No match for fuzzy expression: %s" normalized))))))
11123 ;; Disclose surroundings of match, if appropriate.
11124 (when (and (derived-mode-p 'org-mode) (not stealth))
11125 (org-show-context 'link-search))
11126 type))
11128 (defun org-get-buffer-for-internal-link (buffer)
11129 "Return a buffer to be used for displaying the link target of internal links."
11130 (cond
11131 ((not org-display-internal-link-with-indirect-buffer)
11132 buffer)
11133 ((string-match "(Clone)$" (buffer-name buffer))
11134 (message "Buffer is already a clone, not making another one")
11135 ;; we also do not modify visibility in this case
11136 buffer)
11137 (t ; make a new indirect buffer for displaying the link
11138 (let* ((bn (buffer-name buffer))
11139 (ibn (concat bn "(Clone)"))
11140 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11141 (with-current-buffer ib (org-overview))
11142 ib))))
11144 (defun org-do-occur (regexp &optional cleanup)
11145 "Call the Emacs command `occur'.
11146 If CLEANUP is non-nil, remove the printout of the regular expression
11147 in the *Occur* buffer. This is useful if the regex is long and not useful
11148 to read."
11149 (occur regexp)
11150 (when cleanup
11151 (let ((cwin (selected-window)) win beg end)
11152 (when (setq win (get-buffer-window "*Occur*"))
11153 (select-window win))
11154 (goto-char (point-min))
11155 (when (re-search-forward "match[a-z]+" nil t)
11156 (setq beg (match-end 0))
11157 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11158 (setq end (1- (match-beginning 0)))))
11159 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11160 (goto-char (point-min))
11161 (select-window cwin))))
11163 ;;; The mark ring for links jumps
11165 (defvar org-mark-ring nil
11166 "Mark ring for positions before jumps in Org-mode.")
11167 (defvar org-mark-ring-last-goto nil
11168 "Last position in the mark ring used to go back.")
11169 ;; Fill and close the ring
11170 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11171 (dotimes (_ org-mark-ring-length)
11172 (push (make-marker) org-mark-ring))
11173 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11174 org-mark-ring)
11176 (defun org-mark-ring-push (&optional pos buffer)
11177 "Put the current position or POS into the mark ring and rotate it."
11178 (interactive)
11179 (setq pos (or pos (point)))
11180 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11181 (move-marker (car org-mark-ring)
11182 (or pos (point))
11183 (or buffer (current-buffer)))
11184 (message "%s"
11185 (substitute-command-keys
11186 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11188 (defun org-mark-ring-goto (&optional n)
11189 "Jump to the previous position in the mark ring.
11190 With prefix arg N, jump back that many stored positions. When
11191 called several times in succession, walk through the entire ring.
11192 Org-mode commands jumping to a different position in the current file,
11193 or to another Org-mode file, automatically push the old position
11194 onto the ring."
11195 (interactive "p")
11196 (let (p m)
11197 (if (eq last-command this-command)
11198 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11199 (setq p org-mark-ring))
11200 (setq org-mark-ring-last-goto p)
11201 (setq m (car p))
11202 (org-pop-to-buffer-same-window (marker-buffer m))
11203 (goto-char m)
11204 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11206 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11207 ;;; Emacs 24.4+
11208 (defun org-remove-angle-brackets (s)
11209 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11210 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11212 (defun org-add-angle-brackets (s)
11213 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11214 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11216 (defun org-remove-double-quotes (s)
11217 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11218 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11221 ;;; Following specific links
11223 (defvar org-agenda-buffer-tmp-name)
11224 (defvar org-agenda-start-on-weekday)
11225 (defun org-follow-timestamp-link ()
11226 "Open an agenda view for the time-stamp date/range at point."
11227 (cond
11228 ((org-at-date-range-p t)
11229 (let ((org-agenda-start-on-weekday)
11230 (t1 (match-string 1))
11231 (t2 (match-string 2)) tt1 tt2)
11232 (setq tt1 (time-to-days (org-time-string-to-time t1))
11233 tt2 (time-to-days (org-time-string-to-time t2)))
11234 (let ((org-agenda-buffer-tmp-name
11235 (format "*Org Agenda(a:%s)"
11236 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11237 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11238 ((org-at-timestamp-p t)
11239 (let ((org-agenda-buffer-tmp-name
11240 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11241 (org-agenda-list nil (time-to-days (org-time-string-to-time
11242 (substring (match-string 1) 0 10)))
11243 1)))
11244 (t (error "This should not happen"))))
11247 ;;; Following file links
11248 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11249 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11250 (declare-function mailcap-mime-info
11251 "mailcap" (string &optional request no-decode))
11252 (defvar org-wait nil)
11253 (defun org-open-file (path &optional in-emacs line search)
11254 "Open the file at PATH.
11255 First, this expands any special file name abbreviations. Then the
11256 configuration variable `org-file-apps' is checked if it contains an
11257 entry for this file type, and if yes, the corresponding command is launched.
11259 If no application is found, Emacs simply visits the file.
11261 With optional prefix argument IN-EMACS, Emacs will visit the file.
11262 With a double \\[universal-argument] \\[universal-argument] \
11263 prefix arg, Org tries to avoid opening in Emacs
11264 and to use an external application to visit the file.
11266 Optional LINE specifies a line to go to, optional SEARCH a string
11267 to search for. If LINE or SEARCH is given, the file will be
11268 opened in Emacs, unless an entry from org-file-apps that makes
11269 use of groups in a regexp matches.
11271 If you want to change the way frames are used when following a
11272 link, please customize `org-link-frame-setup'.
11274 If the file does not exist, an error is thrown."
11275 (let* ((file (if (equal path "")
11276 buffer-file-name
11277 (substitute-in-file-name (expand-file-name path))))
11278 (file-apps (append org-file-apps (org-default-apps)))
11279 (apps (cl-remove-if
11280 'org-file-apps-entry-match-against-dlink-p file-apps))
11281 (apps-dlink (cl-remove-if-not
11282 'org-file-apps-entry-match-against-dlink-p file-apps))
11283 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11284 (dirp (unless remp (file-directory-p file)))
11285 (file (if (and dirp org-open-directory-means-index-dot-org)
11286 (concat (file-name-as-directory file) "index.org")
11287 file))
11288 (a-m-a-p (assq 'auto-mode apps))
11289 (dfile (downcase file))
11290 ;; Reconstruct the original link from the PATH, LINE and
11291 ;; SEARCH args.
11292 (link (cond (line (concat file "::" (number-to-string line)))
11293 (search (concat file "::" search))
11294 (t file)))
11295 (dlink (downcase link))
11296 (old-buffer (current-buffer))
11297 (old-pos (point))
11298 (old-mode major-mode)
11299 (ext
11300 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11301 (match-string 1 dfile)))
11302 cmd link-match-data)
11303 (cond
11304 ((member in-emacs '((16) system))
11305 (setq cmd (cdr (assq 'system apps))))
11306 (in-emacs (setq cmd 'emacs))
11308 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11309 (and dirp (cdr (assq 'directory apps)))
11310 ;; First, try matching against apps-dlink if we
11311 ;; get a match here, store the match data for
11312 ;; later.
11313 (let ((match (assoc-default dlink apps-dlink
11314 'string-match)))
11315 (if match
11316 (progn (setq link-match-data (match-data))
11317 match)
11318 (progn (setq in-emacs (or in-emacs line search))
11319 nil))) ; if we have no match in apps-dlink,
11320 ; always open the file in emacs if line or search
11321 ; is given (for backwards compatibility)
11322 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11323 'string-match)
11324 (cdr (assoc ext apps))
11325 (cdr (assq t apps))))))
11326 (when (eq cmd 'system)
11327 (setq cmd (cdr (assoc 'system apps))))
11328 (when (eq cmd 'default)
11329 (setq cmd (cdr (assoc t apps))))
11330 (when (eq cmd 'mailcap)
11331 (require 'mailcap)
11332 (mailcap-parse-mailcaps)
11333 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11334 (command (mailcap-mime-info mime-type)))
11335 (if (stringp command)
11336 (setq cmd command)
11337 (setq cmd 'emacs))))
11338 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11339 (not (file-exists-p file))
11340 (not org-open-non-existing-files))
11341 (user-error "No such file: %s" file))
11342 (cond
11343 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11344 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11345 (while (string-match "['\"]%s['\"]" cmd)
11346 (setq cmd (replace-match "%s" t t cmd)))
11347 (while (string-match "%s" cmd)
11348 (setq cmd (replace-match
11349 (save-match-data
11350 (shell-quote-argument
11351 (convert-standard-filename file)))
11352 t t cmd)))
11354 ;; Replace "%1", "%2" etc. in command with group matches from regex
11355 (save-match-data
11356 (let ((match-index 1)
11357 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11358 (set-match-data link-match-data)
11359 (while (<= match-index number-of-groups)
11360 (let ((regex (concat "%" (number-to-string match-index)))
11361 (replace-with (match-string match-index dlink)))
11362 (while (string-match regex cmd)
11363 (setq cmd (replace-match replace-with t t cmd))))
11364 (setq match-index (+ match-index 1)))))
11366 (save-window-excursion
11367 (message "Running %s...done" cmd)
11368 (start-process-shell-command cmd nil cmd)
11369 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11370 ((or (stringp cmd)
11371 (eq cmd 'emacs))
11372 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11373 (widen)
11374 (cond (line (org-goto-line line)
11375 (when (derived-mode-p 'org-mode) (org-reveal)))
11376 (search (org-link-search search))))
11377 ((functionp cmd)
11378 (save-match-data
11379 (set-match-data link-match-data)
11380 (condition-case nil
11381 (funcall cmd file link)
11382 ;; FIXME: Remove this check when most default installations
11383 ;; of Emacs have at least Org 9.0.
11384 ((debug wrong-number-of-arguments wrong-type-argument
11385 invalid-function)
11386 (user-error "Please see Org News for version 9.0 about \
11387 `org-file-apps'--Lisp error: %S" cmd)))))
11388 ((consp cmd)
11389 ;; FIXME: Remove this check when most default installations of
11390 ;; Emacs have at least Org 9.0.
11391 ;; Heads-up instead of silently fall back to
11392 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11393 ;; with sexp instead of a function for `cmd'.
11394 (user-error "Please see Org News for version 9.0 about \
11395 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11396 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11397 (and (derived-mode-p 'org-mode)
11398 (eq old-mode 'org-mode)
11399 (or (not (eq old-buffer (current-buffer)))
11400 (not (eq old-pos (point))))
11401 (org-mark-ring-push old-pos old-buffer))))
11403 (defun org-file-apps-entry-match-against-dlink-p (entry)
11404 "This function returns non-nil if `entry' uses a regular
11405 expression which should be matched against the whole link by
11406 org-open-file.
11408 It assumes that is the case when the entry uses a regular
11409 expression which has at least one grouping construct and the
11410 action is either a lisp form or a command string containing
11411 `%1', i.e. using at least one subexpression match as a
11412 parameter."
11413 (let ((selector (car entry))
11414 (action (cdr entry)))
11415 (if (stringp selector)
11416 (and (> (regexp-opt-depth selector) 0)
11417 (or (and (stringp action)
11418 (string-match "%[0-9]" action))
11419 (consp action)))
11420 nil)))
11422 (defun org-default-apps ()
11423 "Return the default applications for this operating system."
11424 (cond
11425 ((eq system-type 'darwin)
11426 org-file-apps-defaults-macosx)
11427 ((eq system-type 'windows-nt)
11428 org-file-apps-defaults-windowsnt)
11429 (t org-file-apps-defaults-gnu)))
11431 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11432 "Convert extensions to regular expressions in the cars of LIST.
11433 Also, weed out any non-string entries, because the return value is used
11434 only for regexp matching.
11435 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11436 point to the symbol `emacs', indicating that the file should
11437 be opened in Emacs."
11438 (append
11439 (delq nil
11440 (mapcar (lambda (x)
11441 (unless (not (stringp (car x)))
11442 (if (string-match "\\W" (car x))
11444 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11445 list))
11446 (when add-auto-mode
11447 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11449 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11450 (defun org-file-remote-p (file)
11451 "Test whether FILE specifies a location on a remote system.
11452 Return non-nil if the location is indeed remote.
11454 For example, the filename \"/user@host:/foo\" specifies a location
11455 on the system \"/user@host:\"."
11456 (cond ((fboundp 'file-remote-p)
11457 (file-remote-p file))
11458 ((fboundp 'tramp-handle-file-remote-p)
11459 (tramp-handle-file-remote-p file))
11460 ((and (boundp 'ange-ftp-name-format)
11461 (string-match (car ange-ftp-name-format) file))
11462 t)))
11465 ;;;; Refiling
11467 (defun org-get-org-file ()
11468 "Read a filename, with default directory `org-directory'."
11469 (let ((default (or org-default-notes-file remember-data-file)))
11470 (read-file-name (format "File name [%s]: " default)
11471 (file-name-as-directory org-directory)
11472 default)))
11474 (defun org-notes-order-reversed-p ()
11475 "Check if the current file should receive notes in reversed order."
11476 (cond
11477 ((not org-reverse-note-order) nil)
11478 ((eq t org-reverse-note-order) t)
11479 ((not (listp org-reverse-note-order)) nil)
11480 (t (catch 'exit
11481 (dolist (entry org-reverse-note-order)
11482 (when (string-match (car entry) buffer-file-name)
11483 (throw 'exit (cdr entry))))))))
11485 (defvar org-refile-target-table nil
11486 "The list of refile targets, created by `org-refile'.")
11488 (defvar org-agenda-new-buffers nil
11489 "Buffers created to visit agenda files.")
11491 (defvar org-refile-cache nil
11492 "Cache for refile targets.")
11494 (defvar org-refile-markers nil
11495 "All the markers used for caching refile locations.")
11497 (defun org-refile-marker (pos)
11498 "Get a new refile marker, but only if caching is in use."
11499 (if (not org-refile-use-cache)
11501 (let ((m (make-marker)))
11502 (move-marker m pos)
11503 (push m org-refile-markers)
11504 m)))
11506 (defun org-refile-cache-clear ()
11507 "Clear the refile cache and disable all the markers."
11508 (dolist (m org-refile-markers) (move-marker m nil))
11509 (setq org-refile-markers nil)
11510 (setq org-refile-cache nil)
11511 (message "Refile cache has been cleared"))
11513 (defun org-refile-cache-check-set (set)
11514 "Check if all the markers in the cache still have live buffers."
11515 (let (marker)
11516 (catch 'exit
11517 (while (and set (setq marker (nth 3 (pop set))))
11518 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11519 (when (and marker (null (marker-buffer marker)))
11520 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11521 (sit-for 3)
11522 (throw 'exit nil)))
11523 t)))
11525 (defun org-refile-cache-put (set &rest identifiers)
11526 "Push the refile targets SET into the cache, under IDENTIFIERS."
11527 (let* ((key (sha1 (prin1-to-string identifiers)))
11528 (entry (assoc key org-refile-cache)))
11529 (if entry
11530 (setcdr entry set)
11531 (push (cons key set) org-refile-cache))))
11533 (defun org-refile-cache-get (&rest identifiers)
11534 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11535 (cond
11536 ((not org-refile-cache) nil)
11537 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11539 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11540 org-refile-cache))))
11541 (and set (org-refile-cache-check-set set) set)))))
11543 (defvar org-outline-path-cache nil
11544 "Alist between buffer positions and outline paths.
11545 It value is an alist (POSITION . PATH) where POSITION is the
11546 buffer position at the beginning of an entry and PATH is a list
11547 of strings describing the outline path for that entry, in reverse
11548 order.")
11550 (defun org-refile-get-targets (&optional default-buffer)
11551 "Produce a table with refile targets."
11552 (let ((case-fold-search nil)
11553 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11554 (entries (or org-refile-targets '((nil . (:level . 1)))))
11555 targets tgs files desc descre)
11556 (message "Getting targets...")
11557 (with-current-buffer (or default-buffer (current-buffer))
11558 (dolist (entry entries)
11559 (setq files (car entry) desc (cdr entry))
11560 (cond
11561 ((null files) (setq files (list (current-buffer))))
11562 ((eq files 'org-agenda-files)
11563 (setq files (org-agenda-files 'unrestricted)))
11564 ((and (symbolp files) (fboundp files))
11565 (setq files (funcall files)))
11566 ((and (symbolp files) (boundp files))
11567 (setq files (symbol-value files))))
11568 (when (stringp files) (setq files (list files)))
11569 (cond
11570 ((eq (car desc) :tag)
11571 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11572 ((eq (car desc) :todo)
11573 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11574 ((eq (car desc) :regexp)
11575 (setq descre (cdr desc)))
11576 ((eq (car desc) :level)
11577 (setq descre (concat "^\\*\\{" (number-to-string
11578 (if org-odd-levels-only
11579 (1- (* 2 (cdr desc)))
11580 (cdr desc)))
11581 "\\}[ \t]")))
11582 ((eq (car desc) :maxlevel)
11583 (setq descre (concat "^\\*\\{1," (number-to-string
11584 (if org-odd-levels-only
11585 (1- (* 2 (cdr desc)))
11586 (cdr desc)))
11587 "\\}[ \t]")))
11588 (t (error "Bad refiling target description %s" desc)))
11589 (dolist (f files)
11590 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11592 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11593 (progn
11594 (when (bufferp f)
11595 (setq f (buffer-file-name (buffer-base-buffer f))))
11596 (setq f (and f (expand-file-name f)))
11597 (when (eq org-refile-use-outline-path 'file)
11598 (push (list (file-name-nondirectory f) f nil nil) tgs))
11599 (org-with-wide-buffer
11600 (goto-char (point-min))
11601 (setq org-outline-path-cache nil)
11602 (while (re-search-forward descre nil t)
11603 (beginning-of-line)
11604 (looking-at org-complex-heading-regexp)
11605 (let ((begin (point))
11606 (heading (org-match-string-no-properties 4)))
11607 (unless (or (and
11608 org-refile-target-verify-function
11609 (not
11610 (funcall org-refile-target-verify-function)))
11611 (not heading))
11612 (let ((re (format org-complex-heading-regexp-format
11613 (regexp-quote heading)))
11614 (target
11615 (if (not org-refile-use-outline-path) heading
11616 (mapconcat
11617 #'org-protect-slash
11618 (append
11619 (pcase org-refile-use-outline-path
11620 (`file (list (file-name-nondirectory
11621 (buffer-file-name
11622 (buffer-base-buffer)))))
11623 (`full-file-path
11624 (list (buffer-file-name
11625 (buffer-base-buffer))))
11626 (_ nil))
11627 (org-get-outline-path t t))
11628 "/"))))
11629 (push (list target f re (org-refile-marker (point)))
11630 tgs)))
11631 (when (= (point) begin)
11632 ;; Verification function has not moved point.
11633 (end-of-line)))))))
11634 (when org-refile-use-cache
11635 (org-refile-cache-put tgs (buffer-file-name) descre))
11636 (setq targets (append tgs targets))))))
11637 (message "Getting targets...done")
11638 (nreverse targets)))
11640 (defun org-protect-slash (s)
11641 (while (string-match "/" s)
11642 (setq s (replace-match "\\" t t s)))
11645 (defun org--get-outline-path-1 (&optional use-cache)
11646 "Return outline path to current headline.
11648 Outline path is a list of strings, in reverse order. When
11649 optional argument USE-CACHE is non-nil, make use of a cache. See
11650 `org-get-outline-path' for details.
11652 Assume buffer is widened and point is on a headline."
11653 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11654 (let ((p (point))
11655 (heading (progn
11656 (looking-at org-complex-heading-regexp)
11657 (if (not (match-end 4)) ""
11658 ;; Remove statistics cookies.
11659 (org-trim
11660 (org-link-display-format
11661 (replace-regexp-in-string
11662 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11663 (org-match-string-no-properties 4))))))))
11664 (if (org-up-heading-safe)
11665 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11666 (when use-cache
11667 (push (cons p path) org-outline-path-cache))
11668 path)
11669 ;; This is a new root node. Since we assume we are moving
11670 ;; forward, we can drop previous cache so as to limit number
11671 ;; of associations there.
11672 (let ((path (list heading)))
11673 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11674 path)))))
11676 (defun org-get-outline-path (&optional with-self use-cache)
11677 "Return the outline path to the current entry.
11679 An outline path is a list of ancestors for current headline, as
11680 a list of strings. Statistics cookies are removed and links are
11681 replaced with their description, if any, or their path otherwise.
11683 When optional argument WITH-SELF is non-nil, the path also
11684 includes the current headline.
11686 When optional argument USE-CACHE is non-nil, cache outline paths
11687 between calls to this function so as to avoid backtracking. This
11688 argument is useful when planning to find more than one outline
11689 path in the same document. In that case, there are two
11690 conditions to satisfy:
11691 - `org-outline-path-cache' is set to nil before starting the
11692 process;
11693 - outline paths are computed by increasing buffer positions."
11694 (org-with-wide-buffer
11695 (and (or (and with-self (org-back-to-heading t))
11696 (org-up-heading-safe))
11697 (reverse (org--get-outline-path-1 use-cache)))))
11699 (defun org-format-outline-path (path &optional width prefix separator)
11700 "Format the outline path PATH for display.
11701 WIDTH is the maximum number of characters that is available.
11702 PREFIX is a prefix to be included in the returned string,
11703 such as the file name.
11704 SEPARATOR is inserted between the different parts of the path,
11705 the default is \"/\"."
11706 (setq width (or width 79))
11707 (setq path (delq nil path))
11708 (unless (> width 0)
11709 (user-error "Argument `width' must be positive"))
11710 (setq separator (or separator "/"))
11711 (let* ((org-odd-levels-only nil)
11712 (fpath (concat
11713 prefix (and prefix path separator)
11714 (mapconcat
11715 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11716 (cl-loop for head in path
11717 for n from 0
11718 collect (org-add-props
11719 head nil 'face
11720 (nth (% n org-n-level-faces) org-level-faces)))
11721 separator))))
11722 (when (> (length fpath) width)
11723 (if (< width 7)
11724 ;; It's unlikely that `width' will be this small, but don't
11725 ;; waste characters by adding ".." if it is.
11726 (setq fpath (substring fpath 0 width))
11727 (setf (substring fpath (- width 2)) "..")))
11728 fpath))
11730 (defun org-display-outline-path (&optional file current separator just-return-string)
11731 "Display the current outline path in the echo area.
11733 If FILE is non-nil, prepend the output with the file name.
11734 If CURRENT is non-nil, append the current heading to the output.
11735 SEPARATOR is passed through to `org-format-outline-path'. It separates
11736 the different parts of the path and defaults to \"/\".
11737 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11738 (interactive "P")
11739 (let* (case-fold-search
11740 (bfn (buffer-file-name (buffer-base-buffer)))
11741 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11742 res)
11743 (when current (setq path (append path
11744 (save-excursion
11745 (org-back-to-heading t)
11746 (when (looking-at org-complex-heading-regexp)
11747 (list (match-string 4)))))))
11748 (setq res
11749 (org-format-outline-path
11750 path
11751 (1- (frame-width))
11752 (and file bfn (concat (file-name-nondirectory bfn) separator))
11753 separator))
11754 (if just-return-string
11755 (org-no-properties res)
11756 (org-unlogged-message "%s" res))))
11758 (defvar org-refile-history nil
11759 "History for refiling operations.")
11761 (defvar org-after-refile-insert-hook nil
11762 "Hook run after `org-refile' has inserted its stuff at the new location.
11763 Note that this is still *before* the stuff will be removed from
11764 the *old* location.")
11766 (defvar org-capture-last-stored-marker)
11767 (defvar org-refile-keep nil
11768 "Non-nil means `org-refile' will copy instead of refile.")
11770 (defun org-copy ()
11771 "Like `org-refile', but copy."
11772 (interactive)
11773 (let ((org-refile-keep t))
11774 (funcall 'org-refile nil nil nil "Copy")))
11776 (defun org-refile (&optional arg default-buffer rfloc msg)
11777 "Move the entry or entries at point to another heading.
11778 The list of target headings is compiled using the information in
11779 `org-refile-targets', which see.
11781 At the target location, the entry is filed as a subitem of the
11782 target heading. Depending on `org-reverse-note-order', the new
11783 subitem will either be the first or the last subitem.
11785 If there is an active region, all entries in that region will be
11786 refiled. However, the region must fulfill the requirement that
11787 the first heading sets the top-level of the moved text.
11789 With prefix arg ARG, the command will only visit the target
11790 location and not actually move anything.
11792 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11793 refiling operation has put the subtree.
11795 With a numeric prefix argument of `2', refile to the running clock.
11797 With a numeric prefix argument of `3', emulate `org-refile-keep'
11798 being set to t and copy to the target location, don't move it.
11799 Beware that keeping refiled entries may result in duplicated ID
11800 properties.
11802 RFLOC can be a refile location obtained in a different way.
11804 MSG is a string to replace \"Refile\" in the default prompt with
11805 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11807 See also `org-refile-use-outline-path'.
11809 If you are using target caching (see `org-refile-use-cache'), you
11810 have to clear the target cache in order to find new targets.
11811 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11812 prefix argument (`C-u C-u C-u C-c C-w')."
11813 (interactive "P")
11814 (if (member arg '(0 (64)))
11815 (org-refile-cache-clear)
11816 (let* ((actionmsg (cond (msg msg)
11817 ((equal arg 3) "Refile (and keep)")
11818 (t "Refile")))
11819 (regionp (org-region-active-p))
11820 (region-start (and regionp (region-beginning)))
11821 (region-end (and regionp (region-end)))
11822 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11823 pos it nbuf file level reversed)
11824 (setq last-command nil)
11825 (when regionp
11826 (goto-char region-start)
11827 (or (bolp) (goto-char (point-at-bol)))
11828 (setq region-start (point))
11829 (unless (or (org-kill-is-subtree-p
11830 (buffer-substring region-start region-end))
11831 (prog1 org-refile-active-region-within-subtree
11832 (let ((s (point-at-eol)))
11833 (org-toggle-heading)
11834 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11835 (user-error "The region is not a (sequence of) subtree(s)")))
11836 (if (equal arg '(16))
11837 (org-refile-goto-last-stored)
11838 (when (or
11839 (and (equal arg 2)
11840 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11841 (prog1
11842 (setq it (list (or org-clock-heading "running clock")
11843 (buffer-file-name
11844 (marker-buffer org-clock-hd-marker))
11846 (marker-position org-clock-hd-marker)))
11847 (setq arg nil)))
11848 (setq it
11849 (or rfloc
11850 (let (heading-text)
11851 (save-excursion
11852 (unless (and arg (listp arg))
11853 (org-back-to-heading t)
11854 (setq heading-text
11855 (replace-regexp-in-string
11856 org-bracket-link-regexp
11857 "\\3"
11858 (nth 4 (org-heading-components)))))
11859 (org-refile-get-location
11860 (cond ((and arg (listp arg)) "Goto")
11861 (regionp (concat actionmsg " region to"))
11862 (t (concat actionmsg " subtree \""
11863 heading-text "\" to")))
11864 default-buffer
11865 (and (not (equal '(4) arg))
11866 org-refile-allow-creating-parent-nodes)))))))
11867 (setq file (nth 1 it)
11868 pos (nth 3 it))
11869 (when (and (not arg)
11871 (equal (buffer-file-name) file)
11872 (if regionp
11873 (and (>= pos region-start)
11874 (<= pos region-end))
11875 (and (>= pos (point))
11876 (< pos (save-excursion
11877 (org-end-of-subtree t t))))))
11878 (error "Cannot refile to position inside the tree or region"))
11879 (setq nbuf (or (find-buffer-visiting file)
11880 (find-file-noselect file)))
11881 (if (and arg (not (equal arg 3)))
11882 (progn
11883 (org-pop-to-buffer-same-window nbuf)
11884 (goto-char pos)
11885 (org-show-context 'org-goto))
11886 (if regionp
11887 (progn
11888 (org-kill-new (buffer-substring region-start region-end))
11889 (org-save-markers-in-region region-start region-end))
11890 (org-copy-subtree 1 nil t))
11891 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11892 (find-file-noselect file)))
11893 (setq reversed (org-notes-order-reversed-p))
11894 (save-excursion
11895 (save-restriction
11896 (widen)
11897 (if pos
11898 (progn
11899 (goto-char pos)
11900 (looking-at org-outline-regexp)
11901 (setq level (org-get-valid-level (funcall outline-level) 1))
11902 (goto-char
11903 (if reversed
11904 (or (outline-next-heading) (point-max))
11905 (or (save-excursion (org-get-next-sibling))
11906 (org-end-of-subtree t t)
11907 (point-max)))))
11908 (setq level 1)
11909 (if (not reversed)
11910 (goto-char (point-max))
11911 (goto-char (point-min))
11912 (or (outline-next-heading) (goto-char (point-max)))))
11913 (unless (bolp) (newline))
11914 (org-paste-subtree level nil nil t)
11915 (when org-log-refile
11916 (org-add-log-setup 'refile nil nil org-log-refile)
11917 (unless (eq org-log-refile 'note)
11918 (save-excursion (org-add-log-note))))
11919 (and org-auto-align-tags
11920 (let ((org-loop-over-headlines-in-active-region nil))
11921 (org-set-tags nil t)))
11922 (let ((bookmark-name (plist-get org-bookmark-names-plist
11923 :last-refile)))
11924 (when bookmark-name
11925 (with-demoted-errors
11926 (bookmark-set bookmark-name))))
11927 ;; If we are refiling for capture, make sure that the
11928 ;; last-capture pointers point here
11929 (when (org-bound-and-true-p org-capture-is-refiling)
11930 (let ((bookmark-name (plist-get org-bookmark-names-plist
11931 :last-capture-marker)))
11932 (when bookmark-name
11933 (with-demoted-errors
11934 (bookmark-set bookmark-name))))
11935 (move-marker org-capture-last-stored-marker (point)))
11936 (when (fboundp 'deactivate-mark) (deactivate-mark))
11937 (run-hooks 'org-after-refile-insert-hook))))
11938 (unless org-refile-keep
11939 (if regionp
11940 (delete-region (point) (+ (point) (- region-end region-start)))
11941 (delete-region
11942 (and (org-back-to-heading t) (point))
11943 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11944 (when (featurep 'org-inlinetask)
11945 (org-inlinetask-remove-END-maybe))
11946 (setq org-markers-to-move nil)
11947 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11949 (defun org-refile-goto-last-stored ()
11950 "Go to the location where the last refile was stored."
11951 (interactive)
11952 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11953 (message "This is the location of the last refile"))
11955 (defun org-refile--get-location (refloc tbl)
11956 "When user refile to REFLOC, find the associated target in TBL.
11957 Also check `org-refile-target-table'."
11958 (car (delq
11960 (mapcar
11961 (lambda (r) (or (assoc r tbl)
11962 (assoc r org-refile-target-table)))
11963 (list (replace-regexp-in-string "/$" "" refloc)
11964 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11966 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11967 "Prompt the user for a refile location, using PROMPT.
11968 PROMPT should not be suffixed with a colon and a space, because
11969 this function appends the default value from
11970 `org-refile-history' automatically, if that is not empty."
11971 (let ((org-refile-targets org-refile-targets)
11972 (org-refile-use-outline-path org-refile-use-outline-path))
11973 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11974 (unless org-refile-target-table
11975 (user-error "No refile targets"))
11976 (let* ((cbuf (current-buffer))
11977 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11978 (cfunc (if (and org-refile-use-outline-path
11979 org-outline-path-complete-in-steps)
11980 #'org-olpath-completing-read
11981 #'completing-read))
11982 (extra (if org-refile-use-outline-path "/" ""))
11983 (cbnex (concat (buffer-name) extra))
11984 (filename (and cfn (expand-file-name cfn)))
11985 (tbl (mapcar
11986 (lambda (x)
11987 (if (and (not (member org-refile-use-outline-path
11988 '(file full-file-path)))
11989 (not (equal filename (nth 1 x))))
11990 (cons (concat (car x) extra " ("
11991 (file-name-nondirectory (nth 1 x)) ")")
11992 (cdr x))
11993 (cons (concat (car x) extra) (cdr x))))
11994 org-refile-target-table))
11995 (completion-ignore-case t)
11996 cdef
11997 (prompt (concat prompt
11998 (or (and (car org-refile-history)
11999 (concat " (default " (car org-refile-history) ")"))
12000 (and (assoc cbnex tbl) (setq cdef cbnex)
12001 (concat " (default " cbnex ")"))) ": "))
12002 pa answ parent-target child parent old-hist)
12003 (setq old-hist org-refile-history)
12004 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12005 nil 'org-refile-history (or cdef (car org-refile-history))))
12006 (if (setq pa (org-refile--get-location answ tbl))
12007 (progn
12008 (org-refile-check-position pa)
12009 (when (or (not org-refile-history)
12010 (not (eq old-hist org-refile-history))
12011 (not (equal (car pa) (car org-refile-history))))
12012 (setq org-refile-history
12013 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12014 org-refile-history
12015 (cdr org-refile-history))))
12016 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12017 (pop org-refile-history)))
12019 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12020 (progn
12021 (setq parent (match-string 1 answ)
12022 child (match-string 2 answ))
12023 (setq parent-target (org-refile--get-location parent tbl))
12024 (when (and parent-target
12025 (or (eq new-nodes t)
12026 (and (eq new-nodes 'confirm)
12027 (y-or-n-p (format "Create new node \"%s\"? "
12028 child)))))
12029 (org-refile-new-child parent-target child)))
12030 (user-error "Invalid target location")))))
12032 (declare-function org-string-nw-p "org-macs" (s))
12033 (defun org-refile-check-position (refile-pointer)
12034 "Check if the refile pointer matches the headline to which it points."
12035 (let* ((file (nth 1 refile-pointer))
12036 (re (nth 2 refile-pointer))
12037 (pos (nth 3 refile-pointer))
12038 buffer)
12039 (if (and (not (markerp pos)) (not file))
12040 (user-error "Please indicate a target file in the refile path")
12041 (when (org-string-nw-p re)
12042 (setq buffer (if (markerp pos)
12043 (marker-buffer pos)
12044 (or (find-buffer-visiting file)
12045 (find-file-noselect file))))
12046 (with-current-buffer buffer
12047 (save-excursion
12048 (save-restriction
12049 (widen)
12050 (goto-char pos)
12051 (beginning-of-line 1)
12052 (unless (org-looking-at-p re)
12053 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12055 (defun org-refile-new-child (parent-target child)
12056 "Use refile target PARENT-TARGET to add new CHILD below it."
12057 (unless parent-target
12058 (error "Cannot find parent for new node"))
12059 (let ((file (nth 1 parent-target))
12060 (pos (nth 3 parent-target))
12061 level)
12062 (with-current-buffer (or (find-buffer-visiting file)
12063 (find-file-noselect file))
12064 (save-excursion
12065 (save-restriction
12066 (widen)
12067 (if pos
12068 (goto-char pos)
12069 (goto-char (point-max))
12070 (unless (bolp) (newline)))
12071 (when (looking-at org-outline-regexp)
12072 (setq level (funcall outline-level))
12073 (org-end-of-subtree t t))
12074 (org-back-over-empty-lines)
12075 (insert "\n" (make-string
12076 (if pos (org-get-valid-level level 1) 1) ?*)
12077 " " child "\n")
12078 (beginning-of-line 0)
12079 (list (concat (car parent-target) "/" child) file "" (point)))))))
12081 (defun org-olpath-completing-read (prompt collection &rest args)
12082 "Read an outline path like a file name."
12083 (let ((thetable collection))
12084 (apply #'completing-read
12085 prompt
12086 (lambda (string predicate &optional flag)
12087 (cond
12088 ((eq flag nil) (try-completion string thetable))
12089 ((eq flag t)
12090 (let ((l (length string)))
12091 (mapcar (lambda (x)
12092 (let ((r (substring x l))
12093 (f (if (string-match " ([^)]*)$" x)
12094 (match-string 0 x)
12095 "")))
12096 (if (string-match "/" r)
12097 (concat string (substring r 0 (match-end 0)) f)
12098 x)))
12099 (all-completions string thetable predicate))))
12100 ;; Exact match?
12101 ((eq flag 'lambda) (assoc string thetable))))
12102 args)))
12104 ;;;; Dynamic blocks
12106 (defun org-find-dblock (name)
12107 "Find the first dynamic block with name NAME in the buffer.
12108 If not found, stay at current position and return nil."
12109 (let ((case-fold-search t) pos)
12110 (save-excursion
12111 (goto-char (point-min))
12112 (setq pos (and (re-search-forward
12113 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12114 (match-beginning 0))))
12115 (when pos (goto-char pos))
12116 pos))
12118 (defun org-create-dblock (plist)
12119 "Create a dynamic block section, with parameters taken from PLIST.
12120 PLIST must contain a :name entry which is used as the name of the block."
12121 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12122 (end-of-line 1)
12123 (newline))
12124 (let ((col (current-column))
12125 (name (plist-get plist :name)))
12126 (insert "#+BEGIN: " name)
12127 (while plist
12128 (if (eq (car plist) :name)
12129 (setq plist (cddr plist))
12130 (insert " " (prin1-to-string (pop plist)))))
12131 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12132 (beginning-of-line -2)))
12134 (defun org-prepare-dblock ()
12135 "Prepare dynamic block for refresh.
12136 This empties the block, puts the cursor at the insert position and returns
12137 the property list including an extra property :name with the block name."
12138 (unless (looking-at org-dblock-start-re)
12139 (user-error "Not at a dynamic block"))
12140 (let* ((begdel (1+ (match-end 0)))
12141 (name (org-no-properties (match-string 1)))
12142 (params (append (list :name name)
12143 (read (concat "(" (match-string 3) ")")))))
12144 (save-excursion
12145 (beginning-of-line 1)
12146 (skip-chars-forward " \t")
12147 (setq params (plist-put params :indentation-column (current-column))))
12148 (unless (re-search-forward org-dblock-end-re nil t)
12149 (error "Dynamic block not terminated"))
12150 (setq params
12151 (append params
12152 (list :content (buffer-substring
12153 begdel (match-beginning 0)))))
12154 (delete-region begdel (match-beginning 0))
12155 (goto-char begdel)
12156 (open-line 1)
12157 params))
12159 (defun org-map-dblocks (&optional command)
12160 "Apply COMMAND to all dynamic blocks in the current buffer.
12161 If COMMAND is not given, use `org-update-dblock'."
12162 (let ((cmd (or command 'org-update-dblock)))
12163 (save-excursion
12164 (goto-char (point-min))
12165 (while (re-search-forward org-dblock-start-re nil t)
12166 (goto-char (match-beginning 0))
12167 (save-excursion
12168 (condition-case nil
12169 (funcall cmd)
12170 (error (message "Error during update of dynamic block"))))
12171 (unless (re-search-forward org-dblock-end-re nil t)
12172 (error "Dynamic block not terminated"))))))
12174 (defun org-dblock-update (&optional arg)
12175 "User command for updating dynamic blocks.
12176 Update the dynamic block at point. With prefix ARG, update all dynamic
12177 blocks in the buffer."
12178 (interactive "P")
12179 (if arg
12180 (org-update-all-dblocks)
12181 (or (looking-at org-dblock-start-re)
12182 (org-beginning-of-dblock))
12183 (org-update-dblock)))
12185 (defun org-update-dblock ()
12186 "Update the dynamic block at point.
12187 This means to empty the block, parse for parameters and then call
12188 the correct writing function."
12189 (interactive)
12190 (save-excursion
12191 (let* ((win (selected-window))
12192 (pos (point))
12193 (line (org-current-line))
12194 (params (org-prepare-dblock))
12195 (name (plist-get params :name))
12196 (indent (plist-get params :indentation-column))
12197 (cmd (intern (concat "org-dblock-write:" name))))
12198 (message "Updating dynamic block `%s' at line %d..." name line)
12199 (funcall cmd params)
12200 (message "Updating dynamic block `%s' at line %d...done" name line)
12201 (goto-char pos)
12202 (when (and indent (> indent 0))
12203 (setq indent (make-string indent ?\ ))
12204 (save-excursion
12205 (select-window win)
12206 (org-beginning-of-dblock)
12207 (forward-line 1)
12208 (while (not (looking-at org-dblock-end-re))
12209 (insert indent)
12210 (beginning-of-line 2))
12211 (when (looking-at org-dblock-end-re)
12212 (and (looking-at "[ \t]+")
12213 (replace-match ""))
12214 (insert indent)))))))
12216 (defun org-beginning-of-dblock ()
12217 "Find the beginning of the dynamic block at point.
12218 Error if there is no such block at point."
12219 (let ((pos (point))
12220 beg)
12221 (end-of-line 1)
12222 (if (and (re-search-backward org-dblock-start-re nil t)
12223 (setq beg (match-beginning 0))
12224 (re-search-forward org-dblock-end-re nil t)
12225 (> (match-end 0) pos))
12226 (goto-char beg)
12227 (goto-char pos)
12228 (error "Not in a dynamic block"))))
12230 (defun org-update-all-dblocks ()
12231 "Update all dynamic blocks in the buffer.
12232 This function can be used in a hook."
12233 (interactive)
12234 (when (derived-mode-p 'org-mode)
12235 (org-map-dblocks 'org-update-dblock)))
12238 ;;;; Completion
12240 (declare-function org-export-backend-name "org-export" (cl-x))
12241 (declare-function org-export-backend-options "org-export" (cl-x))
12242 (defun org-get-export-keywords ()
12243 "Return a list of all currently understood export keywords.
12244 Export keywords include options, block names, attributes and
12245 keywords relative to each registered export back-end."
12246 (let (keywords)
12247 (dolist (backend
12248 (org-bound-and-true-p org-export-registered-backends)
12249 (delq nil keywords))
12250 ;; Back-end name (for keywords, like #+LATEX:)
12251 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12252 (dolist (option-entry (org-export-backend-options backend))
12253 ;; Back-end options.
12254 (push (nth 1 option-entry) keywords)))))
12256 (defconst org-options-keywords
12257 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12258 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12259 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12260 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12261 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12263 (defcustom org-structure-template-alist
12264 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12265 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12266 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12267 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12268 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12269 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12270 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12271 ("L" "#+LaTeX: ")
12272 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12273 ("H" "#+HTML: ")
12274 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12275 ("A" "#+ASCII: ")
12276 ("i" "#+INDEX: ?")
12277 ("I" "#+INCLUDE: %file ?"))
12278 "Structure completion elements.
12279 This is a list of abbreviation keys and values. The value gets inserted
12280 if you type `<' followed by the key and then press the completion key,
12281 usually `TAB'. %file will be replaced by a file name after prompting
12282 for the file using completion. The cursor will be placed at the position
12283 of the `?' in the template.
12284 There are two templates for each key, the first uses the original Org syntax,
12285 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12286 the default when the /org-mtags.el/ module has been loaded. See also the
12287 variable `org-mtags-prefer-muse-templates'."
12288 :group 'org-completion
12289 :type '(repeat
12290 (list
12291 (string :tag "Key")
12292 (string :tag "Template")))
12293 :version "25.1"
12294 :package-version '(Org . "8.3"))
12296 (defun org-try-structure-completion ()
12297 "Try to complete a structure template before point.
12298 This looks for strings like \"<e\" on an otherwise empty line and
12299 expands them."
12300 (let ((l (buffer-substring (point-at-bol) (point)))
12302 (when (and (looking-at "[ \t]*$")
12303 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12304 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12305 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12306 (match-beginning 1)) a)
12307 t)))
12309 (defun org-complete-expand-structure-template (start cell)
12310 "Expand a structure template."
12311 (let ((rpl (nth 1 cell))
12312 (ind ""))
12313 (delete-region start (point))
12314 (when (string-match "\\`[ \t]*#\\+" rpl)
12315 (cond
12316 ((bolp))
12317 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12318 (setq ind (buffer-substring (point-at-bol) (point))))
12319 (t (newline))))
12320 (setq start (point))
12321 (when (string-match "%file" rpl)
12322 (setq rpl (replace-match
12323 (concat
12324 "\""
12325 (save-match-data
12326 (abbreviate-file-name (read-file-name "Include file: ")))
12327 "\"")
12328 t t rpl)))
12329 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12330 (concat "\n" ind)))
12331 (insert rpl)
12332 (when (re-search-backward "\\?" start t) (delete-char 1))))
12334 ;;;; TODO, DEADLINE, Comments
12336 (defun org-toggle-comment ()
12337 "Change the COMMENT state of an entry."
12338 (interactive)
12339 (save-excursion
12340 (org-back-to-heading)
12341 (looking-at org-complex-heading-regexp)
12342 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12343 (skip-chars-forward " \t")
12344 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12345 (if (org-in-commented-heading-p t)
12346 (delete-region (point)
12347 (progn (search-forward " " (line-end-position) 'move)
12348 (skip-chars-forward " \t")
12349 (point)))
12350 (insert org-comment-string)
12351 (unless (eolp) (insert " ")))))
12353 (defvar org-last-todo-state-is-todo nil
12354 "This is non-nil when the last TODO state change led to a TODO state.
12355 If the last change removed the TODO tag or switched to DONE, then
12356 this is nil.")
12358 (defvar org-setting-tags nil) ; dynamically skipped
12360 (defvar org-todo-setup-filter-hook nil
12361 "Hook for functions that pre-filter todo specs.
12362 Each function takes a todo spec and returns either nil or the spec
12363 transformed into canonical form." )
12365 (defvar org-todo-get-default-hook nil
12366 "Hook for functions that get a default item for todo.
12367 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12368 nil or a string to be used for the todo mark." )
12370 (defvar org-agenda-headline-snapshot-before-repeat)
12372 (defun org-current-effective-time ()
12373 "Return current time adjusted for `org-extend-today-until' variable."
12374 (let* ((ct (org-current-time))
12375 (dct (decode-time ct))
12376 (ct1
12377 (cond
12378 (org-use-last-clock-out-time-as-effective-time
12379 (or (org-clock-get-last-clock-out-time) ct))
12380 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12381 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12382 (t ct))))
12383 ct1))
12385 (defun org-todo-yesterday (&optional arg)
12386 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12387 (interactive "P")
12388 (if (eq major-mode 'org-agenda-mode)
12389 (apply 'org-agenda-todo-yesterday arg)
12390 (let* ((org-use-effective-time t)
12391 (hour (nth 2 (decode-time (org-current-time))))
12392 (org-extend-today-until (1+ hour)))
12393 (org-todo arg))))
12395 (defvar org-block-entry-blocking ""
12396 "First entry preventing the TODO state change.")
12398 (defun org-cancel-repeater ()
12399 "Cancel a repeater by setting its numeric value to zero."
12400 (interactive)
12401 (save-excursion
12402 (org-back-to-heading t)
12403 (let ((bound1 (point))
12404 (bound0 (save-excursion (outline-next-heading) (point))))
12405 (when (and (re-search-forward
12406 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12407 org-deadline-time-regexp "\\)\\|\\("
12408 org-ts-regexp "\\)")
12409 bound0 t)
12410 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12411 bound1 t))
12412 (replace-match "0" t nil nil 1)))))
12414 (defvar org-state) ;; dynamically scoped into this function
12415 (defun org-todo (&optional arg)
12416 "Change the TODO state of an item.
12417 The state of an item is given by a keyword at the start of the heading,
12418 like
12419 *** TODO Write paper
12420 *** DONE Call mom
12422 The different keywords are specified in the variable `org-todo-keywords'.
12423 By default the available states are \"TODO\" and \"DONE\".
12424 So for this example: when the item starts with TODO, it is changed to DONE.
12425 When it starts with DONE, the DONE is removed. And when neither TODO nor
12426 DONE are present, add TODO at the beginning of the heading.
12428 With \\[universal-argument] prefix arg, use completion to determine the new \
12429 state.
12430 With numeric prefix arg, switch to that state.
12431 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12432 keywords (nextset).
12433 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12434 With a numeric prefix arg of 0, inhibit note taking for the change.
12435 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12437 When called through ELisp, arg is also interpreted in the following way:
12438 `none' -> empty state
12439 \"\"(empty string) -> switch to empty state
12440 `done' -> switch to DONE
12441 `nextset' -> switch to the next set of keywords
12442 `previousset' -> switch to the previous set of keywords
12443 \"WAITING\" -> switch to the specified keyword, but only if it
12444 really is a member of `org-todo-keywords'."
12445 (interactive "P")
12446 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12447 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12448 'region-start-level 'region))
12449 org-loop-over-headlines-in-active-region)
12450 (org-map-entries
12451 `(org-todo ,arg)
12452 org-loop-over-headlines-in-active-region
12453 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12454 (when (equal arg '(16)) (setq arg 'nextset))
12455 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12456 (let ((org-blocker-hook org-blocker-hook)
12457 commentp
12458 case-fold-search)
12459 (when (equal arg '(64))
12460 (setq arg nil org-blocker-hook nil))
12461 (when (and org-blocker-hook
12462 (or org-inhibit-blocking
12463 (org-entry-get nil "NOBLOCKING")))
12464 (setq org-blocker-hook nil))
12465 (save-excursion
12466 (catch 'exit
12467 (org-back-to-heading t)
12468 (when (org-in-commented-heading-p t)
12469 (org-toggle-comment)
12470 (setq commentp t))
12471 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12472 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12473 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12474 (let* ((match-data (match-data))
12475 (startpos (point-at-bol))
12476 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12477 (org-log-done org-log-done)
12478 (org-log-repeat org-log-repeat)
12479 (org-todo-log-states org-todo-log-states)
12480 (org-inhibit-logging
12481 (if (equal arg 0)
12482 (progn (setq arg nil) 'note) org-inhibit-logging))
12483 (this (match-string 1))
12484 (hl-pos (match-beginning 0))
12485 (head (org-get-todo-sequence-head this))
12486 (ass (assoc head org-todo-kwd-alist))
12487 (interpret (nth 1 ass))
12488 (done-word (nth 3 ass))
12489 (final-done-word (nth 4 ass))
12490 (org-last-state (or this ""))
12491 (completion-ignore-case t)
12492 (member (member this org-todo-keywords-1))
12493 (tail (cdr member))
12494 (org-state (cond
12495 ((and org-todo-key-trigger
12496 (or (and (equal arg '(4))
12497 (eq org-use-fast-todo-selection 'prefix))
12498 (and (not arg) org-use-fast-todo-selection
12499 (not (eq org-use-fast-todo-selection
12500 'prefix)))))
12501 ;; Use fast selection
12502 (org-fast-todo-selection))
12503 ((and (equal arg '(4))
12504 (or (not org-use-fast-todo-selection)
12505 (not org-todo-key-trigger)))
12506 ;; Read a state with completion
12507 (completing-read
12508 "State: " (mapcar #'list org-todo-keywords-1)
12509 nil t))
12510 ((eq arg 'right)
12511 (if this
12512 (if tail (car tail) nil)
12513 (car org-todo-keywords-1)))
12514 ((eq arg 'left)
12515 (unless (equal member org-todo-keywords-1)
12516 (if this
12517 (nth (- (length org-todo-keywords-1)
12518 (length tail) 2)
12519 org-todo-keywords-1)
12520 (org-last org-todo-keywords-1))))
12521 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12522 (setq arg nil))) ; hack to fall back to cycling
12523 (arg
12524 ;; user or caller requests a specific state
12525 (cond
12526 ((equal arg "") nil)
12527 ((eq arg 'none) nil)
12528 ((eq arg 'done) (or done-word (car org-done-keywords)))
12529 ((eq arg 'nextset)
12530 (or (car (cdr (member head org-todo-heads)))
12531 (car org-todo-heads)))
12532 ((eq arg 'previousset)
12533 (let ((org-todo-heads (reverse org-todo-heads)))
12534 (or (car (cdr (member head org-todo-heads)))
12535 (car org-todo-heads))))
12536 ((car (member arg org-todo-keywords-1)))
12537 ((stringp arg)
12538 (user-error "State `%s' not valid in this file" arg))
12539 ((nth (1- (prefix-numeric-value arg))
12540 org-todo-keywords-1))))
12541 ((null member) (or head (car org-todo-keywords-1)))
12542 ((equal this final-done-word) nil) ;; -> make empty
12543 ((null tail) nil) ;; -> first entry
12544 ((memq interpret '(type priority))
12545 (if (eq this-command last-command)
12546 (car tail)
12547 (if (> (length tail) 0)
12548 (or done-word (car org-done-keywords))
12549 nil)))
12551 (car tail))))
12552 (org-state (or
12553 (run-hook-with-args-until-success
12554 'org-todo-get-default-hook org-state org-last-state)
12555 org-state))
12556 (next (if org-state (concat " " org-state " ") " "))
12557 (change-plist (list :type 'todo-state-change :from this :to org-state
12558 :position startpos))
12559 dolog now-done-p)
12560 (when org-blocker-hook
12561 (setq org-last-todo-state-is-todo
12562 (not (member this org-done-keywords)))
12563 (unless (save-excursion
12564 (save-match-data
12565 (org-with-wide-buffer
12566 (run-hook-with-args-until-failure
12567 'org-blocker-hook change-plist))))
12568 (if (org-called-interactively-p 'interactive)
12569 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12570 this org-state org-block-entry-blocking)
12571 ;; fail silently
12572 (message "TODO state change from %s to %s blocked (by \"%s\")"
12573 this org-state org-block-entry-blocking)
12574 (throw 'exit nil))))
12575 (store-match-data match-data)
12576 (replace-match next t t)
12577 (cond ((equal this org-state)
12578 (message "TODO state was already %s" (org-trim next)))
12579 ((pos-visible-in-window-p hl-pos)
12580 (message "TODO state changed to %s" (org-trim next))))
12581 (unless head
12582 (setq head (org-get-todo-sequence-head org-state)
12583 ass (assoc head org-todo-kwd-alist)
12584 interpret (nth 1 ass)
12585 done-word (nth 3 ass)
12586 final-done-word (nth 4 ass)))
12587 (when (memq arg '(nextset previousset))
12588 (message "Keyword-Set %d/%d: %s"
12589 (- (length org-todo-sets) -1
12590 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12591 (length org-todo-sets)
12592 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12593 (setq org-last-todo-state-is-todo
12594 (not (member org-state org-done-keywords)))
12595 (setq now-done-p (and (member org-state org-done-keywords)
12596 (not (member this org-done-keywords))))
12597 (and logging (org-local-logging logging))
12598 (when (and (or org-todo-log-states org-log-done)
12599 (not (eq org-inhibit-logging t))
12600 (not (memq arg '(nextset previousset))))
12601 ;; we need to look at recording a time and note
12602 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12603 (nth 2 (assoc this org-todo-log-states))))
12604 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12605 (setq dolog 'time))
12606 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12607 (and org-state
12608 (member org-state org-not-done-keywords)
12609 (not (member this org-not-done-keywords))))
12610 ;; This is now a todo state and was not one before
12611 ;; If there was a CLOSED time stamp, get rid of it.
12612 (org-add-planning-info nil nil 'closed))
12613 (when (and now-done-p org-log-done)
12614 ;; It is now done, and it was not done before
12615 (org-add-planning-info 'closed (org-current-effective-time))
12616 (when (and (not dolog) (eq 'note org-log-done))
12617 (org-add-log-setup 'done org-state this 'note)))
12618 (when (and org-state dolog)
12619 ;; This is a non-nil state, and we need to log it
12620 (org-add-log-setup 'state org-state this dolog)))
12621 ;; Fixup tag positioning
12622 (org-todo-trigger-tag-changes org-state)
12623 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12624 (when org-provide-todo-statistics
12625 (org-update-parent-todo-statistics))
12626 (run-hooks 'org-after-todo-state-change-hook)
12627 (when (and arg (not (member org-state org-done-keywords)))
12628 (setq head (org-get-todo-sequence-head org-state)))
12629 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12630 ;; Do we need to trigger a repeat?
12631 (when now-done-p
12632 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12633 ;; This is for the agenda, take a snapshot of the headline.
12634 (save-match-data
12635 (setq org-agenda-headline-snapshot-before-repeat
12636 (org-get-heading))))
12637 (org-auto-repeat-maybe org-state))
12638 ;; Fixup cursor location if close to the keyword
12639 (when (and (outline-on-heading-p)
12640 (not (bolp))
12641 (save-excursion (beginning-of-line 1)
12642 (looking-at org-todo-line-regexp))
12643 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12644 (goto-char (or (match-end 2) (match-end 1)))
12645 (and (looking-at " ") (just-one-space)))
12646 (when org-trigger-hook
12647 (save-excursion
12648 (run-hook-with-args 'org-trigger-hook change-plist)))
12649 (when commentp (org-toggle-comment))))))))
12651 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12652 "Block turning an entry into a TODO, using the hierarchy.
12653 This checks whether the current task should be blocked from state
12654 changes. Such blocking occurs when:
12656 1. The task has children which are not all in a completed state.
12658 2. A task has a parent with the property :ORDERED:, and there
12659 are siblings prior to the current task with incomplete
12660 status.
12662 3. The parent of the task is blocked because it has siblings that should
12663 be done first, or is child of a block grandparent TODO entry."
12665 (if (not org-enforce-todo-dependencies)
12666 t ; if locally turned off don't block
12667 (catch 'dont-block
12668 ;; If this is not a todo state change, or if this entry is already DONE,
12669 ;; do not block
12670 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12671 (member (plist-get change-plist :from)
12672 (cons 'done org-done-keywords))
12673 (member (plist-get change-plist :to)
12674 (cons 'todo org-not-done-keywords))
12675 (not (plist-get change-plist :to)))
12676 (throw 'dont-block t))
12677 ;; If this task has children, and any are undone, it's blocked
12678 (save-excursion
12679 (org-back-to-heading t)
12680 (let ((this-level (funcall outline-level)))
12681 (outline-next-heading)
12682 (let ((child-level (funcall outline-level)))
12683 (while (and (not (eobp))
12684 (> child-level this-level))
12685 ;; this todo has children, check whether they are all
12686 ;; completed
12687 (when (and (not (org-entry-is-done-p))
12688 (org-entry-is-todo-p))
12689 (setq org-block-entry-blocking (org-get-heading))
12690 (throw 'dont-block nil))
12691 (outline-next-heading)
12692 (setq child-level (funcall outline-level))))))
12693 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12694 ;; any previous siblings are undone, it's blocked
12695 (save-excursion
12696 (org-back-to-heading t)
12697 (let* ((pos (point))
12698 (parent-pos (and (org-up-heading-safe) (point))))
12699 (unless parent-pos (throw 'dont-block t)) ; no parent
12700 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12701 (forward-line 1)
12702 (re-search-forward org-not-done-heading-regexp pos t))
12703 (setq org-block-entry-blocking (match-string 0))
12704 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12705 ;; Search further up the hierarchy, to see if an ancestor is blocked
12706 (while t
12707 (goto-char parent-pos)
12708 (unless (looking-at org-not-done-heading-regexp)
12709 (throw 'dont-block t)) ; do not block, parent is not a TODO
12710 (setq pos (point))
12711 (setq parent-pos (and (org-up-heading-safe) (point)))
12712 (unless parent-pos (throw 'dont-block t)) ; no parent
12713 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12714 (forward-line 1)
12715 (re-search-forward org-not-done-heading-regexp pos t)
12716 (setq org-block-entry-blocking (org-get-heading)))
12717 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12719 (defcustom org-track-ordered-property-with-tag nil
12720 "Should the ORDERED property also be shown as a tag?
12721 The ORDERED property decides if an entry should require subtasks to be
12722 completed in sequence. Since a property is not very visible, setting
12723 this option means that toggling the ORDERED property with the command
12724 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12725 not relevant for the behavior, but it makes things more visible.
12727 Note that toggling the tag with tags commands will not change the property
12728 and therefore not influence behavior!
12730 This can be t, meaning the tag ORDERED should be used, It can also be a
12731 string to select a different tag for this task."
12732 :group 'org-todo
12733 :type '(choice
12734 (const :tag "No tracking" nil)
12735 (const :tag "Track with ORDERED tag" t)
12736 (string :tag "Use other tag")))
12738 (defun org-toggle-ordered-property ()
12739 "Toggle the ORDERED property of the current entry.
12740 For better visibility, you can track the value of this property with a tag.
12741 See variable `org-track-ordered-property-with-tag'."
12742 (interactive)
12743 (let* ((t1 org-track-ordered-property-with-tag)
12744 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12745 (save-excursion
12746 (org-back-to-heading)
12747 (if (org-entry-get nil "ORDERED")
12748 (progn
12749 (org-delete-property "ORDERED")
12750 (and tag (org-toggle-tag tag 'off))
12751 (message "Subtasks can be completed in arbitrary order"))
12752 (org-entry-put nil "ORDERED" "t")
12753 (and tag (org-toggle-tag tag 'on))
12754 (message "Subtasks must be completed in sequence")))))
12756 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12757 (defun org-block-todo-from-checkboxes (change-plist)
12758 "Block turning an entry into a TODO, using checkboxes.
12759 This checks whether the current task should be blocked from state
12760 changes because there are unchecked boxes in this entry."
12761 (if (not org-enforce-todo-checkbox-dependencies)
12762 t ; if locally turned off don't block
12763 (catch 'dont-block
12764 ;; If this is not a todo state change, or if this entry is already DONE,
12765 ;; do not block
12766 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12767 (member (plist-get change-plist :from)
12768 (cons 'done org-done-keywords))
12769 (member (plist-get change-plist :to)
12770 (cons 'todo org-not-done-keywords))
12771 (not (plist-get change-plist :to)))
12772 (throw 'dont-block t))
12773 ;; If this task has checkboxes that are not checked, it's blocked
12774 (save-excursion
12775 (org-back-to-heading t)
12776 (let ((beg (point)) end)
12777 (outline-next-heading)
12778 (setq end (point))
12779 (goto-char beg)
12780 (when (org-list-search-forward
12781 (concat (org-item-beginning-re)
12782 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12783 "\\[[- ]\\]")
12784 end t)
12785 (when (boundp 'org-blocked-by-checkboxes)
12786 (setq org-blocked-by-checkboxes t))
12787 (throw 'dont-block nil))))
12788 t))) ; do not block
12790 (defun org-entry-blocked-p ()
12791 "Non-nil if entry at point is blocked."
12792 (and (not (org-entry-get nil "NOBLOCKING"))
12793 (member (org-entry-get nil "TODO") org-not-done-keywords)
12794 (not (run-hook-with-args-until-failure
12795 'org-blocker-hook
12796 (list :type 'todo-state-change
12797 :position (point)
12798 :from 'todo
12799 :to 'done)))))
12801 (defun org-update-statistics-cookies (all)
12802 "Update the statistics cookie, either from TODO or from checkboxes.
12803 This should be called with the cursor in a line with a statistics cookie."
12804 (interactive "P")
12805 (if all
12806 (progn
12807 (org-update-checkbox-count 'all)
12808 (org-map-entries 'org-update-parent-todo-statistics))
12809 (if (not (org-at-heading-p))
12810 (org-update-checkbox-count)
12811 (let ((pos (point-marker))
12812 end l1 l2)
12813 (ignore-errors (org-back-to-heading t))
12814 (if (not (org-at-heading-p))
12815 (org-update-checkbox-count)
12816 (setq l1 (org-outline-level))
12817 (setq end (save-excursion
12818 (outline-next-heading)
12819 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12820 (point)))
12821 (if (and (save-excursion
12822 (re-search-forward
12823 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12824 (not (save-excursion (re-search-forward
12825 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12826 (org-update-checkbox-count)
12827 (if (and l2 (> l2 l1))
12828 (progn
12829 (goto-char end)
12830 (org-update-parent-todo-statistics))
12831 (goto-char pos)
12832 (beginning-of-line 1)
12833 (while (re-search-forward
12834 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12835 (point-at-eol) t)
12836 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12837 (goto-char pos)
12838 (move-marker pos nil)))))
12840 (defvar org-entry-property-inherited-from) ;; defined below
12841 (defun org-update-parent-todo-statistics ()
12842 "Update any statistics cookie in the parent of the current headline.
12843 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12844 the entire subtree and this will travel up the hierarchy and update
12845 statistics everywhere."
12846 (let* ((prop (save-excursion (org-up-heading-safe)
12847 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12848 (recursive (or (not org-hierarchical-todo-statistics)
12849 (and prop (string-match "\\<recursive\\>" prop))))
12850 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12852 (first t)
12853 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12854 level ltoggle l1 new ndel
12855 (cnt-all 0) (cnt-done 0) is-percent kwd
12856 checkbox-beg ov ovs ove cookie-present)
12857 (catch 'exit
12858 (save-excursion
12859 (beginning-of-line 1)
12860 (setq ltoggle (funcall outline-level))
12861 ;; Three situations are to consider:
12863 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12864 ;; to the top-level ancestor on the headline;
12866 ;; 2. If parent has "recursive" property, repeat up to the
12867 ;; headline setting that property, taking inheritance into
12868 ;; account;
12870 ;; 3. Else, move up to direct parent and proceed only once.
12871 (while (and (setq level (org-up-heading-safe))
12872 (or recursive first)
12873 (>= (point) lim))
12874 (setq first nil cookie-present nil)
12875 (unless (and level
12876 (not (string-match
12877 "\\<checkbox\\>"
12878 (downcase (or (org-entry-get nil "COOKIE_DATA")
12879 "")))))
12880 (throw 'exit nil))
12881 (while (re-search-forward box-re (point-at-eol) t)
12882 (setq cnt-all 0 cnt-done 0 cookie-present t)
12883 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12884 (save-match-data
12885 (unless (outline-next-heading) (throw 'exit nil))
12886 (while (and (looking-at org-complex-heading-regexp)
12887 (> (setq l1 (length (match-string 1))) level))
12888 (setq kwd (and (or recursive (= l1 ltoggle))
12889 (match-string 2)))
12890 (if (or (eq org-provide-todo-statistics 'all-headlines)
12891 (and (eq org-provide-todo-statistics t)
12892 (or (member kwd org-done-keywords)))
12893 (and (listp org-provide-todo-statistics)
12894 (stringp (car org-provide-todo-statistics))
12895 (or (member kwd org-provide-todo-statistics)
12896 (member kwd org-done-keywords)))
12897 (and (listp org-provide-todo-statistics)
12898 (listp (car org-provide-todo-statistics))
12899 (or (member kwd (car org-provide-todo-statistics))
12900 (and (member kwd org-done-keywords)
12901 (member kwd (cadr org-provide-todo-statistics))))))
12902 (setq cnt-all (1+ cnt-all))
12903 (and (eq org-provide-todo-statistics t)
12905 (setq cnt-all (1+ cnt-all))))
12906 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12907 (member kwd org-done-keywords))
12908 (and (listp org-provide-todo-statistics)
12909 (listp (car org-provide-todo-statistics))
12910 (member kwd org-done-keywords)
12911 (member kwd (cadr org-provide-todo-statistics)))
12912 (and (listp org-provide-todo-statistics)
12913 (stringp (car org-provide-todo-statistics))
12914 (member kwd org-done-keywords)))
12915 (setq cnt-done (1+ cnt-done)))
12916 (outline-next-heading)))
12917 (setq new
12918 (if is-percent
12919 (format "[%d%%]" (floor (* 100.0 cnt-done)
12920 (max 1 cnt-all)))
12921 (format "[%d/%d]" cnt-done cnt-all))
12922 ndel (- (match-end 0) checkbox-beg))
12923 ;; handle overlays when updating cookie from column view
12924 (when (setq ov (car (overlays-at checkbox-beg)))
12925 (setq ovs (overlay-start ov) ove (overlay-end ov))
12926 (delete-overlay ov))
12927 (goto-char checkbox-beg)
12928 (insert new)
12929 (delete-region (point) (+ (point) ndel))
12930 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12931 (when ov (move-overlay ov ovs ove)))
12932 (when cookie-present
12933 (run-hook-with-args 'org-after-todo-statistics-hook
12934 cnt-done (- cnt-all cnt-done))))))
12935 (run-hooks 'org-todo-statistics-hook)))
12937 (defvar org-after-todo-statistics-hook nil
12938 "Hook that is called after a TODO statistics cookie has been updated.
12939 Each function is called with two arguments: the number of not-done entries
12940 and the number of done entries.
12942 For example, the following function, when added to this hook, will switch
12943 an entry to DONE when all children are done, and back to TODO when new
12944 entries are set to a TODO status. Note that this hook is only called
12945 when there is a statistics cookie in the headline!
12947 \(defun org-summary-todo (n-done n-not-done)
12948 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12949 \(let (org-log-done org-log-states) ; turn off logging
12950 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12953 (defvar org-todo-statistics-hook nil
12954 "Hook that is run whenever Org thinks TODO statistics should be updated.
12955 This hook runs even if there is no statistics cookie present, in which case
12956 `org-after-todo-statistics-hook' would not run.")
12958 (defun org-todo-trigger-tag-changes (state)
12959 "Apply the changes defined in `org-todo-state-tags-triggers'."
12960 (let ((l org-todo-state-tags-triggers)
12961 changes)
12962 (when (or (not state) (equal state ""))
12963 (setq changes (append changes (cdr (assoc "" l)))))
12964 (when (and (stringp state) (> (length state) 0))
12965 (setq changes (append changes (cdr (assoc state l)))))
12966 (when (member state org-not-done-keywords)
12967 (setq changes (append changes (cdr (assoc 'todo l)))))
12968 (when (member state org-done-keywords)
12969 (setq changes (append changes (cdr (assoc 'done l)))))
12970 (dolist (c changes)
12971 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12973 (defun org-local-logging (value)
12974 "Get logging settings from a property VALUE."
12975 ;; Directly set the variables, they are already local.
12976 (setq org-log-done nil
12977 org-log-repeat nil
12978 org-todo-log-states nil)
12979 (dolist (w (org-split-string value))
12980 (let (a)
12981 (cond
12982 ((setq a (assoc w org-startup-options))
12983 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12984 (set (nth 1 a) (nth 2 a))))
12985 ((setq a (org-extract-log-state-settings w))
12986 (and (member (car a) org-todo-keywords-1)
12987 (push a org-todo-log-states)))))))
12989 (defun org-get-todo-sequence-head (kwd)
12990 "Return the head of the TODO sequence to which KWD belongs.
12991 If KWD is not set, check if there is a text property remembering the
12992 right sequence."
12993 (let (p)
12994 (cond
12995 ((not kwd)
12996 (or (get-text-property (point-at-bol) 'org-todo-head)
12997 (progn
12998 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12999 nil (point-at-eol)))
13000 (get-text-property p 'org-todo-head))))
13001 ((not (member kwd org-todo-keywords-1))
13002 (car org-todo-keywords-1))
13003 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13005 (defun org-fast-todo-selection ()
13006 "Fast TODO keyword selection with single keys.
13007 Returns the new TODO keyword, or nil if no state change should occur."
13008 (let* ((fulltable org-todo-key-alist)
13009 (done-keywords org-done-keywords) ;; needed for the faces.
13010 (maxlen (apply 'max (mapcar
13011 (lambda (x)
13012 (if (stringp (car x)) (string-width (car x)) 0))
13013 fulltable)))
13014 (expert nil)
13015 (fwidth (+ maxlen 3 1 3))
13016 (ncol (/ (- (window-width) 4) fwidth))
13017 tg cnt e c tbl
13018 groups ingroup)
13019 (save-excursion
13020 (save-window-excursion
13021 (if expert
13022 (set-buffer (get-buffer-create " *Org todo*"))
13023 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13024 (erase-buffer)
13025 (setq-local org-done-keywords done-keywords)
13026 (setq tbl fulltable cnt 0)
13027 (while (setq e (pop tbl))
13028 (cond
13029 ((equal e '(:startgroup))
13030 (push '() groups) (setq ingroup t)
13031 (unless (= cnt 0)
13032 (setq cnt 0)
13033 (insert "\n"))
13034 (insert "{ "))
13035 ((equal e '(:endgroup))
13036 (setq ingroup nil cnt 0)
13037 (insert "}\n"))
13038 ((equal e '(:newline))
13039 (unless (= cnt 0)
13040 (setq cnt 0)
13041 (insert "\n")
13042 (setq e (car tbl))
13043 (while (equal (car tbl) '(:newline))
13044 (insert "\n")
13045 (setq tbl (cdr tbl)))))
13047 (setq tg (car e) c (cdr e))
13048 (when ingroup (push tg (car groups)))
13049 (setq tg (org-add-props tg nil 'face
13050 (org-get-todo-face tg)))
13051 (when (and (= cnt 0) (not ingroup)) (insert " "))
13052 (insert "[" c "] " tg (make-string
13053 (- fwidth 4 (length tg)) ?\ ))
13054 (when (= (setq cnt (1+ cnt)) ncol)
13055 (insert "\n")
13056 (when ingroup (insert " "))
13057 (setq cnt 0)))))
13058 (insert "\n")
13059 (goto-char (point-min))
13060 (unless expert (org-fit-window-to-buffer))
13061 (message "[a-z..]:Set [SPC]:clear")
13062 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13063 (cond
13064 ((or (= c ?\C-g)
13065 (and (= c ?q) (not (rassoc c fulltable))))
13066 (setq quit-flag t))
13067 ((= c ?\ ) nil)
13068 ((setq e (rassoc c fulltable) tg (car e))
13070 (t (setq quit-flag t)))))))
13072 (defun org-entry-is-todo-p ()
13073 (member (org-get-todo-state) org-not-done-keywords))
13075 (defun org-entry-is-done-p ()
13076 (member (org-get-todo-state) org-done-keywords))
13078 (defun org-get-todo-state ()
13079 "Return the TODO keyword of the current subtree."
13080 (save-excursion
13081 (org-back-to-heading t)
13082 (and (looking-at org-todo-line-regexp)
13083 (match-end 2)
13084 (match-string 2))))
13086 (defun org-at-date-range-p (&optional inactive-ok)
13087 "Non-nil if point is inside a date range.
13089 When optional argument INACTIVE-OK is non-nil, also consider
13090 inactive time ranges.
13092 When this function returns a non-nil value, match data is set
13093 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13094 on INACTIVE-OK."
13095 (interactive)
13096 (save-excursion
13097 (catch 'exit
13098 (let ((pos (point)))
13099 (skip-chars-backward "^[<\r\n")
13100 (skip-chars-backward "<[")
13101 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13102 (>= (match-end 0) pos)
13103 (throw 'exit t))
13104 (skip-chars-backward "^<[\r\n")
13105 (skip-chars-backward "<[")
13106 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13107 (>= (match-end 0) pos)
13108 (throw 'exit t)))
13109 nil)))
13111 (defun org-get-repeat (&optional tagline)
13112 "Check if there is a deadline/schedule with repeater in this entry."
13113 (save-match-data
13114 (save-excursion
13115 (org-back-to-heading t)
13116 (and (re-search-forward (if tagline
13117 (concat tagline "\\s-*" org-repeat-re)
13118 org-repeat-re)
13119 (org-entry-end-position) t)
13120 (match-string-no-properties 1)))))
13122 (defvar org-last-changed-timestamp)
13123 (defvar org-last-inserted-timestamp)
13124 (defvar org-log-post-message)
13125 (defvar org-log-note-purpose)
13126 (defvar org-log-note-how nil)
13127 (defvar org-log-note-extra)
13128 (defun org-auto-repeat-maybe (done-word)
13129 "Check if the current headline contains a repeated time-stamp.
13131 If yes, set TODO state back to what it was and change the base date
13132 of repeating deadline/scheduled time stamps to new date.
13134 This function is run automatically after each state change to a DONE state."
13135 (let* ((repeat (org-get-repeat))
13136 (aa (assoc org-last-state org-todo-kwd-alist))
13137 (interpret (nth 1 aa))
13138 (head (nth 2 aa))
13139 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13140 (msg "Entry repeats: ")
13141 (org-log-done nil)
13142 (org-todo-log-states nil))
13143 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13144 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13145 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13146 org-todo-repeat-to-state)))
13147 (unless (and to-state (member to-state org-todo-keywords-1))
13148 (setq to-state (if (eq interpret 'type) org-last-state head)))
13149 (org-todo to-state))
13150 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13151 (org-entry-put nil "LAST_REPEAT" (format-time-string
13152 (org-time-stamp-format t t))))
13153 (when org-log-repeat
13154 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13155 (memq 'org-add-log-note post-command-hook))
13156 ;; We are already setup for some record.
13157 (when (eq org-log-repeat 'note)
13158 ;; Make sure we take a note, not only a time stamp.
13159 (setq org-log-note-how 'note))
13160 ;; Set up for taking a record.
13161 (org-add-log-setup 'state
13162 (or done-word (car org-done-keywords))
13163 org-last-state
13164 org-log-repeat)))
13165 (org-back-to-heading t)
13166 (org-add-planning-info nil nil 'closed)
13167 (let ((end (save-excursion (outline-next-heading) (point))))
13168 (while (re-search-forward org-ts-regexp end t)
13169 (when (save-match-data
13170 (or (org-at-planning-p)
13171 (org-at-property-p)
13172 (eq (org-element-type (save-excursion
13173 (backward-char)
13174 (org-element-context)))
13175 'timestamp)))
13176 (let ((type (cond ((match-end 1) org-scheduled-string)
13177 ((match-end 3) org-deadline-string)
13178 (t "Plain:")))
13179 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13180 (cond
13181 ((not
13182 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13183 ;; Time-stamps without a repeater are usually skipped.
13184 ;; However, a SCHEDULED time-stamp without one is
13185 ;; removed, as it is considered as no longer relevant.
13186 (when (equal type org-scheduled-string)
13187 (org-remove-timestamp-with-keyword type)))
13189 (let ((n (string-to-number (match-string 2 ts)))
13190 (what (match-string 3 ts)))
13191 (when (equal what "w") (setq n (* n 7) what "d"))
13192 (when (and (equal what "h")
13193 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13194 ts)))
13195 (user-error
13196 "Cannot repeat in Repeat in %d hour(s) because no hour \
13197 has been set"
13199 ;; Preparation, see if we need to modify the start
13200 ;; date for the change.
13201 (when (match-end 1)
13202 (let ((time (save-match-data (org-time-string-to-time ts))))
13203 (cond
13204 ((equal (match-string 1 ts) ".")
13205 ;; Shift starting date to today
13206 (org-timestamp-change
13207 (- (org-today) (time-to-days time))
13208 'day))
13209 ((equal (match-string 1 ts) "+")
13210 (let ((nshiftmax 10)
13211 (nshift 0))
13212 (while (or (= nshift 0)
13213 (<= (time-to-days time)
13214 (time-to-days (current-time))))
13215 (when (= (cl-incf nshift) nshiftmax)
13216 (or (y-or-n-p
13217 (format "%d repeater intervals were not \
13218 enough to shift date past today. Continue? "
13219 nshift))
13220 (user-error "Abort")))
13221 (org-timestamp-change n (cdr (assoc what whata)))
13222 (org-at-timestamp-p t)
13223 (setq ts (match-string 1))
13224 (setq time
13225 (save-match-data
13226 (org-time-string-to-time ts)))))
13227 (org-timestamp-change (- n) (cdr (assoc what whata)))
13228 ;; Rematch, so that we have everything in
13229 ;; place for the real shift.
13230 (org-at-timestamp-p t)
13231 (setq ts (match-string 1))
13232 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13233 ts)))))
13234 (save-excursion
13235 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13236 (setq msg
13237 (concat
13238 msg type " " org-last-changed-timestamp " ")))))))))
13239 (setq org-log-post-message msg)
13240 (message "%s" msg))))
13242 (defun org-show-todo-tree (arg)
13243 "Make a compact tree which shows all headlines marked with TODO.
13244 The tree will show the lines where the regexp matches, and all higher
13245 headlines above the match.
13246 With a \\[universal-argument] prefix, prompt for a regexp to match.
13247 With a numeric prefix N, construct a sparse tree for the Nth element
13248 of `org-todo-keywords-1'."
13249 (interactive "P")
13250 (let ((case-fold-search nil)
13251 (kwd-re
13252 (cond ((null arg) org-not-done-regexp)
13253 ((equal arg '(4))
13254 (let ((kwd
13255 (completing-read "Keyword (or KWD1|KWD2|...): "
13256 (mapcar #'list org-todo-keywords-1))))
13257 (concat "\\("
13258 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13259 "\\)\\>")))
13260 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13261 (regexp-quote (nth (1- (prefix-numeric-value arg))
13262 org-todo-keywords-1)))
13263 (t (user-error "Invalid prefix argument: %s" arg)))))
13264 (message "%d TODO entries found"
13265 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13267 (defun org-deadline (arg &optional time)
13268 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13269 With one universal prefix argument, remove any deadline from the item.
13270 With two universal prefix arguments, prompt for a warning delay.
13271 With argument TIME, set the deadline at the corresponding date. TIME
13272 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13273 (interactive "P")
13274 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13275 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13276 'region-start-level 'region))
13277 org-loop-over-headlines-in-active-region)
13278 (org-map-entries
13279 `(org-deadline ',arg ,time)
13280 org-loop-over-headlines-in-active-region
13281 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13282 (let* ((old-date (org-entry-get nil "DEADLINE"))
13283 (old-date-time (when old-date (org-time-string-to-time old-date)))
13284 (repeater (and old-date
13285 (string-match
13286 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13287 old-date)
13288 (match-string 1 old-date))))
13289 (cond
13290 ((equal arg '(4))
13291 (when (and old-date org-log-redeadline)
13292 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13293 (org-remove-timestamp-with-keyword org-deadline-string)
13294 (message "Item no longer has a deadline."))
13295 ((equal arg '(16))
13296 (save-excursion
13297 (org-back-to-heading t)
13298 (if (re-search-forward
13299 org-deadline-time-regexp
13300 (save-excursion (outline-next-heading) (point)) t)
13301 (let* ((rpl0 (match-string 1))
13302 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13303 (replace-match
13304 (concat org-deadline-string
13305 " <" rpl
13306 (format " -%dd"
13307 (abs
13308 (- (time-to-days
13309 (save-match-data
13310 (org-read-date nil t nil "Warn starting from" old-date-time)))
13311 (time-to-days old-date-time))))
13312 ">") t t))
13313 (user-error "No deadline information to update"))))
13315 (org-add-planning-info 'deadline time 'closed)
13316 (when (and old-date
13317 org-log-redeadline
13318 (not (equal old-date org-last-inserted-timestamp)))
13319 (org-add-log-setup
13320 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13321 (when repeater
13322 (save-excursion
13323 (org-back-to-heading t)
13324 (when (re-search-forward (concat org-deadline-string " "
13325 org-last-inserted-timestamp)
13326 (save-excursion
13327 (outline-next-heading) (point)) t)
13328 (goto-char (1- (match-end 0)))
13329 (insert " " repeater)
13330 (setq org-last-inserted-timestamp
13331 (concat (substring org-last-inserted-timestamp 0 -1)
13332 " " repeater
13333 (substring org-last-inserted-timestamp -1))))))
13334 (message "Deadline on %s" org-last-inserted-timestamp))))))
13336 (defun org-schedule (arg &optional time)
13337 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13338 With one universal prefix argument, remove any scheduling date from the item.
13339 With two universal prefix arguments, prompt for a delay cookie.
13340 With argument TIME, scheduled at the corresponding date. TIME can
13341 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13342 (interactive "P")
13343 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13344 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13345 'region-start-level 'region))
13346 org-loop-over-headlines-in-active-region)
13347 (org-map-entries
13348 `(org-schedule ',arg ,time)
13349 org-loop-over-headlines-in-active-region
13350 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13351 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13352 (old-date-time (when old-date (org-time-string-to-time old-date)))
13353 (repeater (and old-date
13354 (string-match
13355 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13356 old-date)
13357 (match-string 1 old-date))))
13358 (cond
13359 ((equal arg '(4))
13360 (progn
13361 (when (and old-date org-log-reschedule)
13362 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13363 (org-remove-timestamp-with-keyword org-scheduled-string)
13364 (message "Item is no longer scheduled.")))
13365 ((equal arg '(16))
13366 (save-excursion
13367 (org-back-to-heading t)
13368 (if (re-search-forward
13369 org-scheduled-time-regexp
13370 (save-excursion (outline-next-heading) (point)) t)
13371 (let* ((rpl0 (match-string 1))
13372 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13373 (replace-match
13374 (concat org-scheduled-string
13375 " <" rpl
13376 (format " -%dd"
13377 (abs
13378 (- (time-to-days
13379 (save-match-data
13380 (org-read-date nil t nil "Delay until" old-date-time)))
13381 (time-to-days old-date-time))))
13382 ">") t t))
13383 (user-error "No scheduled information to update"))))
13385 (org-add-planning-info 'scheduled time 'closed)
13386 (when (and old-date
13387 org-log-reschedule
13388 (not (equal old-date org-last-inserted-timestamp)))
13389 (org-add-log-setup
13390 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13391 (when repeater
13392 (save-excursion
13393 (org-back-to-heading t)
13394 (when (re-search-forward (concat org-scheduled-string " "
13395 org-last-inserted-timestamp)
13396 (save-excursion
13397 (outline-next-heading) (point)) t)
13398 (goto-char (1- (match-end 0)))
13399 (insert " " repeater)
13400 (setq org-last-inserted-timestamp
13401 (concat (substring org-last-inserted-timestamp 0 -1)
13402 " " repeater
13403 (substring org-last-inserted-timestamp -1))))))
13404 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13406 (defun org-get-scheduled-time (pom &optional inherit)
13407 "Get the scheduled time as a time tuple, of a format suitable
13408 for calling org-schedule with, or if there is no scheduling,
13409 returns nil."
13410 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13411 (when time
13412 (apply 'encode-time (org-parse-time-string time)))))
13414 (defun org-get-deadline-time (pom &optional inherit)
13415 "Get the deadline as a time tuple, of a format suitable for
13416 calling org-deadline with, or if there is no scheduling, returns
13417 nil."
13418 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13419 (when time
13420 (apply 'encode-time (org-parse-time-string time)))))
13422 (defun org-remove-timestamp-with-keyword (keyword)
13423 "Remove all time stamps with KEYWORD in the current entry."
13424 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13425 beg)
13426 (save-excursion
13427 (org-back-to-heading t)
13428 (setq beg (point))
13429 (outline-next-heading)
13430 (while (re-search-backward re beg t)
13431 (replace-match "")
13432 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13433 (equal (char-before) ?\ ))
13434 (backward-delete-char 1)
13435 (when (string-match "^[ \t]*$" (buffer-substring
13436 (point-at-bol) (point-at-eol)))
13437 (delete-region (point-at-bol)
13438 (min (point-max) (1+ (point-at-eol))))))))))
13440 (defvar org-time-was-given) ; dynamically scoped parameter
13441 (defvar org-end-time-was-given) ; dynamically scoped parameter
13443 (defun org-at-planning-p ()
13444 "Non-nil when point is on a planning info line."
13445 ;; This is as accurate and faster than `org-element-at-point' since
13446 ;; planning info location is fixed in the section.
13447 (org-with-wide-buffer
13448 (beginning-of-line)
13449 (and (org-looking-at-p org-planning-line-re)
13450 (eq (point)
13451 (ignore-errors
13452 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13453 (org-back-to-heading t)
13454 (org-with-limited-levels (org-back-to-heading t)))
13455 (line-beginning-position 2))))))
13457 (defun org-add-planning-info (what &optional time &rest remove)
13458 "Insert new timestamp with keyword in the planning line.
13459 WHAT indicates what kind of time stamp to add. It is a symbol
13460 among `closed', `deadline', `scheduled' and nil. TIME indicates
13461 the time to use. If none is given, the user is prompted for
13462 a date. REMOVE indicates what kind of entries to remove. An old
13463 WHAT entry will also be removed."
13464 (let (org-time-was-given org-end-time-was-given default-time default-input)
13465 (catch 'exit
13466 (when (and (memq what '(scheduled deadline))
13467 (or (not time)
13468 (and (stringp time)
13469 (string-match "^[-+]+[0-9]" time))))
13470 ;; Try to get a default date/time from existing timestamp
13471 (save-excursion
13472 (org-back-to-heading t)
13473 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13474 (when (re-search-forward (if (eq what 'scheduled)
13475 org-scheduled-time-regexp
13476 org-deadline-time-regexp)
13477 end t)
13478 (setq ts (match-string 1)
13479 default-time (apply 'encode-time (org-parse-time-string ts))
13480 default-input (and ts (org-get-compact-tod ts)))))))
13481 (when what
13482 (setq time
13483 (if (stringp time)
13484 ;; This is a string (relative or absolute), set
13485 ;; proper date.
13486 (apply #'encode-time
13487 (org-read-date-analyze
13488 time default-time (decode-time default-time)))
13489 ;; If necessary, get the time from the user
13490 (or time (org-read-date nil 'to-time nil nil
13491 default-time default-input)))))
13493 (org-with-wide-buffer
13494 (org-back-to-heading t)
13495 (forward-line)
13496 (unless (bolp) (insert "\n"))
13497 (cond ((org-looking-at-p org-planning-line-re)
13498 ;; Move to current indentation.
13499 (skip-chars-forward " \t")
13500 ;; Check if we have to remove something.
13501 (dolist (type (if what (cons what remove) remove))
13502 (save-excursion
13503 (when (re-search-forward
13504 (cl-case type
13505 (closed org-closed-time-regexp)
13506 (deadline org-deadline-time-regexp)
13507 (scheduled org-scheduled-time-regexp)
13508 (otherwise
13509 (error "Invalid planning type: %s" type)))
13510 (line-end-position) t)
13511 ;; Delete until next keyword or end of line.
13512 (delete-region
13513 (match-beginning 0)
13514 (if (re-search-forward org-keyword-time-not-clock-regexp
13515 (line-end-position)
13517 (match-beginning 0)
13518 (line-end-position))))))
13519 ;; If there is nothing more to add and no more keyword
13520 ;; is left, remove the line completely.
13521 (if (and (org-looking-at-p "[ \t]*$") (not what))
13522 (delete-region (line-beginning-position)
13523 (line-beginning-position 2))
13524 ;; If we removed last keyword, do not leave trailing
13525 ;; white space at the end of line.
13526 (let ((p (point)))
13527 (save-excursion
13528 (end-of-line)
13529 (unless (= (skip-chars-backward " \t" p) 0)
13530 (delete-region (point) (line-end-position)))))))
13531 ((not what) (throw 'exit nil)) ; Nothing to do.
13532 (t (insert-before-markers "\n")
13533 (backward-char 1)
13534 (when org-adapt-indentation
13535 (org-indent-to-column (1+ (org-outline-level))))))
13536 (when what
13537 ;; Insert planning keyword.
13538 (insert (cl-case what
13539 (closed org-closed-string)
13540 (deadline org-deadline-string)
13541 (scheduled org-scheduled-string)
13542 (otherwise (error "Invalid planning type: %s" what)))
13543 " ")
13544 ;; Insert associated timestamp.
13545 (let ((ts (org-insert-time-stamp
13546 time
13547 (or org-time-was-given
13548 (and (eq what 'closed) org-log-done-with-time))
13549 (eq what 'closed)
13550 nil nil (list org-end-time-was-given))))
13551 (unless (eolp) (insert " "))
13552 ts))))))
13554 (defvar org-log-note-marker (make-marker)
13555 "Marker pointing at the entry where the note is to be inserted.")
13556 (defvar org-log-note-purpose nil)
13557 (defvar org-log-note-state nil)
13558 (defvar org-log-note-previous-state nil)
13559 (defvar org-log-note-extra nil)
13560 (defvar org-log-note-window-configuration nil)
13561 (defvar org-log-note-return-to (make-marker))
13562 (defvar org-log-note-effective-time nil
13563 "Remembered current time so that dynamically scoped
13564 `org-extend-today-until' affects timestamps in state change log")
13566 (defvar org-log-post-message nil
13567 "Message to be displayed after a log note has been stored.
13568 The auto-repeater uses this.")
13570 (defun org-add-note ()
13571 "Add a note to the current entry.
13572 This is done in the same way as adding a state change note."
13573 (interactive)
13574 (org-add-log-setup 'note))
13576 (defun org-log-beginning (&optional create)
13577 "Return expected start of log notes in current entry.
13578 When optional argument CREATE is non-nil, the function creates
13579 a drawer to store notes, if necessary. Returned position ignores
13580 narrowing."
13581 (org-with-wide-buffer
13582 (let ((drawer (org-log-into-drawer)))
13583 (cond
13584 (drawer
13585 (org-end-of-meta-data)
13586 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13587 (end (if (org-at-heading-p) (point)
13588 (save-excursion (outline-next-heading) (point))))
13589 (case-fold-search t))
13590 (catch 'exit
13591 ;; Try to find existing drawer.
13592 (while (re-search-forward regexp end t)
13593 (let ((element (org-element-at-point)))
13594 (when (eq (org-element-type element) 'drawer)
13595 (let ((cend (org-element-property :contents-end element)))
13596 (when (and (not org-log-states-order-reversed) cend)
13597 (goto-char cend)))
13598 (throw 'exit nil))))
13599 ;; No drawer found. Create one, if permitted.
13600 (when create
13601 (unless (bolp) (insert "\n"))
13602 (let ((beg (point)))
13603 (insert ":" drawer ":\n:END:\n")
13604 (org-indent-region beg (point)))
13605 (end-of-line -1)))))
13607 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13608 (skip-chars-forward " \t\n")
13609 (beginning-of-line)
13610 (unless org-log-states-order-reversed
13611 (org-skip-over-state-notes)
13612 (skip-chars-backward " \t\n")
13613 (forward-line)))))
13614 (if (bolp) (point) (line-beginning-position 2))))
13616 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13617 "Set up the post command hook to take a note.
13618 If this is about to TODO state change, the new state is expected in STATE.
13619 HOW is an indicator what kind of note should be created.
13620 EXTRA is additional text that will be inserted into the notes buffer."
13621 (move-marker org-log-note-marker (point))
13622 (setq org-log-note-purpose purpose
13623 org-log-note-state state
13624 org-log-note-previous-state prev-state
13625 org-log-note-how how
13626 org-log-note-extra extra
13627 org-log-note-effective-time (org-current-effective-time))
13628 (add-hook 'post-command-hook 'org-add-log-note 'append))
13630 (defun org-skip-over-state-notes ()
13631 "Skip past the list of State notes in an entry."
13632 (when (ignore-errors (goto-char (org-in-item-p)))
13633 (let* ((struct (org-list-struct))
13634 (prevs (org-list-prevs-alist struct))
13635 (regexp
13636 (concat "[ \t]*- +"
13637 (replace-regexp-in-string
13638 " +" " +"
13639 (org-replace-escapes
13640 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13641 `(("%d" . ,org-ts-regexp-inactive)
13642 ("%D" . ,org-ts-regexp)
13643 ("%s" . "\"\\S-+\"")
13644 ("%S" . "\"\\S-+\"")
13645 ("%t" . ,org-ts-regexp-inactive)
13646 ("%T" . ,org-ts-regexp)
13647 ("%u" . ".*?")
13648 ("%U" . ".*?")))))))
13649 (while (org-looking-at-p regexp)
13650 (goto-char (or (org-list-get-next-item (point) struct prevs)
13651 (org-list-get-item-end (point) struct)))))))
13653 (defun org-add-log-note (&optional _purpose)
13654 "Pop up a window for taking a note, and add this note later."
13655 (remove-hook 'post-command-hook 'org-add-log-note)
13656 (setq org-log-note-window-configuration (current-window-configuration))
13657 (delete-other-windows)
13658 (move-marker org-log-note-return-to (point))
13659 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13660 (goto-char org-log-note-marker)
13661 (org-switch-to-buffer-other-window "*Org Note*")
13662 (erase-buffer)
13663 (if (memq org-log-note-how '(time state))
13664 (let (current-prefix-arg) (org-store-log-note))
13665 (let ((org-inhibit-startup t)) (org-mode))
13666 (insert (format "# Insert note for %s.
13667 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13668 (cond
13669 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13670 ((eq org-log-note-purpose 'done) "closed todo item")
13671 ((eq org-log-note-purpose 'state)
13672 (format "state change from \"%s\" to \"%s\""
13673 (or org-log-note-previous-state "")
13674 (or org-log-note-state "")))
13675 ((eq org-log-note-purpose 'reschedule)
13676 "rescheduling")
13677 ((eq org-log-note-purpose 'delschedule)
13678 "no longer scheduled")
13679 ((eq org-log-note-purpose 'redeadline)
13680 "changing deadline")
13681 ((eq org-log-note-purpose 'deldeadline)
13682 "removing deadline")
13683 ((eq org-log-note-purpose 'refile)
13684 "refiling")
13685 ((eq org-log-note-purpose 'note)
13686 "this entry")
13687 (t (error "This should not happen")))))
13688 (when org-log-note-extra (insert org-log-note-extra))
13689 (setq-local org-finish-function 'org-store-log-note)
13690 (run-hooks 'org-log-buffer-setup-hook)))
13692 (defvar org-note-abort nil) ; dynamically scoped
13693 (defun org-store-log-note ()
13694 "Finish taking a log note, and insert it to where it belongs."
13695 (let ((txt (prog1 (buffer-string)
13696 (kill-buffer)))
13697 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13698 lines)
13699 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13700 (setq txt (replace-match "" t t txt)))
13701 (when (string-match "\\s-+\\'" txt)
13702 (setq txt (replace-match "" t t txt)))
13703 (setq lines (org-split-string txt "\n"))
13704 (when (org-string-nw-p note)
13705 (setq note
13706 (org-replace-escapes
13707 note
13708 (list (cons "%u" (user-login-name))
13709 (cons "%U" user-full-name)
13710 (cons "%t" (format-time-string
13711 (org-time-stamp-format 'long 'inactive)
13712 org-log-note-effective-time))
13713 (cons "%T" (format-time-string
13714 (org-time-stamp-format 'long nil)
13715 org-log-note-effective-time))
13716 (cons "%d" (format-time-string
13717 (org-time-stamp-format nil 'inactive)
13718 org-log-note-effective-time))
13719 (cons "%D" (format-time-string
13720 (org-time-stamp-format nil nil)
13721 org-log-note-effective-time))
13722 (cons "%s" (cond
13723 ((not org-log-note-state) "")
13724 ((org-string-match-p org-ts-regexp
13725 org-log-note-state)
13726 (format "\"[%s]\""
13727 (substring org-log-note-state 1 -1)))
13728 (t (format "\"%s\"" org-log-note-state))))
13729 (cons "%S"
13730 (cond
13731 ((not org-log-note-previous-state) "")
13732 ((org-string-match-p org-ts-regexp
13733 org-log-note-previous-state)
13734 (format "\"[%s]\""
13735 (substring
13736 org-log-note-previous-state 1 -1)))
13737 (t (format "\"%s\""
13738 org-log-note-previous-state)))))))
13739 (when lines (setq note (concat note " \\\\")))
13740 (push note lines))
13741 (when (and lines (not (or current-prefix-arg org-note-abort)))
13742 (with-current-buffer (marker-buffer org-log-note-marker)
13743 (org-with-wide-buffer
13744 ;; Find location for the new note.
13745 (goto-char org-log-note-marker)
13746 (set-marker org-log-note-marker nil)
13747 (goto-char (org-log-beginning t))
13748 ;; Make sure point is at the beginning of an empty line.
13749 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13750 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13751 ;; In an existing list, add a new item at the top level.
13752 ;; Otherwise, indent line like a regular one.
13753 (let ((itemp (org-in-item-p)))
13754 (if itemp
13755 (org-indent-line-to
13756 (let ((struct (save-excursion
13757 (goto-char itemp) (org-list-struct))))
13758 (org-list-get-ind (org-list-get-top-point struct) struct)))
13759 (org-indent-line)))
13760 (insert (org-list-bullet-string "-") (pop lines))
13761 (let ((ind (org-list-item-body-column (line-beginning-position))))
13762 (dolist (line lines)
13763 (insert "\n")
13764 (org-indent-line-to ind)
13765 (insert line)))
13766 (message "Note stored")
13767 (org-back-to-heading t)
13768 (org-cycle-hide-drawers 'children))
13769 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13770 ;; from within `org-add-log-note' because `buffer-undo-list'
13771 ;; is then modified outside of `org-with-remote-undo'.
13772 (when (eq this-command 'org-agenda-todo)
13773 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13774 ;; Don't add undo information when called from `org-agenda-todo'.
13775 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13776 (set-window-configuration org-log-note-window-configuration)
13777 (with-current-buffer (marker-buffer org-log-note-return-to)
13778 (goto-char org-log-note-return-to))
13779 (move-marker org-log-note-return-to nil)
13780 (when org-log-post-message (message "%s" org-log-post-message))))
13782 (defun org-remove-empty-drawer-at (pos)
13783 "Remove an empty drawer at position POS.
13784 POS may also be a marker."
13785 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13786 (org-with-wide-buffer
13787 (goto-char pos)
13788 (let ((drawer (org-element-at-point)))
13789 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13790 (not (org-element-property :contents-begin drawer)))
13791 (delete-region (org-element-property :begin drawer)
13792 (progn (goto-char (org-element-property :end drawer))
13793 (skip-chars-backward " \r\t\n")
13794 (forward-line)
13795 (point))))))))
13797 (defvar org-ts-type nil)
13798 (defun org-sparse-tree (&optional arg type)
13799 "Create a sparse tree, prompt for the details.
13800 This command can create sparse trees. You first need to select the type
13801 of match used to create the tree:
13803 t Show all TODO entries.
13804 T Show entries with a specific TODO keyword.
13805 m Show entries selected by a tags/property match.
13806 p Enter a property name and its value (both with completion on existing
13807 names/values) and show entries with that property.
13808 r Show entries matching a regular expression (`/' can be used as well).
13809 b Show deadlines and scheduled items before a date.
13810 a Show deadlines and scheduled items after a date.
13811 d Show deadlines due within `org-deadline-warning-days'.
13812 D Show deadlines and scheduled items between a date range."
13813 (interactive "P")
13814 (setq type (or type org-sparse-tree-default-date-type))
13815 (setq org-ts-type type)
13816 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13817 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13818 \[c]ycle through date types: %s"
13819 (cl-case type
13820 (all "all timestamps")
13821 (scheduled "only scheduled")
13822 (deadline "only deadline")
13823 (active "only active timestamps")
13824 (inactive "only inactive timestamps")
13825 (closed "with a closed time-stamp")
13826 (otherwise "scheduled/deadline")))
13827 (let ((answer (read-char-exclusive)))
13828 (cl-case answer
13830 (org-sparse-tree
13832 (cadr
13833 (memq type '(nil all scheduled deadline active inactive closed)))))
13834 (?d (call-interactively 'org-check-deadlines))
13835 (?b (call-interactively 'org-check-before-date))
13836 (?a (call-interactively 'org-check-after-date))
13837 (?D (call-interactively 'org-check-dates-range))
13838 (?t (call-interactively 'org-show-todo-tree))
13839 (?T (org-show-todo-tree '(4)))
13840 (?m (call-interactively 'org-match-sparse-tree))
13841 ((?p ?P)
13842 (let* ((kwd (completing-read
13843 "Property: " (mapcar #'list (org-buffer-property-keys))))
13844 (value (completing-read
13845 "Value: " (mapcar #'list (org-property-values kwd)))))
13846 (unless (string-match "\\`{.*}\\'" value)
13847 (setq value (concat "\"" value "\"")))
13848 (org-match-sparse-tree arg (concat kwd "=" value))))
13849 ((?r ?R ?/) (call-interactively 'org-occur))
13850 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13852 (defvar-local org-occur-highlights nil
13853 "List of overlays used for occur matches.")
13854 (defvar-local org-occur-parameters nil
13855 "Parameters of the active org-occur calls.
13856 This is a list, each call to org-occur pushes as cons cell,
13857 containing the regular expression and the callback, onto the list.
13858 The list can contain several entries if `org-occur' has been called
13859 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13860 will only contain one set of parameters. When the highlights are
13861 removed (for example with `C-c C-c', or with the next edit (depending
13862 on `org-remove-highlights-with-change'), this variable is emptied
13863 as well.")
13865 (defun org-occur (regexp &optional keep-previous callback)
13866 "Make a compact tree which shows all matches of REGEXP.
13867 The tree will show the lines where the regexp matches, and all higher
13868 headlines above the match. It will also show the heading after the match,
13869 to make sure editing the matching entry is easy.
13870 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13871 call to `org-occur' will be kept, to allow stacking of calls to this
13872 command.
13873 If CALLBACK is non-nil, it is a function which is called to confirm
13874 that the match should indeed be shown."
13875 (interactive "sRegexp: \nP")
13876 (when (equal regexp "")
13877 (user-error "Regexp cannot be empty"))
13878 (unless keep-previous
13879 (org-remove-occur-highlights nil nil t))
13880 (push (cons regexp callback) org-occur-parameters)
13881 (let ((cnt 0))
13882 (save-excursion
13883 (goto-char (point-min))
13884 (when (or (not keep-previous) ; do not want to keep
13885 (not org-occur-highlights)) ; no previous matches
13886 ;; hide everything
13887 (org-overview))
13888 (while (re-search-forward regexp nil t)
13889 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13890 (when (or (not callback)
13891 (save-match-data (funcall callback)))
13892 (setq cnt (1+ cnt))
13893 (when org-highlight-sparse-tree-matches
13894 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13895 (org-show-context 'occur-tree))))
13896 (when org-remove-highlights-with-change
13897 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13898 nil 'local))
13899 (unless org-sparse-tree-open-archived-trees
13900 (org-hide-archived-subtrees (point-min) (point-max)))
13901 (run-hooks 'org-occur-hook)
13902 (when (org-called-interactively-p 'interactive)
13903 (message "%d match(es) for regexp %s" cnt regexp))
13904 cnt))
13906 (defun org-occur-next-match (&optional n _reset)
13907 "Function for `next-error-function' to find sparse tree matches.
13908 N is the number of matches to move, when negative move backwards.
13909 This function always goes back to the starting point when no
13910 match is found."
13911 (let* ((limit (if (< n 0) (point-min) (point-max)))
13912 (search-func (if (< n 0)
13913 'previous-single-char-property-change
13914 'next-single-char-property-change))
13915 (n (abs n))
13916 (pos (point))
13918 (catch 'exit
13919 (while (setq p1 (funcall search-func (point) 'org-type))
13920 (when (equal p1 limit)
13921 (goto-char pos)
13922 (user-error "No more matches"))
13923 (when (equal (get-char-property p1 'org-type) 'org-occur)
13924 (setq n (1- n))
13925 (when (= n 0)
13926 (goto-char p1)
13927 (throw 'exit (point))))
13928 (goto-char p1))
13929 (goto-char p1)
13930 (user-error "No more matches"))))
13932 (defun org-show-context (&optional key)
13933 "Make sure point and context are visible.
13934 Optional argument KEY, when non-nil, is a symbol. See
13935 `org-show-context-detail' for allowed values and how much is to
13936 be shown."
13937 (org-show-set-visibility
13938 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13939 ((cdr (assq key org-show-context-detail)))
13940 (t (cdr (assq 'default org-show-context-detail))))))
13942 (defun org-show-set-visibility (detail)
13943 "Set visibility around point according to DETAIL.
13944 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13945 `tree', `canonical' or t. See `org-show-context-detail' for more
13946 information."
13947 (unless (org-before-first-heading-p)
13948 ;; Show current heading and possibly its entry, following headline
13949 ;; or all children.
13950 (if (and (org-at-heading-p) (not (eq detail 'local)))
13951 (org-flag-heading nil)
13952 (org-show-entry)
13953 (org-with-limited-levels
13954 (cl-case detail
13955 ((tree canonical t) (org-show-children))
13956 ((nil minimal ancestors))
13957 (t (save-excursion
13958 (outline-next-heading)
13959 (org-flag-heading nil))))))
13960 ;; Show all siblings.
13961 (when (eq detail 'lineage) (org-show-siblings))
13962 ;; Show ancestors, possibly with their children.
13963 (when (memq detail '(ancestors lineage tree canonical t))
13964 (save-excursion
13965 (while (org-up-heading-safe)
13966 (org-flag-heading nil)
13967 (when (memq detail '(canonical t)) (org-show-entry))
13968 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13970 (defvar org-reveal-start-hook nil
13971 "Hook run before revealing a location.")
13973 (defun org-reveal (&optional siblings)
13974 "Show current entry, hierarchy above it, and the following headline.
13976 This can be used to show a consistent set of context around
13977 locations exposed with `org-show-context'.
13979 With optional argument SIBLINGS, on each level of the hierarchy all
13980 siblings are shown. This repairs the tree structure to what it would
13981 look like when opened with hierarchical calls to `org-cycle'.
13983 With double optional argument \\[universal-argument] \\[universal-argument], \
13984 go to the parent and show the
13985 entire tree."
13986 (interactive "P")
13987 (run-hooks 'org-reveal-start-hook)
13988 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13989 ((equal siblings '(16))
13990 (save-excursion
13991 (when (org-up-heading-safe)
13992 (org-show-subtree)
13993 (run-hook-with-args 'org-cycle-hook 'subtree))))
13994 (t (org-show-set-visibility 'lineage))))
13996 (defun org-highlight-new-match (beg end)
13997 "Highlight from BEG to END and mark the highlight is an occur headline."
13998 (let ((ov (make-overlay beg end)))
13999 (overlay-put ov 'face 'secondary-selection)
14000 (overlay-put ov 'org-type 'org-occur)
14001 (push ov org-occur-highlights)))
14003 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14004 "Remove the occur highlights from the buffer.
14005 BEG and END are ignored. If NOREMOVE is nil, remove this function
14006 from the `before-change-functions' in the current buffer."
14007 (interactive)
14008 (unless org-inhibit-highlight-removal
14009 (mapc #'delete-overlay org-occur-highlights)
14010 (setq org-occur-highlights nil)
14011 (setq org-occur-parameters nil)
14012 (unless noremove
14013 (remove-hook 'before-change-functions
14014 'org-remove-occur-highlights 'local))))
14016 ;;;; Priorities
14018 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14019 "Regular expression matching the priority indicator.")
14021 (defvar org-remove-priority-next-time nil)
14023 (defun org-priority-up ()
14024 "Increase the priority of the current item."
14025 (interactive)
14026 (org-priority 'up))
14028 (defun org-priority-down ()
14029 "Decrease the priority of the current item."
14030 (interactive)
14031 (org-priority 'down))
14033 (defun org-priority (&optional action _show)
14034 "Change the priority of an item.
14035 ACTION can be `set', `up', `down', or a character."
14036 (interactive "P")
14037 (if (equal action '(4))
14038 (org-show-priority)
14039 (unless org-enable-priority-commands
14040 (user-error "Priority commands are disabled"))
14041 (setq action (or action 'set))
14042 (let (current new news have remove)
14043 (save-excursion
14044 (org-back-to-heading t)
14045 (when (looking-at org-priority-regexp)
14046 (setq current (string-to-char (match-string 2))
14047 have t))
14048 (cond
14049 ((eq action 'remove)
14050 (setq remove t new ?\ ))
14051 ((or (eq action 'set)
14052 (if (featurep 'xemacs) (characterp action) (integerp action)))
14053 (if (not (eq action 'set))
14054 (setq new action)
14055 (message "Priority %c-%c, SPC to remove: "
14056 org-highest-priority org-lowest-priority)
14057 (save-match-data
14058 (setq new (read-char-exclusive))))
14059 (when (and (= (upcase org-highest-priority) org-highest-priority)
14060 (= (upcase org-lowest-priority) org-lowest-priority))
14061 (setq new (upcase new)))
14062 (cond ((equal new ?\ ) (setq remove t))
14063 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14064 (user-error "Priority must be between `%c' and `%c'"
14065 org-highest-priority org-lowest-priority))))
14066 ((eq action 'up)
14067 (setq new (if have
14068 (1- current) ; normal cycling
14069 ;; last priority was empty
14070 (if (eq last-command this-command)
14071 org-lowest-priority ; wrap around empty to lowest
14072 ;; default
14073 (if org-priority-start-cycle-with-default
14074 org-default-priority
14075 (1- org-default-priority))))))
14076 ((eq action 'down)
14077 (setq new (if have
14078 (1+ current) ; normal cycling
14079 ;; last priority was empty
14080 (if (eq last-command this-command)
14081 org-highest-priority ; wrap around empty to highest
14082 ;; default
14083 (if org-priority-start-cycle-with-default
14084 org-default-priority
14085 (1+ org-default-priority))))))
14086 (t (user-error "Invalid action")))
14087 (when (or (< (upcase new) org-highest-priority)
14088 (> (upcase new) org-lowest-priority))
14089 (if (and (memq action '(up down))
14090 (not have) (not (eq last-command this-command)))
14091 ;; `new' is from default priority
14092 (error
14093 "The default can not be set, see `org-default-priority' why")
14094 ;; normal cycling: `new' is beyond highest/lowest priority
14095 ;; and is wrapped around to the empty priority
14096 (setq remove t)))
14097 (setq news (format "%c" new))
14098 (if have
14099 (if remove
14100 (replace-match "" t t nil 1)
14101 (replace-match news t t nil 2))
14102 (if remove
14103 (user-error "No priority cookie found in line")
14104 (let ((case-fold-search nil))
14105 (looking-at org-todo-line-regexp))
14106 (if (match-end 2)
14107 (progn
14108 (goto-char (match-end 2))
14109 (insert " [#" news "]"))
14110 (goto-char (match-beginning 3))
14111 (insert "[#" news "] "))))
14112 (org-set-tags nil 'align))
14113 (if remove
14114 (message "Priority removed")
14115 (message "Priority of current item set to %s" news)))))
14117 (defun org-show-priority ()
14118 "Show the priority of the current item.
14119 This priority is composed of the main priority given with the [#A] cookies,
14120 and by additional input from the age of a schedules or deadline entry."
14121 (interactive)
14122 (let ((pri (if (eq major-mode 'org-agenda-mode)
14123 (org-get-at-bol 'priority)
14124 (save-excursion
14125 (save-match-data
14126 (beginning-of-line)
14127 (and (looking-at org-heading-regexp)
14128 (org-get-priority (match-string 0))))))))
14129 (message "Priority is %d" (if pri pri -1000))))
14131 (defun org-get-priority (s)
14132 "Find priority cookie and return priority."
14133 (save-match-data
14134 (if (functionp org-get-priority-function)
14135 (funcall org-get-priority-function)
14136 (if (not (string-match org-priority-regexp s))
14137 (* 1000 (- org-lowest-priority org-default-priority))
14138 (* 1000 (- org-lowest-priority
14139 (string-to-char (match-string 2 s))))))))
14141 ;;;; Tags
14143 (defvar org-agenda-archives-mode)
14144 (defvar org-map-continue-from nil
14145 "Position from where mapping should continue.
14146 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14148 (defvar org-scanner-tags nil
14149 "The current tag list while the tags scanner is running.")
14151 (defvar org-trust-scanner-tags nil
14152 "Should `org-get-tags-at' use the tags for the scanner.
14153 This is for internal dynamical scoping only.
14154 When this is non-nil, the function `org-get-tags-at' will return the value
14155 of `org-scanner-tags' instead of building the list by itself. This
14156 can lead to large speed-ups when the tags scanner is used in a file with
14157 many entries, and when the list of tags is retrieved, for example to
14158 obtain a list of properties. Building the tags list for each entry in such
14159 a file becomes an N^2 operation - but with this variable set, it scales
14160 as N.")
14162 (defvar org--matcher-tags-todo-only nil)
14164 (defun org-scan-tags (action matcher todo-only &optional start-level)
14165 "Scan headline tags with inheritance and produce output ACTION.
14167 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14168 or `agenda' to produce an entry list for an agenda view. It can also be
14169 a Lisp form or a function that should be called at each matched headline, in
14170 this case the return value is a list of all return values from these calls.
14172 MATCHER is a function accepting three arguments, returning
14173 a non-nil value whenever a given set of tags qualifies a headline
14174 for inclusion. See `org-make-tags-matcher' for more information.
14175 As a special case, it can also be set to t (respectively nil) in
14176 order to match all (respectively none) headline.
14178 When TODO-ONLY is non-nil, only lines with a not-done TODO
14179 keyword are included in the output.
14181 START-LEVEL can be a string with asterisks, reducing the scope to
14182 headlines matching this string."
14183 (require 'org-agenda)
14184 (let* ((re (concat "^"
14185 (if start-level
14186 ;; Get the correct level to match
14187 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14188 org-outline-regexp)
14189 " *\\(\\<\\("
14190 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14191 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14192 (props (list 'face 'default
14193 'done-face 'org-agenda-done
14194 'undone-face 'default
14195 'mouse-face 'highlight
14196 'org-not-done-regexp org-not-done-regexp
14197 'org-todo-regexp org-todo-regexp
14198 'org-complex-heading-regexp org-complex-heading-regexp
14199 'help-echo
14200 (format "mouse-2 or RET jump to org file %s"
14201 (abbreviate-file-name
14202 (or (buffer-file-name (buffer-base-buffer))
14203 (buffer-name (buffer-base-buffer)))))))
14204 (org-map-continue-from nil)
14205 lspos tags tags-list
14206 (tags-alist (list (cons 0 org-file-tags)))
14207 (llast 0) rtn rtn1 level category i txt
14208 todo marker entry priority
14209 ts-date ts-date-type ts-date-pair)
14210 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14211 (setq action (list 'lambda nil action)))
14212 (save-excursion
14213 (goto-char (point-min))
14214 (when (eq action 'sparse-tree)
14215 (org-overview)
14216 (org-remove-occur-highlights))
14217 (while (let (case-fold-search)
14218 (re-search-forward re nil t))
14219 (setq org-map-continue-from nil)
14220 (catch :skip
14221 (setq todo
14222 ;; TODO: is the 1-2 difference a bug?
14223 (when (match-end 1) (org-match-string-no-properties 2))
14224 tags (when (match-end 4) (org-match-string-no-properties 4)))
14225 (goto-char (setq lspos (match-beginning 0)))
14226 (setq level (org-reduced-level (org-outline-level))
14227 category (org-get-category))
14228 (when (eq action 'agenda)
14229 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14230 ts-date (car ts-date-pair)
14231 ts-date-type (cdr ts-date-pair)))
14232 (setq i llast llast level)
14233 ;; remove tag lists from same and sublevels
14234 (while (>= i level)
14235 (when (setq entry (assoc i tags-alist))
14236 (setq tags-alist (delete entry tags-alist)))
14237 (setq i (1- i)))
14238 ;; add the next tags
14239 (when tags
14240 (setq tags (org-split-string tags ":")
14241 tags-alist
14242 (cons (cons level tags) tags-alist)))
14243 ;; compile tags for current headline
14244 (setq tags-list
14245 (if org-use-tag-inheritance
14246 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14247 tags)
14248 org-scanner-tags tags-list)
14249 (when org-use-tag-inheritance
14250 (setcdr (car tags-alist)
14251 (mapcar (lambda (x)
14252 (setq x (copy-sequence x))
14253 (org-add-prop-inherited x))
14254 (cdar tags-alist))))
14255 (when (and tags org-use-tag-inheritance
14256 (or (not (eq t org-use-tag-inheritance))
14257 org-tags-exclude-from-inheritance))
14258 ;; Selective inheritance, remove uninherited ones.
14259 (setcdr (car tags-alist)
14260 (org-remove-uninherited-tags (cdar tags-alist))))
14261 (when (and
14263 ;; eval matcher only when the todo condition is OK
14264 (and (or (not todo-only) (member todo org-not-done-keywords))
14265 (if (functionp matcher)
14266 (let ((case-fold-search t) (org-trust-scanner-tags t))
14267 (funcall matcher todo tags-list level))
14268 matcher))
14270 ;; Call the skipper, but return t if it does not
14271 ;; skip, so that the `and' form continues evaluating.
14272 (progn
14273 (unless (eq action 'sparse-tree) (org-agenda-skip))
14276 ;; Check if timestamps are deselecting this entry
14277 (or (not todo-only)
14278 (and (member todo org-not-done-keywords)
14279 (or (not org-agenda-tags-todo-honor-ignore-options)
14280 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14282 ;; select this headline
14283 (cond
14284 ((eq action 'sparse-tree)
14285 (and org-highlight-sparse-tree-matches
14286 (org-get-heading) (match-end 0)
14287 (org-highlight-new-match
14288 (match-beginning 1) (match-end 1)))
14289 (org-show-context 'tags-tree))
14290 ((eq action 'agenda)
14291 (setq txt (org-agenda-format-item
14293 (concat
14294 (if (eq org-tags-match-list-sublevels 'indented)
14295 (make-string (1- level) ?.) "")
14296 (org-get-heading))
14297 (make-string level ?\s)
14298 category
14299 tags-list)
14300 priority (org-get-priority txt))
14301 (goto-char lspos)
14302 (setq marker (org-agenda-new-marker))
14303 (org-add-props txt props
14304 'org-marker marker 'org-hd-marker marker 'org-category category
14305 'todo-state todo
14306 'ts-date ts-date
14307 'priority priority
14308 'type (concat "tagsmatch" ts-date-type))
14309 (push txt rtn))
14310 ((functionp action)
14311 (setq org-map-continue-from nil)
14312 (save-excursion
14313 (setq rtn1 (funcall action))
14314 (push rtn1 rtn)))
14315 (t (user-error "Invalid action")))
14317 ;; if we are to skip sublevels, jump to end of subtree
14318 (unless org-tags-match-list-sublevels
14319 (org-end-of-subtree t)
14320 (backward-char 1))))
14321 ;; Get the correct position from where to continue
14322 (if org-map-continue-from
14323 (goto-char org-map-continue-from)
14324 (and (= (point) lspos) (end-of-line 1)))))
14325 (when (and (eq action 'sparse-tree)
14326 (not org-sparse-tree-open-archived-trees))
14327 (org-hide-archived-subtrees (point-min) (point-max)))
14328 (nreverse rtn)))
14330 (defun org-remove-uninherited-tags (tags)
14331 "Remove all tags that are not inherited from the list TAGS."
14332 (cond
14333 ((eq org-use-tag-inheritance t)
14334 (if org-tags-exclude-from-inheritance
14335 (org-delete-all org-tags-exclude-from-inheritance tags)
14336 tags))
14337 ((not org-use-tag-inheritance) nil)
14338 ((stringp org-use-tag-inheritance)
14339 (delq nil (mapcar
14340 (lambda (x)
14341 (if (and (string-match org-use-tag-inheritance x)
14342 (not (member x org-tags-exclude-from-inheritance)))
14343 x nil))
14344 tags)))
14345 ((listp org-use-tag-inheritance)
14346 (delq nil (mapcar
14347 (lambda (x)
14348 (if (member x org-use-tag-inheritance) x nil))
14349 tags)))))
14351 (defun org-match-sparse-tree (&optional todo-only match)
14352 "Create a sparse tree according to tags string MATCH.
14353 MATCH can contain positive and negative selection of tags, like
14354 \"+WORK+URGENT-WITHBOSS\".
14355 If optional argument TODO-ONLY is non-nil, only select lines that are
14356 also TODO lines."
14357 (interactive "P")
14358 (org-agenda-prepare-buffers (list (current-buffer)))
14359 (let ((org--matcher-tags-todo-only todo-only))
14360 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14361 org--matcher-tags-todo-only)))
14363 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14365 (defvar org-cached-props nil)
14366 (defun org-cached-entry-get (pom property)
14367 (if (or (eq t org-use-property-inheritance)
14368 (and (stringp org-use-property-inheritance)
14369 (let ((case-fold-search t))
14370 (org-string-match-p org-use-property-inheritance property)))
14371 (and (listp org-use-property-inheritance)
14372 (member-ignore-case property org-use-property-inheritance)))
14373 ;; Caching is not possible, check it directly.
14374 (org-entry-get pom property 'inherit)
14375 ;; Get all properties, so we can do complicated checks easily.
14376 (cdr (assoc-string property
14377 (or org-cached-props
14378 (setq org-cached-props (org-entry-properties pom)))
14379 t))))
14381 (defun org-global-tags-completion-table (&optional files)
14382 "Return the list of all tags in all agenda buffer/files.
14383 Optional FILES argument is a list of files which can be used
14384 instead of the agenda files."
14385 (save-excursion
14386 (org-uniquify
14387 (delq nil
14388 (apply #'append
14389 (mapcar
14390 (lambda (file)
14391 (set-buffer (find-file-noselect file))
14392 (mapcar (lambda (x)
14393 (and (stringp (car-safe x))
14394 (list (car-safe x))))
14395 (or org-current-tag-alist (org-get-buffer-tags))))
14396 (if (car-safe files) files
14397 (org-agenda-files))))))))
14399 (defun org-make-tags-matcher (match)
14400 "Create the TAGS/TODO matcher form for the selection string MATCH.
14402 Returns a cons of the selection string MATCH and a function
14403 implementing the matcher.
14405 The matcher is to be called at an Org entry, with point on the
14406 headline, and returns non-nil if the entry matches the selection
14407 string MATCH. It must be called with three arguments: the TODO
14408 keyword at the entry (or nil if none), the list of all tags at
14409 the entry including inherited ones and the reduced level of the
14410 headline. Additionally, the category of the entry, if any, must
14411 be specified as the text property `org-category' on the headline.
14413 This function sets the variable `org--matcher-tags-todo-only' to
14414 a non-nil value if the matcher restricts matching to TODO
14415 entries, otherwise it is not touched.
14417 See also `org-scan-tags'."
14418 (unless match
14419 ;; Get a new match request, with completion against the global
14420 ;; tags table and the local tags in current buffer.
14421 (let ((org-last-tags-completion-table
14422 (org-uniquify
14423 (delq nil (append (org-get-buffer-tags)
14424 (org-global-tags-completion-table))))))
14425 (setq match
14426 (completing-read
14427 "Match: "
14428 'org-tags-completion-function nil nil nil 'org-tags-history))))
14430 (let ((match0 match)
14431 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14432 (start 0)
14433 tagsmatch todomatch tagsmatcher todomatcher)
14435 ;; Expand group tags.
14436 (setq match (org-tags-expand match))
14438 ;; Check if there is a TODO part of this match, which would be the
14439 ;; part after a "/". To make sure that this slash is not part of
14440 ;; a property value to be matched against, we also check that
14441 ;; there is no / after that slash. First, find the last slash.
14442 (let ((s 0))
14443 (while (string-match "/+" match s)
14444 (setq start (match-beginning 0))
14445 (setq s (match-end 0))))
14446 (if (and (string-match "/+" match start)
14447 (not (string-match-p "\"" match start)))
14448 ;; Match contains also a TODO-matching request.
14449 (progn
14450 (setq tagsmatch (substring match 0 (match-beginning 0)))
14451 (setq todomatch (substring match (match-end 0)))
14452 (when (string-match "\\`!" todomatch)
14453 (setq org--matcher-tags-todo-only t)
14454 (setq todomatch (substring todomatch 1)))
14455 (when (string-match "\\`\\s-*\\'" todomatch)
14456 (setq todomatch nil)))
14457 ;; Only matching tags.
14458 (setq tagsmatch match)
14459 (setq todomatch nil))
14461 ;; Make the tags matcher.
14462 (when (org-string-nw-p tagsmatch)
14463 (let ((orlist nil)
14464 (orterms (org-split-string tagsmatch "|"))
14465 term)
14466 (while (setq term (pop orterms))
14467 (while (and (equal (substring term -1) "\\") orterms)
14468 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14469 (while (string-match re term)
14470 (let* ((rest (substring term (match-end 0)))
14471 (minus (and (match-end 1)
14472 (equal (match-string 1 term) "-")))
14473 (tag (save-match-data
14474 (replace-regexp-in-string
14475 "\\\\-" "-" (match-string 2 term))))
14476 (regexp (eq (string-to-char tag) ?{))
14477 (levelp (match-end 4))
14478 (propp (match-end 5))
14480 (cond
14481 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14482 (levelp
14483 `(,(org-op-to-function (match-string 3 term))
14484 level
14485 ,(string-to-number (match-string 4 term))))
14486 (propp
14487 (let* ((gv (pcase (upcase (match-string 5 term))
14488 ("CATEGORY"
14489 '(get-text-property (point) 'org-category))
14490 ("TODO" 'todo)
14491 (p `(org-cached-entry-get nil ,p))))
14492 (pv (match-string 7 term))
14493 (regexp (eq (string-to-char pv) ?{))
14494 (strp (eq (string-to-char pv) ?\"))
14495 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14496 (po (org-op-to-function (match-string 6 term)
14497 (if timep 'time strp))))
14498 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14499 (when timep (setq pv (org-matcher-time pv)))
14500 (cond ((and regexp (eq po 'org<>))
14501 `(not (string-match ,pv (or ,gv ""))))
14502 (regexp `(string-match ,pv (or ,gv "")))
14503 (strp `(,po (or ,gv "") ,pv))
14505 `(,po
14506 (string-to-number (or ,gv ""))
14507 ,(string-to-number pv))))))
14508 (t `(member ,tag tags-list)))))
14509 (push (if minus `(not ,mm) mm) tagsmatcher)
14510 (setq term rest)))
14511 (push `(and ,@tagsmatcher) orlist)
14512 (setq tagsmatcher nil))
14513 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14515 ;; Make the TODO matcher.
14516 (when (org-string-nw-p todomatch)
14517 (let ((orlist nil))
14518 (dolist (term (org-split-string todomatch "|"))
14519 (while (string-match re term)
14520 (let* ((minus (and (match-end 1)
14521 (equal (match-string 1 term) "-")))
14522 (kwd (match-string 2 term))
14523 (regexp (eq (string-to-char kwd) ?{))
14524 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14525 `(equal todo ,kwd))))
14526 (push (if minus `(not ,mm) mm) todomatcher))
14527 (setq term (substring term (match-end 0))))
14528 (push (if (> (length todomatcher) 1)
14529 (cons 'and todomatcher)
14530 (car todomatcher))
14531 orlist)
14532 (setq todomatcher nil))
14533 (setq todomatcher (cons 'or orlist))))
14535 ;; Return the string and function of the matcher. If no
14536 ;; tags-specific or todo-specific matcher exists, match
14537 ;; everything.
14538 (let ((matcher (if (and tagsmatcher todomatcher)
14539 `(and ,tagsmatcher ,todomatcher)
14540 (or tagsmatcher todomatcher t))))
14541 (when org--matcher-tags-todo-only
14542 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14543 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14545 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14546 "Expand group tags in MATCH.
14548 This replaces every group tag in MATCH with a regexp tag search.
14549 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14550 will be replaced like this:
14552 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14553 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14554 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14556 Replacing by a regexp preserves the structure of the match.
14557 E.g., this expansion
14559 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14561 will match anything tagged with \"Lab\" and \"Home\", or tagged
14562 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14564 A group tag in MATCH can contain regular expressions of its own.
14565 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14566 will be replaced like this:
14568 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14570 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14571 assumed to be a single group tag, and the function will return
14572 the list of tags in this group.
14574 When DOWNCASE is non-nil, expand downcased TAGS."
14575 (if org-group-tags
14576 (let* ((case-fold-search t)
14577 (stable org-mode-syntax-table)
14578 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14579 (taggroups (if downcased
14580 (mapcar (lambda (tg) (mapcar #'downcase tg))
14581 taggroups)
14582 taggroups))
14583 (taggroups-keys (mapcar #'car taggroups))
14584 (return-match (if downcased (downcase match) match))
14585 (count 0)
14586 (work-already-expanded tags-already-expanded)
14587 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14588 ;; @ and _ are allowed as word-components in tags.
14589 (modify-syntax-entry ?@ "w" stable)
14590 (modify-syntax-entry ?_ "w" stable)
14591 ;; Temporarily replace regexp-expressions in the match-expression.
14592 (while (string-match "{.+?}" return-match)
14593 (cl-incf count)
14594 (push (match-string 0 return-match) regexps-in-match)
14595 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14596 (while (and taggroups-keys
14597 (with-syntax-table stable
14598 (string-match
14599 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14600 (regexp-opt taggroups-keys) "\\>\\)")
14601 return-match)))
14602 (let* ((dir (match-string 1 return-match))
14603 (tag (match-string 2 return-match))
14604 (tag (if downcased (downcase tag) tag)))
14605 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14606 (member tag work-already-expanded))
14607 (setq tags-in-group (assoc tag taggroups))
14608 (push tag work-already-expanded)
14609 ;; Recursively expand each tag in the group, if the tag hasn't
14610 ;; already been expanded. Restore the match-data after all recursive calls.
14611 (save-match-data
14612 (let (tags-expanded)
14613 (dolist (x (cdr tags-in-group))
14614 (if (and (member x taggroups-keys)
14615 (not (member x work-already-expanded)))
14616 (setq tags-expanded
14617 (delete-dups
14618 (append
14619 (org-tags-expand x t downcased
14620 work-already-expanded)
14621 tags-expanded)))
14622 (setq tags-expanded
14623 (append (list x) tags-expanded)))
14624 (setq work-already-expanded
14625 (delete-dups
14626 (append tags-expanded
14627 work-already-expanded))))
14628 (setq tags-in-group
14629 (delete-dups (cons (car tags-in-group)
14630 tags-expanded)))))
14631 ;; Filter tag-regexps from tags.
14632 (setq regexp-in-group-escaped
14633 (delq nil (mapcar (lambda (x)
14634 (if (stringp x)
14635 (and (equal "{" (substring x 0 1))
14636 (equal "}" (substring x -1))
14639 tags-in-group))
14640 regexp-in-group
14641 (mapcar (lambda (x)
14642 (substring x 1 -1))
14643 regexp-in-group-escaped)
14644 tags-in-group
14645 (delq nil (mapcar (lambda (x)
14646 (if (stringp x)
14647 (and (not (equal "{" (substring x 0 1)))
14648 (not (equal "}" (substring x -1)))
14651 tags-in-group)))
14652 ;; If single-as-list, do no more in the while-loop.
14653 (if (not single-as-list)
14654 (progn
14655 (when regexp-in-group
14656 (setq regexp-in-group
14657 (concat "\\|"
14658 (mapconcat 'identity regexp-in-group
14659 "\\|"))))
14660 (setq tags-in-group
14661 (concat dir
14662 "{\\<"
14663 (regexp-opt tags-in-group)
14664 "\\>"
14665 regexp-in-group
14666 "}"))
14667 (when (stringp tags-in-group)
14668 (org-add-props tags-in-group '(grouptag t)))
14669 (setq return-match
14670 (replace-match tags-in-group t t return-match)))
14671 (setq tags-in-group
14672 (append regexp-in-group-escaped tags-in-group))))
14673 (setq taggroups-keys (delete tag taggroups-keys))))
14674 ;; Add the regular expressions back into the match-expression again.
14675 (while regexps-in-match
14676 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14677 (pop regexps-in-match)
14678 return-match t t))
14679 (cl-decf count))
14680 (if single-as-list
14681 (if tags-in-group tags-in-group (list return-match))
14682 return-match))
14683 (if single-as-list
14684 (list (if downcased (downcase match) match))
14685 match)))
14687 (defun org-op-to-function (op &optional stringp)
14688 "Turn an operator into the appropriate function."
14689 (setq op
14690 (cond
14691 ((equal op "<" ) '(< string< org-time<))
14692 ((equal op ">" ) '(> org-string> org-time>))
14693 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14694 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14695 ((member op '("=" "==")) '(= string= org-time=))
14696 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14697 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14699 (defun org<> (a b) (not (= a b)))
14700 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14701 (defun org-string>= (a b) (not (string< a b)))
14702 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14703 (defun org-string<> (a b) (not (string= a b)))
14704 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14705 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14706 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14707 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14708 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14709 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14710 (defun org-2ft (s)
14711 "Convert S to a floating point time.
14712 If S is already a number, just return it. If it is a string, parse
14713 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14714 (cond
14715 ((numberp s) s)
14716 ((stringp s)
14717 (condition-case nil
14718 (float-time (apply 'encode-time (org-parse-time-string s)))
14719 (error 0.)))
14720 (t 0.)))
14722 (defun org-time-today ()
14723 "Time in seconds today at 0:00.
14724 Returns the float number of seconds since the beginning of the
14725 epoch to the beginning of today (00:00)."
14726 (float-time (apply 'encode-time
14727 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14729 (defun org-matcher-time (s)
14730 "Interpret a time comparison value."
14731 (save-match-data
14732 (cond
14733 ((string= s "<now>") (float-time))
14734 ((string= s "<today>") (org-time-today))
14735 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14736 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14737 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14738 (+ (org-time-today)
14739 (* (string-to-number (match-string 1 s))
14740 (cdr (assoc (match-string 2 s)
14741 '(("d" . 86400.0) ("w" . 604800.0)
14742 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14743 (t (org-2ft s)))))
14745 (defun org-match-any-p (re list)
14746 "Does re match any element of list?"
14747 (setq list (mapcar (lambda (x) (string-match re x)) list))
14748 (delq nil list))
14750 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14751 (defvar org-tags-overlay (make-overlay 1 1))
14752 (org-detach-overlay org-tags-overlay)
14754 (defun org-get-local-tags-at (&optional pos)
14755 "Get a list of tags defined in the current headline."
14756 (org-get-tags-at pos 'local))
14758 (defun org-get-local-tags ()
14759 "Get a list of tags defined in the current headline."
14760 (org-get-tags-at nil 'local))
14762 (defun org-get-tags-at (&optional pos local)
14763 "Get a list of all headline tags applicable at POS.
14764 POS defaults to point. If tags are inherited, the list contains
14765 the targets in the same sequence as the headlines appear, i.e.
14766 the tags of the current headline come last.
14767 When LOCAL is non-nil, only return tags from the current headline,
14768 ignore inherited ones."
14769 (interactive)
14770 (if (and org-trust-scanner-tags
14771 (or (not pos) (equal pos (point)))
14772 (not local))
14773 org-scanner-tags
14774 (let (tags ltags lastpos parent)
14775 (save-excursion
14776 (save-restriction
14777 (widen)
14778 (goto-char (or pos (point)))
14779 (save-match-data
14780 (catch 'done
14781 (condition-case nil
14782 (progn
14783 (org-back-to-heading t)
14784 (while (not (equal lastpos (point)))
14785 (setq lastpos (point))
14786 (when (looking-at
14787 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14788 (setq ltags (org-split-string
14789 (org-match-string-no-properties 1) ":"))
14790 (when parent
14791 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14792 (setq tags (append
14793 (if parent
14794 (org-remove-uninherited-tags ltags)
14795 ltags)
14796 tags)))
14797 (or org-use-tag-inheritance (throw 'done t))
14798 (when local (throw 'done t))
14799 (or (org-up-heading-safe) (error nil))
14800 (setq parent t)))
14801 (error nil)))))
14802 (if local
14803 tags
14804 (reverse (delete-dups
14805 (reverse (append
14806 (org-remove-uninherited-tags
14807 org-file-tags)
14808 tags)))))))))
14810 (defun org-add-prop-inherited (s)
14811 (add-text-properties 0 (length s) '(inherited t) s)
14814 (defun org-toggle-tag (tag &optional onoff)
14815 "Toggle the tag TAG for the current line.
14816 If ONOFF is `on' or `off', don't toggle but set to this state."
14817 (let (res current)
14818 (save-excursion
14819 (org-back-to-heading t)
14820 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14821 (point-at-eol) t)
14822 (progn
14823 (setq current (match-string 1))
14824 (replace-match ""))
14825 (setq current ""))
14826 (setq current (nreverse (org-split-string current ":")))
14827 (cond
14828 ((eq onoff 'on)
14829 (setq res t)
14830 (or (member tag current) (push tag current)))
14831 ((eq onoff 'off)
14832 (or (not (member tag current)) (setq current (delete tag current))))
14833 (t (if (member tag current)
14834 (setq current (delete tag current))
14835 (setq res t)
14836 (push tag current))))
14837 (end-of-line 1)
14838 (if current
14839 (progn
14840 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14841 (org-set-tags nil t))
14842 (delete-horizontal-space))
14843 (run-hooks 'org-after-tags-change-hook))
14844 res))
14846 (defun org-align-tags-here (to-col)
14847 ;; Assumes that this is a headline
14848 "Align tags on the current headline to TO-COL."
14849 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14850 (beginning-of-line 1)
14851 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14852 (< pos (match-beginning 2)))
14853 (progn
14854 (setq tags-l (- (match-end 2) (match-beginning 2)))
14855 (goto-char (match-beginning 1))
14856 (insert " ")
14857 (delete-region (point) (1+ (match-beginning 2)))
14858 (setq ncol (max (current-column)
14859 (1+ col)
14860 (if (> to-col 0)
14861 to-col
14862 (- (abs to-col) tags-l))))
14863 (setq p (point))
14864 (insert (make-string (- ncol (current-column)) ?\ ))
14865 (setq ncol (current-column))
14866 (when indent-tabs-mode (tabify p (point-at-eol)))
14867 (org-move-to-column (min ncol col)))
14868 (goto-char pos))))
14870 (defun org-set-tags-command (&optional arg just-align)
14871 "Call the set-tags command for the current entry."
14872 (interactive "P")
14873 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14874 (org-set-tags arg just-align)
14875 (save-excursion
14876 (unless (and (org-region-active-p)
14877 org-loop-over-headlines-in-active-region)
14878 (org-back-to-heading t))
14879 (org-set-tags arg just-align))))
14881 (defun org-set-tags-to (data)
14882 "Set the tags of the current entry to DATA, replacing the current tags.
14883 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14884 If DATA is nil or the empty string, any tags will be removed."
14885 (interactive "sTags: ")
14886 (setq data
14887 (cond
14888 ((eq data nil) "")
14889 ((equal data "") "")
14890 ((stringp data)
14891 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14892 ":"))
14893 ((listp data)
14894 (concat ":" (mapconcat 'identity data ":") ":"))))
14895 (when data
14896 (save-excursion
14897 (org-back-to-heading t)
14898 (when (looking-at org-complex-heading-regexp)
14899 (if (match-end 5)
14900 (progn
14901 (goto-char (match-beginning 5))
14902 (insert data)
14903 (delete-region (point) (point-at-eol))
14904 (org-set-tags nil 'align))
14905 (goto-char (point-at-eol))
14906 (insert " " data)
14907 (org-set-tags nil 'align)))
14908 (beginning-of-line 1)
14909 (when (looking-at ".*?\\([ \t]+\\)$")
14910 (delete-region (match-beginning 1) (match-end 1))))))
14912 (defun org-align-all-tags ()
14913 "Align the tags in all headings."
14914 (interactive)
14915 (save-excursion
14916 (or (ignore-errors (org-back-to-heading t))
14917 (outline-next-heading))
14918 (if (org-at-heading-p)
14919 (org-set-tags t)
14920 (message "No headings"))))
14922 (defvar org-indent-indentation-per-level)
14923 (defun org-set-tags (&optional arg just-align)
14924 "Set the tags for the current headline.
14925 With prefix ARG, realign all tags in headings in the current buffer.
14926 When JUST-ALIGN is non-nil, only align tags."
14927 (interactive "P")
14928 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14929 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14930 'region-start-level
14931 'region))
14932 org-loop-over-headlines-in-active-region)
14933 (org-map-entries
14934 ;; We don't use ARG and JUST-ALIGN here because these args
14935 ;; are not useful when looping over headlines.
14936 #'org-set-tags
14937 org-loop-over-headlines-in-active-region
14939 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14940 (let ((org-setting-tags t))
14941 (if arg
14942 (save-excursion
14943 (goto-char (point-min))
14944 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14945 (while (re-search-forward org-outline-regexp-bol nil t)
14946 (org-set-tags nil t)
14947 (end-of-line)))
14948 (message "All tags realigned to column %d" org-tags-column))
14949 (let* ((current (org-get-tags-string))
14950 (col (current-column))
14951 (tags
14952 (if just-align current
14953 ;; Get a new set of tags from the user.
14954 (save-excursion
14955 (let* ((seen)
14956 (table
14957 (setq
14958 org-last-tags-completion-table
14959 ;; Uniquify tags in alists, yet preserve
14960 ;; structure (i.e., keywords).
14961 (delq nil
14962 (mapcar
14963 (lambda (pair)
14964 (let ((head (car pair)))
14965 (cond ((symbolp head) pair)
14966 ((member head seen) nil)
14967 (t (push head seen)
14968 pair))))
14969 (append
14970 (or org-current-tag-alist
14971 (org-get-buffer-tags))
14972 (and
14973 org-complete-tags-always-offer-all-agenda-tags
14974 (org-global-tags-completion-table
14975 (org-agenda-files))))))))
14976 (current-tags (org-split-string current ":"))
14977 (inherited-tags
14978 (nreverse (nthcdr (length current-tags)
14979 (nreverse (org-get-tags-at))))))
14980 (replace-regexp-in-string
14981 "\\([-+&]+\\|,\\)"
14983 (if (or (eq t org-use-fast-tag-selection)
14984 (and org-use-fast-tag-selection
14985 (delq nil (mapcar #'cdr table))))
14986 (org-fast-tag-selection
14987 current-tags inherited-tags table
14988 (and org-fast-tag-selection-include-todo
14989 org-todo-key-alist))
14990 (let ((org-add-colon-after-tag-completion
14991 (< 1 (length table))))
14992 (org-trim
14993 (completing-read
14994 "Tags: "
14995 #'org-tags-completion-function
14996 nil nil current 'org-tags-history))))))))))
14998 (when org-tags-sort-function
14999 (setq tags
15000 (mapconcat
15001 #'identity
15002 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
15003 org-tags-sort-function)
15004 ":")))
15006 (if (not (org-string-nw-p tags)) (setq tags "")
15007 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15008 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15010 ;; Insert new tags at the correct column
15011 (beginning-of-line)
15012 (let ((level (if (looking-at org-outline-regexp)
15013 (- (match-end 0) (point) 1)
15014 1)))
15015 (cond
15016 ((and (equal current "") (equal tags "")))
15017 ((re-search-forward
15018 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15019 (line-end-position)
15021 (if (equal tags "") (replace-match "" t t)
15022 (goto-char (match-beginning 0))
15023 (let* ((c0 (current-column))
15024 ;; Compute offset for the case of org-indent-mode
15025 ;; active.
15026 (di (if (org-bound-and-true-p org-indent-mode)
15027 (* (1- org-indent-indentation-per-level)
15028 (1- level))
15030 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15031 (tc (+ org-tags-column
15032 (if (> org-tags-column 0) (- di) di)))
15033 (c1 (max (1+ c0)
15034 (if (> tc 0) tc
15035 (- (- tc) (string-width tags)))))
15036 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15037 (replace-match rpl t t)
15038 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
15039 (tabify p0 (point))))))
15040 (t (error "Tags alignment failed"))))
15041 (org-move-to-column col))
15042 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15044 (defun org-change-tag-in-region (beg end tag off)
15045 "Add or remove TAG for each entry in the region.
15046 This works in the agenda, and also in an org-mode buffer."
15047 (interactive
15048 (list (region-beginning) (region-end)
15049 (let ((org-last-tags-completion-table
15050 (if (derived-mode-p 'org-mode)
15051 (org-uniquify
15052 (delq nil (append (org-get-buffer-tags)
15053 (org-global-tags-completion-table))))
15054 (org-global-tags-completion-table))))
15055 (completing-read
15056 "Tag: " 'org-tags-completion-function nil nil nil
15057 'org-tags-history))
15058 (progn
15059 (message "[s]et or [r]emove? ")
15060 (equal (read-char-exclusive) ?r))))
15061 (when (fboundp 'deactivate-mark) (deactivate-mark))
15062 (let ((agendap (equal major-mode 'org-agenda-mode))
15063 l1 l2 m buf pos newhead (cnt 0))
15064 (goto-char end)
15065 (setq l2 (1- (org-current-line)))
15066 (goto-char beg)
15067 (setq l1 (org-current-line))
15068 (cl-loop for l from l1 to l2 do
15069 (org-goto-line l)
15070 (setq m (get-text-property (point) 'org-hd-marker))
15071 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15072 (and agendap m))
15073 (setq buf (if agendap (marker-buffer m) (current-buffer))
15074 pos (if agendap m (point)))
15075 (with-current-buffer buf
15076 (save-excursion
15077 (save-restriction
15078 (goto-char pos)
15079 (setq cnt (1+ cnt))
15080 (org-toggle-tag tag (if off 'off 'on))
15081 (setq newhead (org-get-heading)))))
15082 (and agendap (org-agenda-change-all-lines newhead m))))
15083 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15085 (defun org-tags-completion-function (string _predicate &optional flag)
15086 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15087 (confirm (lambda (x) (stringp (car x)))))
15088 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15089 (setq s1 (match-string 1 string)
15090 s2 (match-string 2 string))
15091 (setq s1 "" s2 string))
15092 (cond
15093 ((eq flag nil)
15094 ;; try completion
15095 (setq rtn (try-completion s2 ctable confirm))
15096 (when (stringp rtn)
15097 (setq rtn
15098 (concat s1 s2 (substring rtn (length s2))
15099 (if (and org-add-colon-after-tag-completion
15100 (assoc rtn ctable))
15101 ":" ""))))
15102 rtn)
15103 ((eq flag t)
15104 ;; all-completions
15105 (all-completions s2 ctable confirm))
15106 ((eq flag 'lambda)
15107 ;; exact match?
15108 (assoc s2 ctable)))))
15110 (defun org-fast-tag-insert (kwd tags face &optional end)
15111 "Insert KDW, and the TAGS, the latter with face FACE.
15112 Also insert END."
15113 (insert (format "%-12s" (concat kwd ":"))
15114 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15115 (or end "")))
15117 (defun org-fast-tag-show-exit (flag)
15118 (save-excursion
15119 (org-goto-line 3)
15120 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15121 (replace-match ""))
15122 (when flag
15123 (end-of-line 1)
15124 (org-move-to-column (- (window-width) 19) t)
15125 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15127 (defun org-set-current-tags-overlay (current prefix)
15128 "Add an overlay to CURRENT tag with PREFIX."
15129 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15130 (if (featurep 'xemacs)
15131 (org-overlay-display org-tags-overlay (concat prefix s)
15132 'secondary-selection)
15133 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15134 (org-overlay-display org-tags-overlay (concat prefix s)))))
15136 (defvar org-last-tag-selection-key nil)
15137 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15138 "Fast tag selection with single keys.
15139 CURRENT is the current list of tags in the headline, INHERITED is the
15140 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15141 possibly with grouping information. TODO-TABLE is a similar table with
15142 TODO keywords, should these have keys assigned to them.
15143 If the keys are nil, a-z are automatically assigned.
15144 Returns the new tags string, or nil to not change the current settings."
15145 (let* ((fulltable (append table todo-table))
15146 (maxlen (apply 'max (mapcar
15147 (lambda (x)
15148 (if (stringp (car x)) (string-width (car x)) 0))
15149 fulltable)))
15150 (buf (current-buffer))
15151 (expert (eq org-fast-tag-selection-single-key 'expert))
15152 (buffer-tags nil)
15153 (fwidth (+ maxlen 3 1 3))
15154 (ncol (/ (- (window-width) 4) fwidth))
15155 (i-face 'org-done)
15156 (c-face 'org-todo)
15157 tg cnt e c char c1 c2 ntable tbl rtn
15158 ov-start ov-end ov-prefix
15159 (exit-after-next org-fast-tag-selection-single-key)
15160 (done-keywords org-done-keywords)
15161 groups ingroup intaggroup)
15162 (save-excursion
15163 (beginning-of-line 1)
15164 (if (looking-at
15165 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15166 (setq ov-start (match-beginning 1)
15167 ov-end (match-end 1)
15168 ov-prefix "")
15169 (setq ov-start (1- (point-at-eol))
15170 ov-end (1+ ov-start))
15171 (skip-chars-forward "^\n\r")
15172 (setq ov-prefix
15173 (concat
15174 (buffer-substring (1- (point)) (point))
15175 (if (> (current-column) org-tags-column)
15177 (make-string (- org-tags-column (current-column)) ?\ ))))))
15178 (move-overlay org-tags-overlay ov-start ov-end)
15179 (save-window-excursion
15180 (if expert
15181 (set-buffer (get-buffer-create " *Org tags*"))
15182 (delete-other-windows)
15183 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15184 (org-switch-to-buffer-other-window " *Org tags*"))
15185 (erase-buffer)
15186 (setq-local org-done-keywords done-keywords)
15187 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15188 (org-fast-tag-insert "Current" current c-face "\n\n")
15189 (org-fast-tag-show-exit exit-after-next)
15190 (org-set-current-tags-overlay current ov-prefix)
15191 (setq tbl fulltable char ?a cnt 0)
15192 (while (setq e (pop tbl))
15193 (cond
15194 ((eq (car e) :startgroup)
15195 (push '() groups) (setq ingroup t)
15196 (unless (zerop cnt)
15197 (setq cnt 0)
15198 (insert "\n"))
15199 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15200 ((eq (car e) :endgroup)
15201 (setq ingroup nil cnt 0)
15202 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15203 ((eq (car e) :startgrouptag)
15204 (setq intaggroup t)
15205 (unless (zerop cnt)
15206 (setq cnt 0)
15207 (insert "\n"))
15208 (insert "[ "))
15209 ((eq (car e) :endgrouptag)
15210 (setq intaggroup nil cnt 0)
15211 (insert "]\n"))
15212 ((equal e '(:newline))
15213 (unless (zerop cnt)
15214 (setq cnt 0)
15215 (insert "\n")
15216 (setq e (car tbl))
15217 (while (equal (car tbl) '(:newline))
15218 (insert "\n")
15219 (setq tbl (cdr tbl)))))
15220 ((equal e '(:grouptags)) (insert " : "))
15222 (setq tg (copy-sequence (car e)) c2 nil)
15223 (if (cdr e)
15224 (setq c (cdr e))
15225 ;; automatically assign a character.
15226 (setq c1 (string-to-char
15227 (downcase (substring
15228 tg (if (= (string-to-char tg) ?@) 1 0)))))
15229 (if (or (rassoc c1 ntable) (rassoc c1 table))
15230 (while (or (rassoc char ntable) (rassoc char table))
15231 (setq char (1+ char)))
15232 (setq c2 c1))
15233 (setq c (or c2 char)))
15234 (when ingroup (push tg (car groups)))
15235 (setq tg (org-add-props tg nil 'face
15236 (cond
15237 ((not (assoc tg table))
15238 (org-get-todo-face tg))
15239 ((member tg current) c-face)
15240 ((member tg inherited) i-face))))
15241 (when (equal (caar tbl) :grouptags)
15242 (org-add-props tg nil 'face 'org-tag-group))
15243 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15244 (insert "[" c "] " tg (make-string
15245 (- fwidth 4 (length tg)) ?\ ))
15246 (push (cons tg c) ntable)
15247 (when (= (cl-incf cnt) ncol)
15248 (insert "\n")
15249 (when (or ingroup intaggroup) (insert " "))
15250 (setq cnt 0)))))
15251 (setq ntable (nreverse ntable))
15252 (insert "\n")
15253 (goto-char (point-min))
15254 (unless expert (org-fit-window-to-buffer))
15255 (setq rtn
15256 (catch 'exit
15257 (while t
15258 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15259 (if (not groups) "no " "")
15260 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15261 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15262 (setq org-last-tag-selection-key c)
15263 (cond
15264 ((= c ?\r) (throw 'exit t))
15265 ((= c ?!)
15266 (setq groups (not groups))
15267 (goto-char (point-min))
15268 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15269 ((= c ?\C-c)
15270 (if (not expert)
15271 (org-fast-tag-show-exit
15272 (setq exit-after-next (not exit-after-next)))
15273 (setq expert nil)
15274 (delete-other-windows)
15275 (set-window-buffer (split-window-vertically) " *Org tags*")
15276 (org-switch-to-buffer-other-window " *Org tags*")
15277 (org-fit-window-to-buffer)))
15278 ((or (= c ?\C-g)
15279 (and (= c ?q) (not (rassoc c ntable))))
15280 (org-detach-overlay org-tags-overlay)
15281 (setq quit-flag t))
15282 ((= c ?\ )
15283 (setq current nil)
15284 (when exit-after-next (setq exit-after-next 'now)))
15285 ((= c ?\t)
15286 (condition-case nil
15287 (setq tg (completing-read
15288 "Tag: "
15289 (or buffer-tags
15290 (with-current-buffer buf
15291 (setq buffer-tags
15292 (org-get-buffer-tags))))))
15293 (quit (setq tg "")))
15294 (when (string-match "\\S-" tg)
15295 (cl-pushnew (list tg) buffer-tags :test #'equal)
15296 (if (member tg current)
15297 (setq current (delete tg current))
15298 (push tg current)))
15299 (when exit-after-next (setq exit-after-next 'now)))
15300 ((setq e (rassoc c todo-table) tg (car e))
15301 (with-current-buffer buf
15302 (save-excursion (org-todo tg)))
15303 (when exit-after-next (setq exit-after-next 'now)))
15304 ((setq e (rassoc c ntable) tg (car e))
15305 (if (member tg current)
15306 (setq current (delete tg current))
15307 (cl-loop for g in groups do
15308 (when (member tg g)
15309 (dolist (x g) (setq current (delete x current)))))
15310 (push tg current))
15311 (when exit-after-next (setq exit-after-next 'now))))
15313 ;; Create a sorted list
15314 (setq current
15315 (sort current
15316 (lambda (a b)
15317 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15318 (when (eq exit-after-next 'now) (throw 'exit t))
15319 (goto-char (point-min))
15320 (beginning-of-line 2)
15321 (delete-region (point) (point-at-eol))
15322 (org-fast-tag-insert "Current" current c-face)
15323 (org-set-current-tags-overlay current ov-prefix)
15324 (while (re-search-forward
15325 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15326 (setq tg (match-string 1))
15327 (add-text-properties
15328 (match-beginning 1) (match-end 1)
15329 (list 'face
15330 (cond
15331 ((member tg current) c-face)
15332 ((member tg inherited) i-face)
15333 (t (get-text-property (match-beginning 1) 'face))))))
15334 (goto-char (point-min)))))
15335 (org-detach-overlay org-tags-overlay)
15336 (if rtn
15337 (mapconcat 'identity current ":")
15338 nil))))
15340 (defun org-get-tags-string ()
15341 "Get the TAGS string in the current headline."
15342 (unless (org-at-heading-p t)
15343 (user-error "Not on a heading"))
15344 (save-excursion
15345 (beginning-of-line 1)
15346 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15347 (org-match-string-no-properties 1)
15348 "")))
15350 (defun org-get-tags ()
15351 "Get the list of tags specified in the current headline."
15352 (org-split-string (org-get-tags-string) ":"))
15354 (defun org-get-buffer-tags ()
15355 "Get a table of all tags used in the buffer, for completion."
15356 (org-with-wide-buffer
15357 (goto-char (point-min))
15358 (let ((tag-re (concat org-outline-regexp-bol
15359 "\\(?:.*?[ \t]\\)?"
15360 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15361 tags)
15362 (while (re-search-forward tag-re nil t)
15363 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15364 (push tag tags)))
15365 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15367 ;;;; The mapping API
15369 (defvar org-agenda-skip-comment-trees)
15370 (defvar org-agenda-skip-function)
15371 (defun org-map-entries (func &optional match scope &rest skip)
15372 "Call FUNC at each headline selected by MATCH in SCOPE.
15374 FUNC is a function or a lisp form. The function will be called without
15375 arguments, with the cursor positioned at the beginning of the headline.
15376 The return values of all calls to the function will be collected and
15377 returned as a list.
15379 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15380 does not need to preserve point. After evaluation, the cursor will be
15381 moved to the end of the line (presumably of the headline of the
15382 processed entry) and search continues from there. Under some
15383 circumstances, this may not produce the wanted results. For example,
15384 if you have removed (e.g. archived) the current (sub)tree it could
15385 mean that the next entry will be skipped entirely. In such cases, you
15386 can specify the position from where search should continue by making
15387 FUNC set the variable `org-map-continue-from' to the desired buffer
15388 position.
15390 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15391 Only headlines that are matched by this query will be considered during
15392 the iteration. When MATCH is nil or t, all headlines will be
15393 visited by the iteration.
15395 SCOPE determines the scope of this command. It can be any of:
15397 nil The current buffer, respecting the restriction if any
15398 tree The subtree started with the entry at point
15399 region The entries within the active region, if any
15400 region-start-level
15401 The entries within the active region, but only those at
15402 the same level than the first one.
15403 file The current buffer, without restriction
15404 file-with-archives
15405 The current buffer, and any archives associated with it
15406 agenda All agenda files
15407 agenda-with-archives
15408 All agenda files with any archive files associated with them
15409 \(file1 file2 ...)
15410 If this is a list, all files in the list will be scanned
15412 The remaining args are treated as settings for the skipping facilities of
15413 the scanner. The following items can be given here:
15415 archive skip trees with the archive tag
15416 comment skip trees with the COMMENT keyword
15417 function or Emacs Lisp form:
15418 will be used as value for `org-agenda-skip-function', so
15419 whenever the function returns a position, FUNC will not be
15420 called for that entry and search will continue from the
15421 position returned
15423 If your function needs to retrieve the tags including inherited tags
15424 at the *current* entry, you can use the value of the variable
15425 `org-scanner-tags' which will be much faster than getting the value
15426 with `org-get-tags-at'. If your function gets properties with
15427 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15428 to t around the call to `org-entry-properties' to get the same speedup.
15429 Note that if your function moves around to retrieve tags and properties at
15430 a *different* entry, you cannot use these techniques."
15431 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15432 (not (org-region-active-p)))
15433 (let* ((org-agenda-archives-mode nil) ; just to make sure
15434 (org-agenda-skip-archived-trees (memq 'archive skip))
15435 (org-agenda-skip-comment-trees (memq 'comment skip))
15436 (org-agenda-skip-function
15437 (car (org-delete-all '(comment archive) skip)))
15438 (org-tags-match-list-sublevels t)
15439 (start-level (eq scope 'region-start-level))
15440 matcher res
15441 org-todo-keywords-for-agenda
15442 org-done-keywords-for-agenda
15443 org-todo-keyword-alist-for-agenda
15444 org-tag-alist-for-agenda
15445 org--matcher-tags-todo-only)
15447 (cond
15448 ((eq match t) (setq matcher t))
15449 ((eq match nil) (setq matcher t))
15450 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15452 (save-excursion
15453 (save-restriction
15454 (cond ((eq scope 'tree)
15455 (org-back-to-heading t)
15456 (org-narrow-to-subtree)
15457 (setq scope nil))
15458 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15459 (org-region-active-p))
15460 ;; If needed, set start-level to a string like "2"
15461 (when start-level
15462 (save-excursion
15463 (goto-char (region-beginning))
15464 (unless (org-at-heading-p) (outline-next-heading))
15465 (setq start-level (org-current-level))))
15466 (narrow-to-region (region-beginning)
15467 (save-excursion
15468 (goto-char (region-end))
15469 (unless (and (bolp) (org-at-heading-p))
15470 (outline-next-heading))
15471 (point)))
15472 (setq scope nil)))
15474 (if (not scope)
15475 (progn
15476 (org-agenda-prepare-buffers
15477 (and buffer-file-name (list buffer-file-name)))
15478 (setq res
15479 (org-scan-tags
15480 func matcher org--matcher-tags-todo-only start-level)))
15481 ;; Get the right scope
15482 (cond
15483 ((and scope (listp scope) (symbolp (car scope)))
15484 (setq scope (eval scope)))
15485 ((eq scope 'agenda)
15486 (setq scope (org-agenda-files t)))
15487 ((eq scope 'agenda-with-archives)
15488 (setq scope (org-agenda-files t))
15489 (setq scope (org-add-archive-files scope)))
15490 ((eq scope 'file)
15491 (setq scope (and buffer-file-name (list buffer-file-name))))
15492 ((eq scope 'file-with-archives)
15493 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15494 (org-agenda-prepare-buffers scope)
15495 (dolist (file scope)
15496 (with-current-buffer (org-find-base-buffer-visiting file)
15497 (save-excursion
15498 (save-restriction
15499 (widen)
15500 (goto-char (point-min))
15501 (setq res
15502 (append
15504 (org-scan-tags
15505 func matcher org--matcher-tags-todo-only))))))))))
15506 res)))
15508 ;;; Properties API
15510 (defconst org-special-properties
15511 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15512 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15513 "The special properties valid in Org mode.
15514 These are properties that are not defined in the property drawer,
15515 but in some other way.")
15517 (defconst org-default-properties
15518 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15519 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15520 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15521 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15522 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15523 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15524 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15525 "Some properties that are used by Org mode for various purposes.
15526 Being in this list makes sure that they are offered for completion.")
15528 (defun org--valid-property-p (property)
15529 "Non nil when string PROPERTY is a valid property name."
15530 (not
15531 (or (equal property "")
15532 (org-string-match-p "\\s-" property))))
15534 (defun org--update-property-plist (key val props)
15535 "Associate KEY to VAL in alist PROPS.
15536 Modifications are made by side-effect. Return new alist."
15537 (let* ((appending (string= (substring key -1) "+"))
15538 (key (if appending (substring key 0 -1) key))
15539 (old (assoc-string key props t)))
15540 (if (not old) (cons (cons key val) props)
15541 (setcdr old (if appending (concat (cdr old) " " val) val))
15542 props)))
15544 (defun org-get-property-block (&optional beg force)
15545 "Return the (beg . end) range of the body of the property drawer.
15546 BEG is the beginning of the current subtree, or of the part
15547 before the first headline. If it is not given, it will be found.
15548 If the drawer does not exist, create it if FORCE is non-nil, or
15549 return nil."
15550 (org-with-wide-buffer
15551 (when beg (goto-char beg))
15552 (unless (org-before-first-heading-p)
15553 (let ((beg (cond (beg)
15554 ((or (not (featurep 'org-inlinetask))
15555 (org-inlinetask-in-task-p))
15556 (org-back-to-heading t))
15557 (t (org-with-limited-levels (org-back-to-heading t))))))
15558 (forward-line)
15559 (when (org-looking-at-p org-planning-line-re) (forward-line))
15560 (cond ((looking-at org-property-drawer-re)
15561 (forward-line)
15562 (cons (point) (progn (goto-char (match-end 0))
15563 (line-beginning-position))))
15564 (force
15565 (goto-char beg)
15566 (org-insert-property-drawer)
15567 (let ((pos (save-excursion (search-forward ":END:")
15568 (line-beginning-position))))
15569 (cons pos pos))))))))
15571 (defun org-at-property-p ()
15572 "Non-nil when point is inside a property drawer.
15573 See `org-property-re' for match data, if applicable."
15574 (save-excursion
15575 (beginning-of-line)
15576 (and (looking-at org-property-re)
15577 (let ((property-drawer (save-match-data (org-get-property-block))))
15578 (and property-drawer
15579 (>= (point) (car property-drawer))
15580 (< (point) (cdr property-drawer)))))))
15582 (defun org-property-action ()
15583 "Do an action on properties."
15584 (interactive)
15585 (unless (org-at-property-p) (user-error "Not at a property"))
15586 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15587 (let ((c (read-char-exclusive)))
15588 (cl-case c
15589 (?s (call-interactively #'org-set-property))
15590 (?d (call-interactively #'org-delete-property))
15591 (?D (call-interactively #'org-delete-property-globally))
15592 (?c (call-interactively #'org-compute-property-at-point))
15593 (otherwise (user-error "No such property action %c" c)))))
15595 (defun org-inc-effort ()
15596 "Increment the value of the effort property in the current entry."
15597 (interactive)
15598 (org-set-effort nil t))
15600 (defvar org-clock-effort) ; Defined in org-clock.el.
15601 (defvar org-clock-current-task) ; Defined in org-clock.el.
15602 (defun org-set-effort (&optional value increment)
15603 "Set the effort property of the current entry.
15604 With numerical prefix arg, use the nth allowed value, 0 stands for the
15605 10th allowed value.
15607 When INCREMENT is non-nil, set the property to the next allowed value."
15608 (interactive "P")
15609 (when (equal value 0) (setq value 10))
15610 (let* ((completion-ignore-case t)
15611 (prop org-effort-property)
15612 (cur (org-entry-get nil prop))
15613 (allowed (org-property-get-allowed-values nil prop 'table))
15614 (existing (mapcar 'list (org-property-values prop)))
15615 (heading (nth 4 (org-heading-components)))
15617 (val (cond
15618 ((stringp value) value)
15619 ((and allowed (integerp value))
15620 (or (car (nth (1- value) allowed))
15621 (car (org-last allowed))))
15622 ((and allowed increment)
15623 (or (cl-caadr (member (list cur) allowed))
15624 (user-error "Allowed effort values are not set")))
15625 (allowed
15626 (message "Select 1-9,0, [RET%s]: %s"
15627 (if cur (concat "=" cur) "")
15628 (mapconcat 'car allowed " "))
15629 (setq rpl (read-char-exclusive))
15630 (if (equal rpl ?\r)
15632 (setq rpl (- rpl ?0))
15633 (when (equal rpl 0) (setq rpl 10))
15634 (if (and (> rpl 0) (<= rpl (length allowed)))
15635 (car (nth (1- rpl) allowed))
15636 (org-completing-read "Effort: " allowed nil))))
15638 (org-completing-read
15639 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15640 (concat "[" cur "]") "")
15641 ": ")
15642 existing nil nil "" nil cur)))))
15643 (unless (equal (org-entry-get nil prop) val)
15644 (org-entry-put nil prop val))
15645 (org-refresh-property
15646 '((effort . identity)
15647 (effort-minutes . org-duration-string-to-minutes))
15648 val)
15649 (when (string= heading org-clock-current-task)
15650 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15651 (org-clock-update-mode-line))
15652 (message "%s is now %s" prop val)))
15654 (defun org-entry-properties (&optional pom which)
15655 "Get all properties of the current entry.
15657 When POM is a buffer position, get all properties from the entry
15658 there instead.
15660 This includes the TODO keyword, the tags, time strings for
15661 deadline, scheduled, and clocking, and any additional properties
15662 defined in the entry.
15664 If WHICH is nil or `all', get all properties. If WHICH is
15665 `special' or `standard', only get that subclass. If WHICH is
15666 a string, only get that property.
15668 Return value is an alist. Keys are properties, as upcased
15669 strings."
15670 (org-with-point-at pom
15671 (when (and (derived-mode-p 'org-mode)
15672 (ignore-errors (org-back-to-heading t)))
15673 (catch 'exit
15674 (let* ((beg (point))
15675 (specific (and (stringp which) (upcase which)))
15676 (which (cond ((not specific) which)
15677 ((member specific org-special-properties) 'special)
15678 (t 'standard)))
15679 props)
15680 ;; Get the special properties, like TODO and TAGS.
15681 (when (memq which '(nil all special))
15682 (when (or (not specific) (string= specific "CLOCKSUM"))
15683 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15684 (when clocksum
15685 (push (cons "CLOCKSUM"
15686 (org-minutes-to-clocksum-string clocksum))
15687 props)))
15688 (when specific (throw 'exit props)))
15689 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15690 (let ((clocksumt (get-text-property (point)
15691 :org-clock-minutes-today)))
15692 (when clocksumt
15693 (push (cons "CLOCKSUM_T"
15694 (org-minutes-to-clocksum-string clocksumt))
15695 props)))
15696 (when specific (throw 'exit props)))
15697 (when (or (not specific) (string= specific "ITEM"))
15698 (when (looking-at org-complex-heading-regexp)
15699 (push (cons "ITEM"
15700 (let ((title (match-string-no-properties 4)))
15701 (if (org-string-nw-p title)
15702 (org-remove-tabs title)
15703 "")))
15704 props))
15705 (when specific (throw 'exit props)))
15706 (when (or (not specific) (string= specific "TODO"))
15707 (let ((case-fold-search nil))
15708 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15709 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15710 (when specific (throw 'exit props)))
15711 (when (or (not specific) (string= specific "PRIORITY"))
15712 (push (cons "PRIORITY"
15713 (if (looking-at org-priority-regexp)
15714 (org-match-string-no-properties 2)
15715 (char-to-string org-default-priority)))
15716 props)
15717 (when specific (throw 'exit props)))
15718 (when (or (not specific) (string= specific "FILE"))
15719 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15720 props)
15721 (when specific (throw 'exit props)))
15722 (when (or (not specific) (string= specific "TAGS"))
15723 (let ((value (org-string-nw-p (org-get-tags-string))))
15724 (when value (push (cons "TAGS" value) props)))
15725 (when specific (throw 'exit props)))
15726 (when (or (not specific) (string= specific "ALLTAGS"))
15727 (let ((value (org-get-tags-at)))
15728 (when value
15729 (push (cons "ALLTAGS"
15730 (format ":%s:" (mapconcat #'identity value ":")))
15731 props)))
15732 (when specific (throw 'exit props)))
15733 (when (or (not specific) (string= specific "BLOCKED"))
15734 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15735 (when specific (throw 'exit props)))
15736 (when (or (not specific)
15737 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15738 (forward-line)
15739 (when (org-looking-at-p org-planning-line-re)
15740 (end-of-line)
15741 (let ((bol (line-beginning-position))
15742 ;; Backward compatibility: time keywords used to
15743 ;; be configurable (before 8.3). Make sure we
15744 ;; get the correct keyword.
15745 (key-assoc `(("CLOSED" . ,org-closed-string)
15746 ("DEADLINE" . ,org-deadline-string)
15747 ("SCHEDULED" . ,org-scheduled-string))))
15748 (dolist (pair (if specific (list (assoc specific key-assoc))
15749 key-assoc))
15750 (save-excursion
15751 (when (search-backward (cdr pair) bol t)
15752 (goto-char (match-end 0))
15753 (skip-chars-forward " \t")
15754 (and (looking-at org-ts-regexp-both)
15755 (push (cons (car pair)
15756 (org-match-string-no-properties 0))
15757 props)))))))
15758 (when specific (throw 'exit props)))
15759 (when (or (not specific)
15760 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15761 (let ((find-ts
15762 (lambda (end ts)
15763 ;; Fix next time-stamp before END. TS is the
15764 ;; list of time-stamps found so far.
15765 (let ((ts ts)
15766 (regexp (cond
15767 ((string= specific "TIMESTAMP")
15768 org-ts-regexp)
15769 ((string= specific "TIMESTAMP_IA")
15770 org-ts-regexp-inactive)
15771 ((assoc "TIMESTAMP_IA" ts)
15772 org-ts-regexp)
15773 ((assoc "TIMESTAMP" ts)
15774 org-ts-regexp-inactive)
15775 (t org-ts-regexp-both))))
15776 (catch 'next
15777 (while (re-search-forward regexp end t)
15778 (backward-char)
15779 (let ((object (org-element-context)))
15780 ;; Accept to match timestamps in node
15781 ;; properties, too.
15782 (when (memq (org-element-type object)
15783 '(node-property timestamp))
15784 (let ((type
15785 (org-element-property :type object)))
15786 (cond
15787 ((and (memq type '(active active-range))
15788 (not (equal specific "TIMESTAMP_IA")))
15789 (unless (assoc "TIMESTAMP" ts)
15790 (push (cons "TIMESTAMP"
15791 (org-element-property
15792 :raw-value object))
15794 (when specific (throw 'exit ts))))
15795 ((and (memq type '(inactive inactive-range))
15796 (not (string= specific "TIMESTAMP")))
15797 (unless (assoc "TIMESTAMP_IA" ts)
15798 (push (cons "TIMESTAMP_IA"
15799 (org-element-property
15800 :raw-value object))
15802 (when specific (throw 'exit ts))))))
15803 ;; Both timestamp types are found,
15804 ;; move to next part.
15805 (when (= (length ts) 2) (throw 'next ts)))))
15806 ts)))))
15807 (goto-char beg)
15808 ;; First look for timestamps within headline.
15809 (let ((ts (funcall find-ts (line-end-position) nil)))
15810 (if (= (length ts) 2) (setq props (nconc ts props))
15811 (forward-line)
15812 ;; Then find timestamps in the section, skipping
15813 ;; planning line.
15814 (when (org-looking-at-p org-planning-line-re)
15815 (forward-line))
15816 (let ((end (save-excursion (outline-next-heading))))
15817 (setq props (nconc (funcall find-ts end ts) props))))))))
15818 ;; Get the standard properties, like :PROP:.
15819 (when (memq which '(nil all standard))
15820 ;; If we are looking after a specific property, delegate
15821 ;; to `org-entry-get', which is faster. However, make an
15822 ;; exception for "CATEGORY", since it can be also set
15823 ;; through keywords (i.e. #+CATEGORY).
15824 (if (and specific (not (equal specific "CATEGORY")))
15825 (let ((value (org-entry-get beg specific nil t)))
15826 (throw 'exit (and value (list (cons specific value)))))
15827 (let ((range (org-get-property-block beg)))
15828 (when range
15829 (let ((end (cdr range)) seen-base)
15830 (goto-char (car range))
15831 ;; Unlike to `org--update-property-plist', we
15832 ;; handle the case where base values is found
15833 ;; after its extension. We also forbid standard
15834 ;; properties to be named as special properties.
15835 (while (re-search-forward org-property-re end t)
15836 (let* ((key (upcase (org-match-string-no-properties 2)))
15837 (extendp (org-string-match-p "\\+\\'" key))
15838 (key-base (if extendp (substring key 0 -1) key))
15839 (value (org-match-string-no-properties 3)))
15840 (cond
15841 ((member-ignore-case key-base org-special-properties))
15842 (extendp
15843 (setq props
15844 (org--update-property-plist key value props)))
15845 ((member key seen-base))
15846 (t (push key seen-base)
15847 (let ((p (assoc-string key props t)))
15848 (if p (setcdr p (concat value " " (cdr p)))
15849 (push (cons key value) props))))))))))))
15850 (unless (assoc "CATEGORY" props)
15851 (push (cons "CATEGORY" (org-get-category beg)) props)
15852 (when (string= specific "CATEGORY") (throw 'exit props)))
15853 ;; Return value.
15854 props)))))
15856 (defun org-property--local-values (property literal-nil)
15857 "Return value for PROPERTY in current entry.
15858 Value is a list whose car is the base value for PROPERTY and cdr
15859 a list of accumulated values. Return nil if neither is found in
15860 the entry. Also return nil when PROPERTY is set to \"nil\",
15861 unless LITERAL-NIL is non-nil."
15862 (let ((range (org-get-property-block)))
15863 (when range
15864 (goto-char (car range))
15865 (let* ((case-fold-search t)
15866 (end (cdr range))
15867 (value
15868 ;; Base value.
15869 (save-excursion
15870 (let ((v (and (re-search-forward
15871 (org-re-property property nil t) end t)
15872 (org-match-string-no-properties 3))))
15873 (list (if literal-nil v (org-not-nil v)))))))
15874 ;; Find additional values.
15875 (let* ((property+ (org-re-property (concat property "+") nil t)))
15876 (while (re-search-forward property+ end t)
15877 (push (org-match-string-no-properties 3) value)))
15878 ;; Return final values.
15879 (and (not (equal value '(nil))) (nreverse value))))))
15881 (defun org-entry-get (pom property &optional inherit literal-nil)
15882 "Get value of PROPERTY for entry or content at point-or-marker POM.
15884 If INHERIT is non-nil and the entry does not have the property,
15885 then also check higher levels of the hierarchy. If INHERIT is
15886 the symbol `selective', use inheritance only if the setting in
15887 `org-use-property-inheritance' selects PROPERTY for inheritance.
15889 If the property is present but empty, the return value is the
15890 empty string. If the property is not present at all, nil is
15891 returned. In any other case, return the value as a string.
15892 Search is case-insensitive.
15894 If LITERAL-NIL is set, return the string value \"nil\" as
15895 a string, do not interpret it as the list atom nil. This is used
15896 for inheritance when a \"nil\" value can supersede a non-nil
15897 value higher up the hierarchy."
15898 (org-with-point-at pom
15899 (cond
15900 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15901 ;; We need a special property. Use `org-entry-properties' to
15902 ;; retrieve it, but specify the wanted property.
15903 (cdr (assoc-string property (org-entry-properties nil property))))
15904 ((and inherit
15905 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15906 (org-entry-get-with-inheritance property literal-nil))
15908 (let* ((local (org-property--local-values property literal-nil))
15909 (value (and local (mapconcat #'identity (delq nil local) " "))))
15910 (if literal-nil value (org-not-nil value)))))))
15912 (defun org-property-or-variable-value (var &optional inherit)
15913 "Check if there is a property fixing the value of VAR.
15914 If yes, return this value. If not, return the current value of the variable."
15915 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15916 (if (and prop (stringp prop) (string-match "\\S-" prop))
15917 (read prop)
15918 (symbol-value var))))
15920 (defun org-entry-delete (pom property)
15921 "Delete PROPERTY from entry at point-or-marker POM.
15922 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15923 non-nil when a property was removed."
15924 (unless (member property org-special-properties)
15925 (org-with-point-at pom
15926 (let ((range (org-get-property-block)))
15927 (when range
15928 (let* ((begin (car range))
15929 (origin (cdr range))
15930 (end (copy-marker origin))
15931 (re (org-re-property
15932 (concat (regexp-quote property) "\\+?") t t)))
15933 (goto-char begin)
15934 (while (re-search-forward re end t)
15935 (delete-region (match-beginning 0) (line-beginning-position 2)))
15936 ;; If drawer is empty, remove it altogether.
15937 (when (= begin end)
15938 (delete-region (line-beginning-position 0)
15939 (line-beginning-position 2)))
15940 ;; Return non-nil if some property was removed.
15941 (prog1 (/= end origin) (set-marker end nil))))))))
15943 ;; Multi-values properties are properties that contain multiple values
15944 ;; These values are assumed to be single words, separated by whitespace.
15945 (defun org-entry-add-to-multivalued-property (pom property value)
15946 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15947 (let* ((old (org-entry-get pom property))
15948 (values (and old (org-split-string old "[ \t]"))))
15949 (setq value (org-entry-protect-space value))
15950 (unless (member value values)
15951 (setq values (append values (list value)))
15952 (org-entry-put pom property
15953 (mapconcat 'identity values " ")))))
15955 (defun org-entry-remove-from-multivalued-property (pom property value)
15956 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15957 (let* ((old (org-entry-get pom property))
15958 (values (and old (org-split-string old "[ \t]"))))
15959 (setq value (org-entry-protect-space value))
15960 (when (member value values)
15961 (setq values (delete value values))
15962 (org-entry-put pom property
15963 (mapconcat 'identity values " ")))))
15965 (defun org-entry-member-in-multivalued-property (pom property value)
15966 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15967 (let* ((old (org-entry-get pom property))
15968 (values (and old (org-split-string old "[ \t]"))))
15969 (setq value (org-entry-protect-space value))
15970 (member value values)))
15972 (defun org-entry-get-multivalued-property (pom property)
15973 "Return a list of values in a multivalued property."
15974 (let* ((value (org-entry-get pom property))
15975 (values (and value (org-split-string value "[ \t]"))))
15976 (mapcar 'org-entry-restore-space values)))
15978 (defun org-entry-put-multivalued-property (pom property &rest values)
15979 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15980 VALUES should be a list of strings. Spaces will be protected."
15981 (org-entry-put pom property
15982 (mapconcat 'org-entry-protect-space values " "))
15983 (let* ((value (org-entry-get pom property))
15984 (values (and value (org-split-string value "[ \t]"))))
15985 (mapcar 'org-entry-restore-space values)))
15987 (defun org-entry-protect-space (s)
15988 "Protect spaces and newline in string S."
15989 (while (string-match " " s)
15990 (setq s (replace-match "%20" t t s)))
15991 (while (string-match "\n" s)
15992 (setq s (replace-match "%0A" t t s)))
15995 (defun org-entry-restore-space (s)
15996 "Restore spaces and newline in string S."
15997 (while (string-match "%20" s)
15998 (setq s (replace-match " " t t s)))
15999 (while (string-match "%0A" s)
16000 (setq s (replace-match "\n" t t s)))
16003 (defvar org-entry-property-inherited-from (make-marker)
16004 "Marker pointing to the entry from where a property was inherited.
16005 Each call to `org-entry-get-with-inheritance' will set this marker to the
16006 location of the entry where the inheritance search matched. If there was
16007 no match, the marker will point nowhere.
16008 Note that also `org-entry-get' calls this function, if the INHERIT flag
16009 is set.")
16011 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16012 "Get PROPERTY of entry or content at point, search higher levels if needed.
16013 The search will stop at the first ancestor which has the property defined.
16014 If the value found is \"nil\", return nil to show that the property
16015 should be considered as undefined (this is the meaning of nil here).
16016 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16017 (move-marker org-entry-property-inherited-from nil)
16018 (org-with-wide-buffer
16019 (let (value)
16020 (catch 'exit
16021 (while t
16022 (let ((v (org-property--local-values property literal-nil)))
16023 (when v
16024 (setq value
16025 (concat (mapconcat #'identity (delq nil v) " ")
16026 (and value " ")
16027 value)))
16028 (cond
16029 ((car v)
16030 (org-back-to-heading t)
16031 (move-marker org-entry-property-inherited-from (point))
16032 (throw 'exit nil))
16033 ((org-up-heading-safe))
16035 (let ((global
16036 (cdr (or (assoc-string property org-file-properties t)
16037 (assoc-string property org-global-properties t)
16038 (assoc-string property org-global-properties-fixed t)))))
16039 (cond ((not global))
16040 (value (setq value (concat global " " value)))
16041 (t (setq value global))))
16042 (throw 'exit nil))))))
16043 (if literal-nil value (org-not-nil value)))))
16045 (defvar org-property-changed-functions nil
16046 "Hook called when the value of a property has changed.
16047 Each hook function should accept two arguments, the name of the property
16048 and the new value.")
16050 (defun org-entry-put (pom property value)
16051 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16053 If the value is nil, it is converted to the empty string. If it
16054 is not a string, an error is raised. Also raise an error on
16055 invalid property names.
16057 PROPERTY can be any regular property (see
16058 `org-special-properties'). It can also be \"TODO\",
16059 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16061 For the last two properties, VALUE may have any of the special
16062 values \"earlier\" and \"later\". The function then increases or
16063 decreases scheduled or deadline date by one day."
16064 (cond ((null value) (setq value ""))
16065 ((not (stringp value)) (error "Properties values should be strings"))
16066 ((not (org--valid-property-p property))
16067 (user-error "Invalid property name: \"%s\"" property)))
16068 (org-with-point-at pom
16069 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16070 (org-back-to-heading t)
16071 (org-with-limited-levels (org-back-to-heading t)))
16072 (let ((beg (point)))
16073 (cond
16074 ((equal property "TODO")
16075 (cond ((not (org-string-nw-p value)) (setq value 'none))
16076 ((not (member value org-todo-keywords-1))
16077 (user-error "\"%s\" is not a valid TODO state" value)))
16078 (org-todo value)
16079 (org-set-tags nil 'align))
16080 ((equal property "PRIORITY")
16081 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16082 (org-set-tags nil 'align))
16083 ((equal property "SCHEDULED")
16084 (forward-line)
16085 (if (and (org-looking-at-p org-planning-line-re)
16086 (re-search-forward
16087 org-scheduled-time-regexp (line-end-position) t))
16088 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16089 ((string= value "later") (org-timestamp-change 1 'day))
16090 ((string= value "") (org-schedule '(4)))
16091 (t (org-schedule nil value)))
16092 (if (member value '("earlier" "later" ""))
16093 (call-interactively #'org-schedule)
16094 (org-schedule nil value))))
16095 ((equal property "DEADLINE")
16096 (forward-line)
16097 (if (and (org-looking-at-p org-planning-line-re)
16098 (re-search-forward
16099 org-deadline-time-regexp (line-end-position) t))
16100 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16101 ((string= value "later") (org-timestamp-change 1 'day))
16102 ((string= value "") (org-deadline '(4)))
16103 (t (org-deadline nil value)))
16104 (if (member value '("earlier" "later" ""))
16105 (call-interactively #'org-deadline)
16106 (org-deadline nil value))))
16107 ((member property org-special-properties)
16108 (error "The %s property cannot be set with `org-entry-put'" property))
16110 (let* ((range (org-get-property-block beg 'force))
16111 (end (cdr range))
16112 (case-fold-search t))
16113 (goto-char (car range))
16114 (if (re-search-forward (org-re-property property nil t) end t)
16115 (progn (delete-region (match-beginning 0) (match-end 0))
16116 (goto-char (match-beginning 0)))
16117 (goto-char end)
16118 (insert "\n")
16119 (backward-char))
16120 (insert ":" property ":")
16121 (when value (insert " " value))
16122 (org-indent-line)))))
16123 (run-hook-with-args 'org-property-changed-functions property value)))
16125 (defun org-buffer-property-keys
16126 (&optional specials defaults columns ignore-malformed)
16127 "Get all property keys in the current buffer.
16129 When SPECIALS is non-nil, also list the special properties that
16130 reflect things like tags and TODO state.
16132 When DEFAULTS is non-nil, also include properties that has
16133 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16134 DESCRIPTION, LOCATION, and LOGGING and others.
16136 When COLUMNS in non-nil, also include property names given in
16137 COLUMN formats in the current buffer.
16139 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16140 automatically performed, such drawers will be silently ignored."
16141 (let ((case-fold-search t)
16142 (props (append
16143 (and specials org-special-properties)
16144 (and defaults (cons org-effort-property org-default-properties))
16145 nil)))
16146 (org-with-wide-buffer
16147 (goto-char (point-min))
16148 (while (re-search-forward org-property-start-re nil t)
16149 (let ((range (org-get-property-block)))
16150 (catch 'skip
16151 (unless range
16152 (when (and (not ignore-malformed)
16153 (not (org-before-first-heading-p))
16154 (y-or-n-p (format "Malformed drawer at %d, repair?"
16155 (line-beginning-position))))
16156 (org-get-property-block nil t))
16157 (throw 'skip nil))
16158 (goto-char (car range))
16159 (let ((begin (car range))
16160 (end (cdr range)))
16161 ;; Make sure that found property block is not located
16162 ;; before current point, as it would generate an infloop.
16163 ;; It can happen, for example, in the following
16164 ;; situation:
16166 ;; * Headline
16167 ;; :PROPERTIES:
16168 ;; ...
16169 ;; :END:
16170 ;; *************** Inlinetask
16171 ;; #+BEGIN_EXAMPLE
16172 ;; :PROPERTIES:
16173 ;; #+END_EXAMPLE
16175 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16176 (while (< (point) end)
16177 (let ((p (progn (looking-at org-property-re)
16178 (org-match-string-no-properties 2))))
16179 ;; Only add true property name, not extension symbol.
16180 (push (if (not (org-string-match-p "\\+\\'" p)) p
16181 (substring p 0 -1))
16182 props))
16183 (forward-line))))
16184 (outline-next-heading)))
16185 (when columns
16186 (goto-char (point-min))
16187 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16188 (let ((element (org-element-at-point)))
16189 (when (memq (org-element-type element) '(keyword node-property))
16190 (let ((value (org-element-property :value element))
16191 (start 0))
16192 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16193 (setq start (match-end 0))
16194 (let ((p (org-match-string-no-properties 1 value)))
16195 (unless (member-ignore-case p org-special-properties)
16196 (push p props))))))))))
16197 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16199 (defun org-property-values (key)
16200 "List all non-nil values of property KEY in current buffer."
16201 (org-with-wide-buffer
16202 (goto-char (point-min))
16203 (let ((case-fold-search t)
16204 (re (org-re-property key))
16205 values)
16206 (while (re-search-forward re nil t)
16207 (push (org-entry-get (point) key) values))
16208 (delete-dups values))))
16210 (defun org-insert-property-drawer ()
16211 "Insert a property drawer into the current entry."
16212 (org-with-wide-buffer
16213 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16214 (org-back-to-heading t)
16215 (org-with-limited-levels (org-back-to-heading t)))
16216 (forward-line)
16217 (when (org-looking-at-p org-planning-line-re) (forward-line))
16218 (unless (org-looking-at-p org-property-drawer-re)
16219 ;; Make sure we start editing a line from current entry, not from
16220 ;; next one. It prevents extending text properties or overlays
16221 ;; belonging to the latter.
16222 (when (bolp) (backward-char))
16223 (let ((begin (1+ (point)))
16224 (inhibit-read-only t))
16225 (insert "\n:PROPERTIES:\n:END:")
16226 (when (eobp) (insert "\n"))
16227 (org-indent-region begin (point))))))
16229 (defun org-insert-drawer (&optional arg drawer)
16230 "Insert a drawer at point.
16232 When optional argument ARG is non-nil, insert a property drawer.
16234 Optional argument DRAWER, when non-nil, is a string representing
16235 drawer's name. Otherwise, the user is prompted for a name.
16237 If a region is active, insert the drawer around that region
16238 instead.
16240 Point is left between drawer's boundaries."
16241 (interactive "P")
16242 (let* ((drawer (if arg "PROPERTIES"
16243 (or drawer (read-from-minibuffer "Drawer: ")))))
16244 (cond
16245 ;; With C-u, fall back on `org-insert-property-drawer'
16246 (arg (org-insert-property-drawer))
16247 ;; Check validity of suggested drawer's name.
16248 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16249 (user-error "Invalid drawer name"))
16250 ;; With an active region, insert a drawer at point.
16251 ((not (org-region-active-p))
16252 (progn
16253 (unless (bolp) (insert "\n"))
16254 (insert (format ":%s:\n\n:END:\n" drawer))
16255 (forward-line -2)))
16256 ;; Otherwise, insert the drawer at point
16258 (let ((rbeg (region-beginning))
16259 (rend (copy-marker (region-end))))
16260 (unwind-protect
16261 (progn
16262 (goto-char rbeg)
16263 (beginning-of-line)
16264 (when (save-excursion
16265 (re-search-forward org-outline-regexp-bol rend t))
16266 (user-error "Drawers cannot contain headlines"))
16267 ;; Position point at the beginning of the first
16268 ;; non-blank line in region. Insert drawer's opening
16269 ;; there, then indent it.
16270 (org-skip-whitespace)
16271 (beginning-of-line)
16272 (insert ":" drawer ":\n")
16273 (forward-line -1)
16274 (indent-for-tab-command)
16275 ;; Move point to the beginning of the first blank line
16276 ;; after the last non-blank line in region. Insert
16277 ;; drawer's closing, then indent it.
16278 (goto-char rend)
16279 (skip-chars-backward " \r\t\n")
16280 (insert "\n:END:")
16281 (deactivate-mark t)
16282 (indent-for-tab-command)
16283 (unless (eolp) (insert "\n")))
16284 ;; Clear marker, whatever the outcome of insertion is.
16285 (set-marker rend nil)))))))
16287 (defvar org-property-set-functions-alist nil
16288 "Property set function alist.
16289 Each entry should have the following format:
16291 (PROPERTY . READ-FUNCTION)
16293 The read function will be called with the same argument as
16294 `org-completing-read'.")
16296 (defun org-set-property-function (property)
16297 "Get the function that should be used to set PROPERTY.
16298 This is computed according to `org-property-set-functions-alist'."
16299 (or (cdr (assoc property org-property-set-functions-alist))
16300 'org-completing-read))
16302 (defun org-read-property-value (property)
16303 "Read PROPERTY value from user."
16304 (let* ((completion-ignore-case t)
16305 (allowed (org-property-get-allowed-values nil property 'table))
16306 (cur (org-entry-get nil property))
16307 (prompt (concat property " value"
16308 (if (and cur (string-match "\\S-" cur))
16309 (concat " [" cur "]") "") ": "))
16310 (set-function (org-set-property-function property))
16311 (val (if allowed
16312 (funcall set-function prompt allowed nil
16313 (not (get-text-property 0 'org-unrestricted
16314 (caar allowed))))
16315 (funcall set-function prompt
16316 (mapcar 'list (org-property-values property))
16317 nil nil "" nil cur))))
16318 (org-trim val)))
16320 (defvar org-last-set-property nil)
16321 (defvar org-last-set-property-value nil)
16322 (defun org-read-property-name ()
16323 "Read a property name."
16324 (let ((completion-ignore-case t)
16325 (default-prop (or (and (org-at-property-p)
16326 (org-match-string-no-properties 2))
16327 org-last-set-property)))
16328 (org-completing-read
16329 (concat "Property"
16330 (if default-prop (concat " [" default-prop "]") "")
16331 ": ")
16332 (mapcar #'list (org-buffer-property-keys nil t t))
16333 nil nil nil nil default-prop)))
16335 (defun org-set-property-and-value (use-last)
16336 "Allow to set [PROPERTY]: [value] direction from prompt.
16337 When use-default, don't even ask, just use the last
16338 \"[PROPERTY]: [value]\" string from the history."
16339 (interactive "P")
16340 (let* ((completion-ignore-case t)
16341 (pv (or (and use-last org-last-set-property-value)
16342 (org-completing-read
16343 "Enter a \"[Property]: [value]\" pair: "
16344 nil nil nil nil nil
16345 org-last-set-property-value)))
16346 prop val)
16347 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16348 (setq prop (match-string 1 pv)
16349 val (match-string 2 pv))
16350 (org-set-property prop val))))
16352 (defun org-set-property (property value)
16353 "In the current entry, set PROPERTY to VALUE.
16355 When called interactively, this will prompt for a property name, offering
16356 completion on existing and default properties. And then it will prompt
16357 for a value, offering completion either on allowed values (via an inherited
16358 xxx_ALL property) or on existing values in other instances of this property
16359 in the current file.
16361 Throw an error when trying to set a property with an invalid name."
16362 (interactive (list nil nil))
16363 (let ((property (or property (org-read-property-name))))
16364 ;; `org-entry-put' also makes the following check, but this one
16365 ;; avoids polluting `org-last-set-property' and
16366 ;; `org-last-set-property-value' needlessly.
16367 (unless (org--valid-property-p property)
16368 (user-error "Invalid property name: \"%s\"" property))
16369 (let ((value (or value (org-read-property-value property)))
16370 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16371 (setq org-last-set-property property)
16372 (setq org-last-set-property-value (concat property ": " value))
16373 ;; Possibly postprocess the inserted value:
16374 (when fn (setq value (funcall fn value)))
16375 (unless (equal (org-entry-get nil property) value)
16376 (org-entry-put nil property value)))))
16378 (defun org-find-property (property &optional value)
16379 "Find first entry in buffer that sets PROPERTY.
16381 When optional argument VALUE is non-nil, only consider an entry
16382 if it contains PROPERTY set to this value. If PROPERTY should be
16383 explicitly set to nil, use string \"nil\" for VALUE.
16385 Return position where the entry begins, or nil if there is no
16386 such entry. If narrowing is in effect, only search the visible
16387 part of the buffer."
16388 (save-excursion
16389 (goto-char (point-min))
16390 (let ((case-fold-search t)
16391 (re (org-re-property property nil (not value) value)))
16392 (catch 'exit
16393 (while (re-search-forward re nil t)
16394 (when (if value (org-at-property-p)
16395 (org-entry-get (point) property nil t))
16396 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16398 (defun org-delete-property (property)
16399 "In the current entry, delete PROPERTY."
16400 (interactive
16401 (let* ((completion-ignore-case t)
16402 (cat (org-entry-get (point) "CATEGORY"))
16403 (props0 (org-entry-properties nil 'standard))
16404 (props (if cat props0
16405 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16406 (prop (if (< 1 (length props))
16407 (completing-read "Property: " props nil t)
16408 (caar props))))
16409 (list prop)))
16410 (if (not property)
16411 (message "No property to delete in this entry")
16412 (org-entry-delete nil property)
16413 (message "Property \"%s\" deleted" property)))
16415 (defun org-delete-property-globally (property)
16416 "Remove PROPERTY globally, from all entries.
16417 This function ignores narrowing, if any."
16418 (interactive
16419 (let* ((completion-ignore-case t)
16420 (prop (completing-read
16421 "Globally remove property: "
16422 (mapcar #'list (org-buffer-property-keys)))))
16423 (list prop)))
16424 (org-with-wide-buffer
16425 (goto-char (point-min))
16426 (let ((count 0)
16427 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16428 (while (re-search-forward re nil t)
16429 (when (org-entry-delete (point) property) (cl-incf count)))
16430 (message "Property \"%s\" removed from %d entries" property count))))
16432 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16434 (defun org-compute-property-at-point ()
16435 "Compute the property at point.
16436 This looks for an enclosing column format, extracts the operator and
16437 then applies it to the property in the column format's scope."
16438 (interactive)
16439 (unless (org-at-property-p)
16440 (user-error "Not at a property"))
16441 (let ((prop (org-match-string-no-properties 2)))
16442 (org-columns-get-format-and-top-level)
16443 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16444 (user-error "No operator defined for property %s" prop))
16445 (org-columns-compute prop)))
16447 (defvar org-property-allowed-value-functions nil
16448 "Hook for functions supplying allowed values for a specific property.
16449 The functions must take a single argument, the name of the property, and
16450 return a flat list of allowed values. If \":ETC\" is one of
16451 the values, this means that these values are intended as defaults for
16452 completion, but that other values should be allowed too.
16453 The functions must return nil if they are not responsible for this
16454 property.")
16456 (defun org-property-get-allowed-values (pom property &optional table)
16457 "Get allowed values for the property PROPERTY.
16458 When TABLE is non-nil, return an alist that can directly be used for
16459 completion."
16460 (let (vals)
16461 (cond
16462 ((equal property "TODO")
16463 (setq vals (org-with-point-at pom
16464 (append org-todo-keywords-1 '("")))))
16465 ((equal property "PRIORITY")
16466 (let ((n org-lowest-priority))
16467 (while (>= n org-highest-priority)
16468 (push (char-to-string n) vals)
16469 (setq n (1- n)))))
16470 ((equal property "CATEGORY"))
16471 ((member property org-special-properties))
16472 ((setq vals (run-hook-with-args-until-success
16473 'org-property-allowed-value-functions property)))
16475 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16476 (when (and vals (string-match "\\S-" vals))
16477 (setq vals (car (read-from-string (concat "(" vals ")"))))
16478 (setq vals (mapcar (lambda (x)
16479 (cond ((stringp x) x)
16480 ((numberp x) (number-to-string x))
16481 ((symbolp x) (symbol-name x))
16482 (t "???")))
16483 vals)))))
16484 (when (member ":ETC" vals)
16485 (setq vals (remove ":ETC" vals))
16486 (org-add-props (car vals) '(org-unrestricted t)))
16487 (if table (mapcar 'list vals) vals)))
16489 (defun org-property-previous-allowed-value (&optional _previous)
16490 "Switch to the next allowed value for this property."
16491 (interactive)
16492 (org-property-next-allowed-value t))
16494 (defun org-property-next-allowed-value (&optional previous)
16495 "Switch to the next allowed value for this property."
16496 (interactive)
16497 (unless (org-at-property-p)
16498 (user-error "Not at a property"))
16499 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16500 (key (match-string 2))
16501 (value (match-string 3))
16502 (allowed (or (org-property-get-allowed-values (point) key)
16503 (and (member value '("[ ]" "[-]" "[X]"))
16504 '("[ ]" "[X]"))))
16505 (heading (save-match-data (nth 4 (org-heading-components))))
16506 nval)
16507 (unless allowed
16508 (user-error "Allowed values for this property have not been defined"))
16509 (when previous (setq allowed (reverse allowed)))
16510 (when (member value allowed)
16511 (setq nval (car (cdr (member value allowed)))))
16512 (setq nval (or nval (car allowed)))
16513 (when (equal nval value)
16514 (user-error "Only one allowed value for this property"))
16515 (org-at-property-p)
16516 (replace-match (concat " :" key ": " nval) t t)
16517 (org-indent-line)
16518 (beginning-of-line 1)
16519 (skip-chars-forward " \t")
16520 (when (equal prop org-effort-property)
16521 (org-refresh-property
16522 '((effort . identity)
16523 (effort-minutes . org-duration-string-to-minutes))
16524 nval)
16525 (when (string= org-clock-current-task heading)
16526 (setq org-clock-effort nval)
16527 (org-clock-update-mode-line)))
16528 (run-hook-with-args 'org-property-changed-functions key nval)))
16530 (defun org-find-olp (path &optional this-buffer)
16531 "Return a marker pointing to the entry at outline path OLP.
16532 If anything goes wrong, throw an error.
16533 You can wrap this call to catch the error like this:
16535 \(condition-case msg
16536 \(org-mobile-locate-entry (match-string 4))
16537 \(error (nth 1 msg)))
16539 The return value will then be either a string with the error message,
16540 or a marker if everything is OK.
16542 If THIS-BUFFER is set, the outline path does not contain a file,
16543 only headings."
16544 (let* ((file (if this-buffer buffer-file-name (pop path)))
16545 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16546 (level 1)
16547 (lmin 1)
16548 (lmax 1)
16549 end found flevel)
16550 (unless buffer (error "File not found :%s" file))
16551 (with-current-buffer buffer
16552 (org-with-wide-buffer
16553 (goto-char (point-min))
16554 (dolist (heading path)
16555 (let ((re (format org-complex-heading-regexp-format
16556 (regexp-quote heading)))
16557 (cnt 0))
16558 (while (re-search-forward re end t)
16559 (setq level (- (match-end 1) (match-beginning 1)))
16560 (when (and (>= level lmin) (<= level lmax))
16561 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16562 (when (= cnt 0)
16563 (error "Heading not found on level %d: %s" lmax heading))
16564 (when (> cnt 1)
16565 (error "Heading not unique on level %d: %s" lmax heading))
16566 (goto-char found)
16567 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16568 (setq end (save-excursion (org-end-of-subtree t t)))))
16569 (when (org-at-heading-p)
16570 (point-marker))))))
16572 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16573 "Find node HEADING in BUFFER.
16574 Return a marker to the heading if it was found, or nil if not.
16575 If POS-ONLY is set, return just the position instead of a marker.
16577 The heading text must match exact, but it may have a TODO keyword,
16578 a priority cookie and tags in the standard locations."
16579 (with-current-buffer (or buffer (current-buffer))
16580 (save-excursion
16581 (save-restriction
16582 (widen)
16583 (goto-char (point-min))
16584 (let (case-fold-search)
16585 (when (re-search-forward
16586 (format org-complex-heading-regexp-format
16587 (regexp-quote heading)) nil t)
16588 (if pos-only
16589 (match-beginning 0)
16590 (move-marker (make-marker) (match-beginning 0)))))))))
16592 (defun org-find-exact-heading-in-directory (heading &optional dir)
16593 "Find Org node headline HEADING in all .org files in directory DIR.
16594 When the target headline is found, return a marker to this location."
16595 (let ((files (directory-files (or dir default-directory)
16596 t "\\`[^.#].*\\.org\\'"))
16597 visiting m buffer)
16598 (catch 'found
16599 (dolist (file files)
16600 (message "trying %s" file)
16601 (setq visiting (org-find-base-buffer-visiting file))
16602 (setq buffer (or visiting (find-file-noselect file)))
16603 (setq m (org-find-exact-headline-in-buffer
16604 heading buffer))
16605 (when (and (not m) (not visiting)) (kill-buffer buffer))
16606 (and m (throw 'found m))))))
16608 (defun org-find-entry-with-id (ident)
16609 "Locate the entry that contains the ID property with exact value IDENT.
16610 IDENT can be a string, a symbol or a number, this function will search for
16611 the string representation of it.
16612 Return the position where this entry starts, or nil if there is no such entry."
16613 (interactive "sID: ")
16614 (let ((id (cond
16615 ((stringp ident) ident)
16616 ((symbolp ident) (symbol-name ident))
16617 ((numberp ident) (number-to-string ident))
16618 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16619 (org-with-wide-buffer (org-find-property "ID" id))))
16621 ;;;; Timestamps
16623 (defvar org-last-changed-timestamp nil)
16624 (defvar org-last-inserted-timestamp nil
16625 "The last time stamp inserted with `org-insert-time-stamp'.")
16626 (defvar org-ts-what) ; dynamically scoped parameter
16628 (defun org-time-stamp (arg &optional inactive)
16629 "Prompt for a date/time and insert a time stamp.
16631 If the user specifies a time like HH:MM or if this command is
16632 called with at least one prefix argument, the time stamp contains
16633 the date and the time. Otherwise, only the date is included.
16635 All parts of a date not specified by the user are filled in from
16636 the timestamp at point, if any, or the current date/time
16637 otherwise.
16639 If there is already a timestamp at the cursor, it is replaced.
16641 With two universal prefix arguments, insert an active timestamp
16642 with the current time without prompting the user.
16644 When called from lisp, the timestamp is inactive if INACTIVE is
16645 non-nil."
16646 (interactive "P")
16647 (let* ((ts (cond
16648 ((org-at-date-range-p t)
16649 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16650 ((org-at-timestamp-p t) (match-string 0))))
16651 ;; Default time is either the timestamp at point or today.
16652 ;; When entering a range, only the range start is considered.
16653 (default-time (if (not ts) (current-time)
16654 (apply #'encode-time (org-parse-time-string ts))))
16655 (default-input (and ts (org-get-compact-tod ts)))
16656 (repeater (and ts
16657 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16658 (match-string 0 ts)))
16659 org-time-was-given
16660 org-end-time-was-given
16661 (time
16662 (and (if (equal arg '(16)) (current-time)
16663 ;; Preserve `this-command' and `last-command'.
16664 (let ((this-command this-command)
16665 (last-command last-command))
16666 (org-read-date
16667 arg 'totime nil nil default-time default-input
16668 inactive))))))
16669 (cond
16670 ((and ts
16671 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16672 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16673 (insert "--")
16674 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16676 ;; Make sure we're on a timestamp. When in the middle of a date
16677 ;; range, move arbitrarily to range end.
16678 (unless (org-at-timestamp-p t)
16679 (skip-chars-forward "-")
16680 (org-at-timestamp-p t))
16681 (replace-match "")
16682 (setq org-last-changed-timestamp
16683 (org-insert-time-stamp
16684 time (or org-time-was-given arg)
16685 inactive nil nil (list org-end-time-was-given)))
16686 (when repeater
16687 (backward-char)
16688 (insert " " repeater)
16689 (setq org-last-changed-timestamp
16690 (concat (substring org-last-inserted-timestamp 0 -1)
16691 " " repeater ">")))
16692 (message "Timestamp updated"))
16693 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16694 (t (org-insert-time-stamp
16695 time (or org-time-was-given arg) inactive nil nil
16696 (list org-end-time-was-given))))))
16698 ;; FIXME: can we use this for something else, like computing time differences?
16699 (defun org-get-compact-tod (s)
16700 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16701 (let* ((t1 (match-string 1 s))
16702 (h1 (string-to-number (match-string 2 s)))
16703 (m1 (string-to-number (match-string 3 s)))
16704 (t2 (and (match-end 4) (match-string 5 s)))
16705 (h2 (and t2 (string-to-number (match-string 6 s))))
16706 (m2 (and t2 (string-to-number (match-string 7 s))))
16707 dh dm)
16708 (if (not t2)
16710 (setq dh (- h2 h1) dm (- m2 m1))
16711 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16712 (concat t1 "+" (number-to-string dh)
16713 (and (/= 0 dm) (format ":%02d" dm)))))))
16715 (defun org-time-stamp-inactive (&optional arg)
16716 "Insert an inactive time stamp.
16717 An inactive time stamp is enclosed in square brackets instead of angle
16718 brackets. It is inactive in the sense that it does not trigger agenda entries,
16719 does not link to the calendar and cannot be changed with the S-cursor keys.
16720 So these are more for recording a certain time/date."
16721 (interactive "P")
16722 (org-time-stamp arg 'inactive))
16724 (defvar org-date-ovl (make-overlay 1 1))
16725 (overlay-put org-date-ovl 'face 'org-date-selected)
16726 (org-detach-overlay org-date-ovl)
16728 (defvar org-ans1) ; dynamically scoped parameter
16729 (defvar org-ans2) ; dynamically scoped parameter
16731 (defvar org-plain-time-of-day-regexp) ; defined below
16733 (defvar org-overriding-default-time nil) ; dynamically scoped
16734 (defvar org-read-date-overlay nil)
16735 (defvar org-dcst nil) ; dynamically scoped
16736 (defvar org-read-date-history nil)
16737 (defvar org-read-date-final-answer nil)
16738 (defvar org-read-date-analyze-futurep nil)
16739 (defvar org-read-date-analyze-forced-year nil)
16740 (defvar org-read-date-inactive)
16742 (defvar org-read-date-minibuffer-local-map
16743 (let* ((map (make-sparse-keymap)))
16744 (set-keymap-parent map minibuffer-local-map)
16745 (org-defkey map (kbd ".")
16746 (lambda () (interactive)
16747 ;; Are we at the beginning of the prompt?
16748 (if (org-looking-back "^[^:]+: "
16749 (let ((inhibit-field-text-motion t))
16750 (line-beginning-position)))
16751 (org-eval-in-calendar '(calendar-goto-today))
16752 (insert "."))))
16753 (org-defkey map (kbd "C-.")
16754 (lambda () (interactive)
16755 (org-eval-in-calendar '(calendar-goto-today))))
16756 (org-defkey map [(meta shift left)]
16757 (lambda () (interactive)
16758 (org-eval-in-calendar '(calendar-backward-month 1))))
16759 (org-defkey map [(meta shift right)]
16760 (lambda () (interactive)
16761 (org-eval-in-calendar '(calendar-forward-month 1))))
16762 (org-defkey map [(meta shift up)]
16763 (lambda () (interactive)
16764 (org-eval-in-calendar '(calendar-backward-year 1))))
16765 (org-defkey map [(meta shift down)]
16766 (lambda () (interactive)
16767 (org-eval-in-calendar '(calendar-forward-year 1))))
16768 (org-defkey map [?\e (shift left)]
16769 (lambda () (interactive)
16770 (org-eval-in-calendar '(calendar-backward-month 1))))
16771 (org-defkey map [?\e (shift right)]
16772 (lambda () (interactive)
16773 (org-eval-in-calendar '(calendar-forward-month 1))))
16774 (org-defkey map [?\e (shift up)]
16775 (lambda () (interactive)
16776 (org-eval-in-calendar '(calendar-backward-year 1))))
16777 (org-defkey map [?\e (shift down)]
16778 (lambda () (interactive)
16779 (org-eval-in-calendar '(calendar-forward-year 1))))
16780 (org-defkey map [(shift up)]
16781 (lambda () (interactive)
16782 (org-eval-in-calendar '(calendar-backward-week 1))))
16783 (org-defkey map [(shift down)]
16784 (lambda () (interactive)
16785 (org-eval-in-calendar '(calendar-forward-week 1))))
16786 (org-defkey map [(shift left)]
16787 (lambda () (interactive)
16788 (org-eval-in-calendar '(calendar-backward-day 1))))
16789 (org-defkey map [(shift right)]
16790 (lambda () (interactive)
16791 (org-eval-in-calendar '(calendar-forward-day 1))))
16792 (org-defkey map "!"
16793 (lambda () (interactive)
16794 (org-eval-in-calendar '(diary-view-entries))
16795 (message "")))
16796 (org-defkey map ">"
16797 (lambda () (interactive)
16798 (org-eval-in-calendar '(calendar-scroll-left 1))))
16799 (org-defkey map "<"
16800 (lambda () (interactive)
16801 (org-eval-in-calendar '(calendar-scroll-right 1))))
16802 (org-defkey map "\C-v"
16803 (lambda () (interactive)
16804 (org-eval-in-calendar
16805 '(calendar-scroll-left-three-months 1))))
16806 (org-defkey map "\M-v"
16807 (lambda () (interactive)
16808 (org-eval-in-calendar
16809 '(calendar-scroll-right-three-months 1))))
16810 map)
16811 "Keymap for minibuffer commands when using `org-read-date'.")
16813 (defvar org-def)
16814 (defvar org-defdecode)
16815 (defvar org-with-time)
16817 (defvar calendar-setup) ; Dynamically scoped.
16818 (defun org-read-date (&optional with-time to-time from-string prompt
16819 default-time default-input inactive)
16820 "Read a date, possibly a time, and make things smooth for the user.
16821 The prompt will suggest to enter an ISO date, but you can also enter anything
16822 which will at least partially be understood by `parse-time-string'.
16823 Unrecognized parts of the date will default to the current day, month, year,
16824 hour and minute. If this command is called to replace a timestamp at point,
16825 or to enter the second timestamp of a range, the default time is taken
16826 from the existing stamp. Furthermore, the command prefers the future,
16827 so if you are giving a date where the year is not given, and the day-month
16828 combination is already past in the current year, it will assume you
16829 mean next year. For details, see the manual. A few examples:
16831 3-2-5 --> 2003-02-05
16832 feb 15 --> currentyear-02-15
16833 2/15 --> currentyear-02-15
16834 sep 12 9 --> 2009-09-12
16835 12:45 --> today 12:45
16836 22 sept 0:34 --> currentyear-09-22 0:34
16837 12 --> currentyear-currentmonth-12
16838 Fri --> nearest Friday after today
16839 -Tue --> last Tuesday
16840 etc.
16842 Furthermore you can specify a relative date by giving, as the *first* thing
16843 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16844 change in days weeks, months, years.
16845 With a single plus or minus, the date is relative to today. With a double
16846 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16847 +4d --> four days from today
16848 +4 --> same as above
16849 +2w --> two weeks from today
16850 ++5 --> five days from default date
16852 The function understands only English month and weekday abbreviations.
16854 While prompting, a calendar is popped up - you can also select the
16855 date with the mouse (button 1). The calendar shows a period of three
16856 months. To scroll it to other months, use the keys `>' and `<'.
16857 If you don't like the calendar, turn it off with
16858 (setq org-read-date-popup-calendar nil)
16860 With optional argument TO-TIME, the date will immediately be converted
16861 to an internal time.
16862 With an optional argument WITH-TIME, the prompt will suggest to
16863 also insert a time. Note that when WITH-TIME is not set, you can
16864 still enter a time, and this function will inform the calling routine
16865 about this change. The calling routine may then choose to change the
16866 format used to insert the time stamp into the buffer to include the time.
16867 With optional argument FROM-STRING, read from this string instead from
16868 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16869 the time/date that is used for everything that is not specified by the
16870 user."
16871 (require 'parse-time)
16872 (let* ((org-with-time with-time)
16873 (org-time-stamp-rounding-minutes
16874 (if (equal org-with-time '(16))
16875 '(0 0)
16876 org-time-stamp-rounding-minutes))
16877 (org-dcst org-display-custom-times)
16878 (ct (org-current-time))
16879 (org-def (or org-overriding-default-time default-time ct))
16880 (org-defdecode (decode-time org-def))
16881 (cur-frame (selected-frame))
16882 (mouse-autoselect-window nil) ; Don't let the mouse jump
16883 (calendar-setup
16884 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16885 (calendar-move-hook nil)
16886 (calendar-view-diary-initially-flag nil)
16887 (calendar-view-holidays-initially-flag nil)
16888 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16889 ;; Rationalize `org-def' and `org-defdecode', if required.
16890 (when (< (nth 2 org-defdecode) org-extend-today-until)
16891 (setf (nth 2 org-defdecode) -1)
16892 (setf (nth 1 org-defdecode) 59)
16893 (setq org-def (apply #'encode-time org-defdecode))
16894 (setq org-defdecode (decode-time org-def)))
16895 (let* ((timestr (format-time-string
16896 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16897 org-def))
16898 (prompt (concat (if prompt (concat prompt " ") "")
16899 (format "Date+time [%s]: " timestr))))
16900 (cond
16901 (from-string (setq ans from-string))
16902 (org-read-date-popup-calendar
16903 (save-excursion
16904 (save-window-excursion
16905 (calendar)
16906 (when (eq calendar-setup 'calendar-only)
16907 (setq cal-frame
16908 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16909 (select-frame cal-frame))
16910 (org-eval-in-calendar '(setq cursor-type nil) t)
16911 (unwind-protect
16912 (progn
16913 (calendar-forward-day (- (time-to-days org-def)
16914 (calendar-absolute-from-gregorian
16915 (calendar-current-date))))
16916 (org-eval-in-calendar nil t)
16917 (let* ((old-map (current-local-map))
16918 (map (copy-keymap calendar-mode-map))
16919 (minibuffer-local-map
16920 (copy-keymap org-read-date-minibuffer-local-map)))
16921 (org-defkey map (kbd "RET") 'org-calendar-select)
16922 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16923 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16924 (unwind-protect
16925 (progn
16926 (use-local-map map)
16927 (setq org-read-date-inactive inactive)
16928 (add-hook 'post-command-hook 'org-read-date-display)
16929 (setq org-ans0
16930 (read-string prompt
16931 default-input
16932 'org-read-date-history
16933 nil))
16934 ;; org-ans0: from prompt
16935 ;; org-ans1: from mouse click
16936 ;; org-ans2: from calendar motion
16937 (setq ans
16938 (concat org-ans0 " " (or org-ans1 org-ans2))))
16939 (remove-hook 'post-command-hook 'org-read-date-display)
16940 (use-local-map old-map)
16941 (when org-read-date-overlay
16942 (delete-overlay org-read-date-overlay)
16943 (setq org-read-date-overlay nil)))))
16944 (bury-buffer "*Calendar*")
16945 (when cal-frame
16946 (delete-frame cal-frame)
16947 (select-frame-set-input-focus cur-frame))))))
16949 (t ; Naked prompt only
16950 (unwind-protect
16951 (setq ans (read-string prompt default-input
16952 'org-read-date-history timestr))
16953 (when org-read-date-overlay
16954 (delete-overlay org-read-date-overlay)
16955 (setq org-read-date-overlay nil))))))
16957 (setq final (org-read-date-analyze ans org-def org-defdecode))
16959 (when org-read-date-analyze-forced-year
16960 (message "Year was forced into %s"
16961 (if org-read-date-force-compatible-dates
16962 "compatible range (1970-2037)"
16963 "range representable on this machine"))
16964 (ding))
16966 ;; One round trip to get rid of 34th of August and stuff like that....
16967 (setq final (decode-time (apply 'encode-time final)))
16969 (setq org-read-date-final-answer ans)
16971 (if to-time
16972 (apply 'encode-time final)
16973 (if (and (boundp 'org-time-was-given) org-time-was-given)
16974 (format "%04d-%02d-%02d %02d:%02d"
16975 (nth 5 final) (nth 4 final) (nth 3 final)
16976 (nth 2 final) (nth 1 final))
16977 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16979 (defun org-read-date-display ()
16980 "Display the current date prompt interpretation in the minibuffer."
16981 (when org-read-date-display-live
16982 (when org-read-date-overlay
16983 (delete-overlay org-read-date-overlay))
16984 (when (minibufferp (current-buffer))
16985 (save-excursion
16986 (end-of-line 1)
16987 (while (not (equal (buffer-substring
16988 (max (point-min) (- (point) 4)) (point))
16989 " "))
16990 (insert " ")))
16991 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16992 " " (or org-ans1 org-ans2)))
16993 (org-end-time-was-given nil)
16994 (f (org-read-date-analyze ans org-def org-defdecode))
16995 (fmts (if org-dcst
16996 org-time-stamp-custom-formats
16997 org-time-stamp-formats))
16998 (fmt (if (or org-with-time
16999 (and (boundp 'org-time-was-given) org-time-was-given))
17000 (cdr fmts)
17001 (car fmts)))
17002 (txt (format-time-string fmt (apply 'encode-time f)))
17003 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17004 (txt (concat "=> " txt)))
17005 (when (and org-end-time-was-given
17006 (string-match org-plain-time-of-day-regexp txt))
17007 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17008 org-end-time-was-given
17009 (substring txt (match-end 0)))))
17010 (when org-read-date-analyze-futurep
17011 (setq txt (concat txt " (=>F)")))
17012 (setq org-read-date-overlay
17013 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17014 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17016 (defun org-read-date-analyze (ans def defdecode)
17017 "Analyze the combined answer of the date prompt."
17018 ;; FIXME: cleanup and comment
17019 ;; Pass `current-time' result to `decode-time' (instead of calling
17020 ;; without arguments) so that only `current-time' has to be
17021 ;; overriden in tests.
17022 (let ((org-def def)
17023 (org-defdecode defdecode)
17024 (nowdecode (decode-time (current-time)))
17025 delta deltan deltaw deltadef year month day
17026 hour minute second wday pm h2 m2 tl wday1
17027 iso-year iso-weekday iso-week iso-date futurep kill-year)
17028 (setq org-read-date-analyze-futurep nil
17029 org-read-date-analyze-forced-year nil)
17030 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17031 (setq ans "+0"))
17033 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17034 (setq ans (replace-match "" t t ans)
17035 deltan (car delta)
17036 deltaw (nth 1 delta)
17037 deltadef (nth 2 delta)))
17039 ;; Check if there is an iso week date in there. If yes, store the
17040 ;; info and postpone interpreting it until the rest of the parsing
17041 ;; is done.
17042 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17043 (setq iso-year (when (match-end 1)
17044 (org-small-year-to-year
17045 (string-to-number (match-string 1 ans))))
17046 iso-weekday (when (match-end 3)
17047 (string-to-number (match-string 3 ans)))
17048 iso-week (string-to-number (match-string 2 ans)))
17049 (setq ans (replace-match "" t t ans)))
17051 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17052 (when (string-match
17053 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17054 (setq year (if (match-end 2)
17055 (string-to-number (match-string 2 ans))
17056 (progn (setq kill-year t)
17057 (string-to-number (format-time-string "%Y"))))
17058 month (string-to-number (match-string 3 ans))
17059 day (string-to-number (match-string 4 ans)))
17060 (setq year (org-small-year-to-year year))
17061 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17062 t nil ans)))
17064 ;; Help matching dotted european dates
17065 (when (string-match
17066 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17067 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17068 (setq kill-year t)
17069 (string-to-number (format-time-string "%Y")))
17070 day (string-to-number (match-string 1 ans))
17071 month (string-to-number (match-string 2 ans))
17072 ans (replace-match (format "%04d-%02d-%02d" year month day)
17073 t nil ans)))
17075 ;; Help matching american dates, like 5/30 or 5/30/7
17076 (when (string-match
17077 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17078 (setq year (if (match-end 4)
17079 (string-to-number (match-string 4 ans))
17080 (progn (setq kill-year t)
17081 (string-to-number (format-time-string "%Y"))))
17082 month (string-to-number (match-string 1 ans))
17083 day (string-to-number (match-string 2 ans)))
17084 (setq year (org-small-year-to-year year))
17085 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17086 t nil ans)))
17087 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17088 ;; If there is a time with am/pm, and *no* time without it, we convert
17089 ;; so that matching will be successful.
17090 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17091 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17092 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17093 (setq hour (string-to-number (match-string 1 ans))
17094 minute (if (match-end 3)
17095 (string-to-number (match-string 3 ans))
17097 pm (equal ?p
17098 (string-to-char (downcase (match-string 4 ans)))))
17099 (if (and (= hour 12) (not pm))
17100 (setq hour 0)
17101 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17102 (setq ans (replace-match (format "%02d:%02d" hour minute)
17103 t t ans))))
17105 ;; Check if a time range is given as a duration
17106 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17107 (setq hour (string-to-number (match-string 1 ans))
17108 h2 (+ hour (string-to-number (match-string 3 ans)))
17109 minute (string-to-number (match-string 2 ans))
17110 m2 (+ minute (if (match-end 5) (string-to-number
17111 (match-string 5 ans))0)))
17112 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17113 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17114 t t ans)))
17116 ;; Check if there is a time range
17117 (when (boundp 'org-end-time-was-given)
17118 (setq org-time-was-given nil)
17119 (when (and (string-match org-plain-time-of-day-regexp ans)
17120 (match-end 8))
17121 (setq org-end-time-was-given (match-string 8 ans))
17122 (setq ans (concat (substring ans 0 (match-beginning 7))
17123 (substring ans (match-end 7))))))
17125 (setq tl (parse-time-string ans)
17126 day (or (nth 3 tl) (nth 3 org-defdecode))
17127 month
17128 (cond ((nth 4 tl))
17129 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17130 ;; Day was specified. Make sure DAY+MONTH
17131 ;; combination happens in the future.
17132 ((nth 3 tl)
17133 (setq futurep t)
17134 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17135 (nth 4 nowdecode)))
17136 (t (nth 4 org-defdecode)))
17137 year
17138 (cond ((and (not kill-year) (nth 5 tl)))
17139 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17140 ;; Month was guessed in the future and is at least
17141 ;; equal to NOWDECODE's. Fix year accordingly.
17142 (futurep
17143 (if (or (> month (nth 4 nowdecode))
17144 (>= day (nth 3 nowdecode)))
17145 (nth 5 nowdecode)
17146 (1+ (nth 5 nowdecode))))
17147 ;; Month was specified. Make sure MONTH+YEAR
17148 ;; combination happens in the future.
17149 ((nth 4 tl)
17150 (setq futurep t)
17151 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17152 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17153 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17154 (t (nth 5 nowdecode))))
17155 (t (nth 5 org-defdecode)))
17156 hour (or (nth 2 tl) (nth 2 org-defdecode))
17157 minute (or (nth 1 tl) (nth 1 org-defdecode))
17158 second (or (nth 0 tl) 0)
17159 wday (nth 6 tl))
17161 (when (and (eq org-read-date-prefer-future 'time)
17162 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17163 (equal day (nth 3 nowdecode))
17164 (equal month (nth 4 nowdecode))
17165 (equal year (nth 5 nowdecode))
17166 (nth 2 tl)
17167 (or (< (nth 2 tl) (nth 2 nowdecode))
17168 (and (= (nth 2 tl) (nth 2 nowdecode))
17169 (nth 1 tl)
17170 (< (nth 1 tl) (nth 1 nowdecode)))))
17171 (setq day (1+ day)
17172 futurep t))
17174 ;; Special date definitions below
17175 (cond
17176 (iso-week
17177 ;; There was an iso week
17178 (require 'cal-iso)
17179 (setq futurep nil)
17180 (setq year (or iso-year year)
17181 day (or iso-weekday wday 1)
17182 wday nil ; to make sure that the trigger below does not match
17183 iso-date (calendar-gregorian-from-absolute
17184 (calendar-iso-to-absolute
17185 (list iso-week day year))))
17186 ; FIXME: Should we also push ISO weeks into the future?
17187 ; (when (and org-read-date-prefer-future
17188 ; (not iso-year)
17189 ; (< (calendar-absolute-from-gregorian iso-date)
17190 ; (time-to-days (current-time))))
17191 ; (setq year (1+ year)
17192 ; iso-date (calendar-gregorian-from-absolute
17193 ; (calendar-iso-to-absolute
17194 ; (list iso-week day year)))))
17195 (setq month (car iso-date)
17196 year (nth 2 iso-date)
17197 day (nth 1 iso-date)))
17198 (deltan
17199 (setq futurep nil)
17200 (unless deltadef
17201 ;; Pass `current-time' result to `decode-time' (instead of
17202 ;; calling without arguments) so that only `current-time' has
17203 ;; to be overriden in tests.
17204 (let ((now (decode-time (current-time))))
17205 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17206 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17207 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17208 ((equal deltaw "m") (setq month (+ month deltan)))
17209 ((equal deltaw "y") (setq year (+ year deltan)))))
17210 ((and wday (not (nth 3 tl)))
17211 ;; Weekday was given, but no day, so pick that day in the week
17212 ;; on or after the derived date.
17213 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17214 (unless (equal wday wday1)
17215 (setq day (+ day (% (- wday wday1 -7) 7))))))
17216 (when (and (boundp 'org-time-was-given)
17217 (nth 2 tl))
17218 (setq org-time-was-given t))
17219 (when (< year 100) (setq year (+ 2000 year)))
17220 ;; Check of the date is representable
17221 (if org-read-date-force-compatible-dates
17222 (progn
17223 (when (< year 1970)
17224 (setq year 1970 org-read-date-analyze-forced-year t))
17225 (when (> year 2037)
17226 (setq year 2037 org-read-date-analyze-forced-year t)))
17227 (condition-case nil
17228 (ignore (encode-time second minute hour day month year))
17229 (error
17230 (setq year (nth 5 org-defdecode))
17231 (setq org-read-date-analyze-forced-year t))))
17232 (setq org-read-date-analyze-futurep futurep)
17233 (list second minute hour day month year)))
17235 (defvar parse-time-weekdays)
17236 (defun org-read-date-get-relative (s today default)
17237 "Check string S for special relative date string.
17238 TODAY and DEFAULT are internal times, for today and for a default.
17239 Return shift list (N what def-flag)
17240 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17241 N is the number of WHATs to shift.
17242 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17243 the DEFAULT date rather than TODAY."
17244 (require 'parse-time)
17245 (when (and
17246 (string-match
17247 (concat
17248 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17249 "\\([0-9]+\\)?"
17250 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17251 "\\([ \t]\\|$\\)") s)
17252 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17253 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17254 (string-to-char (substring (match-string 1 s) -1))
17255 ?+))
17256 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17257 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17258 (what (if (match-end 3) (match-string 3 s) "d"))
17259 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17260 (date (if rel default today))
17261 (wday (nth 6 (decode-time date)))
17262 delta)
17263 (if wday1
17264 (progn
17265 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17266 (when (= delta 0) (setq delta 7))
17267 (when (= dir ?-)
17268 (setq delta (- delta 7))
17269 (when (= delta 0) (setq delta -7)))
17270 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17271 (list delta "d" rel))
17272 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17274 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17275 "Turn a user-specified date into the internal representation.
17276 The internal representation needed by the calendar is (month day year).
17277 This is a wrapper to handle the brain-dead convention in calendar that
17278 user function argument order change dependent on argument order."
17279 (if (boundp 'calendar-date-style)
17280 (cond
17281 ((eq calendar-date-style 'american)
17282 (list arg1 arg2 arg3))
17283 ((eq calendar-date-style 'european)
17284 (list arg2 arg1 arg3))
17285 ((eq calendar-date-style 'iso)
17286 (list arg2 arg3 arg1)))
17287 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17288 (if (org-bound-and-true-p european-calendar-style)
17289 (list arg2 arg1 arg3)
17290 (list arg1 arg2 arg3)))))
17292 (defun org-eval-in-calendar (form &optional keepdate)
17293 "Eval FORM in the calendar window and return to current window.
17294 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17295 (let ((sf (selected-frame))
17296 (sw (selected-window)))
17297 (select-window (get-buffer-window "*Calendar*" t))
17298 (eval form)
17299 (when (and (not keepdate) (calendar-cursor-to-date))
17300 (let* ((date (calendar-cursor-to-date))
17301 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17302 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17303 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17304 (select-window sw)
17305 (org-select-frame-set-input-focus sf)))
17307 (defun org-calendar-select ()
17308 "Return to `org-read-date' with the date currently selected.
17309 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17310 (interactive)
17311 (when (calendar-cursor-to-date)
17312 (let* ((date (calendar-cursor-to-date))
17313 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17314 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17315 (when (active-minibuffer-window) (exit-minibuffer))))
17317 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17318 "Insert a date stamp for the date given by the internal TIME.
17319 See `format-time-string' for the format of TIME.
17320 WITH-HM means use the stamp format that includes the time of the day.
17321 INACTIVE means use square brackets instead of angular ones, so that the
17322 stamp will not contribute to the agenda.
17323 PRE and POST are optional strings to be inserted before and after the
17324 stamp.
17325 The command returns the inserted time stamp."
17326 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17327 stamp)
17328 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17329 (insert-before-markers (or pre ""))
17330 (when (listp extra)
17331 (setq extra (car extra))
17332 (if (and (stringp extra)
17333 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17334 (setq extra (format "-%02d:%02d"
17335 (string-to-number (match-string 1 extra))
17336 (string-to-number (match-string 2 extra))))
17337 (setq extra nil)))
17338 (when extra
17339 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17340 (insert-before-markers (setq stamp (format-time-string fmt time)))
17341 (insert-before-markers (or post ""))
17342 (setq org-last-inserted-timestamp stamp)))
17344 (defun org-toggle-time-stamp-overlays ()
17345 "Toggle the use of custom time stamp formats."
17346 (interactive)
17347 (setq org-display-custom-times (not org-display-custom-times))
17348 (unless org-display-custom-times
17349 (let ((p (point-min)) (bmp (buffer-modified-p)))
17350 (while (setq p (next-single-property-change p 'display))
17351 (when (and (get-text-property p 'display)
17352 (eq (get-text-property p 'face) 'org-date))
17353 (remove-text-properties
17354 p (setq p (next-single-property-change p 'display))
17355 '(display t))))
17356 (set-buffer-modified-p bmp)))
17357 (when (featurep 'xemacs)
17358 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17359 (org-restart-font-lock)
17360 (setq org-table-may-need-update t)
17361 (if org-display-custom-times
17362 (message "Time stamps are overlaid with custom format")
17363 (message "Time stamp overlays removed")))
17365 (defun org-display-custom-time (beg end)
17366 "Overlay modified time stamp format over timestamp between BEG and END."
17367 (let* ((ts (buffer-substring beg end))
17368 t1 w1 with-hm tf time str w2 (off 0))
17369 (save-match-data
17370 (setq t1 (org-parse-time-string ts t))
17371 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17372 (setq off (- (match-end 0) (match-beginning 0)))))
17373 (setq end (- end off))
17374 (setq w1 (- end beg)
17375 with-hm (and (nth 1 t1) (nth 2 t1))
17376 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17377 time (org-fix-decoded-time t1)
17378 str (org-add-props
17379 (format-time-string
17380 (substring tf 1 -1) (apply 'encode-time time))
17381 nil 'mouse-face 'highlight)
17382 w2 (length str))
17383 (unless (= w2 w1)
17384 (add-text-properties (1+ beg) (+ 2 beg)
17385 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17386 (if (featurep 'xemacs)
17387 (progn
17388 (put-text-property beg end 'invisible t)
17389 (put-text-property beg end 'end-glyph (make-glyph str)))
17390 (put-text-property beg end 'display str))))
17392 (defun org-fix-decoded-time (time)
17393 "Set 0 instead of nil for the first 6 elements of time.
17394 Don't touch the rest."
17395 (let ((n 0))
17396 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17398 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17400 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17401 "Difference between TIMESTAMP-STRING and now in days.
17402 If SECONDS is non-nil, return the difference in seconds."
17403 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17404 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17405 (funcall fdiff (current-time)))))
17407 (defun org-deadline-close (timestamp-string &optional ndays)
17408 "Is the time in TIMESTAMP-STRING close to the current date?"
17409 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17410 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17411 (not (org-entry-is-done-p))))
17413 (defun org-get-wdays (ts &optional delay zero-delay)
17414 "Get the deadline lead time appropriate for timestring TS.
17415 When DELAY is non-nil, get the delay time for scheduled items
17416 instead of the deadline lead time. When ZERO-DELAY is non-nil
17417 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17418 don't try to find the delay cookie in the scheduled timestamp."
17419 (let ((tv (if delay org-scheduled-delay-days
17420 org-deadline-warning-days)))
17421 (cond
17422 ((or (and delay (< tv 0))
17423 (and delay zero-delay (<= tv 0))
17424 (and (not delay) (<= tv 0)))
17425 ;; Enforce this value no matter what
17426 (- tv))
17427 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17428 ;; lead time is specified.
17429 (floor (* (string-to-number (match-string 1 ts))
17430 (cdr (assoc (match-string 2 ts)
17431 '(("d" . 1) ("w" . 7)
17432 ("m" . 30.4) ("y" . 365.25)
17433 ("h" . 0.041667)))))))
17434 ;; go for the default.
17435 (t tv))))
17437 (defun org-calendar-select-mouse (ev)
17438 "Return to `org-read-date' with the date currently selected.
17439 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17440 (interactive "e")
17441 (mouse-set-point ev)
17442 (when (calendar-cursor-to-date)
17443 (let* ((date (calendar-cursor-to-date))
17444 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17445 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17446 (when (active-minibuffer-window) (exit-minibuffer))))
17448 (defun org-check-deadlines (ndays)
17449 "Check if there are any deadlines due or past due.
17450 A deadline is considered due if it happens within `org-deadline-warning-days'
17451 days from today's date. If the deadline appears in an entry marked DONE,
17452 it is not shown. The prefix arg NDAYS can be used to test that many
17453 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17454 (interactive "P")
17455 (let* ((org-warn-days
17456 (cond
17457 ((equal ndays '(4)) 100000)
17458 (ndays (prefix-numeric-value ndays))
17459 (t (abs org-deadline-warning-days))))
17460 (case-fold-search nil)
17461 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17462 (callback
17463 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17464 (message "%d deadlines past-due or due within %d days"
17465 (org-occur regexp nil callback)
17466 org-warn-days)))
17468 (defsubst org-re-timestamp (type)
17469 "Return a regexp for timestamp TYPE.
17470 Allowed values for TYPE are:
17472 all: all timestamps
17473 active: only active timestamps (<...>)
17474 inactive: only inactive timestamps ([...])
17475 scheduled: only scheduled timestamps
17476 deadline: only deadline timestamps
17477 closed: only closed time-stamps
17479 When TYPE is nil, fall back on returning a regexp that matches
17480 both scheduled and deadline timestamps."
17481 (cl-case type
17482 (all org-ts-regexp-both)
17483 (active org-ts-regexp)
17484 (inactive org-ts-regexp-inactive)
17485 (scheduled org-scheduled-time-regexp)
17486 (deadline org-deadline-time-regexp)
17487 (closed org-closed-time-regexp)
17488 (otherwise
17489 (concat "\\<"
17490 (regexp-opt (list org-deadline-string org-scheduled-string))
17491 " *<\\([^>]+\\)>"))))
17493 (defun org-check-before-date (d)
17494 "Check if there are deadlines or scheduled entries before date D."
17495 (interactive (list (org-read-date)))
17496 (let* ((case-fold-search nil)
17497 (regexp (org-re-timestamp org-ts-type))
17498 (ts-type org-ts-type)
17499 (callback
17500 (lambda ()
17501 (let ((match (match-string 1)))
17502 (and (if (memq ts-type '(active inactive all))
17503 (eq (org-element-type (org-element-context)) 'timestamp)
17504 (org-at-planning-p))
17505 (time-less-p
17506 (org-time-string-to-time match)
17507 (org-time-string-to-time d)))))))
17508 (message "%d entries before %s"
17509 (org-occur regexp nil callback)
17510 d)))
17512 (defun org-check-after-date (d)
17513 "Check if there are deadlines or scheduled entries after date D."
17514 (interactive (list (org-read-date)))
17515 (let* ((case-fold-search nil)
17516 (regexp (org-re-timestamp org-ts-type))
17517 (ts-type org-ts-type)
17518 (callback
17519 (lambda ()
17520 (let ((match (match-string 1)))
17521 (and (if (memq ts-type '(active inactive all))
17522 (eq (org-element-type (org-element-context)) 'timestamp)
17523 (org-at-planning-p))
17524 (not (time-less-p
17525 (org-time-string-to-time match)
17526 (org-time-string-to-time d))))))))
17527 (message "%d entries after %s"
17528 (org-occur regexp nil callback)
17529 d)))
17531 (defun org-check-dates-range (start-date end-date)
17532 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17533 (interactive (list (org-read-date nil nil nil "Range starts")
17534 (org-read-date nil nil nil "Range end")))
17535 (let ((case-fold-search nil)
17536 (regexp (org-re-timestamp org-ts-type))
17537 (callback
17538 (let ((type org-ts-type))
17539 (lambda ()
17540 (let ((match (match-string 1)))
17541 (and
17542 (if (memq type '(active inactive all))
17543 (eq (org-element-type (org-element-context)) 'timestamp)
17544 (org-at-planning-p))
17545 (not (time-less-p
17546 (org-time-string-to-time match)
17547 (org-time-string-to-time start-date)))
17548 (time-less-p
17549 (org-time-string-to-time match)
17550 (org-time-string-to-time end-date))))))))
17551 (message "%d entries between %s and %s"
17552 (org-occur regexp nil callback) start-date end-date)))
17554 (defun org-evaluate-time-range (&optional to-buffer)
17555 "Evaluate a time range by computing the difference between start and end.
17556 Normally the result is just printed in the echo area, but with prefix arg
17557 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17558 If the time range is actually in a table, the result is inserted into the
17559 next column.
17560 For time difference computation, a year is assumed to be exactly 365
17561 days in order to avoid rounding problems."
17562 (interactive "P")
17564 (org-clock-update-time-maybe)
17565 (save-excursion
17566 (unless (org-at-date-range-p t)
17567 (goto-char (point-at-bol))
17568 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17569 (unless (org-at-date-range-p t)
17570 (user-error "Not at a time-stamp range, and none found in current line")))
17571 (let* ((ts1 (match-string 1))
17572 (ts2 (match-string 2))
17573 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17574 (match-end (match-end 0))
17575 (time1 (org-time-string-to-time ts1))
17576 (time2 (org-time-string-to-time ts2))
17577 (t1 (org-float-time time1))
17578 (t2 (org-float-time time2))
17579 (diff (abs (- t2 t1)))
17580 (negative (< (- t2 t1) 0))
17581 ;; (ys (floor (* 365 24 60 60)))
17582 (ds (* 24 60 60))
17583 (hs (* 60 60))
17584 (fy "%dy %dd %02d:%02d")
17585 (fy1 "%dy %dd")
17586 (fd "%dd %02d:%02d")
17587 (fd1 "%dd")
17588 (fh "%02d:%02d")
17589 y d h m align)
17590 (if havetime
17591 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17593 d (floor (/ diff ds)) diff (mod diff ds)
17594 h (floor (/ diff hs)) diff (mod diff hs)
17595 m (floor (/ diff 60)))
17596 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17598 d (floor (+ (/ diff ds) 0.5))
17599 h 0 m 0))
17600 (if (not to-buffer)
17601 (message "%s" (org-make-tdiff-string y d h m))
17602 (if (org-at-table-p)
17603 (progn
17604 (goto-char match-end)
17605 (setq align t)
17606 (and (looking-at " *|") (goto-char (match-end 0))))
17607 (goto-char match-end))
17608 (when (looking-at
17609 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17610 (replace-match ""))
17611 (when negative (insert " -"))
17612 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17613 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17614 (insert " " (format fh h m))))
17615 (when align (org-table-align))
17616 (message "Time difference inserted")))))
17618 (defun org-make-tdiff-string (y d h m)
17619 (let ((fmt "")
17620 (l nil))
17621 (when (> y 0)
17622 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17623 (push y l))
17624 (when (> d 0)
17625 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17626 (push d l))
17627 (when (> h 0)
17628 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17629 (push h l))
17630 (when (> m 0)
17631 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17632 (push m l))
17633 (apply 'format fmt (nreverse l))))
17635 (defun org-time-string-to-time (s &optional buffer pos)
17636 "Convert a timestamp string into internal time."
17637 (condition-case errdata
17638 (apply 'encode-time (org-parse-time-string s))
17639 (error (error "Bad timestamp `%s'%s\nError was: %s"
17640 s (if (not (and buffer pos))
17642 (format-message " at %d in buffer `%s'" pos buffer))
17643 (cdr errdata)))))
17645 (defun org-time-string-to-seconds (s)
17646 "Convert a timestamp string to a number of seconds."
17647 (org-float-time (org-time-string-to-time s)))
17649 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17651 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17652 "Convert time stamp S to an absolute day number.
17654 If DAYNR in non-nil, and there is a specifier for a cyclic time
17655 stamp, get the closest date to DAYNR. If PREFER is
17656 `past' (respectively `future') return a date past (respectively
17657 after) or equal to DAYNR.
17659 POS is the location of time stamp S, as a buffer position in
17660 BUFFER.
17662 Diary sexp timestamps are matched against DAYNR, when non-nil.
17663 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17664 signalled."
17665 (cond
17666 ((string-match "\\`%%\\((.*)\\)" s)
17667 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17668 ;; only able to match individual dates. If it fails, raise an
17669 ;; error.
17670 (if (and daynr
17671 (org-diary-sexp-entry
17672 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17673 daynr
17674 (signal 'org-diary-sexp-no-match (list s))))
17675 ((and daynr show-all) (org-closest-date s daynr prefer))
17676 (t (time-to-days
17677 (condition-case errdata
17678 (apply #'encode-time (org-parse-time-string s))
17679 (error (error "Bad timestamp `%s'%s\nError was: %s"
17681 (if (not (and buffer pos)) ""
17682 (format-message " at %d in buffer `%s'" pos buffer))
17683 (cdr errdata))))))))
17685 (defun org-days-to-iso-week (days)
17686 "Return the iso week number."
17687 (require 'cal-iso)
17688 (car (calendar-iso-from-absolute days)))
17690 (defun org-small-year-to-year (year)
17691 "Convert 2-digit years into 4-digit years.
17692 YEAR is expanded into one of the 30 next years, if possible, or
17693 into a past one. Any year larger than 99 is returned unchanged."
17694 (if (>= year 100) year
17695 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17696 (century (/ current 100))
17697 (offset (- year (% current 100))))
17698 (cond ((> offset 30) (+ (* (1- century) 100) year))
17699 ((> offset -70) (+ (* century 100) year))
17700 (t (+ (* (1+ century) 100) year))))))
17702 (defun org-time-from-absolute (d)
17703 "Return the time corresponding to date D.
17704 D may be an absolute day number, or a calendar-type list (month day year)."
17705 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17706 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17708 (defvar org-agenda-current-date)
17709 (defun org-calendar-holiday ()
17710 "List of holidays, for Diary display in Org mode."
17711 (require 'holidays)
17712 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17713 (and hl (mapconcat #'identity hl "; "))))
17715 (defun org-diary-sexp-entry (sexp entry d)
17716 "Process a SEXP diary ENTRY for date D."
17717 (require 'diary-lib)
17718 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17719 ;; dynamically.
17720 (let* ((sexp `(let ((entry ,entry)
17721 (date ',d))
17722 ,(car (read-from-string sexp))))
17723 (result (if calendar-debug-sexp (eval sexp)
17724 (condition-case nil
17725 (eval sexp)
17726 (error
17727 (beep)
17728 (message "Bad sexp at line %d in %s: %s"
17729 (org-current-line)
17730 (buffer-file-name) sexp)
17731 (sleep-for 2))))))
17732 (cond ((stringp result) (split-string result "; "))
17733 ((and (consp result)
17734 (not (consp (cdr result)))
17735 (stringp (cdr result))) (cdr result))
17736 ((and (consp result)
17737 (stringp (car result))) result)
17738 (result entry))))
17740 (defun org-diary-to-ical-string (frombuf)
17741 "Get iCalendar entries from diary entries in buffer FROMBUF.
17742 This uses the icalendar.el library."
17743 (let* ((tmpdir (if (featurep 'xemacs)
17744 (temp-directory)
17745 temporary-file-directory))
17746 (tmpfile (make-temp-name
17747 (expand-file-name "orgics" tmpdir)))
17748 buf rtn b e)
17749 (with-current-buffer frombuf
17750 (icalendar-export-region (point-min) (point-max) tmpfile)
17751 (setq buf (find-buffer-visiting tmpfile))
17752 (set-buffer buf)
17753 (goto-char (point-min))
17754 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17755 (setq b (match-beginning 0)))
17756 (goto-char (point-max))
17757 (when (re-search-backward "^END:VEVENT" nil t)
17758 (setq e (match-end 0)))
17759 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17760 (kill-buffer buf)
17761 (delete-file tmpfile)
17762 rtn))
17764 (defun org-closest-date (start current prefer)
17765 "Return closest date to CURRENT starting from START.
17767 CURRENT and START are both time stamps.
17769 When PREFER is `past', return a date that is either CURRENT or
17770 past. When PREFER is `future', return a date that is either
17771 CURRENT or future.
17773 Only time stamps with a repeater are modified. Any other time
17774 stamp stay unchanged. In any case, return value is an absolute
17775 day number."
17776 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17777 ;; No repeater. Do not shift time stamp.
17778 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17779 (let ((value (string-to-number (match-string 1 start)))
17780 (type (match-string 2 start)))
17781 (if (= 0 value)
17782 ;; Repeater with a 0-value is considered as void.
17783 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17784 (let* ((base (org-date-to-gregorian start))
17785 (target (org-date-to-gregorian current))
17786 (sday (calendar-absolute-from-gregorian base))
17787 (cday (calendar-absolute-from-gregorian target))
17788 n1 n2)
17789 ;; If START is already past CURRENT, just return START.
17790 (if (<= cday sday) sday
17791 ;; Compute closest date before (N1) and closest date past
17792 ;; (N2) CURRENT.
17793 (pcase type
17794 ("h"
17795 (let ((missing-hours
17796 (mod (+ (- (* 24 (- cday sday))
17797 (nth 2 (org-parse-time-string start)))
17798 org-extend-today-until)
17799 value)))
17800 (setf n1 (if (= missing-hours 0) cday
17801 (- cday (1+ (/ missing-hours 24)))))
17802 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17803 ((or "d" "w")
17804 (let ((value (if (equal type "w") (* 7 value) value)))
17805 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17806 (setf n2 (+ n1 value))))
17807 ("m"
17808 (let* ((add-months
17809 (lambda (d n)
17810 ;; Add N months to gregorian date D, i.e.,
17811 ;; a list (MONTH DAY YEAR). Return a valid
17812 ;; gregorian date.
17813 (let ((m (+ (nth 0 d) n)))
17814 (list (mod m 12)
17815 (nth 1 d)
17816 (+ (/ m 12) (nth 2 d))))))
17817 (months ; Complete months to TARGET.
17818 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17819 (- (nth 0 target) (nth 0 base))
17820 ;; If START's day is greater than
17821 ;; TARGET's, remove incomplete month.
17822 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17823 value)
17824 value))
17825 (before (funcall add-months base months)))
17826 (setf n1 (calendar-absolute-from-gregorian before))
17827 (setf n2
17828 (calendar-absolute-from-gregorian
17829 (funcall add-months before value)))))
17831 (let* ((d (nth 1 base))
17832 (m (nth 0 base))
17833 (y (nth 2 base))
17834 (years ; Complete years to TARGET.
17835 (* (/ (- (nth 2 target)
17837 ;; If START's month and day are
17838 ;; greater than TARGET's, remove
17839 ;; incomplete year.
17840 (if (or (> (nth 0 target) m)
17841 (and (= (nth 0 target) m)
17842 (> (nth 1 target) d)))
17845 value)
17846 value))
17847 (before (list m d (+ y years))))
17848 (setf n1 (calendar-absolute-from-gregorian before))
17849 (setf n2 (calendar-absolute-from-gregorian
17850 (list m d (+ (nth 2 before) value)))))))
17851 ;; Handle PREFER parameter, if any.
17852 (cond
17853 ((eq prefer 'past) (if (= cday n2) n2 n1))
17854 ((eq prefer 'future) (if (= cday n1) n1 n2))
17855 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17857 (defun org-date-to-gregorian (d)
17858 "Turn any specification of date D into a Gregorian date for the calendar."
17859 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17860 ((and (listp d) (= (length d) 3)) d)
17861 ((stringp d)
17862 (let ((d (org-parse-time-string d)))
17863 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17864 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17866 (defun org-parse-time-string (s &optional nodefault)
17867 "Parse the standard Org-mode time string.
17868 This should be a lot faster than the normal `parse-time-string'.
17869 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17870 hour and minute fields will be nil if not given."
17871 (cond ((string-match org-ts-regexp0 s)
17872 (list 0
17873 (when (or (match-beginning 8) (not nodefault))
17874 (string-to-number (or (match-string 8 s) "0")))
17875 (when (or (match-beginning 7) (not nodefault))
17876 (string-to-number (or (match-string 7 s) "0")))
17877 (string-to-number (match-string 4 s))
17878 (string-to-number (match-string 3 s))
17879 (string-to-number (match-string 2 s))
17880 nil nil nil))
17881 ((string-match "^<[^>]+>$" s)
17882 (decode-time (seconds-to-time (org-matcher-time s))))
17883 (t (error "Not a standard Org-mode time string: %s" s))))
17885 (defun org-timestamp-up (&optional arg)
17886 "Increase the date item at the cursor by one.
17887 If the cursor is on the year, change the year. If it is on the month,
17888 the day or the time, change that.
17889 With prefix ARG, change by that many units."
17890 (interactive "p")
17891 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17893 (defun org-timestamp-down (&optional arg)
17894 "Decrease the date item at the cursor by one.
17895 If the cursor is on the year, change the year. If it is on the month,
17896 the day or the time, change that.
17897 With prefix ARG, change by that many units."
17898 (interactive "p")
17899 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17901 (defun org-timestamp-up-day (&optional arg)
17902 "Increase the date in the time stamp by one day.
17903 With prefix ARG, change that many days."
17904 (interactive "p")
17905 (if (and (not (org-at-timestamp-p t))
17906 (org-at-heading-p))
17907 (org-todo 'up)
17908 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17910 (defun org-timestamp-down-day (&optional arg)
17911 "Decrease the date in the time stamp by one day.
17912 With prefix ARG, change that many days."
17913 (interactive "p")
17914 (if (and (not (org-at-timestamp-p t))
17915 (org-at-heading-p))
17916 (org-todo 'down)
17917 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17919 (defun org-at-timestamp-p (&optional inactive-ok)
17920 "Non-nil if point is inside a timestamp.
17922 When optional argument INACTIVE-OK is non-nil, also consider
17923 inactive timestamps.
17925 When this function returns a non-nil value, match data is set
17926 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17927 INACTIVE-OK."
17928 (interactive)
17929 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17930 (pos (point))
17931 (ans (or (looking-at tsr)
17932 (save-excursion
17933 (skip-chars-backward "^[<\n\r\t")
17934 (when (> (point) (point-min)) (backward-char 1))
17935 (and (looking-at tsr)
17936 (> (- (match-end 0) pos) -1))))))
17937 (and ans
17938 (boundp 'org-ts-what)
17939 (setq org-ts-what
17940 (cond
17941 ((= pos (match-beginning 0)) 'bracket)
17942 ;; Point is considered to be "on the bracket" whether
17943 ;; it's really on it or right after it.
17944 ((= pos (1- (match-end 0))) 'bracket)
17945 ((= pos (match-end 0)) 'after)
17946 ((org-pos-in-match-range pos 2) 'year)
17947 ((org-pos-in-match-range pos 3) 'month)
17948 ((org-pos-in-match-range pos 7) 'hour)
17949 ((org-pos-in-match-range pos 8) 'minute)
17950 ((or (org-pos-in-match-range pos 4)
17951 (org-pos-in-match-range pos 5)) 'day)
17952 ((and (> pos (or (match-end 8) (match-end 5)))
17953 (< pos (match-end 0)))
17954 (- pos (or (match-end 8) (match-end 5))))
17955 (t 'day))))
17956 ans))
17958 (defun org-toggle-timestamp-type ()
17959 "Toggle the type (<active> or [inactive]) of a time stamp."
17960 (interactive)
17961 (when (org-at-timestamp-p t)
17962 (let ((beg (match-beginning 0)) (end (match-end 0))
17963 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17964 (save-excursion
17965 (goto-char beg)
17966 (while (re-search-forward "[][<>]" end t)
17967 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17968 t t)))
17969 (message "Timestamp is now %sactive"
17970 (if (equal (char-after beg) ?<) "" "in")))))
17972 (defun org-at-clock-log-p nil
17973 "Is the cursor on the clock log line?"
17974 (save-excursion
17975 (move-beginning-of-line 1)
17976 (looking-at org-clock-line-re)))
17978 (defvar org-clock-history) ; defined in org-clock.el
17979 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17980 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17981 "Change the date in the time stamp at point.
17982 The date will be changed by N times WHAT. WHAT can be `day', `month',
17983 `year', `minute', `second'. If WHAT is not given, the cursor position
17984 in the timestamp determines what will be changed.
17985 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17986 (let ((origin (point)) origin-cat
17987 with-hm inactive
17988 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17989 org-ts-what
17990 extra rem
17991 ts time time0 fixnext clrgx)
17992 (unless (org-at-timestamp-p t)
17993 (user-error "Not at a timestamp"))
17994 (if (and (not what) (eq org-ts-what 'bracket))
17995 (org-toggle-timestamp-type)
17996 ;; Point isn't on brackets. Remember the part of the time-stamp
17997 ;; the point was in. Indeed, size of time-stamps may change,
17998 ;; but point must be kept in the same category nonetheless.
17999 (setq origin-cat org-ts-what)
18000 (when (and (not what) (not (eq org-ts-what 'day))
18001 org-display-custom-times
18002 (get-text-property (point) 'display)
18003 (not (get-text-property (1- (point)) 'display)))
18004 (setq org-ts-what 'day))
18005 (setq org-ts-what (or what org-ts-what)
18006 inactive (= (char-after (match-beginning 0)) ?\[)
18007 ts (match-string 0))
18008 (replace-match "")
18009 (when (string-match
18010 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18012 (setq extra (match-string 1 ts))
18013 (when suppress-tmp-delay
18014 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18015 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18016 (setq with-hm t))
18017 (setq time0 (org-parse-time-string ts))
18018 (when (and updown
18019 (eq org-ts-what 'minute)
18020 (not current-prefix-arg))
18021 ;; This looks like s-up and s-down. Change by one rounding step.
18022 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18023 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18024 (setcar (cdr time0) (+ (nth 1 time0)
18025 (if (> n 0) (- rem) (- dm rem))))))
18026 (setq time
18027 (apply #'encode-time
18028 (or (car time0) 0)
18029 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18030 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18031 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18032 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18033 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18034 (nthcdr 6 time0)))
18035 (when (and (member org-ts-what '(hour minute))
18036 extra
18037 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18038 (setq extra (org-modify-ts-extra
18039 extra
18040 (if (eq org-ts-what 'hour) 2 5)
18041 n dm)))
18042 (when (integerp org-ts-what)
18043 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18044 (when (eq what 'calendar)
18045 (let ((cal-date (org-get-date-from-calendar)))
18046 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18047 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18048 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18049 (setcar time0 (or (car time0) 0))
18050 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18051 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18052 (setq time (apply 'encode-time time0))))
18053 ;; Insert the new time-stamp, and ensure point stays in the same
18054 ;; category as before (i.e. not after the last position in that
18055 ;; category).
18056 (let ((pos (point)))
18057 ;; Stay before inserted string. `save-excursion' is of no use.
18058 (setq org-last-changed-timestamp
18059 (org-insert-time-stamp time with-hm inactive nil nil extra))
18060 (goto-char pos))
18061 (save-match-data
18062 (looking-at org-ts-regexp3)
18063 (goto-char (cond
18064 ;; `day' category ends before `hour' if any, or at
18065 ;; the end of the day name.
18066 ((eq origin-cat 'day)
18067 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18068 ((eq origin-cat 'hour) (min (match-end 7) origin))
18069 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18070 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18071 ;; `year' and `month' have both fixed size: point
18072 ;; couldn't have moved into another part.
18073 (t origin))))
18074 ;; Update clock if on a CLOCK line.
18075 (org-clock-update-time-maybe)
18076 ;; Maybe adjust the closest clock in `org-clock-history'
18077 (when org-clock-adjust-closest
18078 (if (not (and (org-at-clock-log-p)
18079 (< 1 (length (delq nil (mapcar 'marker-position
18080 org-clock-history))))))
18081 (message "No clock to adjust")
18082 (cond ((save-excursion ; fix previous clock?
18083 (re-search-backward org-ts-regexp0 nil t)
18084 (org-looking-back (concat org-clock-string " \\[")
18085 (line-beginning-position)))
18086 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18087 ((save-excursion ; fix next clock?
18088 (re-search-backward org-ts-regexp0 nil t)
18089 (looking-at (concat org-ts-regexp0 "\\] =>")))
18090 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18091 (save-window-excursion
18092 ;; Find closest clock to point, adjust the previous/next one in history
18093 (let* ((p (save-excursion (org-back-to-heading t)))
18094 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18095 (clfixnth
18096 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18097 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18098 (if (not clfixpos)
18099 (message "No clock to adjust")
18100 (save-excursion
18101 (org-goto-marker-or-bmk clfixpos)
18102 (org-show-subtree)
18103 (when (re-search-forward clrgx nil t)
18104 (goto-char (match-beginning 1))
18105 (let (org-clock-adjust-closest)
18106 (org-timestamp-change n org-ts-what updown))
18107 (message "Clock adjusted in %s for heading: %s"
18108 (file-name-nondirectory (buffer-file-name))
18109 (org-get-heading t t)))))))))
18110 ;; Try to recenter the calendar window, if any.
18111 (when (and org-calendar-follow-timestamp-change
18112 (get-buffer-window "*Calendar*" t)
18113 (memq org-ts-what '(day month year)))
18114 (org-recenter-calendar (time-to-days time))))))
18116 (defun org-modify-ts-extra (s pos n dm)
18117 "Change the different parts of the lead-time and repeat fields in timestamp."
18118 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18119 ng h m new rem)
18120 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18121 (cond
18122 ((or (org-pos-in-match-range pos 2)
18123 (org-pos-in-match-range pos 3))
18124 (setq m (string-to-number (match-string 3 s))
18125 h (string-to-number (match-string 2 s)))
18126 (if (org-pos-in-match-range pos 2)
18127 (setq h (+ h n))
18128 (setq n (* dm (org-no-warnings (signum n))))
18129 (unless (= 0 (setq rem (% m dm)))
18130 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18131 (setq m (+ m n)))
18132 (when (< m 0) (setq m (+ m 60) h (1- h)))
18133 (when (> m 59) (setq m (- m 60) h (1+ h)))
18134 (setq h (mod h 24))
18135 (setq ng 1 new (format "-%02d:%02d" h m)))
18136 ((org-pos-in-match-range pos 6)
18137 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18138 ((org-pos-in-match-range pos 5)
18139 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18141 ((org-pos-in-match-range pos 9)
18142 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18143 ((org-pos-in-match-range pos 8)
18144 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18146 (when ng
18147 (setq s (concat
18148 (substring s 0 (match-beginning ng))
18150 (substring s (match-end ng))))))
18153 (defun org-recenter-calendar (d)
18154 "If the calendar is visible, recenter it to date D."
18155 (let ((cwin (get-buffer-window "*Calendar*" t)))
18156 (when cwin
18157 (let ((calendar-move-hook nil))
18158 (with-selected-window cwin
18159 (calendar-goto-date
18160 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18162 (defun org-goto-calendar (&optional arg)
18163 "Go to the Emacs calendar at the current date.
18164 If there is a time stamp in the current line, go to that date.
18165 A prefix ARG can be used to force the current date."
18166 (interactive "P")
18167 (let ((tsr org-ts-regexp) diff
18168 (calendar-move-hook nil)
18169 (calendar-view-holidays-initially-flag nil)
18170 (calendar-view-diary-initially-flag nil))
18171 (when (or (org-at-timestamp-p)
18172 (save-excursion
18173 (beginning-of-line 1)
18174 (looking-at (concat ".*" tsr))))
18175 (let ((d1 (time-to-days (current-time)))
18176 (d2 (time-to-days
18177 (org-time-string-to-time (match-string 1)))))
18178 (setq diff (- d2 d1))))
18179 (calendar)
18180 (calendar-goto-today)
18181 (when (and diff (not arg)) (calendar-forward-day diff))))
18183 (defun org-get-date-from-calendar ()
18184 "Return a list (month day year) of date at point in calendar."
18185 (with-current-buffer "*Calendar*"
18186 (save-match-data
18187 (calendar-cursor-to-date))))
18189 (defun org-date-from-calendar ()
18190 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18191 If there is already a time stamp at the cursor position, update it."
18192 (interactive)
18193 (if (org-at-timestamp-p t)
18194 (org-timestamp-change 0 'calendar)
18195 (let ((cal-date (org-get-date-from-calendar)))
18196 (org-insert-time-stamp
18197 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18199 (defcustom org-effort-durations
18200 `(("min" . 1)
18201 ("h" . 60)
18202 ("d" . ,(* 60 8))
18203 ("w" . ,(* 60 8 5))
18204 ("m" . ,(* 60 8 5 4))
18205 ("y" . ,(* 60 8 5 40)))
18206 "Conversion factor to minutes for an effort modifier.
18208 Each entry has the form (MODIFIER . MINUTES).
18210 In an effort string, a number followed by MODIFIER is multiplied
18211 by the specified number of MINUTES to obtain an effort in
18212 minutes.
18214 For example, if the value of this variable is ((\"hours\" . 60)), then an
18215 effort string \"2hours\" is equivalent to 120 minutes."
18216 :group 'org-agenda
18217 :version "25.1"
18218 :package-version '(Org . "8.3")
18219 :type '(alist :key-type (string :tag "Modifier")
18220 :value-type (number :tag "Minutes")))
18222 (defun org-minutes-to-clocksum-string (m)
18223 "Format number of minutes as a clocksum string.
18224 The format is determined by `org-time-clocksum-format',
18225 `org-time-clocksum-use-fractional' and
18226 `org-time-clocksum-fractional-format' and
18227 `org-time-clocksum-use-effort-durations'."
18228 (let ((clocksum "")
18229 (m (round m)) ; Don't allow fractions of minutes
18230 h d w mo y fmt n)
18231 (setq h (if org-time-clocksum-use-effort-durations
18232 (cdr (assoc "h" org-effort-durations)) 60)
18233 d (if org-time-clocksum-use-effort-durations
18234 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18235 w (if org-time-clocksum-use-effort-durations
18236 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18237 mo (if org-time-clocksum-use-effort-durations
18238 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18239 y (if org-time-clocksum-use-effort-durations
18240 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18241 ;; fractional format
18242 (if org-time-clocksum-use-fractional
18243 (cond
18244 ;; single format string
18245 ((stringp org-time-clocksum-fractional-format)
18246 (format org-time-clocksum-fractional-format (/ m (float h))))
18247 ;; choice of fractional formats for different time units
18248 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18249 (> (/ (truncate m) (* y d h)) 0))
18250 (format fmt (/ m (* y d (float h)))))
18251 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18252 (> (/ (truncate m) (* mo d h)) 0))
18253 (format fmt (/ m (* mo d (float h)))))
18254 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18255 (> (/ (truncate m) (* w d h)) 0))
18256 (format fmt (/ m (* w d (float h)))))
18257 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18258 (> (/ (truncate m) (* d h)) 0))
18259 (format fmt (/ m (* d (float h)))))
18260 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18261 (> (/ (truncate m) h) 0))
18262 (format fmt (/ m (float h))))
18263 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18264 (format fmt m))
18265 ;; fall back to smallest time unit with a format
18266 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18267 (format fmt (/ m (float h))))
18268 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18269 (format fmt (/ m (* d (float h)))))
18270 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18271 (format fmt (/ m (* w d (float h)))))
18272 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18273 (format fmt (/ m (* mo d (float h)))))
18274 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18275 (format fmt (/ m (* y d (float h))))))
18276 ;; standard (non-fractional) format, with single format string
18277 (if (stringp org-time-clocksum-format)
18278 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18279 ;; separate formats components
18280 (and (setq fmt (plist-get org-time-clocksum-format :years))
18281 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18282 (plist-get org-time-clocksum-format :require-years))
18283 (setq clocksum (concat clocksum (format fmt n))
18284 m (- m (* n y d h))))
18285 (and (setq fmt (plist-get org-time-clocksum-format :months))
18286 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18287 (plist-get org-time-clocksum-format :require-months))
18288 (setq clocksum (concat clocksum (format fmt n))
18289 m (- m (* n mo d h))))
18290 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18291 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18292 (plist-get org-time-clocksum-format :require-weeks))
18293 (setq clocksum (concat clocksum (format fmt n))
18294 m (- m (* n w d h))))
18295 (and (setq fmt (plist-get org-time-clocksum-format :days))
18296 (or (> (setq n (/ (truncate m) (* d h))) 0)
18297 (plist-get org-time-clocksum-format :require-days))
18298 (setq clocksum (concat clocksum (format fmt n))
18299 m (- m (* n d h))))
18300 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18301 (or (> (setq n (/ (truncate m) h)) 0)
18302 (plist-get org-time-clocksum-format :require-hours))
18303 (setq clocksum (concat clocksum (format fmt n))
18304 m (- m (* n h))))
18305 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18306 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18307 (setq clocksum (concat clocksum (format fmt m))))
18308 ;; return formatted time duration
18309 clocksum))))
18311 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18312 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18313 "Org mode version 8.0")
18315 (defun org-hours-to-clocksum-string (n)
18316 (org-minutes-to-clocksum-string (* n 60)))
18318 (defun org-hh:mm-string-to-minutes (s)
18319 "Convert a string H:MM to a number of minutes.
18320 If the string is just a number, interpret it as minutes.
18321 In fact, the first hh:mm or number in the string will be taken,
18322 there can be extra stuff in the string.
18323 If no number is found, the return value is 0."
18324 (cond
18325 ((integerp s) s)
18326 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18327 (+ (* (string-to-number (match-string 1 s)) 60)
18328 (string-to-number (match-string 2 s))))
18329 ((string-match "\\([0-9]+\\)" s)
18330 (string-to-number (match-string 1 s)))
18331 (t 0)))
18333 (defcustom org-image-actual-width t
18334 "Should we use the actual width of images when inlining them?
18336 When set to t, always use the image width.
18338 When set to a number, use imagemagick (when available) to set
18339 the image's width to this value.
18341 When set to a number in a list, try to get the width from any
18342 #+ATTR.* keyword if it matches a width specification like
18344 #+ATTR_HTML: :width 300px
18346 and fall back on that number if none is found.
18348 When set to nil, try to get the width from an #+ATTR.* keyword
18349 and fall back on the original width if none is found.
18351 This requires Emacs >= 24.1, build with imagemagick support."
18352 :group 'org-appearance
18353 :version "24.4"
18354 :package-version '(Org . "8.0")
18355 :type '(choice
18356 (const :tag "Use the image width" t)
18357 (integer :tag "Use a number of pixels")
18358 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18359 (const :tag "Use #+ATTR* or don't resize" nil)))
18361 (defcustom org-agenda-inhibit-startup nil
18362 "Inhibit startup when preparing agenda buffers.
18363 When this variable is t, the initialization of the Org agenda
18364 buffers is inhibited: e.g. the visibility state is not set, the
18365 tables are not re-aligned, etc."
18366 :type 'boolean
18367 :version "24.3"
18368 :group 'org-agenda)
18370 (define-obsolete-variable-alias
18371 'org-agenda-ignore-drawer-properties
18372 'org-agenda-ignore-properties "25.1")
18374 (defcustom org-agenda-ignore-properties nil
18375 "Avoid updating text properties when building the agenda.
18376 Properties are used to prepare buffers for effort estimates,
18377 appointments, statistics and subtree-local categories.
18378 If you don't use these in the agenda, you can add them to this
18379 list and agenda building will be a bit faster.
18380 The value is a list, with zero or more of the symbols `effort', `appt',
18381 `stats' or `category'."
18382 :type '(set :greedy t
18383 (const effort)
18384 (const appt)
18385 (const stats)
18386 (const category))
18387 :version "25.1"
18388 :package-version '(Org . "8.3")
18389 :group 'org-agenda)
18391 (defun org-duration-string-to-minutes (s &optional output-to-string)
18392 "Convert a duration string S to minutes.
18394 A bare number is interpreted as minutes, modifiers can be set by
18395 customizing `org-effort-durations' (which see).
18397 Entries containing a colon are interpreted as H:MM by
18398 `org-hh:mm-string-to-minutes'."
18399 (let ((result 0)
18400 (re (concat "\\([0-9.]+\\) *\\("
18401 (regexp-opt (mapcar 'car org-effort-durations))
18402 "\\)")))
18403 (while (string-match re s)
18404 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18405 (string-to-number (match-string 1 s))))
18406 (setq s (replace-match "" nil t s)))
18407 (setq result (floor result))
18408 (cl-incf result (org-hh:mm-string-to-minutes s))
18409 (if output-to-string (number-to-string result) result)))
18411 ;;;; Files
18413 (defun org-save-all-org-buffers ()
18414 "Save all Org-mode buffers without user confirmation."
18415 (interactive)
18416 (message "Saving all Org-mode buffers...")
18417 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18418 (when (featurep 'org-id) (org-id-locations-save))
18419 (message "Saving all Org-mode buffers... done"))
18421 (defun org-revert-all-org-buffers ()
18422 "Revert all Org-mode buffers.
18423 Prompt for confirmation when there are unsaved changes.
18424 Be sure you know what you are doing before letting this function
18425 overwrite your changes.
18427 This function is useful in a setup where one tracks org files
18428 with a version control system, to revert on one machine after pulling
18429 changes from another. I believe the procedure must be like this:
18431 1. M-x org-save-all-org-buffers
18432 2. Pull changes from the other machine, resolve conflicts
18433 3. M-x org-revert-all-org-buffers"
18434 (interactive)
18435 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18436 (user-error "Abort"))
18437 (save-excursion
18438 (save-window-excursion
18439 (dolist (b (buffer-list))
18440 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18441 (with-current-buffer b buffer-file-name))
18442 (org-pop-to-buffer-same-window b)
18443 (revert-buffer t 'no-confirm)))
18444 (when (and (featurep 'org-id) org-id-track-globally)
18445 (org-id-locations-load)))))
18447 ;;;; Agenda files
18449 ;;;###autoload
18450 (defun org-switchb (&optional arg)
18451 "Switch between Org buffers.
18453 With \\[universal-argument] prefix, restrict available buffers to files.
18455 With \\[universal-argument] \\[universal-argument] \
18456 prefix, restrict available buffers to agenda files."
18457 (interactive "P")
18458 (let ((blist (org-buffer-list
18459 (cond ((equal arg '(4)) 'files)
18460 ((equal arg '(16)) 'agenda)))))
18461 (org-pop-to-buffer-same-window
18462 (completing-read "Org buffer: "
18463 (mapcar #'list (mapcar #'buffer-name blist))
18464 nil t))))
18466 (defun org-buffer-list (&optional predicate exclude-tmp)
18467 "Return a list of Org buffers.
18468 PREDICATE can be `export', `files' or `agenda'.
18470 export restrict the list to Export buffers.
18471 files restrict the list to buffers visiting Org files.
18472 agenda restrict the list to buffers visiting agenda files.
18474 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18475 (let* ((bfn nil)
18476 (agenda-files (and (eq predicate 'agenda)
18477 (mapcar 'file-truename (org-agenda-files t))))
18478 (filter
18479 (cond
18480 ((eq predicate 'files)
18481 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18482 ((eq predicate 'export)
18483 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18484 ((eq predicate 'agenda)
18485 (lambda (b)
18486 (with-current-buffer b
18487 (and (derived-mode-p 'org-mode)
18488 (setq bfn (buffer-file-name b))
18489 (member (file-truename bfn) agenda-files)))))
18490 (t (lambda (b) (with-current-buffer b
18491 (or (derived-mode-p 'org-mode)
18492 (string-match "\\*Org .*Export"
18493 (buffer-name b)))))))))
18494 (delq nil
18495 (mapcar
18496 (lambda(b)
18497 (if (and (funcall filter b)
18498 (or (not exclude-tmp)
18499 (not (string-match "tmp" (buffer-name b)))))
18501 nil))
18502 (buffer-list)))))
18504 (defun org-agenda-files (&optional unrestricted archives)
18505 "Get the list of agenda files.
18506 Optional UNRESTRICTED means return the full list even if a restriction
18507 is currently in place.
18508 When ARCHIVES is t, include all archive files that are really being
18509 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18510 `org-agenda-archives-mode' is t."
18511 (let ((files
18512 (cond
18513 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18514 ((stringp org-agenda-files) (org-read-agenda-file-list))
18515 ((listp org-agenda-files) org-agenda-files)
18516 (t (error "Invalid value of `org-agenda-files'")))))
18517 (setq files (apply 'append
18518 (mapcar (lambda (f)
18519 (if (file-directory-p f)
18520 (directory-files
18521 f t org-agenda-file-regexp)
18522 (list f)))
18523 files)))
18524 (when org-agenda-skip-unavailable-files
18525 (setq files (delq nil
18526 (mapcar (function
18527 (lambda (file)
18528 (and (file-readable-p file) file)))
18529 files))))
18530 (when (or (eq archives t)
18531 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18532 (setq files (org-add-archive-files files)))
18533 files))
18535 (defun org-agenda-file-p (&optional file)
18536 "Return non-nil, if FILE is an agenda file.
18537 If FILE is omitted, use the file associated with the current
18538 buffer."
18539 (let ((fname (or file (buffer-file-name))))
18540 (and fname
18541 (member (file-truename fname)
18542 (mapcar #'file-truename (org-agenda-files t))))))
18544 (defun org-edit-agenda-file-list ()
18545 "Edit the list of agenda files.
18546 Depending on setup, this either uses customize to edit the variable
18547 `org-agenda-files', or it visits the file that is holding the list. In the
18548 latter case, the buffer is set up in a way that saving it automatically kills
18549 the buffer and restores the previous window configuration."
18550 (interactive)
18551 (if (stringp org-agenda-files)
18552 (let ((cw (current-window-configuration)))
18553 (find-file org-agenda-files)
18554 (setq-local org-window-configuration cw)
18555 (org-add-hook 'after-save-hook
18556 (lambda ()
18557 (set-window-configuration
18558 (prog1 org-window-configuration
18559 (kill-buffer (current-buffer))))
18560 (org-install-agenda-files-menu)
18561 (message "New agenda file list installed"))
18562 nil 'local)
18563 (message "%s" (substitute-command-keys
18564 "Edit list and finish with \\[save-buffer]")))
18565 (customize-variable 'org-agenda-files)))
18567 (defun org-store-new-agenda-file-list (list)
18568 "Set new value for the agenda file list and save it correctly."
18569 (if (stringp org-agenda-files)
18570 (let ((fe (org-read-agenda-file-list t)) b u)
18571 (while (setq b (find-buffer-visiting org-agenda-files))
18572 (kill-buffer b))
18573 (with-temp-file org-agenda-files
18574 (insert
18575 (mapconcat
18576 (lambda (f) ;; Keep un-expanded entries.
18577 (if (setq u (assoc f fe))
18578 (cdr u)
18580 list "\n")
18581 "\n")))
18582 (let ((org-mode-hook nil) (org-inhibit-startup t)
18583 (org-insert-mode-line-in-empty-file nil))
18584 (setq org-agenda-files list)
18585 (customize-save-variable 'org-agenda-files org-agenda-files))))
18587 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18588 "Read the list of agenda files from a file.
18589 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18590 filenames, used by `org-store-new-agenda-file-list' to write back
18591 un-expanded file names."
18592 (when (file-directory-p org-agenda-files)
18593 (error "`org-agenda-files' cannot be a single directory"))
18594 (when (stringp org-agenda-files)
18595 (with-temp-buffer
18596 (insert-file-contents org-agenda-files)
18597 (mapcar
18598 (lambda (f)
18599 (let ((e (expand-file-name (substitute-in-file-name f)
18600 org-directory)))
18601 (if pair-with-expansion
18602 (cons e f)
18603 e)))
18604 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18606 ;;;###autoload
18607 (defun org-cycle-agenda-files ()
18608 "Cycle through the files in `org-agenda-files'.
18609 If the current buffer visits an agenda file, find the next one in the list.
18610 If the current buffer does not, find the first agenda file."
18611 (interactive)
18612 (let* ((fs (or (org-agenda-files t)
18613 (user-error "No agenda files")))
18614 (files (copy-sequence fs))
18615 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18616 file)
18617 (when tcf
18618 (while (and (setq file (pop files))
18619 (not (equal (file-truename file) tcf)))))
18620 (find-file (car (or files fs)))
18621 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18623 (defun org-agenda-file-to-front (&optional to-end)
18624 "Move/add the current file to the top of the agenda file list.
18625 If the file is not present in the list, it is added to the front. If it is
18626 present, it is moved there. With optional argument TO-END, add/move to the
18627 end of the list."
18628 (interactive "P")
18629 (let ((org-agenda-skip-unavailable-files nil)
18630 (file-alist (mapcar (lambda (x)
18631 (cons (file-truename x) x))
18632 (org-agenda-files t)))
18633 (ctf (file-truename
18634 (or buffer-file-name
18635 (user-error "Please save the current buffer to a file"))))
18636 x had)
18637 (setq x (assoc ctf file-alist) had x)
18639 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18640 (if to-end
18641 (setq file-alist (append (delq x file-alist) (list x)))
18642 (setq file-alist (cons x (delq x file-alist))))
18643 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18644 (org-install-agenda-files-menu)
18645 (message "File %s to %s of agenda file list"
18646 (if had "moved" "added") (if to-end "end" "front"))))
18648 (defun org-remove-file (&optional file)
18649 "Remove current file from the list of files in variable `org-agenda-files'.
18650 These are the files which are being checked for agenda entries.
18651 Optional argument FILE means use this file instead of the current."
18652 (interactive)
18653 (let* ((org-agenda-skip-unavailable-files nil)
18654 (file (or file buffer-file-name
18655 (user-error "Current buffer does not visit a file")))
18656 (true-file (file-truename file))
18657 (afile (abbreviate-file-name file))
18658 (files (delq nil (mapcar
18659 (lambda (x)
18660 (unless (equal true-file
18661 (file-truename x))
18663 (org-agenda-files t)))))
18664 (if (not (= (length files) (length (org-agenda-files t))))
18665 (progn
18666 (org-store-new-agenda-file-list files)
18667 (org-install-agenda-files-menu)
18668 (message "Removed from Org Agenda list: %s" afile))
18669 (message "File was not in list: %s (not removed)" afile))))
18671 (defun org-file-menu-entry (file)
18672 (vector file (list 'find-file file) t))
18674 (defun org-check-agenda-file (file)
18675 "Make sure FILE exists. If not, ask user what to do."
18676 (unless (file-exists-p file)
18677 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18678 (abbreviate-file-name file))
18679 (let ((r (downcase (read-char-exclusive))))
18680 (cond
18681 ((equal r ?r)
18682 (org-remove-file file)
18683 (throw 'nextfile t))
18684 (t (user-error "Abort"))))))
18686 (defun org-get-agenda-file-buffer (file)
18687 "Get an agenda buffer visiting FILE.
18688 If the buffer needs to be created, add it to the list of buffers
18689 which might be released later."
18690 (let ((buf (org-find-base-buffer-visiting file)))
18691 (if buf
18692 buf ; just return it
18693 ;; Make a new buffer and remember it
18694 (setq buf (find-file-noselect file))
18695 (when buf (push buf org-agenda-new-buffers))
18696 buf)))
18698 (defun org-release-buffers (blist)
18699 "Release all buffers in list, asking the user for confirmation when needed.
18700 When a buffer is unmodified, it is just killed. When modified, it is saved
18701 \(if the user agrees) and then killed."
18702 (let (file)
18703 (dolist (buf blist)
18704 (setq file (buffer-file-name buf))
18705 (when (and (buffer-modified-p buf)
18706 file
18707 (y-or-n-p (format "Save file %s? " file)))
18708 (with-current-buffer buf (save-buffer)))
18709 (kill-buffer buf))))
18711 (defun org-agenda-prepare-buffers (files)
18712 "Create buffers for all agenda files, protect archived trees and comments."
18713 (interactive)
18714 (let ((pa '(:org-archived t))
18715 (pc '(:org-comment t))
18716 (pall '(:org-archived t :org-comment t))
18717 (inhibit-read-only t)
18718 (org-inhibit-startup org-agenda-inhibit-startup)
18719 (rea (concat ":" org-archive-tag ":"))
18720 re pos)
18721 (setq org-tag-alist-for-agenda nil
18722 org-tag-groups-alist-for-agenda nil)
18723 (save-excursion
18724 (save-restriction
18725 (dolist (file files)
18726 (catch 'nextfile
18727 (if (bufferp file)
18728 (set-buffer file)
18729 (org-check-agenda-file file)
18730 (set-buffer (org-get-agenda-file-buffer file)))
18731 (widen)
18732 (org-set-regexps-and-options 'tags-only)
18733 (setq pos (point))
18734 (or (memq 'category org-agenda-ignore-properties)
18735 (org-refresh-category-properties))
18736 (or (memq 'stats org-agenda-ignore-properties)
18737 (org-refresh-stats-properties))
18738 (or (memq 'effort org-agenda-ignore-properties)
18739 (org-refresh-effort-properties))
18740 (or (memq 'appt org-agenda-ignore-properties)
18741 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18742 (setq org-todo-keywords-for-agenda
18743 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18744 (setq org-done-keywords-for-agenda
18745 (append org-done-keywords-for-agenda org-done-keywords))
18746 (setq org-todo-keyword-alist-for-agenda
18747 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18748 (setq org-tag-alist-for-agenda
18749 (org-uniquify
18750 (append org-tag-alist-for-agenda
18751 org-current-tag-alist)))
18752 ;; Merge current file's tag groups into global
18753 ;; `org-tag-groups-alist-for-agenda'.
18754 (when org-group-tags
18755 (dolist (alist org-tag-groups-alist)
18756 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18757 (if old
18758 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18759 (push alist org-tag-groups-alist-for-agenda)))))
18760 (org-with-silent-modifications
18761 (save-excursion
18762 (remove-text-properties (point-min) (point-max) pall)
18763 (when org-agenda-skip-archived-trees
18764 (goto-char (point-min))
18765 (while (re-search-forward rea nil t)
18766 (when (org-at-heading-p t)
18767 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18768 (goto-char (point-min))
18769 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18770 (while (re-search-forward re nil t)
18771 (when (save-match-data (org-in-commented-heading-p t))
18772 (add-text-properties
18773 (match-beginning 0) (org-end-of-subtree t) pc)))))
18774 (goto-char pos)))))
18775 (setq org-todo-keywords-for-agenda
18776 (org-uniquify org-todo-keywords-for-agenda))
18777 (setq org-todo-keyword-alist-for-agenda
18778 (org-uniquify org-todo-keyword-alist-for-agenda))))
18781 ;;;; CDLaTeX minor mode
18783 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18784 "Keymap for the minor `org-cdlatex-mode'.")
18786 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18787 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18788 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18789 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18790 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18792 (defvar org-cdlatex-texmathp-advice-is-done nil
18793 "Flag remembering if we have applied the advice to texmathp already.")
18795 (define-minor-mode org-cdlatex-mode
18796 "Toggle the minor `org-cdlatex-mode'.
18797 This mode supports entering LaTeX environment and math in LaTeX fragments
18798 in Org-mode.
18799 \\{org-cdlatex-mode-map}"
18800 nil " OCDL" nil
18801 (when org-cdlatex-mode
18802 (require 'cdlatex)
18803 (run-hooks 'cdlatex-mode-hook)
18804 (cdlatex-compute-tables))
18805 (unless org-cdlatex-texmathp-advice-is-done
18806 (setq org-cdlatex-texmathp-advice-is-done t)
18807 (defadvice texmathp (around org-math-always-on activate)
18808 "Always return t in org-mode buffers.
18809 This is because we want to insert math symbols without dollars even outside
18810 the LaTeX math segments. If Orgmode thinks that point is actually inside
18811 an embedded LaTeX fragment, let texmathp do its job.
18812 \\[org-cdlatex-mode-map]"
18813 (interactive)
18814 (let (p)
18815 (cond
18816 ((not (derived-mode-p 'org-mode)) ad-do-it)
18817 ((eq this-command 'cdlatex-math-symbol)
18818 (setq ad-return-value t
18819 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18821 (let ((p (org-inside-LaTeX-fragment-p)))
18822 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18823 (setq ad-return-value t
18824 texmathp-why '("Org-mode embedded math" . 0))
18825 (when p ad-do-it)))))))))
18827 (defun turn-on-org-cdlatex ()
18828 "Unconditionally turn on `org-cdlatex-mode'."
18829 (org-cdlatex-mode 1))
18831 (defun org-try-cdlatex-tab ()
18832 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18833 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18834 - inside a LaTeX fragment, or
18835 - after the first word in a line, where an abbreviation expansion could
18836 insert a LaTeX environment."
18837 (when org-cdlatex-mode
18838 (cond
18839 ;; Before any word on the line: No expansion possible.
18840 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18841 ;; Just after first word on the line: Expand it. Make sure it
18842 ;; cannot happen on headlines, though.
18843 ((save-excursion
18844 (skip-chars-backward "a-zA-Z0-9*")
18845 (skip-chars-backward " \t")
18846 (and (bolp) (not (org-at-heading-p))))
18847 (cdlatex-tab) t)
18848 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18850 (defun org-cdlatex-underscore-caret (&optional _arg)
18851 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18852 Revert to the normal definition outside of these fragments."
18853 (interactive "P")
18854 (if (org-inside-LaTeX-fragment-p)
18855 (call-interactively 'cdlatex-sub-superscript)
18856 (let (org-cdlatex-mode)
18857 (call-interactively (key-binding (vector last-input-event))))))
18859 (defun org-cdlatex-math-modify (&optional _arg)
18860 "Execute `cdlatex-math-modify' in LaTeX fragments.
18861 Revert to the normal definition outside of these fragments."
18862 (interactive "P")
18863 (if (org-inside-LaTeX-fragment-p)
18864 (call-interactively 'cdlatex-math-modify)
18865 (let (org-cdlatex-mode)
18866 (call-interactively (key-binding (vector last-input-event))))))
18868 (defun org-cdlatex-environment-indent (&optional environment item)
18869 "Execute `cdlatex-environment' and indent the inserted environment.
18871 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18873 The inserted environment is indented to current indentation
18874 unless point is at the beginning of the line, in which the
18875 environment remains unintended."
18876 (interactive)
18877 ;; cdlatex-environment always return nil. Therefore, capture output
18878 ;; first and determine if an environment was selected.
18879 (let* ((beg (point-marker))
18880 (end (copy-marker (point) t))
18881 (inserted (progn
18882 (ignore-errors (cdlatex-environment environment item))
18883 (< beg end)))
18884 ;; Figure out how many lines to move forward after the
18885 ;; environment has been inserted.
18886 (lines (when inserted
18887 (save-excursion
18888 (- (cl-loop while (< beg (point))
18889 with x = 0
18890 do (forward-line -1)
18891 (cl-incf x)
18892 finally return x)
18893 (if (progn (goto-char beg)
18894 (and (progn (skip-chars-forward " \t") (eolp))
18895 (progn (skip-chars-backward " \t") (bolp))))
18896 1 0)))))
18897 (env (org-trim (delete-and-extract-region beg end))))
18898 (when inserted
18899 ;; Get indentation of next line unless at column 0.
18900 (let ((ind (if (bolp) 0
18901 (save-excursion
18902 (org-return-indent)
18903 (prog1 (org-get-indentation)
18904 (when (progn (skip-chars-forward " \t") (eolp))
18905 (delete-region beg (point)))))))
18906 (bol (progn (skip-chars-backward " \t") (bolp))))
18907 ;; Insert a newline before environment unless at column zero
18908 ;; to "escape" the current line. Insert a newline if
18909 ;; something is one the same line as \end{ENVIRONMENT}.
18910 (insert
18911 (concat (unless bol "\n") env
18912 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18913 (unless (zerop ind)
18914 (save-excursion
18915 (goto-char beg)
18916 (while (< (point) end)
18917 (unless (eolp) (org-indent-line-to ind))
18918 (forward-line))))
18919 (goto-char beg)
18920 (forward-line lines)
18921 (org-indent-line-to ind)))
18922 (set-marker beg nil)
18923 (set-marker end nil)))
18926 ;;;; LaTeX fragments
18928 (defun org-inside-LaTeX-fragment-p ()
18929 "Test if point is inside a LaTeX fragment.
18930 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18931 sequence appearing also before point.
18932 Even though the matchers for math are configurable, this function assumes
18933 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18934 delimiters are skipped when they have been removed by customization.
18935 The return value is nil, or a cons cell with the delimiter and the
18936 position of this delimiter.
18938 This function does a reasonably good job, but can locally be fooled by
18939 for example currency specifications. For example it will assume being in
18940 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18941 fragments that are properly closed, but during editing, we have to live
18942 with the uncertainty caused by missing closing delimiters. This function
18943 looks only before point, not after."
18944 (catch 'exit
18945 (let ((pos (point))
18946 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18947 (lim (progn
18948 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18949 (point)))
18950 dd-on str (start 0) m re)
18951 (goto-char pos)
18952 (when dodollar
18953 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18954 re (nth 1 (assoc "$" org-latex-regexps)))
18955 (while (string-match re str start)
18956 (cond
18957 ((= (match-end 0) (length str))
18958 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18959 ((= (match-end 0) (- (length str) 5))
18960 (throw 'exit nil))
18961 (t (setq start (match-end 0))))))
18962 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18963 (goto-char pos)
18964 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18965 (and (match-beginning 2) (throw 'exit nil))
18966 ;; count $$
18967 (while (re-search-backward "\\$\\$" lim t)
18968 (setq dd-on (not dd-on)))
18969 (goto-char pos)
18970 (when dd-on (cons "$$" m))))))
18972 (defun org-inside-latex-macro-p ()
18973 "Is point inside a LaTeX macro or its arguments?"
18974 (save-match-data
18975 (org-in-regexp
18976 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18978 (defun org--format-latex-make-overlay (beg end image)
18979 "Build an overlay between BEG and END using IMAGE file."
18980 (let ((ov (make-overlay beg end)))
18981 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18982 (overlay-put ov 'evaporate t)
18983 (overlay-put ov
18984 'modification-hooks
18985 (list (lambda (o _flag _beg _end &optional _l)
18986 (delete-overlay o))))
18987 (if (featurep 'xemacs)
18988 (progn
18989 (overlay-put ov 'invisible t)
18990 (overlay-put ov 'end-glyph (make-glyph (vector 'png :file image))))
18991 (overlay-put ov
18992 'display
18993 (list 'image :type 'png :file image :ascent 'center)))))
18995 (defun org--list-latex-overlays (&optional beg end)
18996 "List all Org LaTeX overlays in current buffer.
18997 Limit to overlays between BEG and END when those are provided."
18998 (cl-remove-if-not
18999 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19000 (overlays-in (or beg (point-min)) (or end (point-max)))))
19002 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19003 "Remove all overlays with LaTeX fragment images in current buffer.
19004 When optional arguments BEG and END are non-nil, remove all
19005 overlays between them instead. Return a non-nil value when some
19006 overlays were removed, nil otherwise."
19007 (let ((overlays (org--list-latex-overlays beg end)))
19008 (mapc #'delete-overlay overlays)
19009 overlays))
19011 (define-obsolete-function-alias
19012 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
19013 (defun org-toggle-latex-fragment (&optional arg)
19014 "Preview the LaTeX fragment at point, or all locally or globally.
19016 If the cursor is on a LaTeX fragment, create the image and overlay
19017 it over the source code, if there is none. Remove it otherwise.
19018 If there is no fragment at point, display all fragments in the
19019 current section.
19021 With prefix ARG, preview or clear image for all fragments in the
19022 current subtree or in the whole buffer when used before the first
19023 headline. With a double prefix ARG \\[universal-argument] \
19024 \\[universal-argument] preview or clear images
19025 for all fragments in the buffer."
19026 (interactive "P")
19027 (when (display-graphic-p)
19028 (catch 'exit
19029 (save-excursion
19030 (let ((window-start (window-start)) msg)
19031 (save-restriction
19032 (cond
19033 ((or (equal arg '(16))
19034 (and (equal arg '(4))
19035 (org-with-limited-levels (org-before-first-heading-p))))
19036 (if (org-remove-latex-fragment-image-overlays)
19037 (progn (message "LaTeX fragments images removed from buffer")
19038 (throw 'exit nil))
19039 (setq msg "Creating images for buffer...")))
19040 ((equal arg '(4))
19041 (org-with-limited-levels (org-back-to-heading t))
19042 (let ((beg (point))
19043 (end (progn (org-end-of-subtree t) (point))))
19044 (if (org-remove-latex-fragment-image-overlays beg end)
19045 (progn
19046 (message "LaTeX fragment images removed from subtree")
19047 (throw 'exit nil))
19048 (setq msg "Creating images for subtree...")
19049 (narrow-to-region beg end))))
19050 ((let ((datum (org-element-context)))
19051 (when (memq (org-element-type datum)
19052 '(latex-environment latex-fragment))
19053 (let* ((beg (org-element-property :begin datum))
19054 (end (org-element-property :end datum)))
19055 (if (org-remove-latex-fragment-image-overlays beg end)
19056 (progn (message "LaTeX fragment image removed")
19057 (throw 'exit nil))
19058 (narrow-to-region beg end)
19059 (setq msg "Creating image..."))))))
19061 (org-with-limited-levels
19062 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19063 (outline-previous-heading)
19064 (point)))
19065 (end (progn (outline-next-heading) (point))))
19066 (if (org-remove-latex-fragment-image-overlays beg end)
19067 (progn
19068 (message "LaTeX fragment images removed from section")
19069 (throw 'exit nil))
19070 (setq msg "Creating images for section...")
19071 (narrow-to-region beg end))))))
19072 (let ((file (buffer-file-name (buffer-base-buffer))))
19073 (org-format-latex
19074 (concat org-latex-preview-ltxpng-directory "org-ltxpng")
19075 ;; Emacs cannot overlay images from remote hosts.
19076 ;; Create it in `temporary-file-directory' instead.
19077 (if (or (not file) (file-remote-p file))
19078 temporary-file-directory
19079 default-directory)
19080 'overlays msg 'forbuffer
19081 org-latex-create-formula-image-program)))
19082 ;; Work around a bug that doesn't restore window's start
19083 ;; when widening back the buffer.
19084 (set-window-start nil window-start)
19085 (message (concat msg "done")))))))
19087 (defun org-format-latex
19088 (prefix &optional dir overlays msg forbuffer processing-type)
19089 "Replace LaTeX fragments with links to an image, and produce images.
19091 When optional argument OVERLAYS is non-nil, display the image on
19092 top of the fragment instead of replacing it.
19094 PROCESSING-TYPE is the conversion method to use, as a symbol.
19096 Some of the options can be changed using the variable
19097 `org-format-latex-options', which see."
19098 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19099 (unless (eq processing-type 'verbatim)
19100 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19101 (cnt 0)
19102 checkdir-flag)
19103 (goto-char (point-min))
19104 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19105 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19106 (overlay-recenter (point-max)))
19107 (while (re-search-forward math-regexp nil t)
19108 (unless (and overlays
19109 (eq (get-char-property (point) 'org-overlay-type)
19110 'org-latex-overlay))
19111 (let* ((context (org-element-context))
19112 (type (org-element-type context)))
19113 (when (memq type '(latex-environment latex-fragment))
19114 (let ((block-type (eq type 'latex-environment))
19115 (value (org-element-property :value context))
19116 (beg (org-element-property :begin context))
19117 (end (save-excursion
19118 (goto-char (org-element-property :end context))
19119 (skip-chars-backward " \r\t\n")
19120 (point))))
19121 (cl-case processing-type
19122 (mathjax
19123 ;; Prepare for MathJax processing.
19124 (if (not (string-match "\\`\\$\\$?" value))
19125 (goto-char end)
19126 (delete-region beg end)
19127 (if (string= (match-string 0 value) "$$")
19128 (insert "\\[" (substring value 2 -2) "\\]")
19129 (insert "\\(" (substring value 1 -1) "\\)"))))
19130 ((dvipng imagemagick)
19131 ;; Process to an image.
19132 (cl-incf cnt)
19133 (goto-char beg)
19134 (let* ((face (face-at-point))
19135 ;; Get the colors from the face at point.
19137 (let ((color (plist-get org-format-latex-options
19138 :foreground)))
19139 (if (and forbuffer (eq color 'auto))
19140 (face-attribute face :foreground nil 'default)
19141 color)))
19143 (let ((color (plist-get org-format-latex-options
19144 :background)))
19145 (if (and forbuffer (eq color 'auto))
19146 (face-attribute face :background nil 'default)
19147 color)))
19148 (hash (sha1 (prin1-to-string
19149 (list org-format-latex-header
19150 org-latex-default-packages-alist
19151 org-latex-packages-alist
19152 org-format-latex-options
19153 forbuffer value fg bg))))
19154 (absprefix (expand-file-name prefix dir))
19155 (linkfile (format "%s_%s.png" prefix hash))
19156 (movefile (format "%s_%s.png" absprefix hash))
19157 (sep (and block-type "\n\n"))
19158 (link (concat sep "[[file:" linkfile "]]" sep))
19159 (options
19160 (org-combine-plists
19161 org-format-latex-options
19162 `(:foreground ,fg :background ,bg))))
19163 (when msg (message msg cnt))
19164 (unless checkdir-flag ; Ensure the directory exists.
19165 (setq checkdir-flag t)
19166 (let ((todir (file-name-directory absprefix)))
19167 (unless (file-directory-p todir)
19168 (make-directory todir t))))
19169 (unless (file-exists-p movefile)
19170 (org-create-formula-image
19171 value movefile options forbuffer processing-type))
19172 (if overlays
19173 (progn
19174 (dolist (o (overlays-in beg end))
19175 (when (eq (overlay-get o 'org-overlay-type)
19176 'org-latex-overlay)
19177 (delete-overlay o)))
19178 (org--format-latex-make-overlay beg end movefile)
19179 (goto-char end))
19180 (delete-region beg end)
19181 (insert
19182 (org-add-props link
19183 (list 'org-latex-src
19184 (replace-regexp-in-string "\"" "" value)
19185 'org-latex-src-embed-type
19186 (if block-type 'paragraph 'character)))))))
19187 (mathml
19188 ;; Process to MathML.
19189 (unless (org-format-latex-mathml-available-p)
19190 (user-error "LaTeX to MathML converter not configured"))
19191 (cl-incf cnt)
19192 (when msg (message msg cnt))
19193 (goto-char beg)
19194 (delete-region beg end)
19195 (insert (org-format-latex-as-mathml
19196 value block-type prefix dir)))
19197 (otherwise
19198 (error "Unknown conversion type %s for LaTeX fragments"
19199 processing-type)))))))))))
19201 (defun org-create-math-formula (latex-frag &optional mathml-file)
19202 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19203 Use `org-latex-to-mathml-convert-command'. If the conversion is
19204 sucessful, return the portion between \"<math...> </math>\"
19205 elements otherwise return nil. When MATHML-FILE is specified,
19206 write the results in to that file. When invoked as an
19207 interactive command, prompt for LATEX-FRAG, with initial value
19208 set to the current active region and echo the results for user
19209 inspection."
19210 (interactive (list (let ((frag (when (org-region-active-p)
19211 (buffer-substring-no-properties
19212 (region-beginning) (region-end)))))
19213 (read-string "LaTeX Fragment: " frag nil frag))))
19214 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19215 (let* ((tmp-in-file
19216 (let ((file (file-relative-name
19217 (make-temp-name (expand-file-name "ltxmathml-in")))))
19218 (write-region latex-frag nil file)
19219 file))
19220 (tmp-out-file (file-relative-name
19221 (make-temp-name (expand-file-name "ltxmathml-out"))))
19222 (cmd (format-spec
19223 org-latex-to-mathml-convert-command
19224 `((?j . ,(and org-latex-to-mathml-jar-file
19225 (shell-quote-argument
19226 (expand-file-name
19227 org-latex-to-mathml-jar-file))))
19228 (?I . ,(shell-quote-argument tmp-in-file))
19229 (?i . ,latex-frag)
19230 (?o . ,(shell-quote-argument tmp-out-file)))))
19231 mathml shell-command-output)
19232 (when (org-called-interactively-p 'any)
19233 (unless (org-format-latex-mathml-available-p)
19234 (user-error "LaTeX to MathML converter not configured")))
19235 (message "Running %s" cmd)
19236 (setq shell-command-output (shell-command-to-string cmd))
19237 (setq mathml
19238 (when (file-readable-p tmp-out-file)
19239 (with-current-buffer (find-file-noselect tmp-out-file t)
19240 (goto-char (point-min))
19241 (when (re-search-forward
19242 (concat
19243 (regexp-quote
19244 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19245 "[^>]*?>"
19246 "\\(.\\|\n\\)*"
19247 "</math>")
19248 nil t)
19249 (prog1 (match-string 0) (kill-buffer))))))
19250 (cond
19251 (mathml
19252 (setq mathml
19253 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19254 (when mathml-file
19255 (write-region mathml nil mathml-file))
19256 (when (org-called-interactively-p 'any)
19257 (message mathml)))
19258 ((message "LaTeX to MathML conversion failed")
19259 (message shell-command-output)))
19260 (delete-file tmp-in-file)
19261 (when (file-exists-p tmp-out-file)
19262 (delete-file tmp-out-file))
19263 mathml))
19265 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19266 prefix &optional dir)
19267 "Use `org-create-math-formula' but check local cache first."
19268 (let* ((absprefix (expand-file-name prefix dir))
19269 (print-length nil) (print-level nil)
19270 (formula-id (concat
19271 "formula-"
19272 (sha1
19273 (prin1-to-string
19274 (list latex-frag
19275 org-latex-to-mathml-convert-command)))))
19276 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19277 (formula-cache-dir (file-name-directory formula-cache)))
19279 (unless (file-directory-p formula-cache-dir)
19280 (make-directory formula-cache-dir t))
19282 (unless (file-exists-p formula-cache)
19283 (org-create-math-formula latex-frag formula-cache))
19285 (if (file-exists-p formula-cache)
19286 ;; Successful conversion. Return the link to MathML file.
19287 (org-add-props
19288 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19289 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19290 'org-latex-src-embed-type (if latex-frag-type
19291 'paragraph 'character)))
19292 ;; Failed conversion. Return the LaTeX fragment verbatim
19293 latex-frag)))
19295 (defun org-create-formula-image (string tofile options buffer &optional type)
19296 "Create an image from LaTeX source using dvipng or convert.
19297 This function calls either `org-create-formula-image-with-dvipng'
19298 or `org-create-formula-image-with-imagemagick' depending on the
19299 value of `org-latex-create-formula-image-program' or on the value
19300 of the optional TYPE variable.
19302 Note: ultimately these two function should be combined as they
19303 share a good deal of logic."
19304 (org-check-external-command
19305 "latex" "needed to convert LaTeX fragments to images")
19306 (funcall
19307 (cl-case (or type org-latex-create-formula-image-program)
19308 (dvipng
19309 (org-check-external-command
19310 "dvipng" "needed to convert LaTeX fragments to images")
19311 #'org-create-formula-image-with-dvipng)
19312 (imagemagick
19313 (org-check-external-command
19314 "convert" "you need to install imagemagick")
19315 #'org-create-formula-image-with-imagemagick)
19316 (t (error
19317 "Invalid value of `org-latex-create-formula-image-program'")))
19318 string tofile options buffer))
19320 (declare-function org-export-get-backend "ox" (name))
19321 (declare-function org-export--get-global-options "ox" (&optional backend))
19322 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19323 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19324 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19325 (defun org-create-formula--latex-header ()
19326 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19327 (let ((info (org-combine-plists (org-export--get-global-options
19328 (org-export-get-backend 'latex))
19329 (org-export--get-inbuffer-options
19330 (org-export-get-backend 'latex)))))
19331 (org-latex-guess-babel-language
19332 (org-latex-guess-inputenc
19333 (org-splice-latex-header
19334 org-format-latex-header
19335 org-latex-default-packages-alist
19336 org-latex-packages-alist t
19337 (plist-get info :latex-header)))
19338 info)))
19340 (defun org--get-display-dpi ()
19341 "Get the DPI of the display.
19343 Assumes that the display has the same pixel width in the
19344 horizontal and vertical directions."
19345 (if (display-graphic-p)
19346 (round (/ (display-pixel-height)
19347 (/ (display-mm-height) 25.4)))
19348 (error "Attempt to calculate the dpi of a non-graphic display")))
19350 ;; This function borrows from Ganesh Swami's latex2png.el
19351 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19352 "This calls dvipng."
19353 (require 'ox-latex)
19354 (let* ((tmpdir (if (featurep 'xemacs)
19355 (temp-directory)
19356 temporary-file-directory))
19357 (texfilebase (make-temp-name
19358 (expand-file-name "orgtex" tmpdir)))
19359 (texfile (concat texfilebase ".tex"))
19360 (dvifile (concat texfilebase ".dvi"))
19361 (pngfile (concat texfilebase ".png"))
19362 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19363 ;; This assumes that the display has the same pixel width in
19364 ;; the horizontal and vertical directions
19365 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19366 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19367 "Black"))
19368 (bg (or (plist-get options (if buffer :background :html-background))
19369 "Transparent")))
19370 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19371 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19372 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19373 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19374 (let ((latex-header (org-create-formula--latex-header)))
19375 (with-temp-file texfile
19376 (insert latex-header)
19377 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19378 (let ((dir default-directory))
19379 (ignore-errors
19380 (cd tmpdir)
19381 (call-process "latex" nil nil nil texfile))
19382 (cd dir))
19383 (if (not (file-exists-p dvifile))
19384 (progn (message "Failed to create dvi file from %s" texfile) nil)
19385 (ignore-errors
19386 (if (featurep 'xemacs)
19387 (call-process "dvipng" nil nil nil
19388 "-fg" fg "-bg" bg
19389 "-T" "tight"
19390 "-o" pngfile
19391 dvifile)
19392 (call-process "dvipng" nil nil nil
19393 "-fg" fg "-bg" bg
19394 "-D" dpi
19395 ;;"-x" scale "-y" scale
19396 "-T" "tight"
19397 "-o" pngfile
19398 dvifile)))
19399 (if (not (file-exists-p pngfile))
19400 (if org-format-latex-signal-error
19401 (error "Failed to create png file from %s" texfile)
19402 (message "Failed to create png file from %s" texfile)
19403 nil)
19404 ;; Use the requested file name and clean up
19405 (copy-file pngfile tofile 'replace)
19406 (dolist (e '(".dvi" ".tex" ".aux" ".log" ".png" ".out"))
19407 (when (file-exists-p (concat texfilebase e))
19408 (delete-file (concat texfilebase e))))
19409 pngfile))))
19411 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19412 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19413 "This calls convert, which is included into imagemagick."
19414 (require 'ox-latex)
19415 (let* ((tmpdir (if (featurep 'xemacs)
19416 (temp-directory)
19417 temporary-file-directory))
19418 (texfilebase (make-temp-name
19419 (expand-file-name "orgtex" tmpdir)))
19420 (texfile (concat texfilebase ".tex"))
19421 (pdffile (concat texfilebase ".pdf"))
19422 (pngfile (concat texfilebase ".png"))
19423 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19424 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19425 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19426 "black"))
19427 (bg (or (plist-get options (if buffer :background :html-background))
19428 "white")))
19429 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19430 (setq fg (org-latex-color-format fg)))
19431 (if (eq bg 'default) (setq bg (org-latex-color :background))
19432 (setq bg (org-latex-color-format
19433 (if (string= bg "Transparent") "white" bg))))
19434 (let ((latex-header (org-create-formula--latex-header)))
19435 (with-temp-file texfile
19436 (insert latex-header)
19437 (insert "\n\\begin{document}\n"
19438 "\\definecolor{fg}{rgb}{" fg "}\n"
19439 "\\definecolor{bg}{rgb}{" bg "}\n"
19440 "\n\\pagecolor{bg}\n"
19441 "\n{\\color{fg}\n"
19442 string
19443 "\n}\n"
19444 "\n\\end{document}\n")))
19445 (org-latex-compile texfile t)
19446 (if (not (file-exists-p pdffile))
19447 (progn (message "Failed to create pdf file from %s" texfile) nil)
19448 (ignore-errors
19449 (if (featurep 'xemacs)
19450 (call-process "convert" nil nil nil
19451 "-density" "96"
19452 "-trim"
19453 "-antialias"
19454 pdffile
19455 "-quality" "100"
19456 ;; "-sharpen" "0x1.0"
19457 pngfile)
19458 (call-process "convert" nil nil nil
19459 "-density" dpi
19460 "-trim"
19461 "-antialias"
19462 pdffile
19463 "-quality" "100"
19464 ;; "-sharpen" "0x1.0"
19465 pngfile)))
19466 (if (not (file-exists-p pngfile))
19467 (if org-format-latex-signal-error
19468 (error "Failed to create png file from %s" texfile)
19469 (message "Failed to create png file from %s" texfile)
19470 nil)
19471 ;; Use the requested file name and clean up
19472 (copy-file pngfile tofile 'replace)
19473 (dolist (e '(".pdf" ".tex" ".aux" ".log" ".png"))
19474 (when (file-exists-p (concat texfilebase e))
19475 (delete-file (concat texfilebase e))))
19476 pngfile))))
19478 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19479 "Fill a LaTeX header template TPL.
19480 In the template, the following place holders will be recognized:
19482 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19483 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19484 [PACKAGES] \\usepackage statements for PKG
19485 [NO-PACKAGES] do not include PKG
19486 [EXTRA] the string EXTRA
19487 [NO-EXTRA] do not include EXTRA
19489 For backward compatibility, if both the positive and the negative place
19490 holder is missing, the positive one (without the \"NO-\") will be
19491 assumed to be present at the end of the template.
19492 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19493 EXTRA is a string.
19494 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19495 (let (rpl (end ""))
19496 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19497 (setq rpl (if (or (match-end 1) (not def-pkg))
19498 "" (org-latex-packages-to-string def-pkg snippets-p t))
19499 tpl (replace-match rpl t t tpl))
19500 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19502 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19503 (setq rpl (if (or (match-end 1) (not pkg))
19504 "" (org-latex-packages-to-string pkg snippets-p t))
19505 tpl (replace-match rpl t t tpl))
19506 (when pkg (setq end
19507 (concat end "\n"
19508 (org-latex-packages-to-string pkg snippets-p)))))
19510 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19511 (setq rpl (if (or (match-end 1) (not extra))
19512 "" (concat extra "\n"))
19513 tpl (replace-match rpl t t tpl))
19514 (when (and extra (string-match "\\S-" extra))
19515 (setq end (concat end "\n" extra))))
19517 (if (string-match "\\S-" end)
19518 (concat tpl "\n" end)
19519 tpl)))
19521 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19522 "Turn an alist of packages into a string with the \\usepackage macros."
19523 (setq pkg (mapconcat (lambda(p)
19524 (cond
19525 ((stringp p) p)
19526 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19527 (format "%% Package %s omitted" (cadr p)))
19528 ((equal "" (car p))
19529 (format "\\usepackage{%s}" (cadr p)))
19531 (format "\\usepackage[%s]{%s}"
19532 (car p) (cadr p)))))
19534 "\n"))
19535 (if newline (concat pkg "\n") pkg))
19537 (defun org-dvipng-color (attr)
19538 "Return a RGB color specification for dvipng."
19539 (apply 'format "rgb %s %s %s"
19540 (mapcar 'org-normalize-color
19541 (if (featurep 'xemacs)
19542 (color-rgb-components
19543 (face-property 'default
19544 (cond ((eq attr :foreground) 'foreground)
19545 ((eq attr :background) 'background))))
19546 (color-values (face-attribute 'default attr nil))))))
19548 (defun org-dvipng-color-format (color-name)
19549 "Convert COLOR-NAME to a RGB color value for dvipng."
19550 (apply 'format "rgb %s %s %s"
19551 (mapcar 'org-normalize-color
19552 (color-values color-name))))
19554 (defun org-latex-color (attr)
19555 "Return a RGB color for the LaTeX color package."
19556 (apply 'format "%s,%s,%s"
19557 (mapcar 'org-normalize-color
19558 (if (featurep 'xemacs)
19559 (color-rgb-components
19560 (face-property 'default
19561 (cond ((eq attr :foreground) 'foreground)
19562 ((eq attr :background) 'background))))
19563 (color-values (face-attribute 'default attr nil))))))
19565 (defun org-latex-color-format (color-name)
19566 "Convert COLOR-NAME to a RGB color value."
19567 (apply 'format "%s,%s,%s"
19568 (mapcar 'org-normalize-color
19569 (color-values color-name))))
19571 (defun org-normalize-color (value)
19572 "Return string to be used as color value for an RGB component."
19573 (format "%g" (/ value 65535.0)))
19577 ;; Image display
19579 (defvar-local org-inline-image-overlays nil)
19581 (defun org-toggle-inline-images (&optional include-linked)
19582 "Toggle the display of inline images.
19583 INCLUDE-LINKED is passed to `org-display-inline-images'."
19584 (interactive "P")
19585 (if org-inline-image-overlays
19586 (progn
19587 (org-remove-inline-images)
19588 (when (org-called-interactively-p 'interactive)
19589 (message "Inline image display turned off")))
19590 (org-display-inline-images include-linked)
19591 (when (org-called-interactively-p 'interactive)
19592 (message (if org-inline-image-overlays
19593 (format "%d images displayed inline"
19594 (length org-inline-image-overlays))
19595 "No images to display inline")))))
19597 (defun org-redisplay-inline-images ()
19598 "Refresh the display of inline images."
19599 (interactive)
19600 (if (not org-inline-image-overlays)
19601 (org-toggle-inline-images)
19602 (org-toggle-inline-images)
19603 (org-toggle-inline-images)))
19605 (defun org-display-inline-images (&optional include-linked refresh beg end)
19606 "Display inline images.
19608 An inline image is a link which follows either of these
19609 conventions:
19611 1. Its path is a file with an extension matching return value
19612 from `image-file-name-regexp' and it has no contents.
19614 2. Its description consists in a single link of the previous
19615 type.
19617 When optional argument INCLUDE-LINKED is non-nil, also links with
19618 a text description part will be inlined. This can be nice for
19619 a quick look at those images, but it does not reflect what
19620 exported files will look like.
19622 When optional argument REFRESH is non-nil, refresh existing
19623 images between BEG and END. This will create new image displays
19624 only if necessary. BEG and END default to the buffer
19625 boundaries."
19626 (interactive "P")
19627 (when (display-graphic-p)
19628 (unless refresh
19629 (org-remove-inline-images)
19630 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19631 (org-with-wide-buffer
19632 (goto-char (or beg (point-min)))
19633 (let ((case-fold-search t)
19634 (file-extension-re (image-file-name-regexp)))
19635 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19636 (let ((link (save-match-data (org-element-context))))
19637 ;; Check if we're at an inline image.
19638 (when (and (equal (org-element-property :type link) "file")
19639 (or include-linked
19640 (not (org-element-property :contents-begin link)))
19641 (let ((parent (org-element-property :parent link)))
19642 (or (not (eq (org-element-type parent) 'link))
19643 (not (cdr (org-element-contents parent)))))
19644 (org-string-match-p file-extension-re
19645 (org-element-property :path link)))
19646 (let ((file (expand-file-name
19647 (org-link-unescape
19648 (org-element-property :path link)))))
19649 (when (file-exists-p file)
19650 (let ((width
19651 ;; Apply `org-image-actual-width' specifications.
19652 (cond
19653 ((not (image-type-available-p 'imagemagick)) nil)
19654 ((eq org-image-actual-width t) nil)
19655 ((listp org-image-actual-width)
19657 ;; First try to find a width among
19658 ;; attributes associated to the paragraph
19659 ;; containing link.
19660 (let ((paragraph
19661 (let ((e link))
19662 (while (and (setq e (org-element-property
19663 :parent e))
19664 (not (eq (org-element-type e)
19665 'paragraph))))
19666 e)))
19667 (when paragraph
19668 (save-excursion
19669 (goto-char (org-element-property :begin paragraph))
19670 (when
19671 (re-search-forward
19672 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19673 (org-element-property
19674 :post-affiliated paragraph)
19676 (string-to-number (match-string 1))))))
19677 ;; Otherwise, fall-back to provided number.
19678 (car org-image-actual-width)))
19679 ((numberp org-image-actual-width)
19680 org-image-actual-width)))
19681 (old (get-char-property-and-overlay
19682 (org-element-property :begin link)
19683 'org-image-overlay)))
19684 (if (and (car-safe old) refresh)
19685 (image-refresh (overlay-get (cdr old) 'display))
19686 (let ((image (create-image file
19687 (and width 'imagemagick)
19689 :width width)))
19690 (when image
19691 (let* ((link
19692 ;; If inline image is the description
19693 ;; of another link, be sure to
19694 ;; consider the latter as the one to
19695 ;; apply the overlay on.
19696 (let ((parent
19697 (org-element-property :parent link)))
19698 (if (eq (org-element-type parent) 'link)
19699 parent
19700 link)))
19701 (ov (make-overlay
19702 (org-element-property :begin link)
19703 (progn
19704 (goto-char
19705 (org-element-property :end link))
19706 (skip-chars-backward " \t")
19707 (point)))))
19708 (overlay-put ov 'display image)
19709 (overlay-put ov 'face 'default)
19710 (overlay-put ov 'org-image-overlay t)
19711 (overlay-put
19712 ov 'modification-hooks
19713 (list 'org-display-inline-remove-overlay))
19714 (push ov org-inline-image-overlays)))))))))))))))
19716 (define-obsolete-function-alias
19717 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19719 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19720 "Remove inline-display overlay if a corresponding region is modified."
19721 (let ((inhibit-modification-hooks t))
19722 (when (and ov after)
19723 (delete ov org-inline-image-overlays)
19724 (delete-overlay ov))))
19726 (defun org-remove-inline-images ()
19727 "Remove inline display of images."
19728 (interactive)
19729 (mapc #'delete-overlay org-inline-image-overlays)
19730 (setq org-inline-image-overlays nil))
19732 ;;;; Key bindings
19734 ;; Outline functions from `outline-mode-prefix-map'
19735 ;; that can be remapped in Org:
19736 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19737 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19738 (define-key org-mode-map [remap outline-forward-same-level]
19739 'org-forward-heading-same-level)
19740 (define-key org-mode-map [remap outline-backward-same-level]
19741 'org-backward-heading-same-level)
19742 (define-key org-mode-map [remap outline-show-branches]
19743 'org-kill-note-or-show-branches)
19744 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19745 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19746 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19747 (define-key org-mode-map [remap outline-next-visible-heading]
19748 'org-next-visible-heading)
19749 (define-key org-mode-map [remap outline-previous-visible-heading]
19750 'org-previous-visible-heading)
19751 (define-key org-mode-map [remap show-children] 'org-show-children)
19753 ;; Outline functions from `outline-mode-prefix-map' that can not
19754 ;; be remapped in Org:
19756 ;; - the column "key binding" shows whether the Outline function is still
19757 ;; available in Org mode on the same key that it has been bound to in
19758 ;; Outline mode:
19759 ;; - "overridden": key used for a different functionality in Org mode
19760 ;; - else: key still bound to the same Outline function in Org mode
19762 ;; | Outline function | key binding | Org replacement |
19763 ;; |------------------------------------+-------------+--------------------------|
19764 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19765 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19766 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19767 ;; | `show-entry' | overridden | no replacement |
19768 ;; | `show-branches' | `C-c C-k' | still same function |
19769 ;; | `show-subtree' | overridden | visibility cycling |
19770 ;; | `show-all' | overridden | no replacement |
19771 ;; | `hide-subtree' | overridden | visibility cycling |
19772 ;; | `hide-body' | overridden | no replacement |
19773 ;; | `hide-entry' | overridden | visibility cycling |
19774 ;; | `hide-leaves' | overridden | no replacement |
19775 ;; | `hide-sublevels' | overridden | no replacement |
19776 ;; | `hide-other' | overridden | no replacement |
19778 ;; Make `C-c C-x' a prefix key
19779 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19781 ;; TAB key with modifiers
19782 (org-defkey org-mode-map "\C-i" 'org-cycle)
19783 (org-defkey org-mode-map [(tab)] 'org-cycle)
19784 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19785 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19786 ;; The following line is necessary under Suse GNU/Linux
19787 (unless (featurep 'xemacs)
19788 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19789 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19790 (define-key org-mode-map [backtab] 'org-shifttab)
19792 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19793 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19794 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19796 ;; Cursor keys with modifiers
19797 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19798 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19799 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19800 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19802 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19803 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19804 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19805 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19806 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19807 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19809 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19810 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19811 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19812 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19814 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19815 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19816 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19817 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19819 ;; Babel keys
19820 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19821 (dolist (pair org-babel-key-bindings)
19822 (define-key org-babel-map (car pair) (cdr pair)))
19824 ;;; Extra keys for tty access.
19825 ;; We only set them when really needed because otherwise the
19826 ;; menus don't show the simple keys
19828 (when (or org-use-extra-keys
19829 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19830 (not window-system))
19831 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19832 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19833 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19834 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19835 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19836 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19837 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19838 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19839 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19840 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19841 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19842 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19843 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19844 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19845 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19846 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19847 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19848 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19849 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19850 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19851 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19852 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19853 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19854 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19855 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19856 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19857 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19858 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19860 ;; All the other keys
19862 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19863 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19864 (if (boundp 'narrow-map)
19865 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19866 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19867 (if (boundp 'narrow-map)
19868 (org-defkey narrow-map "b" 'org-narrow-to-block)
19869 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19870 (if (boundp 'narrow-map)
19871 (org-defkey narrow-map "e" 'org-narrow-to-element)
19872 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19873 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19874 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19875 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19876 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19877 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19878 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19879 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19880 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19881 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19882 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19883 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19884 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19885 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19886 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19887 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19888 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19889 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19890 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19891 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19892 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19893 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19894 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19895 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19896 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19897 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19898 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19899 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19900 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19901 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19902 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19903 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19904 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19905 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19906 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19907 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19908 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19909 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19910 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19911 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19912 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19913 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19914 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19915 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19916 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19917 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19918 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19919 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19920 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19921 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19922 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19923 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19924 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19925 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19926 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19927 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19928 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19929 (org-defkey org-mode-map "\C-c^" 'org-sort)
19930 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19931 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19932 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19933 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19934 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19935 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19936 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19937 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19938 (org-defkey org-mode-map "\C-m" 'org-return)
19939 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19940 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19941 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19942 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19943 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19944 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19945 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19946 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19947 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19948 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19949 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19950 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19951 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19952 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19953 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19954 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19955 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19956 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19957 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19958 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19959 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19960 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19961 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19962 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19963 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19965 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19966 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19967 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19969 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19970 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19971 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19972 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19973 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19974 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19975 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19976 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19977 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19978 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19979 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19980 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19981 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19982 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19983 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19984 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19985 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19986 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19987 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19988 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19989 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19990 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19992 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19993 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19994 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19995 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19996 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19998 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20000 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20002 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20003 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20005 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20008 (when (featurep 'xemacs)
20009 (org-defkey org-mode-map 'button3 'popup-mode-menu))
20012 (defconst org-speed-commands-default
20014 ("Outline Navigation")
20015 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20016 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20017 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20018 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20019 ("F" . org-next-block)
20020 ("B" . org-previous-block)
20021 ("u" . (org-speed-move-safe 'outline-up-heading))
20022 ("j" . org-goto)
20023 ("g" . (org-refile t))
20024 ("Outline Visibility")
20025 ("c" . org-cycle)
20026 ("C" . org-shifttab)
20027 (" " . org-display-outline-path)
20028 ("s" . org-narrow-to-subtree)
20029 ("=" . org-columns)
20030 ("Outline Structure Editing")
20031 ("U" . org-metaup)
20032 ("D" . org-metadown)
20033 ("r" . org-metaright)
20034 ("l" . org-metaleft)
20035 ("R" . org-shiftmetaright)
20036 ("L" . org-shiftmetaleft)
20037 ("i" . (progn (forward-char 1) (call-interactively
20038 'org-insert-heading-respect-content)))
20039 ("^" . org-sort)
20040 ("w" . org-refile)
20041 ("a" . org-archive-subtree-default-with-confirmation)
20042 ("@" . org-mark-subtree)
20043 ("#" . org-toggle-comment)
20044 ("Clock Commands")
20045 ("I" . org-clock-in)
20046 ("O" . org-clock-out)
20047 ("Meta Data Editing")
20048 ("t" . org-todo)
20049 ("," . (org-priority))
20050 ("0" . (org-priority ?\ ))
20051 ("1" . (org-priority ?A))
20052 ("2" . (org-priority ?B))
20053 ("3" . (org-priority ?C))
20054 (":" . org-set-tags-command)
20055 ("e" . org-set-effort)
20056 ("E" . org-inc-effort)
20057 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20058 (org-entry-put (point) "APPT_WARNTIME" m)))
20059 ("Agenda Views etc")
20060 ("v" . org-agenda)
20061 ("/" . org-sparse-tree)
20062 ("Misc")
20063 ("o" . org-open-at-point)
20064 ("?" . org-speed-command-help)
20065 ("<" . (org-agenda-set-restriction-lock 'subtree))
20066 (">" . (org-agenda-remove-restriction-lock))
20068 "The default speed commands.")
20070 (defun org-print-speed-command (e)
20071 (if (> (length (car e)) 1)
20072 (progn
20073 (princ "\n")
20074 (princ (car e))
20075 (princ "\n")
20076 (princ (make-string (length (car e)) ?-))
20077 (princ "\n"))
20078 (princ (car e))
20079 (princ " ")
20080 (if (symbolp (cdr e))
20081 (princ (symbol-name (cdr e)))
20082 (prin1 (cdr e)))
20083 (princ "\n")))
20085 (defun org-speed-command-help ()
20086 "Show the available speed commands."
20087 (interactive)
20088 (if (not org-use-speed-commands)
20089 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20090 (with-output-to-temp-buffer "*Help*"
20091 (princ "User-defined Speed commands\n===========================\n")
20092 (mapc #'org-print-speed-command org-speed-commands-user)
20093 (princ "\n")
20094 (princ "Built-in Speed commands\n=======================\n")
20095 (mapc #'org-print-speed-command org-speed-commands-default))
20096 (with-current-buffer "*Help*"
20097 (setq truncate-lines t))))
20099 (defun org-speed-move-safe (cmd)
20100 "Execute CMD, but make sure that the cursor always ends up in a headline.
20101 If not, return to the original position and throw an error."
20102 (interactive)
20103 (let ((pos (point)))
20104 (call-interactively cmd)
20105 (unless (and (bolp) (org-at-heading-p))
20106 (goto-char pos)
20107 (error "Boundary reached while executing %s" cmd))))
20109 (defvar org-self-insert-command-undo-counter 0)
20111 (defvar org-table-auto-blank-field) ; defined in org-table.el
20112 (defvar org-speed-command nil)
20114 (define-obsolete-function-alias
20115 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20117 (defun org-speed-command-activate (keys)
20118 "Hook for activating single-letter speed commands.
20119 `org-speed-commands-default' specifies a minimal command set.
20120 Use `org-speed-commands-user' for further customization."
20121 (when (or (and (bolp) (looking-at org-outline-regexp))
20122 (and (functionp org-use-speed-commands)
20123 (funcall org-use-speed-commands)))
20124 (cdr (assoc keys (append org-speed-commands-user
20125 org-speed-commands-default)))))
20127 (define-obsolete-function-alias
20128 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20130 (defun org-babel-speed-command-activate (keys)
20131 "Hook for activating single-letter code block commands."
20132 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20133 (cdr (assoc keys org-babel-key-bindings))))
20135 (defcustom org-speed-command-hook
20136 '(org-speed-command-default-hook org-babel-speed-command-hook)
20137 "Hook for activating speed commands at strategic locations.
20138 Hook functions are called in sequence until a valid handler is
20139 found.
20141 Each hook takes a single argument, a user-pressed command key
20142 which is also a `self-insert-command' from the global map.
20144 Within the hook, examine the cursor position and the command key
20145 and return nil or a valid handler as appropriate. Handler could
20146 be one of an interactive command, a function, or a form.
20148 Set `org-use-speed-commands' to non-nil value to enable this
20149 hook. The default setting is `org-speed-command-activate'."
20150 :group 'org-structure
20151 :version "24.1"
20152 :type 'hook)
20154 (defun org-self-insert-command (N)
20155 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20156 If the cursor is in a table looking at whitespace, the whitespace is
20157 overwritten, and the table is not marked as requiring realignment."
20158 (interactive "p")
20159 (org-check-before-invisible-edit 'insert)
20160 (cond
20161 ((and org-use-speed-commands
20162 (let ((kv (this-command-keys-vector)))
20163 (setq org-speed-command
20164 (run-hook-with-args-until-success
20165 'org-speed-command-hook
20166 (make-string 1 (aref kv (1- (length kv))))))))
20167 (cond
20168 ((commandp org-speed-command)
20169 (setq this-command org-speed-command)
20170 (call-interactively org-speed-command))
20171 ((functionp org-speed-command)
20172 (funcall org-speed-command))
20173 ((and org-speed-command (listp org-speed-command))
20174 (eval org-speed-command))
20175 (t (let (org-use-speed-commands)
20176 (call-interactively 'org-self-insert-command)))))
20177 ((and
20178 (org-at-table-p)
20179 (progn
20180 ;; Check if we blank the field, and if that triggers align.
20181 (and (featurep 'org-table) org-table-auto-blank-field
20182 (memq last-command
20183 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20184 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20185 ;; Got extra space, this field does not determine
20186 ;; column width.
20187 (let (org-table-may-need-update) (org-table-blank-field))
20188 ;; No extra space, this field may determine column
20189 ;; width.
20190 (org-table-blank-field)))
20192 (eq N 1)
20193 (looking-at "[^|\n]* \\( \\)|"))
20194 ;; There is room for insertion without re-aligning the table.
20195 (delete-region (match-beginning 1) (match-end 1))
20196 (self-insert-command N))
20198 (setq org-table-may-need-update t)
20199 (self-insert-command N)
20200 (org-fix-tags-on-the-fly)
20201 (when org-self-insert-cluster-for-undo
20202 (if (not (eq last-command 'org-self-insert-command))
20203 (setq org-self-insert-command-undo-counter 1)
20204 (if (>= org-self-insert-command-undo-counter 20)
20205 (setq org-self-insert-command-undo-counter 1)
20206 (and (> org-self-insert-command-undo-counter 0)
20207 buffer-undo-list (listp buffer-undo-list)
20208 (not (cadr buffer-undo-list)) ; remove nil entry
20209 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20210 (setq org-self-insert-command-undo-counter
20211 (1+ org-self-insert-command-undo-counter))))))))
20213 (defun org-check-before-invisible-edit (kind)
20214 "Check is editing if kind KIND would be dangerous with invisible text around.
20215 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20216 ;; First, try to get out of here as quickly as possible, to reduce overhead
20217 (when (and org-catch-invisible-edits
20218 (or (not (boundp 'visible-mode)) (not visible-mode))
20219 (or (get-char-property (point) 'invisible)
20220 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20221 ;; OK, we need to take a closer look
20222 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20223 (invisible-before-point (unless (bobp) (get-char-property
20224 (1- (point)) 'invisible)))
20225 (border-and-ok-direction
20227 ;; Check if we are acting predictably before invisible text
20228 (and invisible-at-point (not invisible-before-point)
20229 (memq kind '(insert delete-backward)))
20230 ;; Check if we are acting predictably after invisible text
20231 ;; This works not well, and I have turned it off. It seems
20232 ;; better to always show and stop after invisible text.
20233 ;; (and (not invisible-at-point) invisible-before-point
20234 ;; (memq kind '(insert delete)))
20236 (when (or (memq invisible-at-point '(outline org-hide-block t))
20237 (memq invisible-before-point '(outline org-hide-block t)))
20238 (when (eq org-catch-invisible-edits 'error)
20239 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20240 (if (and org-custom-properties-overlays
20241 (y-or-n-p "Display invisible properties in this buffer? "))
20242 (org-toggle-custom-properties-visibility)
20243 ;; Make the area visible
20244 (save-excursion
20245 (when invisible-before-point
20246 (goto-char (previous-single-char-property-change
20247 (point) 'invisible)))
20248 (outline-show-subtree))
20249 (cond
20250 ((eq org-catch-invisible-edits 'show)
20251 ;; That's it, we do the edit after showing
20252 (message
20253 "Unfolding invisible region around point before editing")
20254 (sit-for 1))
20255 ((and (eq org-catch-invisible-edits 'smart)
20256 border-and-ok-direction)
20257 (message "Unfolding invisible region around point before editing"))
20259 ;; Don't do the edit, make the user repeat it in full visibility
20260 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20262 (defun org-fix-tags-on-the-fly ()
20263 (when (and (equal (char-after (point-at-bol)) ?*)
20264 (org-at-heading-p))
20265 (org-align-tags-here org-tags-column)))
20267 (defun org-delete-backward-char (N)
20268 "Like `delete-backward-char', insert whitespace at field end in tables.
20269 When deleting backwards, in tables this function will insert whitespace in
20270 front of the next \"|\" separator, to keep the table aligned. The table will
20271 still be marked for re-alignment if the field did fill the entire column,
20272 because, in this case the deletion might narrow the column."
20273 (interactive "p")
20274 (save-match-data
20275 (org-check-before-invisible-edit 'delete-backward)
20276 (if (and (org-at-table-p)
20277 (eq N 1)
20278 (string-match "|" (buffer-substring (point-at-bol) (point)))
20279 (looking-at ".*?|"))
20280 (let ((pos (point))
20281 (noalign (looking-at "[^|\n\r]* |"))
20282 (c org-table-may-need-update))
20283 (backward-delete-char N)
20284 (unless overwrite-mode
20285 (skip-chars-forward "^|")
20286 (insert " ")
20287 (goto-char (1- pos)))
20288 ;; noalign: if there were two spaces at the end, this field
20289 ;; does not determine the width of the column.
20290 (when noalign (setq org-table-may-need-update c)))
20291 (backward-delete-char N)
20292 (org-fix-tags-on-the-fly))))
20294 (defun org-delete-char (N)
20295 "Like `delete-char', but insert whitespace at field end in tables.
20296 When deleting characters, in tables this function will insert whitespace in
20297 front of the next \"|\" separator, to keep the table aligned. The table will
20298 still be marked for re-alignment if the field did fill the entire column,
20299 because, in this case the deletion might narrow the column."
20300 (interactive "p")
20301 (save-match-data
20302 (org-check-before-invisible-edit 'delete)
20303 (if (and (org-at-table-p)
20304 (not (bolp))
20305 (not (= (char-after) ?|))
20306 (eq N 1))
20307 (if (looking-at ".*?|")
20308 (let ((pos (point))
20309 (noalign (looking-at "[^|\n\r]* |"))
20310 (c org-table-may-need-update))
20311 (replace-match
20312 (concat (substring (match-string 0) 1 -1) " |") nil t)
20313 (goto-char pos)
20314 ;; noalign: if there were two spaces at the end, this field
20315 ;; does not determine the width of the column.
20316 (when noalign (setq org-table-may-need-update c)))
20317 (delete-char N))
20318 (delete-char N)
20319 (org-fix-tags-on-the-fly))))
20321 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20322 (put 'org-self-insert-command 'delete-selection
20323 (lambda ()
20324 (not (run-hook-with-args-until-success
20325 'self-insert-uses-region-functions))))
20326 (put 'orgtbl-self-insert-command 'delete-selection
20327 (lambda ()
20328 (not (run-hook-with-args-until-success
20329 'self-insert-uses-region-functions))))
20330 (put 'org-delete-char 'delete-selection 'supersede)
20331 (put 'org-delete-backward-char 'delete-selection 'supersede)
20332 (put 'org-yank 'delete-selection 'yank)
20334 ;; Make `flyspell-mode' delay after some commands
20335 (put 'org-self-insert-command 'flyspell-delayed t)
20336 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20337 (put 'org-delete-char 'flyspell-delayed t)
20338 (put 'org-delete-backward-char 'flyspell-delayed t)
20340 ;; Make pabbrev-mode expand after org-mode commands
20341 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20342 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20344 (defun org-remap (map &rest commands)
20345 "In MAP, remap the functions given in COMMANDS.
20346 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20347 (let (new old)
20348 (while commands
20349 (setq old (pop commands) new (pop commands))
20350 (if (fboundp 'command-remapping)
20351 (org-defkey map (vector 'remap old) new)
20352 (substitute-key-definition old new map global-map)))))
20354 (defun org-transpose-words ()
20355 "Transpose words for Org.
20356 This uses the `org-mode-transpose-word-syntax-table' syntax
20357 table, which interprets characters in `org-emphasis-alist' as
20358 word constituents."
20359 (interactive)
20360 (with-syntax-table org-mode-transpose-word-syntax-table
20361 (call-interactively 'transpose-words)))
20362 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20364 (when (eq org-enable-table-editor 'optimized)
20365 ;; If the user wants maximum table support, we need to hijack
20366 ;; some standard editing functions
20367 (org-remap org-mode-map
20368 'self-insert-command 'org-self-insert-command
20369 'delete-char 'org-delete-char
20370 'delete-backward-char 'org-delete-backward-char)
20371 (org-defkey org-mode-map "|" 'org-force-self-insert))
20373 (defvar org-ctrl-c-ctrl-c-hook nil
20374 "Hook for functions attaching themselves to `C-c C-c'.
20376 This can be used to add additional functionality to the C-c C-c
20377 key which executes context-dependent commands. This hook is run
20378 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20379 run after the last test.
20381 Each function will be called with no arguments. The function
20382 must check if the context is appropriate for it to act. If yes,
20383 it should do its thing and then return a non-nil value. If the
20384 context is wrong, just do nothing and return nil.")
20386 (defvar org-ctrl-c-ctrl-c-final-hook nil
20387 "Hook for functions attaching themselves to `C-c C-c'.
20389 This can be used to add additional functionality to the C-c C-c
20390 key which executes context-dependent commands. This hook is run
20391 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20392 before the first test.
20394 Each function will be called with no arguments. The function
20395 must check if the context is appropriate for it to act. If yes,
20396 it should do its thing and then return a non-nil value. If the
20397 context is wrong, just do nothing and return nil.")
20399 (defvar org-tab-first-hook nil
20400 "Hook for functions to attach themselves to TAB.
20401 See `org-ctrl-c-ctrl-c-hook' for more information.
20402 This hook runs as the first action when TAB is pressed, even before
20403 `org-cycle' messes around with the `outline-regexp' to cater for
20404 inline tasks and plain list item folding.
20405 If any function in this hook returns t, any other actions that
20406 would have been caused by TAB (such as table field motion or visibility
20407 cycling) will not occur.")
20409 (defvar org-tab-after-check-for-table-hook nil
20410 "Hook for functions to attach themselves to TAB.
20411 See `org-ctrl-c-ctrl-c-hook' for more information.
20412 This hook runs after it has been established that the cursor is not in a
20413 table, but before checking if the cursor is in a headline or if global cycling
20414 should be done.
20415 If any function in this hook returns t, not other actions like visibility
20416 cycling will be done.")
20418 (defvar org-tab-after-check-for-cycling-hook nil
20419 "Hook for functions to attach themselves to TAB.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.
20421 This hook runs after it has been established that not table field motion and
20422 not visibility should be done because of current context. This is probably
20423 the place where a package like yasnippets can hook in.")
20425 (defvar org-tab-before-tab-emulation-hook nil
20426 "Hook for functions to attach themselves to TAB.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.
20428 This hook runs after every other options for TAB have been exhausted, but
20429 before indentation and \t insertion takes place.")
20431 (defvar org-metaleft-hook nil
20432 "Hook for functions attaching themselves to `M-left'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-metaright-hook nil
20435 "Hook for functions attaching themselves to `M-right'.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-metaup-hook nil
20438 "Hook for functions attaching themselves to `M-up'.
20439 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defvar org-metadown-hook nil
20441 "Hook for functions attaching themselves to `M-down'.
20442 See `org-ctrl-c-ctrl-c-hook' for more information.")
20443 (defvar org-shiftmetaleft-hook nil
20444 "Hook for functions attaching themselves to `M-S-left'.
20445 See `org-ctrl-c-ctrl-c-hook' for more information.")
20446 (defvar org-shiftmetaright-hook nil
20447 "Hook for functions attaching themselves to `M-S-right'.
20448 See `org-ctrl-c-ctrl-c-hook' for more information.")
20449 (defvar org-shiftmetaup-hook nil
20450 "Hook for functions attaching themselves to `M-S-up'.
20451 See `org-ctrl-c-ctrl-c-hook' for more information.")
20452 (defvar org-shiftmetadown-hook nil
20453 "Hook for functions attaching themselves to `M-S-down'.
20454 See `org-ctrl-c-ctrl-c-hook' for more information.")
20455 (defvar org-metareturn-hook nil
20456 "Hook for functions attaching themselves to `M-RET'.
20457 See `org-ctrl-c-ctrl-c-hook' for more information.")
20458 (defvar org-shiftup-hook nil
20459 "Hook for functions attaching themselves to `S-up'.
20460 See `org-ctrl-c-ctrl-c-hook' for more information.")
20461 (defvar org-shiftup-final-hook nil
20462 "Hook for functions attaching themselves to `S-up'.
20463 This one runs after all other options except shift-select have been excluded.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-shiftdown-hook nil
20466 "Hook for functions attaching themselves to `S-down'.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-shiftdown-final-hook nil
20469 "Hook for functions attaching themselves to `S-down'.
20470 This one runs after all other options except shift-select have been excluded.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.")
20472 (defvar org-shiftleft-hook nil
20473 "Hook for functions attaching themselves to `S-left'.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.")
20475 (defvar org-shiftleft-final-hook nil
20476 "Hook for functions attaching themselves to `S-left'.
20477 This one runs after all other options except shift-select have been excluded.
20478 See `org-ctrl-c-ctrl-c-hook' for more information.")
20479 (defvar org-shiftright-hook nil
20480 "Hook for functions attaching themselves to `S-right'.
20481 See `org-ctrl-c-ctrl-c-hook' for more information.")
20482 (defvar org-shiftright-final-hook nil
20483 "Hook for functions attaching themselves to `S-right'.
20484 This one runs after all other options except shift-select have been excluded.
20485 See `org-ctrl-c-ctrl-c-hook' for more information.")
20487 (defun org-modifier-cursor-error ()
20488 "Throw an error, a modified cursor command was applied in wrong context."
20489 (user-error "This command is active in special context like tables, headlines or items"))
20491 (defun org-shiftselect-error ()
20492 "Throw an error because Shift-Cursor command was applied in wrong context."
20493 (if (and (boundp 'shift-select-mode) shift-select-mode)
20494 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20495 (user-error "This command works only in special context like headlines or timestamps")))
20497 (defun org-call-for-shift-select (cmd)
20498 (let ((this-command-keys-shift-translated t))
20499 (call-interactively cmd)))
20501 (defun org-shifttab (&optional arg)
20502 "Global visibility cycling or move to previous table field.
20503 Call `org-table-previous-field' within a table.
20504 When ARG is nil, cycle globally through visibility states.
20505 When ARG is a numeric prefix, show contents of this level."
20506 (interactive "P")
20507 (cond
20508 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20509 ((integerp arg)
20510 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20511 (message "Content view to level: %d" arg)
20512 (org-content (prefix-numeric-value arg2))
20513 (org-cycle-show-empty-lines t)
20514 (setq org-cycle-global-status 'overview)))
20515 (t (call-interactively 'org-global-cycle))))
20517 (defun org-shiftmetaleft ()
20518 "Promote subtree or delete table column.
20519 Calls `org-promote-subtree', `org-outdent-item-tree', or
20520 `org-table-delete-column', depending on context. See the
20521 individual commands for more information."
20522 (interactive)
20523 (cond
20524 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20525 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20526 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20527 ((if (not (org-region-active-p)) (org-at-item-p)
20528 (save-excursion (goto-char (region-beginning))
20529 (org-at-item-p)))
20530 (call-interactively 'org-outdent-item-tree))
20531 (t (org-modifier-cursor-error))))
20533 (defun org-shiftmetaright ()
20534 "Demote subtree or insert table column.
20535 Calls `org-demote-subtree', `org-indent-item-tree', or
20536 `org-table-insert-column', depending on context. See the
20537 individual commands for more information."
20538 (interactive)
20539 (cond
20540 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20541 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20542 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20543 ((if (not (org-region-active-p)) (org-at-item-p)
20544 (save-excursion (goto-char (region-beginning))
20545 (org-at-item-p)))
20546 (call-interactively 'org-indent-item-tree))
20547 (t (org-modifier-cursor-error))))
20549 (defun org-shiftmetaup (&optional _arg)
20550 "Drag the line at point up.
20551 In a table, kill the current row.
20552 On a clock timestamp, update the value of the timestamp like `S-<up>'
20553 but also adjust the previous clocked item in the clock history.
20554 Everywhere else, drag the line at point up."
20555 (interactive "P")
20556 (cond
20557 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20558 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20559 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20560 (call-interactively 'org-timestamp-up)))
20561 (t (call-interactively 'org-drag-line-backward))))
20563 (defun org-shiftmetadown (&optional _arg)
20564 "Drag the line at point down.
20565 In a table, insert an empty row at the current line.
20566 On a clock timestamp, update the value of the timestamp like `S-<down>'
20567 but also adjust the previous clocked item in the clock history.
20568 Everywhere else, drag the line at point down."
20569 (interactive "P")
20570 (cond
20571 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20572 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20573 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20574 (call-interactively 'org-timestamp-down)))
20575 (t (call-interactively 'org-drag-line-forward))))
20577 (defsubst org-hidden-tree-error ()
20578 (user-error
20579 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20581 (defun org-metaleft (&optional _arg)
20582 "Promote heading, list item at point or move table column left.
20584 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20585 depending on context. With no specific context, calls the Emacs
20586 default `backward-word'. See the individual commands for more
20587 information.
20589 This function runs the hook `org-metaleft-hook' as a first step,
20590 and returns at first non-nil value."
20591 (interactive "P")
20592 (cond
20593 ((run-hook-with-args-until-success 'org-metaleft-hook))
20594 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20595 ((org-with-limited-levels
20596 (or (org-at-heading-p)
20597 (and (org-region-active-p)
20598 (save-excursion
20599 (goto-char (region-beginning))
20600 (org-at-heading-p)))))
20601 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20602 (call-interactively 'org-do-promote))
20603 ;; At an inline task.
20604 ((org-at-heading-p)
20605 (call-interactively 'org-inlinetask-promote))
20606 ((or (org-at-item-p)
20607 (and (org-region-active-p)
20608 (save-excursion
20609 (goto-char (region-beginning))
20610 (org-at-item-p))))
20611 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20612 (call-interactively 'org-outdent-item))
20613 (t (call-interactively 'backward-word))))
20615 (defun org-metaright (&optional _arg)
20616 "Demote heading, list item at point or move table column right.
20618 In front of a drawer or a block keyword, indent it correctly.
20620 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20621 `org-indnet-drawer' or `org-indent-block' depending on context.
20622 With no specific context, calls the Emacs default `forward-word'.
20623 See the individual commands for more information.
20625 This function runs the hook `org-metaright-hook' as a first step,
20626 and returns at first non-nil value."
20627 (interactive "P")
20628 (cond
20629 ((run-hook-with-args-until-success 'org-metaright-hook))
20630 ((org-at-table-p) (call-interactively 'org-table-move-column))
20631 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20632 ((org-at-block-p) (call-interactively 'org-indent-block))
20633 ((org-with-limited-levels
20634 (or (org-at-heading-p)
20635 (and (org-region-active-p)
20636 (save-excursion
20637 (goto-char (region-beginning))
20638 (org-at-heading-p)))))
20639 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20640 (call-interactively 'org-do-demote))
20641 ;; At an inline task.
20642 ((org-at-heading-p)
20643 (call-interactively 'org-inlinetask-demote))
20644 ((or (org-at-item-p)
20645 (and (org-region-active-p)
20646 (save-excursion
20647 (goto-char (region-beginning))
20648 (org-at-item-p))))
20649 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20650 (call-interactively 'org-indent-item))
20651 (t (call-interactively 'forward-word))))
20653 (defun org-check-for-hidden (what)
20654 "Check if there are hidden headlines/items in the current visual line.
20655 WHAT can be either `headlines' or `items'. If the current line is
20656 an outline or item heading and it has a folded subtree below it,
20657 this function returns t, nil otherwise."
20658 (let ((re (cond
20659 ((eq what 'headlines) org-outline-regexp-bol)
20660 ((eq what 'items) (org-item-beginning-re))
20661 (t (error "This should not happen"))))
20662 beg end)
20663 (save-excursion
20664 (catch 'exit
20665 (unless (org-region-active-p)
20666 (setq beg (point-at-bol))
20667 (beginning-of-line 2)
20668 (while (and (not (eobp)) ;; this is like `next-line'
20669 (get-char-property (1- (point)) 'invisible))
20670 (beginning-of-line 2))
20671 (setq end (point))
20672 (goto-char beg)
20673 (goto-char (point-at-eol))
20674 (setq end (max end (point)))
20675 (while (re-search-forward re end t)
20676 (when (get-char-property (match-beginning 0) 'invisible)
20677 (throw 'exit t))))
20678 nil))))
20680 (defun org-metaup (&optional _arg)
20681 "Move subtree up or move table row up.
20682 Calls `org-move-subtree-up' or `org-table-move-row' or
20683 `org-move-item-up', depending on context. See the individual commands
20684 for more information."
20685 (interactive "P")
20686 (cond
20687 ((run-hook-with-args-until-success 'org-metaup-hook))
20688 ((org-region-active-p)
20689 (let* ((a (min (region-beginning) (region-end)))
20690 (b (1- (max (region-beginning) (region-end))))
20691 (c (save-excursion (goto-char a)
20692 (move-beginning-of-line 0)))
20693 (d (save-excursion (goto-char a)
20694 (move-end-of-line 0) (point))))
20695 (transpose-regions a b c d)
20696 (goto-char c)))
20697 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20698 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20699 ((org-at-item-p) (call-interactively 'org-move-item-up))
20700 (t (org-drag-element-backward))))
20702 (defun org-metadown (&optional _arg)
20703 "Move subtree down or move table row down.
20704 Calls `org-move-subtree-down' or `org-table-move-row' or
20705 `org-move-item-down', depending on context. See the individual
20706 commands for more information."
20707 (interactive "P")
20708 (cond
20709 ((run-hook-with-args-until-success 'org-metadown-hook))
20710 ((org-region-active-p)
20711 (let* ((a (min (region-beginning) (region-end)))
20712 (b (max (region-beginning) (region-end)))
20713 (c (save-excursion (goto-char b)
20714 (move-beginning-of-line 1)))
20715 (d (save-excursion (goto-char b)
20716 (move-end-of-line 1) (1+ (point)))))
20717 (transpose-regions a b c d)
20718 (goto-char d)))
20719 ((org-at-table-p) (call-interactively 'org-table-move-row))
20720 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20721 ((org-at-item-p) (call-interactively 'org-move-item-down))
20722 (t (org-drag-element-forward))))
20724 (defun org-shiftup (&optional arg)
20725 "Increase item in timestamp or increase priority of current headline.
20726 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20727 depending on context. See the individual commands for more information."
20728 (interactive "P")
20729 (cond
20730 ((run-hook-with-args-until-success 'org-shiftup-hook))
20731 ((and org-support-shift-select (org-region-active-p))
20732 (org-call-for-shift-select 'previous-line))
20733 ((org-at-timestamp-p t)
20734 (call-interactively (if org-edit-timestamp-down-means-later
20735 'org-timestamp-down 'org-timestamp-up)))
20736 ((and (not (eq org-support-shift-select 'always))
20737 org-enable-priority-commands
20738 (org-at-heading-p))
20739 (call-interactively 'org-priority-up))
20740 ((and (not org-support-shift-select) (org-at-item-p))
20741 (call-interactively 'org-previous-item))
20742 ((org-clocktable-try-shift 'up arg))
20743 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20744 (org-support-shift-select
20745 (org-call-for-shift-select 'previous-line))
20746 (t (org-shiftselect-error))))
20748 (defun org-shiftdown (&optional arg)
20749 "Decrease item in timestamp or decrease priority of current headline.
20750 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20751 depending on context. See the individual commands for more information."
20752 (interactive "P")
20753 (cond
20754 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20755 ((and org-support-shift-select (org-region-active-p))
20756 (org-call-for-shift-select 'next-line))
20757 ((org-at-timestamp-p t)
20758 (call-interactively (if org-edit-timestamp-down-means-later
20759 'org-timestamp-up 'org-timestamp-down)))
20760 ((and (not (eq org-support-shift-select 'always))
20761 org-enable-priority-commands
20762 (org-at-heading-p))
20763 (call-interactively 'org-priority-down))
20764 ((and (not org-support-shift-select) (org-at-item-p))
20765 (call-interactively 'org-next-item))
20766 ((org-clocktable-try-shift 'down arg))
20767 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20768 (org-support-shift-select
20769 (org-call-for-shift-select 'next-line))
20770 (t (org-shiftselect-error))))
20772 (defun org-shiftright (&optional arg)
20773 "Cycle the thing at point or in the current line, depending on context.
20774 Depending on context, this does one of the following:
20776 - switch a timestamp at point one day into the future
20777 - on a headline, switch to the next TODO keyword.
20778 - on an item, switch entire list to the next bullet type
20779 - on a property line, switch to the next allowed value
20780 - on a clocktable definition line, move time block into the future"
20781 (interactive "P")
20782 (cond
20783 ((run-hook-with-args-until-success 'org-shiftright-hook))
20784 ((and org-support-shift-select (org-region-active-p))
20785 (org-call-for-shift-select 'forward-char))
20786 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20787 ((and (not (eq org-support-shift-select 'always))
20788 (org-at-heading-p))
20789 (let ((org-inhibit-logging
20790 (not org-treat-S-cursor-todo-selection-as-state-change))
20791 (org-inhibit-blocking
20792 (not org-treat-S-cursor-todo-selection-as-state-change)))
20793 (org-call-with-arg 'org-todo 'right)))
20794 ((or (and org-support-shift-select
20795 (not (eq org-support-shift-select 'always))
20796 (org-at-item-bullet-p))
20797 (and (not org-support-shift-select) (org-at-item-p)))
20798 (org-call-with-arg 'org-cycle-list-bullet nil))
20799 ((and (not (eq org-support-shift-select 'always))
20800 (org-at-property-p))
20801 (call-interactively 'org-property-next-allowed-value))
20802 ((org-clocktable-try-shift 'right arg))
20803 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20804 (org-support-shift-select
20805 (org-call-for-shift-select 'forward-char))
20806 (t (org-shiftselect-error))))
20808 (defun org-shiftleft (&optional arg)
20809 "Cycle the thing at point or in the current line, depending on context.
20810 Depending on context, this does one of the following:
20812 - switch a timestamp at point one day into the past
20813 - on a headline, switch to the previous TODO keyword.
20814 - on an item, switch entire list to the previous bullet type
20815 - on a property line, switch to the previous allowed value
20816 - on a clocktable definition line, move time block into the past"
20817 (interactive "P")
20818 (cond
20819 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20820 ((and org-support-shift-select (org-region-active-p))
20821 (org-call-for-shift-select 'backward-char))
20822 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20823 ((and (not (eq org-support-shift-select 'always))
20824 (org-at-heading-p))
20825 (let ((org-inhibit-logging
20826 (not org-treat-S-cursor-todo-selection-as-state-change))
20827 (org-inhibit-blocking
20828 (not org-treat-S-cursor-todo-selection-as-state-change)))
20829 (org-call-with-arg 'org-todo 'left)))
20830 ((or (and org-support-shift-select
20831 (not (eq org-support-shift-select 'always))
20832 (org-at-item-bullet-p))
20833 (and (not org-support-shift-select) (org-at-item-p)))
20834 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20835 ((and (not (eq org-support-shift-select 'always))
20836 (org-at-property-p))
20837 (call-interactively 'org-property-previous-allowed-value))
20838 ((org-clocktable-try-shift 'left arg))
20839 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20840 (org-support-shift-select
20841 (org-call-for-shift-select 'backward-char))
20842 (t (org-shiftselect-error))))
20844 (defun org-shiftcontrolright ()
20845 "Switch to next TODO set."
20846 (interactive)
20847 (cond
20848 ((and org-support-shift-select (org-region-active-p))
20849 (org-call-for-shift-select 'forward-word))
20850 ((and (not (eq org-support-shift-select 'always))
20851 (org-at-heading-p))
20852 (org-call-with-arg 'org-todo 'nextset))
20853 (org-support-shift-select
20854 (org-call-for-shift-select 'forward-word))
20855 (t (org-shiftselect-error))))
20857 (defun org-shiftcontrolleft ()
20858 "Switch to previous TODO set."
20859 (interactive)
20860 (cond
20861 ((and org-support-shift-select (org-region-active-p))
20862 (org-call-for-shift-select 'backward-word))
20863 ((and (not (eq org-support-shift-select 'always))
20864 (org-at-heading-p))
20865 (org-call-with-arg 'org-todo 'previousset))
20866 (org-support-shift-select
20867 (org-call-for-shift-select 'backward-word))
20868 (t (org-shiftselect-error))))
20870 (defun org-shiftcontrolup (&optional n)
20871 "Change timestamps synchronously up in CLOCK log lines.
20872 Optional argument N tells to change by that many units."
20873 (interactive "P")
20874 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20875 (let (org-support-shift-select)
20876 (org-clock-timestamps-up n))
20877 (user-error "Not at a clock log")))
20879 (defun org-shiftcontroldown (&optional n)
20880 "Change timestamps synchronously down in CLOCK log lines.
20881 Optional argument N tells to change by that many units."
20882 (interactive "P")
20883 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20884 (let (org-support-shift-select)
20885 (org-clock-timestamps-down n))
20886 (user-error "Not at a clock log")))
20888 (defun org-increase-number-at-point (&optional inc)
20889 "Increment the number at point.
20890 With an optional prefix numeric argument INC, increment using
20891 this numeric value."
20892 (interactive "p")
20893 (if (not (number-at-point))
20894 (user-error "Not on a number")
20895 (unless inc (setq inc 1))
20896 (let ((pos (point))
20897 (beg (skip-chars-backward "-+^/*0-9eE."))
20898 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20899 (setq nap (buffer-substring-no-properties
20900 (+ pos beg) (+ pos beg end)))
20901 (delete-region (+ pos beg) (+ pos beg end))
20902 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20903 (when (org-at-table-p)
20904 (org-table-align)
20905 (org-table-end-of-field 1))))
20907 (defun org-decrease-number-at-point (&optional inc)
20908 "Decrement the number at point.
20909 With an optional prefix numeric argument INC, decrement using
20910 this numeric value."
20911 (interactive "p")
20912 (org-increase-number-at-point (- (or inc 1))))
20914 (defun org-ctrl-c-ret ()
20915 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20916 (interactive)
20917 (cond
20918 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20919 (t (call-interactively 'org-insert-heading))))
20921 (defun org-find-visible ()
20922 (let ((s (point)))
20923 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20924 (get-char-property s 'invisible)))
20926 (defun org-find-invisible ()
20927 (let ((s (point)))
20928 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20929 (not (get-char-property s 'invisible))))
20932 (defun org-copy-visible (beg end)
20933 "Copy the visible parts of the region."
20934 (interactive "r")
20935 (let (snippets s)
20936 (save-excursion
20937 (save-restriction
20938 (narrow-to-region beg end)
20939 (setq s (goto-char (point-min)))
20940 (while (not (= (point) (point-max)))
20941 (goto-char (org-find-invisible))
20942 (push (buffer-substring s (point)) snippets)
20943 (setq s (goto-char (org-find-visible))))))
20944 (kill-new (apply 'concat (nreverse snippets)))))
20946 (defun org-copy-special ()
20947 "Copy region in table or copy current subtree.
20948 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20949 See the individual commands for more information."
20950 (interactive)
20951 (call-interactively
20952 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20954 (defun org-cut-special ()
20955 "Cut region in table or cut current subtree.
20956 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20957 See the individual commands for more information."
20958 (interactive)
20959 (call-interactively
20960 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20962 (defun org-paste-special (arg)
20963 "Paste rectangular region into table, or past subtree relative to level.
20964 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20965 See the individual commands for more information."
20966 (interactive "P")
20967 (if (org-at-table-p)
20968 (org-table-paste-rectangle)
20969 (org-paste-subtree arg)))
20971 (defsubst org-in-fixed-width-region-p ()
20972 "Is point in a fixed-width region?"
20973 (save-match-data
20974 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20976 (defun org-edit-special (&optional arg)
20977 "Call a special editor for the element at point.
20978 When at a table, call the formula editor with `org-table-edit-formulas'.
20979 When in a source code block, call `org-edit-src-code'.
20980 When in a fixed-width region, call `org-edit-fixed-width-region'.
20981 When in an export block, call `org-edit-export-block'.
20982 When at an #+INCLUDE keyword, visit the included file.
20983 When at a footnote reference, call `org-edit-footnote-reference'
20984 On a link, call `ffap' to visit the link at point.
20985 Otherwise, return a user error."
20986 (interactive "P")
20987 (let ((element (org-element-at-point)))
20988 (cl-assert (not buffer-read-only) nil
20989 "Buffer is read-only: %s" (buffer-name))
20990 (pcase (org-element-type element)
20991 (`src-block
20992 (if (not arg) (org-edit-src-code)
20993 (let* ((info (org-babel-get-src-block-info))
20994 (lang (nth 0 info))
20995 (params (nth 2 info))
20996 (session (cdr (assq :session params))))
20997 (if (not session) (org-edit-src-code)
20998 ;; At a src-block with a session and function called with
20999 ;; an ARG: switch to the buffer related to the inferior
21000 ;; process.
21001 (switch-to-buffer
21002 (funcall (intern (concat "org-babel-prep-session:" lang))
21003 session params))))))
21004 (`keyword
21005 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21006 (org-open-link-from-string
21007 (format "[[%s]]"
21008 (expand-file-name
21009 (let ((value (org-element-property :value element)))
21010 (cond ((not (org-string-nw-p value))
21011 (user-error "No file to edit"))
21012 ((string-match "\\`\"\\(.*?\\)\"" value)
21013 (match-string 1 value))
21014 ((string-match "\\`[^ \t\"]\\S-*" value)
21015 (match-string 0 value))
21016 (t (user-error "No valid file specified")))))))
21017 (user-error "No special environment to edit here")))
21018 (`table
21019 (if (eq (org-element-property :type element) 'table.el)
21020 (org-edit-table.el)
21021 (call-interactively 'org-table-edit-formulas)))
21022 ;; Only Org tables contain `table-row' type elements.
21023 (`table-row (call-interactively 'org-table-edit-formulas))
21024 (`example-block (org-edit-src-code))
21025 (`export-block (org-edit-export-block))
21026 (`fixed-width (org-edit-fixed-width-region))
21028 ;; No notable element at point. Though, we may be at a link or
21029 ;; a footnote reference, which are objects. Thus, scan deeper.
21030 (let ((context (org-element-context element)))
21031 (pcase (org-element-type context)
21032 (`footnote-reference (org-edit-footnote-reference))
21033 (`inline-src-block (org-edit-inline-src-code))
21034 (`link (call-interactively #'ffap))
21035 (_ (user-error "No special environment to edit here"))))))))
21037 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21038 (defun org-ctrl-c-ctrl-c (&optional arg)
21039 "Set tags in headline, or update according to changed information at point.
21041 This command does many different things, depending on context:
21043 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21044 this is what we do.
21046 - If the cursor is on a statistics cookie, update it.
21048 - If the cursor is in a headline, prompt for tags and insert them
21049 into the current line, aligned to `org-tags-column'. When called
21050 with prefix arg, realign all tags in the current buffer.
21052 - If the cursor is in one of the special #+KEYWORD lines, this
21053 triggers scanning the buffer for these lines and updating the
21054 information.
21056 - If the cursor is inside a table, realign the table. This command
21057 works even if the automatic table editor has been turned off.
21059 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21060 the entire table.
21062 - If the cursor is at a footnote reference or definition, jump to
21063 the corresponding definition or references, respectively.
21065 - If the cursor is a the beginning of a dynamic block, update it.
21067 - If the current buffer is a capture buffer, close note and file it.
21069 - If the cursor is on a <<<target>>>, update radio targets and
21070 corresponding links in this buffer.
21072 - If the cursor is on a numbered item in a plain list, renumber the
21073 ordered list.
21075 - If the cursor is on a checkbox, toggle it.
21077 - If the cursor is on a code block, evaluate it. The variable
21078 `org-confirm-babel-evaluate' can be used to control prompting
21079 before code block evaluation, by default every code block
21080 evaluation requires confirmation. Code block evaluation can be
21081 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21082 (interactive "P")
21083 (cond
21084 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21085 org-occur-highlights)
21086 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21087 (org-remove-occur-highlights)
21088 (message "Temporary highlights/overlays removed from current buffer"))
21089 ((and (local-variable-p 'org-finish-function (current-buffer))
21090 (fboundp org-finish-function))
21091 (funcall org-finish-function))
21092 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21094 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21095 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21096 (user-error "C-c C-c can do nothing useful at this location"))
21097 (let* ((context (org-element-context))
21098 (type (org-element-type context)))
21099 (cl-case type
21100 ;; When at a link, act according to the parent instead.
21101 (link (setq context (org-element-property :parent context))
21102 (setq type (org-element-type context)))
21103 ;; Unsupported object types: refer to the first supported
21104 ;; element or object containing it.
21105 ((bold code entity export-snippet inline-babel-call inline-src-block
21106 italic latex-fragment line-break macro strike-through subscript
21107 superscript underline verbatim)
21108 (setq context
21109 (org-element-lineage
21110 context '(radio-target paragraph verse-block table-cell)))))
21111 ;; For convenience: at the first line of a paragraph on the
21112 ;; same line as an item, apply function on that item instead.
21113 (when (eq type 'paragraph)
21114 (let ((parent (org-element-property :parent context)))
21115 (when (and (eq (org-element-type parent) 'item)
21116 (= (line-beginning-position)
21117 (org-element-property :begin parent)))
21118 (setq context parent type 'item))))
21119 ;; Act according to type of element or object at point.
21120 (cl-case type
21121 (clock (org-clock-update-time-maybe))
21122 (dynamic-block
21123 (save-excursion
21124 (goto-char (org-element-property :post-affiliated context))
21125 (org-update-dblock)))
21126 (footnote-definition
21127 (goto-char (org-element-property :post-affiliated context))
21128 (call-interactively 'org-footnote-action))
21129 (footnote-reference (call-interactively 'org-footnote-action))
21130 ((headline inlinetask)
21131 (save-excursion (goto-char (org-element-property :begin context))
21132 (call-interactively 'org-set-tags)))
21133 (item
21134 ;; At an item: a double C-u set checkbox to "[-]"
21135 ;; unconditionally, whereas a single one will toggle its
21136 ;; presence. Without a universal argument, if the item
21137 ;; has a checkbox, toggle it. Otherwise repair the list.
21138 (let* ((box (org-element-property :checkbox context))
21139 (struct (org-element-property :structure context))
21140 (old-struct (copy-tree struct))
21141 (parents (org-list-parents-alist struct))
21142 (prevs (org-list-prevs-alist struct))
21143 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21144 (org-list-set-checkbox
21145 (org-element-property :begin context) struct
21146 (cond ((equal arg '(16)) "[-]")
21147 ((and (not box) (equal arg '(4))) "[ ]")
21148 ((or (not box) (equal arg '(4))) nil)
21149 ((eq box 'on) "[ ]")
21150 (t "[X]")))
21151 ;; Mimic `org-list-write-struct' but with grabbing
21152 ;; a return value from `org-list-struct-fix-box'.
21153 (org-list-struct-fix-ind struct parents 2)
21154 (org-list-struct-fix-item-end struct)
21155 (org-list-struct-fix-bul struct prevs)
21156 (org-list-struct-fix-ind struct parents)
21157 (let ((block-item
21158 (org-list-struct-fix-box struct parents prevs orderedp)))
21159 (if (and box (equal struct old-struct))
21160 (if (equal arg '(16))
21161 (message "Checkboxes already reset")
21162 (user-error "Cannot toggle this checkbox: %s"
21163 (if (eq box 'on)
21164 "all subitems checked"
21165 "unchecked subitems")))
21166 (org-list-struct-apply-struct struct old-struct)
21167 (org-update-checkbox-count-maybe))
21168 (when block-item
21169 (message "Checkboxes were removed due to empty box at line %d"
21170 (org-current-line block-item))))))
21171 (keyword
21172 (let ((org-inhibit-startup-visibility-stuff t)
21173 (org-startup-align-all-tables nil))
21174 (when (boundp 'org-table-coordinate-overlays)
21175 (mapc #'delete-overlay org-table-coordinate-overlays)
21176 (setq org-table-coordinate-overlays nil))
21177 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21178 (message "Local setup has been refreshed"))
21179 (plain-list
21180 ;; At a plain list, with a double C-u argument, set
21181 ;; checkboxes of each item to "[-]", whereas a single one
21182 ;; will toggle their presence according to the state of the
21183 ;; first item in the list. Without an argument, repair the
21184 ;; list.
21185 (let* ((begin (org-element-property :contents-begin context))
21186 (beginm (move-marker (make-marker) begin))
21187 (struct (org-element-property :structure context))
21188 (old-struct (copy-tree struct))
21189 (first-box (save-excursion
21190 (goto-char begin)
21191 (looking-at org-list-full-item-re)
21192 (match-string-no-properties 3)))
21193 (new-box (cond ((equal arg '(16)) "[-]")
21194 ((equal arg '(4)) (unless first-box "[ ]"))
21195 ((equal first-box "[X]") "[ ]")
21196 (t "[X]"))))
21197 (cond
21198 (arg
21199 (dolist (pos
21200 (org-list-get-all-items
21201 begin struct (org-list-prevs-alist struct)))
21202 (org-list-set-checkbox pos struct new-box)))
21203 ((and first-box (eq (point) begin))
21204 ;; For convenience, when point is at bol on the first
21205 ;; item of the list and no argument is provided, simply
21206 ;; toggle checkbox of that item, if any.
21207 (org-list-set-checkbox begin struct new-box)))
21208 (org-list-write-struct
21209 struct (org-list-parents-alist struct) old-struct)
21210 (org-update-checkbox-count-maybe)
21211 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21212 ((property-drawer node-property)
21213 (call-interactively 'org-property-action))
21214 ((radio-target target)
21215 (call-interactively 'org-update-radio-target-regexp))
21216 (statistics-cookie
21217 (call-interactively 'org-update-statistics-cookies))
21218 ((table table-cell table-row)
21219 ;; At a table, recalculate every field and align it. Also
21220 ;; send the table if necessary. If the table has
21221 ;; a `table.el' type, just give up. At a table row or
21222 ;; cell, maybe recalculate line but always align table.
21223 (if (eq (org-element-property :type context) 'table.el)
21224 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21225 Use \\[org-edit-special] to edit table.el tables"))
21226 (let ((org-enable-table-editor t))
21227 (if (or (eq type 'table)
21228 ;; Check if point is at a TBLFM line.
21229 (and (eq type 'table-row)
21230 (= (point) (org-element-property :end context))))
21231 (save-excursion
21232 (if (org-at-TBLFM-p)
21233 (progn (require 'org-table)
21234 (org-table-calc-current-TBLFM))
21235 (goto-char (org-element-property :contents-begin context))
21236 (org-call-with-arg 'org-table-recalculate (or arg t))
21237 (orgtbl-send-table 'maybe)))
21238 (org-table-maybe-eval-formula)
21239 (cond (arg (call-interactively 'org-table-recalculate))
21240 ((org-table-maybe-recalculate-line))
21241 (t (org-table-align)))))))
21242 (timestamp (org-timestamp-change 0 'day))
21243 (otherwise
21244 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21245 (user-error
21246 "C-c C-c can do nothing useful at this location")))))))))
21248 (defun org-mode-restart ()
21249 (interactive)
21250 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21251 (funcall major-mode)
21252 (hack-local-variables)
21253 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21254 (org-indent-mode -1)))
21255 (message "%s restarted" major-mode))
21257 (defun org-kill-note-or-show-branches ()
21258 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21259 (interactive)
21260 (if (not org-finish-function)
21261 (progn
21262 (outline-hide-subtree)
21263 (call-interactively 'outline-show-branches))
21264 (let ((org-note-abort t))
21265 (funcall org-finish-function))))
21267 (defun org-delete-indentation (&optional ARG)
21268 "Join current line to previous and fix whitespace at join.
21270 If previous line is a headline add to headline title. Otherwise
21271 the function calls `delete-indentation'.
21273 With argument, join this line to following line."
21274 (interactive "*P")
21275 (if (save-excursion
21276 (if ARG (beginning-of-line)
21277 (forward-line -1))
21278 (looking-at org-complex-heading-regexp))
21279 ;; At headline.
21280 (let ((tags-column (when (match-beginning 5)
21281 (save-excursion (goto-char (match-beginning 5))
21282 (current-column))))
21283 (string (concat " " (progn (when ARG (forward-line 1))
21284 (org-trim (delete-and-extract-region
21285 (line-beginning-position)
21286 (line-end-position)))))))
21287 (unless (bobp) (delete-region (point) (1- (point))))
21288 (goto-char (or (match-end 4)
21289 (match-beginning 5)
21290 (match-end 0)))
21291 (skip-chars-backward " \t")
21292 (save-excursion (insert string))
21293 ;; Adjust alignment of tags.
21294 (when tags-column
21295 (org-align-tags-here (if org-auto-align-tags
21296 org-tags-column
21297 tags-column))))
21298 (delete-indentation ARG)))
21300 (defun org-open-line (n)
21301 "Insert a new row in tables, call `open-line' elsewhere.
21302 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21303 (interactive "*p")
21304 (cond
21305 ((not org-special-ctrl-o)
21306 (open-line n))
21307 ((org-at-table-p)
21308 (org-table-insert-row))
21310 (open-line n))))
21312 (defun org-return (&optional indent)
21313 "Goto next table row or insert a newline.
21315 Calls `org-table-next-row' or `newline', depending on context.
21317 When optional INDENT argument is non-nil, call
21318 `newline-and-indent' instead of `newline'.
21320 When `org-return-follows-link' is non-nil and point is on
21321 a timestamp or a link, call `org-open-at-point'. However, it
21322 will not happen if point is in a table or on a \"dead\"
21323 object (e.g., within a comment). In these case, you need to use
21324 `org-open-at-point' directly."
21325 (interactive)
21326 (let ((context (if org-return-follows-link (org-element-context)
21327 (org-element-at-point))))
21328 (cond
21329 ;; In a table, call `org-table-next-row'.
21330 ((or (and (eq (org-element-type context) 'table)
21331 (>= (point) (org-element-property :contents-begin context))
21332 (< (point) (org-element-property :contents-end context)))
21333 (org-element-lineage context '(table-row table-cell) t))
21334 (org-table-justify-field-maybe)
21335 (call-interactively #'org-table-next-row))
21336 ;; On a link or a timestamp, call `org-open-at-point' if
21337 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21338 ;; locations, e.g., in a comment, as `org-open-at-point'.
21339 ((and org-return-follows-link
21340 (or (org-in-regexp org-ts-regexp-both nil t)
21341 (org-in-regexp org-tsr-regexp-both nil t)
21342 (org-in-regexp org-any-link-re nil t)))
21343 (call-interactively #'org-open-at-point))
21344 ;; Insert newline in heading, but preserve tags.
21345 ((and (not (bolp))
21346 (save-excursion (beginning-of-line)
21347 (looking-at org-complex-heading-regexp)))
21348 ;; At headline. Split line. However, if point is on keyword,
21349 ;; priority cookie or tags, do not break any of them: add
21350 ;; a newline after the headline instead.
21351 (let ((tags-column (and (match-beginning 5)
21352 (save-excursion (goto-char (match-beginning 5))
21353 (current-column))))
21354 (string
21355 (when (and (match-end 4)
21356 (>= (point)
21357 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21358 (<= (point) (match-end 4)))
21359 (delete-and-extract-region (point) (match-end 4)))))
21360 (when (and tags-column string) ; Adjust tag alignment.
21361 (org-align-tags-here
21362 (if org-auto-align-tags org-tags-column tags-column)))
21363 (end-of-line)
21364 (org-show-entry)
21365 (if indent (newline-and-indent) (newline))
21366 (when string (save-excursion (insert (org-trim string))))))
21367 ;; In a list, make sure indenting keeps trailing text within.
21368 ((and indent
21369 (not (eolp))
21370 (org-element-lineage context '(item)))
21371 (let ((trailing-data
21372 (delete-and-extract-region (point) (line-end-position))))
21373 (newline-and-indent)
21374 (save-excursion (insert trailing-data))))
21375 (t (if indent (newline-and-indent) (newline))))))
21377 (defun org-return-indent ()
21378 "Goto next table row or insert a newline and indent.
21379 Calls `org-table-next-row' or `newline-and-indent', depending on
21380 context. See the individual commands for more information."
21381 (interactive)
21382 (org-return t))
21384 (defun org-ctrl-c-star ()
21385 "Compute table, or change heading status of lines.
21386 Calls `org-table-recalculate' or `org-toggle-heading',
21387 depending on context."
21388 (interactive)
21389 (cond
21390 ((org-at-table-p)
21391 (call-interactively 'org-table-recalculate))
21393 ;; Convert all lines in region to list items
21394 (call-interactively 'org-toggle-heading))))
21396 (defun org-ctrl-c-minus ()
21397 "Insert separator line in table or modify bullet status of line.
21398 Also turns a plain line or a region of lines into list items.
21399 Calls `org-table-insert-hline', `org-toggle-item', or
21400 `org-cycle-list-bullet', depending on context."
21401 (interactive)
21402 (cond
21403 ((org-at-table-p)
21404 (call-interactively 'org-table-insert-hline))
21405 ((org-region-active-p)
21406 (call-interactively 'org-toggle-item))
21407 ((org-in-item-p)
21408 (call-interactively 'org-cycle-list-bullet))
21410 (call-interactively 'org-toggle-item))))
21412 (defun org-toggle-item (arg)
21413 "Convert headings or normal lines to items, items to normal lines.
21414 If there is no active region, only the current line is considered.
21416 If the first non blank line in the region is a headline, convert
21417 all headlines to items, shifting text accordingly.
21419 If it is an item, convert all items to normal lines.
21421 If it is normal text, change region into a list of items.
21422 With a prefix argument ARG, change the region in a single item."
21423 (interactive "P")
21424 (let ((shift-text
21425 (function
21426 ;; Shift text in current section to IND, from point to END.
21427 ;; The function leaves point to END line.
21428 (lambda (ind end)
21429 (let ((min-i 1000) (end (copy-marker end)))
21430 ;; First determine the minimum indentation (MIN-I) of
21431 ;; the text.
21432 (save-excursion
21433 (catch 'exit
21434 (while (< (point) end)
21435 (let ((i (org-get-indentation)))
21436 (cond
21437 ;; Skip blank lines and inline tasks.
21438 ((looking-at "^[ \t]*$"))
21439 ((looking-at org-outline-regexp-bol))
21440 ;; We can't find less than 0 indentation.
21441 ((zerop i) (throw 'exit (setq min-i 0)))
21442 ((< i min-i) (setq min-i i))))
21443 (forward-line))))
21444 ;; Then indent each line so that a line indented to
21445 ;; MIN-I becomes indented to IND. Ignore blank lines
21446 ;; and inline tasks in the process.
21447 (let ((delta (- ind min-i)))
21448 (while (< (point) end)
21449 (unless (or (looking-at "^[ \t]*$")
21450 (looking-at org-outline-regexp-bol))
21451 (org-indent-line-to (+ (org-get-indentation) delta)))
21452 (forward-line)))))))
21453 (skip-blanks
21454 (function
21455 ;; Return beginning of first non-blank line, starting from
21456 ;; line at POS.
21457 (lambda (pos)
21458 (save-excursion
21459 (goto-char pos)
21460 (skip-chars-forward " \r\t\n")
21461 (point-at-bol)))))
21462 beg end)
21463 ;; Determine boundaries of changes.
21464 (if (org-region-active-p)
21465 (setq beg (funcall skip-blanks (region-beginning))
21466 end (copy-marker (region-end)))
21467 (setq beg (funcall skip-blanks (point-at-bol))
21468 end (copy-marker (point-at-eol))))
21469 ;; Depending on the starting line, choose an action on the text
21470 ;; between BEG and END.
21471 (org-with-limited-levels
21472 (save-excursion
21473 (goto-char beg)
21474 (cond
21475 ;; Case 1. Start at an item: de-itemize. Note that it only
21476 ;; happens when a region is active: `org-ctrl-c-minus'
21477 ;; would call `org-cycle-list-bullet' otherwise.
21478 ((org-at-item-p)
21479 (while (< (point) end)
21480 (when (org-at-item-p)
21481 (skip-chars-forward " \t")
21482 (delete-region (point) (match-end 0)))
21483 (forward-line)))
21484 ;; Case 2. Start at an heading: convert to items.
21485 ((org-at-heading-p)
21486 (let* ((bul (org-list-bullet-string "-"))
21487 (bul-len (length bul))
21488 (done (org-entry-is-done-p))
21489 (todo (org-entry-is-todo-p))
21490 ;; Indentation of the first heading. It should be
21491 ;; relative to the indentation of its parent, if any.
21492 (start-ind (save-excursion
21493 (cond
21494 ((not org-adapt-indentation) 0)
21495 ((not (outline-previous-heading)) 0)
21496 (t (length (match-string 0))))))
21497 ;; Level of first heading. Further headings will be
21498 ;; compared to it to determine hierarchy in the list.
21499 (ref-level (org-reduced-level (org-outline-level))))
21500 (when (or done todo) (org-todo ""))
21501 (while (< (point) end)
21502 (let* ((level (org-reduced-level (org-outline-level)))
21503 (delta (max 0 (- level ref-level))))
21504 ;; If current headline is less indented than the first
21505 ;; one, set it as reference, in order to preserve
21506 ;; subtrees.
21507 (when (< level ref-level) (setq ref-level level))
21508 (replace-match bul t t)
21509 (org-indent-line-to (+ start-ind (* delta bul-len)))
21510 (when (or done todo)
21511 (let* ((struct (org-list-struct))
21512 (old (copy-tree struct)))
21513 (org-list-set-checkbox (line-beginning-position)
21514 struct
21515 (if done "[X]" "[ ]"))
21516 (org-list-write-struct struct
21517 (org-list-parents-alist struct)
21518 old)))
21519 ;; Ensure all text down to END (or SECTION-END) belongs
21520 ;; to the newly created item.
21521 (let ((section-end (save-excursion
21522 (or (outline-next-heading) (point)))))
21523 (forward-line)
21524 (funcall shift-text
21525 (+ start-ind (* (1+ delta) bul-len))
21526 (min end section-end)))))))
21527 ;; Case 3. Normal line with ARG: make the first line of region
21528 ;; an item, and shift indentation of others lines to
21529 ;; set them as item's body.
21530 (arg (let* ((bul (org-list-bullet-string "-"))
21531 (bul-len (length bul))
21532 (ref-ind (org-get-indentation)))
21533 (skip-chars-forward " \t")
21534 (insert bul)
21535 (forward-line)
21536 (while (< (point) end)
21537 ;; Ensure that lines less indented than first one
21538 ;; still get included in item body.
21539 (funcall shift-text
21540 (+ ref-ind bul-len)
21541 (min end (save-excursion (or (outline-next-heading)
21542 (point)))))
21543 (forward-line))))
21544 ;; Case 4. Normal line without ARG: turn each non-item line
21545 ;; into an item.
21547 (while (< (point) end)
21548 (unless (or (org-at-heading-p) (org-at-item-p))
21549 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21550 (replace-match
21551 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21552 (forward-line))))))))
21554 (defun org-toggle-heading (&optional nstars)
21555 "Convert headings to normal text, or items or text to headings.
21556 If there is no active region, only convert the current line.
21558 With a \\[universal-argument] prefix, convert the whole list at
21559 point into heading.
21561 In a region:
21563 - If the first non blank line is a headline, remove the stars
21564 from all headlines in the region.
21566 - If it is a normal line, turn each and every normal line (i.e.,
21567 not an heading or an item) in the region into headings. If you
21568 want to convert only the first line of this region, use one
21569 universal prefix argument.
21571 - If it is a plain list item, turn all plain list items into headings.
21573 When converting a line into a heading, the number of stars is chosen
21574 such that the lines become children of the current entry. However,
21575 when a numeric prefix argument is given, its value determines the
21576 number of stars to add."
21577 (interactive "P")
21578 (let ((skip-blanks
21579 (function
21580 ;; Return beginning of first non-blank line, starting from
21581 ;; line at POS.
21582 (lambda (pos)
21583 (save-excursion
21584 (goto-char pos)
21585 (while (org-at-comment-p) (forward-line))
21586 (skip-chars-forward " \r\t\n")
21587 (point-at-bol)))))
21588 beg end toggled)
21589 ;; Determine boundaries of changes. If a universal prefix has
21590 ;; been given, put the list in a region. If region ends at a bol,
21591 ;; do not consider the last line to be in the region.
21593 (when (and current-prefix-arg (org-at-item-p))
21594 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21595 (org-mark-element))
21597 (if (org-region-active-p)
21598 (setq beg (funcall skip-blanks (region-beginning))
21599 end (copy-marker (save-excursion
21600 (goto-char (region-end))
21601 (if (bolp) (point) (point-at-eol)))))
21602 (setq beg (funcall skip-blanks (point-at-bol))
21603 end (copy-marker (point-at-eol))))
21604 ;; Ensure inline tasks don't count as headings.
21605 (org-with-limited-levels
21606 (save-excursion
21607 (goto-char beg)
21608 (cond
21609 ;; Case 1. Started at an heading: de-star headings.
21610 ((org-at-heading-p)
21611 (while (< (point) end)
21612 (when (org-at-heading-p t)
21613 (looking-at org-outline-regexp) (replace-match "")
21614 (setq toggled t))
21615 (forward-line)))
21616 ;; Case 2. Started at an item: change items into headlines.
21617 ;; One star will be added by `org-list-to-subtree'.
21618 ((org-at-item-p)
21619 (while (< (point) end)
21620 (when (org-at-item-p)
21621 ;; Pay attention to cases when region ends before list.
21622 (let* ((struct (org-list-struct))
21623 (list-end
21624 (min (org-list-get-bottom-point struct) (1+ end))))
21625 (save-restriction
21626 (narrow-to-region (point) list-end)
21627 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21628 (setq toggled t))
21629 (forward-line)))
21630 ;; Case 3. Started at normal text: make every line an heading,
21631 ;; skipping headlines and items.
21632 (t (let* ((stars
21633 (make-string
21634 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21635 (add-stars
21636 (cond (nstars "") ; stars from prefix only
21637 ((equal stars "") "*") ; before first heading
21638 (org-odd-levels-only "**") ; inside heading, odd
21639 (t "*"))) ; inside heading, oddeven
21640 (rpl (concat stars add-stars " "))
21641 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21642 (while (< (point) (if (equal nstars '(4)) lend end))
21643 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21644 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21645 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21646 (forward-line)))))))
21647 (unless toggled (message "Cannot toggle heading from here"))))
21649 (defun org-meta-return (&optional _arg)
21650 "Insert a new heading or wrap a region in a table.
21651 Calls `org-insert-heading' or `org-table-wrap-region', depending
21652 on context. See the individual commands for more information."
21653 (interactive)
21654 (org-check-before-invisible-edit 'insert)
21655 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21656 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21657 #'org-insert-heading))))
21659 ;;; Menu entries
21661 (defsubst org-in-subtree-not-table-p ()
21662 "Are we in a subtree and not in a table?"
21663 (and (not (org-before-first-heading-p))
21664 (not (org-at-table-p))))
21666 ;; Define the Org-mode menus
21667 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21668 '("Tbl"
21669 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21670 ["Next Field" org-cycle (org-at-table-p)]
21671 ["Previous Field" org-shifttab (org-at-table-p)]
21672 ["Next Row" org-return (org-at-table-p)]
21673 "--"
21674 ["Blank Field" org-table-blank-field (org-at-table-p)]
21675 ["Edit Field" org-table-edit-field (org-at-table-p)]
21676 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21677 "--"
21678 ("Column"
21679 ["Move Column Left" org-metaleft (org-at-table-p)]
21680 ["Move Column Right" org-metaright (org-at-table-p)]
21681 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21682 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21683 ("Row"
21684 ["Move Row Up" org-metaup (org-at-table-p)]
21685 ["Move Row Down" org-metadown (org-at-table-p)]
21686 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21687 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21688 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21689 "--"
21690 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21691 ("Rectangle"
21692 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21693 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21694 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21695 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21696 "--"
21697 ("Calculate"
21698 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21699 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21700 ["Edit Formulas" org-edit-special (org-at-table-p)]
21701 "--"
21702 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21703 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21704 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21705 "--"
21706 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21707 "--"
21708 ["Sum Column/Rectangle" org-table-sum
21709 (or (org-at-table-p) (org-region-active-p))]
21710 ["Which Column?" org-table-current-column (org-at-table-p)])
21711 ["Debug Formulas"
21712 org-table-toggle-formula-debugger
21713 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21714 ["Show Col/Row Numbers"
21715 org-table-toggle-coordinate-overlays
21716 :style toggle
21717 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21718 "--"
21719 ["Create" org-table-create (and (not (org-at-table-p))
21720 org-enable-table-editor)]
21721 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21722 ["Import from File" org-table-import (not (org-at-table-p))]
21723 ["Export to File" org-table-export (org-at-table-p)]
21724 "--"
21725 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21726 "--"
21727 ("Plot"
21728 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21729 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21731 (easy-menu-define org-org-menu org-mode-map "Org menu"
21732 '("Org"
21733 ("Show/Hide"
21734 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21735 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21736 ["Sparse Tree..." org-sparse-tree t]
21737 ["Reveal Context" org-reveal t]
21738 ["Show All" outline-show-all t]
21739 "--"
21740 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21741 "--"
21742 ["New Heading" org-insert-heading t]
21743 ("Navigate Headings"
21744 ["Up" outline-up-heading t]
21745 ["Next" outline-next-visible-heading t]
21746 ["Previous" outline-previous-visible-heading t]
21747 ["Next Same Level" outline-forward-same-level t]
21748 ["Previous Same Level" outline-backward-same-level t]
21749 "--"
21750 ["Jump" org-goto t])
21751 ("Edit Structure"
21752 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21753 "--"
21754 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21755 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21756 "--"
21757 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21758 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21759 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21760 "--"
21761 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21762 "--"
21763 ["Copy visible text" org-copy-visible t]
21764 "--"
21765 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21766 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21767 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21768 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21769 "--"
21770 ["Sort Region/Children" org-sort t]
21771 "--"
21772 ["Convert to odd levels" org-convert-to-odd-levels t]
21773 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21774 ("Editing"
21775 ["Emphasis..." org-emphasize t]
21776 ["Edit Source Example" org-edit-special t]
21777 "--"
21778 ["Footnote new/jump" org-footnote-action t]
21779 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21780 ("Archive"
21781 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21782 "--"
21783 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21784 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21785 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21787 "--"
21788 ("Hyperlinks"
21789 ["Store Link (Global)" org-store-link t]
21790 ["Find existing link to here" org-occur-link-in-agenda-files t]
21791 ["Insert Link" org-insert-link t]
21792 ["Follow Link" org-open-at-point t]
21793 "--"
21794 ["Next link" org-next-link t]
21795 ["Previous link" org-previous-link t]
21796 "--"
21797 ["Descriptive Links"
21798 org-toggle-link-display
21799 :style radio
21800 :selected org-descriptive-links
21802 ["Literal Links"
21803 org-toggle-link-display
21804 :style radio
21805 :selected (not org-descriptive-links)])
21806 "--"
21807 ("TODO Lists"
21808 ["TODO/DONE/-" org-todo t]
21809 ("Select keyword"
21810 ["Next keyword" org-shiftright (org-at-heading-p)]
21811 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21812 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21813 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21814 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21815 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21816 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21817 "--"
21818 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21819 :selected org-enforce-todo-dependencies :style toggle :active t]
21820 "Settings for tree at point"
21821 ["Do Children sequentially" org-toggle-ordered-property :style radio
21822 :selected (org-entry-get nil "ORDERED")
21823 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21824 ["Do Children parallel" org-toggle-ordered-property :style radio
21825 :selected (not (org-entry-get nil "ORDERED"))
21826 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21827 "--"
21828 ["Set Priority" org-priority t]
21829 ["Priority Up" org-shiftup t]
21830 ["Priority Down" org-shiftdown t]
21831 "--"
21832 ["Get news from all feeds" org-feed-update-all t]
21833 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21834 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21835 ("TAGS and Properties"
21836 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21837 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21838 "--"
21839 ["Set property" org-set-property (not (org-before-first-heading-p))]
21840 ["Column view of properties" org-columns t]
21841 ["Insert Column View DBlock" org-columns-insert-dblock t])
21842 ("Dates and Scheduling"
21843 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21844 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21845 ("Change Date"
21846 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21847 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21848 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21849 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21850 ["Compute Time Range" org-evaluate-time-range t]
21851 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21852 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21853 "--"
21854 ["Custom time format" org-toggle-time-stamp-overlays
21855 :style radio :selected org-display-custom-times]
21856 "--"
21857 ["Goto Calendar" org-goto-calendar t]
21858 ["Date from Calendar" org-date-from-calendar t]
21859 "--"
21860 ["Start/Restart Timer" org-timer-start t]
21861 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21862 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21863 ["Insert Timer String" org-timer t]
21864 ["Insert Timer Item" org-timer-item t])
21865 ("Logging work"
21866 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21867 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21868 ["Clock out" org-clock-out t]
21869 ["Clock cancel" org-clock-cancel t]
21870 "--"
21871 ["Mark as default task" org-clock-mark-default-task t]
21872 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21873 ["Goto running clock" org-clock-goto t]
21874 "--"
21875 ["Display times" org-clock-display t]
21876 ["Create clock table" org-clock-report t]
21877 "--"
21878 ["Record DONE time"
21879 (progn (setq org-log-done (not org-log-done))
21880 (message "Switching to %s will %s record a timestamp"
21881 (car org-done-keywords)
21882 (if org-log-done "automatically" "not")))
21883 :style toggle :selected org-log-done])
21884 "--"
21885 ["Agenda Command..." org-agenda t]
21886 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21887 ("File List for Agenda")
21888 ("Special views current file"
21889 ["TODO Tree" org-show-todo-tree t]
21890 ["Check Deadlines" org-check-deadlines t]
21891 ["Timeline" org-timeline t]
21892 ["Tags/Property tree" org-match-sparse-tree t])
21893 "--"
21894 ["Export/Publish..." org-export-dispatch t]
21895 ("LaTeX"
21896 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21897 :selected org-cdlatex-mode]
21898 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21899 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21900 ["Modify math symbol" org-cdlatex-math-modify
21901 (org-inside-LaTeX-fragment-p)]
21902 ["Insert citation" org-reftex-citation t]
21903 "--"
21904 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21905 "--"
21906 ("MobileOrg"
21907 ["Push Files and Views" org-mobile-push t]
21908 ["Get Captured and Flagged" org-mobile-pull t]
21909 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21910 "--"
21911 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21912 "--"
21913 ("Documentation"
21914 ["Show Version" org-version t]
21915 ["Info Documentation" org-info t])
21916 ("Customize"
21917 ["Browse Org Group" org-customize t]
21918 "--"
21919 ["Expand This Menu" org-create-customize-menu
21920 (fboundp 'customize-menu-create)])
21921 ["Send bug report" org-submit-bug-report t]
21922 "--"
21923 ("Refresh/Reload"
21924 ["Refresh setup current buffer" org-mode-restart t]
21925 ["Reload Org (after update)" org-reload t]
21926 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21929 (defun org-info (&optional node)
21930 "Read documentation for Org-mode in the info system.
21931 With optional NODE, go directly to that node."
21932 (interactive)
21933 (info (format "(org)%s" (or node ""))))
21935 ;;;###autoload
21936 (defun org-submit-bug-report ()
21937 "Submit a bug report on Org-mode via mail.
21939 Don't hesitate to report any problems or inaccurate documentation.
21941 If you don't have setup sending mail from (X)Emacs, please copy the
21942 output buffer into your mail program, as it gives us important
21943 information about your Org-mode version and configuration."
21944 (interactive)
21945 (require 'reporter)
21946 (defvar reporter-prompt-for-summary-p)
21947 (org-load-modules-maybe)
21948 (org-require-autoloaded-modules)
21949 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21950 (reporter-submit-bug-report
21951 "emacs-orgmode@gnu.org"
21952 (org-version nil 'full)
21953 (let (list)
21954 (save-window-excursion
21955 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21956 (delete-other-windows)
21957 (erase-buffer)
21958 (insert "You are about to submit a bug report to the Org-mode mailing list.
21960 We would like to add your full Org-mode and Outline configuration to the
21961 bug report. This greatly simplifies the work of the maintainer and
21962 other experts on the mailing list.
21964 HOWEVER, some variables you have customized may contain private
21965 information. The names of customers, colleagues, or friends, might
21966 appear in the form of file names, tags, todo states, or search strings.
21967 If you answer yes to the prompt, you might want to check and remove
21968 such private information before sending the email.")
21969 (add-text-properties (point-min) (point-max) '(face org-warning))
21970 (when (yes-or-no-p "Include your Org-mode configuration ")
21971 (mapatoms
21972 (lambda (v)
21973 (and (boundp v)
21974 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21975 (or (and (symbol-value v)
21976 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21977 (and
21978 (get v 'custom-type) (get v 'standard-value)
21979 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21980 (push v list)))))
21981 (kill-buffer (get-buffer "*Warn about privacy*"))
21982 list))
21983 nil nil
21984 "Remember to cover the basics, that is, what you expected to happen and
21985 what in fact did happen. You don't know how to make a good report? See
21987 http://orgmode.org/manual/Feedback.html#Feedback
21989 Your bug report will be posted to the Org-mode mailing list.
21990 ------------------------------------------------------------------------")
21991 (save-excursion
21992 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21993 (replace-match "\\1Bug: \\3 [\\2]")))))
21996 (defun org-install-agenda-files-menu ()
21997 (let ((bl (buffer-list)))
21998 (save-excursion
21999 (while bl
22000 (set-buffer (pop bl))
22001 (when (derived-mode-p 'org-mode) (setq bl nil)))
22002 (when (derived-mode-p 'org-mode)
22003 (easy-menu-change
22004 '("Org") "File List for Agenda"
22005 (append
22006 (list
22007 ["Edit File List" (org-edit-agenda-file-list) t]
22008 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
22009 ["Remove Current File from List" org-remove-file t]
22010 ["Cycle through agenda files" org-cycle-agenda-files t]
22011 ["Occur in all agenda files" org-occur-in-agenda-files t]
22012 "--")
22013 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22015 ;;;; Documentation
22017 (defun org-require-autoloaded-modules ()
22018 (interactive)
22019 (mapc #'require
22020 '(org-agenda org-archive org-attach org-clock org-colview org-id
22021 org-table org-timer)))
22023 ;;;###autoload
22024 (defun org-reload (&optional uncompiled)
22025 "Reload all org lisp files.
22026 With prefix arg UNCOMPILED, load the uncompiled versions."
22027 (interactive "P")
22028 (require 'loadhist)
22029 (let* ((org-dir (org-find-library-dir "org"))
22030 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22031 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22032 (remove-re (mapconcat 'identity
22033 (mapcar (lambda (f) (concat "^" f "$"))
22034 (list (if (featurep 'xemacs)
22035 "org-colview"
22036 "org-colview-xemacs")
22037 "org" "org-loaddefs" "org-version"))
22038 "\\|"))
22039 (feats (delete-dups
22040 (mapcar 'file-name-sans-extension
22041 (mapcar 'file-name-nondirectory
22042 (delq nil
22043 (mapcar 'feature-file
22044 features))))))
22045 (lfeat (append
22046 (sort
22047 (setq feats
22048 (delq nil (mapcar
22049 (lambda (f)
22050 (if (and (string-match feature-re f)
22051 (not (string-match remove-re f)))
22052 f nil))
22053 feats)))
22054 'string-lessp)
22055 (list "org-version" "org")))
22056 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22057 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22058 load-uncore load-misses)
22059 (setq load-misses
22060 (delq 't
22061 (mapcar (lambda (f)
22062 (or (org-load-noerror-mustsuffix (concat org-dir f))
22063 (and (string= org-dir contrib-dir)
22064 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22065 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22066 (add-to-list 'load-uncore f 'append)
22069 lfeat)))
22070 (when load-uncore
22071 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22072 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22073 (if load-misses
22074 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22075 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22076 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22078 ;;;###autoload
22079 (defun org-customize ()
22080 "Call the customize function with org as argument."
22081 (interactive)
22082 (org-load-modules-maybe)
22083 (org-require-autoloaded-modules)
22084 (customize-browse 'org))
22086 (defun org-create-customize-menu ()
22087 "Create a full customization menu for Org-mode, insert it into the menu."
22088 (interactive)
22089 (org-load-modules-maybe)
22090 (org-require-autoloaded-modules)
22091 (if (fboundp 'customize-menu-create)
22092 (progn
22093 (easy-menu-change
22094 '("Org") "Customize"
22095 `(["Browse Org group" org-customize t]
22096 "--"
22097 ,(customize-menu-create 'org)
22098 ["Set" Custom-set t]
22099 ["Save" Custom-save t]
22100 ["Reset to Current" Custom-reset-current t]
22101 ["Reset to Saved" Custom-reset-saved t]
22102 ["Reset to Standard Settings" Custom-reset-standard t]))
22103 (message "\"Org\"-menu now contains full customization menu"))
22104 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22106 ;;;; Miscellaneous stuff
22108 ;;; Generally useful functions
22110 (defun org-get-at-eol (property n)
22111 "Get text property PROPERTY at the end of line less N characters."
22112 (get-text-property (- (point-at-eol) n) property))
22114 (defun org-find-text-property-in-string (prop s)
22115 "Return the first non-nil value of property PROP in string S."
22116 (or (get-text-property 0 prop s)
22117 (get-text-property (or (next-single-property-change 0 prop s) 0)
22118 prop s)))
22120 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22121 "Display the given MESSAGE as a warning."
22122 (if (fboundp 'display-warning)
22123 (display-warning 'org message
22124 (if (featurep 'xemacs) 'warning :warning))
22125 (let ((buf (get-buffer-create "*Org warnings*")))
22126 (with-current-buffer buf
22127 (goto-char (point-max))
22128 (insert "Warning (Org): " message)
22129 (unless (bolp)
22130 (newline)))
22131 (display-buffer buf)
22132 (sit-for 0))))
22134 (defun org-eval (form)
22135 "Eval FORM and return result."
22136 (condition-case error
22137 (eval form)
22138 (error (format "%%![Error: %s]" error))))
22140 (defun org-in-clocktable-p ()
22141 "Check if the cursor is in a clocktable."
22142 (let ((pos (point)) start)
22143 (save-excursion
22144 (end-of-line 1)
22145 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22146 (setq start (match-beginning 0))
22147 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22148 (>= (match-end 0) pos)
22149 start))))
22151 (defun org-in-verbatim-emphasis ()
22152 (save-match-data
22153 (and (org-in-regexp org-emph-re 2)
22154 (>= (point) (match-beginning 3))
22155 (<= (point) (match-end 4))
22156 (member (match-string 3) '("=" "~")))))
22158 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22159 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22160 (if (and marker (marker-buffer marker)
22161 (buffer-live-p (marker-buffer marker)))
22162 (progn
22163 (org-pop-to-buffer-same-window (marker-buffer marker))
22164 (when (or (> marker (point-max)) (< marker (point-min)))
22165 (widen))
22166 (goto-char marker)
22167 (org-show-context 'org-goto))
22168 (if bookmark
22169 (bookmark-jump bookmark)
22170 (error "Cannot find location"))))
22172 (defun org-quote-csv-field (s)
22173 "Quote field for inclusion in CSV material."
22174 (if (string-match "[\",]" s)
22175 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22178 (defun org-force-self-insert (N)
22179 "Needed to enforce self-insert under remapping."
22180 (interactive "p")
22181 (self-insert-command N))
22183 (defun org-string-width (s)
22184 "Compute width of string, ignoring invisible characters.
22185 This ignores character with invisibility property `org-link', and also
22186 characters with property `org-cwidth', because these will become invisible
22187 upon the next fontification round."
22188 (let (b l)
22189 (when (or (eq t buffer-invisibility-spec)
22190 (assq 'org-link buffer-invisibility-spec))
22191 (while (setq b (text-property-any 0 (length s)
22192 'invisible 'org-link s))
22193 (setq s (concat (substring s 0 b)
22194 (substring s (or (next-single-property-change
22195 b 'invisible s)
22196 (length s)))))))
22197 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22198 (setq s (concat (substring s 0 b)
22199 (substring s (or (next-single-property-change
22200 b 'org-cwidth s)
22201 (length s))))))
22202 (setq l (string-width s) b -1)
22203 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22204 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22207 (defun org-shorten-string (s maxlength)
22208 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22209 If the string is shorter or has length MAXLENGTH, just return the
22210 original string. If it is longer, the functions finds a space in the
22211 string, breaks this string off at that locations and adds three dots
22212 as ellipsis. Including the ellipsis, the string will not be longer
22213 than MAXLENGTH. If finding a good breaking point in the string does
22214 not work, the string is just chopped off in the middle of a word
22215 if necessary."
22216 (if (<= (length s) maxlength)
22218 (let* ((n (max (- maxlength 4) 1))
22219 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22220 (if (string-match re s)
22221 (concat (match-string 1 s) "...")
22222 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22224 (defun org-get-indentation (&optional line)
22225 "Get the indentation of the current line, interpreting tabs.
22226 When LINE is given, assume it represents a line and compute its indentation."
22227 (if line
22228 (when (string-match "^ *" (org-remove-tabs line))
22229 (match-end 0))
22230 (save-excursion
22231 (beginning-of-line 1)
22232 (skip-chars-forward " \t")
22233 (current-column))))
22235 (defun org-get-string-indentation (s)
22236 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22237 (let ((n -1) (i 0) (w tab-width) c)
22238 (catch 'exit
22239 (while (< (setq n (1+ n)) (length s))
22240 (setq c (aref s n))
22241 (cond ((= c ?\ ) (setq i (1+ i)))
22242 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22243 (t (throw 'exit t)))))
22246 (defun org-remove-tabs (s &optional width)
22247 "Replace tabulators in S with spaces.
22248 Assumes that s is a single line, starting in column 0."
22249 (setq width (or width tab-width))
22250 (while (string-match "\t" s)
22251 (setq s (replace-match
22252 (make-string
22253 (- (* width (/ (+ (match-beginning 0) width) width))
22254 (match-beginning 0)) ?\ )
22255 t t s)))
22258 (defun org-fix-indentation (line ind)
22259 "Fix indentation in LINE.
22260 IND is a cons cell with target and minimum indentation.
22261 If the current indentation in LINE is smaller than the minimum,
22262 leave it alone. If it is larger than ind, set it to the target."
22263 (let* ((l (org-remove-tabs line))
22264 (i (org-get-indentation l))
22265 (i1 (car ind)) (i2 (cdr ind)))
22266 (when (>= i i2) (setq l (substring line i2)))
22267 (if (> i1 0)
22268 (concat (make-string i1 ?\ ) l)
22269 l)))
22271 (defun org-remove-indentation (code &optional n)
22272 "Remove maximum common indentation in string CODE and return it.
22273 N may optionally be the number of columns to remove. Return CODE
22274 as-is if removal failed."
22275 (with-temp-buffer
22276 (insert code)
22277 (if (org-do-remove-indentation n) (buffer-string) code)))
22279 (defun org-do-remove-indentation (&optional n)
22280 "Remove the maximum common indentation from the buffer.
22281 When optional argument N is a positive integer, remove exactly
22282 that much characters from indentation, if possible. Return nil
22283 if it fails."
22284 (catch :exit
22285 (goto-char (point-min))
22286 ;; Find maximum common indentation, if not specified.
22287 (let ((n (or n
22288 (let ((min-ind (point-max)))
22289 (save-excursion
22290 (while (re-search-forward "^[ \t]*\\S-" nil t)
22291 (let ((ind (1- (current-column))))
22292 (if (zerop ind) (throw :exit nil)
22293 (setq min-ind (min min-ind ind))))))
22294 min-ind))))
22295 (if (zerop n) (throw :exit nil)
22296 ;; Remove exactly N indentation, but give up if not possible.
22297 (while (not (eobp))
22298 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22299 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22300 ((< ind n) (throw :exit nil))
22301 (t (org-indent-line-to (- ind n))))
22302 (forward-line)))
22303 ;; Signal success.
22304 t))))
22306 (defun org-fill-template (template alist)
22307 "Find each %key of ALIST in TEMPLATE and replace it."
22308 (let ((case-fold-search nil))
22309 (dolist (entry (sort (copy-sequence alist)
22310 (lambda (a b) (< (length (car a)) (length (car b))))))
22311 (setq template
22312 (replace-regexp-in-string
22313 (concat "%" (regexp-quote (car entry)))
22314 (or (cdr entry) "") template t t)))
22315 template))
22317 (defun org-base-buffer (buffer)
22318 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22319 (if (not buffer)
22320 buffer
22321 (or (buffer-base-buffer buffer)
22322 buffer)))
22324 (defun org-wrap (string &optional width lines)
22325 "Wrap string to either a number of lines, or a width in characters.
22326 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22327 that costs. If there is a word longer than WIDTH, the text is actually
22328 wrapped to the length of that word.
22329 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22330 many lines, whatever width that takes.
22331 The return value is a list of lines, without newlines at the end."
22332 (let* ((words (org-split-string string "[ \t\n]+"))
22333 (maxword (apply 'max (mapcar 'org-string-width words)))
22334 w ll)
22335 (cond (width
22336 (org-do-wrap words (max maxword width)))
22337 (lines
22338 (setq w maxword)
22339 (setq ll (org-do-wrap words maxword))
22340 (if (<= (length ll) lines)
22342 (setq ll words)
22343 (while (> (length ll) lines)
22344 (setq w (1+ w))
22345 (setq ll (org-do-wrap words w)))
22346 ll))
22347 (t (error "Cannot wrap this")))))
22349 (defun org-do-wrap (words width)
22350 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22351 (let (lines line)
22352 (while words
22353 (setq line (pop words))
22354 (while (and words (< (+ (length line) (length (car words))) width))
22355 (setq line (concat line " " (pop words))))
22356 (setq lines (push line lines)))
22357 (nreverse lines)))
22359 (defun org-split-string (string &optional separators)
22360 "Splits STRING into substrings at SEPARATORS.
22361 SEPARATORS is a regular expression.
22362 No empty strings are returned if there are matches at the beginning
22363 and end of string."
22364 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22365 (let ((start 0) notfirst list)
22366 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22367 (if (and notfirst
22368 (= start (match-beginning 0))
22369 (< start (length string)))
22370 (1+ start) start))
22371 (< (match-beginning 0) (length string)))
22372 (setq notfirst t)
22373 (or (eq (match-beginning 0) 0)
22374 (and (eq (match-beginning 0) (match-end 0))
22375 (eq (match-beginning 0) start))
22376 (push (substring string start (match-beginning 0)) list))
22377 (setq start (match-end 0)))
22378 (or (eq start (length string))
22379 (push (substring string start) list))
22380 (nreverse list)))
22382 (defun org-quote-vert (s)
22383 "Replace \"|\" with \"\\vert\"."
22384 (while (string-match "|" s)
22385 (setq s (replace-match "\\vert" t t s)))
22388 (defun org-uuidgen-p (s)
22389 "Is S an ID created by UUIDGEN?"
22390 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22392 (defun org-in-src-block-p (&optional inside)
22393 "Whether point is in a code source block.
22394 When INSIDE is non-nil, don't consider we are within a src block
22395 when point is at #+BEGIN_SRC or #+END_SRC."
22396 (let ((case-fold-search t))
22397 (or (and (eq (get-char-property (point) 'src-block) t))
22398 (and (not inside)
22399 (save-match-data
22400 (save-excursion
22401 (beginning-of-line)
22402 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22404 (defun org-context ()
22405 "Return a list of contexts of the current cursor position.
22406 If several contexts apply, all are returned.
22407 Each context entry is a list with a symbol naming the context, and
22408 two positions indicating start and end of the context. Possible
22409 contexts are:
22411 :headline anywhere in a headline
22412 :headline-stars on the leading stars in a headline
22413 :todo-keyword on a TODO keyword (including DONE) in a headline
22414 :tags on the TAGS in a headline
22415 :priority on the priority cookie in a headline
22416 :item on the first line of a plain list item
22417 :item-bullet on the bullet/number of a plain list item
22418 :checkbox on the checkbox in a plain list item
22419 :table in an org-mode table
22420 :table-special on a special filed in a table
22421 :table-table in a table.el table
22422 :clocktable in a clocktable
22423 :src-block in a source block
22424 :link on a hyperlink
22425 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22426 :target on a <<target>>
22427 :radio-target on a <<<radio-target>>>
22428 :latex-fragment on a LaTeX fragment
22429 :latex-preview on a LaTeX fragment with overlaid preview image
22431 This function expects the position to be visible because it uses font-lock
22432 faces as a help to recognize the following contexts: :table-special, :link,
22433 and :keyword."
22434 (let* ((f (get-text-property (point) 'face))
22435 (faces (if (listp f) f (list f)))
22436 (case-fold-search t)
22437 (p (point)) clist o)
22438 ;; First the large context
22439 (cond
22440 ((org-at-heading-p t)
22441 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22442 (when (progn
22443 (beginning-of-line 1)
22444 (looking-at org-todo-line-tags-regexp))
22445 (push (org-point-in-group p 1 :headline-stars) clist)
22446 (push (org-point-in-group p 2 :todo-keyword) clist)
22447 (push (org-point-in-group p 4 :tags) clist))
22448 (goto-char p)
22449 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22450 (when (looking-at "\\[#[A-Z0-9]\\]")
22451 (push (org-point-in-group p 0 :priority) clist)))
22453 ((org-at-item-p)
22454 (push (org-point-in-group p 2 :item-bullet) clist)
22455 (push (list :item (point-at-bol)
22456 (save-excursion (org-end-of-item) (point)))
22457 clist)
22458 (and (org-at-item-checkbox-p)
22459 (push (org-point-in-group p 0 :checkbox) clist)))
22461 ((org-at-table-p)
22462 (push (list :table (org-table-begin) (org-table-end)) clist)
22463 (when (memq 'org-formula faces)
22464 (push (list :table-special
22465 (previous-single-property-change p 'face)
22466 (next-single-property-change p 'face)) clist)))
22467 ((org-at-table-p 'any)
22468 (push (list :table-table) clist)))
22469 (goto-char p)
22471 (let ((case-fold-search t))
22472 ;; New the "medium" contexts: clocktables, source blocks
22473 (cond ((org-in-clocktable-p)
22474 (push (list :clocktable
22475 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22476 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22477 (match-beginning 1))
22478 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22479 (match-end 0))) clist))
22480 ((org-in-src-block-p)
22481 (push (list :src-block
22482 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22483 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22484 (match-beginning 1))
22485 (and (search-forward "#+END_SRC" nil t)
22486 (match-beginning 0))) clist))))
22487 (goto-char p)
22489 ;; Now the small context
22490 (cond
22491 ((org-at-timestamp-p)
22492 (push (org-point-in-group p 0 :timestamp) clist))
22493 ((memq 'org-link faces)
22494 (push (list :link
22495 (previous-single-property-change p 'face)
22496 (next-single-property-change p 'face)) clist))
22497 ((memq 'org-special-keyword faces)
22498 (push (list :keyword
22499 (previous-single-property-change p 'face)
22500 (next-single-property-change p 'face)) clist))
22501 ((org-at-target-p)
22502 (push (org-point-in-group p 0 :target) clist)
22503 (goto-char (1- (match-beginning 0)))
22504 (when (looking-at org-radio-target-regexp)
22505 (push (org-point-in-group p 0 :radio-target) clist))
22506 (goto-char p))
22507 ((setq o (cl-some
22508 (lambda (o)
22509 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22511 (overlays-at (point))))
22512 (push (list :latex-fragment
22513 (overlay-start o) (overlay-end o)) clist)
22514 (push (list :latex-preview
22515 (overlay-start o) (overlay-end o)) clist))
22516 ((org-inside-LaTeX-fragment-p)
22517 ;; FIXME: positions wrong.
22518 (push (list :latex-fragment (point) (point)) clist)))
22520 (setq clist (nreverse (delq nil clist)))
22521 clist))
22523 (defun org-in-regexp (regexp &optional nlines visually)
22524 "Check if point is inside a match of REGEXP.
22526 Normally only the current line is checked, but you can include
22527 NLINES extra lines around point into the search. If VISUALLY is
22528 set, require that the cursor is not after the match but really
22529 on, so that the block visually is on the match.
22531 Return nil or a cons cell (BEG . END) where BEG and END are,
22532 respectively, the positions at the beginning and the end of the
22533 match."
22534 (catch :exit
22535 (let ((pos (point))
22536 (eol (line-end-position (if nlines (1+ nlines) 1))))
22537 (save-excursion
22538 (beginning-of-line (- 1 (or nlines 0)))
22539 (while (and (re-search-forward regexp eol t)
22540 (<= (match-beginning 0) pos))
22541 (let ((end (match-end 0)))
22542 (when (or (> end pos) (and (= end pos) (not visually)))
22543 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22544 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22545 "Org mode 8.3")
22547 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22548 "Non-nil when point is between matches of START-RE and END-RE.
22550 Also return a non-nil value when point is on one of the matches.
22552 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22553 buffer positions. Default values are the positions of headlines
22554 surrounding the point.
22556 The functions returns a cons cell whose car (resp. cdr) is the
22557 position before START-RE (resp. after END-RE)."
22558 (save-match-data
22559 (let ((pos (point))
22560 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22561 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22562 beg end)
22563 (save-excursion
22564 ;; Point is on a block when on START-RE or if START-RE can be
22565 ;; found before it...
22566 (and (or (org-in-regexp start-re)
22567 (re-search-backward start-re limit-up t))
22568 (setq beg (match-beginning 0))
22569 ;; ... and END-RE after it...
22570 (goto-char (match-end 0))
22571 (re-search-forward end-re limit-down t)
22572 (> (setq end (match-end 0)) pos)
22573 ;; ... without another START-RE in-between.
22574 (goto-char (match-beginning 0))
22575 (not (re-search-backward start-re (1+ beg) t))
22576 ;; Return value.
22577 (cons beg end))))))
22579 (defun org-in-block-p (names)
22580 "Non-nil when point belongs to a block whose name belongs to NAMES.
22582 NAMES is a list of strings containing names of blocks.
22584 Return first block name matched, or nil. Beware that in case of
22585 nested blocks, the returned name may not belong to the closest
22586 block from point."
22587 (save-match-data
22588 (catch 'exit
22589 (let ((case-fold-search t)
22590 (lim-up (save-excursion (outline-previous-heading)))
22591 (lim-down (save-excursion (outline-next-heading))))
22592 (dolist (name names)
22593 (let ((n (regexp-quote name)))
22594 (when (org-between-regexps-p
22595 (concat "^[ \t]*#\\+begin_" n)
22596 (concat "^[ \t]*#\\+end_" n)
22597 lim-up lim-down)
22598 (throw 'exit n)))))
22599 nil)))
22601 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22602 "Call `multi-occur' with buffers for all agenda files."
22603 (interactive "sOrg-files matching: ")
22604 (let* ((files (org-agenda-files))
22605 (tnames (mapcar #'file-truename files))
22606 (extra org-agenda-text-search-extra-files))
22607 (when (eq (car extra) 'agenda-archives)
22608 (setq extra (cdr extra))
22609 (setq files (org-add-archive-files files)))
22610 (dolist (f extra)
22611 (unless (member (file-truename f) tnames)
22612 (unless (member f files) (setq files (append files (list f))))
22613 (setq tnames (append tnames (list (file-truename f))))))
22614 (multi-occur
22615 (mapcar (lambda (x)
22616 (with-current-buffer
22617 ;; FIXME: Why not just (find-file-noselect x)?
22618 ;; Is it to avoid the "revert buffer" prompt?
22619 (or (get-file-buffer x) (find-file-noselect x))
22620 (widen)
22621 (current-buffer)))
22622 files)
22623 regexp)))
22625 (if (boundp 'occur-mode-find-occurrence-hook)
22626 ;; Emacs 23
22627 (add-hook 'occur-mode-find-occurrence-hook
22628 (lambda ()
22629 (when (derived-mode-p 'org-mode)
22630 (org-reveal))))
22631 ;; Emacs 22
22632 (defadvice occur-mode-goto-occurrence
22633 (after org-occur-reveal activate)
22634 (and (derived-mode-p 'org-mode) (org-reveal)))
22635 (defadvice occur-mode-goto-occurrence-other-window
22636 (after org-occur-reveal activate)
22637 (and (derived-mode-p 'org-mode) (org-reveal)))
22638 (defadvice occur-mode-display-occurrence
22639 (after org-occur-reveal activate)
22640 (when (derived-mode-p 'org-mode)
22641 (let ((pos (occur-mode-find-occurrence)))
22642 (with-current-buffer (marker-buffer pos)
22643 (save-excursion
22644 (goto-char pos)
22645 (org-reveal)))))))
22647 (defun org-occur-link-in-agenda-files ()
22648 "Create a link and search for it in the agendas.
22649 The link is not stored in `org-stored-links', it is just created
22650 for the search purpose."
22651 (interactive)
22652 (let ((link (condition-case nil
22653 (org-store-link nil)
22654 (error "Unable to create a link to here"))))
22655 (org-occur-in-agenda-files (regexp-quote link))))
22657 (defun org-reverse-string (string)
22658 "Return the reverse of STRING."
22659 (apply 'string (reverse (string-to-list string))))
22661 ;; defsubst org-uniquify must be defined before first use
22663 (defun org-uniquify-alist (alist)
22664 "Merge elements of ALIST with the same key.
22666 For example, in this alist:
22668 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22669 => \\='((a 1 3) (b 2))
22671 merge (a 1) and (a 3) into (a 1 3).
22673 The function returns the new ALIST."
22674 (let (rtn)
22675 (dolist (e alist rtn)
22676 (let (n)
22677 (if (not (assoc (car e) rtn))
22678 (push e rtn)
22679 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22680 (setq rtn (assq-delete-all (car e) rtn))
22681 (push n rtn))))))
22683 (defun org-delete-all (elts list)
22684 "Remove all elements in ELTS from LIST."
22685 (while elts
22686 (setq list (delete (pop elts) list)))
22687 list)
22689 (defun org-back-over-empty-lines ()
22690 "Move backwards over whitespace, to the beginning of the first empty line.
22691 Returns the number of empty lines passed."
22692 (let ((pos (point)))
22693 (if (cdr (assoc 'heading org-blank-before-new-entry))
22694 (skip-chars-backward " \t\n\r")
22695 (unless (eobp)
22696 (forward-line -1)))
22697 (beginning-of-line 2)
22698 (goto-char (min (point) pos))
22699 (count-lines (point) pos)))
22701 (defun org-skip-whitespace ()
22702 (skip-chars-forward " \t\n\r"))
22704 (defun org-point-in-group (point group &optional context)
22705 "Check if POINT is in match-group GROUP.
22706 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22707 match. If the match group does not exist or point is not inside it,
22708 return nil."
22709 (and (match-beginning group)
22710 (>= point (match-beginning group))
22711 (<= point (match-end group))
22712 (if context
22713 (list context (match-beginning group) (match-end group))
22714 t)))
22716 (defun org-switch-to-buffer-other-window (&rest args)
22717 "Switch to buffer in a second window on the current frame.
22718 In particular, do not allow pop-up frames.
22719 Returns the newly created buffer."
22720 (org-no-popups
22721 (apply 'switch-to-buffer-other-window args)))
22723 (defun org-combine-plists (&rest plists)
22724 "Create a single property list from all plists in PLISTS.
22725 The process starts by copying the first list, and then setting properties
22726 from the other lists. Settings in the last list are the most significant
22727 ones and overrule settings in the other lists."
22728 (let ((rtn (copy-sequence (pop plists)))
22729 p v ls)
22730 (while plists
22731 (setq ls (pop plists))
22732 (while ls
22733 (setq p (pop ls) v (pop ls))
22734 (setq rtn (plist-put rtn p v))))
22735 rtn))
22737 (defun org-replace-escapes (string table)
22738 "Replace %-escapes in STRING with values in TABLE.
22739 TABLE is an association list with keys like \"%a\" and string values.
22740 The sequences in STRING may contain normal field width and padding information,
22741 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22742 so values can contain further %-escapes if they are define later in TABLE."
22743 (let ((tbl (copy-alist table))
22744 (case-fold-search nil)
22745 (pchg 0)
22746 re rpl)
22747 (dolist (e tbl)
22748 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22749 (when (and (cdr e) (string-match re (cdr e)))
22750 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22751 (safe "SREF"))
22752 (add-text-properties 0 3 (list 'sref sref) safe)
22753 (setcdr e (replace-match safe t t (cdr e)))))
22754 (while (string-match re string)
22755 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22756 (cdr e)))
22757 (setq string (replace-match rpl t t string))))
22758 (while (setq pchg (next-property-change pchg string))
22759 (let ((sref (get-text-property pchg 'sref string)))
22760 (when (and sref (string-match "SREF" string pchg))
22761 (setq string (replace-match sref t t string)))))
22762 string))
22764 (defun org-sublist (list start end)
22765 "Return a section of LIST, from START to END.
22767 Counting starts at 1."
22768 (cl-subseq list (1- start) end))
22769 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22771 (defun org-find-base-buffer-visiting (file)
22772 "Like `find-buffer-visiting' but always return the base buffer and
22773 not an indirect buffer."
22774 (let ((buf (or (get-file-buffer file)
22775 (find-buffer-visiting file))))
22776 (if buf
22777 (or (buffer-base-buffer buf) buf)
22778 nil)))
22780 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22781 "Org 9.0")
22783 ;;; TODO: Only called once, from ox-odt which should probably use
22784 ;;; org-export-inline-image-p or something.
22785 (defun org-file-image-p (file)
22786 "Return non-nil if FILE is an image."
22787 (save-match-data
22788 (string-match (image-file-name-regexp) file)))
22790 (defun org-get-cursor-date (&optional with-time)
22791 "Return the date at cursor in as a time.
22792 This works in the calendar and in the agenda, anywhere else it just
22793 returns the current time.
22794 If WITH-TIME is non-nil, returns the time of the event at point (in
22795 the agenda) or the current time of the day."
22796 (let (date day defd tp hod mod)
22797 (when with-time
22798 (setq tp (get-text-property (point) 'time))
22799 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22800 (setq hod (string-to-number (match-string 1 tp))
22801 mod (string-to-number (match-string 2 tp))))
22802 (or tp (let ((now (decode-time)))
22803 (setq hod (nth 2 now)
22804 mod (nth 1 now)))))
22805 (cond
22806 ((eq major-mode 'calendar-mode)
22807 (setq date (calendar-cursor-to-date)
22808 defd (encode-time 0 (or mod 0) (or hod 0)
22809 (nth 1 date) (nth 0 date) (nth 2 date))))
22810 ((eq major-mode 'org-agenda-mode)
22811 (setq day (get-text-property (point) 'day))
22812 (when day
22813 (setq date (calendar-gregorian-from-absolute day)
22814 defd (encode-time 0 (or mod 0) (or hod 0)
22815 (nth 1 date) (nth 0 date) (nth 2 date))))))
22816 (or defd (current-time))))
22818 (defun org-mark-subtree (&optional up)
22819 "Mark the current subtree.
22820 This puts point at the start of the current subtree, and mark at
22821 the end. If a numeric prefix UP is given, move up into the
22822 hierarchy of headlines by UP levels before marking the subtree."
22823 (interactive "P")
22824 (org-with-limited-levels
22825 (cond ((org-at-heading-p) (beginning-of-line))
22826 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22827 (t (outline-previous-visible-heading 1))))
22828 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22829 (if (org-called-interactively-p 'any)
22830 (call-interactively 'org-mark-element)
22831 (org-mark-element)))
22834 ;;; Indentation
22836 (defun org--get-expected-indentation (element contentsp)
22837 "Expected indentation column for current line, according to ELEMENT.
22838 ELEMENT is an element containing point. CONTENTSP is non-nil
22839 when indentation is to be computed according to contents of
22840 ELEMENT."
22841 (let ((type (org-element-type element))
22842 (start (org-element-property :begin element))
22843 (post-affiliated (org-element-property :post-affiliated element)))
22844 (org-with-wide-buffer
22845 (cond
22846 (contentsp
22847 (cl-case type
22848 ((diary-sexp footnote-definition) 0)
22849 ((headline inlinetask nil)
22850 (if (not org-adapt-indentation) 0
22851 (let ((level (org-current-level)))
22852 (if level (1+ level) 0))))
22853 ((item plain-list) (org-list-item-body-column post-affiliated))
22855 (goto-char start)
22856 (org-get-indentation))))
22857 ((memq type '(headline inlinetask nil))
22858 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22859 (org--get-expected-indentation element t)
22861 ((memq type '(diary-sexp footnote-definition)) 0)
22862 ;; First paragraph of a footnote definition or an item.
22863 ;; Indent like parent.
22864 ((< (line-beginning-position) start)
22865 (org--get-expected-indentation
22866 (org-element-property :parent element) t))
22867 ;; At first line: indent according to previous sibling, if any,
22868 ;; ignoring footnote definitions and inline tasks, or parent's
22869 ;; contents.
22870 ((= (line-beginning-position) start)
22871 (catch 'exit
22872 (while t
22873 (if (= (point-min) start) (throw 'exit 0)
22874 (goto-char (1- start))
22875 (let* ((previous (org-element-at-point))
22876 (parent previous))
22877 (while (and parent (<= (org-element-property :end parent) start))
22878 (setq previous parent
22879 parent (org-element-property :parent parent)))
22880 (cond
22881 ((not previous) (throw 'exit 0))
22882 ((> (org-element-property :end previous) start)
22883 (throw 'exit (org--get-expected-indentation previous t)))
22884 ((memq (org-element-type previous)
22885 '(footnote-definition inlinetask))
22886 (setq start (org-element-property :begin previous)))
22887 (t (goto-char (org-element-property :begin previous))
22888 (throw 'exit
22889 (if (bolp) (org-get-indentation)
22890 ;; At first paragraph in an item or
22891 ;; a footnote definition.
22892 (org--get-expected-indentation
22893 (org-element-property :parent previous) t))))))))))
22894 ;; Otherwise, move to the first non-blank line above.
22896 (beginning-of-line)
22897 (let ((pos (point)))
22898 (skip-chars-backward " \r\t\n")
22899 (cond
22900 ;; Two blank lines end a footnote definition or a plain
22901 ;; list. When we indent an empty line after them, the
22902 ;; containing list or footnote definition is over, so it
22903 ;; qualifies as a previous sibling. Therefore, we indent
22904 ;; like its first line.
22905 ((and (memq type '(footnote-definition plain-list))
22906 (> (count-lines (point) pos) 2))
22907 (goto-char start)
22908 (org-get-indentation))
22909 ;; Line above is the first one of a paragraph at the
22910 ;; beginning of an item or a footnote definition. Indent
22911 ;; like parent.
22912 ((< (line-beginning-position) start)
22913 (org--get-expected-indentation
22914 (org-element-property :parent element) t))
22915 ;; Line above is the beginning of an element, i.e., point
22916 ;; was originally on the blank lines between element's start
22917 ;; and contents.
22918 ((= (line-beginning-position) post-affiliated)
22919 (org--get-expected-indentation element t))
22920 ;; POS is after contents in a greater element. Indent like
22921 ;; the beginning of the element.
22923 ;; As a special case, if point is at the end of a footnote
22924 ;; definition or an item, indent like the very last element
22925 ;; within. If that last element is an item, indent like its
22926 ;; contents.
22927 ((and (not (eq type 'paragraph))
22928 (let ((cend (org-element-property :contents-end element)))
22929 (and cend (<= cend pos))))
22930 (if (memq type '(footnote-definition item plain-list))
22931 (let ((last (org-element-at-point)))
22932 (org--get-expected-indentation
22933 last (eq (org-element-type last) 'item)))
22934 (goto-char start)
22935 (org-get-indentation)))
22936 ;; In any other case, indent like the current line.
22937 (t (org-get-indentation)))))))))
22939 (defun org--align-node-property ()
22940 "Align node property at point.
22941 Alignment is done according to `org-property-format', which see."
22942 (when (save-excursion
22943 (beginning-of-line)
22944 (looking-at org-property-re))
22945 (replace-match
22946 (concat (match-string 4)
22947 (org-trim
22948 (format org-property-format (match-string 1) (match-string 3))))
22949 t t)))
22951 (defun org-indent-line ()
22952 "Indent line depending on context.
22954 Indentation is done according to the following rules:
22956 - Footnote definitions, diary sexps, headlines and inline tasks
22957 have to start at column 0.
22959 - On the very first line of an element, consider, in order, the
22960 next rules until one matches:
22962 1. If there's a sibling element before, ignoring footnote
22963 definitions and inline tasks, indent like its first line.
22965 2. If element has a parent, indent like its contents. More
22966 precisely, if parent is an item, indent after the
22967 description part, if any, or the bullet (see
22968 `org-list-description-max-indent'). Else, indent like
22969 parent's first line.
22971 3. Otherwise, indent relatively to current level, if
22972 `org-adapt-indentation' is non-nil, or to left margin.
22974 - On a blank line at the end of an element, indent according to
22975 the type of the element. More precisely
22977 1. If element is a plain list, an item, or a footnote
22978 definition, indent like the very last element within.
22980 2. If element is a paragraph, indent like its last non blank
22981 line.
22983 3. Otherwise, indent like its very first line.
22985 - In the code part of a source block, use language major mode
22986 to indent current line if `org-src-tab-acts-natively' is
22987 non-nil. If it is nil, do nothing.
22989 - Otherwise, indent like the first non-blank line above.
22991 The function doesn't indent an item as it could break the whole
22992 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22993 \\[org-shiftmetaright].
22995 Also align node properties according to `org-property-format'."
22996 (interactive)
22997 (cond
22998 (orgstruct-is-++
22999 (let ((indent-line-function
23000 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
23001 (indent-according-to-mode)))
23002 ((org-at-heading-p) 'noindent)
23004 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
23005 (type (org-element-type element)))
23006 (cond ((and (memq type '(plain-list item))
23007 (= (line-beginning-position)
23008 (org-element-property :post-affiliated element)))
23009 'noindent)
23010 ((and (eq type 'src-block)
23011 org-src-tab-acts-natively
23012 (> (line-beginning-position)
23013 (org-element-property :post-affiliated element))
23014 (< (line-beginning-position)
23015 (org-with-wide-buffer
23016 (goto-char (org-element-property :end element))
23017 (skip-chars-backward " \r\t\n")
23018 (line-beginning-position))))
23019 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23021 (let ((column (org--get-expected-indentation element nil)))
23022 ;; Preserve current column.
23023 (if (<= (current-column) (current-indentation))
23024 (org-indent-line-to column)
23025 (save-excursion (org-indent-line-to column))))
23026 ;; Align node property. Also preserve current column.
23027 (when (eq type 'node-property)
23028 (let ((column (current-column)))
23029 (org--align-node-property)
23030 (org-move-to-column column)))))))))
23032 (defun org-indent-region (start end)
23033 "Indent each non-blank line in the region.
23034 Called from a program, START and END specify the region to
23035 indent. The function will not indent contents of example blocks,
23036 verse blocks and export blocks as leading white spaces are
23037 assumed to be significant there."
23038 (interactive "r")
23039 (save-excursion
23040 (goto-char start)
23041 (skip-chars-forward " \r\t\n")
23042 (unless (eobp) (beginning-of-line))
23043 (let ((indent-to
23044 (lambda (ind pos)
23045 ;; Set IND as indentation for all lines between point and
23046 ;; POS. Blank lines are ignored. Leave point after POS
23047 ;; once done.
23048 (let ((limit (copy-marker pos)))
23049 (while (< (point) limit)
23050 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23051 (forward-line))
23052 (set-marker limit nil))))
23053 (end (copy-marker end)))
23054 (while (< (point) end)
23055 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23056 (let* ((element (org-element-at-point))
23057 (type (org-element-type element))
23058 (element-end (copy-marker (org-element-property :end element)))
23059 (ind (org--get-expected-indentation element nil)))
23060 (cond
23061 ((or (memq type '(paragraph table table-row))
23062 (not (or (org-element-property :contents-begin element)
23063 (memq type
23064 '(example-block export-block src-block)))))
23065 ;; Elements here are indented as a single block. Also
23066 ;; align node properties.
23067 (when (eq type 'node-property)
23068 (org--align-node-property)
23069 (beginning-of-line))
23070 (funcall indent-to ind (min element-end end)))
23072 ;; Elements in this category consist of three parts:
23073 ;; before the contents, the contents, and after the
23074 ;; contents. The contents are treated specially,
23075 ;; according to the element type, or not indented at
23076 ;; all. Other parts are indented as a single block.
23077 (let* ((post (copy-marker
23078 (org-element-property :post-affiliated element)))
23079 (cbeg
23080 (copy-marker
23081 (cond
23082 ((not (org-element-property :contents-begin element))
23083 ;; Fake contents for source blocks.
23084 (org-with-wide-buffer
23085 (goto-char post)
23086 (forward-line)
23087 (point)))
23088 ((memq type '(footnote-definition item plain-list))
23089 ;; Contents in these elements could start on
23090 ;; the same line as the beginning of the
23091 ;; element. Make sure we start indenting
23092 ;; from the second line.
23093 (org-with-wide-buffer
23094 (goto-char post)
23095 (end-of-line)
23096 (skip-chars-forward " \r\t\n")
23097 (if (eobp) (point) (line-beginning-position))))
23098 (t (org-element-property :contents-begin element)))))
23099 (cend (copy-marker
23100 (or (org-element-property :contents-end element)
23101 ;; Fake contents for source blocks.
23102 (org-with-wide-buffer
23103 (goto-char element-end)
23104 (skip-chars-backward " \r\t\n")
23105 (line-beginning-position)))
23106 t)))
23107 ;; Do not change items indentation individually as it
23108 ;; might break the list as a whole. On the other
23109 ;; hand, when at a plain list, indent it as a whole.
23110 (cond ((eq type 'plain-list)
23111 (let ((offset (- ind (org-get-indentation))))
23112 (unless (zerop offset)
23113 (indent-rigidly (org-element-property :begin element)
23114 (org-element-property :end element)
23115 offset))
23116 (goto-char cbeg)))
23117 ((eq type 'item) (goto-char cbeg))
23118 (t (funcall indent-to ind (min cbeg end))))
23119 (when (< (point) end)
23120 (cl-case type
23121 ((example-block export-block verse-block))
23122 (src-block
23123 ;; In a source block, indent source code
23124 ;; according to language major mode, but only if
23125 ;; `org-src-tab-acts-natively' is non-nil.
23126 (when (and (< (point) end) org-src-tab-acts-natively)
23127 (ignore-errors
23128 (org-babel-do-in-edit-buffer
23129 (indent-region (point-min) (point-max))))))
23130 (t (org-indent-region (point) (min cend end))))
23131 (goto-char (min cend end))
23132 (when (< (point) end)
23133 (funcall indent-to ind (min element-end end))))
23134 (set-marker post nil)
23135 (set-marker cbeg nil)
23136 (set-marker cend nil))))
23137 (set-marker element-end nil))))
23138 (set-marker end nil))))
23140 (defun org-indent-drawer ()
23141 "Indent the drawer at point."
23142 (interactive)
23143 (unless (save-excursion
23144 (beginning-of-line)
23145 (org-looking-at-p org-drawer-regexp))
23146 (user-error "Not at a drawer"))
23147 (let ((element (org-element-at-point)))
23148 (unless (memq (org-element-type element) '(drawer property-drawer))
23149 (user-error "Not at a drawer"))
23150 (org-with-wide-buffer
23151 (org-indent-region (org-element-property :begin element)
23152 (org-element-property :end element))))
23153 (message "Drawer at point indented"))
23155 (defun org-indent-block ()
23156 "Indent the block at point."
23157 (interactive)
23158 (unless (save-excursion
23159 (beginning-of-line)
23160 (let ((case-fold-search t))
23161 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23162 (user-error "Not at a block"))
23163 (let ((element (org-element-at-point)))
23164 (unless (memq (org-element-type element)
23165 '(comment-block center-block dynamic-block example-block
23166 export-block quote-block special-block
23167 src-block verse-block))
23168 (user-error "Not at a block"))
23169 (org-with-wide-buffer
23170 (org-indent-region (org-element-property :begin element)
23171 (org-element-property :end element))))
23172 (message "Block at point indented"))
23175 ;;; Filling
23177 ;; We use our own fill-paragraph and auto-fill functions.
23179 ;; `org-fill-paragraph' relies on adaptive filling and context
23180 ;; checking. Appropriate `fill-prefix' is computed with
23181 ;; `org-adaptive-fill-function'.
23183 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23184 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23185 ;; `org-adaptive-fill-function' value. Internally,
23186 ;; `org-comment-line-break-function' breaks the line.
23188 ;; `org-setup-filling' installs filling and auto-filling related
23189 ;; variables during `org-mode' initialization.
23191 (defvar org-element-paragraph-separate) ; org-element.el
23192 (defun org-setup-filling ()
23193 (require 'org-element)
23194 ;; Prevent auto-fill from inserting unwanted new items.
23195 (when (boundp 'fill-nobreak-predicate)
23196 (setq-local
23197 fill-nobreak-predicate
23198 (org-uniquify
23199 (append fill-nobreak-predicate
23200 '(org-fill-line-break-nobreak-p
23201 org-fill-paragraph-with-timestamp-nobreak-p)))))
23202 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23203 (setq-local paragraph-start paragraph-ending)
23204 (setq-local paragraph-separate paragraph-ending))
23205 (setq-local fill-paragraph-function 'org-fill-paragraph)
23206 (setq-local auto-fill-inhibit-regexp nil)
23207 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23208 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23209 (setq-local comment-line-break-function 'org-comment-line-break-function))
23211 (defun org-fill-line-break-nobreak-p ()
23212 "Non-nil when a new line at point would create an Org line break."
23213 (save-excursion
23214 (skip-chars-backward "[ \t]")
23215 (skip-chars-backward "\\\\")
23216 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23218 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23219 "Non-nil when a new line at point would split a timestamp."
23220 (and (org-at-timestamp-p t)
23221 (not (looking-at org-ts-regexp-both))))
23223 (declare-function message-in-body-p "message" ())
23224 (defvar orgtbl-line-start-regexp) ; From org-table.el
23225 (defun org-adaptive-fill-function ()
23226 "Compute a fill prefix for the current line.
23227 Return fill prefix, as a string, or nil if current line isn't
23228 meant to be filled. For convenience, if `adaptive-fill-regexp'
23229 matches in paragraphs or comments, use it."
23230 (catch 'exit
23231 (when (derived-mode-p 'message-mode)
23232 (save-excursion
23233 (beginning-of-line)
23234 (cond ((not (message-in-body-p)) (throw 'exit nil))
23235 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23236 ((looking-at message-cite-prefix-regexp)
23237 (throw 'exit (match-string-no-properties 0)))
23238 ((looking-at org-outline-regexp)
23239 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23240 (org-with-wide-buffer
23241 (unless (org-at-heading-p)
23242 (let* ((p (line-beginning-position))
23243 (element (save-excursion
23244 (beginning-of-line)
23245 (org-element-at-point)))
23246 (type (org-element-type element))
23247 (post-affiliated (org-element-property :post-affiliated element)))
23248 (unless (< p post-affiliated)
23249 (cl-case type
23250 (comment
23251 (save-excursion
23252 (beginning-of-line)
23253 (looking-at "[ \t]*")
23254 (concat (match-string 0) "# ")))
23255 (footnote-definition "")
23256 ((item plain-list)
23257 (make-string (org-list-item-body-column post-affiliated) ?\s))
23258 (paragraph
23259 ;; Fill prefix is usually the same as the current line,
23260 ;; unless the paragraph is at the beginning of an item.
23261 (let ((parent (org-element-property :parent element)))
23262 (save-excursion
23263 (beginning-of-line)
23264 (cond ((eq (org-element-type parent) 'item)
23265 (make-string (org-list-item-body-column
23266 (org-element-property :begin parent))
23267 ?\s))
23268 ((and adaptive-fill-regexp
23269 ;; Locally disable
23270 ;; `adaptive-fill-function' to let
23271 ;; `fill-context-prefix' handle
23272 ;; `adaptive-fill-regexp' variable.
23273 (let (adaptive-fill-function)
23274 (fill-context-prefix
23275 post-affiliated
23276 (org-element-property :end element)))))
23277 ((looking-at "[ \t]+") (match-string 0))
23278 (t "")))))
23279 (comment-block
23280 ;; Only fill contents if P is within block boundaries.
23281 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23282 (forward-line)
23283 (point)))
23284 (cend (save-excursion
23285 (goto-char (org-element-property :end element))
23286 (skip-chars-backward " \r\t\n")
23287 (line-beginning-position))))
23288 (when (and (>= p cbeg) (< p cend))
23289 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23290 (match-string 0)
23291 "")))))))))))
23293 (declare-function message-goto-body "message" ())
23294 (defvar message-cite-prefix-regexp) ; From message.el
23295 (defun org-fill-paragraph (&optional justify)
23296 "Fill element at point, when applicable.
23298 This function only applies to comment blocks, comments, example
23299 blocks and paragraphs. Also, as a special case, re-align table
23300 when point is at one.
23302 If JUSTIFY is non-nil (interactively, with prefix argument),
23303 justify as well. If `sentence-end-double-space' is non-nil, then
23304 period followed by one space does not end a sentence, so don't
23305 break a line there. The variable `fill-column' controls the
23306 width for filling.
23308 For convenience, when point is at a plain list, an item or
23309 a footnote definition, try to fill the first paragraph within."
23310 (interactive)
23311 (if (and (derived-mode-p 'message-mode)
23312 (or (not (message-in-body-p))
23313 (save-excursion (move-beginning-of-line 1)
23314 (looking-at message-cite-prefix-regexp))))
23315 ;; First ensure filling is correct in message-mode.
23316 (let ((fill-paragraph-function
23317 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23318 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23319 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23320 (paragraph-separate
23321 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23322 (fill-paragraph nil))
23323 (with-syntax-table org-mode-transpose-word-syntax-table
23324 ;; Move to end of line in order to get the first paragraph
23325 ;; within a plain list or a footnote definition.
23326 (let ((element (save-excursion
23327 (end-of-line)
23328 (or (ignore-errors (org-element-at-point))
23329 (user-error "An element cannot be parsed line %d"
23330 (line-number-at-pos (point)))))))
23331 ;; First check if point is in a blank line at the beginning of
23332 ;; the buffer. In that case, ignore filling.
23333 (cl-case (org-element-type element)
23334 ;; Use major mode filling function is src blocks.
23335 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23336 ;; Align Org tables, leave table.el tables as-is.
23337 (table-row (org-table-align) t)
23338 (table
23339 (when (eq (org-element-property :type element) 'org)
23340 (save-excursion
23341 (goto-char (org-element-property :post-affiliated element))
23342 (org-table-align)))
23344 (paragraph
23345 ;; Paragraphs may contain `line-break' type objects.
23346 (let ((beg (max (point-min)
23347 (org-element-property :contents-begin element)))
23348 (end (min (point-max)
23349 (org-element-property :contents-end element))))
23350 ;; Do nothing if point is at an affiliated keyword.
23351 (if (< (line-end-position) beg) t
23352 (when (derived-mode-p 'message-mode)
23353 ;; In `message-mode', do not fill following citation
23354 ;; in current paragraph nor text before message body.
23355 (let ((body-start (save-excursion (message-goto-body))))
23356 (when body-start (setq beg (max body-start beg))))
23357 (when (save-excursion
23358 (re-search-forward
23359 (concat "^" message-cite-prefix-regexp) end t))
23360 (setq end (match-beginning 0))))
23361 ;; Fill paragraph, taking line breaks into account.
23362 (save-excursion
23363 (goto-char beg)
23364 (let ((cuts (list beg)))
23365 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23366 (when (eq 'line-break
23367 (org-element-type
23368 (save-excursion (backward-char)
23369 (org-element-context))))
23370 (push (point) cuts)))
23371 (dolist (c (delq end cuts))
23372 (fill-region-as-paragraph c end justify)
23373 (setq end c))))
23374 t)))
23375 ;; Contents of `comment-block' type elements should be
23376 ;; filled as plain text, but only if point is within block
23377 ;; markers.
23378 (comment-block
23379 (let* ((case-fold-search t)
23380 (beg (save-excursion
23381 (goto-char (org-element-property :begin element))
23382 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23383 (forward-line)
23384 (point)))
23385 (end (save-excursion
23386 (goto-char (org-element-property :end element))
23387 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23388 (line-beginning-position))))
23389 (if (or (< (point) beg) (> (point) end)) t
23390 (fill-region-as-paragraph
23391 (save-excursion (end-of-line)
23392 (re-search-backward "^[ \t]*$" beg 'move)
23393 (line-beginning-position))
23394 (save-excursion (beginning-of-line)
23395 (re-search-forward "^[ \t]*$" end 'move)
23396 (line-beginning-position))
23397 justify))))
23398 ;; Fill comments.
23399 (comment
23400 (let ((begin (org-element-property :post-affiliated element))
23401 (end (org-element-property :end element)))
23402 (when (and (>= (point) begin) (<= (point) end))
23403 (let ((begin (save-excursion
23404 (end-of-line)
23405 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23406 (progn (forward-line) (point))
23407 begin)))
23408 (end (save-excursion
23409 (end-of-line)
23410 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23411 (1- (line-beginning-position))
23412 (skip-chars-backward " \r\t\n")
23413 (line-end-position)))))
23414 ;; Do not fill comments when at a blank line.
23415 (when (> end begin)
23416 (let ((fill-prefix
23417 (save-excursion
23418 (beginning-of-line)
23419 (looking-at "[ \t]*#")
23420 (let ((comment-prefix (match-string 0)))
23421 (goto-char (match-end 0))
23422 (if (looking-at adaptive-fill-regexp)
23423 (concat comment-prefix (match-string 0))
23424 (concat comment-prefix " "))))))
23425 (save-excursion
23426 (fill-region-as-paragraph begin end justify))))))
23428 ;; Ignore every other element.
23429 (otherwise t))))))
23431 (defun org-auto-fill-function ()
23432 "Auto-fill function."
23433 ;; Check if auto-filling is meaningful.
23434 (let ((fc (current-fill-column)))
23435 (when (and fc (> (current-column) fc))
23436 (let* ((fill-prefix (org-adaptive-fill-function))
23437 ;; Enforce empty fill prefix, if required. Otherwise, it
23438 ;; will be computed again.
23439 (adaptive-fill-mode (not (equal fill-prefix ""))))
23440 (when fill-prefix (do-auto-fill))))))
23442 (defun org-comment-line-break-function (&optional soft)
23443 "Break line at point and indent, continuing comment if within one.
23444 The inserted newline is marked hard if variable
23445 `use-hard-newlines' is true, unless optional argument SOFT is
23446 non-nil."
23447 (if soft (insert-and-inherit ?\n) (newline 1))
23448 (save-excursion (forward-char -1) (delete-horizontal-space))
23449 (delete-horizontal-space)
23450 (indent-to-left-margin)
23451 (insert-before-markers-and-inherit fill-prefix))
23454 ;;; Fixed Width Areas
23456 (defun org-toggle-fixed-width ()
23457 "Toggle fixed-width markup.
23459 Add or remove fixed-width markup on current line, whenever it
23460 makes sense. Return an error otherwise.
23462 If a region is active and if it contains only fixed-width areas
23463 or blank lines, remove all fixed-width markup in it. If the
23464 region contains anything else, convert all non-fixed-width lines
23465 to fixed-width ones.
23467 Blank lines at the end of the region are ignored unless the
23468 region only contains such lines."
23469 (interactive)
23470 (if (not (org-region-active-p))
23471 ;; No region:
23473 ;; Remove fixed width marker only in a fixed-with element.
23475 ;; Add fixed width maker in paragraphs, in blank lines after
23476 ;; elements or at the beginning of a headline or an inlinetask,
23477 ;; and before any one-line elements (e.g., a clock).
23478 (progn
23479 (beginning-of-line)
23480 (let* ((element (org-element-at-point))
23481 (type (org-element-type element)))
23482 (cond
23483 ((and (eq type 'fixed-width)
23484 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23485 (replace-match
23486 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23487 ((and (memq type '(babel-call clock comment diary-sexp headline
23488 horizontal-rule keyword paragraph
23489 planning))
23490 (<= (org-element-property :post-affiliated element) (point)))
23491 (skip-chars-forward " \t")
23492 (insert ": "))
23493 ((and (org-looking-at-p "[ \t]*$")
23494 (or (eq type 'inlinetask)
23495 (save-excursion
23496 (skip-chars-forward " \r\t\n")
23497 (<= (org-element-property :end element) (point)))))
23498 (delete-region (point) (line-end-position))
23499 (org-indent-line)
23500 (insert ": "))
23501 (t (user-error "Cannot insert a fixed-width line here")))))
23502 ;; Region active.
23503 (let* ((begin (save-excursion
23504 (goto-char (region-beginning))
23505 (line-beginning-position)))
23506 (end (copy-marker
23507 (save-excursion
23508 (goto-char (region-end))
23509 (unless (eolp) (beginning-of-line))
23510 (if (save-excursion (re-search-backward "\\S-" begin t))
23511 (progn (skip-chars-backward " \r\t\n") (point))
23512 (point)))))
23513 (all-fixed-width-p
23514 (catch 'not-all-p
23515 (save-excursion
23516 (goto-char begin)
23517 (skip-chars-forward " \r\t\n")
23518 (when (eobp) (throw 'not-all-p nil))
23519 (while (< (point) end)
23520 (let ((element (org-element-at-point)))
23521 (if (eq (org-element-type element) 'fixed-width)
23522 (goto-char (org-element-property :end element))
23523 (throw 'not-all-p nil))))
23524 t))))
23525 (if all-fixed-width-p
23526 (save-excursion
23527 (goto-char begin)
23528 (while (< (point) end)
23529 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23530 (replace-match
23531 "" nil nil nil
23532 (if (= (line-end-position) (match-end 0)) 0 1)))
23533 (forward-line)))
23534 (let ((min-ind (point-max)))
23535 ;; Find minimum indentation across all lines.
23536 (save-excursion
23537 (goto-char begin)
23538 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23539 (setq min-ind 0)
23540 (catch 'zerop
23541 (while (< (point) end)
23542 (unless (org-looking-at-p "[ \t]*$")
23543 (let ((ind (org-get-indentation)))
23544 (setq min-ind (min min-ind ind))
23545 (when (zerop ind) (throw 'zerop t))))
23546 (forward-line)))))
23547 ;; Loop over all lines and add fixed-width markup everywhere
23548 ;; but in fixed-width lines.
23549 (save-excursion
23550 (goto-char begin)
23551 (while (< (point) end)
23552 (cond
23553 ((org-at-heading-p)
23554 (insert ": ")
23555 (forward-line)
23556 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23557 (insert ":")
23558 (forward-line)))
23559 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23560 (let* ((element (org-element-at-point))
23561 (element-end (org-element-property :end element)))
23562 (if (eq (org-element-type element) 'fixed-width)
23563 (progn (goto-char element-end)
23564 (skip-chars-backward " \r\t\n")
23565 (forward-line))
23566 (let ((limit (min end element-end)))
23567 (while (< (point) limit)
23568 (org-move-to-column min-ind t)
23569 (insert ": ")
23570 (forward-line))))))
23572 (org-move-to-column min-ind t)
23573 (insert ": ")
23574 (forward-line)))))))
23575 (set-marker end nil))))
23578 ;;; Comments
23580 ;; Org comments syntax is quite complex. It requires the entire line
23581 ;; to be just a comment. Also, even with the right syntax at the
23582 ;; beginning of line, some some elements (i.e. verse-block or
23583 ;; example-block) don't accept comments. Usual Emacs comment commands
23584 ;; cannot cope with those requirements. Therefore, Org replaces them.
23586 ;; Org still relies on `comment-dwim', but cannot trust
23587 ;; `comment-only-p'. So, `comment-region-function' and
23588 ;; `uncomment-region-function' both point
23589 ;; to`org-comment-or-uncomment-region'. Eventually,
23590 ;; `org-insert-comment' takes care of insertion of comments at the
23591 ;; beginning of line.
23593 ;; `org-setup-comments-handling' install comments related variables
23594 ;; during `org-mode' initialization.
23596 (defun org-setup-comments-handling ()
23597 (interactive)
23598 (setq-local comment-use-syntax nil)
23599 (setq-local comment-start "# ")
23600 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23601 (setq-local comment-insert-comment-function 'org-insert-comment)
23602 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23603 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23605 (defun org-insert-comment ()
23606 "Insert an empty comment above current line.
23607 If the line is empty, insert comment at its beginning. When
23608 point is within a source block, comment according to the related
23609 major mode."
23610 (if (let ((element (org-element-at-point)))
23611 (and (eq (org-element-type element) 'src-block)
23612 (< (save-excursion
23613 (goto-char (org-element-property :post-affiliated element))
23614 (line-end-position))
23615 (point))
23616 (> (save-excursion
23617 (goto-char (org-element-property :end element))
23618 (skip-chars-backward " \r\t\n")
23619 (line-beginning-position))
23620 (point))))
23621 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23622 (beginning-of-line)
23623 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23624 (open-line 1))
23625 (org-indent-line)
23626 (insert "# ")))
23628 (defvar comment-empty-lines) ; From newcomment.el.
23629 (defun org-comment-or-uncomment-region (beg end &rest _)
23630 "Comment or uncomment each non-blank line in the region.
23631 Uncomment each non-blank line between BEG and END if it only
23632 contains commented lines. Otherwise, comment them. If region is
23633 strictly within a source block, use appropriate comment syntax."
23634 (if (let ((element (org-element-at-point)))
23635 (and (eq (org-element-type element) 'src-block)
23636 (< (save-excursion
23637 (goto-char (org-element-property :post-affiliated element))
23638 (line-end-position))
23639 beg)
23640 (>= (save-excursion
23641 (goto-char (org-element-property :end element))
23642 (skip-chars-backward " \r\t\n")
23643 (line-beginning-position))
23644 end)))
23645 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23646 (save-restriction
23647 ;; Restrict region
23648 (narrow-to-region (save-excursion (goto-char beg)
23649 (skip-chars-forward " \r\t\n" end)
23650 (line-beginning-position))
23651 (save-excursion (goto-char end)
23652 (skip-chars-backward " \r\t\n" beg)
23653 (line-end-position)))
23654 (let ((uncommentp
23655 ;; UNCOMMENTP is non-nil when every non blank line between
23656 ;; BEG and END is a comment.
23657 (save-excursion
23658 (goto-char (point-min))
23659 (while (and (not (eobp))
23660 (let ((element (org-element-at-point)))
23661 (and (eq (org-element-type element) 'comment)
23662 (goto-char (min (point-max)
23663 (org-element-property
23664 :end element)))))))
23665 (eobp))))
23666 (if uncommentp
23667 ;; Only blank lines and comments in region: uncomment it.
23668 (save-excursion
23669 (goto-char (point-min))
23670 (while (not (eobp))
23671 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23672 (replace-match "" nil nil nil 1))
23673 (forward-line)))
23674 ;; Comment each line in region.
23675 (let ((min-indent (point-max)))
23676 ;; First find the minimum indentation across all lines.
23677 (save-excursion
23678 (goto-char (point-min))
23679 (while (and (not (eobp)) (not (zerop min-indent)))
23680 (unless (looking-at "[ \t]*$")
23681 (setq min-indent (min min-indent (current-indentation))))
23682 (forward-line)))
23683 ;; Then loop over all lines.
23684 (save-excursion
23685 (goto-char (point-min))
23686 (while (not (eobp))
23687 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23688 ;; Don't get fooled by invisible text (e.g. link path)
23689 ;; when moving to column MIN-INDENT.
23690 (let ((buffer-invisibility-spec nil))
23691 (org-move-to-column min-indent t))
23692 (insert comment-start))
23693 (forward-line)))))))))
23695 (defun org-comment-dwim (_arg)
23696 "Call `comment-dwim' within a source edit buffer if needed."
23697 (interactive "*P")
23698 (if (org-in-src-block-p)
23699 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23700 (call-interactively 'comment-dwim)))
23703 ;;; Timestamps API
23705 ;; This section contains tools to operate on timestamp objects, as
23706 ;; returned by, e.g. `org-element-context'.
23708 (defun org-timestamp--to-internal-time (timestamp &optional end)
23709 "Encode TIMESTAMP object into Emacs internal time.
23710 Use end of date range or time range when END is non-nil."
23711 (apply #'encode-time
23712 (cons 0
23713 (mapcar
23714 (lambda (prop) (or (org-element-property prop timestamp) 0))
23715 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23716 '(:minute-start :hour-start :day-start :month-start
23717 :year-start))))))
23719 (defun org-timestamp-has-time-p (timestamp)
23720 "Non-nil when TIMESTAMP has a time specified."
23721 (org-element-property :hour-start timestamp))
23723 (defun org-timestamp-format (timestamp format &optional end utc)
23724 "Format a TIMESTAMP object into a string.
23726 FORMAT is a format specifier to be passed to
23727 `format-time-string'.
23729 When optional argument END is non-nil, use end of date-range or
23730 time-range, if possible.
23732 When optional argument UTC is non-nil, time will be expressed as
23733 Universal Time."
23734 (format-time-string
23735 format (org-timestamp--to-internal-time timestamp end)
23736 (and utc t)))
23738 (defun org-timestamp-split-range (timestamp &optional end)
23739 "Extract a TIMESTAMP object from a date or time range.
23741 END, when non-nil, means extract the end of the range.
23742 Otherwise, extract its start.
23744 Return a new timestamp object."
23745 (let ((type (org-element-property :type timestamp)))
23746 (if (memq type '(active inactive diary)) timestamp
23747 (let ((split-ts (org-element-copy timestamp)))
23748 ;; Set new type.
23749 (org-element-put-property
23750 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23751 ;; Copy start properties over end properties if END is
23752 ;; non-nil. Otherwise, copy end properties over `start' ones.
23753 (let ((p-alist '((:minute-start . :minute-end)
23754 (:hour-start . :hour-end)
23755 (:day-start . :day-end)
23756 (:month-start . :month-end)
23757 (:year-start . :year-end))))
23758 (dolist (p-cell p-alist)
23759 (org-element-put-property
23760 split-ts
23761 (funcall (if end #'car #'cdr) p-cell)
23762 (org-element-property
23763 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23764 ;; Eventually refresh `:raw-value'.
23765 (org-element-put-property split-ts :raw-value nil)
23766 (org-element-put-property
23767 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23769 (defun org-timestamp-translate (timestamp &optional boundary)
23770 "Translate TIMESTAMP object to custom format.
23772 Format string is defined in `org-time-stamp-custom-formats',
23773 which see.
23775 When optional argument BOUNDARY is non-nil, it is either the
23776 symbol `start' or `end'. In this case, only translate the
23777 starting or ending part of TIMESTAMP if it is a date or time
23778 range. Otherwise, translate both parts.
23780 Return timestamp as-is if `org-display-custom-times' is nil or if
23781 it has a `diary' type."
23782 (let ((type (org-element-property :type timestamp)))
23783 (if (or (not org-display-custom-times) (eq type 'diary))
23784 (org-element-interpret-data timestamp)
23785 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23786 org-time-stamp-custom-formats)))
23787 (if (and (not boundary) (memq type '(active-range inactive-range)))
23788 (concat (org-timestamp-format timestamp fmt)
23789 "--"
23790 (org-timestamp-format timestamp fmt t))
23791 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23795 ;;; Other stuff.
23797 (defvar reftex-docstruct-symbol)
23798 (defvar reftex-cite-format)
23799 (defvar org--rds)
23801 (defun org-reftex-citation ()
23802 "Use reftex-citation to insert a citation into the buffer.
23803 This looks for a line like
23805 #+BIBLIOGRAPHY: foo plain option:-d
23807 and derives from it that foo.bib is the bibliography file relevant
23808 for this document. It then installs the necessary environment for RefTeX
23809 to work in this buffer and calls `reftex-citation' to insert a citation
23810 into the buffer.
23812 Export of such citations to both LaTeX and HTML is handled by the contributed
23813 package ox-bibtex by Taru Karttunen."
23814 (interactive)
23815 (let ((reftex-docstruct-symbol 'org--rds)
23816 (reftex-cite-format "\\cite{%l}")
23817 org--rds bib)
23818 (save-excursion
23819 (save-restriction
23820 (widen)
23821 (let ((case-fold-search t)
23822 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23823 (if (not (save-excursion
23824 (or (re-search-forward re nil t)
23825 (re-search-backward re nil t))))
23826 (user-error "No bibliography defined in file")
23827 (setq bib (concat (match-string 1) ".bib")
23828 org--rds (list (list 'bib bib)))))))
23829 (call-interactively 'reftex-citation)))
23831 ;;;; Functions extending outline functionality
23833 (defun org-beginning-of-line (&optional arg)
23834 "Go to the beginning of the current line. If that is invisible, continue
23835 to a visible line beginning. This makes the function of C-a more intuitive.
23836 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23837 first attempt, and only move to after the tags when the cursor is already
23838 beyond the end of the headline."
23839 (interactive "P")
23840 (let ((pos (point))
23841 (special (if (consp org-special-ctrl-a/e)
23842 (car org-special-ctrl-a/e)
23843 org-special-ctrl-a/e))
23844 deactivate-mark refpos)
23845 (call-interactively (if (org-bound-and-true-p visual-line-mode)
23846 #'beginning-of-visual-line
23847 #'move-beginning-of-line))
23848 (cond
23849 ((or arg (not special)))
23850 ((and (looking-at org-complex-heading-regexp)
23851 (eq (char-after (match-end 1)) ?\s))
23852 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23853 (point-at-eol)))
23854 (goto-char
23855 (if (eq special t)
23856 (cond ((> pos refpos) refpos)
23857 ((= pos (point)) refpos)
23858 (t (point)))
23859 (cond ((> pos (point)) (point))
23860 ((not (eq last-command this-command)) (point))
23861 (t refpos)))))
23862 ((org-at-item-p)
23863 ;; Being at an item and not looking at an the item means point
23864 ;; was previously moved to beginning of a visual line, which
23865 ;; doesn't contain the item. Therefore, do nothing special,
23866 ;; just stay here.
23867 (when (looking-at org-list-full-item-re)
23868 ;; Set special position at first white space character after
23869 ;; bullet, and check-box, if any.
23870 (let ((after-bullet
23871 (let ((box (match-end 3)))
23872 (if (not box) (match-end 1)
23873 (let ((after (char-after box)))
23874 (if (and after (= after ? )) (1+ box) box))))))
23875 ;; Special case: Move point to special position when
23876 ;; currently after it or at beginning of line.
23877 (if (eq special t)
23878 (when (or (> pos after-bullet) (= (point) pos))
23879 (goto-char after-bullet))
23880 ;; Reversed case: Move point to special position when
23881 ;; point was already at beginning of line and command is
23882 ;; repeated.
23883 (when (and (= (point) pos) (eq last-command this-command))
23884 (goto-char after-bullet))))))))
23885 (setq disable-point-adjustment
23886 (or (not (invisible-p (point)))
23887 (not (invisible-p (max (point-min) (1- (point))))))))
23889 (defun org-end-of-line (&optional arg)
23890 "Go to the end of the line.
23891 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23892 tags on the first attempt, and only move to after the tags when
23893 the cursor is already beyond the end of the headline."
23894 (interactive "P")
23895 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23896 org-special-ctrl-a/e))
23897 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23898 'end-of-visual-line)
23899 ((fboundp 'move-end-of-line) 'move-end-of-line)
23900 (t 'end-of-line)))
23901 deactivate-mark)
23902 (if (or (not special) arg) (call-interactively move-fun)
23903 (let* ((element (save-excursion (beginning-of-line)
23904 (org-element-at-point)))
23905 (type (org-element-type element)))
23906 (cond
23907 ((memq type '(headline inlinetask))
23908 (let ((pos (point)))
23909 (beginning-of-line 1)
23910 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23911 (if (eq special t)
23912 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23913 (goto-char (match-beginning 1))
23914 (goto-char (match-end 0)))
23915 (if (or (< pos (match-end 0))
23916 (not (eq this-command last-command)))
23917 (goto-char (match-end 0))
23918 (goto-char (match-beginning 1))))
23919 (call-interactively move-fun))))
23920 ((outline-invisible-p (line-end-position))
23921 ;; If element is hidden, `move-end-of-line' would put point
23922 ;; after it. Use `end-of-line' to stay on current line.
23923 (call-interactively 'end-of-line))
23924 (t (call-interactively move-fun)))))
23925 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23926 (setq disable-point-adjustment
23927 (or (not (invisible-p (point)))
23928 (not (invisible-p (max (point-min) (1- (point))))))))
23930 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23931 (define-key org-mode-map "\C-e" 'org-end-of-line)
23933 (defun org-backward-sentence (&optional _arg)
23934 "Go to beginning of sentence, or beginning of table field.
23935 This will call `backward-sentence' or `org-table-beginning-of-field',
23936 depending on context."
23937 (interactive)
23938 (let* ((element (org-element-at-point))
23939 (contents-begin (org-element-property :contents-begin element))
23940 (table (org-element-lineage element '(table) t)))
23941 (if (and table
23942 (> (point) contents-begin)
23943 (<= (point) (org-element-property :contents-end table)))
23944 (call-interactively #'org-table-beginning-of-field)
23945 (save-restriction
23946 (when (and contents-begin
23947 (< (point-min) contents-begin)
23948 (> (point) contents-begin))
23949 (narrow-to-region contents-begin
23950 (org-element-property :contents-end element)))
23951 (call-interactively #'backward-sentence)))))
23953 (defun org-forward-sentence (&optional _arg)
23954 "Go to end of sentence, or end of table field.
23955 This will call `forward-sentence' or `org-table-end-of-field',
23956 depending on context."
23957 (interactive)
23958 (let* ((element (org-element-at-point))
23959 (contents-end (org-element-property :contents-end element))
23960 (table (org-element-lineage element '(table) t)))
23961 (if (and table
23962 (>= (point) (org-element-property :contents-begin table))
23963 (< (point) contents-end))
23964 (call-interactively #'org-table-end-of-field)
23965 (save-restriction
23966 (when (and contents-end
23967 (> (point-max) contents-end)
23968 ;; Skip blank lines between elements.
23969 (< (org-element-property :end element)
23970 (save-excursion (goto-char contents-end)
23971 (skip-chars-forward " \r\t\n"))))
23972 (narrow-to-region (org-element-property :contents-begin element)
23973 contents-end))
23974 (call-interactively #'forward-sentence)))))
23976 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23977 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23979 (defun org-kill-line (&optional _arg)
23980 "Kill line, to tags or end of line."
23981 (interactive)
23982 (cond
23983 ((or (not org-special-ctrl-k)
23984 (bolp)
23985 (not (org-at-heading-p)))
23986 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23987 org-ctrl-k-protect-subtree
23988 (or (eq org-ctrl-k-protect-subtree 'error)
23989 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23990 (user-error "C-k aborted as it would kill a hidden subtree"))
23991 (call-interactively
23992 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23993 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23994 (kill-region (point) (match-beginning 1))
23995 (org-set-tags nil t))
23996 (t (kill-region (point) (point-at-eol)))))
23998 (define-key org-mode-map "\C-k" 'org-kill-line)
24000 (defun org-yank (&optional arg)
24001 "Yank. If the kill is a subtree, treat it specially.
24002 This command will look at the current kill and check if is a single
24003 subtree, or a series of subtrees[1]. If it passes the test, and if the
24004 cursor is at the beginning of a line or after the stars of a currently
24005 empty headline, then the yank is handled specially. How exactly depends
24006 on the value of the following variables.
24008 `org-yank-folded-subtrees'
24009 By default, this variable is non-nil, which results in subtree(s)
24010 being folded after insertion, but only if doing so would now
24011 swallow text after the yanked text.
24013 `org-yank-adjusted-subtrees'
24014 When non-nil (the default value is nil), the subtree will be
24015 promoted or demoted in order to fit into the local outline tree
24016 structure, which means that the level will be adjusted so that it
24017 becomes the smaller one of the two *visible* surrounding headings.
24019 Any prefix to this command will cause `yank' to be called directly with
24020 no special treatment. In particular, a simple \\[universal-argument] prefix \
24021 will just
24022 plainly yank the text as it is.
24024 \[1] The test checks if the first non-white line is a heading
24025 and if there are no other headings with fewer stars."
24026 (interactive "P")
24027 (org-yank-generic 'yank arg))
24029 (defun org-yank-generic (command arg)
24030 "Perform some yank-like command.
24032 This function implements the behavior described in the `org-yank'
24033 documentation. However, it has been generalized to work for any
24034 interactive command with similar behavior."
24036 ;; pretend to be command COMMAND
24037 (setq this-command command)
24039 (if arg
24040 (call-interactively command)
24042 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24043 (and (org-kill-is-subtree-p)
24044 (or (bolp)
24045 (and (looking-at "[ \t]*$")
24046 (string-match
24047 "\\`\\*+\\'"
24048 (buffer-substring (point-at-bol) (point)))))))
24049 swallowp)
24050 (cond
24051 ((and subtreep org-yank-folded-subtrees)
24052 (let ((beg (point))
24053 end)
24054 (if (and subtreep org-yank-adjusted-subtrees)
24055 (org-paste-subtree nil nil 'for-yank)
24056 (call-interactively command))
24058 (setq end (point))
24059 (goto-char beg)
24060 (when (and (bolp) subtreep
24061 (not (setq swallowp
24062 (org-yank-folding-would-swallow-text beg end))))
24063 (org-with-limited-levels
24064 (or (looking-at org-outline-regexp)
24065 (re-search-forward org-outline-regexp-bol end t))
24066 (while (and (< (point) end) (looking-at org-outline-regexp))
24067 (outline-hide-subtree)
24068 (org-cycle-show-empty-lines 'folded)
24069 (condition-case nil
24070 (outline-forward-same-level 1)
24071 (error (goto-char end))))))
24072 (when swallowp
24073 (message
24074 "Inserted text not folded because that would swallow text"))
24076 (goto-char end)
24077 (skip-chars-forward " \t\n\r")
24078 (beginning-of-line 1)
24079 (push-mark beg 'nomsg)))
24080 ((and subtreep org-yank-adjusted-subtrees)
24081 (let ((beg (point-at-bol)))
24082 (org-paste-subtree nil nil 'for-yank)
24083 (push-mark beg 'nomsg)))
24085 (call-interactively command))))))
24087 (defun org-yank-folding-would-swallow-text (beg end)
24088 "Would hide-subtree at BEG swallow any text after END?"
24089 (let (level)
24090 (org-with-limited-levels
24091 (save-excursion
24092 (goto-char beg)
24093 (when (or (looking-at org-outline-regexp)
24094 (re-search-forward org-outline-regexp-bol end t))
24095 (setq level (org-outline-level)))
24096 (goto-char end)
24097 (skip-chars-forward " \t\r\n\v\f")
24098 (not (or (eobp)
24099 (and (bolp) (looking-at-p org-outline-regexp)
24100 (<= (org-outline-level) level))))))))
24102 (define-key org-mode-map "\C-y" 'org-yank)
24104 (defun org-truely-invisible-p ()
24105 "Check if point is at a character currently not visible.
24106 This version does not only check the character property, but also
24107 `visible-mode'."
24108 ;; Early versions of noutline don't have `outline-invisible-p'.
24109 (unless (org-bound-and-true-p visible-mode)
24110 (outline-invisible-p)))
24112 (defun org-invisible-p2 ()
24113 "Check if point is at a character currently not visible."
24114 (save-excursion
24115 (when (and (eolp) (not (bobp))) (backward-char 1))
24116 ;; Early versions of noutline don't have `outline-invisible-p'.
24117 (outline-invisible-p)))
24119 (defun org-back-to-heading (&optional invisible-ok)
24120 "Call `outline-back-to-heading', but provide a better error message."
24121 (condition-case nil
24122 (outline-back-to-heading invisible-ok)
24123 (error (error "Before first headline at position %d in buffer %s"
24124 (point) (current-buffer)))))
24126 (defun org-before-first-heading-p ()
24127 "Before first heading?"
24128 (save-excursion
24129 (end-of-line)
24130 (null (re-search-backward org-outline-regexp-bol nil t))))
24132 (defun org-at-heading-p (&optional ignored)
24133 (outline-on-heading-p t))
24134 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24135 ;;; warning was only added in Org 9.0, which should be taken into
24136 ;;; account when deciding when to remove the alias.
24137 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24139 (defun org-in-commented-heading-p (&optional no-inheritance)
24140 "Non-nil if point is under a commented heading.
24141 This function also checks ancestors of the current headline,
24142 unless optional argument NO-INHERITANCE is non-nil."
24143 (cond
24144 ((org-before-first-heading-p) nil)
24145 ((let ((headline (nth 4 (org-heading-components))))
24146 (and headline
24147 (let ((case-fold-search nil))
24148 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24149 headline)))))
24150 (no-inheritance nil)
24152 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24154 (defun org-at-comment-p nil
24155 "Is cursor in a commented line?"
24156 (save-excursion
24157 (save-match-data
24158 (beginning-of-line)
24159 (looking-at "^[ \t]*# "))))
24161 (defun org-at-drawer-p nil
24162 "Is cursor at a drawer keyword?"
24163 (save-excursion
24164 (move-beginning-of-line 1)
24165 (looking-at org-drawer-regexp)))
24167 (defun org-at-block-p nil
24168 "Is cursor at a block keyword?"
24169 (save-excursion
24170 (move-beginning-of-line 1)
24171 (looking-at org-block-regexp)))
24173 (defun org-point-at-end-of-empty-headline ()
24174 "If point is at the end of an empty headline, return t, else nil.
24175 If the heading only contains a TODO keyword, it is still still considered
24176 empty."
24177 (and (looking-at "[ \t]*$")
24178 (when org-todo-line-regexp
24179 (save-excursion
24180 (beginning-of-line 1)
24181 (let ((case-fold-search nil))
24182 (looking-at org-todo-line-regexp)
24183 (string= (match-string 3) ""))))))
24185 (defun org-at-heading-or-item-p ()
24186 (or (org-at-heading-p) (org-at-item-p)))
24188 (defun org-at-target-p ()
24189 (or (org-in-regexp org-radio-target-regexp)
24190 (org-in-regexp org-target-regexp)))
24191 ;; Compatibility alias with Org versions < 7.8.03
24192 (defalias 'org-on-target-p 'org-at-target-p)
24194 (defun org-up-heading-all (arg)
24195 "Move to the heading line of which the present line is a subheading.
24196 This function considers both visible and invisible heading lines.
24197 With argument, move up ARG levels."
24198 (if (fboundp 'outline-up-heading-all)
24199 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24200 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24202 (defun org-up-heading-safe ()
24203 "Move to the heading line of which the present line is a subheading.
24204 This version will not throw an error. It will return the level of the
24205 headline found, or nil if no higher level is found.
24207 Also, this function will be a lot faster than `outline-up-heading',
24208 because it relies on stars being the outline starters. This can really
24209 make a significant difference in outlines with very many siblings."
24210 (when (ignore-errors (org-back-to-heading t))
24211 (let ((level-up (1- (funcall outline-level))))
24212 (and (> level-up 0)
24213 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24214 (funcall outline-level)))))
24216 (defun org-first-sibling-p ()
24217 "Is this heading the first child of its parents?"
24218 (interactive)
24219 (let ((re org-outline-regexp-bol)
24220 level l)
24221 (unless (org-at-heading-p t)
24222 (user-error "Not at a heading"))
24223 (setq level (funcall outline-level))
24224 (save-excursion
24225 (if (not (re-search-backward re nil t))
24227 (setq l (funcall outline-level))
24228 (< l level)))))
24230 (defun org-goto-sibling (&optional previous)
24231 "Goto the next sibling, even if it is invisible.
24232 When PREVIOUS is set, go to the previous sibling instead. Returns t
24233 when a sibling was found. When none is found, return nil and don't
24234 move point."
24235 (let ((fun (if previous 're-search-backward 're-search-forward))
24236 (pos (point))
24237 (re org-outline-regexp-bol)
24238 level l)
24239 (when (ignore-errors (org-back-to-heading t))
24240 (setq level (funcall outline-level))
24241 (catch 'exit
24242 (or previous (forward-char 1))
24243 (while (funcall fun re nil t)
24244 (setq l (funcall outline-level))
24245 (when (< l level) (goto-char pos) (throw 'exit nil))
24246 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24247 (goto-char pos)
24248 nil))))
24250 (defun org-show-siblings ()
24251 "Show all siblings of the current headline."
24252 (save-excursion
24253 (while (org-goto-sibling) (org-flag-heading nil)))
24254 (save-excursion
24255 (while (org-goto-sibling 'previous)
24256 (org-flag-heading nil))))
24258 (defun org-goto-first-child ()
24259 "Goto the first child, even if it is invisible.
24260 Return t when a child was found. Otherwise don't move point and
24261 return nil."
24262 (let (level (pos (point)) (re org-outline-regexp-bol))
24263 (when (ignore-errors (org-back-to-heading t))
24264 (setq level (outline-level))
24265 (forward-char 1)
24266 (if (and (re-search-forward re nil t) (> (outline-level) level))
24267 (progn (goto-char (match-beginning 0)) t)
24268 (goto-char pos) nil))))
24270 (defun org-show-hidden-entry ()
24271 "Show an entry where even the heading is hidden."
24272 (save-excursion
24273 (org-show-entry)))
24275 (defun org-flag-heading (flag &optional entry)
24276 "Flag the current heading. FLAG non-nil means make invisible.
24277 When ENTRY is non-nil, show the entire entry."
24278 (save-excursion
24279 (org-back-to-heading t)
24280 ;; Check if we should show the entire entry
24281 (if entry
24282 (progn
24283 (org-show-entry)
24284 (save-excursion
24285 (and (outline-next-heading)
24286 (org-flag-heading nil))))
24287 (outline-flag-region (max (point-min) (1- (point)))
24288 (save-excursion (outline-end-of-heading) (point))
24289 flag))))
24291 (defun org-get-next-sibling ()
24292 "Move to next heading of the same level, and return point.
24293 If there is no such heading, return nil.
24294 This is like outline-next-sibling, but invisible headings are ok."
24295 (let ((level (funcall outline-level)))
24296 (outline-next-heading)
24297 (while (and (not (eobp)) (> (funcall outline-level) level))
24298 (outline-next-heading))
24299 (unless (or (eobp) (< (funcall outline-level) level))
24300 (point))))
24302 (defun org-get-last-sibling ()
24303 "Move to previous heading of the same level, and return point.
24304 If there is no such heading, return nil."
24305 (let ((opoint (point))
24306 (level (funcall outline-level)))
24307 (outline-previous-heading)
24308 (when (and (/= (point) opoint) (outline-on-heading-p t))
24309 (while (and (> (funcall outline-level) level)
24310 (not (bobp)))
24311 (outline-previous-heading))
24312 (unless (< (funcall outline-level) level)
24313 (point)))))
24315 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24316 "Goto to the end of a subtree."
24317 ;; This contains an exact copy of the original function, but it uses
24318 ;; `org-back-to-heading', to make it work also in invisible
24319 ;; trees. And is uses an invisible-ok argument.
24320 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24321 ;; Furthermore, when used inside Org, finding the end of a large subtree
24322 ;; with many children and grandchildren etc, this can be much faster
24323 ;; than the outline version.
24324 (org-back-to-heading invisible-ok)
24325 (let ((first t)
24326 (level (funcall outline-level)))
24327 (if (and (derived-mode-p 'org-mode) (< level 1000))
24328 ;; A true heading (not a plain list item), in Org-mode
24329 ;; This means we can easily find the end by looking
24330 ;; only for the right number of stars. Using a regexp to do
24331 ;; this is so much faster than using a Lisp loop.
24332 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24333 (forward-char 1)
24334 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24335 ;; something else, do it the slow way
24336 (while (and (not (eobp))
24337 (or first (> (funcall outline-level) level)))
24338 (setq first nil)
24339 (outline-next-heading)))
24340 (unless to-heading
24341 (when (memq (preceding-char) '(?\n ?\^M))
24342 ;; Go to end of line before heading
24343 (forward-char -1)
24344 (when (memq (preceding-char) '(?\n ?\^M))
24345 ;; leave blank line before heading
24346 (forward-char -1)))))
24347 (point))
24349 (defun org-end-of-meta-data (&optional full)
24350 "Skip planning line and properties drawer in current entry.
24351 When optional argument FULL is non-nil, also skip empty lines,
24352 clocking lines and regular drawers at the beginning of the
24353 entry."
24354 (org-back-to-heading t)
24355 (forward-line)
24356 (when (org-looking-at-p org-planning-line-re) (forward-line))
24357 (when (looking-at org-property-drawer-re)
24358 (goto-char (match-end 0))
24359 (forward-line))
24360 (when (and full (not (org-at-heading-p)))
24361 (catch 'exit
24362 (let ((end (save-excursion (outline-next-heading) (point)))
24363 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24364 (while (not (eobp))
24365 (cond ((org-looking-at-p org-drawer-regexp)
24366 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24367 (forward-line)
24368 (throw 'exit t)))
24369 ((org-looking-at-p re) (forward-line))
24370 (t (throw 'exit t))))))))
24372 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24373 "Move forward to the ARG'th subheading at same level as this one.
24374 Stop at the first and last subheadings of a superior heading.
24375 Normally this only looks at visible headings, but when INVISIBLE-OK is
24376 non-nil it will also look at invisible ones."
24377 (interactive "p")
24378 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24379 (if (and arg (< arg 0))
24380 (goto-char (point-min))
24381 (outline-next-heading))
24382 (org-at-heading-p)
24383 (let ((level (- (match-end 0) (match-beginning 0) 1))
24384 (f (if (and arg (< arg 0))
24385 're-search-backward
24386 're-search-forward))
24387 (count (if arg (abs arg) 1))
24388 (result (point)))
24389 (while (and (prog1 (> count 0)
24390 (forward-char (if (and arg (< arg 0)) -1 1)))
24391 (funcall f org-outline-regexp-bol nil 'move))
24392 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24393 (cond ((< l level) (setq count 0))
24394 ((and (= l level)
24395 (or invisible-ok
24396 (progn
24397 (goto-char (line-beginning-position))
24398 (not (outline-invisible-p)))))
24399 (setq count (1- count))
24400 (when (eq l level)
24401 (setq result (point)))))))
24402 (goto-char result))
24403 (beginning-of-line 1)))
24405 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24406 "Move backward to the ARG'th subheading at same level as this one.
24407 Stop at the first and last subheadings of a superior heading."
24408 (interactive "p")
24409 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24411 (defun org-next-visible-heading (arg)
24412 "Move to the next visible heading.
24414 This function wraps `outline-next-visible-heading' with
24415 `org-with-limited-levels' in order to skip over inline tasks and
24416 respect customization of `org-odd-levels-only'."
24417 (interactive "p")
24418 (org-with-limited-levels
24419 (outline-next-visible-heading arg)))
24421 (defun org-previous-visible-heading (arg)
24422 "Move to the previous visible heading.
24424 This function wraps `outline-previous-visible-heading' with
24425 `org-with-limited-levels' in order to skip over inline tasks and
24426 respect customization of `org-odd-levels-only'."
24427 (interactive "p")
24428 (org-with-limited-levels
24429 (outline-previous-visible-heading arg)))
24431 (defun org-next-block (arg &optional backward block-regexp)
24432 "Jump to the next block.
24434 With a prefix argument ARG, jump forward ARG many blocks.
24436 When BACKWARD is non-nil, jump to the previous block.
24438 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24439 Match data is set according to this regexp when the function
24440 returns.
24442 Return point at beginning of the opening line of found block.
24443 Throw an error if no block is found."
24444 (interactive "p")
24445 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24446 (case-fold-search t)
24447 (search-fn (if backward #'re-search-backward #'re-search-forward))
24448 (count (or arg 1))
24449 (origin (point))
24450 last-element)
24451 (if backward (beginning-of-line) (end-of-line))
24452 (while (and (> count 0) (funcall search-fn re nil t))
24453 (let ((element (save-excursion
24454 (goto-char (match-beginning 0))
24455 (save-match-data (org-element-at-point)))))
24456 (when (and (memq (org-element-type element)
24457 '(center-block comment-block dynamic-block
24458 example-block export-block quote-block
24459 special-block src-block verse-block))
24460 (<= (match-beginning 0)
24461 (org-element-property :post-affiliated element)))
24462 (setq last-element element)
24463 (cl-decf count))))
24464 (if (= count 0)
24465 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24466 (save-match-data (org-show-context)))
24467 (goto-char origin)
24468 (user-error "No %s code blocks" (if backward "previous" "further")))))
24470 (defun org-previous-block (arg &optional block-regexp)
24471 "Jump to the previous block.
24472 With a prefix argument ARG, jump backward ARG many source blocks.
24473 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24474 (interactive "p")
24475 (org-next-block arg t block-regexp))
24477 (defun org-forward-paragraph ()
24478 "Move forward to beginning of next paragraph or equivalent.
24480 The function moves point to the beginning of the next visible
24481 structural element, which can be a paragraph, a table, a list
24482 item, etc. It also provides some special moves for convenience:
24484 - On an affiliated keyword, jump to the beginning of the
24485 relative element.
24486 - On an item or a footnote definition, move to the second
24487 element inside, if any.
24488 - On a table or a property drawer, jump after it.
24489 - On a verse or source block, stop after blank lines."
24490 (interactive)
24491 (when (eobp) (user-error "Cannot move further down"))
24492 (let* ((deactivate-mark nil)
24493 (element (org-element-at-point))
24494 (type (org-element-type element))
24495 (post-affiliated (org-element-property :post-affiliated element))
24496 (contents-begin (org-element-property :contents-begin element))
24497 (contents-end (org-element-property :contents-end element))
24498 (end (let ((end (org-element-property :end element)) (parent element))
24499 (while (and (setq parent (org-element-property :parent parent))
24500 (= (org-element-property :contents-end parent) end))
24501 (setq end (org-element-property :end parent)))
24502 end)))
24503 (cond ((not element)
24504 (skip-chars-forward " \r\t\n")
24505 (or (eobp) (beginning-of-line)))
24506 ;; On affiliated keywords, move to element's beginning.
24507 ((< (point) post-affiliated)
24508 (goto-char post-affiliated))
24509 ;; At a table row, move to the end of the table. Similarly,
24510 ;; at a node property, move to the end of the property
24511 ;; drawer.
24512 ((memq type '(node-property table-row))
24513 (goto-char (org-element-property
24514 :end (org-element-property :parent element))))
24515 ((memq type '(property-drawer table)) (goto-char end))
24516 ;; Consider blank lines as separators in verse and source
24517 ;; blocks to ease editing.
24518 ((memq type '(src-block verse-block))
24519 (when (eq type 'src-block)
24520 (setq contents-end
24521 (save-excursion (goto-char end)
24522 (skip-chars-backward " \r\t\n")
24523 (line-beginning-position))))
24524 (beginning-of-line)
24525 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24526 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24527 (goto-char end)
24528 (skip-chars-forward " \r\t\n")
24529 (if (= (point) contents-end) (goto-char end)
24530 (beginning-of-line))))
24531 ;; With no contents, just skip element.
24532 ((not contents-begin) (goto-char end))
24533 ;; If contents are invisible, skip the element altogether.
24534 ((outline-invisible-p (line-end-position))
24535 (cl-case type
24536 (headline
24537 (org-with-limited-levels (outline-next-visible-heading 1)))
24538 ;; At a plain list, make sure we move to the next item
24539 ;; instead of skipping the whole list.
24540 (plain-list (forward-char)
24541 (org-forward-paragraph))
24542 (otherwise (goto-char end))))
24543 ((>= (point) contents-end) (goto-char end))
24544 ((>= (point) contents-begin)
24545 ;; This can only happen on paragraphs and plain lists.
24546 (cl-case type
24547 (paragraph (goto-char end))
24548 ;; At a plain list, try to move to second element in
24549 ;; first item, if possible.
24550 (plain-list (end-of-line)
24551 (org-forward-paragraph))))
24552 ;; When contents start on the middle of a line (e.g. in
24553 ;; items and footnote definitions), try to reach first
24554 ;; element starting after current line.
24555 ((> (line-end-position) contents-begin)
24556 (end-of-line)
24557 (org-forward-paragraph))
24558 (t (goto-char contents-begin)))))
24560 (defun org-backward-paragraph ()
24561 "Move backward to start of previous paragraph or equivalent.
24563 The function moves point to the beginning of the current
24564 structural element, which can be a paragraph, a table, a list
24565 item, etc., or to the beginning of the previous visible one if
24566 point is already there. It also provides some special moves for
24567 convenience:
24569 - On an affiliated keyword, jump to the first one.
24570 - On a table or a property drawer, move to its beginning.
24571 - On a verse or source block, stop before blank lines."
24572 (interactive)
24573 (when (bobp) (user-error "Cannot move further up"))
24574 (let* ((deactivate-mark nil)
24575 (element (org-element-at-point))
24576 (type (org-element-type element))
24577 (contents-begin (org-element-property :contents-begin element))
24578 (contents-end (org-element-property :contents-end element))
24579 (post-affiliated (org-element-property :post-affiliated element))
24580 (begin (org-element-property :begin element)))
24581 (cond
24582 ((not element) (goto-char (point-min)))
24583 ((= (point) begin)
24584 (backward-char)
24585 (org-backward-paragraph))
24586 ((<= (point) post-affiliated) (goto-char begin))
24587 ((memq type '(node-property table-row))
24588 (goto-char (org-element-property
24589 :post-affiliated (org-element-property :parent element))))
24590 ((memq type '(property-drawer table)) (goto-char begin))
24591 ((memq type '(src-block verse-block))
24592 (when (eq type 'src-block)
24593 (setq contents-begin
24594 (save-excursion (goto-char begin) (forward-line) (point))))
24595 (if (= (point) contents-begin) (goto-char post-affiliated)
24596 ;; Inside a verse block, see blank lines as paragraph
24597 ;; separators.
24598 (let ((origin (point)))
24599 (skip-chars-backward " \r\t\n" contents-begin)
24600 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24601 (skip-chars-forward " \r\t\n" origin)
24602 (if (= (point) origin) (goto-char contents-begin)
24603 (beginning-of-line))))))
24604 ((not contents-begin) (goto-char (or post-affiliated begin)))
24605 ((eq type 'paragraph)
24606 (goto-char contents-begin)
24607 ;; When at first paragraph in an item or a footnote definition,
24608 ;; move directly to beginning of line.
24609 (let ((parent-contents
24610 (org-element-property
24611 :contents-begin (org-element-property :parent element))))
24612 (when (and parent-contents (= parent-contents contents-begin))
24613 (beginning-of-line))))
24614 ;; At the end of a greater element, move to the beginning of the
24615 ;; last element within.
24616 ((>= (point) contents-end)
24617 (goto-char (1- contents-end))
24618 (org-backward-paragraph))
24619 (t (goto-char (or post-affiliated begin))))
24620 ;; Ensure we never leave point invisible.
24621 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24623 (defun org-forward-element ()
24624 "Move forward by one element.
24625 Move to the next element at the same level, when possible."
24626 (interactive)
24627 (cond ((eobp) (user-error "Cannot move further down"))
24628 ((org-with-limited-levels (org-at-heading-p))
24629 (let ((origin (point)))
24630 (goto-char (org-end-of-subtree nil t))
24631 (unless (org-with-limited-levels (org-at-heading-p))
24632 (goto-char origin)
24633 (user-error "Cannot move further down"))))
24635 (let* ((elem (org-element-at-point))
24636 (end (org-element-property :end elem))
24637 (parent (org-element-property :parent elem)))
24638 (cond ((and parent (= (org-element-property :contents-end parent) end))
24639 (goto-char (org-element-property :end parent)))
24640 ((integer-or-marker-p end) (goto-char end))
24641 (t (message "No element at point")))))))
24643 (defun org-backward-element ()
24644 "Move backward by one element.
24645 Move to the previous element at the same level, when possible."
24646 (interactive)
24647 (cond ((bobp) (user-error "Cannot move further up"))
24648 ((org-with-limited-levels (org-at-heading-p))
24649 ;; At a headline, move to the previous one, if any, or stay
24650 ;; here.
24651 (let ((origin (point)))
24652 (org-with-limited-levels (org-backward-heading-same-level 1))
24653 ;; When current headline has no sibling above, move to its
24654 ;; parent.
24655 (when (= (point) origin)
24656 (or (org-with-limited-levels (org-up-heading-safe))
24657 (progn (goto-char origin)
24658 (user-error "Cannot move further up"))))))
24660 (let* ((elem (org-element-at-point))
24661 (beg (org-element-property :begin elem)))
24662 (cond
24663 ;; Move to beginning of current element if point isn't
24664 ;; there already.
24665 ((null beg) (message "No element at point"))
24666 ((/= (point) beg) (goto-char beg))
24667 (t (goto-char beg)
24668 (skip-chars-backward " \r\t\n")
24669 (unless (bobp)
24670 (let ((prev (org-element-at-point)))
24671 (goto-char (org-element-property :begin prev))
24672 (while (and (setq prev (org-element-property :parent prev))
24673 (<= (org-element-property :end prev) beg))
24674 (goto-char (org-element-property :begin prev)))))))))))
24676 (defun org-up-element ()
24677 "Move to upper element."
24678 (interactive)
24679 (if (org-with-limited-levels (org-at-heading-p))
24680 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24681 (let* ((elem (org-element-at-point))
24682 (parent (org-element-property :parent elem)))
24683 (if parent (goto-char (org-element-property :begin parent))
24684 (if (org-with-limited-levels (org-before-first-heading-p))
24685 (user-error "No surrounding element")
24686 (org-with-limited-levels (org-back-to-heading)))))))
24688 (defvar org-element-greater-elements)
24689 (defun org-down-element ()
24690 "Move to inner element."
24691 (interactive)
24692 (let ((element (org-element-at-point)))
24693 (cond
24694 ((memq (org-element-type element) '(plain-list table))
24695 (goto-char (org-element-property :contents-begin element))
24696 (forward-char))
24697 ((memq (org-element-type element) org-element-greater-elements)
24698 ;; If contents are hidden, first disclose them.
24699 (when (outline-invisible-p (line-end-position)) (org-cycle))
24700 (goto-char (or (org-element-property :contents-begin element)
24701 (user-error "No content for this element"))))
24702 (t (user-error "No inner element")))))
24704 (defun org-drag-element-backward ()
24705 "Move backward element at point."
24706 (interactive)
24707 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24708 (let* ((elem (org-element-at-point))
24709 (prev-elem
24710 (save-excursion
24711 (goto-char (org-element-property :begin elem))
24712 (skip-chars-backward " \r\t\n")
24713 (unless (bobp)
24714 (let* ((beg (org-element-property :begin elem))
24715 (prev (org-element-at-point))
24716 (up prev))
24717 (while (and (setq up (org-element-property :parent up))
24718 (<= (org-element-property :end up) beg))
24719 (setq prev up))
24720 prev)))))
24721 ;; Error out if no previous element or previous element is
24722 ;; a parent of the current one.
24723 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24724 (user-error "Cannot drag element backward")
24725 (let ((pos (point)))
24726 (org-element-swap-A-B prev-elem elem)
24727 (goto-char (+ (org-element-property :begin prev-elem)
24728 (- pos (org-element-property :begin elem)))))))))
24730 (defun org-drag-element-forward ()
24731 "Move forward element at point."
24732 (interactive)
24733 (let* ((pos (point))
24734 (elem (org-element-at-point)))
24735 (when (= (point-max) (org-element-property :end elem))
24736 (user-error "Cannot drag element forward"))
24737 (goto-char (org-element-property :end elem))
24738 (let ((next-elem (org-element-at-point)))
24739 (when (or (org-element-nested-p elem next-elem)
24740 (and (eq (org-element-type next-elem) 'headline)
24741 (not (eq (org-element-type elem) 'headline))))
24742 (goto-char pos)
24743 (user-error "Cannot drag element forward"))
24744 ;; Compute new position of point: it's shifted by NEXT-ELEM
24745 ;; body's length (without final blanks) and by the length of
24746 ;; blanks between ELEM and NEXT-ELEM.
24747 (let ((size-next (- (save-excursion
24748 (goto-char (org-element-property :end next-elem))
24749 (skip-chars-backward " \r\t\n")
24750 (forward-line)
24751 ;; Small correction if buffer doesn't end
24752 ;; with a newline character.
24753 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24754 (org-element-property :begin next-elem)))
24755 (size-blank (- (org-element-property :end elem)
24756 (save-excursion
24757 (goto-char (org-element-property :end elem))
24758 (skip-chars-backward " \r\t\n")
24759 (forward-line)
24760 (point)))))
24761 (org-element-swap-A-B elem next-elem)
24762 (goto-char (+ pos size-next size-blank))))))
24764 (defun org-drag-line-forward (arg)
24765 "Drag the line at point ARG lines forward."
24766 (interactive "p")
24767 (dotimes (_ (abs arg))
24768 (let ((c (current-column)))
24769 (if (< 0 arg)
24770 (progn
24771 (beginning-of-line 2)
24772 (transpose-lines 1)
24773 (beginning-of-line 0))
24774 (transpose-lines 1)
24775 (beginning-of-line -1))
24776 (org-move-to-column c))))
24778 (defun org-drag-line-backward (arg)
24779 "Drag the line at point ARG lines backward."
24780 (interactive "p")
24781 (org-drag-line-forward (- arg)))
24783 (defun org-mark-element ()
24784 "Put point at beginning of this element, mark at end.
24786 Interactively, if this command is repeated or (in Transient Mark
24787 mode) if the mark is active, it marks the next element after the
24788 ones already marked."
24789 (interactive)
24790 (let (deactivate-mark)
24791 (if (and (org-called-interactively-p 'any)
24792 (or (and (eq last-command this-command) (mark t))
24793 (and transient-mark-mode mark-active)))
24794 (set-mark
24795 (save-excursion
24796 (goto-char (mark))
24797 (goto-char (org-element-property :end (org-element-at-point)))))
24798 (let ((element (org-element-at-point)))
24799 (end-of-line)
24800 (push-mark (org-element-property :end element) t t)
24801 (goto-char (org-element-property :begin element))))))
24803 (defun org-narrow-to-element ()
24804 "Narrow buffer to current element."
24805 (interactive)
24806 (let ((elem (org-element-at-point)))
24807 (cond
24808 ((eq (car elem) 'headline)
24809 (narrow-to-region
24810 (org-element-property :begin elem)
24811 (org-element-property :end elem)))
24812 ((memq (car elem) org-element-greater-elements)
24813 (narrow-to-region
24814 (org-element-property :contents-begin elem)
24815 (org-element-property :contents-end elem)))
24817 (narrow-to-region
24818 (org-element-property :begin elem)
24819 (org-element-property :end elem))))))
24821 (defun org-transpose-element ()
24822 "Transpose current and previous elements, keeping blank lines between.
24823 Point is moved after both elements."
24824 (interactive)
24825 (org-skip-whitespace)
24826 (let ((end (org-element-property :end (org-element-at-point))))
24827 (org-drag-element-backward)
24828 (goto-char end)))
24830 (defun org-unindent-buffer ()
24831 "Un-indent the visible part of the buffer.
24832 Relative indentation (between items, inside blocks, etc.) isn't
24833 modified."
24834 (interactive)
24835 (unless (eq major-mode 'org-mode)
24836 (user-error "Cannot un-indent a buffer not in Org mode"))
24837 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24838 (unindent-tree
24839 (lambda (contents)
24840 (dolist (element (reverse contents))
24841 (if (memq (org-element-type element) '(headline section))
24842 (funcall unindent-tree (org-element-contents element))
24843 (save-excursion
24844 (save-restriction
24845 (narrow-to-region
24846 (org-element-property :begin element)
24847 (org-element-property :end element))
24848 (org-do-remove-indentation))))))))
24849 (funcall unindent-tree (org-element-contents parse-tree))))
24851 (defun org-show-children (&optional level)
24852 "Show all direct subheadings of this heading.
24853 Prefix arg LEVEL is how many levels below the current level
24854 should be shown. Default is enough to cause the following
24855 heading to appear."
24856 (interactive "p")
24857 ;; If `orgstruct-mode' is active, use the slower version.
24858 (if orgstruct-mode (call-interactively #'outline-show-children)
24859 (save-excursion
24860 (org-back-to-heading t)
24861 (let* ((current-level (funcall outline-level))
24862 (max-level (org-get-valid-level
24863 current-level
24864 (if level (prefix-numeric-value level) 1)))
24865 (end (save-excursion (org-end-of-subtree t t)))
24866 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24867 (past-first-child nil)
24868 ;; Make sure to skip inlinetasks.
24869 (re (format regexp-fmt
24870 current-level
24871 (cond
24872 ((not (featurep 'org-inlinetask)) "")
24873 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24875 (t (1- org-inlinetask-min-level))))))
24876 ;; Display parent heading.
24877 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24878 (forward-line)
24879 ;; Display children. First child may be deeper than expected
24880 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24881 ;; MAX-LEVEL accordingly.
24882 (while (re-search-forward re end t)
24883 (unless past-first-child
24884 (setq re (format regexp-fmt
24885 current-level
24886 (max (funcall outline-level) max-level)))
24887 (setq past-first-child t))
24888 (outline-flag-region
24889 (line-end-position 0) (line-end-position) nil))))))
24891 (defun org-show-subtree ()
24892 "Show everything after this heading at deeper levels."
24893 (interactive)
24894 (outline-flag-region
24895 (point)
24896 (save-excursion
24897 (org-end-of-subtree t t))
24898 nil))
24900 (defun org-show-entry ()
24901 "Show the body directly following this heading.
24902 Show the heading too, if it is currently invisible."
24903 (interactive)
24904 (save-excursion
24905 (ignore-errors
24906 (org-back-to-heading t)
24907 (outline-flag-region
24908 (max (point-min) (1- (point)))
24909 (save-excursion
24910 (if (re-search-forward
24911 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24912 (match-beginning 1)
24913 (point-max)))
24914 nil)
24915 (org-cycle-hide-drawers 'children))))
24917 (defun org-make-options-regexp (kwds &optional extra)
24918 "Make a regular expression for keyword lines.
24919 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24920 when non-nil, is a regexp matching keywords names."
24921 (concat "^[ \t]*#\\+\\("
24922 (regexp-opt kwds)
24923 (and extra (concat (and kwds "\\|") extra))
24924 "\\):[ \t]*\\(.*\\)"))
24926 ;;;; Integration with and fixes for other packages
24928 ;;; Imenu support
24930 (defvar-local org-imenu-markers nil
24931 "All markers currently used by Imenu.")
24933 (defun org-imenu-new-marker (&optional pos)
24934 "Return a new marker for use by Imenu, and remember the marker."
24935 (let ((m (make-marker)))
24936 (move-marker m (or pos (point)))
24937 (push m org-imenu-markers)
24940 (defun org-imenu-get-tree ()
24941 "Produce the index for Imenu."
24942 (dolist (x org-imenu-markers) (move-marker x nil))
24943 (setq org-imenu-markers nil)
24944 (let* ((n org-imenu-depth)
24945 (re (concat "^" (org-get-limited-outline-regexp)))
24946 (subs (make-vector (1+ n) nil))
24947 (last-level 0)
24948 m level head0 head)
24949 (save-excursion
24950 (save-restriction
24951 (widen)
24952 (goto-char (point-max))
24953 (while (re-search-backward re nil t)
24954 (setq level (org-reduced-level (funcall outline-level)))
24955 (when (and (<= level n)
24956 (looking-at org-complex-heading-regexp)
24957 (setq head0 (org-match-string-no-properties 4)))
24958 (setq head (org-link-display-format head0)
24959 m (org-imenu-new-marker))
24960 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24961 (if (>= level last-level)
24962 (push (cons head m) (aref subs level))
24963 (push (cons head (aref subs (1+ level))) (aref subs level))
24964 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24965 (setq last-level level)))))
24966 (aref subs 1)))
24968 (eval-after-load "imenu"
24969 '(progn
24970 (add-hook 'imenu-after-jump-hook
24971 (lambda ()
24972 (when (derived-mode-p 'org-mode)
24973 (org-show-context 'org-goto))))))
24975 (defun org-link-display-format (s)
24976 "Replace links in string S with their description.
24977 If there is no description, use the link target."
24978 (save-match-data
24979 (replace-regexp-in-string
24980 org-bracket-link-analytic-regexp
24981 (lambda (m)
24982 (if (match-end 5) (match-string 5 m)
24983 (concat (match-string 1 m) (match-string 3 m))))
24984 s nil t)))
24986 (defun org-toggle-link-display ()
24987 "Toggle the literal or descriptive display of links."
24988 (interactive)
24989 (if org-descriptive-links
24990 (progn (org-remove-from-invisibility-spec '(org-link))
24991 (org-restart-font-lock)
24992 (setq org-descriptive-links nil))
24993 (progn (add-to-invisibility-spec '(org-link))
24994 (org-restart-font-lock)
24995 (setq org-descriptive-links t))))
24997 ;; Speedbar support
24999 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25000 "Overlay marking the agenda restriction line in speedbar.")
25001 (overlay-put org-speedbar-restriction-lock-overlay
25002 'face 'org-agenda-restriction-lock)
25003 (overlay-put org-speedbar-restriction-lock-overlay
25004 'help-echo "Agendas are currently limited to this item.")
25005 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25007 (defun org-speedbar-set-agenda-restriction ()
25008 "Restrict future agenda commands to the location at point in speedbar.
25009 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25010 (interactive)
25011 (require 'org-agenda)
25012 (let (p m tp np dir txt)
25013 (cond
25014 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25015 'org-imenu t))
25016 (setq m (get-text-property p 'org-imenu-marker))
25017 (with-current-buffer (marker-buffer m)
25018 (goto-char m)
25019 (org-agenda-set-restriction-lock 'subtree)))
25020 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25021 'speedbar-function 'speedbar-find-file))
25022 (setq tp (previous-single-property-change
25023 (1+ p) 'speedbar-function)
25024 np (next-single-property-change
25025 tp 'speedbar-function)
25026 dir (speedbar-line-directory)
25027 txt (buffer-substring-no-properties (or tp (point-min))
25028 (or np (point-max))))
25029 (with-current-buffer (find-file-noselect
25030 (let ((default-directory dir))
25031 (expand-file-name txt)))
25032 (unless (derived-mode-p 'org-mode)
25033 (user-error "Cannot restrict to non-Org-mode file"))
25034 (org-agenda-set-restriction-lock 'file)))
25035 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25036 (move-overlay org-speedbar-restriction-lock-overlay
25037 (point-at-bol) (point-at-eol))
25038 (setq current-prefix-arg nil)
25039 (org-agenda-maybe-redo)))
25041 (defvar speedbar-file-key-map)
25042 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25043 (eval-after-load "speedbar"
25044 '(progn
25045 (speedbar-add-supported-extension ".org")
25046 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25047 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25048 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25049 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25050 (add-hook 'speedbar-visiting-tag-hook
25051 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25053 ;;; Fixes and Hacks for problems with other packages
25055 (defun org--flyspell-object-check-p (element)
25056 "Non-nil when Flyspell can check object at point.
25057 ELEMENT is the element at point."
25058 (let ((object (save-excursion
25059 (when (org-looking-at-p "\\>") (backward-char))
25060 (org-element-context element))))
25061 (cl-case (org-element-type object)
25062 ;; Prevent checks in links due to keybinding conflict with
25063 ;; Flyspell.
25064 ((code entity export-snippet inline-babel-call
25065 inline-src-block line-break latex-fragment link macro
25066 statistics-cookie target timestamp verbatim)
25067 nil)
25068 (footnote-reference
25069 ;; Only in inline footnotes, within the definition.
25070 (and (eq (org-element-property :type object) 'inline)
25071 (< (save-excursion
25072 (goto-char (org-element-property :begin object))
25073 (search-forward ":" nil t 2))
25074 (point))))
25075 (otherwise t))))
25077 (defun org-mode-flyspell-verify ()
25078 "Function used for `flyspell-generic-check-word-predicate'."
25079 (if (org-at-heading-p)
25080 ;; At a headline or an inlinetask, check title only. This is
25081 ;; faster than relying on `org-element-at-point'.
25082 (and (save-excursion (beginning-of-line)
25083 (and (let ((case-fold-search t))
25084 (not (looking-at "\\*+ END[ \t]*$")))
25085 (looking-at org-complex-heading-regexp)))
25086 (match-beginning 4)
25087 (>= (point) (match-beginning 4))
25088 (or (not (match-beginning 5))
25089 (< (point) (match-beginning 5))))
25090 (let* ((element (org-element-at-point))
25091 (post-affiliated (org-element-property :post-affiliated element)))
25092 (cond
25093 ;; Ignore checks in all affiliated keywords but captions.
25094 ((< (point) post-affiliated)
25095 (and (save-excursion
25096 (beginning-of-line)
25097 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25098 (> (point) (match-end 0))
25099 (org--flyspell-object-check-p element)))
25100 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25101 ((let ((log (org-log-into-drawer)))
25102 (and log
25103 (let ((drawer (org-element-lineage element '(drawer))))
25104 (and drawer
25105 (eq (compare-strings
25106 log nil nil
25107 (org-element-property :drawer-name drawer) nil nil t)
25108 t)))))
25109 nil)
25111 (cl-case (org-element-type element)
25112 ((comment quote-section) t)
25113 (comment-block
25114 ;; Allow checks between block markers, not on them.
25115 (and (> (line-beginning-position) post-affiliated)
25116 (save-excursion
25117 (end-of-line)
25118 (skip-chars-forward " \r\t\n")
25119 (< (point) (org-element-property :end element)))))
25120 ;; Arbitrary list of keywords where checks are meaningful.
25121 ;; Make sure point is on the value part of the element.
25122 (keyword
25123 (and (member (org-element-property :key element)
25124 '("DESCRIPTION" "TITLE"))
25125 (save-excursion
25126 (search-backward ":" (line-beginning-position) t))))
25127 ;; Check is globally allowed in paragraphs verse blocks and
25128 ;; table rows (after affiliated keywords) but some objects
25129 ;; must not be affected.
25130 ((paragraph table-row verse-block)
25131 (let ((cbeg (org-element-property :contents-begin element))
25132 (cend (org-element-property :contents-end element)))
25133 (and cbeg (>= (point) cbeg) (< (point) cend)
25134 (org--flyspell-object-check-p element))))))))))
25135 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25137 (defun org-remove-flyspell-overlays-in (beg end)
25138 "Remove flyspell overlays in region."
25139 (and (org-bound-and-true-p flyspell-mode)
25140 (fboundp 'flyspell-delete-region-overlays)
25141 (flyspell-delete-region-overlays beg end)))
25143 (defvar flyspell-delayed-commands)
25144 (eval-after-load "flyspell"
25145 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25147 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25148 (eval-after-load "bookmark"
25149 '(if (boundp 'bookmark-after-jump-hook)
25150 ;; We can use the hook
25151 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25152 ;; Hook not available, use advice
25153 (defadvice bookmark-jump (after org-make-visible activate)
25154 "Make the position visible."
25155 (org-bookmark-jump-unhide))))
25157 ;; Make sure saveplace shows the location if it was hidden
25158 (eval-after-load "saveplace"
25159 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25160 "Make the position visible."
25161 (org-bookmark-jump-unhide)))
25163 ;; Make sure ecb shows the location if it was hidden
25164 (eval-after-load "ecb"
25165 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25166 "Make hierarchy visible when jumping into location from ECB tree buffer."
25167 (when (derived-mode-p 'org-mode)
25168 (org-show-context))))
25170 (defun org-bookmark-jump-unhide ()
25171 "Unhide the current position, to show the bookmark location."
25172 (and (derived-mode-p 'org-mode)
25173 (or (outline-invisible-p)
25174 (save-excursion (goto-char (max (point-min) (1- (point))))
25175 (outline-invisible-p)))
25176 (org-show-context 'bookmark-jump)))
25178 (defun org-mark-jump-unhide ()
25179 "Make the point visible with `org-show-context' after jumping to the mark."
25180 (when (and (derived-mode-p 'org-mode)
25181 (outline-invisible-p))
25182 (org-show-context 'mark-goto)))
25184 (eval-after-load "simple"
25185 '(defadvice pop-to-mark-command (after org-make-visible activate)
25186 "Make the point visible with `org-show-context'."
25187 (org-mark-jump-unhide)))
25189 (eval-after-load "simple"
25190 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25191 "Make the point visible with `org-show-context'."
25192 (org-mark-jump-unhide)))
25194 (eval-after-load "simple"
25195 '(defadvice pop-global-mark (after org-make-visible activate)
25196 "Make the point visible with `org-show-context'."
25197 (org-mark-jump-unhide)))
25199 ;; Make session.el ignore our circular variable
25200 (defvar session-globals-exclude)
25201 (eval-after-load "session"
25202 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25204 ;;;; Finish up
25206 (provide 'org)
25208 (run-hooks 'org-load-hook)
25210 ;;; org.el ends here