Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob1f06cbdb5215f77f0020329323cbef5e8f70cd20
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)
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 "24.4"
783 :package-version '(Org . "8.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-not-done-keywords nil)
2585 (defvar-local org-done-keywords nil)
2586 (defvar-local org-todo-heads nil)
2587 (defvar-local org-todo-sets nil)
2588 (defvar-local org-todo-log-states nil)
2589 (defvar-local org-todo-kwd-alist nil)
2590 (defvar-local org-todo-key-alist nil)
2591 (defvar-local org-todo-key-trigger nil)
2593 (defcustom org-todo-interpretation 'sequence
2594 "Controls how TODO keywords are interpreted.
2595 This variable is in principle obsolete and is only used for
2596 backward compatibility, if the interpretation of todo keywords is
2597 not given already in `org-todo-keywords'. See that variable for
2598 more information."
2599 :group 'org-todo
2600 :group 'org-keywords
2601 :type '(choice (const sequence)
2602 (const type)))
2604 (defcustom org-use-fast-todo-selection t
2605 "\\<org-mode-map>\
2606 Non-nil means use the fast todo selection scheme with \\[org-todo].
2607 This variable describes if and under what circumstances the cycling
2608 mechanism for TODO keywords will be replaced by a single-key, direct
2609 selection scheme.
2611 When nil, fast selection is never used.
2613 When the symbol `prefix', it will be used when `org-todo' is called
2614 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2615 in an Org-mode buffer, and
2616 `\\[universal-argument] t' in an agenda buffer.
2618 When t, fast selection is used by default. In this case, the prefix
2619 argument forces cycling instead.
2621 In all cases, the special interface is only used if access keys have
2622 actually been assigned by the user, i.e. if keywords in the configuration
2623 are followed by a letter in parenthesis, like TODO(t)."
2624 :group 'org-todo
2625 :type '(choice
2626 (const :tag "Never" nil)
2627 (const :tag "By default" t)
2628 (const :tag "Only with C-u C-c C-t" prefix)))
2630 (defcustom org-provide-todo-statistics t
2631 "Non-nil means update todo statistics after insert and toggle.
2632 ALL-HEADLINES means update todo statistics by including headlines
2633 with no TODO keyword as well, counting them as not done.
2634 A list of TODO keywords means the same, but skip keywords that are
2635 not in this list.
2636 When set to a list of two lists, the first list contains keywords
2637 to consider as TODO keywords, the second list contains keywords
2638 to consider as DONE keywords.
2640 When this is set, todo statistics is updated in the parent of the
2641 current entry each time a todo state is changed."
2642 :group 'org-todo
2643 :type '(choice
2644 (const :tag "Yes, only for TODO entries" t)
2645 (const :tag "Yes, including all entries" all-headlines)
2646 (repeat :tag "Yes, for TODOs in this list"
2647 (string :tag "TODO keyword"))
2648 (list :tag "Yes, for TODOs and DONEs in these lists"
2649 (repeat (string :tag "TODO keyword"))
2650 (repeat (string :tag "DONE keyword")))
2651 (other :tag "No TODO statistics" nil)))
2653 (defcustom org-hierarchical-todo-statistics t
2654 "Non-nil means TODO statistics covers just direct children.
2655 When nil, all entries in the subtree are considered.
2656 This has only an effect if `org-provide-todo-statistics' is set.
2657 To set this to nil for only a single subtree, use a COOKIE_DATA
2658 property and include the word \"recursive\" into the value."
2659 :group 'org-todo
2660 :type 'boolean)
2662 (defcustom org-after-todo-state-change-hook nil
2663 "Hook which is run after the state of a TODO item was changed.
2664 The new state (a string with a TODO keyword, or nil) is available in the
2665 Lisp variable `org-state'."
2666 :group 'org-todo
2667 :type 'hook)
2669 (defvar org-blocker-hook nil
2670 "Hook for functions that are allowed to block a state change.
2672 Functions in this hook should not modify the buffer.
2673 Each function gets as its single argument a property list,
2674 see `org-trigger-hook' for more information about this list.
2676 If any of the functions in this hook returns nil, the state change
2677 is blocked.")
2679 (defvar org-trigger-hook nil
2680 "Hook for functions that are triggered by a state change.
2682 Each function gets as its single argument a property list with at
2683 least the following elements:
2685 (:type type-of-change :position pos-at-entry-start
2686 :from old-state :to new-state)
2688 Depending on the type, more properties may be present.
2690 This mechanism is currently implemented for:
2692 TODO state changes
2693 ------------------
2694 :type todo-state-change
2695 :from previous state (keyword as a string), or nil, or a symbol
2696 `todo' or `done', to indicate the general type of state.
2697 :to new state, like in :from")
2699 (defcustom org-enforce-todo-dependencies nil
2700 "Non-nil means undone TODO entries will block switching the parent to DONE.
2701 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2702 be blocked if any prior sibling is not yet done.
2703 Finally, if the parent is blocked because of ordered siblings of its own,
2704 the child will also be blocked."
2705 :set (lambda (var val)
2706 (set var val)
2707 (if val
2708 (add-hook 'org-blocker-hook
2709 'org-block-todo-from-children-or-siblings-or-parent)
2710 (remove-hook 'org-blocker-hook
2711 'org-block-todo-from-children-or-siblings-or-parent)))
2712 :group 'org-todo
2713 :type 'boolean)
2715 (defcustom org-enforce-todo-checkbox-dependencies nil
2716 "Non-nil means unchecked boxes will block switching the parent to DONE.
2717 When this is nil, checkboxes have no influence on switching TODO states.
2718 When non-nil, you first need to check off all check boxes before the TODO
2719 entry can be switched to DONE.
2720 This variable needs to be set before org.el is loaded, and you need to
2721 restart Emacs after a change to make the change effective. The only way
2722 to change is while Emacs is running is through the customize interface."
2723 :set (lambda (var val)
2724 (set var val)
2725 (if val
2726 (add-hook 'org-blocker-hook
2727 'org-block-todo-from-checkboxes)
2728 (remove-hook 'org-blocker-hook
2729 'org-block-todo-from-checkboxes)))
2730 :group 'org-todo
2731 :type 'boolean)
2733 (defcustom org-treat-insert-todo-heading-as-state-change nil
2734 "Non-nil means inserting a TODO heading is treated as state change.
2735 So when the command \\[org-insert-todo-heading] is used, state change
2736 logging will apply if appropriate. When nil, the new TODO item will
2737 be inserted directly, and no logging will take place."
2738 :group 'org-todo
2739 :type 'boolean)
2741 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2742 "Non-nil means switching TODO states with S-cursor counts as state change.
2743 This is the default behavior. However, setting this to nil allows a
2744 convenient way to select a TODO state and bypass any logging associated
2745 with that."
2746 :group 'org-todo
2747 :type 'boolean)
2749 (defcustom org-todo-state-tags-triggers nil
2750 "Tag changes that should be triggered by TODO state changes.
2751 This is a list. Each entry is
2753 (state-change (tag . flag) .......)
2755 State-change can be a string with a state, and empty string to indicate the
2756 state that has no TODO keyword, or it can be one of the symbols `todo'
2757 or `done', meaning any not-done or done state, respectively."
2758 :group 'org-todo
2759 :group 'org-tags
2760 :type '(repeat
2761 (cons (choice :tag "When changing to"
2762 (const :tag "Not-done state" todo)
2763 (const :tag "Done state" done)
2764 (string :tag "State"))
2765 (repeat
2766 (cons :tag "Tag action"
2767 (string :tag "Tag")
2768 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2770 (defcustom org-log-done nil
2771 "Information to record when a task moves to the DONE state.
2773 Possible values are:
2775 nil Don't add anything, just change the keyword
2776 time Add a time stamp to the task
2777 note Prompt for a note and add it with template `org-log-note-headings'
2779 This option can also be set with on a per-file-basis with
2781 #+STARTUP: nologdone
2782 #+STARTUP: logdone
2783 #+STARTUP: lognotedone
2785 You can have local logging settings for a subtree by setting the LOGGING
2786 property to one or more of these keywords."
2787 :group 'org-todo
2788 :group 'org-progress
2789 :type '(choice
2790 (const :tag "No logging" nil)
2791 (const :tag "Record CLOSED timestamp" time)
2792 (const :tag "Record CLOSED timestamp with note." note)))
2794 ;; Normalize old uses of org-log-done.
2795 (cond
2796 ((eq org-log-done t) (setq org-log-done 'time))
2797 ((and (listp org-log-done) (memq 'done org-log-done))
2798 (setq org-log-done 'note)))
2800 (defcustom org-log-reschedule nil
2801 "Information to record when the scheduling date of a tasks is modified.
2803 Possible values are:
2805 nil Don't add anything, just change the date
2806 time Add a time stamp to the task
2807 note Prompt for a note and add it with template `org-log-note-headings'
2809 This option can also be set with on a per-file-basis with
2811 #+STARTUP: nologreschedule
2812 #+STARTUP: logreschedule
2813 #+STARTUP: lognotereschedule"
2814 :group 'org-todo
2815 :group 'org-progress
2816 :type '(choice
2817 (const :tag "No logging" nil)
2818 (const :tag "Record timestamp" time)
2819 (const :tag "Record timestamp with note." note)))
2821 (defcustom org-log-redeadline nil
2822 "Information to record when the deadline date of a tasks is modified.
2824 Possible values are:
2826 nil Don't add anything, just change the date
2827 time Add a time stamp to the task
2828 note Prompt for a note and add it with template `org-log-note-headings'
2830 This option can also be set with on a per-file-basis with
2832 #+STARTUP: nologredeadline
2833 #+STARTUP: logredeadline
2834 #+STARTUP: lognoteredeadline
2836 You can have local logging settings for a subtree by setting the LOGGING
2837 property to one or more of these keywords."
2838 :group 'org-todo
2839 :group 'org-progress
2840 :type '(choice
2841 (const :tag "No logging" nil)
2842 (const :tag "Record timestamp" time)
2843 (const :tag "Record timestamp with note." note)))
2845 (defcustom org-log-note-clock-out nil
2846 "Non-nil means record a note when clocking out of an item.
2847 This can also be configured on a per-file basis by adding one of
2848 the following lines anywhere in the buffer:
2850 #+STARTUP: lognoteclock-out
2851 #+STARTUP: nolognoteclock-out"
2852 :group 'org-todo
2853 :group 'org-progress
2854 :type 'boolean)
2856 (defcustom org-log-done-with-time t
2857 "Non-nil means the CLOSED time stamp will contain date and time.
2858 When nil, only the date will be recorded."
2859 :group 'org-progress
2860 :type 'boolean)
2862 (defcustom org-log-note-headings
2863 '((done . "CLOSING NOTE %t")
2864 (state . "State %-12s from %-12S %t")
2865 (note . "Note taken on %t")
2866 (reschedule . "Rescheduled from %S on %t")
2867 (delschedule . "Not scheduled, was %S on %t")
2868 (redeadline . "New deadline from %S on %t")
2869 (deldeadline . "Removed deadline, was %S on %t")
2870 (refile . "Refiled on %t")
2871 (clock-out . ""))
2872 "Headings for notes added to entries.
2874 The value is an alist, with the car being a symbol indicating the
2875 note context, and the cdr is the heading to be used. The heading
2876 may also be the empty string. The following placeholders can be
2877 used:
2879 %t a time stamp.
2880 %T an active time stamp instead the default inactive one
2881 %d a short-format time stamp.
2882 %D an active short-format time stamp.
2883 %s the new TODO state or time stamp (inactive), in double quotes.
2884 %S the old TODO state or time stamp (inactive), in double quotes.
2885 %u the user name.
2886 %U full user name.
2888 In fact, it is not a good idea to change the `state' entry,
2889 because Agenda Log mode depends on the format of these entries."
2890 :group 'org-todo
2891 :group 'org-progress
2892 :type '(list :greedy t
2893 (cons (const :tag "Heading when closing an item" done) string)
2894 (cons (const :tag
2895 "Heading when changing todo state (todo sequence only)"
2896 state) string)
2897 (cons (const :tag "Heading when just taking a note" note) string)
2898 (cons (const :tag "Heading when rescheduling" reschedule) string)
2899 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2900 (cons (const :tag "Heading when changing deadline" redeadline) string)
2901 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2902 (cons (const :tag "Heading when refiling" refile) string)
2903 (cons (const :tag "Heading when clocking out" clock-out) string)))
2905 (unless (assq 'note org-log-note-headings)
2906 (push '(note . "%t") org-log-note-headings))
2908 (defcustom org-log-into-drawer nil
2909 "Non-nil means insert state change notes and time stamps into a drawer.
2910 When nil, state changes notes will be inserted after the headline and
2911 any scheduling and clock lines, but not inside a drawer.
2913 The value of this variable should be the name of the drawer to use.
2914 LOGBOOK is proposed as the default drawer for this purpose, you can
2915 also set this to a string to define the drawer of your choice.
2917 A value of t is also allowed, representing \"LOGBOOK\".
2919 A value of t or nil can also be set with on a per-file-basis with
2921 #+STARTUP: logdrawer
2922 #+STARTUP: nologdrawer
2924 If this variable is set, `org-log-state-notes-insert-after-drawers'
2925 will be ignored.
2927 You can set the property LOG_INTO_DRAWER to overrule this setting for
2928 a subtree.
2930 Do not check directly this variable in a Lisp program. Call
2931 function `org-log-into-drawer' instead."
2932 :group 'org-todo
2933 :group 'org-progress
2934 :type '(choice
2935 (const :tag "Not into a drawer" nil)
2936 (const :tag "LOGBOOK" t)
2937 (string :tag "Other")))
2939 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2941 (defun org-log-into-drawer ()
2942 "Name of the log drawer, as a string, or nil.
2943 This is the value of `org-log-into-drawer'. However, if the
2944 current entry has or inherits a LOG_INTO_DRAWER property, it will
2945 be used instead of the default value."
2946 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2947 (cond ((equal p "nil") nil)
2948 ((equal p "t") "LOGBOOK")
2949 ((stringp p) p)
2950 (p "LOGBOOK")
2951 ((stringp org-log-into-drawer) org-log-into-drawer)
2952 (org-log-into-drawer "LOGBOOK"))))
2954 (defcustom org-log-state-notes-insert-after-drawers nil
2955 "Non-nil means insert state change notes after any drawers in entry.
2956 Only the drawers that *immediately* follow the headline and the
2957 deadline/scheduled line are skipped.
2958 When nil, insert notes right after the heading and perhaps the line
2959 with deadline/scheduling if present.
2961 This variable will have no effect if `org-log-into-drawer' is
2962 set."
2963 :group 'org-todo
2964 :group 'org-progress
2965 :type 'boolean)
2967 (defcustom org-log-states-order-reversed t
2968 "Non-nil means the latest state note will be directly after heading.
2969 When nil, the state change notes will be ordered according to time.
2971 This option can also be set with on a per-file-basis with
2973 #+STARTUP: logstatesreversed
2974 #+STARTUP: nologstatesreversed"
2975 :group 'org-todo
2976 :group 'org-progress
2977 :type 'boolean)
2979 (defcustom org-todo-repeat-to-state nil
2980 "The TODO state to which a repeater should return the repeating task.
2981 By default this is the first task in a TODO sequence, or the previous state
2982 in a TODO_TYP set. But you can specify another task here.
2983 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2984 :group 'org-todo
2985 :version "24.1"
2986 :type '(choice (const :tag "Head of sequence" nil)
2987 (string :tag "Specific state")))
2989 (defcustom org-log-repeat 'time
2990 "Non-nil means record moving through the DONE state when triggering repeat.
2991 An auto-repeating task is immediately switched back to TODO when
2992 marked DONE. If you are not logging state changes (by adding \"@\"
2993 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2994 record a closing note, there will be no record of the task moving
2995 through DONE. This variable forces taking a note anyway.
2997 nil Don't force a record
2998 time Record a time stamp
2999 note Prompt for a note and add it with template `org-log-note-headings'
3001 This option can also be set with on a per-file-basis with
3003 #+STARTUP: nologrepeat
3004 #+STARTUP: logrepeat
3005 #+STARTUP: lognoterepeat
3007 You can have local logging settings for a subtree by setting the LOGGING
3008 property to one or more of these keywords."
3009 :group 'org-todo
3010 :group 'org-progress
3011 :type '(choice
3012 (const :tag "Don't force a record" nil)
3013 (const :tag "Force recording the DONE state" time)
3014 (const :tag "Force recording a note with the DONE state" note)))
3017 (defgroup org-priorities nil
3018 "Priorities in Org-mode."
3019 :tag "Org Priorities"
3020 :group 'org-todo)
3022 (defcustom org-enable-priority-commands t
3023 "Non-nil means priority commands are active.
3024 When nil, these commands will be disabled, so that you never accidentally
3025 set a priority."
3026 :group 'org-priorities
3027 :type 'boolean)
3029 (defcustom org-highest-priority ?A
3030 "The highest priority of TODO items. A character like ?A, ?B etc.
3031 Must have a smaller ASCII number than `org-lowest-priority'."
3032 :group 'org-priorities
3033 :type 'character)
3035 (defcustom org-lowest-priority ?C
3036 "The lowest priority of TODO items. A character like ?A, ?B etc.
3037 Must have a larger ASCII number than `org-highest-priority'."
3038 :group 'org-priorities
3039 :type 'character)
3041 (defcustom org-default-priority ?B
3042 "The default priority of TODO items.
3043 This is the priority an item gets if no explicit priority is given.
3044 When starting to cycle on an empty priority the first step in the cycle
3045 depends on `org-priority-start-cycle-with-default'. The resulting first
3046 step priority must not exceed the range from `org-highest-priority' to
3047 `org-lowest-priority' which means that `org-default-priority' has to be
3048 in this range exclusive or inclusive the range boundaries. Else the
3049 first step refuses to set the default and the second will fall back
3050 to (depending on the command used) the highest or lowest priority."
3051 :group 'org-priorities
3052 :type 'character)
3054 (defcustom org-priority-start-cycle-with-default t
3055 "Non-nil means start with default priority when starting to cycle.
3056 When this is nil, the first step in the cycle will be (depending on the
3057 command used) one higher or lower than the default priority.
3058 See also `org-default-priority'."
3059 :group 'org-priorities
3060 :type 'boolean)
3062 (defcustom org-get-priority-function nil
3063 "Function to extract the priority from a string.
3064 The string is normally the headline. If this is nil Org computes the
3065 priority from the priority cookie like [#A] in the headline. It returns
3066 an integer, increasing by 1000 for each priority level.
3067 The user can set a different function here, which should take a string
3068 as an argument and return the numeric priority."
3069 :group 'org-priorities
3070 :version "24.1"
3071 :type '(choice
3072 (const nil)
3073 (function)))
3075 (defgroup org-time nil
3076 "Options concerning time stamps and deadlines in Org-mode."
3077 :tag "Org Time"
3078 :group 'org)
3080 (defcustom org-time-stamp-rounding-minutes '(0 5)
3081 "Number of minutes to round time stamps to.
3082 \\<org-mode-map>\
3083 These are two values, the first applies when first creating a time stamp.
3084 The second applies when changing it with the commands `S-up' and `S-down'.
3085 When changing the time stamp, this means that it will change in steps
3086 of N minutes, as given by the second value.
3088 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3089 numbers should be factors of 60, so for example 5, 10, 15.
3091 When this is larger than 1, you can still force an exact time stamp by using
3092 a double prefix argument to a time stamp command like \
3093 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3094 and by using a prefix arg to `S-up/down' to specify the exact number
3095 of minutes to shift."
3096 :group 'org-time
3097 :get (lambda (var) ; Make sure both elements are there
3098 (if (integerp (default-value var))
3099 (list (default-value var) 5)
3100 (default-value var)))
3101 :type '(list
3102 (integer :tag "when inserting times")
3103 (integer :tag "when modifying times")))
3105 ;; Normalize old customizations of this variable.
3106 (when (integerp org-time-stamp-rounding-minutes)
3107 (setq org-time-stamp-rounding-minutes
3108 (list org-time-stamp-rounding-minutes
3109 org-time-stamp-rounding-minutes)))
3111 (defcustom org-display-custom-times nil
3112 "Non-nil means overlay custom formats over all time stamps.
3113 The formats are defined through the variable `org-time-stamp-custom-formats'.
3114 To turn this on on a per-file basis, insert anywhere in the file:
3115 #+STARTUP: customtime"
3116 :group 'org-time
3117 :set 'set-default
3118 :type 'sexp)
3119 (make-variable-buffer-local 'org-display-custom-times)
3121 (defcustom org-time-stamp-custom-formats
3122 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3123 "Custom formats for time stamps. See `format-time-string' for the syntax.
3124 These are overlaid over the default ISO format if the variable
3125 `org-display-custom-times' is set. Time like %H:%M should be at the
3126 end of the second format. The custom formats are also honored by export
3127 commands, if custom time display is turned on at the time of export."
3128 :group 'org-time
3129 :type 'sexp)
3131 (defun org-time-stamp-format (&optional long inactive)
3132 "Get the right format for a time string."
3133 (let ((f (if long (cdr org-time-stamp-formats)
3134 (car org-time-stamp-formats))))
3135 (if inactive
3136 (concat "[" (substring f 1 -1) "]")
3137 f)))
3139 (defcustom org-time-clocksum-format
3140 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3141 "The format string used when creating CLOCKSUM lines.
3142 This is also used when Org mode generates a time duration.
3144 The value can be a single format string containing two
3145 %-sequences, which will be filled with the number of hours and
3146 minutes in that order.
3148 Alternatively, the value can be a plist associating any of the
3149 keys :years, :months, :weeks, :days, :hours or :minutes with
3150 format strings. The time duration is formatted using only the
3151 time components that are needed and concatenating the results.
3152 If a time unit in absent, it falls back to the next smallest
3153 unit.
3155 The keys :require-years, :require-months, :require-days,
3156 :require-weeks, :require-hours, :require-minutes are also
3157 meaningful. A non-nil value for these keys indicates that the
3158 corresponding time component should always be included, even if
3159 its value is 0.
3162 For example,
3164 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3165 :require-minutes t)
3167 means durations longer than a day will be expressed in days,
3168 hours and minutes, and durations less than a day will always be
3169 expressed in hours and minutes (even for durations less than an
3170 hour).
3172 The value
3174 (:days \"%dd\" :minutes \"%dm\")
3176 means durations longer than a day will be expressed in days and
3177 minutes, and durations less than a day will be expressed entirely
3178 in minutes (even for durations longer than an hour)."
3179 :group 'org-time
3180 :group 'org-clock
3181 :version "24.4"
3182 :package-version '(Org . "8.0")
3183 :type '(choice (string :tag "Format string")
3184 (set :tag "Plist"
3185 (group :inline t (const :tag "Years" :years)
3186 (string :tag "Format string"))
3187 (group :inline t
3188 (const :tag "Always show years" :require-years)
3189 (const t))
3190 (group :inline t (const :tag "Months" :months)
3191 (string :tag "Format string"))
3192 (group :inline t
3193 (const :tag "Always show months" :require-months)
3194 (const t))
3195 (group :inline t (const :tag "Weeks" :weeks)
3196 (string :tag "Format string"))
3197 (group :inline t
3198 (const :tag "Always show weeks" :require-weeks)
3199 (const t))
3200 (group :inline t (const :tag "Days" :days)
3201 (string :tag "Format string"))
3202 (group :inline t
3203 (const :tag "Always show days" :require-days)
3204 (const t))
3205 (group :inline t (const :tag "Hours" :hours)
3206 (string :tag "Format string"))
3207 (group :inline t
3208 (const :tag "Always show hours" :require-hours)
3209 (const t))
3210 (group :inline t (const :tag "Minutes" :minutes)
3211 (string :tag "Format string"))
3212 (group :inline t
3213 (const :tag "Always show minutes" :require-minutes)
3214 (const t)))))
3216 (defcustom org-time-clocksum-use-fractional nil
3217 "When non-nil, \\[org-clock-display] uses fractional times.
3218 See `org-time-clocksum-format' for more on time clock formats."
3219 :group 'org-time
3220 :group 'org-clock
3221 :version "24.3"
3222 :type 'boolean)
3224 (defcustom org-time-clocksum-use-effort-durations nil
3225 "When non-nil, \\[org-clock-display] uses effort durations.
3226 E.g. by default, one day is considered to be a 8 hours effort,
3227 so a task that has been clocked for 16 hours will be displayed
3228 as during 2 days in the clock display or in the clocktable.
3230 See `org-effort-durations' on how to set effort durations
3231 and `org-time-clocksum-format' for more on time clock formats."
3232 :group 'org-time
3233 :group 'org-clock
3234 :version "24.4"
3235 :package-version '(Org . "8.0")
3236 :type 'boolean)
3238 (defcustom org-time-clocksum-fractional-format "%.2f"
3239 "The format string used when creating CLOCKSUM lines,
3240 or when Org mode generates a time duration, if
3241 `org-time-clocksum-use-fractional' is enabled.
3243 The value can be a single format string containing one
3244 %-sequence, which will be filled with the number of hours as
3245 a float.
3247 Alternatively, the value can be a plist associating any of the
3248 keys :years, :months, :weeks, :days, :hours or :minutes with
3249 a format string. The time duration is formatted using the
3250 largest time unit which gives a non-zero integer part. If all
3251 specified formats have zero integer part, the smallest time unit
3252 is used."
3253 :group 'org-time
3254 :type '(choice (string :tag "Format string")
3255 (set (group :inline t (const :tag "Years" :years)
3256 (string :tag "Format string"))
3257 (group :inline t (const :tag "Months" :months)
3258 (string :tag "Format string"))
3259 (group :inline t (const :tag "Weeks" :weeks)
3260 (string :tag "Format string"))
3261 (group :inline t (const :tag "Days" :days)
3262 (string :tag "Format string"))
3263 (group :inline t (const :tag "Hours" :hours)
3264 (string :tag "Format string"))
3265 (group :inline t (const :tag "Minutes" :minutes)
3266 (string :tag "Format string")))))
3268 (defcustom org-deadline-warning-days 14
3269 "Number of days before expiration during which a deadline becomes active.
3270 This variable governs the display in sparse trees and in the agenda.
3271 When 0 or negative, it means use this number (the absolute value of it)
3272 even if a deadline has a different individual lead time specified.
3274 Custom commands can set this variable in the options section."
3275 :group 'org-time
3276 :group 'org-agenda-daily/weekly
3277 :type 'integer)
3279 (defcustom org-scheduled-delay-days 0
3280 "Number of days before a scheduled item becomes active.
3281 This variable governs the display in sparse trees and in the agenda.
3282 The default value (i.e. 0) means: don't delay scheduled item.
3283 When negative, it means use this number (the absolute value of it)
3284 even if a scheduled item has a different individual delay time
3285 specified.
3287 Custom commands can set this variable in the options section."
3288 :group 'org-time
3289 :group 'org-agenda-daily/weekly
3290 :version "24.4"
3291 :package-version '(Org . "8.0")
3292 :type 'integer)
3294 (defcustom org-read-date-prefer-future t
3295 "Non-nil means assume future for incomplete date input from user.
3296 This affects the following situations:
3297 1. The user gives a month but not a year.
3298 For example, if it is April and you enter \"feb 2\", this will be read
3299 as Feb 2, *next* year. \"May 5\", however, will be this year.
3300 2. The user gives a day, but no month.
3301 For example, if today is the 15th, and you enter \"3\", Org-mode will
3302 read this as the third of *next* month. However, if you enter \"17\",
3303 it will be considered as *this* month.
3305 If you set this variable to the symbol `time', then also the following
3306 will work:
3308 3. If the user gives a time.
3309 If the time is before now, it will be interpreted as tomorrow.
3311 Currently none of this works for ISO week specifications.
3313 When this option is nil, the current day, month and year will always be
3314 used as defaults.
3316 See also `org-agenda-jump-prefer-future'."
3317 :group 'org-time
3318 :type '(choice
3319 (const :tag "Never" nil)
3320 (const :tag "Check month and day" t)
3321 (const :tag "Check month, day, and time" time)))
3323 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3324 "Should the agenda jump command prefer the future for incomplete dates?
3325 The default is to do the same as configured in `org-read-date-prefer-future'.
3326 But you can also set a deviating value here.
3327 This may t or nil, or the symbol `org-read-date-prefer-future'."
3328 :group 'org-agenda
3329 :group 'org-time
3330 :version "24.1"
3331 :type '(choice
3332 (const :tag "Use org-read-date-prefer-future"
3333 org-read-date-prefer-future)
3334 (const :tag "Never" nil)
3335 (const :tag "Always" t)))
3337 (defcustom org-read-date-force-compatible-dates t
3338 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3340 Depending on the system Emacs is running on, certain dates cannot
3341 be represented with the type used internally to represent time.
3342 Dates between 1970-1-1 and 2038-1-1 can always be represented
3343 correctly. Some systems allow for earlier dates, some for later,
3344 some for both. One way to find out it to insert any date into an
3345 Org buffer, putting the cursor on the year and hitting S-up and
3346 S-down to test the range.
3348 When this variable is set to t, the date/time prompt will not let
3349 you specify dates outside the 1970-2037 range, so it is certain that
3350 these dates will work in whatever version of Emacs you are
3351 running, and also that you can move a file from one Emacs implementation
3352 to another. WHenever Org is forcing the year for you, it will display
3353 a message and beep.
3355 When this variable is nil, Org will check if the date is
3356 representable in the specific Emacs implementation you are using.
3357 If not, it will force a year, usually the current year, and beep
3358 to remind you. Currently this setting is not recommended because
3359 the likelihood that you will open your Org files in an Emacs that
3360 has limited date range is not negligible.
3362 A workaround for this problem is to use diary sexp dates for time
3363 stamps outside of this range."
3364 :group 'org-time
3365 :version "24.1"
3366 :type 'boolean)
3368 (defcustom org-read-date-display-live t
3369 "Non-nil means display current interpretation of date prompt live.
3370 This display will be in an overlay, in the minibuffer."
3371 :group 'org-time
3372 :type 'boolean)
3374 (defcustom org-read-date-popup-calendar t
3375 "Non-nil means pop up a calendar when prompting for a date.
3376 In the calendar, the date can be selected with mouse-1. However, the
3377 minibuffer will also be active, and you can simply enter the date as well.
3378 When nil, only the minibuffer will be available."
3379 :group 'org-time
3380 :type 'boolean)
3381 (org-defvaralias 'org-popup-calendar-for-date-prompt
3382 'org-read-date-popup-calendar)
3384 (make-obsolete-variable
3385 'org-read-date-minibuffer-setup-hook
3386 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3387 (defcustom org-read-date-minibuffer-setup-hook nil
3388 "Hook to be used to set up keys for the date/time interface.
3389 Add key definitions to `minibuffer-local-map', which will be a
3390 temporary copy.
3392 WARNING: This option is obsolete, you should use
3393 `org-read-date-minibuffer-local-map' to set up keys."
3394 :group 'org-time
3395 :type 'hook)
3397 (defcustom org-extend-today-until 0
3398 "The hour when your day really ends. Must be an integer.
3399 This has influence for the following applications:
3400 - When switching the agenda to \"today\". It it is still earlier than
3401 the time given here, the day recognized as TODAY is actually yesterday.
3402 - When a date is read from the user and it is still before the time given
3403 here, the current date and time will be assumed to be yesterday, 23:59.
3404 Also, timestamps inserted in capture templates follow this rule.
3406 IMPORTANT: This is a feature whose implementation is and likely will
3407 remain incomplete. Really, it is only here because past midnight seems to
3408 be the favorite working time of John Wiegley :-)"
3409 :group 'org-time
3410 :type 'integer)
3412 (defcustom org-use-effective-time nil
3413 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3414 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3415 \"effective time\" of any timestamps between midnight and 8am will be
3416 23:59 of the previous day."
3417 :group 'org-time
3418 :version "24.1"
3419 :type 'boolean)
3421 (defcustom org-use-last-clock-out-time-as-effective-time nil
3422 "When non-nil, use the last clock out time for `org-todo'.
3423 Note that this option has precedence over the combined use of
3424 `org-use-effective-time' and `org-extend-today-until'."
3425 :group 'org-time
3426 :version "24.4"
3427 :package-version '(Org . "8.0")
3428 :type 'boolean)
3430 (defcustom org-edit-timestamp-down-means-later nil
3431 "Non-nil means S-down will increase the time in a time stamp.
3432 When nil, S-up will increase."
3433 :group 'org-time
3434 :type 'boolean)
3436 (defcustom org-calendar-follow-timestamp-change t
3437 "Non-nil means make the calendar window follow timestamp changes.
3438 When a timestamp is modified and the calendar window is visible, it will be
3439 moved to the new date."
3440 :group 'org-time
3441 :type 'boolean)
3443 (defgroup org-tags nil
3444 "Options concerning tags in Org-mode."
3445 :tag "Org Tags"
3446 :group 'org)
3448 (defcustom org-tag-alist nil
3449 "List of tags allowed in Org-mode files.
3450 When this list is nil, Org-mode will base TAG input on what is already in the
3451 buffer.
3452 The value of this variable is an alist, the car of each entry must be a
3453 keyword as a string, the cdr may be a character that is used to select
3454 that tag through the fast-tag-selection interface.
3455 See the manual for details."
3456 :group 'org-tags
3457 :type '(repeat
3458 (choice
3459 (cons (string :tag "Tag name")
3460 (character :tag "Access char"))
3461 (list :tag "Start radio group"
3462 (const :startgroup)
3463 (option (string :tag "Group description")))
3464 (list :tag "Start tag group, non distinct"
3465 (const :startgrouptag)
3466 (option (string :tag "Group description")))
3467 (list :tag "Group tags delimiter"
3468 (const :grouptags))
3469 (list :tag "End radio group"
3470 (const :endgroup)
3471 (option (string :tag "Group description")))
3472 (list :tag "End tag group, non distinct"
3473 (const :endgrouptag)
3474 (option (string :tag "Group description")))
3475 (const :tag "New line" (:newline)))))
3477 (defcustom org-tag-persistent-alist nil
3478 "List of tags that will always appear in all Org-mode files.
3479 This is in addition to any in buffer settings or customizations
3480 of `org-tag-alist'.
3481 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
3482 The value of this variable is an alist, the car of each entry must be a
3483 keyword as a string, the cdr may be a character that is used to select
3484 that tag through the fast-tag-selection interface.
3485 See the manual for details.
3486 To disable these tags on a per-file basis, insert anywhere in the file:
3487 #+STARTUP: noptag"
3488 :group 'org-tags
3489 :type '(repeat
3490 (choice
3491 (cons (string :tag "Tag name")
3492 (character :tag "Access char"))
3493 (const :tag "Start radio group" (:startgroup))
3494 (const :tag "Group tags delimiter" (:grouptags))
3495 (const :tag "End radio group" (:endgroup))
3496 (const :tag "New line" (:newline)))))
3498 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3499 "If non-nil, always offer completion for all tags of all agenda files.
3500 Instead of customizing this variable directly, you might want to
3501 set it locally for capture buffers, because there no list of
3502 tags in that file can be created dynamically (there are none).
3504 (add-hook \\='org-capture-mode-hook
3505 (lambda ()
3506 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3507 :group 'org-tags
3508 :version "24.1"
3509 :type 'boolean)
3511 (defvar org-file-tags nil
3512 "List of tags that can be inherited by all entries in the file.
3513 The tags will be inherited if the variable `org-use-tag-inheritance'
3514 says they should be.
3515 This variable is populated from #+FILETAGS lines.")
3517 (defcustom org-use-fast-tag-selection 'auto
3518 "Non-nil means use fast tag selection scheme.
3519 This is a special interface to select and deselect tags with single keys.
3520 When nil, fast selection is never used.
3521 When the symbol `auto', fast selection is used if and only if selection
3522 characters for tags have been configured, either through the variable
3523 `org-tag-alist' or through a #+TAGS line in the buffer.
3524 When t, fast selection is always used and selection keys are assigned
3525 automatically if necessary."
3526 :group 'org-tags
3527 :type '(choice
3528 (const :tag "Always" t)
3529 (const :tag "Never" nil)
3530 (const :tag "When selection characters are configured" auto)))
3532 (defcustom org-fast-tag-selection-single-key nil
3533 "Non-nil means fast tag selection exits after first change.
3534 When nil, you have to press RET to exit it.
3535 During fast tag selection, you can toggle this flag with `C-c'.
3536 This variable can also have the value `expert'. In this case, the window
3537 displaying the tags menu is not even shown, until you press C-c again."
3538 :group 'org-tags
3539 :type '(choice
3540 (const :tag "No" nil)
3541 (const :tag "Yes" t)
3542 (const :tag "Expert" expert)))
3544 (defvar org-fast-tag-selection-include-todo nil
3545 "Non-nil means fast tags selection interface will also offer TODO states.
3546 This is an undocumented feature, you should not rely on it.")
3548 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3549 "The column to which tags should be indented in a headline.
3550 If this number is positive, it specifies the column. If it is negative,
3551 it means that the tags should be flushright to that column. For example,
3552 -80 works well for a normal 80 character screen.
3553 When 0, place tags directly after headline text, with only one space in
3554 between."
3555 :group 'org-tags
3556 :type 'integer)
3558 (defcustom org-auto-align-tags t
3559 "Non-nil keeps tags aligned when modifying headlines.
3560 Some operations (i.e. demoting) change the length of a headline and
3561 therefore shift the tags around. With this option turned on, after
3562 each such operation the tags are again aligned to `org-tags-column'."
3563 :group 'org-tags
3564 :type 'boolean)
3566 (defcustom org-use-tag-inheritance t
3567 "Non-nil means tags in levels apply also for sublevels.
3568 When nil, only the tags directly given in a specific line apply there.
3569 This may also be a list of tags that should be inherited, or a regexp that
3570 matches tags that should be inherited. Additional control is possible
3571 with the variable `org-tags-exclude-from-inheritance' which gives an
3572 explicit list of tags to be excluded from inheritance, even if the value of
3573 `org-use-tag-inheritance' would select it for inheritance.
3575 If this option is t, a match early-on in a tree can lead to a large
3576 number of matches in the subtree when constructing the agenda or creating
3577 a sparse tree. If you only want to see the first match in a tree during
3578 a search, check out the variable `org-tags-match-list-sublevels'."
3579 :group 'org-tags
3580 :type '(choice
3581 (const :tag "Not" nil)
3582 (const :tag "Always" t)
3583 (repeat :tag "Specific tags" (string :tag "Tag"))
3584 (regexp :tag "Tags matched by regexp")))
3586 (defcustom org-tags-exclude-from-inheritance nil
3587 "List of tags that should never be inherited.
3588 This is a way to exclude a few tags from inheritance. For way to do
3589 the opposite, to actively allow inheritance for selected tags,
3590 see the variable `org-use-tag-inheritance'."
3591 :group 'org-tags
3592 :type '(repeat (string :tag "Tag")))
3594 (defun org-tag-inherit-p (tag)
3595 "Check if TAG is one that should be inherited."
3596 (cond
3597 ((member tag org-tags-exclude-from-inheritance) nil)
3598 ((eq org-use-tag-inheritance t) t)
3599 ((not org-use-tag-inheritance) nil)
3600 ((stringp org-use-tag-inheritance)
3601 (string-match org-use-tag-inheritance tag))
3602 ((listp org-use-tag-inheritance)
3603 (member tag org-use-tag-inheritance))
3604 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3606 (defcustom org-tags-match-list-sublevels t
3607 "Non-nil means list also sublevels of headlines matching a search.
3608 This variable applies to tags/property searches, and also to stuck
3609 projects because this search is based on a tags match as well.
3611 When set to the symbol `indented', sublevels are indented with
3612 leading dots.
3614 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3615 the sublevels of a headline matching a tag search often also match
3616 the same search. Listing all of them can create very long lists.
3617 Setting this variable to nil causes subtrees of a match to be skipped.
3619 This variable is semi-obsolete and probably should always be true. It
3620 is better to limit inheritance to certain tags using the variables
3621 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3622 :group 'org-tags
3623 :type '(choice
3624 (const :tag "No, don't list them" nil)
3625 (const :tag "Yes, do list them" t)
3626 (const :tag "List them, indented with leading dots" indented)))
3628 (defcustom org-tags-sort-function nil
3629 "When set, tags are sorted using this function as a comparator."
3630 :group 'org-tags
3631 :type '(choice
3632 (const :tag "No sorting" nil)
3633 (const :tag "Alphabetical" string<)
3634 (const :tag "Reverse alphabetical" string>)
3635 (function :tag "Custom function" nil)))
3637 (defvar org-tags-history nil
3638 "History of minibuffer reads for tags.")
3639 (defvar org-last-tags-completion-table nil
3640 "The last used completion table for tags.")
3641 (defvar org-after-tags-change-hook nil
3642 "Hook that is run after the tags in a line have changed.")
3644 (defgroup org-properties nil
3645 "Options concerning properties in Org-mode."
3646 :tag "Org Properties"
3647 :group 'org)
3649 (defcustom org-property-format "%-10s %s"
3650 "How property key/value pairs should be formatted by `indent-line'.
3651 When `indent-line' hits a property definition, it will format the line
3652 according to this format, mainly to make sure that the values are
3653 lined-up with respect to each other."
3654 :group 'org-properties
3655 :type 'string)
3657 (defcustom org-properties-postprocess-alist nil
3658 "Alist of properties and functions to adjust inserted values.
3659 Elements of this alist must be of the form
3661 ([string] [function])
3663 where [string] must be a property name and [function] must be a
3664 lambda expression: this lambda expression must take one argument,
3665 the value to adjust, and return the new value as a string.
3667 For example, this element will allow the property \"Remaining\"
3668 to be updated wrt the relation between the \"Effort\" property
3669 and the clock summary:
3671 ((\"Remaining\" (lambda(value)
3672 (let ((clocksum (org-clock-sum-current-item))
3673 (effort (org-duration-string-to-minutes
3674 (org-entry-get (point) \"Effort\"))))
3675 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3676 :group 'org-properties
3677 :version "24.1"
3678 :type '(alist :key-type (string :tag "Property")
3679 :value-type (function :tag "Function")))
3681 (defcustom org-use-property-inheritance nil
3682 "Non-nil means properties apply also for sublevels.
3684 This setting is chiefly used during property searches. Turning it on can
3685 cause significant overhead when doing a search, which is why it is not
3686 on by default.
3688 When nil, only the properties directly given in the current entry count.
3689 When t, every property is inherited. The value may also be a list of
3690 properties that should have inheritance, or a regular expression matching
3691 properties that should be inherited.
3693 However, note that some special properties use inheritance under special
3694 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3695 and the properties ending in \"_ALL\" when they are used as descriptor
3696 for valid values of a property.
3698 Note for programmers:
3699 When querying an entry with `org-entry-get', you can control if inheritance
3700 should be used. By default, `org-entry-get' looks only at the local
3701 properties. You can request inheritance by setting the inherit argument
3702 to t (to force inheritance) or to `selective' (to respect the setting
3703 in this variable)."
3704 :group 'org-properties
3705 :type '(choice
3706 (const :tag "Not" nil)
3707 (const :tag "Always" t)
3708 (repeat :tag "Specific properties" (string :tag "Property"))
3709 (regexp :tag "Properties matched by regexp")))
3711 (defun org-property-inherit-p (property)
3712 "Check if PROPERTY is one that should be inherited."
3713 (cond
3714 ((eq org-use-property-inheritance t) t)
3715 ((not org-use-property-inheritance) nil)
3716 ((stringp org-use-property-inheritance)
3717 (string-match org-use-property-inheritance property))
3718 ((listp org-use-property-inheritance)
3719 (member property org-use-property-inheritance))
3720 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3722 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3723 "The default column format, if no other format has been defined.
3724 This variable can be set on the per-file basis by inserting a line
3726 #+COLUMNS: %25ITEM ....."
3727 :group 'org-properties
3728 :type 'string)
3730 (defcustom org-columns-ellipses ".."
3731 "The ellipses to be used when a field in column view is truncated.
3732 When this is the empty string, as many characters as possible are shown,
3733 but then there will be no visual indication that the field has been truncated.
3734 When this is a string of length N, the last N characters of a truncated
3735 field are replaced by this string. If the column is narrower than the
3736 ellipses string, only part of the ellipses string will be shown."
3737 :group 'org-properties
3738 :type 'string)
3740 (defconst org-global-properties-fixed
3741 '(("VISIBILITY_ALL" . "folded children content all")
3742 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3743 "List of property/value pairs that can be inherited by any entry.
3745 These are fixed values, for the preset properties. The user variable
3746 that can be used to add to this list is `org-global-properties'.
3748 The entries in this list are cons cells where the car is a property
3749 name and cdr is a string with the value. If the value represents
3750 multiple items like an \"_ALL\" property, separate the items by
3751 spaces.")
3753 (defcustom org-global-properties nil
3754 "List of property/value pairs that can be inherited by any entry.
3756 This list will be combined with the constant `org-global-properties-fixed'.
3758 The entries in this list are cons cells where the car is a property
3759 name and cdr is a string with the value.
3761 You can set buffer-local values for the same purpose in the variable
3762 `org-file-properties' this by adding lines like
3764 #+PROPERTY: NAME VALUE"
3765 :group 'org-properties
3766 :type '(repeat
3767 (cons (string :tag "Property")
3768 (string :tag "Value"))))
3770 (defvar-local org-file-properties nil
3771 "List of property/value pairs that can be inherited by any entry.
3772 Valid for the current buffer.
3773 This variable is populated from #+PROPERTY lines.")
3775 (defgroup org-agenda nil
3776 "Options concerning agenda views in Org-mode."
3777 :tag "Org Agenda"
3778 :group 'org)
3780 (defvar-local org-category nil
3781 "Variable used by org files to set a category for agenda display.
3782 Such files should use a file variable to set it, for example
3784 # -*- mode: org; org-category: \"ELisp\"
3786 or contain a special line
3788 #+CATEGORY: ELisp
3790 If the file does not specify a category, then file's base name
3791 is used instead.")
3792 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3794 (defcustom org-agenda-files nil
3795 "The files to be used for agenda display.
3796 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3797 \\[org-remove-file]. You can also use customize to edit the list.
3799 If an entry is a directory, all files in that directory that are matched by
3800 `org-agenda-file-regexp' will be part of the file list.
3802 If the value of the variable is not a list but a single file name, then
3803 the list of agenda files is actually stored and maintained in that file, one
3804 agenda file per line. In this file paths can be given relative to
3805 `org-directory'. Tilde expansion and environment variable substitution
3806 are also made."
3807 :group 'org-agenda
3808 :type '(choice
3809 (repeat :tag "List of files and directories" file)
3810 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3812 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3813 "Regular expression to match files for `org-agenda-files'.
3814 If any element in the list in that variable contains a directory instead
3815 of a normal file, all files in that directory that are matched by this
3816 regular expression will be included."
3817 :group 'org-agenda
3818 :type 'regexp)
3820 (defcustom org-agenda-text-search-extra-files nil
3821 "List of extra files to be searched by text search commands.
3822 These files will be searched in addition to the agenda files by the
3823 commands `org-search-view' (`\\[org-agenda] s') \
3824 and `org-occur-in-agenda-files'.
3825 Note that these files will only be searched for text search commands,
3826 not for the other agenda views like todo lists, tag searches or the weekly
3827 agenda. This variable is intended to list notes and possibly archive files
3828 that should also be searched by these two commands.
3829 In fact, if the first element in the list is the symbol `agenda-archives',
3830 then all archive files of all agenda files will be added to the search
3831 scope."
3832 :group 'org-agenda
3833 :type '(set :greedy t
3834 (const :tag "Agenda Archives" agenda-archives)
3835 (repeat :inline t (file))))
3837 (org-defvaralias 'org-agenda-multi-occur-extra-files
3838 'org-agenda-text-search-extra-files)
3840 (defcustom org-agenda-skip-unavailable-files nil
3841 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3842 A nil value means to remove them, after a query, from the list."
3843 :group 'org-agenda
3844 :type 'boolean)
3846 (defcustom org-calendar-to-agenda-key [?c]
3847 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3848 The command `org-calendar-goto-agenda' will be bound to this key. The
3849 default is the character `c' because then `c' can be used to switch back and
3850 forth between agenda and calendar."
3851 :group 'org-agenda
3852 :type 'sexp)
3854 (defcustom org-calendar-insert-diary-entry-key [?i]
3855 "The key to be installed in `calendar-mode-map' for adding diary entries.
3856 This option is irrelevant until `org-agenda-diary-file' has been configured
3857 to point to an Org-mode file. When that is the case, the command
3858 `org-agenda-diary-entry' will be bound to the key given here, by default
3859 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3860 if you want to continue doing this, you need to change this to a different
3861 key."
3862 :group 'org-agenda
3863 :type 'sexp)
3865 (defcustom org-agenda-diary-file 'diary-file
3866 "File to which to add new entries with the `i' key in agenda and calendar.
3867 When this is the symbol `diary-file', the functionality in the Emacs
3868 calendar will be used to add entries to the `diary-file'. But when this
3869 points to a file, `org-agenda-diary-entry' will be used instead."
3870 :group 'org-agenda
3871 :type '(choice
3872 (const :tag "The standard Emacs diary file" diary-file)
3873 (file :tag "Special Org file diary entries")))
3875 (eval-after-load "calendar"
3876 '(progn
3877 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3878 'org-calendar-goto-agenda)
3879 (add-hook 'calendar-mode-hook
3880 (lambda ()
3881 (unless (eq org-agenda-diary-file 'diary-file)
3882 (define-key calendar-mode-map
3883 org-calendar-insert-diary-entry-key
3884 'org-agenda-diary-entry))))))
3886 (defgroup org-latex nil
3887 "Options for embedding LaTeX code into Org-mode."
3888 :tag "Org LaTeX"
3889 :group 'org)
3891 (defcustom org-format-latex-options
3892 '(:foreground default :background default :scale 1.0
3893 :html-foreground "Black" :html-background "Transparent"
3894 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3895 "Options for creating images from LaTeX fragments.
3896 This is a property list with the following properties:
3897 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3898 `default' means use the foreground of the default face.
3899 `auto' means use the foreground from the text face.
3900 :background the background color, or \"Transparent\".
3901 `default' means use the background of the default face.
3902 `auto' means use the background from the text face.
3903 :scale a scaling factor for the size of the images, to get more pixels
3904 :html-foreground, :html-background, :html-scale
3905 the same numbers for HTML export.
3906 :matchers a list indicating which matchers should be used to
3907 find LaTeX fragments. Valid members of this list are:
3908 \"begin\" find environments
3909 \"$1\" find single characters surrounded by $.$
3910 \"$\" find math expressions surrounded by $...$
3911 \"$$\" find math expressions surrounded by $$....$$
3912 \"\\(\" find math expressions surrounded by \\(...\\)
3913 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3914 :group 'org-latex
3915 :type 'plist)
3917 (defcustom org-format-latex-signal-error t
3918 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3919 When nil, just push out a message."
3920 :group 'org-latex
3921 :version "24.1"
3922 :type 'boolean)
3924 (defcustom org-latex-to-mathml-jar-file nil
3925 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3926 Use this to specify additional executable file say a jar file.
3928 When using MathToWeb as the converter, specify the full-path to
3929 your mathtoweb.jar file."
3930 :group 'org-latex
3931 :version "24.1"
3932 :type '(choice
3933 (const :tag "None" nil)
3934 (file :tag "JAR file" :must-match t)))
3936 (defcustom org-latex-to-mathml-convert-command nil
3937 "Command to convert LaTeX fragments to MathML.
3938 Replace format-specifiers in the command as noted below and use
3939 `shell-command' to convert LaTeX to MathML.
3940 %j: Executable file in fully expanded form as specified by
3941 `org-latex-to-mathml-jar-file'.
3942 %I: Input LaTeX file in fully expanded form.
3943 %i: The latex fragment to be converted.
3944 %o: Output MathML file.
3946 This command is used by `org-create-math-formula'.
3948 When using MathToWeb as the converter, set this option to
3949 \"java -jar %j -unicode -force -df %o %I\".
3951 When using LaTeXML set this option to
3952 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3953 :group 'org-latex
3954 :version "24.1"
3955 :type '(choice
3956 (const :tag "None" nil)
3957 (string :tag "\nShell command")))
3959 (defcustom org-latex-create-formula-image-program 'dvipng
3960 "Program to convert LaTeX fragments with.
3962 dvipng Process the LaTeX fragments to dvi file, then convert
3963 dvi files to png files using dvipng.
3964 This will also include processing of non-math environments.
3965 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3966 to convert pdf files to png files"
3967 :group 'org-latex
3968 :version "24.1"
3969 :type '(choice
3970 (const :tag "dvipng" dvipng)
3971 (const :tag "imagemagick" imagemagick)))
3973 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3974 "Path to store latex preview images.
3975 A relative path here creates many directories relative to the
3976 processed org files paths. An absolute path puts all preview
3977 images at the same place."
3978 :group 'org-latex
3979 :version "24.3"
3980 :type 'string)
3982 (defun org-format-latex-mathml-available-p ()
3983 "Return t if `org-latex-to-mathml-convert-command' is usable."
3984 (save-match-data
3985 (when (and (boundp 'org-latex-to-mathml-convert-command)
3986 org-latex-to-mathml-convert-command)
3987 (let ((executable (car (split-string
3988 org-latex-to-mathml-convert-command))))
3989 (when (executable-find executable)
3990 (if (string-match
3991 "%j" org-latex-to-mathml-convert-command)
3992 (file-readable-p org-latex-to-mathml-jar-file)
3993 t))))))
3995 (defcustom org-format-latex-header "\\documentclass{article}
3996 \\usepackage[usenames]{color}
3997 \[PACKAGES]
3998 \[DEFAULT-PACKAGES]
3999 \\pagestyle{empty} % do not remove
4000 % The settings below are copied from fullpage.sty
4001 \\setlength{\\textwidth}{\\paperwidth}
4002 \\addtolength{\\textwidth}{-3cm}
4003 \\setlength{\\oddsidemargin}{1.5cm}
4004 \\addtolength{\\oddsidemargin}{-2.54cm}
4005 \\setlength{\\evensidemargin}{\\oddsidemargin}
4006 \\setlength{\\textheight}{\\paperheight}
4007 \\addtolength{\\textheight}{-\\headheight}
4008 \\addtolength{\\textheight}{-\\headsep}
4009 \\addtolength{\\textheight}{-\\footskip}
4010 \\addtolength{\\textheight}{-3cm}
4011 \\setlength{\\topmargin}{1.5cm}
4012 \\addtolength{\\topmargin}{-2.54cm}"
4013 "The document header used for processing LaTeX fragments.
4014 It is imperative that this header make sure that no page number
4015 appears on the page. The package defined in the variables
4016 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4017 will either replace the placeholder \"[PACKAGES]\" in this
4018 header, or they will be appended."
4019 :group 'org-latex
4020 :type 'string)
4022 (defun org-set-packages-alist (var val)
4023 "Set the packages alist and make sure it has 3 elements per entry."
4024 (set var (mapcar (lambda (x)
4025 (if (and (consp x) (= (length x) 2))
4026 (list (car x) (nth 1 x) t)
4028 val)))
4030 (defun org-get-packages-alist (var)
4031 "Get the packages alist and make sure it has 3 elements per entry."
4032 (mapcar (lambda (x)
4033 (if (and (consp x) (= (length x) 2))
4034 (list (car x) (nth 1 x) t)
4036 (default-value var)))
4038 (defcustom org-latex-default-packages-alist
4039 '(("AUTO" "inputenc" t ("pdflatex"))
4040 ("T1" "fontenc" t ("pdflatex"))
4041 ("" "graphicx" t)
4042 ("" "grffile" t)
4043 ("" "longtable" nil)
4044 ("" "wrapfig" nil)
4045 ("" "rotating" nil)
4046 ("normalem" "ulem" t)
4047 ("" "amsmath" t)
4048 ("" "textcomp" t)
4049 ("" "amssymb" t)
4050 ("" "capt-of" nil)
4051 ("" "hyperref" nil))
4052 "Alist of default packages to be inserted in the header.
4054 Change this only if one of the packages here causes an
4055 incompatibility with another package you are using.
4057 The packages in this list are needed by one part or another of
4058 Org mode to function properly:
4060 - inputenc, fontenc: for basic font and character selection
4061 - graphicx: for including images
4062 - grffile: allow periods and spaces in graphics file names
4063 - longtable: For multipage tables
4064 - wrapfig: for figure placement
4065 - rotating: for sideways figures and tables
4066 - ulem: for underline and strike-through
4067 - amsmath: for subscript and superscript and math environments
4068 - textcomp, amssymb: for various symbols used
4069 for interpreting the entities in `org-entities'. You can skip
4070 some of these packages if you don't use any of their symbols.
4071 - capt-of: for captions outside of floats
4072 - hyperref: for cross references
4074 Therefore you should not modify this variable unless you know
4075 what you are doing. The one reason to change it anyway is that
4076 you might be loading some other package that conflicts with one
4077 of the default packages. Each element is either a cell or
4078 a string.
4080 A cell is of the format
4082 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4084 If SNIPPET-FLAG is non-nil, the package also needs to be included
4085 when compiling LaTeX snippets into images for inclusion into
4086 non-LaTeX output. COMPILERS is a list of compilers that should
4087 include the package, see `org-latex-compiler'. If the document
4088 compiler is not in the list, and the list is non-nil, the package
4089 will not be inserted in the final document.
4091 A string will be inserted as-is in the header of the document."
4092 :group 'org-latex
4093 :group 'org-export-latex
4094 :set 'org-set-packages-alist
4095 :get 'org-get-packages-alist
4096 :version "25.1"
4097 :package-version '(Org . "8.3")
4098 :type '(repeat
4099 (choice
4100 (list :tag "options/package pair"
4101 (string :tag "options")
4102 (string :tag "package")
4103 (boolean :tag "Snippet"))
4104 (string :tag "A line of LaTeX"))))
4106 (defcustom org-latex-packages-alist nil
4107 "Alist of packages to be inserted in every LaTeX header.
4109 These will be inserted after `org-latex-default-packages-alist'.
4110 Each element is either a cell or a string.
4112 A cell is of the format:
4114 (\"options\" \"package\" SNIPPET-FLAG)
4116 SNIPPET-FLAG, when non-nil, indicates that this package is also
4117 needed when turning LaTeX snippets into images for inclusion into
4118 non-LaTeX output.
4120 A string will be inserted as-is in the header of the document.
4122 Make sure that you only list packages here which:
4124 - you want in every file;
4125 - do not conflict with the setup in `org-format-latex-header';
4126 - do not conflict with the default packages in
4127 `org-latex-default-packages-alist'."
4128 :group 'org-latex
4129 :group 'org-export-latex
4130 :set 'org-set-packages-alist
4131 :get 'org-get-packages-alist
4132 :type '(repeat
4133 (choice
4134 (list :tag "options/package pair"
4135 (string :tag "options")
4136 (string :tag "package")
4137 (boolean :tag "Snippet"))
4138 (string :tag "A line of LaTeX"))))
4140 (defgroup org-appearance nil
4141 "Settings for Org-mode appearance."
4142 :tag "Org Appearance"
4143 :group 'org)
4145 (defcustom org-level-color-stars-only nil
4146 "Non-nil means fontify only the stars in each headline.
4147 When nil, the entire headline is fontified.
4148 Changing it requires restart of `font-lock-mode' to become effective
4149 also in regions already fontified."
4150 :group 'org-appearance
4151 :type 'boolean)
4153 (defcustom org-hide-leading-stars nil
4154 "Non-nil means hide the first N-1 stars in a headline.
4155 This works by using the face `org-hide' for these stars. This
4156 face is white for a light background, and black for a dark
4157 background. You may have to customize the face `org-hide' to
4158 make this work.
4159 Changing it requires restart of `font-lock-mode' to become effective
4160 also in regions already fontified.
4161 You may also set this on a per-file basis by adding one of the following
4162 lines to the buffer:
4164 #+STARTUP: hidestars
4165 #+STARTUP: showstars"
4166 :group 'org-appearance
4167 :type 'boolean)
4169 (defcustom org-hidden-keywords nil
4170 "List of symbols corresponding to keywords to be hidden the org buffer.
4171 For example, a value \\='(title) for this list will make the document's title
4172 appear in the buffer without the initial #+TITLE: keyword."
4173 :group 'org-appearance
4174 :version "24.1"
4175 :type '(set (const :tag "#+AUTHOR" author)
4176 (const :tag "#+DATE" date)
4177 (const :tag "#+EMAIL" email)
4178 (const :tag "#+TITLE" title)))
4180 (defcustom org-custom-properties nil
4181 "List of properties (as strings) with a special meaning.
4182 The default use of these custom properties is to let the user
4183 hide them with `org-toggle-custom-properties-visibility'."
4184 :group 'org-properties
4185 :group 'org-appearance
4186 :version "24.3"
4187 :type '(repeat (string :tag "Property Name")))
4189 (defcustom org-fontify-done-headline nil
4190 "Non-nil means change the face of a headline if it is marked DONE.
4191 Normally, only the TODO/DONE keyword indicates the state of a headline.
4192 When this is non-nil, the headline after the keyword is set to the
4193 `org-headline-done' as an additional indication."
4194 :group 'org-appearance
4195 :type 'boolean)
4197 (defcustom org-fontify-emphasized-text t
4198 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4199 Changing this variable requires a restart of Emacs to take effect."
4200 :group 'org-appearance
4201 :type 'boolean)
4203 (defcustom org-fontify-whole-heading-line nil
4204 "Non-nil means fontify the whole line for headings.
4205 This is useful when setting a background color for the
4206 org-level-* faces."
4207 :group 'org-appearance
4208 :type 'boolean)
4210 (defcustom org-highlight-latex-and-related nil
4211 "Non-nil means highlight LaTeX related syntax in the buffer.
4212 When non nil, the value should be a list containing any of the
4213 following symbols:
4214 `latex' Highlight LaTeX snippets and environments.
4215 `script' Highlight subscript and superscript.
4216 `entities' Highlight entities."
4217 :group 'org-appearance
4218 :version "24.4"
4219 :package-version '(Org . "8.0")
4220 :type '(choice
4221 (const :tag "No highlighting" nil)
4222 (set :greedy t :tag "Highlight"
4223 (const :tag "LaTeX snippets and environments" latex)
4224 (const :tag "Subscript and superscript" script)
4225 (const :tag "Entities" entities))))
4227 (defcustom org-hide-emphasis-markers nil
4228 "Non-nil mean font-lock should hide the emphasis marker characters."
4229 :group 'org-appearance
4230 :type 'boolean)
4232 (defcustom org-hide-macro-markers nil
4233 "Non-nil mean font-lock should hide the brackets marking macro calls."
4234 :group 'org-appearance
4235 :type 'boolean)
4237 (defcustom org-pretty-entities nil
4238 "Non-nil means show entities as UTF8 characters.
4239 When nil, the \\name form remains in the buffer."
4240 :group 'org-appearance
4241 :version "24.1"
4242 :type 'boolean)
4244 (defcustom org-pretty-entities-include-sub-superscripts t
4245 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4246 :group 'org-appearance
4247 :version "24.1"
4248 :type 'boolean)
4250 (defvar org-emph-re nil
4251 "Regular expression for matching emphasis.
4252 After a match, the match groups contain these elements:
4253 0 The match of the full regular expression, including the characters
4254 before and after the proper match
4255 1 The character before the proper match, or empty at beginning of line
4256 2 The proper match, including the leading and trailing markers
4257 3 The leading marker like * or /, indicating the type of highlighting
4258 4 The text between the emphasis markers, not including the markers
4259 5 The character after the match, empty at the end of a line")
4260 (defvar org-verbatim-re nil
4261 "Regular expression for matching verbatim text.")
4262 (defvar org-emphasis-regexp-components) ; defined just below
4263 (defvar org-emphasis-alist) ; defined just below
4264 (defun org-set-emph-re (var val)
4265 "Set variable and compute the emphasis regular expression."
4266 (set var val)
4267 (when (and (boundp 'org-emphasis-alist)
4268 (boundp 'org-emphasis-regexp-components)
4269 org-emphasis-alist org-emphasis-regexp-components)
4270 (let* ((e org-emphasis-regexp-components)
4271 (pre (car e))
4272 (post (nth 1 e))
4273 (border (nth 2 e))
4274 (body (nth 3 e))
4275 (nl (nth 4 e))
4276 (body1 (concat body "*?"))
4277 (markers (mapconcat 'car org-emphasis-alist ""))
4278 (vmarkers (mapconcat
4279 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4280 org-emphasis-alist "")))
4281 ;; make sure special characters appear at the right position in the class
4282 (if (string-match "\\^" markers)
4283 (setq markers (concat (replace-match "" t t markers) "^")))
4284 (if (string-match "-" markers)
4285 (setq markers (concat (replace-match "" t t markers) "-")))
4286 (if (string-match "\\^" vmarkers)
4287 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4288 (if (string-match "-" vmarkers)
4289 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4290 (if (> nl 0)
4291 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4292 (int-to-string nl) "\\}")))
4293 ;; Make the regexp
4294 (setq org-emph-re
4295 (concat "\\([" pre "]\\|^\\)"
4296 "\\("
4297 "\\([" markers "]\\)"
4298 "\\("
4299 "[^" border "]\\|"
4300 "[^" border "]"
4301 body1
4302 "[^" border "]"
4303 "\\)"
4304 "\\3\\)"
4305 "\\([" post "]\\|$\\)"))
4306 (setq org-verbatim-re
4307 (concat "\\([" pre "]\\|^\\)"
4308 "\\("
4309 "\\([" vmarkers "]\\)"
4310 "\\("
4311 "[^" border "]\\|"
4312 "[^" border "]"
4313 body1
4314 "[^" border "]"
4315 "\\)"
4316 "\\3\\)"
4317 "\\([" post "]\\|$\\)")))))
4319 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4320 ;; set this option proved cumbersome. See this message/thread:
4321 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4322 (defvar org-emphasis-regexp-components
4323 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4324 "Components used to build the regular expression for emphasis.
4325 This is a list with five entries. Terminology: In an emphasis string
4326 like \" *strong word* \", we call the initial space PREMATCH, the final
4327 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4328 and \"trong wor\" is the body. The different components in this variable
4329 specify what is allowed/forbidden in each part:
4331 pre Chars allowed as prematch. Beginning of line will be allowed too.
4332 post Chars allowed as postmatch. End of line will be allowed too.
4333 border The chars *forbidden* as border characters.
4334 body-regexp A regexp like \".\" to match a body character. Don't use
4335 non-shy groups here, and don't allow newline here.
4336 newline The maximum number of newlines allowed in an emphasis exp.
4338 You need to reload Org or to restart Emacs after customizing this.")
4340 (defcustom org-emphasis-alist
4341 `(("*" bold)
4342 ("/" italic)
4343 ("_" underline)
4344 ("=" org-verbatim verbatim)
4345 ("~" org-code verbatim)
4346 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4347 "Alist of characters and faces to emphasize text.
4348 Text starting and ending with a special character will be emphasized,
4349 for example *bold*, _underlined_ and /italic/. This variable sets the
4350 marker characters and the face to be used by font-lock for highlighting
4351 in Org-mode Emacs buffers.
4353 You need to reload Org or to restart Emacs after customizing this."
4354 :group 'org-appearance
4355 :set 'org-set-emph-re
4356 :version "24.4"
4357 :package-version '(Org . "8.0")
4358 :type '(repeat
4359 (list
4360 (string :tag "Marker character")
4361 (choice
4362 (face :tag "Font-lock-face")
4363 (plist :tag "Face property list"))
4364 (option (const verbatim)))))
4366 (defvar org-protecting-blocks '("src" "example" "export")
4367 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4368 This is needed for font-lock setup.")
4370 ;;; Functions and variables from their packages
4371 ;; Declared here to avoid compiler warnings
4373 ;; XEmacs only
4374 (defvar outline-mode-menu-heading)
4375 (defvar outline-mode-menu-show)
4376 (defvar outline-mode-menu-hide)
4377 (defvar zmacs-regions) ; XEmacs regions
4379 ;; Emacs only
4380 (defvar mark-active)
4382 ;; Various packages
4383 (declare-function calc-eval "calc" (str &optional separator &rest args))
4384 (declare-function calendar-forward-day "cal-move" (arg))
4385 (declare-function calendar-goto-date "cal-move" (date))
4386 (declare-function calendar-goto-today "cal-move" ())
4387 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4388 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4389 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4390 (declare-function cdlatex-tab "ext:cdlatex" ())
4391 (declare-function dired-get-filename
4392 "dired"
4393 (&optional localp no-error-if-not-filep))
4394 (declare-function iswitchb-read-buffer
4395 "iswitchb"
4396 (prompt &optional default require-match start matches-set))
4397 (declare-function org-agenda-change-all-lines
4398 "org-agenda"
4399 (newhead hdmarker &optional fixface just-this))
4400 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4401 "org-agenda"
4402 (&optional end))
4403 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4404 (declare-function org-agenda-format-item
4405 "org-agenda"
4406 (extra txt &optional level category tags dotime noprefix
4407 remove-re habitp))
4408 (declare-function org-agenda-maybe-redo "org-agenda" ())
4409 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4410 (declare-function org-agenda-save-markers-for-cut-and-paste
4411 "org-agenda"
4412 (beg end))
4413 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4414 (declare-function org-agenda-skip "org-agenda" ())
4415 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4416 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4417 (declare-function org-indent-mode "org-indent" (&optional arg))
4418 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4419 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4420 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4421 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4422 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4423 (declare-function parse-time-string "parse-time" (string))
4424 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4425 (declare-function table--at-cell-p
4426 "table"
4427 (position &optional object at-column))
4429 (defvar align-mode-rules-list)
4430 (defvar calc-embedded-close-formula)
4431 (defvar calc-embedded-open-formula)
4432 (defvar calc-embedded-open-mode)
4433 (defvar font-lock-unfontify-region-function)
4434 (defvar iswitchb-temp-buflist)
4435 (defvar org-agenda-tags-todo-honor-ignore-options)
4436 (defvar remember-data-file)
4437 (defvar texmathp-why)
4439 ;;;###autoload
4440 (defun turn-on-orgtbl ()
4441 "Unconditionally turn on `orgtbl-mode'."
4442 (require 'org-table)
4443 (orgtbl-mode 1))
4445 (defun org-at-table-p (&optional table-type)
4446 "Non-nil if the cursor is inside an Org table.
4447 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4448 If `org-enable-table-editor' is nil, return nil unconditionally."
4449 (and
4450 org-enable-table-editor
4451 (save-excursion
4452 (beginning-of-line)
4453 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4454 (or (not (derived-mode-p 'org-mode))
4455 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4456 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4457 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4459 (defun org-at-table.el-p ()
4460 "Non-nil when point is at a table.el table."
4461 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4462 (let ((element (org-element-at-point)))
4463 (and (eq (org-element-type element) 'table)
4464 (eq (org-element-property :type element) 'table.el)))))
4466 (defun org-table-recognize-table.el ()
4467 "If there is a table.el table nearby, recognize it and move into it."
4468 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4469 (beginning-of-line)
4470 (unless (or (looking-at org-table-dataline-regexp)
4471 (not (looking-at org-table1-hline-regexp)))
4472 (forward-line)
4473 (when (looking-at org-table-any-border-regexp)
4474 (forward-line -2)))
4475 (if (re-search-forward "|" (org-table-end t) t)
4476 (progn
4477 (require 'table)
4478 (if (table--at-cell-p (point)) t
4479 (message "recognizing table.el table...")
4480 (table-recognize-table)
4481 (message "recognizing table.el table...done")))
4482 (error "This should not happen"))))
4483 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4484 (make-obsolete 'org-table-recognize-table.el
4485 "please notify the org mailing list if you use this function."
4486 "Org 9.0")
4488 (defun org-at-table-hline-p ()
4489 "Non-nil when point is inside a hline in a table.
4490 Assume point is already in a table. If `org-enable-table-editor'
4491 is nil, return nil unconditionally."
4492 (and org-enable-table-editor
4493 (save-excursion
4494 (beginning-of-line)
4495 (looking-at org-table-hline-regexp))))
4497 (defun org-table-map-tables (function &optional quietly)
4498 "Apply FUNCTION to the start of all tables in the buffer."
4499 (save-excursion
4500 (save-restriction
4501 (widen)
4502 (goto-char (point-min))
4503 (while (re-search-forward org-table-any-line-regexp nil t)
4504 (unless quietly
4505 (message "Mapping tables: %d%%"
4506 (floor (* 100.0 (point)) (buffer-size))))
4507 (beginning-of-line 1)
4508 (when (and (looking-at org-table-line-regexp)
4509 ;; Exclude tables in src/example/verbatim/clocktable blocks
4510 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4511 (save-excursion (funcall function))
4512 (or (looking-at org-table-line-regexp)
4513 (forward-char 1)))
4514 (re-search-forward org-table-any-border-regexp nil 1))))
4515 (unless quietly (message "Mapping tables: done")))
4517 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4518 (declare-function org-clock-update-mode-line "org-clock" ())
4519 (declare-function org-resolve-clocks "org-clock"
4520 (&optional also-non-dangling-p prompt last-valid))
4522 (defun org-at-TBLFM-p (&optional pos)
4523 "Non-nil when point (or POS) is in #+TBLFM line."
4524 (save-excursion
4525 (goto-char (or pos (point)))
4526 (beginning-of-line)
4527 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4528 (eq (org-element-type (org-element-at-point)) 'table))))
4530 (defvar org-clock-start-time)
4531 (defvar org-clock-marker (make-marker)
4532 "Marker recording the last clock-in.")
4533 (defvar org-clock-hd-marker (make-marker)
4534 "Marker recording the last clock-in, but the headline position.")
4535 (defvar org-clock-heading ""
4536 "The heading of the current clock entry.")
4537 (defun org-clock-is-active ()
4538 "Return the buffer where the clock is currently running.
4539 Return nil if no clock is running."
4540 (marker-buffer org-clock-marker))
4542 (defun org-check-running-clock ()
4543 "Check if the current buffer contains the running clock.
4544 If yes, offer to stop it and to save the buffer with the changes."
4545 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4546 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4547 (buffer-name))))
4548 (org-clock-out)
4549 (when (y-or-n-p "Save changed buffer?")
4550 (save-buffer))))
4552 (defun org-clocktable-try-shift (dir n)
4553 "Check if this line starts a clock table, if yes, shift the time block."
4554 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4555 (org-clocktable-shift dir n)))
4557 ;;;###autoload
4558 (defun org-clock-persistence-insinuate ()
4559 "Set up hooks for clock persistence."
4560 (require 'org-clock)
4561 (add-hook 'org-mode-hook 'org-clock-load)
4562 (add-hook 'kill-emacs-hook 'org-clock-save))
4564 (defgroup org-archive nil
4565 "Options concerning archiving in Org-mode."
4566 :tag "Org Archive"
4567 :group 'org-structure)
4569 (defcustom org-archive-location "%s_archive::"
4570 "The location where subtrees should be archived.
4572 The value of this variable is a string, consisting of two parts,
4573 separated by a double-colon. The first part is a filename and
4574 the second part is a headline.
4576 When the filename is omitted, archiving happens in the same file.
4577 %s in the filename will be replaced by the current file
4578 name (without the directory part). Archiving to a different file
4579 is useful to keep archived entries from contributing to the
4580 Org-mode Agenda.
4582 The archived entries will be filed as subtrees of the specified
4583 headline. When the headline is omitted, the subtrees are simply
4584 filed away at the end of the file, as top-level entries. Also in
4585 the heading you can use %s to represent the file name, this can be
4586 useful when using the same archive for a number of different files.
4588 Here are a few examples:
4589 \"%s_archive::\"
4590 If the current file is Projects.org, archive in file
4591 Projects.org_archive, as top-level trees. This is the default.
4593 \"::* Archived Tasks\"
4594 Archive in the current file, under the top-level headline
4595 \"* Archived Tasks\".
4597 \"~/org/archive.org::\"
4598 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4600 \"~/org/archive.org::* From %s\"
4601 Archive in file ~/org/archive.org (absolute path), under headlines
4602 \"From FILENAME\" where file name is the current file name.
4604 \"~/org/datetree.org::datetree/* Finished Tasks\"
4605 The \"datetree/\" string is special, signifying to archive
4606 items to the datetree. Items are placed in either the CLOSED
4607 date of the item, or the current date if there is no CLOSED date.
4608 The heading will be a subentry to the current date. There doesn't
4609 need to be a heading, but there always needs to be a slash after
4610 datetree. For example, to store archived items directly in the
4611 datetree, use \"~/org/datetree.org::datetree/\".
4613 \"basement::** Finished Tasks\"
4614 Archive in file ./basement (relative path), as level 3 trees
4615 below the level 2 heading \"** Finished Tasks\".
4617 You may set this option on a per-file basis by adding to the buffer a
4618 line like
4620 #+ARCHIVE: basement::** Finished Tasks
4622 You may also define it locally for a subtree by setting an ARCHIVE property
4623 in the entry. If such a property is found in an entry, or anywhere up
4624 the hierarchy, it will be used."
4625 :group 'org-archive
4626 :type 'string)
4628 (defcustom org-agenda-skip-archived-trees t
4629 "Non-nil means the agenda will skip any items located in archived trees.
4630 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4631 variable is no longer recommended, you should leave it at the value t.
4632 Instead, use the key `v' to cycle the archives-mode in the agenda."
4633 :group 'org-archive
4634 :group 'org-agenda-skip
4635 :type 'boolean)
4637 (defcustom org-columns-skip-archived-trees t
4638 "Non-nil means ignore archived trees when creating column view."
4639 :group 'org-archive
4640 :group 'org-properties
4641 :type 'boolean)
4643 (defcustom org-cycle-open-archived-trees nil
4644 "Non-nil means `org-cycle' will open archived trees.
4645 An archived tree is a tree marked with the tag ARCHIVE.
4646 When nil, archived trees will stay folded. You can still open them with
4647 normal outline commands like `show-all', but not with the cycling commands."
4648 :group 'org-archive
4649 :group 'org-cycle
4650 :type 'boolean)
4652 (defcustom org-sparse-tree-open-archived-trees nil
4653 "Non-nil means sparse tree construction shows matches in archived trees.
4654 When nil, matches in these trees are highlighted, but the trees are kept in
4655 collapsed state."
4656 :group 'org-archive
4657 :group 'org-sparse-trees
4658 :type 'boolean)
4660 (defcustom org-sparse-tree-default-date-type nil
4661 "The default date type when building a sparse tree.
4662 When this is nil, a date is a scheduled or a deadline timestamp.
4663 Otherwise, these types are allowed:
4665 all: all timestamps
4666 active: only active timestamps (<...>)
4667 inactive: only inactive timestamps ([...])
4668 scheduled: only scheduled timestamps
4669 deadline: only deadline timestamps"
4670 :type '(choice (const :tag "Scheduled or deadline" nil)
4671 (const :tag "All timestamps" all)
4672 (const :tag "Only active timestamps" active)
4673 (const :tag "Only inactive timestamps" inactive)
4674 (const :tag "Only scheduled timestamps" scheduled)
4675 (const :tag "Only deadline timestamps" deadline)
4676 (const :tag "Only closed timestamps" closed))
4677 :version "25.1"
4678 :package-version '(Org . "8.3")
4679 :group 'org-sparse-trees)
4681 (defun org-cycle-hide-archived-subtrees (state)
4682 "Re-hide all archived subtrees after a visibility state change."
4683 (when (and (not org-cycle-open-archived-trees)
4684 (not (memq state '(overview folded))))
4685 (save-excursion
4686 (let* ((globalp (memq state '(contents all)))
4687 (beg (if globalp (point-min) (point)))
4688 (end (if globalp (point-max) (org-end-of-subtree t))))
4689 (org-hide-archived-subtrees beg end)
4690 (goto-char beg)
4691 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4692 (message "%s" (substitute-command-keys
4693 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4695 (defun org-force-cycle-archived ()
4696 "Cycle subtree even if it is archived."
4697 (interactive)
4698 (setq this-command 'org-cycle)
4699 (let ((org-cycle-open-archived-trees t))
4700 (call-interactively 'org-cycle)))
4702 (defun org-hide-archived-subtrees (beg end)
4703 "Re-hide all archived subtrees after a visibility state change."
4704 (org-with-wide-buffer
4705 (let ((case-fold-search nil)
4706 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4707 (goto-char beg)
4708 ;; Include headline point is currently on.
4709 (beginning-of-line)
4710 (while (and (< (point) end) (re-search-forward re end t))
4711 (when (member org-archive-tag (org-get-tags))
4712 (org-flag-subtree t)
4713 (org-end-of-subtree t))))))
4715 (declare-function outline-end-of-heading "outline" ())
4716 (declare-function outline-flag-region "outline" (from to flag))
4717 (defun org-flag-subtree (flag)
4718 (save-excursion
4719 (org-back-to-heading t)
4720 (outline-end-of-heading)
4721 (outline-flag-region (point)
4722 (progn (org-end-of-subtree t) (point))
4723 flag)))
4725 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4727 ;; Declare Column View Code
4729 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4730 (declare-function org-columns-compute "org-colview" (property))
4732 ;; Declare ID code
4734 (declare-function org-id-store-link "org-id")
4735 (declare-function org-id-locations-load "org-id")
4736 (declare-function org-id-locations-save "org-id")
4737 (defvar org-id-track-globally)
4739 ;;; Variables for pre-computed regular expressions, all buffer local
4741 (defvar-local org-todo-regexp nil
4742 "Matches any of the TODO state keywords.")
4743 (defvar-local org-not-done-regexp nil
4744 "Matches any of the TODO state keywords except the last one.")
4745 (defvar-local org-not-done-heading-regexp nil
4746 "Matches a TODO headline that is not done.")
4747 (defvar-local org-todo-line-regexp nil
4748 "Matches a headline and puts TODO state into group 2 if present.")
4749 (defvar-local org-complex-heading-regexp nil
4750 "Matches a headline and puts everything into groups:
4751 group 1: the stars
4752 group 2: The todo keyword, maybe
4753 group 3: Priority cookie
4754 group 4: True headline
4755 group 5: Tags")
4756 (defvar-local org-complex-heading-regexp-format nil
4757 "Printf format to make regexp to match an exact headline.
4758 This regexp will match the headline of any node which has the
4759 exact headline text that is put into the format, but may have any
4760 TODO state, priority and tags.")
4761 (defvar-local org-todo-line-tags-regexp nil
4762 "Matches a headline and puts TODO state into group 2 if present.
4763 Also put tags into group 4 if tags are present.")
4765 (defconst org-plain-time-of-day-regexp
4766 (concat
4767 "\\(\\<[012]?[0-9]"
4768 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4769 "\\(--?"
4770 "\\(\\<[012]?[0-9]"
4771 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4772 "\\)?")
4773 "Regular expression to match a plain time or time range.
4774 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4775 groups carry important information:
4776 0 the full match
4777 1 the first time, range or not
4778 8 the second time, if it is a range.")
4780 (defconst org-plain-time-extension-regexp
4781 (concat
4782 "\\(\\<[012]?[0-9]"
4783 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4784 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4785 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4786 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4787 groups carry important information:
4788 0 the full match
4789 7 hours of duration
4790 9 minutes of duration")
4792 (defconst org-stamp-time-of-day-regexp
4793 (concat
4794 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4795 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4796 "\\(--?"
4797 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4798 "Regular expression to match a timestamp time or time range.
4799 After a match, the following groups carry important information:
4800 0 the full match
4801 1 date plus weekday, for back referencing to make sure both times are on the same day
4802 2 the first time, range or not
4803 4 the second time, if it is a range.")
4805 (defconst org-startup-options
4806 '(("fold" org-startup-folded t)
4807 ("overview" org-startup-folded t)
4808 ("nofold" org-startup-folded nil)
4809 ("showall" org-startup-folded nil)
4810 ("showeverything" org-startup-folded showeverything)
4811 ("content" org-startup-folded content)
4812 ("indent" org-startup-indented t)
4813 ("noindent" org-startup-indented nil)
4814 ("hidestars" org-hide-leading-stars t)
4815 ("showstars" org-hide-leading-stars nil)
4816 ("odd" org-odd-levels-only t)
4817 ("oddeven" org-odd-levels-only nil)
4818 ("align" org-startup-align-all-tables t)
4819 ("noalign" org-startup-align-all-tables nil)
4820 ("inlineimages" org-startup-with-inline-images t)
4821 ("noinlineimages" org-startup-with-inline-images nil)
4822 ("latexpreview" org-startup-with-latex-preview t)
4823 ("nolatexpreview" org-startup-with-latex-preview nil)
4824 ("customtime" org-display-custom-times t)
4825 ("logdone" org-log-done time)
4826 ("lognotedone" org-log-done note)
4827 ("nologdone" org-log-done nil)
4828 ("lognoteclock-out" org-log-note-clock-out t)
4829 ("nolognoteclock-out" org-log-note-clock-out nil)
4830 ("logrepeat" org-log-repeat state)
4831 ("lognoterepeat" org-log-repeat note)
4832 ("logdrawer" org-log-into-drawer t)
4833 ("nologdrawer" org-log-into-drawer nil)
4834 ("logstatesreversed" org-log-states-order-reversed t)
4835 ("nologstatesreversed" org-log-states-order-reversed nil)
4836 ("nologrepeat" org-log-repeat nil)
4837 ("logreschedule" org-log-reschedule time)
4838 ("lognotereschedule" org-log-reschedule note)
4839 ("nologreschedule" org-log-reschedule nil)
4840 ("logredeadline" org-log-redeadline time)
4841 ("lognoteredeadline" org-log-redeadline note)
4842 ("nologredeadline" org-log-redeadline nil)
4843 ("logrefile" org-log-refile time)
4844 ("lognoterefile" org-log-refile note)
4845 ("nologrefile" org-log-refile nil)
4846 ("fninline" org-footnote-define-inline t)
4847 ("nofninline" org-footnote-define-inline nil)
4848 ("fnlocal" org-footnote-section nil)
4849 ("fnauto" org-footnote-auto-label t)
4850 ("fnprompt" org-footnote-auto-label nil)
4851 ("fnconfirm" org-footnote-auto-label confirm)
4852 ("fnplain" org-footnote-auto-label plain)
4853 ("fnadjust" org-footnote-auto-adjust t)
4854 ("nofnadjust" org-footnote-auto-adjust nil)
4855 ("constcgs" constants-unit-system cgs)
4856 ("constSI" constants-unit-system SI)
4857 ("noptag" org-tag-persistent-alist nil)
4858 ("hideblocks" org-hide-block-startup t)
4859 ("nohideblocks" org-hide-block-startup nil)
4860 ("beamer" org-startup-with-beamer-mode t)
4861 ("entitiespretty" org-pretty-entities t)
4862 ("entitiesplain" org-pretty-entities nil))
4863 "Variable associated with STARTUP options for org-mode.
4864 Each element is a list of three items: the startup options (as written
4865 in the #+STARTUP line), the corresponding variable, and the value to set
4866 this variable to if the option is found. An optional forth element PUSH
4867 means to push this value onto the list in the variable.")
4869 (defcustom org-group-tags t
4870 "When non-nil (the default), use group tags.
4871 This can be turned on/off through `org-toggle-tags-groups'."
4872 :group 'org-tags
4873 :group 'org-startup
4874 :type 'boolean)
4876 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4878 (defun org-toggle-tags-groups ()
4879 "Toggle support for group tags.
4880 Support for group tags is controlled by the option
4881 `org-group-tags', which is non-nil by default."
4882 (interactive)
4883 (setq org-group-tags (not org-group-tags))
4884 (cond ((and (derived-mode-p 'org-agenda-mode)
4885 org-group-tags)
4886 (org-agenda-redo))
4887 ((derived-mode-p 'org-mode)
4888 (let ((org-inhibit-startup t)) (org-mode))))
4889 (message "Groups tags support has been turned %s"
4890 (if org-group-tags "on" "off")))
4892 (defun org-set-regexps-and-options (&optional tags-only)
4893 "Precompute regular expressions used in the current buffer.
4894 When optional argument TAGS-ONLY is non-nil, only compute tags
4895 related expressions."
4896 (when (derived-mode-p 'org-mode)
4897 (let ((alist (org--setup-collect-keywords
4898 (org-make-options-regexp
4899 (append '("FILETAGS" "TAGS" "SETUPFILE")
4900 (and (not tags-only)
4901 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4902 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4903 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4904 (org--setup-process-tags
4905 (cdr (assq 'tags alist)) (cdr (assq 'filetags alist)))
4906 (unless tags-only
4907 ;; File properties.
4908 (setq-local org-file-properties (cdr (assq 'property alist)))
4909 ;; Archive location.
4910 (let ((archive (cdr (assq 'archive alist))))
4911 (when archive (setq-local org-archive-location archive)))
4912 ;; Category.
4913 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4914 (when cat
4915 (setq-local org-category (intern cat))
4916 (setq-local org-file-properties
4917 (org--update-property-plist
4918 "CATEGORY" cat org-file-properties))))
4919 ;; Columns.
4920 (let ((column (cdr (assq 'columns alist))))
4921 (when column (setq-local org-columns-default-format column)))
4922 ;; Constants.
4923 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4924 ;; Link abbreviations.
4925 (let ((links (cdr (assq 'link alist))))
4926 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4927 ;; Priorities.
4928 (let ((priorities (cdr (assq 'priorities alist))))
4929 (when priorities
4930 (setq-local org-highest-priority (nth 0 priorities))
4931 (setq-local org-lowest-priority (nth 1 priorities))
4932 (setq-local org-default-priority (nth 2 priorities))))
4933 ;; Scripts.
4934 (let ((scripts (assq 'scripts alist)))
4935 (when scripts
4936 (setq-local org-use-sub-superscripts (cdr scripts))))
4937 ;; Startup options.
4938 (let ((startup (cdr (assq 'startup alist))))
4939 (dolist (option startup)
4940 (let ((entry (assoc-string option org-startup-options t)))
4941 (when entry
4942 (let ((var (nth 1 entry))
4943 (val (nth 2 entry)))
4944 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4945 (unless (listp (symbol-value var))
4946 (set (make-local-variable var) nil))
4947 (add-to-list var val)))))))
4948 ;; TODO keywords.
4949 (setq-local org-todo-kwd-alist nil)
4950 (setq-local org-todo-key-alist nil)
4951 (setq-local org-todo-key-trigger nil)
4952 (setq-local org-todo-keywords-1 nil)
4953 (setq-local org-done-keywords nil)
4954 (setq-local org-todo-heads nil)
4955 (setq-local org-todo-sets nil)
4956 (setq-local org-todo-log-states nil)
4957 (let ((todo-sequences
4958 (or (nreverse (cdr (assq 'todo alist)))
4959 (let ((d (default-value 'org-todo-keywords)))
4960 (if (not (stringp (car d))) d
4961 ;; XXX: Backward compatibility code.
4962 (list (cons org-todo-interpretation d)))))))
4963 (dolist (sequence todo-sequences)
4964 (let* ((sequence (or (run-hook-with-args-until-success
4965 'org-todo-setup-filter-hook sequence)
4966 sequence))
4967 (sequence-type (car sequence))
4968 (keywords (cdr sequence))
4969 (sep (member "|" keywords))
4970 names alist)
4971 (dolist (k (remove "|" keywords))
4972 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
4974 (error "Invalid TODO keyword %s" k))
4975 (let ((name (match-string 1 k))
4976 (key (match-string 2 k))
4977 (log (org-extract-log-state-settings k)))
4978 (push name names)
4979 (push (cons name (and key (string-to-char key))) alist)
4980 (when log (push log org-todo-log-states))))
4981 (let* ((names (nreverse names))
4982 (done (if sep (org-remove-keyword-keys (cdr sep))
4983 (last names)))
4984 (head (car names))
4985 (tail (list sequence-type head (car done) (org-last done))))
4986 (add-to-list 'org-todo-heads head 'append)
4987 (push names org-todo-sets)
4988 (setq org-done-keywords (append org-done-keywords done nil))
4989 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
4990 (setq org-todo-key-alist
4991 (append org-todo-key-alist
4992 (and alist
4993 (append '((:startgroup))
4994 (nreverse alist)
4995 '((:endgroup))))))
4996 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
4997 (setq org-todo-sets (nreverse org-todo-sets)
4998 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4999 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5000 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5001 ;; Compute the regular expressions and other local variables.
5002 ;; Using `org-outline-regexp-bol' would complicate them much,
5003 ;; because of the fixed white space at the end of that string.
5004 (unless org-done-keywords
5005 (setq org-done-keywords
5006 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5007 (setq org-not-done-keywords
5008 (org-delete-all org-done-keywords
5009 (copy-sequence org-todo-keywords-1))
5010 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5011 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5012 org-not-done-heading-regexp
5013 (format org-heading-keyword-regexp-format org-not-done-regexp)
5014 org-todo-line-regexp
5015 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5016 org-complex-heading-regexp
5017 (concat "^\\(\\*+\\)"
5018 "\\(?: +" org-todo-regexp "\\)?"
5019 "\\(?: +\\(\\[#.\\]\\)\\)?"
5020 "\\(?: +\\(.*?\\)\\)??"
5021 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5022 "[ \t]*$")
5023 org-complex-heading-regexp-format
5024 (concat "^\\(\\*+\\)"
5025 "\\(?: +" org-todo-regexp "\\)?"
5026 "\\(?: +\\(\\[#.\\]\\)\\)?"
5027 "\\(?: +"
5028 ;; Stats cookies can be stuck to body.
5029 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5030 "\\(%s\\)"
5031 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5032 "\\)"
5033 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5034 "[ \t]*$")
5035 org-todo-line-tags-regexp
5036 (concat "^\\(\\*+\\)"
5037 "\\(?: +" org-todo-regexp "\\)?"
5038 "\\(?: +\\(.*?\\)\\)??"
5039 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5040 "[ \t]*$"))
5041 (org-compute-latex-and-related-regexp)))))
5043 (defun org--setup-collect-keywords (regexp &optional files alist)
5044 "Return setup keywords values as an alist.
5046 REGEXP matches a subset of setup keywords. FILES is a list of
5047 file names already visited. It is used to avoid circular setup
5048 files. ALIST, when non-nil, is the alist computed so far.
5050 Return value contains the following keys: `archive', `category',
5051 `columns', `constants', `filetags', `link', `priorities',
5052 `property', `scripts', `startup', `tags' and `todo'."
5053 (org-with-wide-buffer
5054 (goto-char (point-min))
5055 (let ((case-fold-search t))
5056 (while (re-search-forward regexp nil t)
5057 (let ((element (org-element-at-point)))
5058 (when (eq (org-element-type element) 'keyword)
5059 (let ((key (org-element-property :key element))
5060 (value (org-element-property :value element)))
5061 (cond
5062 ((equal key "ARCHIVE")
5063 (when (org-string-nw-p value)
5064 (push (cons 'archive value) alist)))
5065 ((equal key "CATEGORY") (push (cons 'category value) alist))
5066 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5067 ((equal key "CONSTANTS")
5068 (let* ((constants (assq 'constants alist))
5069 (store (cdr constants)))
5070 (dolist (pair (org-split-string value))
5071 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5072 pair)
5073 (let* ((name (match-string 1 pair))
5074 (value (match-string 2 pair))
5075 (old (assoc name store)))
5076 (if old (setcdr old value)
5077 (push (cons name value) store)))))
5078 (if constants (setcdr constants store)
5079 (push (cons 'constants store) alist))))
5080 ((equal key "FILETAGS")
5081 (when (org-string-nw-p value)
5082 (let ((old (assq 'filetags alist))
5083 (new (apply #'nconc
5084 (mapcar (lambda (x) (org-split-string x ":"))
5085 (org-split-string value)))))
5086 (if old (setcdr old (append new (cdr old)))
5087 (push (cons 'filetags new) alist)))))
5088 ((equal key "LINK")
5089 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5090 (let ((links (assq 'link alist))
5091 (pair (cons (org-match-string-no-properties 1 value)
5092 (org-match-string-no-properties 2 value))))
5093 (if links (push pair (cdr links))
5094 (push (list 'link pair) alist)))))
5095 ((equal key "OPTIONS")
5096 (when (and (org-string-nw-p value)
5097 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5098 (push (cons 'scripts (read (match-string 1 value))) alist)))
5099 ((equal key "PRIORITIES")
5100 (push (cons 'priorities
5101 (let ((prio (org-split-string value)))
5102 (if (< (length prio) 3) '(?A ?C ?B)
5103 (mapcar #'string-to-char prio))))
5104 alist))
5105 ((equal key "PROPERTY")
5106 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5107 (let* ((property (assq 'property alist))
5108 (value (org--update-property-plist
5109 (org-match-string-no-properties 1 value)
5110 (org-match-string-no-properties 2 value)
5111 (cdr property))))
5112 (if property (setcdr property value)
5113 (push (cons 'property value) alist)))))
5114 ((equal key "STARTUP")
5115 (let ((startup (assq 'startup alist)))
5116 (if startup
5117 (setcdr startup
5118 (append (cdr startup) (org-split-string value)))
5119 (push (cons 'startup (org-split-string value)) alist))))
5120 ((equal key "TAGS")
5121 (let ((tag-cell (assq 'tags alist)))
5122 (if tag-cell
5123 (setcdr tag-cell
5124 (append (cdr tag-cell)
5125 '("\\n")
5126 (org-split-string value)))
5127 (push (cons 'tags (org-split-string value)) alist))))
5128 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5129 (let ((todo (assq 'todo alist))
5130 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5131 (org-split-string value))))
5132 (if todo (push value (cdr todo))
5133 (push (list 'todo value) alist))))
5134 ((equal key "SETUPFILE")
5135 (unless buffer-read-only ; Do not check in Gnus messages.
5136 (let ((f (and (org-string-nw-p value)
5137 (expand-file-name
5138 (org-remove-double-quotes value)))))
5139 (when (and f (file-readable-p f) (not (member f files)))
5140 (with-temp-buffer
5141 (setq default-directory (file-name-directory f))
5142 (insert-file-contents f)
5143 (setq alist
5144 ;; Fake Org mode to benefit from cache
5145 ;; without recurring needlessly.
5146 (let ((major-mode 'org-mode))
5147 (org--setup-collect-keywords
5148 regexp (cons f files) alist)))))))))))))))
5149 alist)
5151 (defun org--setup-process-tags (tags filetags)
5152 "Precompute variables used for tags.
5153 TAGS is a list of tags and tag group symbols, as strings.
5154 FILETAGS is a list of tags, as strings."
5155 ;; Process the file tags.
5156 (setq-local org-file-tags
5157 (mapcar #'org-add-prop-inherited filetags))
5158 ;; Provide default tags if no local tags are found.
5159 (when (and (not tags) org-tag-alist)
5160 (setq tags
5161 (mapcar (lambda (tag)
5162 (cl-case (car tag)
5163 (:startgroup "{")
5164 (:endgroup "}")
5165 (:startgrouptag "[")
5166 (:endgrouptag "]")
5167 (:grouptags ":")
5168 (:newline "\\n")
5169 (otherwise (concat (car tag)
5170 (and (characterp (cdr tag))
5171 (format "(%c)" (cdr tag)))))))
5172 org-tag-alist)))
5173 ;; Process the tags.
5174 (setq-local org-tag-groups-alist nil)
5175 (setq-local org-tag-alist nil)
5176 (let (group-flag)
5177 (while tags
5178 (let ((e (car tags)))
5179 (setq tags (cdr tags))
5180 (cond
5181 ((equal e "{")
5182 (push '(:startgroup) org-tag-alist)
5183 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5184 ((equal e "}")
5185 (push '(:endgroup) org-tag-alist)
5186 (setq group-flag nil))
5187 ((equal e "[")
5188 (push '(:startgrouptag) org-tag-alist)
5189 (when (equal (nth 1 tags) ":") (setq group-flag t)))
5190 ((equal e "]")
5191 (push '(:endgrouptag) org-tag-alist)
5192 (setq group-flag nil))
5193 ((equal e ":")
5194 (push '(:grouptags) org-tag-alist)
5195 (setq group-flag 'append))
5196 ((equal e "\\n") (push '(:newline) org-tag-alist))
5197 ((string-match
5198 (org-re (concat "\\`\\([[:alnum:]_@#%]+"
5199 "\\|{.+?}\\)" ; regular expression
5200 "\\(?:(\\(.\\))\\)?\\'")) e)
5201 (let ((tag (match-string 1 e))
5202 (key (and (match-beginning 2)
5203 (string-to-char (match-string 2 e)))))
5204 (cond ((eq group-flag 'append)
5205 (setcar org-tag-groups-alist
5206 (append (car org-tag-groups-alist) (list tag))))
5207 (group-flag (push (list tag) org-tag-groups-alist)))
5208 ;; Push all tags in groups, no matter if they already exist.
5209 (unless (and (not group-flag) (assoc tag org-tag-alist))
5210 (push (cons tag key) org-tag-alist))))))))
5211 (setq org-tag-alist (nreverse org-tag-alist)))
5213 (defun org-file-contents (file &optional noerror)
5214 "Return the contents of FILE, as a string."
5215 (if (and file (file-readable-p file))
5216 (with-temp-buffer
5217 (insert-file-contents file)
5218 (buffer-string))
5219 (funcall (if noerror 'message 'error)
5220 "Cannot read file \"%s\"%s"
5221 file
5222 (let ((from (buffer-file-name (buffer-base-buffer))))
5223 (if from (concat " (referenced in file \"" from "\")") "")))))
5225 (defun org-extract-log-state-settings (x)
5226 "Extract the log state setting from a TODO keyword string.
5227 This will extract info from a string like \"WAIT(w@/!)\"."
5228 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5229 (let ((kw (match-string 1 x))
5230 (log1 (and (match-end 3) (match-string 3 x)))
5231 (log2 (and (match-end 4) (match-string 4 x))))
5232 (and (or log1 log2)
5233 (list kw
5234 (and log1 (if (equal log1 "!") 'time 'note))
5235 (and log2 (if (equal log2 "!") 'time 'note)))))))
5237 (defun org-remove-keyword-keys (list)
5238 "Remove a pair of parenthesis at the end of each string in LIST."
5239 (mapcar (lambda (x)
5240 (if (string-match "(.*)$" x)
5241 (substring x 0 (match-beginning 0))
5243 list))
5245 (defun org-assign-fast-keys (alist)
5246 "Assign fast keys to a keyword-key alist.
5247 Respect keys that are already there."
5248 (let (new e (alt ?0))
5249 (while (setq e (pop alist))
5250 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5251 (cdr e)) ;; Key already assigned.
5252 (push e new)
5253 (let ((clist (string-to-list (downcase (car e))))
5254 (used (append new alist)))
5255 (when (= (car clist) ?@)
5256 (pop clist))
5257 (while (and clist (rassoc (car clist) used))
5258 (pop clist))
5259 (unless clist
5260 (while (rassoc alt used)
5261 (cl-incf alt)))
5262 (push (cons (car e) (or (car clist) alt)) new))))
5263 (nreverse new)))
5265 ;;; Some variables used in various places
5267 (defvar org-window-configuration nil
5268 "Used in various places to store a window configuration.")
5269 (defvar org-selected-window nil
5270 "Used in various places to store a window configuration.")
5271 (defvar org-finish-function nil
5272 "Function to be called when `C-c C-c' is used.
5273 This is for getting out of special buffers like capture.")
5274 (defvar org-last-state)
5276 ;; Defined somewhere in this file, but used before definition.
5277 (defvar org-entities) ;; defined in org-entities.el
5278 (defvar org-struct-menu)
5279 (defvar org-org-menu)
5280 (defvar org-tbl-menu)
5282 ;;;; Define the Org-mode
5284 ;; We use a before-change function to check if a table might need
5285 ;; an update.
5286 (defvar org-table-may-need-update t
5287 "Indicates that a table might need an update.
5288 This variable is set by `org-before-change-function'.
5289 `org-table-align' sets it back to nil.")
5290 (defun org-before-change-function (_beg _end)
5291 "Every change indicates that a table might need an update."
5292 (setq org-table-may-need-update t))
5293 (defvar org-mode-map)
5294 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5295 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5296 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5297 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5298 (defvar org-table-buffer-is-an nil)
5300 (defvar bidi-paragraph-direction)
5301 (defvar buffer-face-mode-face)
5303 (require 'outline)
5304 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5305 (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"))
5306 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5308 ;; Other stuff we need.
5309 (require 'time-date)
5310 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5311 (require 'easymenu)
5312 (autoload 'easy-menu-add "easymenu")
5313 (require 'overlay)
5315 ;; (require 'org-macs) moved higher up in the file before it is first used
5316 (require 'org-entities)
5317 ;; (require 'org-compat) moved higher up in the file before it is first used
5318 (require 'org-faces)
5319 (require 'org-list)
5320 (require 'org-pcomplete)
5321 (require 'org-src)
5322 (require 'org-footnote)
5323 (require 'org-macro)
5325 ;; babel
5326 (require 'ob)
5328 ;;;###autoload
5329 (define-derived-mode org-mode outline-mode "Org"
5330 "Outline-based notes management and organizer, alias
5331 \"Carsten's outline-mode for keeping track of everything.\"
5333 Org-mode develops organizational tasks around a NOTES file which
5334 contains information about projects as plain text. Org-mode is
5335 implemented on top of outline-mode, which is ideal to keep the content
5336 of large files well structured. It supports ToDo items, deadlines and
5337 time stamps, which magically appear in the diary listing of the Emacs
5338 calendar. Tables are easily created with a built-in table editor.
5339 Plain text URL-like links connect to websites, emails (VM), Usenet
5340 messages (Gnus), BBDB entries, and any files related to the project.
5341 For printing and sharing of notes, an Org-mode file (or a part of it)
5342 can be exported as a structured ASCII or HTML file.
5344 The following commands are available:
5346 \\{org-mode-map}"
5348 ;; Get rid of Outline menus, they are not needed
5349 ;; Need to do this here because define-derived-mode sets up
5350 ;; the keymap so late. Still, it is a waste to call this each time
5351 ;; we switch another buffer into org-mode.
5352 (if (featurep 'xemacs)
5353 (when (boundp 'outline-mode-menu-heading)
5354 ;; Assume this is Greg's port, it uses easymenu
5355 (easy-menu-remove outline-mode-menu-heading)
5356 (easy-menu-remove outline-mode-menu-show)
5357 (easy-menu-remove outline-mode-menu-hide))
5358 (define-key org-mode-map [menu-bar headings] 'undefined)
5359 (define-key org-mode-map [menu-bar hide] 'undefined)
5360 (define-key org-mode-map [menu-bar show] 'undefined))
5362 (org-load-modules-maybe)
5363 (when (featurep 'xemacs)
5364 (easy-menu-add org-org-menu)
5365 (easy-menu-add org-tbl-menu))
5366 (org-install-agenda-files-menu)
5367 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5368 (add-to-invisibility-spec '(org-cwidth))
5369 (add-to-invisibility-spec '(org-hide-block . t))
5370 (when (featurep 'xemacs)
5371 (setq-local line-move-ignore-invisible t))
5372 (setq-local outline-regexp org-outline-regexp)
5373 (setq-local outline-level 'org-outline-level)
5374 (setq bidi-paragraph-direction 'left-to-right)
5375 (when (and org-ellipsis
5376 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5377 (fboundp 'make-glyph-code))
5378 (unless org-display-table
5379 (setq org-display-table (make-display-table)))
5380 (set-display-table-slot
5381 org-display-table 4
5382 (vconcat (mapcar
5383 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5384 org-ellipsis)))
5385 (if (stringp org-ellipsis) org-ellipsis "..."))))
5386 (setq buffer-display-table org-display-table))
5387 (org-set-regexps-and-options)
5388 (org-set-font-lock-defaults)
5389 (when (and org-tag-faces (not org-tags-special-faces-re))
5390 ;; tag faces set outside customize.... force initialization.
5391 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5392 ;; Calc embedded
5393 (setq-local calc-embedded-open-mode "# ")
5394 ;; Modify a few syntax entries
5395 (modify-syntax-entry ?@ "w")
5396 (modify-syntax-entry ?\" "\"")
5397 (modify-syntax-entry ?\\ "_")
5398 (modify-syntax-entry ?~ "_")
5399 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5400 ;; Activate before-change-function
5401 (setq-local org-table-may-need-update t)
5402 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5403 ;; Check for running clock before killing a buffer
5404 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5405 ;; Initialize macros templates.
5406 (org-macro-initialize-templates)
5407 ;; Initialize radio targets.
5408 (org-update-radio-target-regexp)
5409 ;; Indentation.
5410 (setq-local indent-line-function 'org-indent-line)
5411 (setq-local indent-region-function 'org-indent-region)
5412 ;; Filling and auto-filling.
5413 (org-setup-filling)
5414 ;; Comments.
5415 (org-setup-comments-handling)
5416 ;; Initialize cache.
5417 (org-element-cache-reset)
5418 ;; Beginning/end of defun
5419 (setq-local beginning-of-defun-function 'org-backward-element)
5420 (setq-local end-of-defun-function
5421 (lambda ()
5422 (if (not (org-at-heading-p))
5423 (org-forward-element)
5424 (org-forward-element)
5425 (forward-char -1))))
5426 ;; Next error for sparse trees
5427 (setq-local next-error-function 'org-occur-next-match)
5428 ;; Make sure dependence stuff works reliably, even for users who set it
5429 ;; too late :-(
5430 (if org-enforce-todo-dependencies
5431 (add-hook 'org-blocker-hook
5432 'org-block-todo-from-children-or-siblings-or-parent)
5433 (remove-hook 'org-blocker-hook
5434 'org-block-todo-from-children-or-siblings-or-parent))
5435 (if org-enforce-todo-checkbox-dependencies
5436 (add-hook 'org-blocker-hook
5437 'org-block-todo-from-checkboxes)
5438 (remove-hook 'org-blocker-hook
5439 'org-block-todo-from-checkboxes))
5441 ;; Align options lines
5442 (setq-local
5443 align-mode-rules-list
5444 '((org-in-buffer-settings
5445 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5446 (modes . '(org-mode)))))
5448 ;; Imenu
5449 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5451 ;; Make isearch reveal context
5452 (setq-local outline-isearch-open-invisible-function
5453 (lambda (&rest _) (org-show-context 'isearch)))
5455 ;; Setup the pcomplete hooks
5456 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5457 (setq-local pcomplete-command-name-function 'org-command-at-point)
5458 (setq-local pcomplete-default-completion-function 'ignore)
5459 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5460 (setq-local pcomplete-termination-string "")
5461 (setq-local buffer-face-mode-face 'org-default)
5463 ;; If empty file that did not turn on Org mode automatically, make
5464 ;; it to.
5465 (when (and org-insert-mode-line-in-empty-file
5466 (org-called-interactively-p 'any)
5467 (= (point-min) (point-max)))
5468 (insert "# -*- mode: org -*-\n\n"))
5469 (unless org-inhibit-startup
5470 (org-unmodified
5471 (when org-startup-with-beamer-mode (org-beamer-mode))
5472 (when org-startup-align-all-tables
5473 (org-table-map-tables #'org-table-align t))
5474 (when org-startup-with-inline-images (org-display-inline-images))
5475 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5476 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5477 (when org-startup-truncated (setq truncate-lines t))
5478 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5479 (org-refresh-effort-properties)))
5480 ;; Try to set `org-hide' face correctly.
5481 (let ((foreground (org-find-invisible-foreground)))
5482 (when foreground
5483 (set-face-foreground 'org-hide foreground))))
5485 ;; Update `customize-package-emacs-version-alist'
5486 (add-to-list 'customize-package-emacs-version-alist
5487 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5488 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5489 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5491 (defvar org-mode-transpose-word-syntax-table
5492 (let ((st (make-syntax-table text-mode-syntax-table)))
5493 (dolist (c org-emphasis-alist st)
5494 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5496 (when (fboundp 'abbrev-table-put)
5497 (abbrev-table-put org-mode-abbrev-table
5498 :parents (list text-mode-abbrev-table)))
5500 (defun org-find-invisible-foreground ()
5501 (let ((candidates (remove
5502 "unspecified-bg"
5503 (nconc
5504 (list (face-background 'default)
5505 (face-background 'org-default))
5506 (mapcar
5507 (lambda (alist)
5508 (when (boundp alist)
5509 (cdr (assoc 'background-color (symbol-value alist)))))
5510 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5511 (list (face-foreground 'org-hide))))))
5512 (car (remove nil candidates))))
5514 (defun org-current-time (&optional rounding-minutes past)
5515 "Current time, possibly rounded to ROUNDING-MINUTES.
5516 When ROUNDING-MINUTES is not an integer, fall back on the car of
5517 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5518 the rounding returns a past time."
5519 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5520 (car org-time-stamp-rounding-minutes)))
5521 (time (decode-time)) res)
5522 (if (< r 1)
5523 (current-time)
5524 (setq res
5525 (apply 'encode-time
5526 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5527 (nthcdr 2 time))))
5528 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5529 (seconds-to-time (- (org-float-time res) (* r 60)))
5530 res))))
5532 (defun org-today ()
5533 "Return today date, considering `org-extend-today-until'."
5534 (time-to-days
5535 (time-subtract (current-time)
5536 (list 0 (* 3600 org-extend-today-until) 0))))
5538 ;;;; Font-Lock stuff, including the activators
5540 (defvar org-mouse-map (make-sparse-keymap))
5541 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5542 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5543 (when org-mouse-1-follows-link
5544 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5545 (when org-tab-follows-link
5546 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5547 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5549 (require 'font-lock)
5551 (defconst org-non-link-chars "]\t\n\r<>")
5552 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5553 "file+sys" "news" "shell" "elisp" "doi" "message"
5554 "help"))
5555 (defvar org-link-types-re nil
5556 "Matches a link that has a url-like prefix like \"http:\"")
5557 (defvar org-link-re-with-space nil
5558 "Matches a link with spaces, optional angular brackets around it.")
5559 (defvar org-link-re-with-space2 nil
5560 "Matches a link with spaces, optional angular brackets around it.")
5561 (defvar org-link-re-with-space3 nil
5562 "Matches a link with spaces, only for internal part in bracket links.")
5563 (defvar org-angle-link-re nil
5564 "Matches link with angular brackets, spaces are allowed.")
5565 (defvar org-plain-link-re nil
5566 "Matches plain link, without spaces.")
5567 (defvar org-bracket-link-regexp nil
5568 "Matches a link in double brackets.")
5569 (defvar org-bracket-link-analytic-regexp nil
5570 "Regular expression used to analyze links.
5571 Here is what the match groups contain after a match:
5572 1: http:
5573 2: http
5574 3: path
5575 4: [desc]
5576 5: desc")
5577 (defvar org-bracket-link-analytic-regexp++ nil
5578 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5579 (defvar org-any-link-re nil
5580 "Regular expression matching any link.")
5582 (defconst org-match-sexp-depth 3
5583 "Number of stacked braces for sub/superscript matching.")
5585 (defun org-create-multibrace-regexp (left right n)
5586 "Create a regular expression which will match a balanced sexp.
5587 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5588 as single character strings.
5589 The regexp returned will match the entire expression including the
5590 delimiters. It will also define a single group which contains the
5591 match except for the outermost delimiters. The maximum depth of
5592 stacked delimiters is N. Escaping delimiters is not possible."
5593 (let* ((nothing (concat "[^" left right "]*?"))
5594 (or "\\|")
5595 (re nothing)
5596 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5597 (while (> n 1)
5598 (setq n (1- n)
5599 re (concat re or next)
5600 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5601 (concat left "\\(" re "\\)" right)))
5603 (defconst org-match-substring-regexp
5604 (concat
5605 "\\(\\S-\\)\\([_^]\\)\\("
5606 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5607 "\\|"
5608 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5609 "\\|"
5610 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5611 "The regular expression matching a sub- or superscript.")
5613 (defconst org-match-substring-with-braces-regexp
5614 (concat
5615 "\\(\\S-\\)\\([_^]\\)"
5616 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5617 "The regular expression matching a sub- or superscript, forcing braces.")
5619 (defun org-make-link-regexps ()
5620 "Update the link regular expressions.
5621 This should be called after the variable `org-link-types' has changed."
5622 (let ((types-re (regexp-opt org-link-types t)))
5623 (setq org-link-types-re
5624 (concat "\\`" types-re ":")
5625 org-link-re-with-space
5626 (concat "<?" types-re ":"
5627 "\\([^" org-non-link-chars " ]"
5628 "[^" org-non-link-chars "]*"
5629 "[^" org-non-link-chars " ]\\)>?")
5630 org-link-re-with-space2
5631 (concat "<?" types-re ":"
5632 "\\([^" org-non-link-chars " ]"
5633 "[^\t\n\r]*"
5634 "[^" org-non-link-chars " ]\\)>?")
5635 org-link-re-with-space3
5636 (concat "<?" types-re ":"
5637 "\\([^" org-non-link-chars " ]"
5638 "[^\t\n\r]*\\)")
5639 org-angle-link-re
5640 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5641 types-re)
5642 org-plain-link-re
5643 (concat
5644 "\\<" types-re ":"
5645 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5646 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5647 org-bracket-link-regexp
5648 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5649 org-bracket-link-analytic-regexp
5650 (concat
5651 "\\[\\["
5652 "\\(" types-re ":\\)?"
5653 "\\([^]]+\\)"
5654 "\\]"
5655 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5656 "\\]")
5657 org-bracket-link-analytic-regexp++
5658 (concat
5659 "\\[\\["
5660 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5661 "\\([^]]+\\)"
5662 "\\]"
5663 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5664 "\\]")
5665 org-any-link-re
5666 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5667 org-angle-link-re "\\)\\|\\("
5668 org-plain-link-re "\\)"))))
5670 (org-make-link-regexps)
5672 (defvar org-emph-face nil)
5674 (defun org-do-emphasis-faces (limit)
5675 "Run through the buffer and emphasize strings."
5676 (let (rtn a)
5677 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5678 (let* ((border (char-after (match-beginning 3)))
5679 (bre (regexp-quote (char-to-string border))))
5680 (when (and (not (= border (char-after (match-beginning 4))))
5681 (not (string-match-p (concat bre ".*" bre)
5682 (replace-regexp-in-string
5683 "\n" " "
5684 (substring (match-string 2) 1 -1)))))
5685 (setq rtn t)
5686 (setq a (assoc (match-string 3) org-emphasis-alist))
5687 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5688 'face
5689 (nth 1 a))
5690 (and (nth 2 a)
5691 (org-remove-flyspell-overlays-in
5692 (match-beginning 0) (match-end 0)))
5693 (add-text-properties (match-beginning 2) (match-end 2)
5694 '(font-lock-multiline t org-emphasis t))
5695 (when org-hide-emphasis-markers
5696 (add-text-properties (match-end 4) (match-beginning 5)
5697 '(invisible org-link))
5698 (add-text-properties (match-beginning 3) (match-end 3)
5699 '(invisible org-link)))))
5700 (goto-char (1+ (match-beginning 0))))
5701 rtn))
5703 (defun org-emphasize (&optional char)
5704 "Insert or change an emphasis, i.e. a font like bold or italic.
5705 If there is an active region, change that region to a new emphasis.
5706 If there is no region, just insert the marker characters and position
5707 the cursor between them.
5708 CHAR should be the marker character. If it is a space, it means to
5709 remove the emphasis of the selected region.
5710 If CHAR is not given (for example in an interactive call) it will be
5711 prompted for."
5712 (interactive)
5713 (let ((erc org-emphasis-regexp-components)
5714 (string "") beg end move s)
5715 (if (org-region-active-p)
5716 (setq beg (region-beginning)
5717 end (region-end)
5718 string (buffer-substring beg end))
5719 (setq move t))
5721 (unless char
5722 (message "Emphasis marker or tag: [%s]"
5723 (mapconcat #'car org-emphasis-alist ""))
5724 (setq char (read-char-exclusive)))
5725 (if (equal char ?\s)
5726 (setq s ""
5727 move nil)
5728 (unless (assoc (char-to-string char) org-emphasis-alist)
5729 (user-error "No such emphasis marker: \"%c\"" char))
5730 (setq s (char-to-string char)))
5731 (while (and (> (length string) 1)
5732 (equal (substring string 0 1) (substring string -1))
5733 (assoc (substring string 0 1) org-emphasis-alist))
5734 (setq string (substring string 1 -1)))
5735 (setq string (concat s string s))
5736 (when beg (delete-region beg end))
5737 (unless (or (bolp)
5738 (string-match (concat "[" (nth 0 erc) "\n]")
5739 (char-to-string (char-before (point)))))
5740 (insert " "))
5741 (unless (or (eobp)
5742 (string-match (concat "[" (nth 1 erc) "\n]")
5743 (char-to-string (char-after (point)))))
5744 (insert " ") (backward-char 1))
5745 (insert string)
5746 (and move (backward-char 1))))
5748 (defconst org-nonsticky-props
5749 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5751 (defsubst org-rear-nonsticky-at (pos)
5752 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5754 (defun org-activate-plain-links (limit)
5755 "Add link properties for plain links."
5756 (when (and (re-search-forward org-plain-link-re limit t)
5757 (not (org-in-src-block-p)))
5758 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5759 'face))
5760 (link (org-match-string-no-properties 0)))
5761 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5762 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5763 (add-text-properties (match-beginning 0) (match-end 0)
5764 (list 'mouse-face 'highlight
5765 'face 'org-link
5766 'htmlize-link `(:uri ,link)
5767 'keymap org-mouse-map))
5768 (org-rear-nonsticky-at (match-end 0))
5769 t))))
5771 (defun org-activate-code (limit)
5772 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5773 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5774 (remove-text-properties (match-beginning 0) (match-end 0)
5775 '(display t invisible t intangible t))
5778 (defcustom org-src-fontify-natively t
5779 "When non-nil, fontify code in code blocks."
5780 :type 'boolean
5781 :version "24.4"
5782 :package-version '(Org . "8.3")
5783 :group 'org-appearance
5784 :group 'org-babel)
5786 (defcustom org-allow-promoting-top-level-subtree nil
5787 "When non-nil, allow promoting a top level subtree.
5788 The leading star of the top level headline will be replaced
5789 by a #."
5790 :type 'boolean
5791 :version "24.1"
5792 :group 'org-appearance)
5794 (defun org-fontify-meta-lines-and-blocks (limit)
5795 (condition-case nil
5796 (org-fontify-meta-lines-and-blocks-1 limit)
5797 (error (message "org-mode fontification error"))))
5799 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5800 "Fontify #+ lines and blocks."
5801 (let ((case-fold-search t))
5802 (when (re-search-forward
5803 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5804 limit t)
5805 (let ((beg (match-beginning 0))
5806 (block-start (match-end 0))
5807 (block-end nil)
5808 (lang (match-string 7))
5809 (beg1 (line-beginning-position 2))
5810 (dc1 (downcase (match-string 2)))
5811 (dc3 (downcase (match-string 3)))
5812 end end1 quoting block-type)
5813 (cond
5814 ((and (match-end 4) (equal dc3 "+begin"))
5815 ;; Truly a block
5816 (setq block-type (downcase (match-string 5))
5817 quoting (member block-type org-protecting-blocks))
5818 (when (re-search-forward
5819 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5820 nil t) ;; on purpose, we look further than LIMIT
5821 (setq end (min (point-max) (match-end 0))
5822 end1 (min (point-max) (1- (match-beginning 0))))
5823 (setq block-end (match-beginning 0))
5824 (when quoting
5825 (org-remove-flyspell-overlays-in beg1 end1)
5826 (remove-text-properties beg end
5827 '(display t invisible t intangible t)))
5828 (add-text-properties
5829 beg end '(font-lock-fontified t font-lock-multiline t))
5830 (add-text-properties beg beg1 '(face org-meta-line))
5831 (org-remove-flyspell-overlays-in beg beg1)
5832 (add-text-properties ; For end_src
5833 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5834 (org-remove-flyspell-overlays-in end1 end)
5835 (cond
5836 ((and lang (not (string= lang "")) org-src-fontify-natively)
5837 (org-src-font-lock-fontify-block lang block-start block-end)
5838 (add-text-properties beg1 block-end '(src-block t)))
5839 (quoting
5840 (add-text-properties beg1 (min (point-max) (1+ end1))
5841 '(face org-block))) ; end of source block
5842 ((not org-fontify-quote-and-verse-blocks))
5843 ((string= block-type "quote")
5844 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5845 ((string= block-type "verse")
5846 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5847 (add-text-properties beg beg1 '(face org-block-begin-line))
5848 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5849 '(face org-block-end-line))
5851 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5852 (org-remove-flyspell-overlays-in
5853 (match-beginning 0)
5854 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5855 (add-text-properties
5856 beg (match-end 3)
5857 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5858 '(font-lock-fontified t invisible t)
5859 '(font-lock-fontified t face org-document-info-keyword)))
5860 (add-text-properties
5861 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5862 (if (string-equal dc1 "+title:")
5863 '(font-lock-fontified t face org-document-title)
5864 '(font-lock-fontified t face org-document-info))))
5865 ((equal dc1 "+caption:")
5866 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5867 (remove-text-properties (match-beginning 0) (match-end 0)
5868 '(display t invisible t intangible t))
5869 (add-text-properties (match-beginning 1) (match-end 3)
5870 '(font-lock-fontified t face org-meta-line))
5871 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5872 '(font-lock-fontified t face org-block))
5874 ((member dc3 '(" " ""))
5875 (org-remove-flyspell-overlays-in beg (match-end 0))
5876 (add-text-properties
5877 beg (match-end 0)
5878 '(font-lock-fontified t face font-lock-comment-face)))
5879 (t ;; just any other in-buffer setting, but not indented
5880 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5881 (remove-text-properties (match-beginning 0) (match-end 0)
5882 '(display t invisible t intangible t))
5883 (add-text-properties beg (match-end 0)
5884 '(font-lock-fontified t face org-meta-line))
5885 t))))))
5887 (defun org-fontify-drawers (limit)
5888 "Fontify drawers."
5889 (when (re-search-forward org-drawer-regexp limit t)
5890 (add-text-properties
5891 (match-beginning 0) (match-end 0)
5892 '(font-lock-fontified t face org-special-keyword))
5893 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5896 (defun org-fontify-macros (limit)
5897 "Fontify macros."
5898 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5899 (add-text-properties
5900 (match-beginning 0) (match-end 0)
5901 '(font-lock-fontified t face org-macro))
5902 (when org-hide-macro-markers
5903 (add-text-properties (match-end 2) (match-beginning 2)
5904 '(invisible t))
5905 (add-text-properties (match-beginning 1) (match-end 1)
5906 '(invisible t)))
5907 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5910 (defun org-activate-angle-links (limit)
5911 "Add text properties for angle links."
5912 (when (and (re-search-forward org-angle-link-re limit t)
5913 (not (org-in-src-block-p)))
5914 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5915 (add-text-properties (match-beginning 0) (match-end 0)
5916 (list 'mouse-face 'highlight
5917 'keymap org-mouse-map
5918 'font-lock-multiline t))
5919 (org-rear-nonsticky-at (match-end 0))
5922 (defun org-activate-footnote-links (limit)
5923 "Add text properties for footnotes."
5924 (let ((fn (org-footnote-next-reference-or-definition limit)))
5925 (when fn
5926 (let* ((beg (nth 1 fn))
5927 (end (nth 2 fn))
5928 (label (car fn))
5929 (referencep (/= (line-beginning-position) beg)))
5930 (when (and referencep (nth 3 fn))
5931 (save-excursion
5932 (goto-char beg)
5933 (search-forward (or label "fn:"))
5934 (org-remove-flyspell-overlays-in beg (match-end 0))))
5935 (add-text-properties beg end
5936 (list 'mouse-face 'highlight
5937 'keymap org-mouse-map
5938 'help-echo
5939 (if referencep "Footnote reference"
5940 "Footnote definition")
5941 'font-lock-fontified t
5942 'font-lock-multiline t
5943 'face 'org-footnote))))))
5945 (defun org-activate-bracket-links (limit)
5946 "Add text properties for bracketed links."
5947 (when (and (re-search-forward org-bracket-link-regexp limit t)
5948 (not (org-in-src-block-p)))
5949 (let* ((hl (org-match-string-no-properties 1))
5950 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
5951 (ip (org-maybe-intangible
5952 (list 'invisible 'org-link
5953 'keymap org-mouse-map 'mouse-face 'highlight
5954 'font-lock-multiline t 'help-echo help
5955 'htmlize-link `(:uri ,hl))))
5956 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
5957 'font-lock-multiline t 'help-echo help
5958 'htmlize-link `(:uri ,hl))))
5959 ;; We need to remove the invisible property here. Table narrowing
5960 ;; may have made some of this invisible.
5961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5962 (remove-text-properties (match-beginning 0) (match-end 0)
5963 '(invisible nil))
5964 (if (match-end 3)
5965 (progn
5966 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
5967 (org-rear-nonsticky-at (match-beginning 3))
5968 (add-text-properties (match-beginning 3) (match-end 3) vp)
5969 (org-rear-nonsticky-at (match-end 3))
5970 (add-text-properties (match-end 3) (match-end 0) ip)
5971 (org-rear-nonsticky-at (match-end 0)))
5972 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
5973 (org-rear-nonsticky-at (match-beginning 1))
5974 (add-text-properties (match-beginning 1) (match-end 1) vp)
5975 (org-rear-nonsticky-at (match-end 1))
5976 (add-text-properties (match-end 1) (match-end 0) ip)
5977 (org-rear-nonsticky-at (match-end 0)))
5978 t)))
5980 (defun org-activate-dates (limit)
5981 "Add text properties for dates."
5982 (when (and (re-search-forward org-tsr-regexp-both limit t)
5983 (not (equal (char-before (match-beginning 0)) 91)))
5984 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5985 (add-text-properties (match-beginning 0) (match-end 0)
5986 (list 'mouse-face 'highlight
5987 'keymap org-mouse-map))
5988 (org-rear-nonsticky-at (match-end 0))
5989 (when org-display-custom-times
5990 (if (match-end 3)
5991 (org-display-custom-time (match-beginning 3) (match-end 3))
5992 (org-display-custom-time (match-beginning 1) (match-end 1))))
5995 (defvar-local org-target-link-regexp nil
5996 "Regular expression matching radio targets in plain text.")
5998 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
5999 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6000 border border border))
6001 "Regular expression matching a link target.")
6003 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6004 "Regular expression matching a radio target.")
6006 (defconst org-any-target-regexp
6007 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6008 "Regular expression matching any target.")
6010 (defun org-activate-target-links (limit)
6011 "Add text properties for target matches."
6012 (when org-target-link-regexp
6013 (let ((case-fold-search t))
6014 (when (re-search-forward org-target-link-regexp limit t)
6015 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6016 (add-text-properties (match-beginning 1) (match-end 1)
6017 (list 'mouse-face 'highlight
6018 'keymap org-mouse-map
6019 'help-echo "Radio target link"
6020 'org-linked-text t))
6021 (org-rear-nonsticky-at (match-end 1))
6022 t))))
6024 (defun org-update-radio-target-regexp ()
6025 "Find all radio targets in this file and update the regular expression.
6026 Also refresh fontification if needed."
6027 (interactive)
6028 (let ((old-regexp org-target-link-regexp)
6029 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6030 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6031 (targets
6032 (org-with-wide-buffer
6033 (goto-char (point-min))
6034 (let (rtn)
6035 (while (re-search-forward org-radio-target-regexp nil t)
6036 ;; Make sure point is really within the object.
6037 (backward-char)
6038 (let ((obj (org-element-context)))
6039 (when (eq (org-element-type obj) 'radio-target)
6040 (cl-pushnew (org-element-property :value obj) rtn
6041 :test #'equal))))
6042 rtn))))
6043 (setq org-target-link-regexp
6044 (and targets
6045 (concat before-re
6046 (mapconcat
6047 (lambda (x)
6048 (replace-regexp-in-string
6049 " +" "\\s-+" (regexp-quote x) t t))
6050 targets
6051 "\\|")
6052 after-re)))
6053 (unless (equal old-regexp org-target-link-regexp)
6054 ;; Clean-up cache.
6055 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6056 ((not org-target-link-regexp) old-regexp)
6058 (concat before-re
6059 (mapconcat
6060 (lambda (re)
6061 (substring re (length before-re)
6062 (- (length after-re))))
6063 (list old-regexp org-target-link-regexp)
6064 "\\|")
6065 after-re)))))
6066 (org-with-wide-buffer
6067 (goto-char (point-min))
6068 (while (re-search-forward regexp nil t)
6069 (org-element-cache-refresh (match-beginning 1)))))
6070 ;; Re fontify buffer.
6071 (when (memq 'radio org-highlight-links)
6072 (org-restart-font-lock)))))
6074 (defun org-hide-wide-columns (limit)
6075 (let (s e)
6076 (setq s (text-property-any (point) (or limit (point-max))
6077 'org-cwidth t))
6078 (when s
6079 (setq e (next-single-property-change s 'org-cwidth))
6080 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6081 (goto-char e)
6082 t)))
6084 (defvar org-latex-and-related-regexp nil
6085 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6087 (defun org-compute-latex-and-related-regexp ()
6088 "Compute regular expression for LaTeX, entities and sub/superscript.
6089 Result depends on variable `org-highlight-latex-and-related'."
6090 (setq-local
6091 org-latex-and-related-regexp
6092 (let* ((re-sub
6093 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6094 ((eq org-use-sub-superscripts '{})
6095 (list org-match-substring-with-braces-regexp))
6096 (org-use-sub-superscripts (list org-match-substring-regexp))))
6097 (re-latex
6098 (when (memq 'latex org-highlight-latex-and-related)
6099 (let ((matchers (plist-get org-format-latex-options :matchers)))
6100 (delq nil
6101 (mapcar (lambda (x)
6102 (and (member (car x) matchers) (nth 1 x)))
6103 org-latex-regexps)))))
6104 (re-entities
6105 (when (memq 'entities org-highlight-latex-and-related)
6106 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6107 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6109 (defun org-do-latex-and-related (limit)
6110 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6111 LIMIT bounds the search for syntax to highlight. Stop at first
6112 highlighted object, if any. Return t if some highlighting was
6113 done, nil otherwise."
6114 (when (org-string-nw-p org-latex-and-related-regexp)
6115 (catch 'found
6116 (while (re-search-forward org-latex-and-related-regexp limit t)
6117 (unless
6118 (cl-some
6119 (lambda (f)
6120 (memq f '(org-code org-verbatim underline org-special-keyword)))
6121 (save-excursion
6122 (goto-char (1+ (match-beginning 0)))
6123 (face-at-point nil t)))
6124 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6125 '(?_ ?^))
6127 0)))
6128 (font-lock-prepend-text-property
6129 (+ offset (match-beginning 0)) (match-end 0)
6130 'face 'org-latex-and-related)
6131 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6132 '(font-lock-multiline t)))
6133 (throw 'found t)))
6134 nil)))
6136 (defun org-restart-font-lock ()
6137 "Restart `font-lock-mode', to force refontification."
6138 (when (and (boundp 'font-lock-mode) font-lock-mode)
6139 (font-lock-mode -1)
6140 (font-lock-mode 1)))
6142 (defun org-activate-tags (limit)
6143 (when (re-search-forward
6144 (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") limit t)
6145 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6146 (add-text-properties (match-beginning 1) (match-end 1)
6147 (list 'mouse-face 'highlight
6148 'keymap org-mouse-map))
6149 (org-rear-nonsticky-at (match-end 1))
6152 (defun org-outline-level ()
6153 "Compute the outline level of the heading at point.
6155 If this is called at a normal headline, the level is the number
6156 of stars. Use `org-reduced-level' to remove the effect of
6157 `org-odd-levels'. Unlike to `org-current-level', this function
6158 takes into consideration inlinetasks."
6159 (org-with-wide-buffer
6160 (end-of-line)
6161 (if (re-search-backward org-outline-regexp-bol nil t)
6162 (1- (- (match-end 0) (match-beginning 0)))
6163 0)))
6165 (defvar org-font-lock-keywords nil)
6167 (defsubst org-re-property (property &optional literal allow-null value)
6168 "Return a regexp matching a PROPERTY line.
6170 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6171 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6172 non-nil, match properties even without a value.
6174 Match group 3 is set to the value when it exists. If there is no
6175 value and ALLOW-NULL is non-nil, it is set to the empty string.
6177 With optional argument VALUE, match only property lines with
6178 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6179 unless LITERAL is non-nil."
6180 (concat
6181 "^\\(?4:[ \t]*\\)"
6182 (format "\\(?1::\\(?2:%s\\):\\)"
6183 (if literal property (regexp-quote property)))
6184 (cond (value
6185 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6186 (if literal value (regexp-quote value))))
6187 (allow-null
6188 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6190 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6192 (defconst org-property-re
6193 (org-re-property "\\S-+" 'literal t)
6194 "Regular expression matching a property line.
6195 There are four matching groups:
6196 1: :PROPKEY: including the leading and trailing colon,
6197 2: PROPKEY without the leading and trailing colon,
6198 3: PROPVAL without leading or trailing spaces,
6199 4: the indentation of the current line,
6200 5: trailing whitespace.")
6202 (defvar org-font-lock-hook nil
6203 "Functions to be called for special font lock stuff.")
6205 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6207 (defvar org-font-lock-set-keywords-hook nil
6208 "Functions that can manipulate `org-font-lock-extra-keywords'.
6209 This is called after `org-font-lock-extra-keywords' is defined, but before
6210 it is installed to be used by font lock. This can be useful if something
6211 needs to be inserted at a specific position in the font-lock sequence.")
6213 (defun org-font-lock-hook (limit)
6214 "Run `org-font-lock-hook' within LIMIT."
6215 (run-hook-with-args 'org-font-lock-hook limit))
6217 (defun org-set-font-lock-defaults ()
6218 "Set font lock defaults for the current buffer."
6219 (let* ((em org-fontify-emphasized-text)
6220 (lk org-highlight-links)
6221 (org-font-lock-extra-keywords
6222 (list
6223 ;; Call the hook
6224 '(org-font-lock-hook)
6225 ;; Headlines
6226 `(,(if org-fontify-whole-heading-line
6227 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6228 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6229 (1 (org-get-level-face 1))
6230 (2 (org-get-level-face 2))
6231 (3 (org-get-level-face 3)))
6232 ;; Table lines
6233 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6234 (1 'org-table t))
6235 ;; Table internals
6236 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6237 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6238 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6239 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6240 ;; Drawers
6241 '(org-fontify-drawers)
6242 ;; Properties
6243 (list org-property-re
6244 '(1 'org-special-keyword t)
6245 '(3 'org-property-value t))
6246 ;; Links
6247 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6248 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6249 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6250 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6251 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6252 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6253 (when (memq 'footnote lk) '(org-activate-footnote-links))
6254 ;; Targets.
6255 (list org-any-target-regexp '(0 'org-target t))
6256 ;; Diary sexps.
6257 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6258 ;; Macro
6259 '(org-fontify-macros)
6260 '(org-hide-wide-columns (0 nil append))
6261 ;; TODO keyword
6262 (list (format org-heading-keyword-regexp-format
6263 org-todo-regexp)
6264 '(2 (org-get-todo-face 2) t))
6265 ;; DONE
6266 (if org-fontify-done-headline
6267 (list (format org-heading-keyword-regexp-format
6268 (concat
6269 "\\(?:"
6270 (mapconcat 'regexp-quote org-done-keywords "\\|")
6271 "\\)"))
6272 '(2 'org-headline-done t))
6273 nil)
6274 ;; Priorities
6275 '(org-font-lock-add-priority-faces)
6276 ;; Tags
6277 '(org-font-lock-add-tag-faces)
6278 ;; Tags groups
6279 (when (and org-group-tags org-tag-groups-alist)
6280 (list (concat org-outline-regexp-bol ".+\\(:"
6281 (regexp-opt (mapcar 'car org-tag-groups-alist))
6282 ":\\).*$")
6283 '(1 'org-tag-group prepend)))
6284 ;; Special keywords
6285 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6286 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6287 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6288 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6289 ;; Emphasis
6290 (when em
6291 (if (featurep 'xemacs)
6292 '(org-do-emphasis-faces (0 nil append))
6293 '(org-do-emphasis-faces)))
6294 ;; Checkboxes
6295 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6296 1 'org-checkbox prepend)
6297 (when (cdr (assq 'checkbox org-list-automatic-rules))
6298 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6299 (0 (org-get-checkbox-statistics-face) t)))
6300 ;; Description list items
6301 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6302 1 'org-list-dt prepend)
6303 ;; ARCHIVEd headings
6304 (list (concat
6305 org-outline-regexp-bol
6306 "\\(.*:" org-archive-tag ":.*\\)")
6307 '(1 'org-archived prepend))
6308 ;; Specials
6309 '(org-do-latex-and-related)
6310 '(org-fontify-entities)
6311 '(org-raise-scripts)
6312 ;; Code
6313 '(org-activate-code (1 'org-code t))
6314 ;; COMMENT
6315 (list (format
6316 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6317 org-todo-regexp
6318 org-comment-string)
6319 '(9 'org-special-keyword t))
6320 ;; Blocks and meta lines
6321 '(org-fontify-meta-lines-and-blocks))))
6322 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6323 (run-hooks 'org-font-lock-set-keywords-hook)
6324 ;; Now set the full font-lock-keywords
6325 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6326 (setq-local font-lock-defaults
6327 '(org-font-lock-keywords t nil nil backward-paragraph))
6328 (kill-local-variable 'font-lock-keywords) nil))
6330 (defun org-toggle-pretty-entities ()
6331 "Toggle the composition display of entities as UTF8 characters."
6332 (interactive)
6333 (setq-local org-pretty-entities (not org-pretty-entities))
6334 (org-restart-font-lock)
6335 (if org-pretty-entities
6336 (message "Entities are now displayed as UTF8 characters")
6337 (save-restriction
6338 (widen)
6339 (org-decompose-region (point-min) (point-max))
6340 (message "Entities are now displayed as plain text"))))
6342 (defvar-local org-custom-properties-overlays nil
6343 "List of overlays used for custom properties.")
6345 (defun org-toggle-custom-properties-visibility ()
6346 "Display or hide properties in `org-custom-properties'."
6347 (interactive)
6348 (if org-custom-properties-overlays
6349 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6350 (setq org-custom-properties-overlays nil))
6351 (when org-custom-properties
6352 (org-with-wide-buffer
6353 (goto-char (point-min))
6354 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6355 (while (re-search-forward regexp nil t)
6356 (let ((end (cdr (save-match-data (org-get-property-block)))))
6357 (when (and end (< (point) end))
6358 ;; Hide first custom property in current drawer.
6359 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6360 (overlay-put o 'invisible t)
6361 (overlay-put o 'org-custom-property t)
6362 (push o org-custom-properties-overlays))
6363 ;; Hide additional custom properties in the same drawer.
6364 (while (re-search-forward regexp end t)
6365 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6366 (overlay-put o 'invisible t)
6367 (overlay-put o 'org-custom-property t)
6368 (push o org-custom-properties-overlays)))))
6369 ;; Each entry is limited to a single property drawer.
6370 (outline-next-heading)))))))
6372 (defun org-fontify-entities (limit)
6373 "Find an entity to fontify."
6374 (let (ee)
6375 (when org-pretty-entities
6376 (catch 'match
6377 ;; "\_ "-family is left out on purpose. Only the first one,
6378 ;; i.e., "\_ ", could be fontified anyway, and it would be
6379 ;; confusing when adding a second white space character.
6380 (while (re-search-forward
6381 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6382 limit t)
6383 (when (and (not (org-at-comment-p))
6384 (setq ee (org-entity-get (match-string 1)))
6385 (= (length (nth 6 ee)) 1))
6386 (let* ((end (if (equal (match-string 2) "{}")
6387 (match-end 2)
6388 (match-end 1))))
6389 (add-text-properties
6390 (match-beginning 0) end
6391 (list 'font-lock-fontified t))
6392 (compose-region (match-beginning 0) end
6393 (nth 6 ee) nil)
6394 (backward-char 1)
6395 (throw 'match t))))
6396 nil))))
6398 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6399 "Fontify string S like in Org-mode."
6400 (with-temp-buffer
6401 (insert s)
6402 (let ((org-odd-levels-only odd-levels))
6403 (org-mode)
6404 (org-font-lock-ensure)
6405 (buffer-string))))
6407 (defvar org-m nil)
6408 (defvar org-l nil)
6409 (defvar org-f nil)
6410 (defun org-get-level-face (n)
6411 "Get the right face for match N in font-lock matching of headlines."
6412 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6413 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6414 (if org-cycle-level-faces
6415 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6416 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6417 (cond
6418 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6419 ((eq n 2) org-f)
6420 (t (unless org-level-color-stars-only org-f))))
6422 (defun org-face-from-face-or-color (context inherit face-or-color)
6423 "Create a face list that inherits INHERIT, but sets the foreground color.
6424 When FACE-OR-COLOR is not a string, just return it."
6425 (if (stringp face-or-color)
6426 (list :inherit inherit
6427 (cdr (assoc context org-faces-easy-properties))
6428 face-or-color)
6429 face-or-color))
6431 (defun org-get-todo-face (kwd)
6432 "Get the right face for a TODO keyword KWD.
6433 If KWD is a number, get the corresponding match group."
6434 (when (numberp kwd) (setq kwd (match-string kwd)))
6435 (or (org-face-from-face-or-color
6436 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6437 (and (member kwd org-done-keywords) 'org-done)
6438 'org-todo))
6440 (defun org-get-priority-face (priority)
6441 "Get the right face for PRIORITY.
6442 PRIORITY is a character."
6443 (or (org-face-from-face-or-color
6444 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6445 'org-priority))
6447 (defun org-get-tag-face (tag)
6448 "Get the right face for TAG.
6449 If TAG is a number, get the corresponding match group."
6450 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6451 (or (org-face-from-face-or-color
6452 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6453 'org-tag)))
6455 (defun org-font-lock-add-priority-faces (limit)
6456 "Add the special priority faces."
6457 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6458 (add-text-properties
6459 (match-beginning 1) (match-end 1)
6460 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6461 'font-lock-fontified t))))
6463 (defun org-font-lock-add-tag-faces (limit)
6464 "Add the special tag faces."
6465 (when (and org-tag-faces org-tags-special-faces-re)
6466 (while (re-search-forward org-tags-special-faces-re limit t)
6467 (add-text-properties (match-beginning 1) (match-end 1)
6468 (list 'face (org-get-tag-face 1)
6469 'font-lock-fontified t))
6470 (backward-char 1))))
6472 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6473 "Remove fontification and activation overlays from links."
6474 (font-lock-default-unfontify-region beg end)
6475 (let* ((buffer-undo-list t)
6476 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6477 (inhibit-modification-hooks t)
6478 deactivate-mark buffer-file-name buffer-file-truename)
6479 (org-decompose-region beg end)
6480 (remove-text-properties beg end
6481 '(mouse-face t keymap t org-linked-text t
6482 invisible t intangible t
6483 org-emphasis t))
6484 (org-remove-font-lock-display-properties beg end)))
6486 (defconst org-script-display '(((raise -0.3) (height 0.7))
6487 ((raise 0.3) (height 0.7))
6488 ((raise -0.5))
6489 ((raise 0.5)))
6490 "Display properties for showing superscripts and subscripts.")
6492 (defun org-remove-font-lock-display-properties (beg end)
6493 "Remove specific display properties that have been added by font lock.
6494 The will remove the raise properties that are used to show superscripts
6495 and subscripts."
6496 (let (next prop)
6497 (while (< beg end)
6498 (setq next (next-single-property-change beg 'display nil end)
6499 prop (get-text-property beg 'display))
6500 (when (member prop org-script-display)
6501 (put-text-property beg next 'display nil))
6502 (setq beg next))))
6504 (defun org-raise-scripts (limit)
6505 "Add raise properties to sub/superscripts."
6506 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6507 (re-search-forward
6508 (if (eq org-use-sub-superscripts t)
6509 org-match-substring-regexp
6510 org-match-substring-with-braces-regexp)
6511 limit t))
6512 (let* ((pos (point)) table-p comment-p
6513 (mpos (match-beginning 3))
6514 (emph-p (get-text-property mpos 'org-emphasis))
6515 (link-p (get-text-property mpos 'mouse-face))
6516 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6517 (goto-char (point-at-bol))
6518 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6519 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6520 (goto-char pos)
6521 ;; Handle a_b^c
6522 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6523 (unless (or comment-p emph-p link-p keyw-p)
6524 (put-text-property (match-beginning 3) (match-end 0)
6525 'display
6526 (if (equal (char-after (match-beginning 2)) ?^)
6527 (nth (if table-p 3 1) org-script-display)
6528 (nth (if table-p 2 0) org-script-display)))
6529 (add-text-properties (match-beginning 2) (match-end 2)
6530 (list 'invisible t
6531 'org-dwidth t 'org-dwidth-n 1))
6532 (if (and (eq (char-after (match-beginning 3)) ?{)
6533 (eq (char-before (match-end 3)) ?}))
6534 (progn
6535 (add-text-properties
6536 (match-beginning 3) (1+ (match-beginning 3))
6537 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6538 (add-text-properties
6539 (1- (match-end 3)) (match-end 3)
6540 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6541 t)))
6543 ;;;; Visibility cycling, including org-goto and indirect buffer
6545 ;;; Cycling
6547 (defvar-local org-cycle-global-status nil)
6548 (put 'org-cycle-global-status 'org-state t)
6549 (defvar-local org-cycle-subtree-status nil)
6550 (put 'org-cycle-subtree-status 'org-state t)
6552 (defvar org-inlinetask-min-level)
6554 (defun org-unlogged-message (&rest args)
6555 "Display a message, but avoid logging it in the *Messages* buffer."
6556 (let ((message-log-max nil))
6557 (apply 'message args)))
6559 ;;;###autoload
6560 (defun org-cycle (&optional arg)
6561 "TAB-action and visibility cycling for Org-mode.
6563 This is the command invoked in Org-mode by the TAB key. Its main purpose
6564 is outline visibility cycling, but it also invokes other actions
6565 in special contexts.
6567 - When this function is called with a prefix argument, rotate the entire
6568 buffer through 3 states (global cycling)
6569 1. OVERVIEW: Show only top-level headlines.
6570 2. CONTENTS: Show all headlines of all levels, but no body text.
6571 3. SHOW ALL: Show everything.
6572 With a double \\[universal-argument] prefix argument, \
6573 switch to the startup visibility,
6574 determined by the variable `org-startup-folded', and by any VISIBILITY
6575 properties in the buffer.
6576 With a triple \\[universal-argument] prefix argument, \
6577 show the entire buffer, including any drawers.
6579 - When inside a table, re-align the table and move to the next field.
6581 - When point is at the beginning of a headline, rotate the subtree started
6582 by this line through 3 different states (local cycling)
6583 1. FOLDED: Only the main headline is shown.
6584 2. CHILDREN: The main headline and the direct children are shown.
6585 From this state, you can move to one of the children
6586 and zoom in further.
6587 3. SUBTREE: Show the entire subtree, including body text.
6588 If there is no subtree, switch directly from CHILDREN to FOLDED.
6590 - When point is at the beginning of an empty headline and the variable
6591 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6592 of the headline by demoting and promoting it to likely levels. This
6593 speeds up creation document structure by pressing TAB once or several
6594 times right after creating a new headline.
6596 - When there is a numeric prefix, go up to a heading with level ARG, do
6597 a `show-subtree' and return to the previous cursor position. If ARG
6598 is negative, go up that many levels.
6600 - When point is not at the beginning of a headline, execute the global
6601 binding for TAB, which is re-indenting the line. See the option
6602 `org-cycle-emulate-tab' for details.
6604 - Special case: if point is at the beginning of the buffer and there is
6605 no headline in line 1, this function will act as if called with prefix arg
6606 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6607 But only if also the variable `org-cycle-global-at-bob' is t."
6608 (interactive "P")
6609 (org-load-modules-maybe)
6610 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6611 (and org-cycle-level-after-item/entry-creation
6612 (or (org-cycle-level)
6613 (org-cycle-item-indentation))))
6614 (let* ((limit-level
6615 (or org-cycle-max-level
6616 (and (boundp 'org-inlinetask-min-level)
6617 org-inlinetask-min-level
6618 (1- org-inlinetask-min-level))))
6619 (nstars (and limit-level
6620 (if org-odd-levels-only
6621 (and limit-level (1- (* limit-level 2)))
6622 limit-level)))
6623 (org-outline-regexp
6624 (if (not (derived-mode-p 'org-mode))
6625 outline-regexp
6626 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6627 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6628 (not (looking-at org-outline-regexp))))
6629 (org-cycle-hook
6630 (if bob-special
6631 (delq 'org-optimize-window-after-visibility-change
6632 (copy-sequence org-cycle-hook))
6633 org-cycle-hook))
6634 (pos (point)))
6636 (when (or bob-special (equal arg '(4)))
6637 ;; special case: use global cycling
6638 (setq arg t))
6640 (cond
6642 ((equal arg '(16))
6643 (setq last-command 'dummy)
6644 (org-set-startup-visibility)
6645 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6647 ((equal arg '(64))
6648 (outline-show-all)
6649 (org-unlogged-message "Entire buffer visible, including drawers"))
6651 ;; Try cdlatex TAB completion
6652 ((org-try-cdlatex-tab))
6654 ;; Table: enter it or move to the next field.
6655 ((org-at-table-p 'any)
6656 (if (org-at-table.el-p)
6657 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6658 Use \\[org-edit-special] to edit table.el tables"))
6659 (if arg (org-table-edit-field t)
6660 (org-table-justify-field-maybe)
6661 (call-interactively 'org-table-next-field))))
6663 ((run-hook-with-args-until-success
6664 'org-tab-after-check-for-table-hook))
6666 ;; Global cycling: delegate to `org-cycle-internal-global'.
6667 ((eq arg t) (org-cycle-internal-global))
6669 ;; Drawers: delegate to `org-flag-drawer'.
6670 ((save-excursion
6671 (beginning-of-line 1)
6672 (looking-at org-drawer-regexp))
6673 (org-flag-drawer ; toggle block visibility
6674 (not (get-char-property (match-end 0) 'invisible))))
6676 ;; Show-subtree, ARG levels up from here.
6677 ((integerp arg)
6678 (save-excursion
6679 (org-back-to-heading)
6680 (outline-up-heading (if (< arg 0) (- arg)
6681 (- (funcall outline-level) arg)))
6682 (org-show-subtree)))
6684 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6685 ((and (featurep 'org-inlinetask)
6686 (org-inlinetask-at-task-p)
6687 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6688 (org-inlinetask-toggle-visibility))
6690 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6691 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6692 (save-excursion (move-beginning-of-line 1)
6693 (looking-at org-outline-regexp)))
6694 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6695 (org-cycle-internal-local))
6697 ;; From there: TAB emulation and template completion.
6698 (buffer-read-only (org-back-to-heading))
6700 ((run-hook-with-args-until-success
6701 'org-tab-after-check-for-cycling-hook))
6703 ((org-try-structure-completion))
6705 ((run-hook-with-args-until-success
6706 'org-tab-before-tab-emulation-hook))
6708 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6709 (or (not (bolp))
6710 (not (looking-at org-outline-regexp))))
6711 (call-interactively (global-key-binding "\t")))
6713 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6714 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6715 (or (and (eq org-cycle-emulate-tab 'white)
6716 (= (match-end 0) (point-at-eol)))
6717 (and (eq org-cycle-emulate-tab 'whitestart)
6718 (>= (match-end 0) pos))))
6720 (eq org-cycle-emulate-tab t))
6721 (call-interactively (global-key-binding "\t")))
6723 (t (save-excursion
6724 (org-back-to-heading)
6725 (org-cycle)))))))
6727 (defun org-cycle-internal-global ()
6728 "Do the global cycling action."
6729 ;; Hack to avoid display of messages for .org attachments in Gnus
6730 (let ((ga (string-match "\\*fontification" (buffer-name))))
6731 (cond
6732 ((and (eq last-command this-command)
6733 (eq org-cycle-global-status 'overview))
6734 ;; We just created the overview - now do table of contents
6735 ;; This can be slow in very large buffers, so indicate action
6736 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6737 (unless ga (org-unlogged-message "CONTENTS..."))
6738 (org-content)
6739 (unless ga (org-unlogged-message "CONTENTS...done"))
6740 (setq org-cycle-global-status 'contents)
6741 (run-hook-with-args 'org-cycle-hook 'contents))
6743 ((and (eq last-command this-command)
6744 (eq org-cycle-global-status 'contents))
6745 ;; We just showed the table of contents - now show everything
6746 (run-hook-with-args 'org-pre-cycle-hook 'all)
6747 (outline-show-all)
6748 (unless ga (org-unlogged-message "SHOW ALL"))
6749 (setq org-cycle-global-status 'all)
6750 (run-hook-with-args 'org-cycle-hook 'all))
6753 ;; Default action: go to overview
6754 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6755 (org-overview)
6756 (unless ga (org-unlogged-message "OVERVIEW"))
6757 (setq org-cycle-global-status 'overview)
6758 (run-hook-with-args 'org-cycle-hook 'overview)))))
6760 (defvar org-called-with-limited-levels nil
6761 "Non-nil when `org-with-limited-levels' is currently active.")
6763 (defun org-cycle-internal-local ()
6764 "Do the local cycling action."
6765 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6766 ;; First, determine end of headline (EOH), end of subtree or item
6767 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6768 (save-excursion
6769 (if (org-at-item-p)
6770 (progn
6771 (beginning-of-line)
6772 (setq struct (org-list-struct))
6773 (setq eoh (point-at-eol))
6774 (setq eos (org-list-get-item-end-before-blank (point) struct))
6775 (setq has-children (org-list-has-child-p (point) struct)))
6776 (org-back-to-heading)
6777 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6778 (setq eos (save-excursion (org-end-of-subtree t t)
6779 (when (bolp) (backward-char)) (point)))
6780 (setq has-children
6781 (or (save-excursion
6782 (let ((level (funcall outline-level)))
6783 (outline-next-heading)
6784 (and (org-at-heading-p t)
6785 (> (funcall outline-level) level))))
6786 (save-excursion
6787 (org-list-search-forward (org-item-beginning-re) eos t)))))
6788 ;; Determine end invisible part of buffer (EOL)
6789 (beginning-of-line 2)
6790 ;; XEmacs doesn't have `next-single-char-property-change'
6791 (if (featurep 'xemacs)
6792 (while (and (not (eobp)) ;; this is like `next-line'
6793 (get-char-property (1- (point)) 'invisible))
6794 (beginning-of-line 2))
6795 (while (and (not (eobp)) ;; this is like `next-line'
6796 (get-char-property (1- (point)) 'invisible))
6797 (goto-char (next-single-char-property-change (point) 'invisible))
6798 (and (eolp) (beginning-of-line 2))))
6799 (setq eol (point)))
6800 ;; Find out what to do next and set `this-command'
6801 (cond
6802 ((= eos eoh)
6803 ;; Nothing is hidden behind this heading
6804 (unless (org-before-first-heading-p)
6805 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6806 (org-unlogged-message "EMPTY ENTRY")
6807 (setq org-cycle-subtree-status nil)
6808 (save-excursion
6809 (goto-char eos)
6810 (outline-next-heading)
6811 (when (outline-invisible-p) (org-flag-heading nil))))
6812 ((and (or (>= eol eos)
6813 (not (string-match "\\S-" (buffer-substring eol eos))))
6814 (or has-children
6815 (not (setq children-skipped
6816 org-cycle-skip-children-state-if-no-children))))
6817 ;; Entire subtree is hidden in one line: children view
6818 (unless (org-before-first-heading-p)
6819 (run-hook-with-args 'org-pre-cycle-hook 'children))
6820 (if (org-at-item-p)
6821 (org-list-set-item-visibility (point-at-bol) struct 'children)
6822 (org-show-entry)
6823 (org-with-limited-levels (org-show-children))
6824 ;; FIXME: This slows down the func way too much.
6825 ;; How keep drawers hidden in subtree anyway?
6826 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6827 ;; (org-cycle-hide-drawers 'subtree))
6829 ;; Fold every list in subtree to top-level items.
6830 (when (eq org-cycle-include-plain-lists 'integrate)
6831 (save-excursion
6832 (org-back-to-heading)
6833 (while (org-list-search-forward (org-item-beginning-re) eos t)
6834 (beginning-of-line 1)
6835 (let* ((struct (org-list-struct))
6836 (prevs (org-list-prevs-alist struct))
6837 (end (org-list-get-bottom-point struct)))
6838 (dolist (e (org-list-get-all-items (point) struct prevs))
6839 (org-list-set-item-visibility e struct 'folded))
6840 (goto-char (if (< end eos) end eos)))))))
6841 (org-unlogged-message "CHILDREN")
6842 (save-excursion
6843 (goto-char eos)
6844 (outline-next-heading)
6845 (when (outline-invisible-p) (org-flag-heading nil)))
6846 (setq org-cycle-subtree-status 'children)
6847 (unless (org-before-first-heading-p)
6848 (run-hook-with-args 'org-cycle-hook 'children)))
6849 ((or children-skipped
6850 (and (eq last-command this-command)
6851 (eq org-cycle-subtree-status 'children)))
6852 ;; We just showed the children, or no children are there,
6853 ;; now show everything.
6854 (unless (org-before-first-heading-p)
6855 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6856 (outline-flag-region eoh eos nil)
6857 (org-unlogged-message
6858 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6859 (setq org-cycle-subtree-status 'subtree)
6860 (unless (org-before-first-heading-p)
6861 (run-hook-with-args 'org-cycle-hook 'subtree)))
6863 ;; Default action: hide the subtree.
6864 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6865 (outline-flag-region eoh eos t)
6866 (org-unlogged-message "FOLDED")
6867 (setq org-cycle-subtree-status 'folded)
6868 (unless (org-before-first-heading-p)
6869 (run-hook-with-args 'org-cycle-hook 'folded))))))
6871 ;;;###autoload
6872 (defun org-global-cycle (&optional arg)
6873 "Cycle the global visibility. For details see `org-cycle'.
6874 With \\[universal-argument] prefix arg, switch to startup visibility.
6875 With a numeric prefix, show all headlines up to that level."
6876 (interactive "P")
6877 (let ((org-cycle-include-plain-lists
6878 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6879 (cond
6880 ((integerp arg)
6881 (outline-show-all)
6882 (outline-hide-sublevels arg)
6883 (setq org-cycle-global-status 'contents))
6884 ((equal arg '(4))
6885 (org-set-startup-visibility)
6886 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6888 (org-cycle '(4))))))
6890 (defun org-set-startup-visibility ()
6891 "Set the visibility required by startup options and properties."
6892 (cond
6893 ((eq org-startup-folded t)
6894 (org-overview))
6895 ((eq org-startup-folded 'content)
6896 (org-content))
6897 ((or (eq org-startup-folded 'showeverything)
6898 (eq org-startup-folded nil))
6899 (outline-show-all)))
6900 (unless (eq org-startup-folded 'showeverything)
6901 (when org-hide-block-startup (org-hide-block-all))
6902 (org-set-visibility-according-to-property 'no-cleanup)
6903 (org-cycle-hide-archived-subtrees 'all)
6904 (org-cycle-hide-drawers 'all)
6905 (org-cycle-show-empty-lines t)))
6907 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6908 "Switch subtree visibilities according to :VISIBILITY: property."
6909 (interactive)
6910 (org-with-wide-buffer
6911 (goto-char (point-min))
6912 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6913 (if (not (org-at-property-p)) (outline-next-heading)
6914 (let ((state (match-string 3)))
6915 (save-excursion
6916 (org-back-to-heading t)
6917 (outline-hide-subtree)
6918 (org-reveal)
6919 (cond
6920 ((equal state "folded")
6921 (outline-hide-subtree))
6922 ((equal state "children")
6923 (org-show-hidden-entry)
6924 (org-show-children))
6925 ((equal state "content")
6926 (save-excursion
6927 (save-restriction
6928 (org-narrow-to-subtree)
6929 (org-content))))
6930 ((member state '("all" "showall"))
6931 (outline-show-subtree)))))))
6932 (unless no-cleanup
6933 (org-cycle-hide-archived-subtrees 'all)
6934 (org-cycle-hide-drawers 'all)
6935 (org-cycle-show-empty-lines 'all))))
6937 ;; This function uses outline-regexp instead of the more fundamental
6938 ;; org-outline-regexp so that org-cycle-global works outside of Org
6939 ;; buffers, where outline-regexp is needed.
6940 (defun org-overview ()
6941 "Switch to overview mode, showing only top-level headlines.
6942 This shows all headlines with a level equal or greater than the level
6943 of the first headline in the buffer. This is important, because if the
6944 first headline is not level one, then (hide-sublevels 1) gives confusing
6945 results."
6946 (interactive)
6947 (save-excursion
6948 (let ((level
6949 (save-excursion
6950 (goto-char (point-min))
6951 (when (re-search-forward (concat "^" outline-regexp) nil t)
6952 (goto-char (match-beginning 0))
6953 (funcall outline-level)))))
6954 (and level (outline-hide-sublevels level)))))
6956 (defun org-content (&optional arg)
6957 "Show all headlines in the buffer, like a table of contents.
6958 With numerical argument N, show content up to level N."
6959 (interactive "P")
6960 (org-overview)
6961 (save-excursion
6962 ;; Visit all headings and show their offspring
6963 (and (integerp arg) (org-overview))
6964 (goto-char (point-max))
6965 (catch 'exit
6966 (while (and (progn (condition-case nil
6967 (outline-previous-visible-heading 1)
6968 (error (goto-char (point-min))))
6970 (looking-at org-outline-regexp))
6971 (if (integerp arg)
6972 (org-show-children (1- arg))
6973 (outline-show-branches))
6974 (when (bobp) (throw 'exit nil))))))
6976 (defun org-optimize-window-after-visibility-change (state)
6977 "Adjust the window after a change in outline visibility.
6978 This function is the default value of the hook `org-cycle-hook'."
6979 (when (get-buffer-window (current-buffer))
6980 (cond
6981 ((eq state 'content) nil)
6982 ((eq state 'all) nil)
6983 ((eq state 'folded) nil)
6984 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
6985 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
6987 (defun org-remove-empty-overlays-at (pos)
6988 "Remove outline overlays that do not contain non-white stuff."
6989 (dolist (o (overlays-at pos))
6990 (and (eq 'outline (overlay-get o 'invisible))
6991 (not (string-match "\\S-" (buffer-substring (overlay-start o)
6992 (overlay-end o))))
6993 (delete-overlay o))))
6995 (defun org-clean-visibility-after-subtree-move ()
6996 "Fix visibility issues after moving a subtree."
6997 ;; First, find a reasonable region to look at:
6998 ;; Start two siblings above, end three below
6999 (let* ((beg (save-excursion
7000 (and (org-get-last-sibling)
7001 (org-get-last-sibling))
7002 (point)))
7003 (end (save-excursion
7004 (and (org-get-next-sibling)
7005 (org-get-next-sibling)
7006 (org-get-next-sibling))
7007 (if (org-at-heading-p)
7008 (point-at-eol)
7009 (point))))
7010 (level (looking-at "\\*+"))
7011 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7012 (save-excursion
7013 (save-restriction
7014 (narrow-to-region beg end)
7015 (when re
7016 ;; Properly fold already folded siblings
7017 (goto-char (point-min))
7018 (while (re-search-forward re nil t)
7019 (when (and (not (outline-invisible-p))
7020 (save-excursion
7021 (goto-char (point-at-eol)) (outline-invisible-p)))
7022 (outline-hide-entry))))
7023 (org-cycle-show-empty-lines 'overview)
7024 (org-cycle-hide-drawers 'overview)))))
7026 (defun org-cycle-show-empty-lines (state)
7027 "Show empty lines above all visible headlines.
7028 The region to be covered depends on STATE when called through
7029 `org-cycle-hook'. Lisp program can use t for STATE to get the
7030 entire buffer covered. Note that an empty line is only shown if there
7031 are at least `org-cycle-separator-lines' empty lines before the headline."
7032 (when (/= org-cycle-separator-lines 0)
7033 (save-excursion
7034 (let* ((n (abs org-cycle-separator-lines))
7035 (re (cond
7036 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7037 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7038 (t (let ((ns (number-to-string (- n 2))))
7039 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7040 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7041 beg end)
7042 (cond
7043 ((memq state '(overview contents t))
7044 (setq beg (point-min) end (point-max)))
7045 ((memq state '(children folded))
7046 (setq beg (point)
7047 end (progn (org-end-of-subtree t t)
7048 (line-beginning-position 2)))))
7049 (when beg
7050 (goto-char beg)
7051 (while (re-search-forward re end t)
7052 (unless (get-char-property (match-end 1) 'invisible)
7053 (let ((e (match-end 1))
7054 (b (if (>= org-cycle-separator-lines 0)
7055 (match-beginning 1)
7056 (save-excursion
7057 (goto-char (match-beginning 0))
7058 (skip-chars-backward " \t\n")
7059 (line-end-position)))))
7060 (outline-flag-region b e nil))))))))
7061 ;; Never hide empty lines at the end of the file.
7062 (save-excursion
7063 (goto-char (point-max))
7064 (outline-previous-heading)
7065 (outline-end-of-heading)
7066 (when (and (looking-at "[ \t\n]+")
7067 (= (match-end 0) (point-max)))
7068 (outline-flag-region (point) (match-end 0) nil))))
7070 (defun org-show-empty-lines-in-parent ()
7071 "Move to the parent and re-show empty lines before visible headlines."
7072 (save-excursion
7073 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7074 (org-cycle-show-empty-lines context))))
7076 (defun org-files-list ()
7077 "Return `org-agenda-files' list, plus all open org-mode files.
7078 This is useful for operations that need to scan all of a user's
7079 open and agenda-wise Org files."
7080 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7081 (dolist (buf (buffer-list))
7082 (with-current-buffer buf
7083 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7084 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7085 files))
7087 (defsubst org-entry-beginning-position ()
7088 "Return the beginning position of the current entry."
7089 (save-excursion (org-back-to-heading t) (point)))
7091 (defsubst org-entry-end-position ()
7092 "Return the end position of the current entry."
7093 (save-excursion (outline-next-heading) (point)))
7095 (defun org-cycle-hide-drawers (state &optional exceptions)
7096 "Re-hide all drawers after a visibility state change.
7097 When non-nil, optional argument EXCEPTIONS is a list of strings
7098 specifying which drawers should not be hidden."
7099 (when (and (derived-mode-p 'org-mode)
7100 (not (memq state '(overview folded contents))))
7101 (save-excursion
7102 (let* ((globalp (memq state '(contents all)))
7103 (beg (if globalp (point-min) (point)))
7104 (end (if globalp (point-max)
7105 (if (eq state 'children)
7106 (save-excursion (outline-next-heading) (point))
7107 (org-end-of-subtree t)))))
7108 (goto-char beg)
7109 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7110 (unless (member-ignore-case (match-string 1) exceptions)
7111 (let ((drawer (org-element-at-point)))
7112 (when (memq (org-element-type drawer) '(drawer property-drawer))
7113 (org-flag-drawer t drawer)
7114 ;; Make sure to skip drawer entirely or we might flag
7115 ;; it another time when matching its ending line with
7116 ;; `org-drawer-regexp'.
7117 (goto-char (org-element-property :end drawer))))))))))
7119 (defun org-flag-drawer (flag &optional element)
7120 "When FLAG is non-nil, hide the drawer we are at.
7121 Otherwise make it visible. When optional argument ELEMENT is
7122 a parsed drawer, as returned by `org-element-at-point', hide or
7123 show that drawer instead."
7124 (when (save-excursion
7125 (beginning-of-line)
7126 (org-looking-at-p org-drawer-regexp))
7127 (let ((drawer (or element (org-element-at-point))))
7128 (when (memq (org-element-type drawer) '(drawer property-drawer))
7129 (let ((post (org-element-property :post-affiliated drawer)))
7130 (save-excursion
7131 (outline-flag-region
7132 (progn (goto-char post) (line-end-position))
7133 (progn (goto-char (org-element-property :end drawer))
7134 (skip-chars-backward " \r\t\n")
7135 (line-end-position))
7136 flag))
7137 ;; When the drawer is hidden away, make sure point lies in
7138 ;; a visible part of the buffer.
7139 (when (and flag (> (line-beginning-position) post))
7140 (goto-char post)))))))
7142 (defun org-subtree-end-visible-p ()
7143 "Is the end of the current subtree visible?"
7144 (pos-visible-in-window-p
7145 (save-excursion (org-end-of-subtree t) (point))))
7147 (defun org-first-headline-recenter ()
7148 "Move cursor to the first headline and recenter the headline."
7149 (goto-char (point-min))
7150 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7151 (set-window-start (selected-window) (point-at-bol))))
7153 ;;; Saving and restoring visibility
7155 (defun org-outline-overlay-data (&optional use-markers)
7156 "Return a list of the locations of all outline overlays.
7157 These are overlays with the `invisible' property value `outline'.
7158 The return value is a list of cons cells, with start and stop
7159 positions for each overlay.
7160 If USE-MARKERS is set, return the positions as markers."
7161 (let (beg end)
7162 (save-excursion
7163 (save-restriction
7164 (widen)
7165 (delq nil
7166 (mapcar (lambda (o)
7167 (when (eq (overlay-get o 'invisible) 'outline)
7168 (setq beg (overlay-start o)
7169 end (overlay-end o))
7170 (and beg end (> end beg)
7171 (if use-markers
7172 (cons (copy-marker beg)
7173 (copy-marker end t))
7174 (cons beg end)))))
7175 (overlays-in (point-min) (point-max))))))))
7177 (defun org-set-outline-overlay-data (data)
7178 "Create visibility overlays for all positions in DATA.
7179 DATA should have been made by `org-outline-overlay-data'."
7180 (org-with-wide-buffer
7181 (outline-show-all)
7182 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7184 ;;; Folding of blocks
7186 (defvar-local org-hide-block-overlays nil
7187 "Overlays hiding blocks.")
7189 (defun org-block-map (function &optional start end)
7190 "Call FUNCTION at the head of all source blocks in the current buffer.
7191 Optional arguments START and END can be used to limit the range."
7192 (let ((start (or start (point-min)))
7193 (end (or end (point-max))))
7194 (save-excursion
7195 (goto-char start)
7196 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7197 (save-excursion
7198 (save-match-data
7199 (goto-char (match-beginning 0))
7200 (funcall function)))))))
7202 (defun org-hide-block-toggle-all ()
7203 "Toggle the visibility of all blocks in the current buffer."
7204 (org-block-map 'org-hide-block-toggle))
7206 (defun org-hide-block-all ()
7207 "Fold all blocks in the current buffer."
7208 (interactive)
7209 (org-show-block-all)
7210 (org-block-map 'org-hide-block-toggle-maybe))
7212 (defun org-show-block-all ()
7213 "Unfold all blocks in the current buffer."
7214 (interactive)
7215 (mapc #'delete-overlay org-hide-block-overlays)
7216 (setq org-hide-block-overlays nil))
7218 (defun org-hide-block-toggle-maybe ()
7219 "Toggle visibility of block at point.
7220 Unlike to `org-hide-block-toggle', this function does not throw
7221 an error. Return a non-nil value when toggling is successful."
7222 (interactive)
7223 (ignore-errors (org-hide-block-toggle)))
7225 (defun org-hide-block-toggle (&optional force)
7226 "Toggle the visibility of the current block.
7227 When optional argument FORCE is `off', make block visible. If it
7228 is non-nil, hide it unconditionally. Throw an error when not at
7229 a block. Return a non-nil value when toggling is successful."
7230 (interactive)
7231 (let ((element (org-element-at-point)))
7232 (unless (memq (org-element-type element)
7233 '(center-block comment-block dynamic-block example-block
7234 export-block quote-block special-block
7235 src-block verse-block))
7236 (user-error "Not at a block"))
7237 (let* ((start (save-excursion
7238 (goto-char (org-element-property :post-affiliated element))
7239 (line-end-position)))
7240 (end (save-excursion
7241 (goto-char (org-element-property :end element))
7242 (skip-chars-backward " \r\t\n")
7243 (line-end-position)))
7244 (overlays (overlays-at start)))
7245 (cond
7246 ;; Do nothing when not before or at the block opening line or
7247 ;; at the block closing line.
7248 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7249 ((and (not (eq force 'off))
7250 (not (memq t (mapcar
7251 (lambda (o)
7252 (eq (overlay-get o 'invisible) 'org-hide-block))
7253 overlays))))
7254 (let ((ov (make-overlay start end)))
7255 (overlay-put ov 'invisible 'org-hide-block)
7256 ;; Make the block accessible to `isearch'.
7257 (overlay-put
7258 ov 'isearch-open-invisible
7259 (lambda (ov)
7260 (when (memq ov org-hide-block-overlays)
7261 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7262 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7263 (delete-overlay ov))))
7264 (push ov org-hide-block-overlays)
7265 ;; When the block is hidden away, make sure point is left in
7266 ;; a visible part of the buffer.
7267 (when (> (line-beginning-position) start)
7268 (goto-char start)
7269 (beginning-of-line))
7270 ;; Signal successful toggling.
7272 ((or (not force) (eq force 'off))
7273 (dolist (ov overlays t)
7274 (when (memq ov org-hide-block-overlays)
7275 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7276 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7277 (delete-overlay ov))))))))
7279 ;; org-tab-after-check-for-cycling-hook
7280 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7281 ;; Remove overlays when changing major mode
7282 (add-hook 'org-mode-hook
7283 (lambda () (org-add-hook 'change-major-mode-hook
7284 'org-show-block-all 'append 'local)))
7286 ;;; Org-goto
7288 (defvar org-goto-window-configuration nil)
7289 (defvar org-goto-marker nil)
7290 (defvar org-goto-map)
7291 (defun org-goto-map ()
7292 "Set the keymap `org-goto'."
7293 (setq org-goto-map
7294 (let ((map (make-sparse-keymap)))
7295 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7296 mouse-drag-region universal-argument org-occur)))
7297 (dolist (cmd cmds)
7298 (substitute-key-definition cmd cmd map global-map)))
7299 (suppress-keymap map)
7300 (org-defkey map "\C-m" 'org-goto-ret)
7301 (org-defkey map [(return)] 'org-goto-ret)
7302 (org-defkey map [(left)] 'org-goto-left)
7303 (org-defkey map [(right)] 'org-goto-right)
7304 (org-defkey map [(control ?g)] 'org-goto-quit)
7305 (org-defkey map "\C-i" 'org-cycle)
7306 (org-defkey map [(tab)] 'org-cycle)
7307 (org-defkey map [(down)] 'outline-next-visible-heading)
7308 (org-defkey map [(up)] 'outline-previous-visible-heading)
7309 (if org-goto-auto-isearch
7310 (if (fboundp 'define-key-after)
7311 (define-key-after map [t] 'org-goto-local-auto-isearch)
7312 nil)
7313 (org-defkey map "q" 'org-goto-quit)
7314 (org-defkey map "n" 'outline-next-visible-heading)
7315 (org-defkey map "p" 'outline-previous-visible-heading)
7316 (org-defkey map "f" 'outline-forward-same-level)
7317 (org-defkey map "b" 'outline-backward-same-level)
7318 (org-defkey map "u" 'outline-up-heading))
7319 (org-defkey map "/" 'org-occur)
7320 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7321 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7322 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7323 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7324 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7325 map)))
7327 (defconst org-goto-help
7328 "Browse buffer copy, to find location or copy text.%s
7329 RET=jump to location C-g=quit and return to previous location
7330 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7332 (defvar org-goto-start-pos) ; dynamically scoped parameter
7334 (defun org-goto (&optional alternative-interface)
7335 "Look up a different location in the current file, keeping current visibility.
7337 When you want look-up or go to a different location in a
7338 document, the fastest way is often to fold the entire buffer and
7339 then dive into the tree. This method has the disadvantage, that
7340 the previous location will be folded, which may not be what you
7341 want.
7343 This command works around this by showing a copy of the current
7344 buffer in an indirect buffer, in overview mode. You can dive
7345 into the tree in that copy, use org-occur and incremental search
7346 to find a location. When pressing RET or `Q', the command
7347 returns to the original buffer in which the visibility is still
7348 unchanged. After RET it will also jump to the location selected
7349 in the indirect buffer and expose the headline hierarchy above.
7351 With a prefix argument, use the alternative interface: e.g., if
7352 `org-goto-interface' is `outline' use `outline-path-completion'."
7353 (interactive "P")
7354 (org-goto-map)
7355 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7356 (org-refile-use-outline-path t)
7357 (org-refile-target-verify-function nil)
7358 (interface
7359 (if (not alternative-interface)
7360 org-goto-interface
7361 (if (eq org-goto-interface 'outline)
7362 'outline-path-completion
7363 'outline)))
7364 (org-goto-start-pos (point))
7365 (selected-point
7366 (if (eq interface 'outline)
7367 (car (org-get-location (current-buffer) org-goto-help))
7368 (let ((pa (org-refile-get-location "Goto" nil nil t)))
7369 (org-refile-check-position pa)
7370 (nth 3 pa)))))
7371 (if selected-point
7372 (progn
7373 (org-mark-ring-push org-goto-start-pos)
7374 (goto-char selected-point)
7375 (when (or (outline-invisible-p) (org-invisible-p2))
7376 (org-show-context 'org-goto)))
7377 (message "Quit"))))
7379 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7380 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7381 (defvar org-goto-local-auto-isearch-map) ; defined below
7383 (defun org-get-location (_buf help)
7384 "Let the user select a location in current buffer.
7385 This function uses a recursive edit. It returns the selected position
7386 or nil."
7387 (org-no-popups
7388 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7389 (isearch-hide-immediately nil)
7390 (isearch-search-fun-function
7391 (lambda () 'org-goto-local-search-headings))
7392 (org-goto-selected-point org-goto-exit-command))
7393 (save-excursion
7394 (save-window-excursion
7395 (delete-other-windows)
7396 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7397 (org-pop-to-buffer-same-window
7398 (condition-case nil
7399 (make-indirect-buffer (current-buffer) "*org-goto*")
7400 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7401 (with-output-to-temp-buffer "*Org Help*"
7402 (princ (format help (if org-goto-auto-isearch
7403 " Just type for auto-isearch."
7404 " n/p/f/b/u to navigate, q to quit."))))
7405 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7406 (setq buffer-read-only nil)
7407 (let ((org-startup-truncated t)
7408 (org-startup-folded nil)
7409 (org-startup-align-all-tables nil))
7410 (org-mode)
7411 (org-overview))
7412 (setq buffer-read-only t)
7413 (if (and (boundp 'org-goto-start-pos)
7414 (integer-or-marker-p org-goto-start-pos))
7415 (progn (goto-char org-goto-start-pos)
7416 (when (outline-invisible-p)
7417 (org-show-set-visibility 'lineage)))
7418 (goto-char (point-min)))
7419 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7420 (message "Select location and press RET")
7421 (use-local-map org-goto-map)
7422 (recursive-edit)))
7423 (kill-buffer "*org-goto*")
7424 (cons org-goto-selected-point org-goto-exit-command))))
7426 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7427 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7428 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7429 (if (fboundp 'isearch-other-control-char)
7430 (progn
7431 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7432 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7433 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7434 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7435 (define-key org-goto-local-auto-isearch-map [return] nil))
7437 (defun org-goto-local-search-headings (string bound noerror)
7438 "Search and make sure that any matches are in headlines."
7439 (catch 'return
7440 (while (if isearch-forward
7441 (search-forward string bound noerror)
7442 (search-backward string bound noerror))
7443 (when (save-match-data
7444 (and (save-excursion
7445 (beginning-of-line)
7446 (looking-at org-complex-heading-regexp))
7447 (or (not (match-beginning 5))
7448 (< (point) (match-beginning 5)))))
7449 (throw 'return (point))))))
7451 (defun org-goto-local-auto-isearch ()
7452 "Start isearch."
7453 (interactive)
7454 (goto-char (point-min))
7455 (let ((keys (this-command-keys)))
7456 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7457 (isearch-mode t)
7458 (isearch-process-search-char (string-to-char keys)))))
7460 (defun org-goto-ret (&optional _arg)
7461 "Finish `org-goto' by going to the new location."
7462 (interactive "P")
7463 (setq org-goto-selected-point (point))
7464 (setq org-goto-exit-command 'return)
7465 (throw 'exit nil))
7467 (defun org-goto-left ()
7468 "Finish `org-goto' by going to the new location."
7469 (interactive)
7470 (if (org-at-heading-p)
7471 (progn
7472 (beginning-of-line 1)
7473 (setq org-goto-selected-point (point)
7474 org-goto-exit-command 'left)
7475 (throw 'exit nil))
7476 (user-error "Not on a heading")))
7478 (defun org-goto-right ()
7479 "Finish `org-goto' by going to the new location."
7480 (interactive)
7481 (if (org-at-heading-p)
7482 (progn
7483 (setq org-goto-selected-point (point)
7484 org-goto-exit-command 'right)
7485 (throw 'exit nil))
7486 (user-error "Not on a heading")))
7488 (defun org-goto-quit ()
7489 "Finish `org-goto' without cursor motion."
7490 (interactive)
7491 (setq org-goto-selected-point nil)
7492 (setq org-goto-exit-command 'quit)
7493 (throw 'exit nil))
7495 ;;; Indirect buffer display of subtrees
7497 (defvar org-indirect-dedicated-frame nil
7498 "This is the frame being used for indirect tree display.")
7499 (defvar org-last-indirect-buffer nil)
7501 (defun org-tree-to-indirect-buffer (&optional arg)
7502 "Create indirect buffer and narrow it to current subtree.
7503 With a numerical prefix ARG, go up to this level and then take that tree.
7504 If ARG is negative, go up that many levels.
7506 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7507 indirect buffer previously made with this command, to avoid proliferation of
7508 indirect buffers. However, when you call the command with a \
7509 \\[universal-argument] prefix, or
7510 when `org-indirect-buffer-display' is `new-frame', the last buffer
7511 is kept so that you can work with several indirect buffers at the same time.
7512 If `org-indirect-buffer-display' is `dedicated-frame', the \
7513 \\[universal-argument] prefix also
7514 requests that a new frame be made for the new buffer, so that the dedicated
7515 frame is not changed."
7516 (interactive "P")
7517 (let ((cbuf (current-buffer))
7518 (cwin (selected-window))
7519 (pos (point))
7520 beg end level heading ibuf)
7521 (save-excursion
7522 (org-back-to-heading t)
7523 (when (numberp arg)
7524 (setq level (org-outline-level))
7525 (when (< arg 0) (setq arg (+ level arg)))
7526 (while (> (setq level (org-outline-level)) arg)
7527 (org-up-heading-safe)))
7528 (setq beg (point)
7529 heading (org-get-heading 'no-tags))
7530 (org-end-of-subtree t t)
7531 (when (org-at-heading-p) (backward-char 1))
7532 (setq end (point)))
7533 (when (and (buffer-live-p org-last-indirect-buffer)
7534 (not (eq org-indirect-buffer-display 'new-frame))
7535 (not arg))
7536 (kill-buffer org-last-indirect-buffer))
7537 (setq ibuf (org-get-indirect-buffer cbuf heading)
7538 org-last-indirect-buffer ibuf)
7539 (cond
7540 ((or (eq org-indirect-buffer-display 'new-frame)
7541 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7542 (select-frame (make-frame))
7543 (delete-other-windows)
7544 (org-pop-to-buffer-same-window ibuf)
7545 (org-set-frame-title heading))
7546 ((eq org-indirect-buffer-display 'dedicated-frame)
7547 (raise-frame
7548 (select-frame (or (and org-indirect-dedicated-frame
7549 (frame-live-p org-indirect-dedicated-frame)
7550 org-indirect-dedicated-frame)
7551 (setq org-indirect-dedicated-frame (make-frame)))))
7552 (delete-other-windows)
7553 (org-pop-to-buffer-same-window ibuf)
7554 (org-set-frame-title (concat "Indirect: " heading)))
7555 ((eq org-indirect-buffer-display 'current-window)
7556 (org-pop-to-buffer-same-window ibuf))
7557 ((eq org-indirect-buffer-display 'other-window)
7558 (pop-to-buffer ibuf))
7559 (t (error "Invalid value")))
7560 (when (featurep 'xemacs)
7561 (save-excursion (org-mode) (turn-on-font-lock)))
7562 (narrow-to-region beg end)
7563 (outline-show-all)
7564 (goto-char pos)
7565 (run-hook-with-args 'org-cycle-hook 'all)
7566 (and (window-live-p cwin) (select-window cwin))))
7568 (defun org-get-indirect-buffer (&optional buffer heading)
7569 (setq buffer (or buffer (current-buffer)))
7570 (let ((n 1) (base (buffer-name buffer)) bname)
7571 (while (buffer-live-p
7572 (get-buffer
7573 (setq bname
7574 (concat base "-"
7575 (if heading (concat heading "-" (number-to-string n))
7576 (number-to-string n))))))
7577 (setq n (1+ n)))
7578 (condition-case nil
7579 (make-indirect-buffer buffer bname 'clone)
7580 (error (make-indirect-buffer buffer bname)))))
7582 (defun org-set-frame-title (title)
7583 "Set the title of the current frame to the string TITLE."
7584 ;; FIXME: how to name a single frame in XEmacs???
7585 (unless (featurep 'xemacs)
7586 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7588 ;;;; Structure editing
7590 ;;; Inserting headlines
7592 (defun org--line-empty-p (n)
7593 "Is the Nth next line empty?
7595 Counts the current line as N = 1 and the previous line as N = 0;
7596 see `beginning-of-line'."
7597 (save-excursion
7598 (and (not (bobp))
7599 (or (beginning-of-line n) t)
7600 (save-match-data
7601 (looking-at "[ \t]*$")))))
7603 (defun org-previous-line-empty-p ()
7604 "Is the previous line a blank line?
7605 When NEXT is non-nil, check the next line instead."
7606 (org--line-empty-p 0))
7608 (defun org-next-line-empty-p ()
7609 "Is the previous line a blank line?
7610 When NEXT is non-nil, check the next line instead."
7611 (org--line-empty-p 2))
7613 (defun org-insert-heading (&optional arg invisible-ok top)
7614 "Insert a new heading or an item with the same depth at point.
7616 If point is at the beginning of a heading or a list item, insert
7617 a new heading or a new item above the current one. If point is
7618 at the beginning of a normal line, turn the line into a heading.
7620 If point is in the middle of a headline or a list item, split the
7621 headline or the item and create a new headline/item with the text
7622 in the current line after point \(see `org-M-RET-may-split-line'
7623 on how to modify this behavior).
7625 With one universal prefix argument, set the user option
7626 `org-insert-heading-respect-content' to t for the duration of
7627 the command. This modifies the behavior described above in this
7628 ways: on list items and at the beginning of normal lines, force
7629 the insertion of a heading after the current subtree.
7631 With two universal prefix arguments, insert the heading at the
7632 end of the grandparent subtree. For example, if point is within
7633 a 2nd-level heading, then it will insert a 2nd-level heading at
7634 the end of the 1st-level parent heading.
7636 If point is at the beginning of a headline, insert a sibling
7637 before the current headline. If point is not at the beginning,
7638 split the line and create a new headline with the text in the
7639 current line after point \(see `org-M-RET-may-split-line' on how
7640 to modify this behavior).
7642 If point is at the beginning of a normal line, turn this line
7643 into a heading.
7645 When INVISIBLE-OK is set, stop at invisible headlines when going
7646 back. This is important for non-interactive uses of the
7647 command.
7649 When optional argument TOP is non-nil, insert a level 1 heading,
7650 unconditionally."
7651 (interactive "P")
7652 (when (org-called-interactively-p 'any) (org-reveal))
7653 (let ((itemp (and (not top) (org-in-item-p)))
7654 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7655 (respect-content (or org-insert-heading-respect-content
7656 (equal arg '(4))))
7657 (initial-content ""))
7659 (cond
7661 ((or (= (buffer-size) 0)
7662 (and (not (save-excursion
7663 (and (ignore-errors (org-back-to-heading invisible-ok))
7664 (org-at-heading-p))))
7665 (or arg (not itemp))))
7666 ;; At beginning of buffer or so high up that only a heading
7667 ;; makes sense.
7668 (cond ((and (bolp) (not respect-content)) (insert "* "))
7669 ((not respect-content)
7670 (unless may-split (end-of-line))
7671 (insert "\n* "))
7672 ((re-search-forward org-outline-regexp-bol nil t)
7673 (beginning-of-line)
7674 (insert "* \n")
7675 (backward-char))
7676 (t (goto-char (point-max))
7677 (insert "\n* ")))
7678 (run-hooks 'org-insert-heading-hook))
7680 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7683 ;; Maybe move at the end of the subtree
7684 (when (equal arg '(16))
7685 (org-up-heading-safe)
7686 (org-end-of-subtree t))
7687 ;; Insert a heading
7688 (save-restriction
7689 (widen)
7690 (let* ((level nil)
7691 (on-heading (org-at-heading-p))
7692 (empty-line-p (if on-heading
7693 (org-previous-line-empty-p)
7694 ;; We will decide later
7695 nil))
7696 ;; Get a level string to fall back on.
7697 (fix-level
7698 (if (org-before-first-heading-p) "*"
7699 (save-excursion
7700 (org-back-to-heading t)
7701 (when (org-previous-line-empty-p) (setq empty-line-p t))
7702 (looking-at org-outline-regexp)
7703 (make-string (1- (length (match-string 0))) ?*))))
7704 (stars
7705 (save-excursion
7706 (condition-case nil
7707 (if top "* "
7708 (org-back-to-heading invisible-ok)
7709 (when (and (not on-heading)
7710 (featurep 'org-inlinetask)
7711 (integerp org-inlinetask-min-level)
7712 (>= (length (match-string 0))
7713 org-inlinetask-min-level))
7714 ;; Find a heading level before the inline
7715 ;; task.
7716 (while (and (setq level (org-up-heading-safe))
7717 (>= level org-inlinetask-min-level)))
7718 (if (org-at-heading-p)
7719 (org-back-to-heading invisible-ok)
7720 (error "This should not happen")))
7721 (unless (and (save-excursion
7722 (save-match-data
7723 (org-backward-heading-same-level
7724 1 invisible-ok))
7725 (= (point) (match-beginning 0)))
7726 (not (org-next-line-empty-p)))
7727 (setq empty-line-p (or empty-line-p
7728 (org-previous-line-empty-p))))
7729 (match-string 0))
7730 (error (or fix-level "* ")))))
7731 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7732 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7734 ;; If we insert after content, move there and clean up
7735 ;; whitespace.
7736 (when (and respect-content
7737 (not (org-looking-at-p org-outline-regexp-bol)))
7738 (if (not (org-before-first-heading-p))
7739 (org-end-of-subtree nil t)
7740 (re-search-forward org-outline-regexp-bol)
7741 (beginning-of-line 0))
7742 (skip-chars-backward " \r\t\n")
7743 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7744 (looking-at "[ \t]+") (replace-match ""))
7745 (unless (eobp) (forward-char 1))
7746 (when (looking-at "^\\*")
7747 (unless (bobp) (backward-char 1))
7748 (insert "\n")))
7750 ;; If we are splitting, grab the text that should be moved
7751 ;; to the new headline.
7752 (when may-split
7753 (if (org-at-heading-p)
7754 ;; This is a heading: split intelligently (keeping
7755 ;; tags).
7756 (let ((pos (point)))
7757 (beginning-of-line)
7758 (unless (looking-at org-complex-heading-regexp)
7759 (error "This should not happen"))
7760 (when (and (match-beginning 4)
7761 (> pos (match-beginning 4))
7762 (< pos (match-end 4)))
7763 (setq initial-content (buffer-substring pos (match-end 4)))
7764 (goto-char pos)
7765 (delete-region (point) (match-end 4))
7766 (if (looking-at "[ \t]*$")
7767 (replace-match "")
7768 (insert (make-string (length initial-content) ?\s)))
7769 (setq initial-content (org-trim initial-content)))
7770 (goto-char pos))
7771 ;; A normal line.
7772 (setq initial-content
7773 (org-trim
7774 (delete-and-extract-region (point) (line-end-position))))))
7776 ;; If we are at the beginning of the line, insert before it.
7777 ;; Otherwise, after it.
7778 (cond
7779 ((and (bolp) (looking-at "[ \t]*$")))
7780 ((bolp) (save-excursion (insert "\n")))
7781 (t (end-of-line)
7782 (insert "\n")))
7784 ;; Insert the new heading
7785 (insert stars)
7786 (just-one-space)
7787 (insert initial-content)
7788 (unless (and blank (org-previous-line-empty-p))
7789 (org-N-empty-lines-before-current (if blank 1 0)))
7790 ;; Adjust visibility, which may be messed up if we removed
7791 ;; blank lines while previous entry was hidden.
7792 (let ((bol (line-beginning-position)))
7793 (dolist (o (overlays-at (1- bol)))
7794 (when (and (eq (overlay-get o 'invisible) 'outline)
7795 (eq (overlay-end o) bol))
7796 (move-overlay o (overlay-start o) (1- bol)))))
7797 (run-hooks 'org-insert-heading-hook)))))))
7799 (defun org-N-empty-lines-before-current (N)
7800 "Make the number of empty lines before current exactly N.
7801 So this will delete or add empty lines."
7802 (save-excursion
7803 (beginning-of-line)
7804 (let ((p (point)))
7805 (skip-chars-backward " \r\t\n")
7806 (unless (bolp) (forward-line))
7807 (delete-region (point) p))
7808 (when (> N 0) (insert (make-string N ?\n)))))
7810 (defun org-get-heading (&optional no-tags no-todo)
7811 "Return the heading of the current entry, without the stars.
7812 When NO-TAGS is non-nil, don't include tags.
7813 When NO-TODO is non-nil, don't include TODO keywords."
7814 (save-excursion
7815 (org-back-to-heading t)
7816 (cond
7817 ((and no-tags no-todo)
7818 (looking-at org-complex-heading-regexp)
7819 (match-string 4))
7820 (no-tags
7821 (looking-at (concat org-outline-regexp
7822 "\\(.*?\\)"
7823 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7824 (match-string 1))
7825 (no-todo
7826 (looking-at org-todo-line-regexp)
7827 (match-string 3))
7828 (t (looking-at org-heading-regexp)
7829 (match-string 2)))))
7831 (defvar orgstruct-mode) ; defined below
7833 (defun org-heading-components ()
7834 "Return the components of the current heading.
7835 This is a list with the following elements:
7836 - the level as an integer
7837 - the reduced level, different if `org-odd-levels-only' is set.
7838 - the TODO keyword, or nil
7839 - the priority character, like ?A, or nil if no priority is given
7840 - the headline text itself, or the tags string if no headline text
7841 - the tags string, or nil."
7842 (save-excursion
7843 (org-back-to-heading t)
7844 (when (let (case-fold-search)
7845 (looking-at
7846 (if orgstruct-mode
7847 org-heading-regexp
7848 org-complex-heading-regexp)))
7849 (if orgstruct-mode
7850 (list (length (match-string 1))
7851 (org-reduced-level (length (match-string 1)))
7854 (match-string 2)
7855 nil)
7856 (list (length (match-string 1))
7857 (org-reduced-level (length (match-string 1)))
7858 (org-match-string-no-properties 2)
7859 (and (match-end 3) (aref (match-string 3) 2))
7860 (org-match-string-no-properties 4)
7861 (org-match-string-no-properties 5))))))
7863 (defun org-get-entry ()
7864 "Get the entry text, after heading, entire subtree."
7865 (save-excursion
7866 (org-back-to-heading t)
7867 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7869 (defun org-edit-headline (&optional heading)
7870 "Edit the current headline.
7871 Set it to HEADING when provided."
7872 (interactive)
7873 (org-with-wide-buffer
7874 (org-back-to-heading t)
7875 (when (looking-at org-complex-heading-regexp)
7876 (let* ((old (match-string-no-properties 4))
7877 (new (org-trim (or heading (read-string "Edit: " old)))))
7878 (unless (equal old new)
7879 (if old (replace-match new t t nil 4)
7880 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7881 (insert " " new))
7882 (org-set-tags nil t)
7883 (when (looking-at "[ \t]*$") (replace-match "")))))))
7885 (defun org-insert-heading-after-current ()
7886 "Insert a new heading with same level as current, after current subtree."
7887 (interactive)
7888 (org-back-to-heading)
7889 (org-insert-heading)
7890 (org-move-subtree-down)
7891 (end-of-line 1))
7893 (defun org-insert-heading-respect-content (&optional invisible-ok)
7894 "Insert heading with `org-insert-heading-respect-content' set to t."
7895 (interactive)
7896 (org-insert-heading '(4) invisible-ok))
7898 (defun org-insert-todo-heading-respect-content (&optional force-state)
7899 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7900 (interactive)
7901 (org-insert-todo-heading force-state '(4)))
7903 (defun org-insert-todo-heading (arg &optional force-heading)
7904 "Insert a new heading with the same level and TODO state as current heading.
7905 If the heading has no TODO state, or if the state is DONE, use the first
7906 state (TODO by default). Also with one prefix arg, force first state. With
7907 two prefix args, force inserting at the end of the parent subtree."
7908 (interactive "P")
7909 (when (or force-heading (not (org-insert-item 'checkbox)))
7910 (org-insert-heading (or (and (equal arg '(16)) '(16))
7911 force-heading))
7912 (save-excursion
7913 (org-back-to-heading)
7914 (outline-previous-heading)
7915 (looking-at org-todo-line-regexp))
7916 (let*
7917 ((new-mark-x
7918 (if (or (equal arg '(4))
7919 (not (match-beginning 2))
7920 (member (match-string 2) org-done-keywords))
7921 (car org-todo-keywords-1)
7922 (match-string 2)))
7923 (new-mark
7925 (run-hook-with-args-until-success
7926 'org-todo-get-default-hook new-mark-x nil)
7927 new-mark-x)))
7928 (beginning-of-line 1)
7929 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7930 (if org-treat-insert-todo-heading-as-state-change
7931 (org-todo new-mark)
7932 (insert new-mark " "))))
7933 (when org-provide-todo-statistics
7934 (org-update-parent-todo-statistics))))
7936 (defun org-insert-subheading (arg)
7937 "Insert a new subheading and demote it.
7938 Works for outline headings and for plain lists alike."
7939 (interactive "P")
7940 (org-insert-heading arg)
7941 (cond
7942 ((org-at-heading-p) (org-do-demote))
7943 ((org-at-item-p) (org-indent-item))))
7945 (defun org-insert-todo-subheading (arg)
7946 "Insert a new subheading with TODO keyword or checkbox and demote it.
7947 Works for outline headings and for plain lists alike."
7948 (interactive "P")
7949 (org-insert-todo-heading arg)
7950 (cond
7951 ((org-at-heading-p) (org-do-demote))
7952 ((org-at-item-p) (org-indent-item))))
7954 ;;; Promotion and Demotion
7956 (defvar org-after-demote-entry-hook nil
7957 "Hook run after an entry has been demoted.
7958 The cursor will be at the beginning of the entry.
7959 When a subtree is being demoted, the hook will be called for each node.")
7961 (defvar org-after-promote-entry-hook nil
7962 "Hook run after an entry has been promoted.
7963 The cursor will be at the beginning of the entry.
7964 When a subtree is being promoted, the hook will be called for each node.")
7966 (defun org-promote-subtree ()
7967 "Promote the entire subtree.
7968 See also `org-promote'."
7969 (interactive)
7970 (save-excursion
7971 (org-with-limited-levels (org-map-tree 'org-promote)))
7972 (org-fix-position-after-promote))
7974 (defun org-demote-subtree ()
7975 "Demote the entire subtree.
7976 See `org-demote' and `org-promote'."
7977 (interactive)
7978 (save-excursion
7979 (org-with-limited-levels (org-map-tree 'org-demote)))
7980 (org-fix-position-after-promote))
7982 (defun org-do-promote ()
7983 "Promote the current heading higher up the tree.
7984 If the region is active in `transient-mark-mode', promote all
7985 headings in the region."
7986 (interactive)
7987 (save-excursion
7988 (if (org-region-active-p)
7989 (org-map-region 'org-promote (region-beginning) (region-end))
7990 (org-promote)))
7991 (org-fix-position-after-promote))
7993 (defun org-do-demote ()
7994 "Demote the current heading lower down the tree.
7995 If the region is active in `transient-mark-mode', demote all
7996 headings in the region."
7997 (interactive)
7998 (save-excursion
7999 (if (org-region-active-p)
8000 (org-map-region 'org-demote (region-beginning) (region-end))
8001 (org-demote)))
8002 (org-fix-position-after-promote))
8004 (defun org-fix-position-after-promote ()
8005 "Fix cursor position and indentation after demoting/promoting."
8006 (let ((pos (point)))
8007 (when (save-excursion
8008 (beginning-of-line 1)
8009 (looking-at org-todo-line-regexp)
8010 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8011 (cond ((eobp) (insert " "))
8012 ((eolp) (insert " "))
8013 ((equal (char-after) ?\ ) (forward-char 1))))))
8015 (defun org-current-level ()
8016 "Return the level of the current entry, or nil if before the first headline.
8017 The level is the number of stars at the beginning of the
8018 headline. Use `org-reduced-level' to remove the effect of
8019 `org-odd-levels'. Unlike to `org-outline-level', this function
8020 ignores inlinetasks."
8021 (let ((level (org-with-limited-levels (org-outline-level))))
8022 (and (> level 0) level)))
8024 (defun org-get-previous-line-level ()
8025 "Return the outline depth of the last headline before the current line.
8026 Returns 0 for the first headline in the buffer, and nil if before the
8027 first headline."
8028 (and (org-current-level)
8029 (or (and (/= (line-beginning-position) (point-min))
8030 (save-excursion (beginning-of-line 0) (org-current-level)))
8031 0)))
8033 (defun org-reduced-level (l)
8034 "Compute the effective level of a heading.
8035 This takes into account the setting of `org-odd-levels-only'."
8036 (cond
8037 ((zerop l) 0)
8038 (org-odd-levels-only (1+ (floor (/ l 2))))
8039 (t l)))
8041 (defun org-level-increment ()
8042 "Return the number of stars that will be added or removed at a
8043 time to headlines when structure editing, based on the value of
8044 `org-odd-levels-only'."
8045 (if org-odd-levels-only 2 1))
8047 (defun org-get-valid-level (level &optional change)
8048 "Rectify a level change under the influence of `org-odd-levels-only'
8049 LEVEL is a current level, CHANGE is by how much the level should be
8050 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8051 even level numbers will become the next higher odd number."
8052 (if org-odd-levels-only
8053 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8054 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8055 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8056 (max 1 (+ level (or change 0)))))
8057 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8059 (defun org-promote ()
8060 "Promote the current heading higher up the tree."
8061 (org-with-wide-buffer
8062 (org-back-to-heading t)
8063 (let* ((after-change-functions (remq 'flyspell-after-change-function
8064 after-change-functions))
8065 (level (save-match-data (funcall outline-level)))
8066 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8067 (diff (abs (- level (length up-head) -1))))
8068 (cond
8069 ((and (= level 1) org-allow-promoting-top-level-subtree)
8070 (replace-match "# " nil t))
8071 ((= level 1)
8072 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8073 (t (replace-match up-head nil t)))
8074 (unless (= level 1)
8075 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8076 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8077 (run-hooks 'org-after-promote-entry-hook))))
8079 (defun org-demote ()
8080 "Demote the current heading lower down the tree."
8081 (org-with-wide-buffer
8082 (org-back-to-heading t)
8083 (let* ((after-change-functions (remq 'flyspell-after-change-function
8084 after-change-functions))
8085 (level (save-match-data (funcall outline-level)))
8086 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8087 (diff (abs (- level (length down-head) -1))))
8088 (replace-match down-head nil t)
8089 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8090 (when org-adapt-indentation (org-fixup-indentation diff))
8091 (run-hooks 'org-after-demote-entry-hook))))
8093 (defun org-cycle-level ()
8094 "Cycle the level of an empty headline through possible states.
8095 This goes first to child, then to parent, level, then up the hierarchy.
8096 After top level, it switches back to sibling level."
8097 (interactive)
8098 (let ((org-adapt-indentation nil))
8099 (when (org-point-at-end-of-empty-headline)
8100 (setq this-command 'org-cycle-level) ; Only needed for caching
8101 (let ((cur-level (org-current-level))
8102 (prev-level (org-get-previous-line-level)))
8103 (cond
8104 ;; If first headline in file, promote to top-level.
8105 ((= prev-level 0)
8106 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8107 do (org-do-promote)))
8108 ;; If same level as prev, demote one.
8109 ((= prev-level cur-level)
8110 (org-do-demote))
8111 ;; If parent is top-level, promote to top level if not already.
8112 ((= prev-level 1)
8113 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8114 do (org-do-promote)))
8115 ;; If top-level, return to prev-level.
8116 ((= cur-level 1)
8117 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8118 do (org-do-demote)))
8119 ;; If less than prev-level, promote one.
8120 ((< cur-level prev-level)
8121 (org-do-promote))
8122 ;; If deeper than prev-level, promote until higher than
8123 ;; prev-level.
8124 ((> cur-level prev-level)
8125 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8126 do (org-do-promote))))
8127 t))))
8129 (defun org-map-tree (fun)
8130 "Call FUN for every heading underneath the current one."
8131 (org-back-to-heading)
8132 (let ((level (funcall outline-level)))
8133 (save-excursion
8134 (funcall fun)
8135 (while (and (progn
8136 (outline-next-heading)
8137 (> (funcall outline-level) level))
8138 (not (eobp)))
8139 (funcall fun)))))
8141 (defun org-map-region (fun beg end)
8142 "Call FUN for every heading between BEG and END."
8143 (let ((org-ignore-region t))
8144 (save-excursion
8145 (setq end (copy-marker end))
8146 (goto-char beg)
8147 (when (and (re-search-forward org-outline-regexp-bol nil t)
8148 (< (point) end))
8149 (funcall fun))
8150 (while (and (progn
8151 (outline-next-heading)
8152 (< (point) end))
8153 (not (eobp)))
8154 (funcall fun)))))
8156 (defun org-fixup-indentation (diff)
8157 "Change the indentation in the current entry by DIFF.
8159 DIFF is an integer. Indentation is done according to the
8160 following rules:
8162 - Planning information and property drawers are always indented
8163 according to the new level of the headline;
8165 - Footnote definitions and their contents are ignored;
8167 - Inlinetasks' boundaries are not shifted;
8169 - Empty lines are ignored;
8171 - Other lines' indentation are shifted by DIFF columns, unless
8172 it would introduce a structural change in the document, in
8173 which case no shifting is done at all.
8175 Assume point is at a heading or an inlinetask beginning."
8176 (org-with-wide-buffer
8177 (narrow-to-region (line-beginning-position)
8178 (save-excursion
8179 (if (org-with-limited-levels (org-at-heading-p))
8180 (org-with-limited-levels (outline-next-heading))
8181 (org-inlinetask-goto-end))
8182 (point)))
8183 (forward-line)
8184 ;; Indent properly planning info and property drawer.
8185 (when (org-looking-at-p org-planning-line-re)
8186 (org-indent-line)
8187 (forward-line))
8188 (when (looking-at org-property-drawer-re)
8189 (goto-char (match-end 0))
8190 (forward-line)
8191 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8192 (catch 'no-shift
8193 (when (zerop diff) (throw 'no-shift nil))
8194 ;; If DIFF is negative, first check if a shift is possible at all
8195 ;; (e.g., it doesn't break structure). This can only happen if
8196 ;; some contents are not properly indented.
8197 (let ((case-fold-search t))
8198 (when (< diff 0)
8199 (let ((diff (- diff))
8200 (forbidden-re (concat org-outline-regexp
8201 "\\|"
8202 (substring org-footnote-definition-re 1))))
8203 (save-excursion
8204 (while (not (eobp))
8205 (cond
8206 ((org-looking-at-p "[ \t]*$") (forward-line))
8207 ((and (org-looking-at-p org-footnote-definition-re)
8208 (let ((e (org-element-at-point)))
8209 (and (eq (org-element-type e) 'footnote-definition)
8210 (goto-char (org-element-property :end e))))))
8211 ((org-looking-at-p org-outline-regexp) (forward-line))
8212 ;; Give up if shifting would move before column 0 or
8213 ;; if it would introduce a headline or a footnote
8214 ;; definition.
8216 (skip-chars-forward " \t")
8217 (let ((ind (current-column)))
8218 (when (or (< ind diff)
8219 (and (= ind diff) (org-looking-at-p forbidden-re)))
8220 (throw 'no-shift nil)))
8221 ;; Ignore contents of example blocks and source
8222 ;; blocks if their indentation is meant to be
8223 ;; preserved. Jump to block's closing line.
8224 (beginning-of-line)
8225 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8226 (let ((e (org-element-at-point)))
8227 (and (memq (org-element-type e)
8228 '(example-block src-block))
8229 (or org-src-preserve-indentation
8230 (org-element-property :preserve-indent e))
8231 (goto-char (org-element-property :end e))
8232 (progn (skip-chars-backward " \r\t\n")
8233 (beginning-of-line)
8234 t))))
8235 (forward-line))))))))
8236 ;; Shift lines but footnote definitions, inlinetasks boundaries
8237 ;; by DIFF. Also skip contents of source or example blocks
8238 ;; when indentation is meant to be preserved.
8239 (while (not (eobp))
8240 (cond
8241 ((and (org-looking-at-p org-footnote-definition-re)
8242 (let ((e (org-element-at-point)))
8243 (and (eq (org-element-type e) 'footnote-definition)
8244 (goto-char (org-element-property :end e))))))
8245 ((org-looking-at-p org-outline-regexp) (forward-line))
8246 ((org-looking-at-p "[ \t]*$") (forward-line))
8248 (org-indent-line-to (+ (org-get-indentation) diff))
8249 (beginning-of-line)
8250 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8251 (let ((e (org-element-at-point)))
8252 (and (memq (org-element-type e)
8253 '(example-block src-block))
8254 (or org-src-preserve-indentation
8255 (org-element-property :preserve-indent e))
8256 (goto-char (org-element-property :end e))
8257 (progn (skip-chars-backward " \r\t\n")
8258 (beginning-of-line)
8259 t))))
8260 (forward-line)))))))))
8262 (defun org-convert-to-odd-levels ()
8263 "Convert an org-mode file with all levels allowed to one with odd levels.
8264 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8265 level 5 etc."
8266 (interactive)
8267 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8268 (let ((outline-level 'org-outline-level)
8269 (org-odd-levels-only nil) n)
8270 (save-excursion
8271 (goto-char (point-min))
8272 (while (re-search-forward "^\\*\\*+ " nil t)
8273 (setq n (- (length (match-string 0)) 2))
8274 (while (>= (setq n (1- n)) 0)
8275 (org-demote))
8276 (end-of-line 1))))))
8278 (defun org-convert-to-oddeven-levels ()
8279 "Convert an org-mode file with only odd levels to one with odd/even levels.
8280 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8281 file contains a section with an even level, conversion would
8282 destroy the structure of the file. An error is signaled in this
8283 case."
8284 (interactive)
8285 (goto-char (point-min))
8286 ;; First check if there are no even levels
8287 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8288 (org-show-set-visibility 'canonical)
8289 (error "Not all levels are odd in this file. Conversion not possible"))
8290 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8291 (let ((outline-regexp org-outline-regexp)
8292 (outline-level 'org-outline-level)
8293 (org-odd-levels-only nil) n)
8294 (save-excursion
8295 (goto-char (point-min))
8296 (while (re-search-forward "^\\*\\*+ " nil t)
8297 (setq n (/ (1- (length (match-string 0))) 2))
8298 (while (>= (setq n (1- n)) 0)
8299 (org-promote))
8300 (end-of-line 1))))))
8302 (defun org-tr-level (n)
8303 "Make N odd if required."
8304 (if org-odd-levels-only (1+ (/ n 2)) n))
8306 ;;; Vertical tree motion, cutting and pasting of subtrees
8308 (defun org-move-subtree-up (&optional arg)
8309 "Move the current subtree up past ARG headlines of the same level."
8310 (interactive "p")
8311 (org-move-subtree-down (- (prefix-numeric-value arg))))
8313 (defun org-move-subtree-down (&optional arg)
8314 "Move the current subtree down past ARG headlines of the same level."
8315 (interactive "p")
8316 (setq arg (prefix-numeric-value arg))
8317 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8318 'org-get-last-sibling))
8319 (ins-point (make-marker))
8320 (cnt (abs arg))
8321 (col (current-column))
8322 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8323 ;; Select the tree
8324 (org-back-to-heading)
8325 (setq beg0 (point))
8326 (save-excursion
8327 (setq ne-beg (org-back-over-empty-lines))
8328 (setq beg (point)))
8329 (save-match-data
8330 (save-excursion (outline-end-of-heading)
8331 (setq folded (outline-invisible-p)))
8332 (progn (org-end-of-subtree nil t)
8333 (unless (eobp) (backward-char))))
8334 (outline-next-heading)
8335 (setq ne-end (org-back-over-empty-lines))
8336 (setq end (point))
8337 (goto-char beg0)
8338 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8339 ;; include less whitespace
8340 (save-excursion
8341 (goto-char beg)
8342 (forward-line (- ne-beg ne-end))
8343 (setq beg (point))))
8344 ;; Find insertion point, with error handling
8345 (while (> cnt 0)
8346 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8347 (progn (goto-char beg0)
8348 (user-error "Cannot move past superior level or buffer limit")))
8349 (setq cnt (1- cnt)))
8350 (when (> arg 0)
8351 ;; Moving forward - still need to move over subtree
8352 (org-end-of-subtree t t)
8353 (save-excursion
8354 (org-back-over-empty-lines)
8355 (or (bolp) (newline))))
8356 (setq ne-ins (org-back-over-empty-lines))
8357 (move-marker ins-point (point))
8358 (setq txt (buffer-substring beg end))
8359 (org-save-markers-in-region beg end)
8360 (delete-region beg end)
8361 (org-remove-empty-overlays-at beg)
8362 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8363 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8364 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8365 (let ((bbb (point)))
8366 (insert-before-markers txt)
8367 (org-reinstall-markers-in-region bbb)
8368 (move-marker ins-point bbb))
8369 (or (bolp) (insert "\n"))
8370 (setq ins-end (point))
8371 (goto-char ins-point)
8372 (org-skip-whitespace)
8373 (when (and (< arg 0)
8374 (org-first-sibling-p)
8375 (> ne-ins ne-beg))
8376 ;; Move whitespace back to beginning
8377 (save-excursion
8378 (goto-char ins-end)
8379 (let ((kill-whole-line t))
8380 (kill-line (- ne-ins ne-beg)) (point)))
8381 (insert (make-string (- ne-ins ne-beg) ?\n)))
8382 (move-marker ins-point nil)
8383 (if folded
8384 (outline-hide-subtree)
8385 (org-show-entry)
8386 (org-show-children)
8387 (org-cycle-hide-drawers 'children))
8388 (org-clean-visibility-after-subtree-move)
8389 ;; move back to the initial column we were at
8390 (move-to-column col)))
8392 (defvar org-subtree-clip ""
8393 "Clipboard for cut and paste of subtrees.
8394 This is actually only a copy of the kill, because we use the normal kill
8395 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8397 (defvar org-subtree-clip-folded nil
8398 "Was the last copied subtree folded?
8399 This is used to fold the tree back after pasting.")
8401 (defun org-cut-subtree (&optional n)
8402 "Cut the current subtree into the clipboard.
8403 With prefix arg N, cut this many sequential subtrees.
8404 This is a short-hand for marking the subtree and then cutting it."
8405 (interactive "p")
8406 (org-copy-subtree n 'cut))
8408 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8409 "Copy the current subtree it in the clipboard.
8410 With prefix arg N, copy this many sequential subtrees.
8411 This is a short-hand for marking the subtree and then copying it.
8412 If CUT is non-nil, actually cut the subtree.
8413 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8414 of some markers in the region, even if CUT is non-nil. This is
8415 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8416 (interactive "p")
8417 (let (beg end folded (beg0 (point)))
8418 (if (org-called-interactively-p 'any)
8419 (org-back-to-heading nil) ; take what looks like a subtree
8420 (org-back-to-heading t)) ; take what is really there
8421 (setq beg (point))
8422 (skip-chars-forward " \t\r\n")
8423 (save-match-data
8424 (if nosubtrees
8425 (outline-next-heading)
8426 (save-excursion (outline-end-of-heading)
8427 (setq folded (outline-invisible-p)))
8428 (ignore-errors (org-forward-heading-same-level (1- n) t))
8429 (org-end-of-subtree t t)))
8430 ;; Include the end of an inlinetask
8431 (when (and (featurep 'org-inlinetask)
8432 (looking-at-p (concat (org-inlinetask-outline-regexp)
8433 "END[ \t]*$")))
8434 (end-of-line))
8435 (setq end (point))
8436 (goto-char beg0)
8437 (when (> end beg)
8438 (setq org-subtree-clip-folded folded)
8439 (when (or cut force-store-markers)
8440 (org-save-markers-in-region beg end))
8441 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8442 (setq org-subtree-clip (current-kill 0))
8443 (message "%s: Subtree(s) with %d characters"
8444 (if cut "Cut" "Copied")
8445 (length org-subtree-clip)))))
8447 (defun org-paste-subtree (&optional level tree for-yank remove)
8448 "Paste the clipboard as a subtree, with modification of headline level.
8449 The entire subtree is promoted or demoted in order to match a new headline
8450 level.
8452 If the cursor is at the beginning of a headline, the same level as
8453 that headline is used to paste the tree.
8455 If not, the new level is derived from the *visible* headings
8456 before and after the insertion point, and taken to be the inferior headline
8457 level of the two. So if the previous visible heading is level 3 and the
8458 next is level 4 (or vice versa), level 4 will be used for insertion.
8459 This makes sure that the subtree remains an independent subtree and does
8460 not swallow low level entries.
8462 You can also force a different level, either by using a numeric prefix
8463 argument, or by inserting the heading marker by hand. For example, if the
8464 cursor is after \"*****\", then the tree will be shifted to level 5.
8466 If optional TREE is given, use this text instead of the kill ring.
8468 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8469 move back over whitespace before inserting, and move point to the end of
8470 the inserted text when done.
8472 When REMOVE is non-nil, remove the subtree from the clipboard."
8473 (interactive "P")
8474 (setq tree (or tree (and kill-ring (current-kill 0))))
8475 (unless (org-kill-is-subtree-p tree)
8476 (user-error "%s"
8477 (substitute-command-keys
8478 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8479 (org-with-limited-levels
8480 (let* ((visp (not (outline-invisible-p)))
8481 (txt tree)
8482 (^re_ "\\(\\*+\\)[ \t]*")
8483 (old-level (if (string-match org-outline-regexp-bol txt)
8484 (- (match-end 0) (match-beginning 0) 1)
8485 -1))
8486 (force-level (cond (level (prefix-numeric-value level))
8487 ((and (looking-at "[ \t]*$")
8488 (string-match
8489 "^\\*+$" (buffer-substring
8490 (point-at-bol) (point))))
8491 (- (match-end 0) (match-beginning 0)))
8492 ((and (bolp)
8493 (looking-at org-outline-regexp))
8494 (- (match-end 0) (point) 1))))
8495 (previous-level (save-excursion
8496 (condition-case nil
8497 (progn
8498 (outline-previous-visible-heading 1)
8499 (if (looking-at ^re_)
8500 (- (match-end 0) (match-beginning 0) 1)
8502 (error 1))))
8503 (next-level (save-excursion
8504 (condition-case nil
8505 (progn
8506 (or (looking-at org-outline-regexp)
8507 (outline-next-visible-heading 1))
8508 (if (looking-at ^re_)
8509 (- (match-end 0) (match-beginning 0) 1)
8511 (error 1))))
8512 (new-level (or force-level (max previous-level next-level)))
8513 (shift (if (or (= old-level -1)
8514 (= new-level -1)
8515 (= old-level new-level))
8517 (- new-level old-level)))
8518 (delta (if (> shift 0) -1 1))
8519 (func (if (> shift 0) 'org-demote 'org-promote))
8520 (org-odd-levels-only nil)
8521 beg end newend)
8522 ;; Remove the forced level indicator
8523 (when force-level
8524 (delete-region (point-at-bol) (point)))
8525 ;; Paste
8526 (beginning-of-line (if (bolp) 1 2))
8527 (setq beg (point))
8528 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8529 (insert-before-markers txt)
8530 (unless (string-match "\n\\'" txt) (insert "\n"))
8531 (setq newend (point))
8532 (org-reinstall-markers-in-region beg)
8533 (setq end (point))
8534 (goto-char beg)
8535 (skip-chars-forward " \t\n\r")
8536 (setq beg (point))
8537 (when (and (outline-invisible-p) visp)
8538 (save-excursion (outline-show-heading)))
8539 ;; Shift if necessary
8540 (unless (= shift 0)
8541 (save-restriction
8542 (narrow-to-region beg end)
8543 (while (not (= shift 0))
8544 (org-map-region func (point-min) (point-max))
8545 (setq shift (+ delta shift)))
8546 (goto-char (point-min))
8547 (setq newend (point-max))))
8548 (when (or (org-called-interactively-p 'interactive) for-yank)
8549 (message "Clipboard pasted as level %d subtree" new-level))
8550 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8551 kill-ring
8552 (eq org-subtree-clip (current-kill 0))
8553 org-subtree-clip-folded)
8554 ;; The tree was folded before it was killed/copied
8555 (outline-hide-subtree))
8556 (and for-yank (goto-char newend))
8557 (and remove (setq kill-ring (cdr kill-ring))))))
8559 (defun org-kill-is-subtree-p (&optional txt)
8560 "Check if the current kill is an outline subtree, or a set of trees.
8561 Returns nil if kill does not start with a headline, or if the first
8562 headline level is not the largest headline level in the tree.
8563 So this will actually accept several entries of equal levels as well,
8564 which is OK for `org-paste-subtree'.
8565 If optional TXT is given, check this string instead of the current kill."
8566 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8567 (re (org-get-limited-outline-regexp))
8568 (^re (concat "^" re))
8569 (start-level (and kill
8570 (string-match
8571 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8572 kill)
8573 (- (match-end 2) (match-beginning 2) 1)))
8574 (start (1+ (or (match-beginning 2) -1))))
8575 (if (not start-level)
8576 (progn
8577 nil) ;; does not even start with a heading
8578 (catch 'exit
8579 (while (setq start (string-match ^re kill (1+ start)))
8580 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8581 (throw 'exit nil)))
8582 t))))
8584 (defvar org-markers-to-move nil
8585 "Markers that should be moved with a cut-and-paste operation.
8586 Those markers are stored together with their positions relative to
8587 the start of the region.")
8589 (defun org-save-markers-in-region (beg end)
8590 "Check markers in region.
8591 If these markers are between BEG and END, record their position relative
8592 to BEG, so that after moving the block of text, we can put the markers back
8593 into place.
8594 This function gets called just before an entry or tree gets cut from the
8595 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8596 called immediately, to move the markers with the entries."
8597 (setq org-markers-to-move nil)
8598 (when (featurep 'org-clock)
8599 (org-clock-save-markers-for-cut-and-paste beg end))
8600 (when (featurep 'org-agenda)
8601 (org-agenda-save-markers-for-cut-and-paste beg end)))
8603 (defun org-check-and-save-marker (marker beg end)
8604 "Check if MARKER is between BEG and END.
8605 If yes, remember the marker and the distance to BEG."
8606 (when (and (marker-buffer marker)
8607 (equal (marker-buffer marker) (current-buffer))
8608 (>= marker beg) (< marker end))
8609 (push (cons marker (- marker beg)) org-markers-to-move)))
8611 (defun org-reinstall-markers-in-region (beg)
8612 "Move all remembered markers to their position relative to BEG."
8613 (dolist (x org-markers-to-move)
8614 (move-marker (car x) (+ beg (cdr x))))
8615 (setq org-markers-to-move nil))
8617 (defun org-narrow-to-subtree ()
8618 "Narrow buffer to the current subtree."
8619 (interactive)
8620 (save-excursion
8621 (save-match-data
8622 (org-with-limited-levels
8623 (narrow-to-region
8624 (progn (org-back-to-heading t) (point))
8625 (progn (org-end-of-subtree t t)
8626 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8627 (point)))))))
8629 (defun org-narrow-to-block ()
8630 "Narrow buffer to the current block."
8631 (interactive)
8632 (let* ((case-fold-search t)
8633 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8634 "^[ \t]*#\\+end_.*")))
8635 (if blockp
8636 (narrow-to-region (car blockp) (cdr blockp))
8637 (user-error "Not in a block"))))
8639 (defun org-clone-subtree-with-time-shift (n &optional shift)
8640 "Clone the task (subtree) at point N times.
8641 The clones will be inserted as siblings.
8643 In interactive use, the user will be prompted for the number of
8644 clones to be produced. If the entry has a timestamp, the user
8645 will also be prompted for a time shift, which may be a repeater
8646 as used in time stamps, for example `+3d'. To disable this,
8647 you can call the function with a universal prefix argument.
8649 When a valid repeater is given and the entry contains any time
8650 stamps, the clones will become a sequence in time, with time
8651 stamps in the subtree shifted for each clone produced. If SHIFT
8652 is nil or the empty string, time stamps will be left alone. The
8653 ID property of the original subtree is removed.
8655 If the original subtree did contain time stamps with a repeater,
8656 the following will happen:
8657 - the repeater will be removed in each clone
8658 - an additional clone will be produced, with the current, unshifted
8659 date(s) in the entry.
8660 - the original entry will be placed *after* all the clones, with
8661 repeater intact.
8662 - the start days in the repeater in the original entry will be shifted
8663 to past the last clone.
8664 In this way you can spell out a number of instances of a repeating task,
8665 and still retain the repeater to cover future instances of the task.
8667 As described above, N+1 clones are produced when the original
8668 subtree has a repeater. Setting N to 0, then, can be used to
8669 remove the repeater from a subtree and create a shifted clone
8670 with the original repeater."
8671 (interactive "nNumber of clones to produce: ")
8672 (let ((shift
8673 (or shift
8674 (if (and (not (equal current-prefix-arg '(4)))
8675 (save-excursion
8676 (re-search-forward org-ts-regexp-both
8677 (save-excursion
8678 (org-end-of-subtree t)
8679 (point)) t)))
8680 (read-from-minibuffer
8681 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8682 ""))) ;; No time shift
8683 (n-no-remove -1)
8684 (drawer-re org-drawer-regexp)
8685 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8686 beg end template task idprop
8687 shift-n shift-what doshift nmin nmax)
8688 (unless (wholenump n)
8689 (user-error "Invalid number of replications %s" n))
8690 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8691 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8692 shift)))
8693 (user-error "Invalid shift specification %s" shift))
8694 (when doshift
8695 (setq shift-n (string-to-number (match-string 1 shift))
8696 shift-what (cdr (assoc (match-string 2 shift)
8697 '(("d" . day) ("w" . week)
8698 ("m" . month) ("y" . year))))))
8699 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8700 (setq nmin 1 nmax n)
8701 (org-back-to-heading t)
8702 (setq beg (point))
8703 (setq idprop (org-entry-get nil "ID"))
8704 (org-end-of-subtree t t)
8705 (or (bolp) (insert "\n"))
8706 (setq end (point))
8707 (setq template (buffer-substring beg end))
8708 (when (and doshift
8709 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8710 (delete-region beg end)
8711 (setq end beg)
8712 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8713 (goto-char end)
8714 (cl-loop for n from nmin to nmax do
8715 ;; prepare clone
8716 (with-temp-buffer
8717 (insert template)
8718 (org-mode)
8719 (goto-char (point-min))
8720 (org-show-subtree)
8721 (and idprop (if org-clone-delete-id
8722 (org-entry-delete nil "ID")
8723 (org-id-get-create t)))
8724 (unless (= n 0)
8725 (while (re-search-forward org-clock-re nil t)
8726 (kill-whole-line))
8727 (goto-char (point-min))
8728 (while (re-search-forward drawer-re nil t)
8729 (org-remove-empty-drawer-at (point))))
8730 (goto-char (point-min))
8731 (when doshift
8732 (while (re-search-forward org-ts-regexp-both nil t)
8733 (org-timestamp-change (* n shift-n) shift-what))
8734 (unless (= n n-no-remove)
8735 (goto-char (point-min))
8736 (while (re-search-forward org-ts-regexp nil t)
8737 (save-excursion
8738 (goto-char (match-beginning 0))
8739 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8740 (delete-region (match-beginning 1) (match-end 1)))))))
8741 (setq task (buffer-string)))
8742 (insert task))
8743 (goto-char beg)))
8745 ;;; Outline Sorting
8747 (defun org-sort (with-case)
8748 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8749 Optional argument WITH-CASE means sort case-sensitively."
8750 (interactive "P")
8751 (cond
8752 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8753 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8755 (org-call-with-arg 'org-sort-entries with-case))))
8757 (defun org-sort-remove-invisible (s)
8758 "Remove invisible links from string S."
8759 (remove-text-properties 0 (length s) org-rm-props s)
8760 (while (string-match org-bracket-link-regexp s)
8761 (setq s (replace-match (if (match-end 2)
8762 (match-string 3 s)
8763 (match-string 1 s))
8764 t t s)))
8765 (let ((st (format " %s " s)))
8766 (while (string-match org-emph-re st)
8767 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8768 (setq s (substring st 1 -1)))
8771 (defvar org-priority-regexp) ; defined later in the file
8773 (defvar org-after-sorting-entries-or-items-hook nil
8774 "Hook that is run after a bunch of entries or items have been sorted.
8775 When children are sorted, the cursor is in the parent line when this
8776 hook gets called. When a region or a plain list is sorted, the cursor
8777 will be in the first entry of the sorted region/list.")
8779 (defun org-sort-entries
8780 (&optional with-case sorting-type getkey-func compare-func property)
8781 "Sort entries on a certain level of an outline tree.
8782 If there is an active region, the entries in the region are sorted.
8783 Else, if the cursor is before the first entry, sort the top-level items.
8784 Else, the children of the entry at point are sorted.
8786 Sorting can be alphabetically, numerically, by date/time as given by
8787 a time stamp, by a property, by priority order, or by a custom function.
8789 The command prompts for the sorting type unless it has been given to the
8790 function through the SORTING-TYPE argument, which needs to be a character,
8791 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8792 the precise meaning of each character:
8794 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8795 c By creation time, which is assumed to be the first inactive time stamp
8796 at the beginning of a line.
8797 d By deadline date/time.
8798 k By clocking time.
8799 n Numerically, by converting the beginning of the entry/item to a number.
8800 o By order of TODO keywords.
8801 p By priority according to the cookie.
8802 r By the value of a property.
8803 s By scheduled date/time.
8804 t By date/time, either the first active time stamp in the entry, or, if
8805 none exist, by the first inactive one.
8807 Capital letters will reverse the sort order.
8809 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8810 called with point at the beginning of the record. It must return either
8811 a string or a number that should serve as the sorting key for that record.
8813 Comparing entries ignores case by default. However, with an optional argument
8814 WITH-CASE, the sorting considers case as well.
8816 Sorting is done against the visible part of the headlines, it ignores hidden
8817 links.
8819 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8820 (interactive "P")
8821 (let ((case-func (if with-case 'identity 'downcase))
8822 (cmstr
8823 ;; The clock marker is lost when using `sort-subr', let's
8824 ;; store the clocking string.
8825 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8826 (save-excursion
8827 (goto-char org-clock-marker)
8828 (buffer-substring-no-properties (line-beginning-position)
8829 (point)))))
8830 start beg end stars re re2
8831 txt what tmp)
8832 ;; Find beginning and end of region to sort
8833 (cond
8834 ((org-region-active-p)
8835 ;; we will sort the region
8836 (setq end (region-end)
8837 what "region")
8838 (goto-char (region-beginning))
8839 (unless (org-at-heading-p) (outline-next-heading))
8840 (setq start (point)))
8841 ((or (org-at-heading-p)
8842 (ignore-errors (progn (org-back-to-heading) t)))
8843 ;; we will sort the children of the current headline
8844 (org-back-to-heading)
8845 (setq start (point)
8846 end (progn (org-end-of-subtree t t)
8847 (or (bolp) (insert "\n"))
8848 (when (>= (org-back-over-empty-lines) 1)
8849 (forward-line 1))
8850 (point))
8851 what "children")
8852 (goto-char start)
8853 (outline-show-subtree)
8854 (outline-next-heading))
8856 ;; we will sort the top-level entries in this file
8857 (goto-char (point-min))
8858 (or (org-at-heading-p) (outline-next-heading))
8859 (setq start (point))
8860 (goto-char (point-max))
8861 (beginning-of-line 1)
8862 (when (looking-at ".*?\\S-")
8863 ;; File ends in a non-white line
8864 (end-of-line 1)
8865 (insert "\n"))
8866 (setq end (point-max))
8867 (setq what "top-level")
8868 (goto-char start)
8869 (outline-show-all)))
8871 (setq beg (point))
8872 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8874 (looking-at "\\(\\*+\\)")
8875 (setq stars (match-string 1)
8876 re (concat "^" (regexp-quote stars) " +")
8877 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8878 txt (buffer-substring beg end))
8879 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8880 (when (and (not (equal stars "*")) (string-match re2 txt))
8881 (user-error "Region to sort contains a level above the first entry"))
8883 (unless sorting-type
8884 (message
8885 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8886 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8887 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8888 what)
8889 (setq sorting-type (read-char-exclusive))
8891 (unless getkey-func
8892 (and (= (downcase sorting-type) ?f)
8893 (setq getkey-func
8894 (completing-read "Sort using function: "
8895 obarray 'fboundp t nil nil))
8896 (setq getkey-func (intern getkey-func))))
8898 (and (= (downcase sorting-type) ?r)
8899 (not property)
8900 (setq property
8901 (completing-read "Property: "
8902 (mapcar #'list (org-buffer-property-keys t))
8903 nil t))))
8905 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8906 (message "Sorting entries...")
8908 (save-restriction
8909 (narrow-to-region start end)
8910 (let ((dcst (downcase sorting-type))
8911 (case-fold-search nil)
8912 (now (current-time)))
8913 (sort-subr
8914 (/= dcst sorting-type)
8915 ;; This function moves to the beginning character of the "record" to
8916 ;; be sorted.
8917 (lambda nil
8918 (if (re-search-forward re nil t)
8919 (goto-char (match-beginning 0))
8920 (goto-char (point-max))))
8921 ;; This function moves to the last character of the "record" being
8922 ;; sorted.
8923 (lambda nil
8924 (save-match-data
8925 (condition-case nil
8926 (outline-forward-same-level 1)
8927 (error
8928 (goto-char (point-max))))))
8929 ;; This function returns the value that gets sorted against.
8930 (lambda nil
8931 (cond
8932 ((= dcst ?n)
8933 (if (looking-at org-complex-heading-regexp)
8934 (string-to-number (org-sort-remove-invisible (match-string 4)))
8935 nil))
8936 ((= dcst ?a)
8937 (if (looking-at org-complex-heading-regexp)
8938 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8939 nil))
8940 ((= dcst ?k)
8941 (or (get-text-property (point) :org-clock-minutes) 0))
8942 ((= dcst ?t)
8943 (let ((end (save-excursion (outline-next-heading) (point))))
8944 (if (or (re-search-forward org-ts-regexp end t)
8945 (re-search-forward org-ts-regexp-both end t))
8946 (org-time-string-to-seconds (match-string 0))
8947 (org-float-time now))))
8948 ((= dcst ?c)
8949 (let ((end (save-excursion (outline-next-heading) (point))))
8950 (if (re-search-forward
8951 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
8952 end t)
8953 (org-time-string-to-seconds (match-string 0))
8954 (org-float-time now))))
8955 ((= dcst ?s)
8956 (let ((end (save-excursion (outline-next-heading) (point))))
8957 (if (re-search-forward org-scheduled-time-regexp end t)
8958 (org-time-string-to-seconds (match-string 1))
8959 (org-float-time now))))
8960 ((= dcst ?d)
8961 (let ((end (save-excursion (outline-next-heading) (point))))
8962 (if (re-search-forward org-deadline-time-regexp end t)
8963 (org-time-string-to-seconds (match-string 1))
8964 (org-float-time now))))
8965 ((= dcst ?p)
8966 (if (re-search-forward org-priority-regexp (point-at-eol) t)
8967 (string-to-char (match-string 2))
8968 org-default-priority))
8969 ((= dcst ?r)
8970 (or (org-entry-get nil property) ""))
8971 ((= dcst ?o)
8972 (when (looking-at org-complex-heading-regexp)
8973 (let* ((m (match-string 2))
8974 (s (if (member m org-done-keywords) '- '+)))
8975 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
8976 ((= dcst ?f)
8977 (if getkey-func
8978 (progn
8979 (setq tmp (funcall getkey-func))
8980 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
8981 tmp)
8982 (error "Invalid key function `%s'" getkey-func)))
8983 (t (error "Invalid sorting type `%c'" sorting-type))))
8985 (cond
8986 ((= dcst ?a) 'string<)
8987 ((= dcst ?f) compare-func)
8988 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
8989 (run-hooks 'org-after-sorting-entries-or-items-hook)
8990 ;; Reset the clock marker if needed
8991 (when cmstr
8992 (save-excursion
8993 (goto-char start)
8994 (search-forward cmstr nil t)
8995 (move-marker org-clock-marker (point))))
8996 (message "Sorting entries...done")))
8998 ;;; The orgstruct minor mode
9000 ;; Define a minor mode which can be used in other modes in order to
9001 ;; integrate the org-mode structure editing commands.
9003 ;; This is really a hack, because the org-mode structure commands use
9004 ;; keys which normally belong to the major mode. Here is how it
9005 ;; works: The minor mode defines all the keys necessary to operate the
9006 ;; structure commands, but wraps the commands into a function which
9007 ;; tests if the cursor is currently at a headline or a plain list
9008 ;; item. If that is the case, the structure command is used,
9009 ;; temporarily setting many Org-mode variables like regular
9010 ;; expressions for filling etc. However, when any of those keys is
9011 ;; used at a different location, function uses `key-binding' to look
9012 ;; up if the key has an associated command in another currently active
9013 ;; keymap (minor modes, major mode, global), and executes that
9014 ;; command. There might be problems if any of the keys is otherwise
9015 ;; used as a prefix key.
9017 (defcustom orgstruct-heading-prefix-regexp ""
9018 "Regexp that matches the custom prefix of Org headlines in
9019 orgstruct(++)-mode."
9020 :group 'org
9021 :version "24.4"
9022 :package-version '(Org . "8.3")
9023 :type 'regexp)
9024 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9026 (defcustom orgstruct-setup-hook nil
9027 "Hook run after orgstruct-mode-map is filled."
9028 :group 'org
9029 :version "24.4"
9030 :package-version '(Org . "8.0")
9031 :type 'hook)
9033 (defvar orgstruct-initialized nil)
9035 (defvar org-local-vars nil
9036 "List of local variables, for use by `orgstruct-mode'.")
9038 ;;;###autoload
9039 (define-minor-mode orgstruct-mode
9040 "Toggle the minor mode `orgstruct-mode'.
9041 This mode is for using Org-mode structure commands in other
9042 modes. The following keys behave as if Org-mode were active, if
9043 the cursor is on a headline, or on a plain list item (both as
9044 defined by Org-mode)."
9045 nil " OrgStruct" (make-sparse-keymap)
9046 (funcall (if orgstruct-mode
9047 'add-to-invisibility-spec
9048 'remove-from-invisibility-spec)
9049 '(outline . t))
9050 (when orgstruct-mode
9051 (org-load-modules-maybe)
9052 (unless orgstruct-initialized
9053 (orgstruct-setup)
9054 (setq orgstruct-initialized t))))
9056 ;;;###autoload
9057 (defun turn-on-orgstruct ()
9058 "Unconditionally turn on `orgstruct-mode'."
9059 (orgstruct-mode 1))
9061 (defvar-local orgstruct-is-++ nil
9062 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9063 (defvar-local org-fb-vars nil)
9064 (defun orgstruct++-mode (&optional arg)
9065 "Toggle `orgstruct-mode', the enhanced version of it.
9066 In addition to setting orgstruct-mode, this also exports all
9067 indentation and autofilling variables from org-mode into the
9068 buffer. It will also recognize item context in multiline items."
9069 (interactive "P")
9070 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9071 (if (< arg 1)
9072 (progn (orgstruct-mode -1)
9073 (dolist (v org-fb-vars)
9074 (set (make-local-variable (car v))
9075 (if (eq (car-safe (cadr v)) 'quote)
9076 (cl-cadadr v)
9077 (nth 1 v)))))
9078 (orgstruct-mode 1)
9079 (setq org-fb-vars nil)
9080 (unless org-local-vars
9081 (setq org-local-vars (org-get-local-variables)))
9082 (let (var val)
9083 (dolist (x org-local-vars)
9084 (when (string-match
9085 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9086 \\|fill-prefix\\|indent-\\)"
9087 (symbol-name (car x)))
9088 (setq var (car x) val (nth 1 x))
9089 (push (list var `(quote ,(eval var))) org-fb-vars)
9090 (set (make-local-variable var)
9091 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9092 (setq-local orgstruct-is-++ t))))
9094 ;;;###autoload
9095 (defun turn-on-orgstruct++ ()
9096 "Unconditionally turn on `orgstruct++-mode'."
9097 (orgstruct++-mode 1))
9099 (defun orgstruct-error ()
9100 "Error when there is no default binding for a structure key."
9101 (interactive)
9102 (funcall (if (fboundp 'user-error)
9103 'user-error
9104 'error)
9105 "This key has no function outside structure elements"))
9107 (defun orgstruct-setup ()
9108 "Setup orgstruct keymap."
9109 (dolist (cell '((org-demote . t)
9110 (org-metaleft . t)
9111 (org-metaright . t)
9112 (org-promote . t)
9113 (org-shiftmetaleft . t)
9114 (org-shiftmetaright . t)
9115 org-backward-element
9116 org-backward-heading-same-level
9117 org-ctrl-c-ret
9118 org-ctrl-c-minus
9119 org-ctrl-c-star
9120 org-cycle
9121 org-force-cycle-archived
9122 org-forward-heading-same-level
9123 org-insert-heading
9124 org-insert-heading-respect-content
9125 org-kill-note-or-show-branches
9126 org-mark-subtree
9127 org-meta-return
9128 org-metadown
9129 org-metaup
9130 org-narrow-to-subtree
9131 org-promote-subtree
9132 org-reveal
9133 org-shiftdown
9134 org-shiftleft
9135 org-shiftmetadown
9136 org-shiftmetaup
9137 org-shiftright
9138 org-shifttab
9139 org-shifttab
9140 org-shiftup
9141 org-show-children
9142 org-show-subtree
9143 org-sort
9144 org-up-element
9145 outline-demote
9146 outline-next-visible-heading
9147 outline-previous-visible-heading
9148 outline-promote
9149 outline-up-heading))
9150 (let ((f (or (car-safe cell) cell))
9151 (disable-when-heading-prefix (cdr-safe cell)))
9152 (when (fboundp f)
9153 (let ((new-bindings))
9154 (dolist (binding (nconc (where-is-internal f org-mode-map)
9155 (where-is-internal f outline-mode-map)))
9156 (push binding new-bindings)
9157 ;; TODO use local-function-key-map
9158 (dolist (rep '(("<tab>" . "TAB")
9159 ("<return>" . "RET")
9160 ("<escape>" . "ESC")
9161 ("<delete>" . "DEL")))
9162 (setq binding (read-kbd-macro
9163 (let ((case-fold-search))
9164 (replace-regexp-in-string
9165 (regexp-quote (cdr rep))
9166 (car rep)
9167 (key-description binding)))))
9168 (cl-pushnew binding new-bindings :test 'equal)))
9169 (dolist (binding new-bindings)
9170 (let ((key (lookup-key orgstruct-mode-map binding)))
9171 (when (or (not key) (numberp key))
9172 (ignore-errors
9173 (org-defkey orgstruct-mode-map
9174 binding
9175 (orgstruct-make-binding
9176 f binding disable-when-heading-prefix))))))))))
9177 (run-hooks 'orgstruct-setup-hook))
9179 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9180 "Create a function for binding in the structure minor mode.
9181 FUN is the command to call inside a table. KEY is the key that
9182 should be checked in for a command to execute outside of tables.
9183 Non-nil `disable-when-heading-prefix' means to disable the command
9184 if `orgstruct-heading-prefix-regexp' is not empty."
9185 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9186 (let ((nname name)
9187 (i 0))
9188 (while (fboundp (intern nname))
9189 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9190 (setq name (intern nname)))
9191 (eval
9192 (let ((bindings '((org-heading-regexp
9193 (concat "^"
9194 orgstruct-heading-prefix-regexp
9195 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9196 (org-outline-regexp
9197 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9198 (org-outline-regexp-bol
9199 (concat "^" org-outline-regexp))
9200 (outline-regexp org-outline-regexp)
9201 (outline-heading-end-regexp "\n")
9202 (outline-level 'org-outline-level)
9203 (outline-heading-alist))))
9204 `(defun ,name (arg)
9205 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9206 "Outside of structure, run the binding of `"
9207 (key-description key) "'."
9208 (when disable-when-heading-prefix
9209 (concat
9210 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9211 "back to the default binding due to limitations of Org's implementation of\n"
9212 "`" (symbol-name fun) "'.")))
9213 (interactive "p")
9214 (let* ((disable
9215 ,(and disable-when-heading-prefix
9216 '(not (string= orgstruct-heading-prefix-regexp ""))))
9217 (fallback
9218 (or disable
9219 (not
9220 (let* ,bindings
9221 (org-context-p 'headline 'item
9222 ,(when (memq fun
9223 '(org-insert-heading
9224 org-insert-heading-respect-content
9225 org-meta-return))
9226 '(when orgstruct-is-++
9227 'item-body))))))))
9228 (if fallback
9229 (let* ((orgstruct-mode)
9230 (binding
9231 (let ((key ,key))
9232 (catch 'exit
9233 (dolist
9234 (rep
9235 '(nil
9236 ("<\\([^>]*\\)tab>" . "\\1TAB")
9237 ("<\\([^>]*\\)return>" . "\\1RET")
9238 ("<\\([^>]*\\)escape>" . "\\1ESC")
9239 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9240 nil)
9241 (when rep
9242 (setq key (read-kbd-macro
9243 (let ((case-fold-search))
9244 (replace-regexp-in-string
9245 (car rep)
9246 (cdr rep)
9247 (key-description key))))))
9248 (when (key-binding key)
9249 (throw 'exit (key-binding key))))))))
9250 (if (keymapp binding)
9251 (org-set-transient-map binding)
9252 (let ((func (or binding
9253 (unless disable
9254 'orgstruct-error))))
9255 (when func
9256 (call-interactively func)))))
9257 (org-run-like-in-org-mode
9258 (lambda ()
9259 (interactive)
9260 (let* ,bindings
9261 (call-interactively ',fun)))))))))
9262 name))
9264 (defun org-contextualize-keys (alist contexts)
9265 "Return valid elements in ALIST depending on CONTEXTS.
9267 `org-agenda-custom-commands' or `org-capture-templates' are the
9268 values used for ALIST, and `org-agenda-custom-commands-contexts'
9269 or `org-capture-templates-contexts' are the associated contexts
9270 definitions."
9271 (let ((contexts
9272 ;; normalize contexts
9273 (mapcar
9274 (lambda(c) (cond ((listp (cadr c))
9275 (list (car c) (car c) (nth 1 c)))
9276 ((string= "" (cadr c))
9277 (list (car c) (car c) (nth 2 c)))
9278 (t c)))
9279 contexts))
9280 (a alist) r s)
9281 ;; loop over all commands or templates
9282 (dolist (c a)
9283 (let (vrules repl)
9284 (cond
9285 ((not (assoc (car c) contexts))
9286 (push c r))
9287 ((and (assoc (car c) contexts)
9288 (setq vrules (org-contextualize-validate-key
9289 (car c) contexts)))
9290 (mapc (lambda (vr)
9291 (unless (equal (car vr) (cadr vr))
9292 (setq repl vr)))
9293 vrules)
9294 (if (not repl) (push c r)
9295 (push (cadr repl) s)
9296 (push
9297 (cons (car c)
9298 (cdr (or (assoc (cadr repl) alist)
9299 (error "Undefined key `%s' as contextual replacement for `%s'"
9300 (cadr repl) (car c)))))
9301 r))))))
9302 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9303 (delq
9305 (delete-dups
9306 (mapcar (lambda (x)
9307 (let ((tpl (car x)))
9308 (unless (delq
9310 (mapcar (lambda (y)
9311 (equal y tpl))
9313 x)))
9314 (reverse r))))))
9316 (defun org-contextualize-validate-key (key contexts)
9317 "Check CONTEXTS for agenda or capture KEY."
9318 (let (res)
9319 (dolist (r contexts)
9320 (dolist (rr (car (last r)))
9321 (when
9322 (and (equal key (car r))
9323 (if (functionp rr) (funcall rr)
9324 (or (and (eq (car rr) 'in-file)
9325 (buffer-file-name)
9326 (string-match (cdr rr) (buffer-file-name)))
9327 (and (eq (car rr) 'in-mode)
9328 (string-match (cdr rr) (symbol-name major-mode)))
9329 (and (eq (car rr) 'in-buffer)
9330 (string-match (cdr rr) (buffer-name)))
9331 (when (and (eq (car rr) 'not-in-file)
9332 (buffer-file-name))
9333 (not (string-match (cdr rr) (buffer-file-name))))
9334 (when (eq (car rr) 'not-in-mode)
9335 (not (string-match (cdr rr) (symbol-name major-mode))))
9336 (when (eq (car rr) 'not-in-buffer)
9337 (not (string-match (cdr rr) (buffer-name)))))))
9338 (push r res))))
9339 (delete-dups (delq nil res))))
9341 (defun org-context-p (&rest contexts)
9342 "Check if local context is any of CONTEXTS.
9343 Possible values in the list of contexts are `table', `headline', and `item'."
9344 (let ((pos (point)))
9345 (goto-char (point-at-bol))
9346 (prog1 (or (and (memq 'table contexts)
9347 (looking-at "[ \t]*|"))
9348 (and (memq 'headline contexts)
9349 (looking-at org-outline-regexp))
9350 (and (memq 'item contexts)
9351 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9352 (and (memq 'item-body contexts)
9353 (org-in-item-p)))
9354 (goto-char pos))))
9356 (defconst org-unique-local-variables
9357 '(org-element--cache
9358 org-element--cache-objects
9359 org-element--cache-sync-keys
9360 org-element--cache-sync-requests
9361 org-element--cache-sync-timer)
9362 "List of local variables that cannot be transferred to another buffer.")
9364 (defun org-get-local-variables ()
9365 "Return a list of all local variables in an Org mode buffer."
9366 (delq nil
9367 (mapcar
9368 (lambda (x)
9369 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9370 (name (car binding)))
9371 (and (not (get name 'org-state))
9372 (not (memq name org-unique-local-variables))
9373 (string-match-p
9374 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9375 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9376 (symbol-name name))
9377 binding)))
9378 (with-temp-buffer
9379 (org-mode)
9380 (buffer-local-variables)))))
9382 (defun org-clone-local-variables (from-buffer &optional regexp)
9383 "Clone local variables from FROM-BUFFER.
9384 Optional argument REGEXP selects variables to clone."
9385 (dolist (pair (buffer-local-variables from-buffer))
9386 (let ((name (car pair)))
9387 (when (and (symbolp name)
9388 (not (memq name org-unique-local-variables))
9389 (or (null regexp) (string-match regexp (symbol-name name))))
9390 (set (make-local-variable name) (cdr pair))))))
9392 ;;;###autoload
9393 (defun org-run-like-in-org-mode (cmd)
9394 "Run a command, pretending that the current buffer is in Org-mode.
9395 This will temporarily bind local variables that are typically bound in
9396 Org-mode to the values they have in Org-mode, and then interactively
9397 call CMD."
9398 (org-load-modules-maybe)
9399 (unless org-local-vars
9400 (setq org-local-vars (org-get-local-variables)))
9401 (let (binds)
9402 (dolist (var org-local-vars)
9403 (when (or (not (boundp (car var)))
9404 (eq (symbol-value (car var))
9405 (default-value (car var))))
9406 (push (list (car var) `(quote ,(cadr var))) binds)))
9407 (eval `(let ,binds
9408 (call-interactively (quote ,cmd))))))
9410 (defun org-get-category (&optional pos force-refresh)
9411 "Get the category applying to position POS."
9412 (save-match-data
9413 (when force-refresh (org-refresh-category-properties))
9414 (let ((pos (or pos (point))))
9415 (or (get-text-property pos 'org-category)
9416 (progn (org-refresh-category-properties)
9417 (get-text-property pos 'org-category))))))
9419 ;;; Refresh properties
9421 (defun org-refresh-properties (dprop tprop)
9422 "Refresh buffer text properties.
9423 DPROP is the drawer property and TPROP is either the
9424 corresponding text property to set, or an alist with each element
9425 being a text property (as a symbol) and a function to apply to
9426 the value of the drawer property."
9427 (let ((case-fold-search t)
9428 (inhibit-read-only t))
9429 (org-with-silent-modifications
9430 (save-excursion
9431 (save-restriction
9432 (widen)
9433 (goto-char (point-min))
9434 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9435 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9437 (defun org-refresh-property (tprop p)
9438 "Refresh the buffer text property TPROP from the drawer property P.
9439 The refresh happens only for the current tree (not subtree)."
9440 (unless (org-before-first-heading-p)
9441 (save-excursion
9442 (org-back-to-heading t)
9443 (if (symbolp tprop)
9444 ;; TPROP is a text property symbol
9445 (put-text-property
9446 (point) (or (outline-next-heading) (point-max)) tprop p)
9447 ;; TPROP is an alist with (properties . function) elements
9448 (dolist (al tprop)
9449 (save-excursion
9450 (put-text-property
9451 (line-beginning-position) (or (outline-next-heading) (point-max))
9452 (car al)
9453 (funcall (cdr al) p))))))))
9455 (defun org-refresh-category-properties ()
9456 "Refresh category text properties in the buffer."
9457 (let ((case-fold-search t)
9458 (inhibit-read-only t)
9459 (default-category
9460 (cond ((null org-category)
9461 (if buffer-file-name
9462 (file-name-sans-extension
9463 (file-name-nondirectory buffer-file-name))
9464 "???"))
9465 ((symbolp org-category) (symbol-name org-category))
9466 (t org-category))))
9467 (org-with-silent-modifications
9468 (org-with-wide-buffer
9469 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9470 ;; This is the default category for the buffer. If none is
9471 ;; found, fall-back to `org-category' or buffer file name.
9472 (put-text-property
9473 (point-min) (point-max)
9474 'org-category
9475 (catch 'buffer-category
9476 (goto-char (point-max))
9477 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9478 (let ((element (org-element-at-point)))
9479 (when (eq (org-element-type element) 'keyword)
9480 (throw 'buffer-category
9481 (org-element-property :value element)))))
9482 default-category))
9483 ;; Set sub-tree specific categories.
9484 (goto-char (point-min))
9485 (let ((regexp (org-re-property "CATEGORY")))
9486 (while (re-search-forward regexp nil t)
9487 (let ((value (org-match-string-no-properties 3)))
9488 (when (org-at-property-p)
9489 (put-text-property
9490 (save-excursion (org-back-to-heading t) (point))
9491 (save-excursion (org-end-of-subtree t t) (point))
9492 'org-category
9493 value)))))))))
9495 (defun org-refresh-stats-properties ()
9496 "Refresh stats text properties in the buffer."
9497 (let (stats)
9498 (org-with-silent-modifications
9499 (save-excursion
9500 (save-restriction
9501 (widen)
9502 (goto-char (point-min))
9503 (while (re-search-forward
9504 (concat org-outline-regexp-bol ".*"
9505 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9506 nil t)
9507 (setq stats (cond ((equal (match-string 3) "0") 0)
9508 ((match-string 2)
9509 (/ (* (string-to-number (match-string 2)) 100)
9510 (string-to-number (match-string 3))))
9511 (t (string-to-number (match-string 1)))))
9512 (org-back-to-heading t)
9513 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9514 'org-stats stats)))))))
9516 (defun org-refresh-effort-properties ()
9517 "Refresh effort properties"
9518 (org-refresh-properties
9519 org-effort-property
9520 '((effort . identity)
9521 (effort-minutes . org-duration-string-to-minutes))))
9523 ;;;; Link Stuff
9525 ;;; Link abbreviations
9527 (defun org-link-expand-abbrev (link)
9528 "Apply replacements as defined in `org-link-abbrev-alist'."
9529 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9530 (let* ((key (match-string 1 link))
9531 (as (or (assoc key org-link-abbrev-alist-local)
9532 (assoc key org-link-abbrev-alist)))
9533 (tag (and (match-end 2) (match-string 3 link)))
9534 rpl)
9535 (if (not as)
9536 link
9537 (setq rpl (cdr as))
9538 (cond
9539 ((symbolp rpl) (funcall rpl tag))
9540 ((string-match "%(\\([^)]+\\))" rpl)
9541 (replace-match
9542 (save-match-data
9543 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9544 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9545 ((string-match "%h" rpl)
9546 (replace-match (url-hexify-string (or tag "")) t t rpl))
9547 (t (concat rpl tag)))))
9548 link))
9550 ;;; Storing and inserting links
9552 (defvar org-insert-link-history nil
9553 "Minibuffer history for links inserted with `org-insert-link'.")
9555 (defvar org-stored-links nil
9556 "Contains the links stored with `org-store-link'.")
9558 (defvar org-store-link-plist nil
9559 "Plist with info about the most recently link created with `org-store-link'.")
9561 (defvar org-link-protocols nil
9562 "Link protocols added to Org-mode using `org-add-link-type'.")
9564 (defvar org-store-link-functions nil
9565 "List of functions that are called to create and store a link.
9566 Each function will be called in turn until one returns a non-nil
9567 value. Each function should check if it is responsible for creating
9568 this link (for example by looking at the major mode).
9569 If not, it must exit and return nil.
9570 If yes, it should return a non-nil value after a calling
9571 `org-store-link-props' with a list of properties and values.
9572 Special properties are:
9574 :type The link prefix, like \"http\". This must be given.
9575 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9576 This is obligatory as well.
9577 :description Optional default description for the second pair
9578 of brackets in an Org-mode link. The user can still change
9579 this when inserting this link into an Org-mode buffer.
9581 In addition to these, any additional properties can be specified
9582 and then used in capture templates.")
9584 (defun org-add-link-type (type &optional follow export)
9585 "Add TYPE to the list of `org-link-types'.
9586 Re-compute all regular expressions depending on `org-link-types'
9588 FOLLOW and EXPORT are two functions.
9590 FOLLOW should take the link path as the single argument and do whatever
9591 is necessary to follow the link, for example find a file or display
9592 a mail message.
9594 EXPORT should format the link path for export to one of the export formats.
9595 It should be a function accepting three arguments:
9597 path the path of the link, the text after the prefix (like \"http:\")
9598 desc the description of the link, if any
9599 format the export format, a symbol like `html' or `latex' or `ascii'.
9601 The function may use the FORMAT information to return different values
9602 depending on the format. The return value will be put literally into
9603 the exported file. If the return value is nil, this means Org should
9604 do what it normally does with links which do not have EXPORT defined.
9606 Org mode has a built-in default for exporting links. If you are happy with
9607 this default, there is no need to define an export function for the link
9608 type. For a simple example of an export function, see `org-bbdb.el'."
9609 (add-to-list 'org-link-types type t)
9610 (org-make-link-regexps)
9611 (org-element-update-syntax)
9612 (if (assoc type org-link-protocols)
9613 (setcdr (assoc type org-link-protocols) (list follow export))
9614 (push (list type follow export) org-link-protocols)))
9616 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9617 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9619 ;;;###autoload
9620 (defun org-store-link (arg)
9621 "\\<org-mode-map>Store an org-link to the current location.
9622 This link is added to `org-stored-links' and can later be inserted
9623 into an Org buffer with \\[org-insert-link].
9625 For some link types, a prefix ARG is interpreted.
9626 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9627 For file links, ARG negates `org-context-in-file-links'.
9629 A double prefix ARG force skipping storing functions that are not
9630 part of Org's core.
9632 A triple prefix ARG force storing a link for each line in the
9633 active region."
9634 (interactive "P")
9635 (org-load-modules-maybe)
9636 (if (and (equal arg '(64)) (org-region-active-p))
9637 (save-excursion
9638 (let ((end (region-end)))
9639 (goto-char (region-beginning))
9640 (set-mark (point))
9641 (while (< (point-at-eol) end)
9642 (move-end-of-line 1) (activate-mark)
9643 (let (current-prefix-arg)
9644 (call-interactively 'org-store-link))
9645 (move-beginning-of-line 2)
9646 (set-mark (point)))))
9647 (org-with-limited-levels
9648 (setq org-store-link-plist nil)
9649 (let (link cpltxt desc description search
9650 txt custom-id agenda-link sfuns sfunsn)
9651 (cond
9653 ;; Store a link using an external link type
9654 ((and (not (equal arg '(16)))
9655 (setq sfuns
9656 (delq
9657 nil (mapcar (lambda (f)
9658 (let (fs) (if (funcall f) (push f fs))))
9659 org-store-link-functions))
9660 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9661 (or (and (cdr sfuns)
9662 (funcall (intern
9663 (completing-read
9664 "Which function for creating the link? "
9665 sfunsn nil t (car sfunsn)))))
9666 (funcall (caar sfuns)))
9667 (setq link (plist-get org-store-link-plist :link)
9668 desc (or (plist-get org-store-link-plist
9669 :description)
9670 link))))
9672 ;; Store a link from a source code buffer.
9673 ((org-src-edit-buffer-p)
9674 (cond
9675 ((save-excursion
9676 (beginning-of-line)
9677 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9678 "[ \t]*$")))
9679 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9680 ((org-called-interactively-p 'any)
9681 (let (label)
9682 (while (or (not label)
9683 (org-with-wide-buffer
9684 (goto-char (point-min))
9685 (re-search-forward
9686 (regexp-quote (format org-coderef-label-format label))
9687 nil t)))
9688 (when label (message "Label exists already") (sit-for 2))
9689 (setq label (read-string "Code line label: " label)))
9690 (end-of-line)
9691 (setq link (format org-coderef-label-format label))
9692 (let ((gc (- 79 (length link))))
9693 (if (< (current-column) gc) (org-move-to-column gc t)
9694 (insert " ")))
9695 (insert link)
9696 (setq link (concat "(" label ")") desc nil)))
9697 (t (setq link nil))))
9699 ;; We are in the agenda, link to referenced location
9700 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9701 (let ((m (or (get-text-property (point) 'org-hd-marker)
9702 (get-text-property (point) 'org-marker))))
9703 (when m
9704 (org-with-point-at m
9705 (setq agenda-link
9706 (if (org-called-interactively-p 'any)
9707 (call-interactively 'org-store-link)
9708 (org-store-link nil)))))))
9710 ((eq major-mode 'calendar-mode)
9711 (let ((cd (calendar-cursor-to-date)))
9712 (setq link
9713 (format-time-string
9714 (car org-time-stamp-formats)
9715 (apply 'encode-time
9716 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9717 nil nil nil))))
9718 (org-store-link-props :type "calendar" :date cd)))
9720 ((eq major-mode 'help-mode)
9721 (setq link (concat "help:" (save-excursion
9722 (goto-char (point-min))
9723 (looking-at "^[^ ]+")
9724 (match-string 0))))
9725 (org-store-link-props :type "help"))
9727 ((eq major-mode 'w3-mode)
9728 (setq cpltxt (if (and (buffer-name)
9729 (not (string-match "Untitled" (buffer-name))))
9730 (buffer-name)
9731 (url-view-url t))
9732 link (url-view-url t))
9733 (org-store-link-props :type "w3" :url (url-view-url t)))
9735 ((eq major-mode 'image-mode)
9736 (setq cpltxt (concat "file:"
9737 (abbreviate-file-name buffer-file-name))
9738 link cpltxt)
9739 (org-store-link-props :type "image" :file buffer-file-name))
9741 ;; In dired, store a link to the file of the current line
9742 ((derived-mode-p 'dired-mode)
9743 (let ((file (dired-get-filename nil t)))
9744 (setq file (if file
9745 (abbreviate-file-name
9746 (expand-file-name (dired-get-filename nil t)))
9747 ;; otherwise, no file so use current directory.
9748 default-directory))
9749 (setq cpltxt (concat "file:" file)
9750 link cpltxt)))
9752 ((setq search (run-hook-with-args-until-success
9753 'org-create-file-search-functions))
9754 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9755 "::" search))
9756 (setq cpltxt (or description link)))
9758 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9759 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9760 (cond
9761 ;; Store a link using the target at point
9762 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9763 (setq cpltxt
9764 (concat "file:"
9765 (abbreviate-file-name
9766 (buffer-file-name (buffer-base-buffer)))
9767 "::" (match-string 1))
9768 link cpltxt))
9769 ((and (featurep 'org-id)
9770 (or (eq org-id-link-to-org-use-id t)
9771 (and (org-called-interactively-p 'any)
9772 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9773 (and (eq org-id-link-to-org-use-id
9774 'create-if-interactive-and-no-custom-id)
9775 (not custom-id))))
9776 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9777 ;; Store a link using the ID at point
9778 (setq link (condition-case nil
9779 (prog1 (org-id-store-link)
9780 (setq desc (or (plist-get org-store-link-plist
9781 :description)
9782 "")))
9783 (error
9784 ;; Probably before first headline, link only to file
9785 (concat "file:"
9786 (abbreviate-file-name
9787 (buffer-file-name (buffer-base-buffer))))))))
9789 ;; Just link to current headline
9790 (setq cpltxt (concat "file:"
9791 (abbreviate-file-name
9792 (buffer-file-name (buffer-base-buffer)))))
9793 ;; Add a context search string
9794 (when (org-xor org-context-in-file-links arg)
9795 (let* ((ee (org-element-at-point))
9796 (et (org-element-type ee))
9797 (ev (plist-get (cadr ee) :value))
9798 (ek (plist-get (cadr ee) :key))
9799 (eok (and (stringp ek) (string-match "name" ek))))
9800 (setq txt (cond
9801 ((org-at-heading-p) nil)
9802 ((and (eq et 'keyword) eok) ev)
9803 ((org-region-active-p)
9804 (buffer-substring (region-beginning) (region-end)))))
9805 (when (or (null txt) (string-match "\\S-" txt))
9806 (setq cpltxt
9807 (concat cpltxt "::"
9808 (condition-case nil
9809 (org-make-org-heading-search-string txt)
9810 (error "")))
9811 desc (or (and (eq et 'keyword) eok ev)
9812 (nth 4 (ignore-errors (org-heading-components)))
9813 "NONE")))))
9814 (when (string-match "::\\'" cpltxt)
9815 (setq cpltxt (substring cpltxt 0 -2)))
9816 (setq link cpltxt))))
9818 ((buffer-file-name (buffer-base-buffer))
9819 ;; Just link to this file here.
9820 (setq cpltxt (concat "file:"
9821 (abbreviate-file-name
9822 (buffer-file-name (buffer-base-buffer)))))
9823 ;; Add a context string.
9824 (when (org-xor org-context-in-file-links arg)
9825 (setq txt (if (org-region-active-p)
9826 (buffer-substring (region-beginning) (region-end))
9827 (buffer-substring (point-at-bol) (point-at-eol))))
9828 ;; Only use search option if there is some text.
9829 (when (string-match "\\S-" txt)
9830 (setq cpltxt
9831 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9832 desc "NONE")))
9833 (setq link cpltxt))
9835 ((org-called-interactively-p 'interactive)
9836 (user-error "No method for storing a link from this buffer"))
9838 (t (setq link nil)))
9840 ;; We're done setting link and desc, clean up
9841 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9842 (setq link (or link cpltxt)
9843 desc (or desc cpltxt))
9844 (cond ((equal desc "NONE") (setq desc nil))
9845 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9846 (let ((d0 (match-string 3 desc))
9847 (p0 (match-string 5 desc)))
9848 (setq desc
9849 (replace-regexp-in-string
9850 org-bracket-link-regexp
9851 (concat (or p0 d0)
9852 (if (equal (length (match-string 0 desc))
9853 (length desc)) "*" "")) desc)))))
9855 ;; Return the link
9856 (if (not (and (or (org-called-interactively-p 'any)
9857 executing-kbd-macro)
9858 link))
9859 (or agenda-link (and link (org-make-link-string link desc)))
9860 (push (list link desc) org-stored-links)
9861 (message "Stored: %s" (or desc link))
9862 (when custom-id
9863 (setq link (concat "file:" (abbreviate-file-name
9864 (buffer-file-name)) "::#" custom-id))
9865 (push (list link desc) org-stored-links))
9866 (car org-stored-links))))))
9868 (defun org-store-link-props (&rest plist)
9869 "Store link properties, extract names, addresses and dates."
9870 (let ((x (plist-get plist :from)))
9871 (when x
9872 (let ((adr (mail-extract-address-components x)))
9873 (setq plist (plist-put plist :fromname (car adr)))
9874 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9875 (let ((x (plist-get plist :to)))
9876 (when x
9877 (let ((adr (mail-extract-address-components x)))
9878 (setq plist (plist-put plist :toname (car adr)))
9879 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9880 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9881 (when x
9882 (setq plist (plist-put plist :date-timestamp
9883 (format-time-string
9884 (org-time-stamp-format t) x)))
9885 (setq plist (plist-put plist :date-timestamp-inactive
9886 (format-time-string
9887 (org-time-stamp-format t t) x)))))
9888 (let ((from (plist-get plist :from))
9889 (to (plist-get plist :to)))
9890 (when (and from to org-from-is-user-regexp)
9891 (setq plist
9892 (plist-put plist :fromto
9893 (if (string-match org-from-is-user-regexp from)
9894 (concat "to %t")
9895 (concat "from %f"))))))
9896 (setq org-store-link-plist plist))
9898 (defun org-add-link-props (&rest plist)
9899 "Add these properties to the link property list."
9900 (let (key value)
9901 (while plist
9902 (setq key (pop plist) value (pop plist))
9903 (setq org-store-link-plist
9904 (plist-put org-store-link-plist key value)))))
9906 (defun org-email-link-description (&optional fmt)
9907 "Return the description part of an email link.
9908 This takes information from `org-store-link-plist' and formats it
9909 according to FMT (default from `org-email-link-description-format')."
9910 (setq fmt (or fmt org-email-link-description-format))
9911 (let* ((p org-store-link-plist)
9912 (to (plist-get p :toaddress))
9913 (from (plist-get p :fromaddress))
9914 (table
9915 (list
9916 (cons "%c" (plist-get p :fromto))
9917 (cons "%F" (plist-get p :from))
9918 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9919 (cons "%T" (plist-get p :to))
9920 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9921 (cons "%s" (plist-get p :subject))
9922 (cons "%d" (plist-get p :date))
9923 (cons "%m" (plist-get p :message-id)))))
9924 (when (string-match "%c" fmt)
9925 ;; Check if the user wrote this message
9926 (if (and org-from-is-user-regexp from to
9927 (save-match-data (string-match org-from-is-user-regexp from)))
9928 (setq fmt (replace-match "to %t" t t fmt))
9929 (setq fmt (replace-match "from %f" t t fmt))))
9930 (org-replace-escapes fmt table)))
9932 (defun org-make-org-heading-search-string (&optional string)
9933 "Make search string for the current headline or STRING."
9934 (let ((s (or string
9935 (and (derived-mode-p 'org-mode)
9936 (save-excursion
9937 (org-back-to-heading t)
9938 (org-element-property :raw-value (org-element-at-point))))))
9939 (lines org-context-in-file-links))
9940 (or string (setq s (concat "*" s))) ; Add * for headlines
9941 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9942 (when (and string (integerp lines) (> lines 0))
9943 (let ((slines (org-split-string s "\n")))
9944 (when (< lines (length slines))
9945 (setq s (mapconcat
9946 'identity
9947 (reverse (nthcdr (- (length slines) lines)
9948 (reverse slines))) "\n")))))
9949 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
9951 (defun org-make-link-string (link &optional description)
9952 "Make a link with brackets, consisting of LINK and DESCRIPTION."
9953 (unless (org-string-nw-p link) (error "Empty link"))
9954 (let ((uri (cond ((string-match org-link-types-re link)
9955 (concat (match-string 1 link)
9956 (org-link-escape (substring link (match-end 1)))))
9957 ;; For readability, url-encode internal links only
9958 ;; when absolutely needed (i.e, when they contain
9959 ;; square brackets). File links however, are
9960 ;; encoded since, e.g., spaces are significant.
9961 ((or (file-name-absolute-p link)
9962 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
9963 (org-link-escape link))
9964 (t link)))
9965 (description
9966 (and (org-string-nw-p description)
9967 ;; Remove brackets from description, as they are fatal.
9968 (replace-regexp-in-string
9969 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
9970 (org-trim description)))))
9971 (format "[[%s]%s]"
9973 (if description (format "[%s]" description) ""))))
9975 (defconst org-link-escape-chars
9976 ;;%20 %5B %5D %25
9977 '(?\s ?\[ ?\] ?%)
9978 "List of characters that should be escaped in a link when stored to Org.
9979 This is the list that is used for internal purposes.")
9981 (defconst org-link-escape-chars-browser
9982 ;;%20 %22
9983 '(?\s ?\")
9984 "List of characters to be escaped before handing over to the browser.
9985 If you consider using this constant then you probably want to use
9986 the function `org-link-escape-browser' instead. See there why
9987 this constant is a candidate to be removed once Org drops support
9988 for Emacs 24.1 and 24.2.")
9990 (defun org-link-escape (text &optional table merge)
9991 "Return percent escaped representation of TEXT.
9992 TEXT is a string with the text to escape.
9993 Optional argument TABLE is a list with characters that should be
9994 escaped. When nil, `org-link-escape-chars' is used.
9995 If optional argument MERGE is set, merge TABLE into
9996 `org-link-escape-chars'."
9997 (let ((characters-to-encode
9998 (cond ((null table) org-link-escape-chars)
9999 (merge (append org-link-escape-chars table))
10000 (t table))))
10001 (mapconcat
10002 (lambda (c)
10003 (if (or (memq c characters-to-encode)
10004 (and org-url-hexify-p (or (< c 32) (> c 126))))
10005 (mapconcat (lambda (e) (format "%%%.2X" e))
10006 (or (encode-coding-char c 'utf-8)
10007 (error "Unable to percent escape character: %c" c))
10009 (char-to-string c)))
10010 text "")))
10012 (defun org-link-escape-browser (text)
10013 "Escape some characters before handing over to the browser.
10014 This function is a candidate to be removed together with the
10015 constant `org-link-escape-chars-browser' once Org drops support
10016 for Emacs 24.1 and 24.2. All calls to this function will have to
10017 be replaced with `url-encode-url' which is available since Emacs
10018 24.3.1."
10019 ;; Example with the Org link
10020 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10021 ;; to open the browser with +subject:"Release 8.2" filled into the
10022 ;; query field: In this case the variable TEXT contains the
10023 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10024 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10025 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10026 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10027 (if (fboundp 'url-encode-url)
10028 (url-encode-url text)
10029 (if (org-string-match-p
10030 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10031 text)
10032 (org-link-escape text org-link-escape-chars-browser)
10033 text)))
10035 (defun org-link-unescape (str)
10036 "Unhex hexified Unicode parts in string STR.
10037 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10038 reciprocal of `org-link-escape', which see."
10039 (if (org-string-nw-p str)
10040 (replace-regexp-in-string
10041 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10042 str))
10044 (defun org-link-unescape-compound (hex)
10045 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10046 Note: this function also decodes single byte encodings like
10047 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10048 (save-match-data
10049 (let* ((bytes (cdr (split-string hex "%")))
10050 (ret "")
10051 (eat 0)
10052 (sum 0))
10053 (while bytes
10054 (let* ((val (string-to-number (pop bytes) 16))
10055 (shift-xor
10056 (if (= 0 eat)
10057 (cond
10058 ((>= val 252) (cons 6 252))
10059 ((>= val 248) (cons 5 248))
10060 ((>= val 240) (cons 4 240))
10061 ((>= val 224) (cons 3 224))
10062 ((>= val 192) (cons 2 192))
10063 (t (cons 0 0)))
10064 (cons 6 128))))
10065 (when (>= val 192) (setq eat (car shift-xor)))
10066 (setq val (logxor val (cdr shift-xor)))
10067 (setq sum (+ (lsh sum (car shift-xor)) val))
10068 (when (> eat 0) (setq eat (- eat 1)))
10069 (cond
10070 ((= 0 eat) ;multi byte
10071 (setq ret (concat ret (org-char-to-string sum)))
10072 (setq sum 0))
10073 ((not bytes) ; single byte(s)
10074 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10075 ret)))
10077 (defun org-link-unescape-single-byte-sequence (hex)
10078 "Unhexify hex-encoded single byte character sequences."
10079 (mapconcat (lambda (byte)
10080 (char-to-string (string-to-number byte 16)))
10081 (cdr (split-string hex "%")) ""))
10083 (defun org-xor (a b)
10084 "Exclusive or."
10085 (if a (not b) b))
10087 (defun org-fixup-message-id-for-http (s)
10088 "Replace special characters in a message id, so it can be used in an http query."
10089 (when (string-match "%" s)
10090 (setq s (mapconcat (lambda (c)
10091 (if (eq c ?%)
10092 "%25"
10093 (char-to-string c)))
10094 s "")))
10095 (while (string-match "<" s)
10096 (setq s (replace-match "%3C" t t s)))
10097 (while (string-match ">" s)
10098 (setq s (replace-match "%3E" t t s)))
10099 (while (string-match "@" s)
10100 (setq s (replace-match "%40" t t s)))
10103 (defun org-link-prettify (link)
10104 "Return a human-readable representation of LINK.
10105 The car of LINK must be a raw link.
10106 The cdr of LINK must be either a link description or nil."
10107 (let ((desc (or (cadr link) "<no description>")))
10108 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10109 "<" (car link) ">")))
10111 ;;;###autoload
10112 (defun org-insert-link-global ()
10113 "Insert a link like Org-mode does.
10114 This command can be called in any mode to insert a link in Org-mode syntax."
10115 (interactive)
10116 (org-load-modules-maybe)
10117 (org-run-like-in-org-mode 'org-insert-link))
10119 (defun org-insert-all-links (arg &optional pre post)
10120 "Insert all links in `org-stored-links'.
10121 When a universal prefix, do not delete the links from `org-stored-links'.
10122 When `ARG' is a number, insert the last N link(s).
10123 `PRE' and `POST' are optional arguments to define a string to
10124 prepend or to append."
10125 (interactive "P")
10126 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10127 (links (copy-sequence org-stored-links))
10128 (pr (or pre "- "))
10129 (po (or post "\n"))
10130 (cnt 1) l)
10131 (if (null org-stored-links)
10132 (message "No link to insert")
10133 (while (and (or (listp arg) (>= arg cnt))
10134 (setq l (if (listp arg)
10135 (pop links)
10136 (pop org-stored-links))))
10137 (setq cnt (1+ cnt))
10138 (insert pr)
10139 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10140 (insert po)))))
10142 (defun org-insert-last-stored-link (arg)
10143 "Insert the last link stored in `org-stored-links'."
10144 (interactive "p")
10145 (org-insert-all-links arg "" "\n"))
10147 (defun org-link-fontify-links-to-this-file ()
10148 "Fontify links to the current file in `org-stored-links'."
10149 (let ((f (buffer-file-name)) a b)
10150 (setq a (mapcar (lambda(l)
10151 (let ((ll (car l)))
10152 (when (and (string-match "^file:\\(.+\\)::" ll)
10153 (equal f (expand-file-name (match-string 1 ll))))
10154 ll)))
10155 org-stored-links))
10156 (when (featurep 'org-id)
10157 (setq b (mapcar (lambda(l)
10158 (let ((ll (car l)))
10159 (when (and (string-match "^id:\\(.+\\)$" ll)
10160 (equal f (expand-file-name
10161 (or (org-id-find-id-file
10162 (match-string 1 ll)) ""))))
10163 ll)))
10164 org-stored-links)))
10165 (mapcar (lambda(l)
10166 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10167 (delq nil (append a b)))))
10169 (defvar org--links-history nil)
10170 (defun org-insert-link (&optional complete-file link-location default-description)
10171 "Insert a link. At the prompt, enter the link.
10173 Completion can be used to insert any of the link protocol prefixes like
10174 http or ftp in use.
10176 The history can be used to select a link previously stored with
10177 `org-store-link'. When the empty string is entered (i.e. if you just
10178 press RET at the prompt), the link defaults to the most recently
10179 stored link. As SPC triggers completion in the minibuffer, you need to
10180 use M-SPC or C-q SPC to force the insertion of a space character.
10182 You will also be prompted for a description, and if one is given, it will
10183 be displayed in the buffer instead of the link.
10185 If there is already a link at point, this command will allow you to edit link
10186 and description parts.
10188 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10189 be selected using completion. The path to the file will be relative to the
10190 current directory if the file is in the current directory or a subdirectory.
10191 Otherwise, the link will be the absolute path as completed in the minibuffer
10192 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10193 option `org-link-file-path-type'.
10195 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10196 the current directory or below.
10198 With three \\[universal-argument] prefixes, negate the meaning of
10199 `org-keep-stored-link-after-insertion'.
10201 If `org-make-link-description-function' is non-nil, this function will be
10202 called with the link target, and the result will be the default
10203 link description.
10205 If the LINK-LOCATION parameter is non-nil, this value will be
10206 used as the link location instead of reading one interactively.
10208 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10209 be used as the default description."
10210 (interactive "P")
10211 (let* ((wcf (current-window-configuration))
10212 (origbuf (current-buffer))
10213 (region (when (org-region-active-p)
10214 (buffer-substring (region-beginning) (region-end))))
10215 (remove (and region (list (region-beginning) (region-end))))
10216 (desc region)
10217 (link link-location)
10218 (abbrevs org-link-abbrev-alist-local)
10219 entry all-prefixes auto-desc)
10220 (cond
10221 (link-location) ; specified by arg, just use it.
10222 ((org-in-regexp org-bracket-link-regexp 1)
10223 ;; We do have a link at point, and we are going to edit it.
10224 (setq remove (list (match-beginning 0) (match-end 0)))
10225 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10226 (setq link (read-string "Link: "
10227 (org-link-unescape
10228 (org-match-string-no-properties 1)))))
10229 ((or (org-in-regexp org-angle-link-re)
10230 (org-in-regexp org-plain-link-re))
10231 ;; Convert to bracket link
10232 (setq remove (list (match-beginning 0) (match-end 0))
10233 link (read-string "Link: "
10234 (org-remove-angle-brackets (match-string 0)))))
10235 ((member complete-file '((4) (16)))
10236 ;; Completing read for file names.
10237 (setq link (org-file-complete-link complete-file)))
10239 ;; Read link, with completion for stored links.
10240 (org-link-fontify-links-to-this-file)
10241 (org-switch-to-buffer-other-window "*Org Links*")
10242 (with-current-buffer "*Org Links*"
10243 (erase-buffer)
10244 (insert "Insert a link.
10245 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10246 (when org-stored-links
10247 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10248 (insert (mapconcat 'org-link-prettify
10249 (reverse org-stored-links) "\n")))
10250 (goto-char (point-min)))
10251 (let ((cw (selected-window)))
10252 (select-window (get-buffer-window "*Org Links*" 'visible))
10253 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10254 (unless (pos-visible-in-window-p (point-max))
10255 (org-fit-window-to-buffer))
10256 (and (window-live-p cw) (select-window cw)))
10257 (setq all-prefixes (append (mapcar 'car abbrevs)
10258 (mapcar 'car org-link-abbrev-alist)
10259 org-link-types))
10260 (unwind-protect
10261 ;; Fake a link history, containing the stored links.
10262 (let ((org--links-history
10263 (append (mapcar #'car org-stored-links)
10264 org-insert-link-history)))
10265 (setq link
10266 (org-completing-read
10267 "Link: "
10268 (append
10269 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10270 (mapcar #'car org-stored-links))
10271 nil nil nil
10272 'org--links-history
10273 (caar org-stored-links)))
10274 (unless (org-string-nw-p link) (user-error "No link selected"))
10275 (dolist (l org-stored-links)
10276 (when (equal link (cadr l))
10277 (setq link (car l))
10278 (setq auto-desc t)))
10279 (when (or (member link all-prefixes)
10280 (and (equal ":" (substring link -1))
10281 (member (substring link 0 -1) all-prefixes)
10282 (setq link (substring link 0 -1))))
10283 (setq link (with-current-buffer origbuf
10284 (org-link-try-special-completion link)))))
10285 (set-window-configuration wcf)
10286 (kill-buffer "*Org Links*"))
10287 (setq entry (assoc link org-stored-links))
10288 (or entry (push link org-insert-link-history))
10289 (setq desc (or desc (nth 1 entry)))))
10291 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10292 (not org-keep-stored-link-after-insertion))
10293 (setq org-stored-links (delq (assoc link org-stored-links)
10294 org-stored-links)))
10296 (when (and (string-match org-plain-link-re link)
10297 (not (string-match org-ts-regexp link)))
10298 ;; URL-like link, normalize the use of angular brackets.
10299 (setq link (org-remove-angle-brackets link)))
10301 ;; Check if we are linking to the current file with a search
10302 ;; option If yes, simplify the link by using only the search
10303 ;; option.
10304 (when (and buffer-file-name
10305 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10306 (let* ((path (match-string 1 link))
10307 (case-fold-search nil)
10308 (search (match-string 2 link)))
10309 (save-match-data
10310 (when (equal (file-truename buffer-file-name) (file-truename path))
10311 ;; We are linking to this same file, with a search option
10312 (setq link search)))))
10314 ;; Check if we can/should use a relative path. If yes, simplify the link
10315 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10316 (let* ((type (match-string 1 link))
10317 (path (match-string 2 link))
10318 (origpath path)
10319 (case-fold-search nil))
10320 (cond
10321 ((or (eq org-link-file-path-type 'absolute)
10322 (equal complete-file '(16)))
10323 (setq path (abbreviate-file-name (expand-file-name path))))
10324 ((eq org-link-file-path-type 'noabbrev)
10325 (setq path (expand-file-name path)))
10326 ((eq org-link-file-path-type 'relative)
10327 (setq path (file-relative-name path)))
10329 (save-match-data
10330 (if (string-match (concat "^" (regexp-quote
10331 (expand-file-name
10332 (file-name-as-directory
10333 default-directory))))
10334 (expand-file-name path))
10335 ;; We are linking a file with relative path name.
10336 (setq path (substring (expand-file-name path)
10337 (match-end 0)))
10338 (setq path (abbreviate-file-name (expand-file-name path)))))))
10339 (setq link (concat type path))
10340 (when (equal desc origpath)
10341 (setq desc path))))
10343 (if org-make-link-description-function
10344 (setq desc
10345 (or (condition-case nil
10346 (funcall org-make-link-description-function link desc)
10347 (error (progn (message "Can't get link description from `%s'"
10348 (symbol-name org-make-link-description-function))
10349 (sit-for 2) nil)))
10350 (read-string "Description: " default-description)))
10351 (if default-description (setq desc default-description)
10352 (setq desc (or (and auto-desc desc)
10353 (read-string "Description: " desc)))))
10355 (unless (string-match "\\S-" desc) (setq desc nil))
10356 (when remove (apply 'delete-region remove))
10357 (insert (org-make-link-string link desc))
10358 ;; Redisplay so as the new link has proper invisible characters.
10359 (sit-for 0)))
10361 (defun org-link-try-special-completion (type)
10362 "If there is completion support for link type TYPE, offer it."
10363 (let ((fun (intern (concat "org-" type "-complete-link"))))
10364 (if (functionp fun)
10365 (funcall fun)
10366 (read-string "Link (no completion support): " (concat type ":")))))
10368 (defun org-file-complete-link (&optional arg)
10369 "Create a file link using completion."
10370 (let ((file (read-file-name "File: "))
10371 (pwd (file-name-as-directory (expand-file-name ".")))
10372 (pwd1 (file-name-as-directory (abbreviate-file-name
10373 (expand-file-name ".")))))
10374 (cond ((equal arg '(16))
10375 (concat "file:"
10376 (abbreviate-file-name (expand-file-name file))))
10377 ((string-match
10378 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10379 (concat "file:" (match-string 1 file)))
10380 ((string-match
10381 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10382 (expand-file-name file))
10383 (concat "file:"
10384 (match-string 1 (expand-file-name file))))
10385 (t (concat "file:" file)))))
10387 (defun org-completing-read (&rest args)
10388 "Completing-read with SPACE being a normal character."
10389 (let ((enable-recursive-minibuffers t)
10390 (minibuffer-local-completion-map
10391 (copy-keymap minibuffer-local-completion-map)))
10392 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10393 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10394 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10395 'org-time-stamp-inactive)
10396 (apply #'completing-read args)))
10398 (define-obsolete-function-alias
10399 'org-completing-read-no-i 'completing-read "Org 9.0")
10400 (define-obsolete-function-alias
10401 'org-icompleting-read 'completing-read "Org 9.0")
10402 (define-obsolete-function-alias
10403 'org-iread-file-name 'read-file-name "Org 9.0")
10405 ;;; Opening/following a link
10407 (defvar org-link-search-failed nil)
10409 (defvar org-open-link-functions nil
10410 "Hook for functions finding a plain text link.
10411 These functions must take a single argument, the link content.
10412 They will be called for links that look like [[link text][description]]
10413 when LINK TEXT does not have a protocol like \"http:\" and does not look
10414 like a filename (e.g. \"./blue.png\").
10416 These functions will be called *before* Org attempts to resolve the
10417 link by doing text searches in the current buffer - so if you want a
10418 link \"[[target]]\" to still find \"<<target>>\", your function should
10419 handle this as a special case.
10421 When the function does handle the link, it must return a non-nil value.
10422 If it decides that it is not responsible for this link, it must return
10423 nil to indicate that that Org-mode can continue with other options
10424 like exact and fuzzy text search.")
10426 (defun org-next-link (&optional search-backward)
10427 "Move forward to the next link.
10428 If the link is in hidden text, expose it."
10429 (interactive "P")
10430 (when (and org-link-search-failed (eq this-command last-command))
10431 (goto-char (point-min))
10432 (message "Link search wrapped back to beginning of buffer"))
10433 (setq org-link-search-failed nil)
10434 (let* ((pos (point))
10435 (ct (org-context))
10436 (a (assoc :link ct))
10437 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10438 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10439 ((looking-at org-any-link-re)
10440 ;; Don't stay stuck at link without an org-link face
10441 (forward-char (if search-backward -1 1))))
10442 (if (funcall srch-fun org-any-link-re nil t)
10443 (progn
10444 (goto-char (match-beginning 0))
10445 (when (outline-invisible-p) (org-show-context)))
10446 (goto-char pos)
10447 (setq org-link-search-failed t)
10448 (message "No further link found"))))
10450 (defun org-previous-link ()
10451 "Move backward to the previous link.
10452 If the link is in hidden text, expose it."
10453 (interactive)
10454 (funcall 'org-next-link t))
10456 (defun org-translate-link (s)
10457 "Translate a link string if a translation function has been defined."
10458 (with-temp-buffer
10459 (insert (org-trim s))
10460 (org-trim (org-element-interpret-data (org-element-context)))))
10462 (defun org-translate-link-from-planner (type path)
10463 "Translate a link from Emacs Planner syntax so that Org can follow it.
10464 This is still an experimental function, your mileage may vary."
10465 (cond
10466 ((member type '("http" "https" "news" "ftp"))
10467 ;; standard Internet links are the same.
10468 nil)
10469 ((and (equal type "irc") (string-match "^//" path))
10470 ;; Planner has two / at the beginning of an irc link, we have 1.
10471 ;; We should have zero, actually....
10472 (setq path (substring path 1)))
10473 ((and (equal type "lisp") (string-match "^/" path))
10474 ;; Planner has a slash, we do not.
10475 (setq type "elisp" path (substring path 1)))
10476 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10477 ;; A typical message link. Planner has the id after the final slash,
10478 ;; we separate it with a hash mark
10479 (setq path (concat (match-string 1 path) "#"
10480 (org-remove-angle-brackets (match-string 2 path))))))
10481 (cons type path))
10483 (defun org-find-file-at-mouse (ev)
10484 "Open file link or URL at mouse."
10485 (interactive "e")
10486 (mouse-set-point ev)
10487 (org-open-at-point 'in-emacs))
10489 (defun org-open-at-mouse (ev)
10490 "Open file link or URL at mouse.
10491 See the docstring of `org-open-file' for details."
10492 (interactive "e")
10493 (mouse-set-point ev)
10494 (when (eq major-mode 'org-agenda-mode)
10495 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10496 (org-open-at-point))
10498 (defvar org-window-config-before-follow-link nil
10499 "The window configuration before following a link.
10500 This is saved in case the need arises to restore it.")
10502 ;;;###autoload
10503 (defun org-open-at-point-global ()
10504 "Follow a link like Org-mode does.
10505 This command can be called in any mode to follow a link that has
10506 Org-mode syntax."
10507 (interactive)
10508 (org-run-like-in-org-mode 'org-open-at-point))
10510 ;;;###autoload
10511 (defun org-open-link-from-string (s &optional arg reference-buffer)
10512 "Open a link in the string S, as if it was in Org-mode."
10513 (interactive "sLink: \nP")
10514 (let ((reference-buffer (or reference-buffer (current-buffer))))
10515 (with-temp-buffer
10516 (let ((org-inhibit-startup (not reference-buffer)))
10517 (org-mode)
10518 (insert s)
10519 (goto-char (point-min))
10520 (when reference-buffer
10521 (setq org-link-abbrev-alist-local
10522 (with-current-buffer reference-buffer
10523 org-link-abbrev-alist-local)))
10524 (org-open-at-point arg reference-buffer)))))
10526 (defvar org-open-at-point-functions nil
10527 "Hook that is run when following a link at point.
10529 Functions in this hook must return t if they identify and follow
10530 a link at point. If they don't find anything interesting at point,
10531 they must return nil.")
10533 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10534 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10535 (defun org-open-at-point (&optional arg reference-buffer)
10536 "Open link, timestamp, footnote or tags at point.
10538 When point is on a link, follow it. Normally, files will be
10539 opened by an appropriate application. If the optional prefix
10540 argument ARG is non-nil, Emacs will visit the file. With
10541 a double prefix argument, try to open outside of Emacs, in the
10542 application the system uses for this file type.
10544 When point is on a timestamp, open the agenda at the day
10545 specified.
10547 When point is a footnote definition, move to the first reference
10548 found. If it is on a reference, move to the associated
10549 definition.
10551 When point is on a headline, display a list of every link in the
10552 entry, so it is possible to pick one, or all, of them. If point
10553 is on a tag, call `org-tags-view' instead.
10555 When optional argument REFERENCE-BUFFER is non-nil, it should
10556 specify a buffer from where the link search should happen. This
10557 is used internally by `org-open-link-from-string'.
10559 On top of syntactically correct links, this function will open
10560 the link at point in comments or comment blocks and the first
10561 link in a property drawer line."
10562 (interactive "P")
10563 ;; On a code block, open block's results.
10564 (unless (call-interactively 'org-babel-open-src-block-result)
10565 (org-load-modules-maybe)
10566 (setq org-window-config-before-follow-link (current-window-configuration))
10567 (org-remove-occur-highlights nil nil t)
10568 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10569 (let* ((context
10570 ;; Only consider supported types, even if they are not
10571 ;; the closest one.
10572 (org-element-lineage
10573 (org-element-context)
10574 '(clock comment comment-block footnote-definition
10575 footnote-reference headline inlinetask keyword link
10576 node-property timestamp)
10578 (type (org-element-type context))
10579 (value (org-element-property :value context)))
10580 (cond
10581 ((not context) (user-error "No link found"))
10582 ;; Exception: open timestamps and links in properties
10583 ;; drawers, keywords and comments.
10584 ((memq type '(comment comment-block keyword node-property))
10585 (cond ((org-in-regexp org-any-link-re)
10586 (org-open-link-from-string (match-string-no-properties 0)))
10587 ((or (org-in-regexp org-ts-regexp-both nil t)
10588 (org-in-regexp org-tsr-regexp-both nil t))
10589 (org-follow-timestamp-link))
10590 (t (user-error "No link found"))))
10591 ;; On a headline or an inlinetask, but not on a timestamp,
10592 ;; a link, a footnote reference or on tags.
10593 ((and (memq type '(headline inlinetask))
10594 ;; Not on tags.
10595 (progn (save-excursion (beginning-of-line)
10596 (looking-at org-complex-heading-regexp))
10597 (or (not (match-beginning 5))
10598 (< (point) (match-beginning 5)))))
10599 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10600 (links (car data))
10601 (links-end (cdr data)))
10602 (if links
10603 (dolist (link (if (stringp links) (list links) links))
10604 (search-forward link nil links-end)
10605 (goto-char (match-beginning 0))
10606 (org-open-at-point))
10607 (require 'org-attach)
10608 (org-attach-reveal 'if-exists))))
10609 ;; On a clock line, make sure point is on the timestamp
10610 ;; before opening it.
10611 ((and (eq type 'clock)
10612 value
10613 (>= (point) (org-element-property :begin value))
10614 (<= (point) (org-element-property :end value)))
10615 (org-follow-timestamp-link))
10616 ;; Do nothing on white spaces after an object.
10617 ((>= (point)
10618 (save-excursion
10619 (goto-char (org-element-property :end context))
10620 (skip-chars-backward " \t")
10621 (point)))
10622 (user-error "No link found"))
10623 ((eq type 'timestamp) (org-follow-timestamp-link))
10624 ;; On tags within a headline or an inlinetask.
10625 ((and (memq type '(headline inlinetask))
10626 (progn (save-excursion (beginning-of-line)
10627 (looking-at org-complex-heading-regexp))
10628 (and (match-beginning 5)
10629 (>= (point) (match-beginning 5)))))
10630 (org-tags-view arg (substring (match-string 5) 0 -1)))
10631 ((eq type 'link)
10632 ;; When link is located within the description of another
10633 ;; link (e.g., an inline image), always open the parent
10634 ;; link.
10635 (let*((link (let ((up (org-element-property :parent context)))
10636 (if (eq (org-element-type up) 'link) up context)))
10637 (type (org-element-property :type link))
10638 (path (org-link-unescape (org-element-property :path link))))
10639 ;; Switch back to REFERENCE-BUFFER needed when called in
10640 ;; a temporary buffer through `org-open-link-from-string'.
10641 (with-current-buffer (or reference-buffer (current-buffer))
10642 (cond
10643 ((equal type "file")
10644 (if (string-match "[*?{]" (file-name-nondirectory path))
10645 (dired path)
10646 ;; Look into `org-link-protocols' in order to find
10647 ;; a DEDICATED-FUNCTION to open file. The function
10648 ;; will be applied on raw link instead of parsed
10649 ;; link due to the limitation in `org-add-link-type'
10650 ;; ("open" function called with a single argument).
10651 ;; If no such function is found, fallback to
10652 ;; `org-open-file'.
10654 ;; Note : "file+emacs" and "file+sys" types are
10655 ;; hard-coded in order to escape the previous
10656 ;; limitation.
10657 (let* ((option (org-element-property :search-option link))
10658 (app (org-element-property :application link))
10659 (dedicated-function
10660 (nth 1 (assoc app org-link-protocols))))
10661 (if dedicated-function
10662 (funcall dedicated-function
10663 (concat path
10664 (and option (concat "::" option))))
10665 (apply #'org-open-file
10666 path
10667 (cond (arg)
10668 ((equal app "emacs") 'emacs)
10669 ((equal app "sys") 'system))
10670 (cond ((not option) nil)
10671 ((org-string-match-p "\\`[0-9]+\\'" option)
10672 (list (string-to-number option)))
10673 (t (list nil
10674 (org-link-unescape option)))))))))
10675 ((assoc type org-link-protocols)
10676 (funcall (nth 1 (assoc type org-link-protocols)) path))
10677 ((equal type "help")
10678 (let ((f-or-v (intern path)))
10679 (cond ((fboundp f-or-v) (describe-function f-or-v))
10680 ((boundp f-or-v) (describe-variable f-or-v))
10681 (t (error "Not a known function or variable")))))
10682 ((member type '("http" "https" "ftp" "mailto" "news"))
10683 (browse-url (org-link-escape-browser (concat type ":" path))))
10684 ((equal type "doi")
10685 (browse-url
10686 (org-link-escape-browser (concat org-doi-server-url path))))
10687 ((equal type "message") (browse-url (concat type ":" path)))
10688 ((equal type "shell")
10689 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10690 (cmd path))
10691 (if (or (and (org-string-nw-p
10692 org-confirm-shell-link-not-regexp)
10693 (string-match
10694 org-confirm-shell-link-not-regexp cmd))
10695 (not org-confirm-shell-link-function)
10696 (funcall org-confirm-shell-link-function
10697 (format "Execute \"%s\" in shell? "
10698 (org-add-props cmd nil
10699 'face 'org-warning))))
10700 (progn
10701 (message "Executing %s" cmd)
10702 (shell-command cmd buf)
10703 (when (featurep 'midnight)
10704 (setq clean-buffer-list-kill-buffer-names
10705 (cons (buffer-name buf)
10706 clean-buffer-list-kill-buffer-names))))
10707 (user-error "Abort"))))
10708 ((equal type "elisp")
10709 (let ((cmd path))
10710 (if (or (and (org-string-nw-p
10711 org-confirm-elisp-link-not-regexp)
10712 (org-string-match-p
10713 org-confirm-elisp-link-not-regexp cmd))
10714 (not org-confirm-elisp-link-function)
10715 (funcall org-confirm-elisp-link-function
10716 (format "Execute \"%s\" as elisp? "
10717 (org-add-props cmd nil
10718 'face 'org-warning))))
10719 (message "%s => %s" cmd
10720 (if (eq (string-to-char cmd) ?\()
10721 (eval (read cmd))
10722 (call-interactively (read cmd))))
10723 (user-error "Abort"))))
10724 ((equal type "id")
10725 (require 'org-id)
10726 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10727 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10728 (unless (run-hook-with-args-until-success
10729 'org-open-link-functions path)
10730 (if (not arg) (org-mark-ring-push)
10731 (switch-to-buffer-other-window
10732 (org-get-buffer-for-internal-link (current-buffer))))
10733 (let ((destination
10734 (org-with-wide-buffer
10735 (if (equal type "radio")
10736 (org-search-radio-target
10737 (org-element-property :path link))
10738 (org-link-search
10739 (if (member type '("custom-id" "coderef"))
10740 (org-element-property :raw-link link)
10741 path)
10742 ;; Prevent fuzzy links from matching
10743 ;; themselves.
10744 (and (equal type "fuzzy")
10745 (+ 2 (org-element-property :begin link)))))
10746 (point))))
10747 (unless (and (<= (point-min) destination)
10748 (>= (point-max) destination))
10749 (widen))
10750 (goto-char destination))))
10751 (t (browse-url-at-point))))))
10752 ;; On a footnote reference or at a footnote definition's label.
10753 ((or (eq type 'footnote-reference)
10754 (and (eq type 'footnote-definition)
10755 (save-excursion
10756 ;; Do not validate action when point is on the
10757 ;; spaces right after the footnote label, in
10758 ;; order to be on par with behaviour on links.
10759 (skip-chars-forward " \t")
10760 (let ((begin
10761 (org-element-property :contents-begin context)))
10762 (if begin (< (point) begin)
10763 (= (org-element-property :post-affiliated context)
10764 (line-beginning-position)))))))
10765 (org-footnote-action))
10766 (t (user-error "No link found")))))
10767 (run-hook-with-args 'org-follow-link-hook)))
10769 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10770 "Offer links in the current entry and return the selected link.
10771 If there is only one link, return it.
10772 If NTH is an integer, return the NTH link found.
10773 If ZERO is a string, check also this string for a link, and if
10774 there is one, return it."
10775 (with-current-buffer buffer
10776 (save-excursion
10777 (save-restriction
10778 (widen)
10779 (goto-char marker)
10780 (let ((cnt ?0)
10781 have-zero end links link c)
10782 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10783 (push (match-string 0 zero) links)
10784 (setq cnt (1- cnt) have-zero t))
10785 (save-excursion
10786 (org-back-to-heading t)
10787 (setq end (save-excursion (outline-next-heading) (point)))
10788 (while (re-search-forward org-any-link-re end t)
10789 (push (match-string 0) links))
10790 (setq links (org-uniquify (reverse links))))
10791 (cond
10792 ((null links)
10793 (message "No links"))
10794 ((equal (length links) 1)
10795 (setq link (car links)))
10796 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10797 (setq link (nth (if have-zero nth (1- nth)) links)))
10798 (t ; we have to select a link
10799 (save-excursion
10800 (save-window-excursion
10801 (delete-other-windows)
10802 (with-output-to-temp-buffer "*Select Link*"
10803 (dolist (l links)
10804 (cond
10805 ((not (string-match org-bracket-link-regexp l))
10806 (princ (format "[%c] %s\n" (cl-incf cnt)
10807 (org-remove-angle-brackets l))))
10808 ((match-end 3)
10809 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10810 (match-string 3 l) (match-string 1 l))))
10811 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10812 (match-string 1 l)))))))
10813 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10814 (message "Select link to open, RET to open all:")
10815 (setq c (read-char-exclusive))
10816 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10817 (when (equal c ?q) (user-error "Abort"))
10818 (if (equal c ?\C-m)
10819 (setq link links)
10820 (setq nth (- c ?0))
10821 (when have-zero (setq nth (1+ nth)))
10822 (unless (and (integerp nth) (>= (length links) nth))
10823 (user-error "Invalid link selection"))
10824 (setq link (nth (1- nth) links)))))
10825 (cons link end))))))
10827 ;; TODO: These functions are deprecated since `org-open-at-point'
10828 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10829 (defun org-open-file-with-system (path)
10830 "Open file at PATH using the system way of opening it."
10831 (org-open-file path 'system))
10832 (defun org-open-file-with-emacs (path)
10833 "Open file at PATH in Emacs."
10834 (org-open-file path 'emacs))
10837 ;;; File search
10839 (defvar org-create-file-search-functions nil
10840 "List of functions to construct the right search string for a file link.
10841 These functions are called in turn with point at the location to
10842 which the link should point.
10844 A function in the hook should first test if it would like to
10845 handle this file type, for example by checking the `major-mode'
10846 or the file extension. If it decides not to handle this file, it
10847 should just return nil to give other functions a chance. If it
10848 does handle the file, it must return the search string to be used
10849 when following the link. The search string will be part of the
10850 file link, given after a double colon, and `org-open-at-point'
10851 will automatically search for it. If special measures must be
10852 taken to make the search successful, another function should be
10853 added to the companion hook `org-execute-file-search-functions',
10854 which see.
10856 A function in this hook may also use `setq' to set the variable
10857 `description' to provide a suggestion for the descriptive text to
10858 be used for this link when it gets inserted into an Org-mode
10859 buffer with \\[org-insert-link].")
10861 (defvar org-execute-file-search-functions nil
10862 "List of functions to execute a file search triggered by a link.
10864 Functions added to this hook must accept a single argument, the
10865 search string that was part of the file link, the part after the
10866 double colon. The function must first check if it would like to
10867 handle this search, for example by checking the `major-mode' or
10868 the file extension. If it decides not to handle this search, it
10869 should just return nil to give other functions a chance. If it
10870 does handle the search, it must return a non-nil value to keep
10871 other functions from trying.
10873 Each function can access the current prefix argument through the
10874 variable `current-prefix-arg'. Note that a single prefix is used
10875 to force opening a link in Emacs, so it may be good to only use a
10876 numeric or double prefix to guide the search function.
10878 In case this is needed, a function in this hook can also restore
10879 the window configuration before `org-open-at-point' was called using:
10881 \(set-window-configuration org-window-config-before-follow-link)")
10883 (defun org-search-radio-target (target)
10884 "Search a radio target matching TARGET in current buffer.
10885 White spaces are not significant."
10886 (let ((re (format "<<<%s>>>"
10887 (mapconcat #'regexp-quote
10888 (org-split-string target "[ \t\n]+")
10889 "[ \t]+\\(?:\n[ \t]*\\)?")))
10890 (origin (point)))
10891 (goto-char (point-min))
10892 (catch :radio-match
10893 (while (re-search-forward re nil t)
10894 (backward-char)
10895 (let ((object (org-element-context)))
10896 (when (eq (org-element-type object) 'radio-target)
10897 (goto-char (org-element-property :begin object))
10898 (org-show-context 'link-search)
10899 (throw :radio-match nil))))
10900 (goto-char origin)
10901 (user-error "No match for radio target: %s" target))))
10903 (defun org-link-search (s &optional avoid-pos stealth)
10904 "Search for a search string S.
10906 If S starts with \"#\", it triggers a custom ID search.
10908 If S is enclosed within parenthesis, it initiates a coderef
10909 search.
10911 If S is surrounded by forward slashes, it is interpreted as
10912 a regular expression. In Org mode files, this will create an
10913 `org-occur' sparse tree. In ordinary files, `occur' will be used
10914 to list matches. If the current buffer is in `dired-mode', grep
10915 will be used to search in all files.
10917 When AVOID-POS is given, ignore matches near that position.
10919 When optional argument STEALTH is non-nil, do not modify
10920 visibility around point, thus ignoring `org-show-context-detail'
10921 variable.
10923 Search is case-insensitive and ignores white spaces. Return type
10924 of matched result, with is either `dedicated' or `fuzzy'."
10925 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10926 (let* ((case-fold-search t)
10927 (origin (point))
10928 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10929 (words (org-split-string s "[ \t\n]+"))
10930 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10931 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10932 type)
10933 (cond
10934 ;; Check if there are any special search functions.
10935 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10936 ((eq (string-to-char s) ?#)
10937 ;; Look for a custom ID S if S starts with "#".
10938 (let* ((id (substring normalized 1))
10939 (match (org-find-property "CUSTOM_ID" id)))
10940 (if match (progn (goto-char match) (setf type 'dedicated))
10941 (error "No match for custom ID: %s" id))))
10942 ((string-match "\\`(\\(.*\\))\\'" normalized)
10943 ;; Look for coderef targets if S is enclosed within parenthesis.
10944 (let ((coderef (match-string-no-properties 1 normalized))
10945 (re (substring s-single-re 1 -1)))
10946 (goto-char (point-min))
10947 (catch :coderef-match
10948 (while (re-search-forward re nil t)
10949 (let ((element (org-element-at-point)))
10950 (when (and (memq (org-element-type element)
10951 '(example-block src-block))
10952 ;; Build proper regexp according to current
10953 ;; block's label format.
10954 (let ((label-fmt
10955 (regexp-quote
10956 (or (org-element-property :label-fmt element)
10957 org-coderef-label-format))))
10958 (save-excursion
10959 (beginning-of-line)
10960 (looking-at (format ".*?\\(%s\\)[ \t]*$"
10961 (format label-fmt coderef))))))
10962 (setq type 'dedicated)
10963 (goto-char (match-beginning 1))
10964 (throw :coderef-match nil))))
10965 (goto-char origin)
10966 (error "No match for coderef: %s" coderef))))
10967 ((string-match "\\`/\\(.*\\)/\\'" normalized)
10968 ;; Look for a regular expression.
10969 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
10970 (match-string 1 s)))
10971 ;; Fuzzy links.
10973 (let ((starred (eq (string-to-char normalized) ?*)))
10974 (cond
10975 ;; Look for targets, only if not in a headline search.
10976 ((and (not starred)
10977 (let ((target (format "<<%s>>" s-multi-re)))
10978 (catch :target-match
10979 (goto-char (point-min))
10980 (while (re-search-forward target nil t)
10981 (backward-char)
10982 (let ((context (org-element-context)))
10983 (when (eq (org-element-type context) 'target)
10984 (setq type 'dedicated)
10985 (goto-char (org-element-property :begin context))
10986 (throw :target-match t))))
10987 nil))))
10988 ;; Look for elements named after S, only if not in a headline
10989 ;; search.
10990 ((and (not starred)
10991 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
10992 (catch :name-match
10993 (goto-char (point-min))
10994 (while (re-search-forward name nil t)
10995 (let ((element (org-element-at-point)))
10996 (when (equal (org-split-string
10997 (org-element-property :name element)
10998 "[ \t]+")
10999 words)
11000 (setq type 'dedicated)
11001 (beginning-of-line)
11002 (throw :name-match t))))
11003 nil))))
11004 ;; Regular text search. Prefer headlines in Org mode
11005 ;; buffers.
11006 ((and (derived-mode-p 'org-mode)
11007 (let* ((wspace "[ \t]")
11008 (wspaceopt (concat wspace "*"))
11009 (cookie (concat "\\(?:"
11010 wspaceopt
11011 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11012 wspaceopt
11013 "\\)"))
11014 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11015 (re (concat
11016 org-outline-regexp-bol
11017 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11018 "\\(?:\\[#.\\][ \t]+\\)?"
11019 "\\(?:" org-comment-string "[ \t]+\\)?"
11020 sep "?"
11021 (let ((title (mapconcat #'regexp-quote
11022 words
11023 sep)))
11024 (if starred (substring title 1) title))
11025 sep "?"
11026 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11027 "[ \t]*$")))
11028 (goto-char (point-min))
11029 (re-search-forward re nil t)))
11030 (goto-char (match-beginning 0))
11031 (setq type 'dedicated))
11032 ;; Offer to create non-existent headline depending on
11033 ;; `org-link-search-must-match-exact-headline'.
11034 ((and (derived-mode-p 'org-mode)
11035 (not org-link-search-inhibit-query)
11036 (eq org-link-search-must-match-exact-headline 'query-to-create)
11037 (yes-or-no-p "No match - create this as a new heading? "))
11038 (goto-char (point-max))
11039 (unless (bolp) (newline))
11040 (org-insert-heading nil t t)
11041 (insert s "\n")
11042 (beginning-of-line 0))
11043 ;; Only headlines are looked after. No need to process
11044 ;; further: throw an error.
11045 ((and (derived-mode-p 'org-mode)
11046 (or starred org-link-search-must-match-exact-headline))
11047 (goto-char origin)
11048 (error "No match for fuzzy expression: %s" normalized))
11049 ;; Regular text search.
11050 ((catch :fuzzy-match
11051 (goto-char (point-min))
11052 (while (re-search-forward s-multi-re nil t)
11053 ;; Skip match if it contains AVOID-POS or it is included
11054 ;; in a link with a description but outside the
11055 ;; description.
11056 (unless (or (and avoid-pos
11057 (<= (match-beginning 0) avoid-pos)
11058 (> (match-end 0) avoid-pos))
11059 (and (save-match-data
11060 (org-in-regexp org-bracket-link-regexp))
11061 (match-beginning 3)
11062 (or (> (match-beginning 3) (point))
11063 (<= (match-end 3) (point)))
11064 (org-element-lineage
11065 (save-match-data (org-element-context))
11066 '(link) t)))
11067 (goto-char (match-beginning 0))
11068 (setq type 'fuzzy)
11069 (throw :fuzzy-match t)))
11070 nil))
11071 ;; All failed. Throw an error.
11072 (t (goto-char origin)
11073 (error "No match for fuzzy expression: %s" normalized))))))
11074 ;; Disclose surroundings of match, if appropriate.
11075 (when (and (derived-mode-p 'org-mode) (not stealth))
11076 (org-show-context 'link-search))
11077 type))
11079 (defun org-get-buffer-for-internal-link (buffer)
11080 "Return a buffer to be used for displaying the link target of internal links."
11081 (cond
11082 ((not org-display-internal-link-with-indirect-buffer)
11083 buffer)
11084 ((string-match "(Clone)$" (buffer-name buffer))
11085 (message "Buffer is already a clone, not making another one")
11086 ;; we also do not modify visibility in this case
11087 buffer)
11088 (t ; make a new indirect buffer for displaying the link
11089 (let* ((bn (buffer-name buffer))
11090 (ibn (concat bn "(Clone)"))
11091 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11092 (with-current-buffer ib (org-overview))
11093 ib))))
11095 (defun org-do-occur (regexp &optional cleanup)
11096 "Call the Emacs command `occur'.
11097 If CLEANUP is non-nil, remove the printout of the regular expression
11098 in the *Occur* buffer. This is useful if the regex is long and not useful
11099 to read."
11100 (occur regexp)
11101 (when cleanup
11102 (let ((cwin (selected-window)) win beg end)
11103 (when (setq win (get-buffer-window "*Occur*"))
11104 (select-window win))
11105 (goto-char (point-min))
11106 (when (re-search-forward "match[a-z]+" nil t)
11107 (setq beg (match-end 0))
11108 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11109 (setq end (1- (match-beginning 0)))))
11110 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11111 (goto-char (point-min))
11112 (select-window cwin))))
11114 ;;; The mark ring for links jumps
11116 (defvar org-mark-ring nil
11117 "Mark ring for positions before jumps in Org-mode.")
11118 (defvar org-mark-ring-last-goto nil
11119 "Last position in the mark ring used to go back.")
11120 ;; Fill and close the ring
11121 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11122 (dotimes (_ org-mark-ring-length)
11123 (push (make-marker) org-mark-ring))
11124 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11125 org-mark-ring)
11127 (defun org-mark-ring-push (&optional pos buffer)
11128 "Put the current position or POS into the mark ring and rotate it."
11129 (interactive)
11130 (setq pos (or pos (point)))
11131 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11132 (move-marker (car org-mark-ring)
11133 (or pos (point))
11134 (or buffer (current-buffer)))
11135 (message "%s"
11136 (substitute-command-keys
11137 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11139 (defun org-mark-ring-goto (&optional n)
11140 "Jump to the previous position in the mark ring.
11141 With prefix arg N, jump back that many stored positions. When
11142 called several times in succession, walk through the entire ring.
11143 Org-mode commands jumping to a different position in the current file,
11144 or to another Org-mode file, automatically push the old position
11145 onto the ring."
11146 (interactive "p")
11147 (let (p m)
11148 (if (eq last-command this-command)
11149 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11150 (setq p org-mark-ring))
11151 (setq org-mark-ring-last-goto p)
11152 (setq m (car p))
11153 (org-pop-to-buffer-same-window (marker-buffer m))
11154 (goto-char m)
11155 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11157 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11158 ;;; Emacs 24.4+
11159 (defun org-remove-angle-brackets (s)
11160 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11161 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11163 (defun org-add-angle-brackets (s)
11164 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11165 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11167 (defun org-remove-double-quotes (s)
11168 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11169 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11172 ;;; Following specific links
11174 (defvar org-agenda-buffer-tmp-name)
11175 (defvar org-agenda-start-on-weekday)
11176 (defun org-follow-timestamp-link ()
11177 "Open an agenda view for the time-stamp date/range at point."
11178 (cond
11179 ((org-at-date-range-p t)
11180 (let ((org-agenda-start-on-weekday)
11181 (t1 (match-string 1))
11182 (t2 (match-string 2)) tt1 tt2)
11183 (setq tt1 (time-to-days (org-time-string-to-time t1))
11184 tt2 (time-to-days (org-time-string-to-time t2)))
11185 (let ((org-agenda-buffer-tmp-name
11186 (format "*Org Agenda(a:%s)"
11187 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11188 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11189 ((org-at-timestamp-p t)
11190 (let ((org-agenda-buffer-tmp-name
11191 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11192 (org-agenda-list nil (time-to-days (org-time-string-to-time
11193 (substring (match-string 1) 0 10)))
11194 1)))
11195 (t (error "This should not happen"))))
11198 ;;; Following file links
11199 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11200 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11201 (declare-function mailcap-mime-info
11202 "mailcap" (string &optional request no-decode))
11203 (defvar org-wait nil)
11204 (defun org-open-file (path &optional in-emacs line search)
11205 "Open the file at PATH.
11206 First, this expands any special file name abbreviations. Then the
11207 configuration variable `org-file-apps' is checked if it contains an
11208 entry for this file type, and if yes, the corresponding command is launched.
11210 If no application is found, Emacs simply visits the file.
11212 With optional prefix argument IN-EMACS, Emacs will visit the file.
11213 With a double \\[universal-argument] \\[universal-argument] \
11214 prefix arg, Org tries to avoid opening in Emacs
11215 and to use an external application to visit the file.
11217 Optional LINE specifies a line to go to, optional SEARCH a string
11218 to search for. If LINE or SEARCH is given, the file will be
11219 opened in Emacs, unless an entry from org-file-apps that makes
11220 use of groups in a regexp matches.
11222 If you want to change the way frames are used when following a
11223 link, please customize `org-link-frame-setup'.
11225 If the file does not exist, an error is thrown."
11226 (let* ((file (if (equal path "")
11227 buffer-file-name
11228 (substitute-in-file-name (expand-file-name path))))
11229 (file-apps (append org-file-apps (org-default-apps)))
11230 (apps (cl-remove-if
11231 'org-file-apps-entry-match-against-dlink-p file-apps))
11232 (apps-dlink (cl-remove-if-not
11233 'org-file-apps-entry-match-against-dlink-p file-apps))
11234 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11235 (dirp (unless remp (file-directory-p file)))
11236 (file (if (and dirp org-open-directory-means-index-dot-org)
11237 (concat (file-name-as-directory file) "index.org")
11238 file))
11239 (a-m-a-p (assq 'auto-mode apps))
11240 (dfile (downcase file))
11241 ;; Reconstruct the original link from the PATH, LINE and
11242 ;; SEARCH args.
11243 (link (cond (line (concat file "::" (number-to-string line)))
11244 (search (concat file "::" search))
11245 (t file)))
11246 (dlink (downcase link))
11247 (old-buffer (current-buffer))
11248 (old-pos (point))
11249 (old-mode major-mode)
11250 (ext
11251 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11252 (match-string 1 dfile)))
11253 cmd link-match-data)
11254 (cond
11255 ((member in-emacs '((16) system))
11256 (setq cmd (cdr (assq 'system apps))))
11257 (in-emacs (setq cmd 'emacs))
11259 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11260 (and dirp (cdr (assq 'directory apps)))
11261 ;; First, try matching against apps-dlink if we
11262 ;; get a match here, store the match data for
11263 ;; later.
11264 (let ((match (assoc-default dlink apps-dlink
11265 'string-match)))
11266 (if match
11267 (progn (setq link-match-data (match-data))
11268 match)
11269 (progn (setq in-emacs (or in-emacs line search))
11270 nil))) ; if we have no match in apps-dlink,
11271 ; always open the file in emacs if line or search
11272 ; is given (for backwards compatibility)
11273 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11274 'string-match)
11275 (cdr (assoc ext apps))
11276 (cdr (assq t apps))))))
11277 (when (eq cmd 'system)
11278 (setq cmd (cdr (assoc 'system apps))))
11279 (when (eq cmd 'default)
11280 (setq cmd (cdr (assoc t apps))))
11281 (when (eq cmd 'mailcap)
11282 (require 'mailcap)
11283 (mailcap-parse-mailcaps)
11284 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11285 (command (mailcap-mime-info mime-type)))
11286 (if (stringp command)
11287 (setq cmd command)
11288 (setq cmd 'emacs))))
11289 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11290 (not (file-exists-p file))
11291 (not org-open-non-existing-files))
11292 (user-error "No such file: %s" file))
11293 (cond
11294 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11295 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11296 (while (string-match "['\"]%s['\"]" cmd)
11297 (setq cmd (replace-match "%s" t t cmd)))
11298 (while (string-match "%s" cmd)
11299 (setq cmd (replace-match
11300 (save-match-data
11301 (shell-quote-argument
11302 (convert-standard-filename file)))
11303 t t cmd)))
11305 ;; Replace "%1", "%2" etc. in command with group matches from regex
11306 (save-match-data
11307 (let ((match-index 1)
11308 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11309 (set-match-data link-match-data)
11310 (while (<= match-index number-of-groups)
11311 (let ((regex (concat "%" (number-to-string match-index)))
11312 (replace-with (match-string match-index dlink)))
11313 (while (string-match regex cmd)
11314 (setq cmd (replace-match replace-with t t cmd))))
11315 (setq match-index (+ match-index 1)))))
11317 (save-window-excursion
11318 (message "Running %s...done" cmd)
11319 (start-process-shell-command cmd nil cmd)
11320 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11321 ((or (stringp cmd)
11322 (eq cmd 'emacs))
11323 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11324 (widen)
11325 (cond (line (org-goto-line line)
11326 (when (derived-mode-p 'org-mode) (org-reveal)))
11327 (search (org-link-search search))))
11328 ((functionp cmd)
11329 (save-match-data
11330 (set-match-data link-match-data)
11331 (condition-case nil
11332 (funcall cmd file link)
11333 ;; FIXME: Remove this check when most default installations
11334 ;; of Emacs have at least Org 9.0.
11335 ((debug wrong-number-of-arguments wrong-type-argument
11336 invalid-function)
11337 (user-error "Please see Org News for version 9.0 about \
11338 `org-file-apps'--Lisp error: %S" cmd)))))
11339 ((consp cmd)
11340 ;; FIXME: Remove this check when most default installations of
11341 ;; Emacs have at least Org 9.0.
11342 ;; Heads-up instead of silently fall back to
11343 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11344 ;; with sexp instead of a function for `cmd'.
11345 (user-error "Please see Org News for version 9.0 about \
11346 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11347 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11348 (and (derived-mode-p 'org-mode)
11349 (eq old-mode 'org-mode)
11350 (or (not (eq old-buffer (current-buffer)))
11351 (not (eq old-pos (point))))
11352 (org-mark-ring-push old-pos old-buffer))))
11354 (defun org-file-apps-entry-match-against-dlink-p (entry)
11355 "This function returns non-nil if `entry' uses a regular
11356 expression which should be matched against the whole link by
11357 org-open-file.
11359 It assumes that is the case when the entry uses a regular
11360 expression which has at least one grouping construct and the
11361 action is either a lisp form or a command string containing
11362 `%1', i.e. using at least one subexpression match as a
11363 parameter."
11364 (let ((selector (car entry))
11365 (action (cdr entry)))
11366 (if (stringp selector)
11367 (and (> (regexp-opt-depth selector) 0)
11368 (or (and (stringp action)
11369 (string-match "%[0-9]" action))
11370 (consp action)))
11371 nil)))
11373 (defun org-default-apps ()
11374 "Return the default applications for this operating system."
11375 (cond
11376 ((eq system-type 'darwin)
11377 org-file-apps-defaults-macosx)
11378 ((eq system-type 'windows-nt)
11379 org-file-apps-defaults-windowsnt)
11380 (t org-file-apps-defaults-gnu)))
11382 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11383 "Convert extensions to regular expressions in the cars of LIST.
11384 Also, weed out any non-string entries, because the return value is used
11385 only for regexp matching.
11386 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11387 point to the symbol `emacs', indicating that the file should
11388 be opened in Emacs."
11389 (append
11390 (delq nil
11391 (mapcar (lambda (x)
11392 (unless (not (stringp (car x)))
11393 (if (string-match "\\W" (car x))
11395 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11396 list))
11397 (when add-auto-mode
11398 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11400 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11401 (defun org-file-remote-p (file)
11402 "Test whether FILE specifies a location on a remote system.
11403 Return non-nil if the location is indeed remote.
11405 For example, the filename \"/user@host:/foo\" specifies a location
11406 on the system \"/user@host:\"."
11407 (cond ((fboundp 'file-remote-p)
11408 (file-remote-p file))
11409 ((fboundp 'tramp-handle-file-remote-p)
11410 (tramp-handle-file-remote-p file))
11411 ((and (boundp 'ange-ftp-name-format)
11412 (string-match (car ange-ftp-name-format) file))
11413 t)))
11416 ;;;; Refiling
11418 (defun org-get-org-file ()
11419 "Read a filename, with default directory `org-directory'."
11420 (let ((default (or org-default-notes-file remember-data-file)))
11421 (read-file-name (format "File name [%s]: " default)
11422 (file-name-as-directory org-directory)
11423 default)))
11425 (defun org-notes-order-reversed-p ()
11426 "Check if the current file should receive notes in reversed order."
11427 (cond
11428 ((not org-reverse-note-order) nil)
11429 ((eq t org-reverse-note-order) t)
11430 ((not (listp org-reverse-note-order)) nil)
11431 (t (catch 'exit
11432 (dolist (entry org-reverse-note-order)
11433 (when (string-match (car entry) buffer-file-name)
11434 (throw 'exit (cdr entry))))))))
11436 (defvar org-refile-target-table nil
11437 "The list of refile targets, created by `org-refile'.")
11439 (defvar org-agenda-new-buffers nil
11440 "Buffers created to visit agenda files.")
11442 (defvar org-refile-cache nil
11443 "Cache for refile targets.")
11445 (defvar org-refile-markers nil
11446 "All the markers used for caching refile locations.")
11448 (defun org-refile-marker (pos)
11449 "Get a new refile marker, but only if caching is in use."
11450 (if (not org-refile-use-cache)
11452 (let ((m (make-marker)))
11453 (move-marker m pos)
11454 (push m org-refile-markers)
11455 m)))
11457 (defun org-refile-cache-clear ()
11458 "Clear the refile cache and disable all the markers."
11459 (dolist (m org-refile-markers) (move-marker m nil))
11460 (setq org-refile-markers nil)
11461 (setq org-refile-cache nil)
11462 (message "Refile cache has been cleared"))
11464 (defun org-refile-cache-check-set (set)
11465 "Check if all the markers in the cache still have live buffers."
11466 (let (marker)
11467 (catch 'exit
11468 (while (and set (setq marker (nth 3 (pop set))))
11469 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11470 (when (and marker (null (marker-buffer marker)))
11471 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11472 (sit-for 3)
11473 (throw 'exit nil)))
11474 t)))
11476 (defun org-refile-cache-put (set &rest identifiers)
11477 "Push the refile targets SET into the cache, under IDENTIFIERS."
11478 (let* ((key (sha1 (prin1-to-string identifiers)))
11479 (entry (assoc key org-refile-cache)))
11480 (if entry
11481 (setcdr entry set)
11482 (push (cons key set) org-refile-cache))))
11484 (defun org-refile-cache-get (&rest identifiers)
11485 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11486 (cond
11487 ((not org-refile-cache) nil)
11488 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11490 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11491 org-refile-cache))))
11492 (and set (org-refile-cache-check-set set) set)))))
11494 (defvar org-outline-path-cache nil
11495 "Alist between buffer positions and outline paths.
11496 It value is an alist (POSITION . PATH) where POSITION is the
11497 buffer position at the beginning of an entry and PATH is a list
11498 of strings describing the outline path for that entry, in reverse
11499 order.")
11501 (defun org-refile-get-targets (&optional default-buffer excluded-entries)
11502 "Produce a table with refile targets."
11503 (let ((case-fold-search nil)
11504 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11505 (entries (or org-refile-targets '((nil . (:level . 1)))))
11506 targets tgs files desc descre)
11507 (message "Getting targets...")
11508 (with-current-buffer (or default-buffer (current-buffer))
11509 (dolist (entry entries)
11510 (setq files (car entry) desc (cdr entry))
11511 (cond
11512 ((null files) (setq files (list (current-buffer))))
11513 ((eq files 'org-agenda-files)
11514 (setq files (org-agenda-files 'unrestricted)))
11515 ((and (symbolp files) (fboundp files))
11516 (setq files (funcall files)))
11517 ((and (symbolp files) (boundp files))
11518 (setq files (symbol-value files))))
11519 (when (stringp files) (setq files (list files)))
11520 (cond
11521 ((eq (car desc) :tag)
11522 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11523 ((eq (car desc) :todo)
11524 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11525 ((eq (car desc) :regexp)
11526 (setq descre (cdr desc)))
11527 ((eq (car desc) :level)
11528 (setq descre (concat "^\\*\\{" (number-to-string
11529 (if org-odd-levels-only
11530 (1- (* 2 (cdr desc)))
11531 (cdr desc)))
11532 "\\}[ \t]")))
11533 ((eq (car desc) :maxlevel)
11534 (setq descre (concat "^\\*\\{1," (number-to-string
11535 (if org-odd-levels-only
11536 (1- (* 2 (cdr desc)))
11537 (cdr desc)))
11538 "\\}[ \t]")))
11539 (t (error "Bad refiling target description %s" desc)))
11540 (dolist (f files)
11541 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11543 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11544 (progn
11545 (when (bufferp f)
11546 (setq f (buffer-file-name (buffer-base-buffer f))))
11547 (setq f (and f (expand-file-name f)))
11548 (when (eq org-refile-use-outline-path 'file)
11549 (push (list (file-name-nondirectory f) f nil nil) tgs))
11550 (org-with-wide-buffer
11551 (goto-char (point-min))
11552 (setq org-outline-path-cache nil)
11553 (while (re-search-forward descre nil t)
11554 (beginning-of-line)
11555 (looking-at org-complex-heading-regexp)
11556 (let ((begin (point))
11557 (heading (org-match-string-no-properties 4)))
11558 (unless (or (and
11559 org-refile-target-verify-function
11560 (not
11561 (funcall org-refile-target-verify-function)))
11562 (not heading)
11563 (member heading excluded-entries))
11564 (let ((re (format org-complex-heading-regexp-format
11565 (regexp-quote heading)))
11566 (target
11567 (if (not org-refile-use-outline-path) heading
11568 (mapconcat
11569 #'org-protect-slash
11570 (append
11571 (pcase org-refile-use-outline-path
11572 (`file (list (file-name-nondirectory
11573 (buffer-file-name
11574 (buffer-base-buffer)))))
11575 (`full-file-path
11576 (list (buffer-file-name
11577 (buffer-base-buffer))))
11578 (_ nil))
11579 (org-get-outline-path t t))
11580 "/"))))
11581 (push (list target f re (org-refile-marker (point)))
11582 tgs)))
11583 (when (= (point) begin)
11584 ;; Verification function has not moved point.
11585 (end-of-line)))))))
11586 (when org-refile-use-cache
11587 (org-refile-cache-put tgs (buffer-file-name) descre))
11588 (setq targets (append tgs targets))))))
11589 (message "Getting targets...done")
11590 (nreverse targets)))
11592 (defun org-protect-slash (s)
11593 (while (string-match "/" s)
11594 (setq s (replace-match "\\" t t s)))
11597 (defun org--get-outline-path-1 (&optional use-cache)
11598 "Return outline path to current headline.
11600 Outline path is a list of strings, in reverse order. When
11601 optional argument USE-CACHE is non-nil, make use of a cache. See
11602 `org-get-outline-path' for details.
11604 Assume buffer is widened and point is on a headline."
11605 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11606 (let ((p (point))
11607 (heading (progn
11608 (looking-at org-complex-heading-regexp)
11609 (if (not (match-end 4)) ""
11610 ;; Remove statistics cookies.
11611 (org-trim
11612 (org-link-display-format
11613 (replace-regexp-in-string
11614 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11615 (org-match-string-no-properties 4))))))))
11616 (if (org-up-heading-safe)
11617 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11618 (when use-cache
11619 (push (cons p path) org-outline-path-cache))
11620 path)
11621 ;; This is a new root node. Since we assume we are moving
11622 ;; forward, we can drop previous cache so as to limit number
11623 ;; of associations there.
11624 (let ((path (list heading)))
11625 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11626 path)))))
11628 (defun org-get-outline-path (&optional with-self use-cache)
11629 "Return the outline path to the current entry.
11631 An outline path is a list of ancestors for current headline, as
11632 a list of strings. Statistics cookies are removed and links are
11633 replaced with their description, if any, or their path otherwise.
11635 When optional argument WITH-SELF is non-nil, the path also
11636 includes the current headline.
11638 When optional argument USE-CACHE is non-nil, cache outline paths
11639 between calls to this function so as to avoid backtracking. This
11640 argument is useful when planning to find more than one outline
11641 path in the same document. In that case, there are two
11642 conditions to satisfy:
11643 - `org-outline-path-cache' is set to nil before starting the
11644 process;
11645 - outline paths are computed by increasing buffer positions."
11646 (org-with-wide-buffer
11647 (and (or (and with-self (org-back-to-heading t))
11648 (org-up-heading-safe))
11649 (reverse (org--get-outline-path-1 use-cache)))))
11651 (defun org-format-outline-path (path &optional width prefix separator)
11652 "Format the outline path PATH for display.
11653 WIDTH is the maximum number of characters that is available.
11654 PREFIX is a prefix to be included in the returned string,
11655 such as the file name.
11656 SEPARATOR is inserted between the different parts of the path,
11657 the default is \"/\"."
11658 (setq width (or width 79))
11659 (setq path (delq nil path))
11660 (unless (> width 0)
11661 (user-error "Argument `width' must be positive"))
11662 (setq separator (or separator "/"))
11663 (let* ((org-odd-levels-only nil)
11664 (fpath (concat
11665 prefix (and prefix path separator)
11666 (mapconcat
11667 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11668 (cl-loop for head in path
11669 for n from 0
11670 collect (org-add-props
11671 head nil 'face
11672 (nth (% n org-n-level-faces) org-level-faces)))
11673 separator))))
11674 (when (> (length fpath) width)
11675 (if (< width 7)
11676 ;; It's unlikely that `width' will be this small, but don't
11677 ;; waste characters by adding ".." if it is.
11678 (setq fpath (substring fpath 0 width))
11679 (setf (substring fpath (- width 2)) "..")))
11680 fpath))
11682 (defun org-display-outline-path (&optional file current separator just-return-string)
11683 "Display the current outline path in the echo area.
11685 If FILE is non-nil, prepend the output with the file name.
11686 If CURRENT is non-nil, append the current heading to the output.
11687 SEPARATOR is passed through to `org-format-outline-path'. It separates
11688 the different parts of the path and defaults to \"/\".
11689 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11690 (interactive "P")
11691 (let* (case-fold-search
11692 (bfn (buffer-file-name (buffer-base-buffer)))
11693 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11694 res)
11695 (when current (setq path (append path
11696 (save-excursion
11697 (org-back-to-heading t)
11698 (when (looking-at org-complex-heading-regexp)
11699 (list (match-string 4)))))))
11700 (setq res
11701 (org-format-outline-path
11702 path
11703 (1- (frame-width))
11704 (and file bfn (concat (file-name-nondirectory bfn) separator))
11705 separator))
11706 (if just-return-string
11707 (org-no-properties res)
11708 (org-unlogged-message "%s" res))))
11710 (defvar org-refile-history nil
11711 "History for refiling operations.")
11713 (defvar org-after-refile-insert-hook nil
11714 "Hook run after `org-refile' has inserted its stuff at the new location.
11715 Note that this is still *before* the stuff will be removed from
11716 the *old* location.")
11718 (defvar org-capture-last-stored-marker)
11719 (defvar org-refile-keep nil
11720 "Non-nil means `org-refile' will copy instead of refile.")
11722 (defun org-copy ()
11723 "Like `org-refile', but copy."
11724 (interactive)
11725 (let ((org-refile-keep t))
11726 (funcall 'org-refile nil nil nil "Copy")))
11728 (defun org-refile (&optional arg default-buffer rfloc msg)
11729 "Move the entry or entries at point to another heading.
11730 The list of target headings is compiled using the information in
11731 `org-refile-targets', which see.
11733 At the target location, the entry is filed as a subitem of the
11734 target heading. Depending on `org-reverse-note-order', the new
11735 subitem will either be the first or the last subitem.
11737 If there is an active region, all entries in that region will be
11738 refiled. However, the region must fulfill the requirement that
11739 the first heading sets the top-level of the moved text.
11741 With prefix arg ARG, the command will only visit the target
11742 location and not actually move anything.
11744 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11745 refiling operation has put the subtree.
11747 With a numeric prefix argument of `2', refile to the running clock.
11749 With a numeric prefix argument of `3', emulate `org-refile-keep'
11750 being set to t and copy to the target location, don't move it.
11751 Beware that keeping refiled entries may result in duplicated ID
11752 properties.
11754 RFLOC can be a refile location obtained in a different way.
11756 MSG is a string to replace \"Refile\" in the default prompt with
11757 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11759 See also `org-refile-use-outline-path'.
11761 If you are using target caching (see `org-refile-use-cache'), you
11762 have to clear the target cache in order to find new targets.
11763 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11764 prefix argument (`C-u C-u C-u C-c C-w')."
11765 (interactive "P")
11766 (if (member arg '(0 (64)))
11767 (org-refile-cache-clear)
11768 (let* ((actionmsg (cond (msg msg)
11769 ((equal arg 3) "Refile (and keep)")
11770 (t "Refile")))
11771 (regionp (org-region-active-p))
11772 (region-start (and regionp (region-beginning)))
11773 (region-end (and regionp (region-end)))
11774 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11775 pos it nbuf file level reversed)
11776 (setq last-command nil)
11777 (when regionp
11778 (goto-char region-start)
11779 (or (bolp) (goto-char (point-at-bol)))
11780 (setq region-start (point))
11781 (unless (or (org-kill-is-subtree-p
11782 (buffer-substring region-start region-end))
11783 (prog1 org-refile-active-region-within-subtree
11784 (let ((s (point-at-eol)))
11785 (org-toggle-heading)
11786 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11787 (user-error "The region is not a (sequence of) subtree(s)")))
11788 (if (equal arg '(16))
11789 (org-refile-goto-last-stored)
11790 (when (or
11791 (and (equal arg 2)
11792 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11793 (prog1
11794 (setq it (list (or org-clock-heading "running clock")
11795 (buffer-file-name
11796 (marker-buffer org-clock-hd-marker))
11798 (marker-position org-clock-hd-marker)))
11799 (setq arg nil)))
11800 (setq it (or rfloc
11801 (let (heading-text)
11802 (save-excursion
11803 (unless (and arg (listp arg))
11804 (org-back-to-heading t)
11805 (setq heading-text
11806 (replace-regexp-in-string
11807 org-bracket-link-regexp
11808 "\\3"
11809 (nth 4 (org-heading-components)))))
11810 (org-refile-get-location
11811 (cond ((and arg (listp arg)) "Goto")
11812 (regionp (concat actionmsg " region to"))
11813 (t (concat actionmsg " subtree \""
11814 heading-text "\" to")))
11815 default-buffer
11816 (and (not (equal '(4) arg))
11817 org-refile-allow-creating-parent-nodes)
11818 arg))))))
11819 (setq file (nth 1 it)
11820 pos (nth 3 it))
11821 (when (and (not arg)
11823 (equal (buffer-file-name) file)
11824 (if regionp
11825 (and (>= pos region-start)
11826 (<= pos region-end))
11827 (and (>= pos (point))
11828 (< pos (save-excursion
11829 (org-end-of-subtree t t))))))
11830 (error "Cannot refile to position inside the tree or region"))
11831 (setq nbuf (or (find-buffer-visiting file)
11832 (find-file-noselect file)))
11833 (if (and arg (not (equal arg 3)))
11834 (progn
11835 (org-pop-to-buffer-same-window nbuf)
11836 (goto-char pos)
11837 (org-show-context 'org-goto))
11838 (if regionp
11839 (progn
11840 (org-kill-new (buffer-substring region-start region-end))
11841 (org-save-markers-in-region region-start region-end))
11842 (org-copy-subtree 1 nil t))
11843 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11844 (find-file-noselect file)))
11845 (setq reversed (org-notes-order-reversed-p))
11846 (save-excursion
11847 (save-restriction
11848 (widen)
11849 (if pos
11850 (progn
11851 (goto-char pos)
11852 (looking-at org-outline-regexp)
11853 (setq level (org-get-valid-level (funcall outline-level) 1))
11854 (goto-char
11855 (if reversed
11856 (or (outline-next-heading) (point-max))
11857 (or (save-excursion (org-get-next-sibling))
11858 (org-end-of-subtree t t)
11859 (point-max)))))
11860 (setq level 1)
11861 (if (not reversed)
11862 (goto-char (point-max))
11863 (goto-char (point-min))
11864 (or (outline-next-heading) (goto-char (point-max)))))
11865 (unless (bolp) (newline))
11866 (org-paste-subtree level nil nil t)
11867 (when org-log-refile
11868 (org-add-log-setup 'refile nil nil org-log-refile)
11869 (unless (eq org-log-refile 'note)
11870 (save-excursion (org-add-log-note))))
11871 (and org-auto-align-tags
11872 (let ((org-loop-over-headlines-in-active-region nil))
11873 (org-set-tags nil t)))
11874 (let ((bookmark-name (plist-get org-bookmark-names-plist
11875 :last-refile)))
11876 (when bookmark-name
11877 (with-demoted-errors
11878 (bookmark-set bookmark-name))))
11879 ;; If we are refiling for capture, make sure that the
11880 ;; last-capture pointers point here
11881 (when (org-bound-and-true-p org-capture-is-refiling)
11882 (let ((bookmark-name (plist-get org-bookmark-names-plist
11883 :last-capture-marker)))
11884 (when bookmark-name
11885 (with-demoted-errors
11886 (bookmark-set bookmark-name))))
11887 (move-marker org-capture-last-stored-marker (point)))
11888 (when (fboundp 'deactivate-mark) (deactivate-mark))
11889 (run-hooks 'org-after-refile-insert-hook))))
11890 (unless org-refile-keep
11891 (if regionp
11892 (delete-region (point) (+ (point) (- region-end region-start)))
11893 (delete-region
11894 (and (org-back-to-heading t) (point))
11895 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11896 (when (featurep 'org-inlinetask)
11897 (org-inlinetask-remove-END-maybe))
11898 (setq org-markers-to-move nil)
11899 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11901 (defun org-refile-goto-last-stored ()
11902 "Go to the location where the last refile was stored."
11903 (interactive)
11904 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11905 (message "This is the location of the last refile"))
11907 (defun org-refile--get-location (refloc tbl)
11908 "When user refile to REFLOC, find the associated target in TBL.
11909 Also check `org-refile-target-table'."
11910 (car (delq
11912 (mapcar
11913 (lambda (r) (or (assoc r tbl)
11914 (assoc r org-refile-target-table)))
11915 (list (replace-regexp-in-string "/$" "" refloc)
11916 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11918 (defun org-refile-get-location (&optional prompt default-buffer new-nodes
11919 no-exclude)
11920 "Prompt the user for a refile location, using PROMPT.
11921 PROMPT should not be suffixed with a colon and a space, because
11922 this function appends the default value from
11923 `org-refile-history' automatically, if that is not empty.
11924 When NO-EXCLUDE is set, do not exclude headlines in the current subtree,
11925 this is used for the GOTO interface."
11926 (let ((org-refile-targets org-refile-targets)
11927 (org-refile-use-outline-path org-refile-use-outline-path)
11928 excluded-entries)
11929 (when (and (derived-mode-p 'org-mode)
11930 (not org-refile-use-cache)
11931 (not no-exclude))
11932 (org-map-tree
11933 (lambda()
11934 (setq excluded-entries
11935 (append excluded-entries (list (org-get-heading t t)))))))
11936 (setq org-refile-target-table
11937 (org-refile-get-targets default-buffer excluded-entries)))
11938 (unless org-refile-target-table
11939 (user-error "No refile targets"))
11940 (let* ((cbuf (current-buffer))
11941 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11942 (cfunc (if (and org-refile-use-outline-path
11943 org-outline-path-complete-in-steps)
11944 #'org-olpath-completing-read
11945 #'completing-read))
11946 (extra (if org-refile-use-outline-path "/" ""))
11947 (cbnex (concat (buffer-name) extra))
11948 (filename (and cfn (expand-file-name cfn)))
11949 (tbl (mapcar
11950 (lambda (x)
11951 (if (and (not (member org-refile-use-outline-path
11952 '(file full-file-path)))
11953 (not (equal filename (nth 1 x))))
11954 (cons (concat (car x) extra " ("
11955 (file-name-nondirectory (nth 1 x)) ")")
11956 (cdr x))
11957 (cons (concat (car x) extra) (cdr x))))
11958 org-refile-target-table))
11959 (completion-ignore-case t)
11960 cdef
11961 (prompt (concat prompt
11962 (or (and (car org-refile-history)
11963 (concat " (default " (car org-refile-history) ")"))
11964 (and (assoc cbnex tbl) (setq cdef cbnex)
11965 (concat " (default " cbnex ")"))) ": "))
11966 pa answ parent-target child parent old-hist)
11967 (setq old-hist org-refile-history)
11968 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
11969 nil 'org-refile-history (or cdef (car org-refile-history))))
11970 (if (setq pa (org-refile--get-location answ tbl))
11971 (progn
11972 (org-refile-check-position pa)
11973 (when (or (not org-refile-history)
11974 (not (eq old-hist org-refile-history))
11975 (not (equal (car pa) (car org-refile-history))))
11976 (setq org-refile-history
11977 (cons (car pa) (if (assoc (car org-refile-history) tbl)
11978 org-refile-history
11979 (cdr org-refile-history))))
11980 (when (equal (car org-refile-history) (nth 1 org-refile-history))
11981 (pop org-refile-history)))
11983 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
11984 (progn
11985 (setq parent (match-string 1 answ)
11986 child (match-string 2 answ))
11987 (setq parent-target (org-refile--get-location parent tbl))
11988 (when (and parent-target
11989 (or (eq new-nodes t)
11990 (and (eq new-nodes 'confirm)
11991 (y-or-n-p (format "Create new node \"%s\"? "
11992 child)))))
11993 (org-refile-new-child parent-target child)))
11994 (user-error "Invalid target location")))))
11996 (declare-function org-string-nw-p "org-macs" (s))
11997 (defun org-refile-check-position (refile-pointer)
11998 "Check if the refile pointer matches the headline to which it points."
11999 (let* ((file (nth 1 refile-pointer))
12000 (re (nth 2 refile-pointer))
12001 (pos (nth 3 refile-pointer))
12002 buffer)
12003 (if (and (not (markerp pos)) (not file))
12004 (user-error "Please indicate a target file in the refile path")
12005 (when (org-string-nw-p re)
12006 (setq buffer (if (markerp pos)
12007 (marker-buffer pos)
12008 (or (find-buffer-visiting file)
12009 (find-file-noselect file))))
12010 (with-current-buffer buffer
12011 (save-excursion
12012 (save-restriction
12013 (widen)
12014 (goto-char pos)
12015 (beginning-of-line 1)
12016 (unless (org-looking-at-p re)
12017 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12019 (defun org-refile-new-child (parent-target child)
12020 "Use refile target PARENT-TARGET to add new CHILD below it."
12021 (unless parent-target
12022 (error "Cannot find parent for new node"))
12023 (let ((file (nth 1 parent-target))
12024 (pos (nth 3 parent-target))
12025 level)
12026 (with-current-buffer (or (find-buffer-visiting file)
12027 (find-file-noselect file))
12028 (save-excursion
12029 (save-restriction
12030 (widen)
12031 (if pos
12032 (goto-char pos)
12033 (goto-char (point-max))
12034 (unless (bolp) (newline)))
12035 (when (looking-at org-outline-regexp)
12036 (setq level (funcall outline-level))
12037 (org-end-of-subtree t t))
12038 (org-back-over-empty-lines)
12039 (insert "\n" (make-string
12040 (if pos (org-get-valid-level level 1) 1) ?*)
12041 " " child "\n")
12042 (beginning-of-line 0)
12043 (list (concat (car parent-target) "/" child) file "" (point)))))))
12045 (defun org-olpath-completing-read (prompt collection &rest args)
12046 "Read an outline path like a file name."
12047 (let ((thetable collection))
12048 (apply #'completing-read
12049 prompt
12050 (lambda (string predicate &optional flag)
12051 (cond
12052 ((eq flag nil) (try-completion string thetable))
12053 ((eq flag t)
12054 (let ((l (length string)))
12055 (mapcar (lambda (x)
12056 (let ((r (substring x l))
12057 (f (if (string-match " ([^)]*)$" x)
12058 (match-string 0 x)
12059 "")))
12060 (if (string-match "/" r)
12061 (concat string (substring r 0 (match-end 0)) f)
12062 x)))
12063 (all-completions string thetable predicate))))
12064 ;; Exact match?
12065 ((eq flag 'lambda) (assoc string thetable))))
12066 args)))
12068 ;;;; Dynamic blocks
12070 (defun org-find-dblock (name)
12071 "Find the first dynamic block with name NAME in the buffer.
12072 If not found, stay at current position and return nil."
12073 (let ((case-fold-search t) pos)
12074 (save-excursion
12075 (goto-char (point-min))
12076 (setq pos (and (re-search-forward
12077 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12078 (match-beginning 0))))
12079 (when pos (goto-char pos))
12080 pos))
12082 (defun org-create-dblock (plist)
12083 "Create a dynamic block section, with parameters taken from PLIST.
12084 PLIST must contain a :name entry which is used as the name of the block."
12085 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12086 (end-of-line 1)
12087 (newline))
12088 (let ((col (current-column))
12089 (name (plist-get plist :name)))
12090 (insert "#+BEGIN: " name)
12091 (while plist
12092 (if (eq (car plist) :name)
12093 (setq plist (cddr plist))
12094 (insert " " (prin1-to-string (pop plist)))))
12095 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12096 (beginning-of-line -2)))
12098 (defun org-prepare-dblock ()
12099 "Prepare dynamic block for refresh.
12100 This empties the block, puts the cursor at the insert position and returns
12101 the property list including an extra property :name with the block name."
12102 (unless (looking-at org-dblock-start-re)
12103 (user-error "Not at a dynamic block"))
12104 (let* ((begdel (1+ (match-end 0)))
12105 (name (org-no-properties (match-string 1)))
12106 (params (append (list :name name)
12107 (read (concat "(" (match-string 3) ")")))))
12108 (save-excursion
12109 (beginning-of-line 1)
12110 (skip-chars-forward " \t")
12111 (setq params (plist-put params :indentation-column (current-column))))
12112 (unless (re-search-forward org-dblock-end-re nil t)
12113 (error "Dynamic block not terminated"))
12114 (setq params
12115 (append params
12116 (list :content (buffer-substring
12117 begdel (match-beginning 0)))))
12118 (delete-region begdel (match-beginning 0))
12119 (goto-char begdel)
12120 (open-line 1)
12121 params))
12123 (defun org-map-dblocks (&optional command)
12124 "Apply COMMAND to all dynamic blocks in the current buffer.
12125 If COMMAND is not given, use `org-update-dblock'."
12126 (let ((cmd (or command 'org-update-dblock)))
12127 (save-excursion
12128 (goto-char (point-min))
12129 (while (re-search-forward org-dblock-start-re nil t)
12130 (goto-char (match-beginning 0))
12131 (save-excursion
12132 (condition-case nil
12133 (funcall cmd)
12134 (error (message "Error during update of dynamic block"))))
12135 (unless (re-search-forward org-dblock-end-re nil t)
12136 (error "Dynamic block not terminated"))))))
12138 (defun org-dblock-update (&optional arg)
12139 "User command for updating dynamic blocks.
12140 Update the dynamic block at point. With prefix ARG, update all dynamic
12141 blocks in the buffer."
12142 (interactive "P")
12143 (if arg
12144 (org-update-all-dblocks)
12145 (or (looking-at org-dblock-start-re)
12146 (org-beginning-of-dblock))
12147 (org-update-dblock)))
12149 (defun org-update-dblock ()
12150 "Update the dynamic block at point.
12151 This means to empty the block, parse for parameters and then call
12152 the correct writing function."
12153 (interactive)
12154 (save-excursion
12155 (let* ((win (selected-window))
12156 (pos (point))
12157 (line (org-current-line))
12158 (params (org-prepare-dblock))
12159 (name (plist-get params :name))
12160 (indent (plist-get params :indentation-column))
12161 (cmd (intern (concat "org-dblock-write:" name))))
12162 (message "Updating dynamic block `%s' at line %d..." name line)
12163 (funcall cmd params)
12164 (message "Updating dynamic block `%s' at line %d...done" name line)
12165 (goto-char pos)
12166 (when (and indent (> indent 0))
12167 (setq indent (make-string indent ?\ ))
12168 (save-excursion
12169 (select-window win)
12170 (org-beginning-of-dblock)
12171 (forward-line 1)
12172 (while (not (looking-at org-dblock-end-re))
12173 (insert indent)
12174 (beginning-of-line 2))
12175 (when (looking-at org-dblock-end-re)
12176 (and (looking-at "[ \t]+")
12177 (replace-match ""))
12178 (insert indent)))))))
12180 (defun org-beginning-of-dblock ()
12181 "Find the beginning of the dynamic block at point.
12182 Error if there is no such block at point."
12183 (let ((pos (point))
12184 beg)
12185 (end-of-line 1)
12186 (if (and (re-search-backward org-dblock-start-re nil t)
12187 (setq beg (match-beginning 0))
12188 (re-search-forward org-dblock-end-re nil t)
12189 (> (match-end 0) pos))
12190 (goto-char beg)
12191 (goto-char pos)
12192 (error "Not in a dynamic block"))))
12194 (defun org-update-all-dblocks ()
12195 "Update all dynamic blocks in the buffer.
12196 This function can be used in a hook."
12197 (interactive)
12198 (when (derived-mode-p 'org-mode)
12199 (org-map-dblocks 'org-update-dblock)))
12202 ;;;; Completion
12204 (declare-function org-export-backend-name "org-export" (cl-x))
12205 (declare-function org-export-backend-options "org-export" (cl-x))
12206 (defun org-get-export-keywords ()
12207 "Return a list of all currently understood export keywords.
12208 Export keywords include options, block names, attributes and
12209 keywords relative to each registered export back-end."
12210 (let (keywords)
12211 (dolist (backend
12212 (org-bound-and-true-p org-export-registered-backends)
12213 (delq nil keywords))
12214 ;; Back-end name (for keywords, like #+LATEX:)
12215 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12216 (dolist (option-entry (org-export-backend-options backend))
12217 ;; Back-end options.
12218 (push (nth 1 option-entry) keywords)))))
12220 (defconst org-options-keywords
12221 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12222 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12223 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12224 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12225 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12227 (defcustom org-structure-template-alist
12228 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12229 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12230 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12231 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12232 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12233 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12234 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12235 ("L" "#+LaTeX: ")
12236 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12237 ("H" "#+HTML: ")
12238 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12239 ("A" "#+ASCII: ")
12240 ("i" "#+INDEX: ?")
12241 ("I" "#+INCLUDE: %file ?"))
12242 "Structure completion elements.
12243 This is a list of abbreviation keys and values. The value gets inserted
12244 if you type `<' followed by the key and then press the completion key,
12245 usually `TAB'. %file will be replaced by a file name after prompting
12246 for the file using completion. The cursor will be placed at the position
12247 of the `?' in the template.
12248 There are two templates for each key, the first uses the original Org syntax,
12249 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12250 the default when the /org-mtags.el/ module has been loaded. See also the
12251 variable `org-mtags-prefer-muse-templates'."
12252 :group 'org-completion
12253 :type '(repeat
12254 (list
12255 (string :tag "Key")
12256 (string :tag "Template")))
12257 :version "25.1"
12258 :package-version '(Org . "8.3"))
12260 (defun org-try-structure-completion ()
12261 "Try to complete a structure template before point.
12262 This looks for strings like \"<e\" on an otherwise empty line and
12263 expands them."
12264 (let ((l (buffer-substring (point-at-bol) (point)))
12266 (when (and (looking-at "[ \t]*$")
12267 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12268 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12269 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12270 (match-beginning 1)) a)
12271 t)))
12273 (defun org-complete-expand-structure-template (start cell)
12274 "Expand a structure template."
12275 (let ((rpl (nth 1 cell))
12276 (ind ""))
12277 (delete-region start (point))
12278 (when (string-match "\\`[ \t]*#\\+" rpl)
12279 (cond
12280 ((bolp))
12281 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12282 (setq ind (buffer-substring (point-at-bol) (point))))
12283 (t (newline))))
12284 (setq start (point))
12285 (when (string-match "%file" rpl)
12286 (setq rpl (replace-match
12287 (concat
12288 "\""
12289 (save-match-data
12290 (abbreviate-file-name (read-file-name "Include file: ")))
12291 "\"")
12292 t t rpl)))
12293 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12294 (concat "\n" ind)))
12295 (insert rpl)
12296 (when (re-search-backward "\\?" start t) (delete-char 1))))
12298 ;;;; TODO, DEADLINE, Comments
12300 (defun org-toggle-comment ()
12301 "Change the COMMENT state of an entry."
12302 (interactive)
12303 (save-excursion
12304 (org-back-to-heading)
12305 (looking-at org-complex-heading-regexp)
12306 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12307 (skip-chars-forward " \t")
12308 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12309 (if (org-in-commented-heading-p t)
12310 (delete-region (point)
12311 (progn (search-forward " " (line-end-position) 'move)
12312 (skip-chars-forward " \t")
12313 (point)))
12314 (insert org-comment-string)
12315 (unless (eolp) (insert " ")))))
12317 (defvar org-last-todo-state-is-todo nil
12318 "This is non-nil when the last TODO state change led to a TODO state.
12319 If the last change removed the TODO tag or switched to DONE, then
12320 this is nil.")
12322 (defvar org-setting-tags nil) ; dynamically skipped
12324 (defvar org-todo-setup-filter-hook nil
12325 "Hook for functions that pre-filter todo specs.
12326 Each function takes a todo spec and returns either nil or the spec
12327 transformed into canonical form." )
12329 (defvar org-todo-get-default-hook nil
12330 "Hook for functions that get a default item for todo.
12331 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12332 nil or a string to be used for the todo mark." )
12334 (defvar org-agenda-headline-snapshot-before-repeat)
12336 (defun org-current-effective-time ()
12337 "Return current time adjusted for `org-extend-today-until' variable."
12338 (let* ((ct (org-current-time))
12339 (dct (decode-time ct))
12340 (ct1
12341 (cond
12342 (org-use-last-clock-out-time-as-effective-time
12343 (or (org-clock-get-last-clock-out-time) ct))
12344 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12345 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12346 (t ct))))
12347 ct1))
12349 (defun org-todo-yesterday (&optional arg)
12350 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12351 (interactive "P")
12352 (if (eq major-mode 'org-agenda-mode)
12353 (apply 'org-agenda-todo-yesterday arg)
12354 (let* ((org-use-effective-time t)
12355 (hour (nth 2 (decode-time (org-current-time))))
12356 (org-extend-today-until (1+ hour)))
12357 (org-todo arg))))
12359 (defvar org-block-entry-blocking ""
12360 "First entry preventing the TODO state change.")
12362 (defun org-cancel-repeater ()
12363 "Cancel a repeater by setting its numeric value to zero."
12364 (interactive)
12365 (save-excursion
12366 (org-back-to-heading t)
12367 (let ((bound1 (point))
12368 (bound0 (save-excursion (outline-next-heading) (point))))
12369 (when (and (re-search-forward
12370 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12371 org-deadline-time-regexp "\\)\\|\\("
12372 org-ts-regexp "\\)")
12373 bound0 t)
12374 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12375 bound1 t))
12376 (replace-match "0" t nil nil 1)))))
12378 (defvar org-state) ;; dynamically scoped into this function
12379 (defun org-todo (&optional arg)
12380 "Change the TODO state of an item.
12381 The state of an item is given by a keyword at the start of the heading,
12382 like
12383 *** TODO Write paper
12384 *** DONE Call mom
12386 The different keywords are specified in the variable `org-todo-keywords'.
12387 By default the available states are \"TODO\" and \"DONE\".
12388 So for this example: when the item starts with TODO, it is changed to DONE.
12389 When it starts with DONE, the DONE is removed. And when neither TODO nor
12390 DONE are present, add TODO at the beginning of the heading.
12392 With \\[universal-argument] prefix arg, use completion to determine the new \
12393 state.
12394 With numeric prefix arg, switch to that state.
12395 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12396 keywords (nextset).
12397 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12398 With a numeric prefix arg of 0, inhibit note taking for the change.
12399 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12401 When called through ELisp, arg is also interpreted in the following way:
12402 `none' -> empty state
12403 \"\"(empty string) -> switch to empty state
12404 `done' -> switch to DONE
12405 `nextset' -> switch to the next set of keywords
12406 `previousset' -> switch to the previous set of keywords
12407 \"WAITING\" -> switch to the specified keyword, but only if it
12408 really is a member of `org-todo-keywords'."
12409 (interactive "P")
12410 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12411 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12412 'region-start-level 'region))
12413 org-loop-over-headlines-in-active-region)
12414 (org-map-entries
12415 `(org-todo ,arg)
12416 org-loop-over-headlines-in-active-region
12417 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12418 (when (equal arg '(16)) (setq arg 'nextset))
12419 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12420 (let ((org-blocker-hook org-blocker-hook)
12421 commentp
12422 case-fold-search)
12423 (when (equal arg '(64))
12424 (setq arg nil org-blocker-hook nil))
12425 (when (and org-blocker-hook
12426 (or org-inhibit-blocking
12427 (org-entry-get nil "NOBLOCKING")))
12428 (setq org-blocker-hook nil))
12429 (save-excursion
12430 (catch 'exit
12431 (org-back-to-heading t)
12432 (when (org-in-commented-heading-p t)
12433 (org-toggle-comment)
12434 (setq commentp t))
12435 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12436 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12437 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12438 (let* ((match-data (match-data))
12439 (startpos (point-at-bol))
12440 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12441 (org-log-done org-log-done)
12442 (org-log-repeat org-log-repeat)
12443 (org-todo-log-states org-todo-log-states)
12444 (org-inhibit-logging
12445 (if (equal arg 0)
12446 (progn (setq arg nil) 'note) org-inhibit-logging))
12447 (this (match-string 1))
12448 (hl-pos (match-beginning 0))
12449 (head (org-get-todo-sequence-head this))
12450 (ass (assoc head org-todo-kwd-alist))
12451 (interpret (nth 1 ass))
12452 (done-word (nth 3 ass))
12453 (final-done-word (nth 4 ass))
12454 (org-last-state (or this ""))
12455 (completion-ignore-case t)
12456 (member (member this org-todo-keywords-1))
12457 (tail (cdr member))
12458 (org-state (cond
12459 ((and org-todo-key-trigger
12460 (or (and (equal arg '(4))
12461 (eq org-use-fast-todo-selection 'prefix))
12462 (and (not arg) org-use-fast-todo-selection
12463 (not (eq org-use-fast-todo-selection
12464 'prefix)))))
12465 ;; Use fast selection
12466 (org-fast-todo-selection))
12467 ((and (equal arg '(4))
12468 (or (not org-use-fast-todo-selection)
12469 (not org-todo-key-trigger)))
12470 ;; Read a state with completion
12471 (completing-read
12472 "State: " (mapcar #'list org-todo-keywords-1)
12473 nil t))
12474 ((eq arg 'right)
12475 (if this
12476 (if tail (car tail) nil)
12477 (car org-todo-keywords-1)))
12478 ((eq arg 'left)
12479 (unless (equal member org-todo-keywords-1)
12480 (if this
12481 (nth (- (length org-todo-keywords-1)
12482 (length tail) 2)
12483 org-todo-keywords-1)
12484 (org-last org-todo-keywords-1))))
12485 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12486 (setq arg nil))) ; hack to fall back to cycling
12487 (arg
12488 ;; user or caller requests a specific state
12489 (cond
12490 ((equal arg "") nil)
12491 ((eq arg 'none) nil)
12492 ((eq arg 'done) (or done-word (car org-done-keywords)))
12493 ((eq arg 'nextset)
12494 (or (car (cdr (member head org-todo-heads)))
12495 (car org-todo-heads)))
12496 ((eq arg 'previousset)
12497 (let ((org-todo-heads (reverse org-todo-heads)))
12498 (or (car (cdr (member head org-todo-heads)))
12499 (car org-todo-heads))))
12500 ((car (member arg org-todo-keywords-1)))
12501 ((stringp arg)
12502 (user-error "State `%s' not valid in this file" arg))
12503 ((nth (1- (prefix-numeric-value arg))
12504 org-todo-keywords-1))))
12505 ((null member) (or head (car org-todo-keywords-1)))
12506 ((equal this final-done-word) nil) ;; -> make empty
12507 ((null tail) nil) ;; -> first entry
12508 ((memq interpret '(type priority))
12509 (if (eq this-command last-command)
12510 (car tail)
12511 (if (> (length tail) 0)
12512 (or done-word (car org-done-keywords))
12513 nil)))
12515 (car tail))))
12516 (org-state (or
12517 (run-hook-with-args-until-success
12518 'org-todo-get-default-hook org-state org-last-state)
12519 org-state))
12520 (next (if org-state (concat " " org-state " ") " "))
12521 (change-plist (list :type 'todo-state-change :from this :to org-state
12522 :position startpos))
12523 dolog now-done-p)
12524 (when org-blocker-hook
12525 (setq org-last-todo-state-is-todo
12526 (not (member this org-done-keywords)))
12527 (unless (save-excursion
12528 (save-match-data
12529 (org-with-wide-buffer
12530 (run-hook-with-args-until-failure
12531 'org-blocker-hook change-plist))))
12532 (if (org-called-interactively-p 'interactive)
12533 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12534 this org-state org-block-entry-blocking)
12535 ;; fail silently
12536 (message "TODO state change from %s to %s blocked (by \"%s\")"
12537 this org-state org-block-entry-blocking)
12538 (throw 'exit nil))))
12539 (store-match-data match-data)
12540 (replace-match next t t)
12541 (cond ((equal this org-state)
12542 (message "TODO state was already %s" (org-trim next)))
12543 ((pos-visible-in-window-p hl-pos)
12544 (message "TODO state changed to %s" (org-trim next))))
12545 (unless head
12546 (setq head (org-get-todo-sequence-head org-state)
12547 ass (assoc head org-todo-kwd-alist)
12548 interpret (nth 1 ass)
12549 done-word (nth 3 ass)
12550 final-done-word (nth 4 ass)))
12551 (when (memq arg '(nextset previousset))
12552 (message "Keyword-Set %d/%d: %s"
12553 (- (length org-todo-sets) -1
12554 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12555 (length org-todo-sets)
12556 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12557 (setq org-last-todo-state-is-todo
12558 (not (member org-state org-done-keywords)))
12559 (setq now-done-p (and (member org-state org-done-keywords)
12560 (not (member this org-done-keywords))))
12561 (and logging (org-local-logging logging))
12562 (when (and (or org-todo-log-states org-log-done)
12563 (not (eq org-inhibit-logging t))
12564 (not (memq arg '(nextset previousset))))
12565 ;; we need to look at recording a time and note
12566 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12567 (nth 2 (assoc this org-todo-log-states))))
12568 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12569 (setq dolog 'time))
12570 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12571 (and org-state
12572 (member org-state org-not-done-keywords)
12573 (not (member this org-not-done-keywords))))
12574 ;; This is now a todo state and was not one before
12575 ;; If there was a CLOSED time stamp, get rid of it.
12576 (org-add-planning-info nil nil 'closed))
12577 (when (and now-done-p org-log-done)
12578 ;; It is now done, and it was not done before
12579 (org-add-planning-info 'closed (org-current-effective-time))
12580 (when (and (not dolog) (eq 'note org-log-done))
12581 (org-add-log-setup 'done org-state this 'note)))
12582 (when (and org-state dolog)
12583 ;; This is a non-nil state, and we need to log it
12584 (org-add-log-setup 'state org-state this dolog)))
12585 ;; Fixup tag positioning
12586 (org-todo-trigger-tag-changes org-state)
12587 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12588 (when org-provide-todo-statistics
12589 (org-update-parent-todo-statistics))
12590 (run-hooks 'org-after-todo-state-change-hook)
12591 (when (and arg (not (member org-state org-done-keywords)))
12592 (setq head (org-get-todo-sequence-head org-state)))
12593 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12594 ;; Do we need to trigger a repeat?
12595 (when now-done-p
12596 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12597 ;; This is for the agenda, take a snapshot of the headline.
12598 (save-match-data
12599 (setq org-agenda-headline-snapshot-before-repeat
12600 (org-get-heading))))
12601 (org-auto-repeat-maybe org-state))
12602 ;; Fixup cursor location if close to the keyword
12603 (when (and (outline-on-heading-p)
12604 (not (bolp))
12605 (save-excursion (beginning-of-line 1)
12606 (looking-at org-todo-line-regexp))
12607 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12608 (goto-char (or (match-end 2) (match-end 1)))
12609 (and (looking-at " ") (just-one-space)))
12610 (when org-trigger-hook
12611 (save-excursion
12612 (run-hook-with-args 'org-trigger-hook change-plist)))
12613 (when commentp (org-toggle-comment))))))))
12615 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12616 "Block turning an entry into a TODO, using the hierarchy.
12617 This checks whether the current task should be blocked from state
12618 changes. Such blocking occurs when:
12620 1. The task has children which are not all in a completed state.
12622 2. A task has a parent with the property :ORDERED:, and there
12623 are siblings prior to the current task with incomplete
12624 status.
12626 3. The parent of the task is blocked because it has siblings that should
12627 be done first, or is child of a block grandparent TODO entry."
12629 (if (not org-enforce-todo-dependencies)
12630 t ; if locally turned off don't block
12631 (catch 'dont-block
12632 ;; If this is not a todo state change, or if this entry is already DONE,
12633 ;; do not block
12634 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12635 (member (plist-get change-plist :from)
12636 (cons 'done org-done-keywords))
12637 (member (plist-get change-plist :to)
12638 (cons 'todo org-not-done-keywords))
12639 (not (plist-get change-plist :to)))
12640 (throw 'dont-block t))
12641 ;; If this task has children, and any are undone, it's blocked
12642 (save-excursion
12643 (org-back-to-heading t)
12644 (let ((this-level (funcall outline-level)))
12645 (outline-next-heading)
12646 (let ((child-level (funcall outline-level)))
12647 (while (and (not (eobp))
12648 (> child-level this-level))
12649 ;; this todo has children, check whether they are all
12650 ;; completed
12651 (when (and (not (org-entry-is-done-p))
12652 (org-entry-is-todo-p))
12653 (setq org-block-entry-blocking (org-get-heading))
12654 (throw 'dont-block nil))
12655 (outline-next-heading)
12656 (setq child-level (funcall outline-level))))))
12657 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12658 ;; any previous siblings are undone, it's blocked
12659 (save-excursion
12660 (org-back-to-heading t)
12661 (let* ((pos (point))
12662 (parent-pos (and (org-up-heading-safe) (point))))
12663 (unless parent-pos (throw 'dont-block t)) ; no parent
12664 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12665 (forward-line 1)
12666 (re-search-forward org-not-done-heading-regexp pos t))
12667 (setq org-block-entry-blocking (match-string 0))
12668 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12669 ;; Search further up the hierarchy, to see if an ancestor is blocked
12670 (while t
12671 (goto-char parent-pos)
12672 (unless (looking-at org-not-done-heading-regexp)
12673 (throw 'dont-block t)) ; do not block, parent is not a TODO
12674 (setq pos (point))
12675 (setq parent-pos (and (org-up-heading-safe) (point)))
12676 (unless parent-pos (throw 'dont-block t)) ; no parent
12677 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12678 (forward-line 1)
12679 (re-search-forward org-not-done-heading-regexp pos t)
12680 (setq org-block-entry-blocking (org-get-heading)))
12681 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12683 (defcustom org-track-ordered-property-with-tag nil
12684 "Should the ORDERED property also be shown as a tag?
12685 The ORDERED property decides if an entry should require subtasks to be
12686 completed in sequence. Since a property is not very visible, setting
12687 this option means that toggling the ORDERED property with the command
12688 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12689 not relevant for the behavior, but it makes things more visible.
12691 Note that toggling the tag with tags commands will not change the property
12692 and therefore not influence behavior!
12694 This can be t, meaning the tag ORDERED should be used, It can also be a
12695 string to select a different tag for this task."
12696 :group 'org-todo
12697 :type '(choice
12698 (const :tag "No tracking" nil)
12699 (const :tag "Track with ORDERED tag" t)
12700 (string :tag "Use other tag")))
12702 (defun org-toggle-ordered-property ()
12703 "Toggle the ORDERED property of the current entry.
12704 For better visibility, you can track the value of this property with a tag.
12705 See variable `org-track-ordered-property-with-tag'."
12706 (interactive)
12707 (let* ((t1 org-track-ordered-property-with-tag)
12708 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12709 (save-excursion
12710 (org-back-to-heading)
12711 (if (org-entry-get nil "ORDERED")
12712 (progn
12713 (org-delete-property "ORDERED")
12714 (and tag (org-toggle-tag tag 'off))
12715 (message "Subtasks can be completed in arbitrary order"))
12716 (org-entry-put nil "ORDERED" "t")
12717 (and tag (org-toggle-tag tag 'on))
12718 (message "Subtasks must be completed in sequence")))))
12720 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12721 (defun org-block-todo-from-checkboxes (change-plist)
12722 "Block turning an entry into a TODO, using checkboxes.
12723 This checks whether the current task should be blocked from state
12724 changes because there are unchecked boxes in this entry."
12725 (if (not org-enforce-todo-checkbox-dependencies)
12726 t ; if locally turned off don't block
12727 (catch 'dont-block
12728 ;; If this is not a todo state change, or if this entry is already DONE,
12729 ;; do not block
12730 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12731 (member (plist-get change-plist :from)
12732 (cons 'done org-done-keywords))
12733 (member (plist-get change-plist :to)
12734 (cons 'todo org-not-done-keywords))
12735 (not (plist-get change-plist :to)))
12736 (throw 'dont-block t))
12737 ;; If this task has checkboxes that are not checked, it's blocked
12738 (save-excursion
12739 (org-back-to-heading t)
12740 (let ((beg (point)) end)
12741 (outline-next-heading)
12742 (setq end (point))
12743 (goto-char beg)
12744 (when (org-list-search-forward
12745 (concat (org-item-beginning-re)
12746 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12747 "\\[[- ]\\]")
12748 end t)
12749 (when (boundp 'org-blocked-by-checkboxes)
12750 (setq org-blocked-by-checkboxes t))
12751 (throw 'dont-block nil))))
12752 t))) ; do not block
12754 (defun org-entry-blocked-p ()
12755 "Non-nil if entry at point is blocked."
12756 (and (not (org-entry-get nil "NOBLOCKING"))
12757 (member (org-entry-get nil "TODO") org-not-done-keywords)
12758 (not (run-hook-with-args-until-failure
12759 'org-blocker-hook
12760 (list :type 'todo-state-change
12761 :position (point)
12762 :from 'todo
12763 :to 'done)))))
12765 (defun org-update-statistics-cookies (all)
12766 "Update the statistics cookie, either from TODO or from checkboxes.
12767 This should be called with the cursor in a line with a statistics cookie."
12768 (interactive "P")
12769 (if all
12770 (progn
12771 (org-update-checkbox-count 'all)
12772 (org-map-entries 'org-update-parent-todo-statistics))
12773 (if (not (org-at-heading-p))
12774 (org-update-checkbox-count)
12775 (let ((pos (point-marker))
12776 end l1 l2)
12777 (ignore-errors (org-back-to-heading t))
12778 (if (not (org-at-heading-p))
12779 (org-update-checkbox-count)
12780 (setq l1 (org-outline-level))
12781 (setq end (save-excursion
12782 (outline-next-heading)
12783 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12784 (point)))
12785 (if (and (save-excursion
12786 (re-search-forward
12787 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12788 (not (save-excursion (re-search-forward
12789 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12790 (org-update-checkbox-count)
12791 (if (and l2 (> l2 l1))
12792 (progn
12793 (goto-char end)
12794 (org-update-parent-todo-statistics))
12795 (goto-char pos)
12796 (beginning-of-line 1)
12797 (while (re-search-forward
12798 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12799 (point-at-eol) t)
12800 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12801 (goto-char pos)
12802 (move-marker pos nil)))))
12804 (defvar org-entry-property-inherited-from) ;; defined below
12805 (defun org-update-parent-todo-statistics ()
12806 "Update any statistics cookie in the parent of the current headline.
12807 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12808 the entire subtree and this will travel up the hierarchy and update
12809 statistics everywhere."
12810 (let* ((prop (save-excursion (org-up-heading-safe)
12811 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12812 (recursive (or (not org-hierarchical-todo-statistics)
12813 (and prop (string-match "\\<recursive\\>" prop))))
12814 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12816 (first t)
12817 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12818 level ltoggle l1 new ndel
12819 (cnt-all 0) (cnt-done 0) is-percent kwd
12820 checkbox-beg ov ovs ove cookie-present)
12821 (catch 'exit
12822 (save-excursion
12823 (beginning-of-line 1)
12824 (setq ltoggle (funcall outline-level))
12825 ;; Three situations are to consider:
12827 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12828 ;; to the top-level ancestor on the headline;
12830 ;; 2. If parent has "recursive" property, repeat up to the
12831 ;; headline setting that property, taking inheritance into
12832 ;; account;
12834 ;; 3. Else, move up to direct parent and proceed only once.
12835 (while (and (setq level (org-up-heading-safe))
12836 (or recursive first)
12837 (>= (point) lim))
12838 (setq first nil cookie-present nil)
12839 (unless (and level
12840 (not (string-match
12841 "\\<checkbox\\>"
12842 (downcase (or (org-entry-get nil "COOKIE_DATA")
12843 "")))))
12844 (throw 'exit nil))
12845 (while (re-search-forward box-re (point-at-eol) t)
12846 (setq cnt-all 0 cnt-done 0 cookie-present t)
12847 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12848 (save-match-data
12849 (unless (outline-next-heading) (throw 'exit nil))
12850 (while (and (looking-at org-complex-heading-regexp)
12851 (> (setq l1 (length (match-string 1))) level))
12852 (setq kwd (and (or recursive (= l1 ltoggle))
12853 (match-string 2)))
12854 (if (or (eq org-provide-todo-statistics 'all-headlines)
12855 (and (eq org-provide-todo-statistics t)
12856 (or (member kwd org-done-keywords)))
12857 (and (listp org-provide-todo-statistics)
12858 (stringp (car org-provide-todo-statistics))
12859 (or (member kwd org-provide-todo-statistics)
12860 (member kwd org-done-keywords)))
12861 (and (listp org-provide-todo-statistics)
12862 (listp (car org-provide-todo-statistics))
12863 (or (member kwd (car org-provide-todo-statistics))
12864 (and (member kwd org-done-keywords)
12865 (member kwd (cadr org-provide-todo-statistics))))))
12866 (setq cnt-all (1+ cnt-all))
12867 (and (eq org-provide-todo-statistics t)
12869 (setq cnt-all (1+ cnt-all))))
12870 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12871 (member kwd org-done-keywords))
12872 (and (listp org-provide-todo-statistics)
12873 (listp (car org-provide-todo-statistics))
12874 (member kwd org-done-keywords)
12875 (member kwd (cadr org-provide-todo-statistics)))
12876 (and (listp org-provide-todo-statistics)
12877 (stringp (car org-provide-todo-statistics))
12878 (member kwd org-done-keywords)))
12879 (setq cnt-done (1+ cnt-done)))
12880 (outline-next-heading)))
12881 (setq new
12882 (if is-percent
12883 (format "[%d%%]" (floor (* 100.0 cnt-done)
12884 (max 1 cnt-all)))
12885 (format "[%d/%d]" cnt-done cnt-all))
12886 ndel (- (match-end 0) checkbox-beg))
12887 ;; handle overlays when updating cookie from column view
12888 (when (setq ov (car (overlays-at checkbox-beg)))
12889 (setq ovs (overlay-start ov) ove (overlay-end ov))
12890 (delete-overlay ov))
12891 (goto-char checkbox-beg)
12892 (insert new)
12893 (delete-region (point) (+ (point) ndel))
12894 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12895 (when ov (move-overlay ov ovs ove)))
12896 (when cookie-present
12897 (run-hook-with-args 'org-after-todo-statistics-hook
12898 cnt-done (- cnt-all cnt-done))))))
12899 (run-hooks 'org-todo-statistics-hook)))
12901 (defvar org-after-todo-statistics-hook nil
12902 "Hook that is called after a TODO statistics cookie has been updated.
12903 Each function is called with two arguments: the number of not-done entries
12904 and the number of done entries.
12906 For example, the following function, when added to this hook, will switch
12907 an entry to DONE when all children are done, and back to TODO when new
12908 entries are set to a TODO status. Note that this hook is only called
12909 when there is a statistics cookie in the headline!
12911 \(defun org-summary-todo (n-done n-not-done)
12912 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12913 \(let (org-log-done org-log-states) ; turn off logging
12914 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12917 (defvar org-todo-statistics-hook nil
12918 "Hook that is run whenever Org thinks TODO statistics should be updated.
12919 This hook runs even if there is no statistics cookie present, in which case
12920 `org-after-todo-statistics-hook' would not run.")
12922 (defun org-todo-trigger-tag-changes (state)
12923 "Apply the changes defined in `org-todo-state-tags-triggers'."
12924 (let ((l org-todo-state-tags-triggers)
12925 changes)
12926 (when (or (not state) (equal state ""))
12927 (setq changes (append changes (cdr (assoc "" l)))))
12928 (when (and (stringp state) (> (length state) 0))
12929 (setq changes (append changes (cdr (assoc state l)))))
12930 (when (member state org-not-done-keywords)
12931 (setq changes (append changes (cdr (assoc 'todo l)))))
12932 (when (member state org-done-keywords)
12933 (setq changes (append changes (cdr (assoc 'done l)))))
12934 (dolist (c changes)
12935 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12937 (defun org-local-logging (value)
12938 "Get logging settings from a property VALUE."
12939 ;; Directly set the variables, they are already local.
12940 (setq org-log-done nil
12941 org-log-repeat nil
12942 org-todo-log-states nil)
12943 (dolist (w (org-split-string value))
12944 (let (a)
12945 (cond
12946 ((setq a (assoc w org-startup-options))
12947 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12948 (set (nth 1 a) (nth 2 a))))
12949 ((setq a (org-extract-log-state-settings w))
12950 (and (member (car a) org-todo-keywords-1)
12951 (push a org-todo-log-states)))))))
12953 (defun org-get-todo-sequence-head (kwd)
12954 "Return the head of the TODO sequence to which KWD belongs.
12955 If KWD is not set, check if there is a text property remembering the
12956 right sequence."
12957 (let (p)
12958 (cond
12959 ((not kwd)
12960 (or (get-text-property (point-at-bol) 'org-todo-head)
12961 (progn
12962 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
12963 nil (point-at-eol)))
12964 (get-text-property p 'org-todo-head))))
12965 ((not (member kwd org-todo-keywords-1))
12966 (car org-todo-keywords-1))
12967 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
12969 (defun org-fast-todo-selection ()
12970 "Fast TODO keyword selection with single keys.
12971 Returns the new TODO keyword, or nil if no state change should occur."
12972 (let* ((fulltable org-todo-key-alist)
12973 (done-keywords org-done-keywords) ;; needed for the faces.
12974 (maxlen (apply 'max (mapcar
12975 (lambda (x)
12976 (if (stringp (car x)) (string-width (car x)) 0))
12977 fulltable)))
12978 (expert nil)
12979 (fwidth (+ maxlen 3 1 3))
12980 (ncol (/ (- (window-width) 4) fwidth))
12981 tg cnt e c tbl
12982 groups ingroup)
12983 (save-excursion
12984 (save-window-excursion
12985 (if expert
12986 (set-buffer (get-buffer-create " *Org todo*"))
12987 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
12988 (erase-buffer)
12989 (setq-local org-done-keywords done-keywords)
12990 (setq tbl fulltable cnt 0)
12991 (while (setq e (pop tbl))
12992 (cond
12993 ((equal e '(:startgroup))
12994 (push '() groups) (setq ingroup t)
12995 (unless (= cnt 0)
12996 (setq cnt 0)
12997 (insert "\n"))
12998 (insert "{ "))
12999 ((equal e '(:endgroup))
13000 (setq ingroup nil cnt 0)
13001 (insert "}\n"))
13002 ((equal e '(:newline))
13003 (unless (= cnt 0)
13004 (setq cnt 0)
13005 (insert "\n")
13006 (setq e (car tbl))
13007 (while (equal (car tbl) '(:newline))
13008 (insert "\n")
13009 (setq tbl (cdr tbl)))))
13011 (setq tg (car e) c (cdr e))
13012 (when ingroup (push tg (car groups)))
13013 (setq tg (org-add-props tg nil 'face
13014 (org-get-todo-face tg)))
13015 (when (and (= cnt 0) (not ingroup)) (insert " "))
13016 (insert "[" c "] " tg (make-string
13017 (- fwidth 4 (length tg)) ?\ ))
13018 (when (= (setq cnt (1+ cnt)) ncol)
13019 (insert "\n")
13020 (when ingroup (insert " "))
13021 (setq cnt 0)))))
13022 (insert "\n")
13023 (goto-char (point-min))
13024 (unless expert (org-fit-window-to-buffer))
13025 (message "[a-z..]:Set [SPC]:clear")
13026 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13027 (cond
13028 ((or (= c ?\C-g)
13029 (and (= c ?q) (not (rassoc c fulltable))))
13030 (setq quit-flag t))
13031 ((= c ?\ ) nil)
13032 ((setq e (rassoc c fulltable) tg (car e))
13034 (t (setq quit-flag t)))))))
13036 (defun org-entry-is-todo-p ()
13037 (member (org-get-todo-state) org-not-done-keywords))
13039 (defun org-entry-is-done-p ()
13040 (member (org-get-todo-state) org-done-keywords))
13042 (defun org-get-todo-state ()
13043 "Return the TODO keyword of the current subtree."
13044 (save-excursion
13045 (org-back-to-heading t)
13046 (and (looking-at org-todo-line-regexp)
13047 (match-end 2)
13048 (match-string 2))))
13050 (defun org-at-date-range-p (&optional inactive-ok)
13051 "Non-nil if point is inside a date range.
13053 When optional argument INACTIVE-OK is non-nil, also consider
13054 inactive time ranges.
13056 When this function returns a non-nil value, match data is set
13057 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13058 on INACTIVE-OK."
13059 (interactive)
13060 (save-excursion
13061 (catch 'exit
13062 (let ((pos (point)))
13063 (skip-chars-backward "^[<\r\n")
13064 (skip-chars-backward "<[")
13065 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13066 (>= (match-end 0) pos)
13067 (throw 'exit t))
13068 (skip-chars-backward "^<[\r\n")
13069 (skip-chars-backward "<[")
13070 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13071 (>= (match-end 0) pos)
13072 (throw 'exit t)))
13073 nil)))
13075 (defun org-get-repeat (&optional tagline)
13076 "Check if there is a deadline/schedule with repeater in this entry."
13077 (save-match-data
13078 (save-excursion
13079 (org-back-to-heading t)
13080 (and (re-search-forward (if tagline
13081 (concat tagline "\\s-*" org-repeat-re)
13082 org-repeat-re)
13083 (org-entry-end-position) t)
13084 (match-string-no-properties 1)))))
13086 (defvar org-last-changed-timestamp)
13087 (defvar org-last-inserted-timestamp)
13088 (defvar org-log-post-message)
13089 (defvar org-log-note-purpose)
13090 (defvar org-log-note-how nil)
13091 (defvar org-log-note-extra)
13092 (defun org-auto-repeat-maybe (done-word)
13093 "Check if the current headline contains a repeated time-stamp.
13095 If yes, set TODO state back to what it was and change the base date
13096 of repeating deadline/scheduled time stamps to new date.
13098 This function is run automatically after each state change to a DONE state."
13099 (let* ((repeat (org-get-repeat))
13100 (aa (assoc org-last-state org-todo-kwd-alist))
13101 (interpret (nth 1 aa))
13102 (head (nth 2 aa))
13103 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13104 (msg "Entry repeats: ")
13105 (org-log-done nil)
13106 (org-todo-log-states nil))
13107 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13108 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13109 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13110 org-todo-repeat-to-state)))
13111 (unless (and to-state (member to-state org-todo-keywords-1))
13112 (setq to-state (if (eq interpret 'type) org-last-state head)))
13113 (org-todo to-state))
13114 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13115 (org-entry-put nil "LAST_REPEAT" (format-time-string
13116 (org-time-stamp-format t t))))
13117 (when org-log-repeat
13118 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13119 (memq 'org-add-log-note post-command-hook))
13120 ;; We are already setup for some record.
13121 (when (eq org-log-repeat 'note)
13122 ;; Make sure we take a note, not only a time stamp.
13123 (setq org-log-note-how 'note))
13124 ;; Set up for taking a record.
13125 (org-add-log-setup 'state
13126 (or done-word (car org-done-keywords))
13127 org-last-state
13128 org-log-repeat)))
13129 (org-back-to-heading t)
13130 (org-add-planning-info nil nil 'closed)
13131 (let ((end (save-excursion (outline-next-heading) (point))))
13132 (while (re-search-forward org-ts-regexp end t)
13133 (when (save-match-data
13134 (or (org-at-planning-p)
13135 (org-at-property-p)
13136 (eq (org-element-type (save-excursion
13137 (backward-char)
13138 (org-element-context)))
13139 'timestamp)))
13140 (let ((type (cond ((match-end 1) org-scheduled-string)
13141 ((match-end 3) org-deadline-string)
13142 (t "Plain:")))
13143 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13144 (cond
13145 ((not
13146 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13147 ;; Time-stamps without a repeater are usually skipped.
13148 ;; However, a SCHEDULED time-stamp without one is
13149 ;; removed, as it is considered as no longer relevant.
13150 (when (equal type org-scheduled-string)
13151 (org-remove-timestamp-with-keyword type)))
13153 (let ((n (string-to-number (match-string 2 ts)))
13154 (what (match-string 3 ts)))
13155 (when (equal what "w") (setq n (* n 7) what "d"))
13156 (when (and (equal what "h")
13157 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13158 ts)))
13159 (user-error
13160 "Cannot repeat in Repeat in %d hour(s) because no hour \
13161 has been set"
13163 ;; Preparation, see if we need to modify the start
13164 ;; date for the change.
13165 (when (match-end 1)
13166 (let ((time (save-match-data (org-time-string-to-time ts))))
13167 (cond
13168 ((equal (match-string 1 ts) ".")
13169 ;; Shift starting date to today
13170 (org-timestamp-change
13171 (- (org-today) (time-to-days time))
13172 'day))
13173 ((equal (match-string 1 ts) "+")
13174 (let ((nshiftmax 10)
13175 (nshift 0))
13176 (while (or (= nshift 0)
13177 (<= (time-to-days time)
13178 (time-to-days (current-time))))
13179 (when (= (cl-incf nshift) nshiftmax)
13180 (or (y-or-n-p
13181 (format "%d repeater intervals were not \
13182 enough to shift date past today. Continue? "
13183 nshift))
13184 (user-error "Abort")))
13185 (org-timestamp-change n (cdr (assoc what whata)))
13186 (org-at-timestamp-p t)
13187 (setq ts (match-string 1))
13188 (setq time
13189 (save-match-data
13190 (org-time-string-to-time ts)))))
13191 (org-timestamp-change (- n) (cdr (assoc what whata)))
13192 ;; Rematch, so that we have everything in
13193 ;; place for the real shift.
13194 (org-at-timestamp-p t)
13195 (setq ts (match-string 1))
13196 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13197 ts)))))
13198 (save-excursion
13199 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13200 (setq msg
13201 (concat
13202 msg type " " org-last-changed-timestamp " ")))))))))
13203 (setq org-log-post-message msg)
13204 (message "%s" msg))))
13206 (defun org-show-todo-tree (arg)
13207 "Make a compact tree which shows all headlines marked with TODO.
13208 The tree will show the lines where the regexp matches, and all higher
13209 headlines above the match.
13210 With a \\[universal-argument] prefix, prompt for a regexp to match.
13211 With a numeric prefix N, construct a sparse tree for the Nth element
13212 of `org-todo-keywords-1'."
13213 (interactive "P")
13214 (let ((case-fold-search nil)
13215 (kwd-re
13216 (cond ((null arg) org-not-done-regexp)
13217 ((equal arg '(4))
13218 (let ((kwd
13219 (completing-read "Keyword (or KWD1|KWD2|...): "
13220 (mapcar #'list org-todo-keywords-1))))
13221 (concat "\\("
13222 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13223 "\\)\\>")))
13224 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13225 (regexp-quote (nth (1- (prefix-numeric-value arg))
13226 org-todo-keywords-1)))
13227 (t (user-error "Invalid prefix argument: %s" arg)))))
13228 (message "%d TODO entries found"
13229 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13231 (defun org-deadline (arg &optional time)
13232 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13233 With one universal prefix argument, remove any deadline from the item.
13234 With two universal prefix arguments, prompt for a warning delay.
13235 With argument TIME, set the deadline at the corresponding date. TIME
13236 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13237 (interactive "P")
13238 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13239 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13240 'region-start-level 'region))
13241 org-loop-over-headlines-in-active-region)
13242 (org-map-entries
13243 `(org-deadline ',arg ,time)
13244 org-loop-over-headlines-in-active-region
13245 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13246 (let* ((old-date (org-entry-get nil "DEADLINE"))
13247 (old-date-time (when old-date (org-time-string-to-time old-date)))
13248 (repeater (and old-date
13249 (string-match
13250 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13251 old-date)
13252 (match-string 1 old-date))))
13253 (cond
13254 ((equal arg '(4))
13255 (when (and old-date org-log-redeadline)
13256 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13257 (org-remove-timestamp-with-keyword org-deadline-string)
13258 (message "Item no longer has a deadline."))
13259 ((equal arg '(16))
13260 (save-excursion
13261 (org-back-to-heading t)
13262 (if (re-search-forward
13263 org-deadline-time-regexp
13264 (save-excursion (outline-next-heading) (point)) t)
13265 (let* ((rpl0 (match-string 1))
13266 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13267 (replace-match
13268 (concat org-deadline-string
13269 " <" rpl
13270 (format " -%dd"
13271 (abs
13272 (- (time-to-days
13273 (save-match-data
13274 (org-read-date nil t nil "Warn starting from" old-date-time)))
13275 (time-to-days old-date-time))))
13276 ">") t t))
13277 (user-error "No deadline information to update"))))
13279 (org-add-planning-info 'deadline time 'closed)
13280 (when (and old-date
13281 org-log-redeadline
13282 (not (equal old-date org-last-inserted-timestamp)))
13283 (org-add-log-setup
13284 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13285 (when repeater
13286 (save-excursion
13287 (org-back-to-heading t)
13288 (when (re-search-forward (concat org-deadline-string " "
13289 org-last-inserted-timestamp)
13290 (save-excursion
13291 (outline-next-heading) (point)) t)
13292 (goto-char (1- (match-end 0)))
13293 (insert " " repeater)
13294 (setq org-last-inserted-timestamp
13295 (concat (substring org-last-inserted-timestamp 0 -1)
13296 " " repeater
13297 (substring org-last-inserted-timestamp -1))))))
13298 (message "Deadline on %s" org-last-inserted-timestamp))))))
13300 (defun org-schedule (arg &optional time)
13301 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13302 With one universal prefix argument, remove any scheduling date from the item.
13303 With two universal prefix arguments, prompt for a delay cookie.
13304 With argument TIME, scheduled at the corresponding date. TIME can
13305 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13306 (interactive "P")
13307 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13308 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13309 'region-start-level 'region))
13310 org-loop-over-headlines-in-active-region)
13311 (org-map-entries
13312 `(org-schedule ',arg ,time)
13313 org-loop-over-headlines-in-active-region
13314 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13315 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13316 (old-date-time (when old-date (org-time-string-to-time old-date)))
13317 (repeater (and old-date
13318 (string-match
13319 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13320 old-date)
13321 (match-string 1 old-date))))
13322 (cond
13323 ((equal arg '(4))
13324 (progn
13325 (when (and old-date org-log-reschedule)
13326 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13327 (org-remove-timestamp-with-keyword org-scheduled-string)
13328 (message "Item is no longer scheduled.")))
13329 ((equal arg '(16))
13330 (save-excursion
13331 (org-back-to-heading t)
13332 (if (re-search-forward
13333 org-scheduled-time-regexp
13334 (save-excursion (outline-next-heading) (point)) t)
13335 (let* ((rpl0 (match-string 1))
13336 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13337 (replace-match
13338 (concat org-scheduled-string
13339 " <" rpl
13340 (format " -%dd"
13341 (abs
13342 (- (time-to-days
13343 (save-match-data
13344 (org-read-date nil t nil "Delay until" old-date-time)))
13345 (time-to-days old-date-time))))
13346 ">") t t))
13347 (user-error "No scheduled information to update"))))
13349 (org-add-planning-info 'scheduled time 'closed)
13350 (when (and old-date
13351 org-log-reschedule
13352 (not (equal old-date org-last-inserted-timestamp)))
13353 (org-add-log-setup
13354 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13355 (when repeater
13356 (save-excursion
13357 (org-back-to-heading t)
13358 (when (re-search-forward (concat org-scheduled-string " "
13359 org-last-inserted-timestamp)
13360 (save-excursion
13361 (outline-next-heading) (point)) t)
13362 (goto-char (1- (match-end 0)))
13363 (insert " " repeater)
13364 (setq org-last-inserted-timestamp
13365 (concat (substring org-last-inserted-timestamp 0 -1)
13366 " " repeater
13367 (substring org-last-inserted-timestamp -1))))))
13368 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13370 (defun org-get-scheduled-time (pom &optional inherit)
13371 "Get the scheduled time as a time tuple, of a format suitable
13372 for calling org-schedule with, or if there is no scheduling,
13373 returns nil."
13374 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13375 (when time
13376 (apply 'encode-time (org-parse-time-string time)))))
13378 (defun org-get-deadline-time (pom &optional inherit)
13379 "Get the deadline as a time tuple, of a format suitable for
13380 calling org-deadline with, or if there is no scheduling, returns
13381 nil."
13382 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13383 (when time
13384 (apply 'encode-time (org-parse-time-string time)))))
13386 (defun org-remove-timestamp-with-keyword (keyword)
13387 "Remove all time stamps with KEYWORD in the current entry."
13388 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13389 beg)
13390 (save-excursion
13391 (org-back-to-heading t)
13392 (setq beg (point))
13393 (outline-next-heading)
13394 (while (re-search-backward re beg t)
13395 (replace-match "")
13396 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13397 (equal (char-before) ?\ ))
13398 (backward-delete-char 1)
13399 (when (string-match "^[ \t]*$" (buffer-substring
13400 (point-at-bol) (point-at-eol)))
13401 (delete-region (point-at-bol)
13402 (min (point-max) (1+ (point-at-eol))))))))))
13404 (defvar org-time-was-given) ; dynamically scoped parameter
13405 (defvar org-end-time-was-given) ; dynamically scoped parameter
13407 (defun org-at-planning-p ()
13408 "Non-nil when point is on a planning info line."
13409 ;; This is as accurate and faster than `org-element-at-point' since
13410 ;; planning info location is fixed in the section.
13411 (org-with-wide-buffer
13412 (beginning-of-line)
13413 (and (org-looking-at-p org-planning-line-re)
13414 (eq (point)
13415 (ignore-errors
13416 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13417 (org-back-to-heading t)
13418 (org-with-limited-levels (org-back-to-heading t)))
13419 (line-beginning-position 2))))))
13421 (defun org-add-planning-info (what &optional time &rest remove)
13422 "Insert new timestamp with keyword in the planning line.
13423 WHAT indicates what kind of time stamp to add. It is a symbol
13424 among `closed', `deadline', `scheduled' and nil. TIME indicates
13425 the time to use. If none is given, the user is prompted for
13426 a date. REMOVE indicates what kind of entries to remove. An old
13427 WHAT entry will also be removed."
13428 (let (org-time-was-given org-end-time-was-given default-time default-input)
13429 (catch 'exit
13430 (when (and (memq what '(scheduled deadline))
13431 (or (not time)
13432 (and (stringp time)
13433 (string-match "^[-+]+[0-9]" time))))
13434 ;; Try to get a default date/time from existing timestamp
13435 (save-excursion
13436 (org-back-to-heading t)
13437 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13438 (when (re-search-forward (if (eq what 'scheduled)
13439 org-scheduled-time-regexp
13440 org-deadline-time-regexp)
13441 end t)
13442 (setq ts (match-string 1)
13443 default-time (apply 'encode-time (org-parse-time-string ts))
13444 default-input (and ts (org-get-compact-tod ts)))))))
13445 (when what
13446 (setq time
13447 (if (stringp time)
13448 ;; This is a string (relative or absolute), set
13449 ;; proper date.
13450 (apply #'encode-time
13451 (org-read-date-analyze
13452 time default-time (decode-time default-time)))
13453 ;; If necessary, get the time from the user
13454 (or time (org-read-date nil 'to-time nil nil
13455 default-time default-input)))))
13457 (org-with-wide-buffer
13458 (org-back-to-heading t)
13459 (forward-line)
13460 (unless (bolp) (insert "\n"))
13461 (cond ((org-looking-at-p org-planning-line-re)
13462 ;; Move to current indentation.
13463 (skip-chars-forward " \t")
13464 ;; Check if we have to remove something.
13465 (dolist (type (if what (cons what remove) remove))
13466 (save-excursion
13467 (when (re-search-forward
13468 (cl-case type
13469 (closed org-closed-time-regexp)
13470 (deadline org-deadline-time-regexp)
13471 (scheduled org-scheduled-time-regexp)
13472 (otherwise
13473 (error "Invalid planning type: %s" type)))
13474 (line-end-position) t)
13475 ;; Delete until next keyword or end of line.
13476 (delete-region
13477 (match-beginning 0)
13478 (if (re-search-forward org-keyword-time-not-clock-regexp
13479 (line-end-position)
13481 (match-beginning 0)
13482 (line-end-position))))))
13483 ;; If there is nothing more to add and no more keyword
13484 ;; is left, remove the line completely.
13485 (if (and (org-looking-at-p "[ \t]*$") (not what))
13486 (delete-region (line-beginning-position)
13487 (line-beginning-position 2))
13488 ;; If we removed last keyword, do not leave trailing
13489 ;; white space at the end of line.
13490 (let ((p (point)))
13491 (save-excursion
13492 (end-of-line)
13493 (unless (= (skip-chars-backward " \t" p) 0)
13494 (delete-region (point) (line-end-position)))))))
13495 ((not what) (throw 'exit nil)) ; Nothing to do.
13496 (t (insert-before-markers "\n")
13497 (backward-char 1)
13498 (when org-adapt-indentation
13499 (org-indent-to-column (1+ (org-outline-level))))))
13500 (when what
13501 ;; Insert planning keyword.
13502 (insert (cl-case what
13503 (closed org-closed-string)
13504 (deadline org-deadline-string)
13505 (scheduled org-scheduled-string)
13506 (otherwise (error "Invalid planning type: %s" what)))
13507 " ")
13508 ;; Insert associated timestamp.
13509 (let ((ts (org-insert-time-stamp
13510 time
13511 (or org-time-was-given
13512 (and (eq what 'closed) org-log-done-with-time))
13513 (eq what 'closed)
13514 nil nil (list org-end-time-was-given))))
13515 (unless (eolp) (insert " "))
13516 ts))))))
13518 (defvar org-log-note-marker (make-marker)
13519 "Marker pointing at the entry where the note is to be inserted.")
13520 (defvar org-log-note-purpose nil)
13521 (defvar org-log-note-state nil)
13522 (defvar org-log-note-previous-state nil)
13523 (defvar org-log-note-extra nil)
13524 (defvar org-log-note-window-configuration nil)
13525 (defvar org-log-note-return-to (make-marker))
13526 (defvar org-log-note-effective-time nil
13527 "Remembered current time so that dynamically scoped
13528 `org-extend-today-until' affects timestamps in state change log")
13530 (defvar org-log-post-message nil
13531 "Message to be displayed after a log note has been stored.
13532 The auto-repeater uses this.")
13534 (defun org-add-note ()
13535 "Add a note to the current entry.
13536 This is done in the same way as adding a state change note."
13537 (interactive)
13538 (org-add-log-setup 'note))
13540 (defun org-log-beginning (&optional create)
13541 "Return expected start of log notes in current entry.
13542 When optional argument CREATE is non-nil, the function creates
13543 a drawer to store notes, if necessary. Returned position ignores
13544 narrowing."
13545 (org-with-wide-buffer
13546 (let ((drawer (org-log-into-drawer)))
13547 (cond
13548 (drawer
13549 (org-end-of-meta-data)
13550 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13551 (end (if (org-at-heading-p) (point)
13552 (save-excursion (outline-next-heading) (point))))
13553 (case-fold-search t))
13554 (catch 'exit
13555 ;; Try to find existing drawer.
13556 (while (re-search-forward regexp end t)
13557 (let ((element (org-element-at-point)))
13558 (when (eq (org-element-type element) 'drawer)
13559 (let ((cend (org-element-property :contents-end element)))
13560 (when (and (not org-log-states-order-reversed) cend)
13561 (goto-char cend)))
13562 (throw 'exit nil))))
13563 ;; No drawer found. Create one, if permitted.
13564 (when create
13565 (unless (bolp) (insert "\n"))
13566 (let ((beg (point)))
13567 (insert ":" drawer ":\n:END:\n")
13568 (org-indent-region beg (point)))
13569 (end-of-line -1)))))
13571 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13572 (skip-chars-forward " \t\n")
13573 (beginning-of-line)
13574 (unless org-log-states-order-reversed
13575 (org-skip-over-state-notes)
13576 (skip-chars-backward " \t\n")
13577 (forward-line)))))
13578 (if (bolp) (point) (line-beginning-position 2))))
13580 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13581 "Set up the post command hook to take a note.
13582 If this is about to TODO state change, the new state is expected in STATE.
13583 HOW is an indicator what kind of note should be created.
13584 EXTRA is additional text that will be inserted into the notes buffer."
13585 (move-marker org-log-note-marker (point))
13586 (setq org-log-note-purpose purpose
13587 org-log-note-state state
13588 org-log-note-previous-state prev-state
13589 org-log-note-how how
13590 org-log-note-extra extra
13591 org-log-note-effective-time (org-current-effective-time))
13592 (add-hook 'post-command-hook 'org-add-log-note 'append))
13594 (defun org-skip-over-state-notes ()
13595 "Skip past the list of State notes in an entry."
13596 (when (ignore-errors (goto-char (org-in-item-p)))
13597 (let* ((struct (org-list-struct))
13598 (prevs (org-list-prevs-alist struct))
13599 (regexp
13600 (concat "[ \t]*- +"
13601 (replace-regexp-in-string
13602 " +" " +"
13603 (org-replace-escapes
13604 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13605 `(("%d" . ,org-ts-regexp-inactive)
13606 ("%D" . ,org-ts-regexp)
13607 ("%s" . "\"\\S-+\"")
13608 ("%S" . "\"\\S-+\"")
13609 ("%t" . ,org-ts-regexp-inactive)
13610 ("%T" . ,org-ts-regexp)
13611 ("%u" . ".*?")
13612 ("%U" . ".*?")))))))
13613 (while (org-looking-at-p regexp)
13614 (goto-char (or (org-list-get-next-item (point) struct prevs)
13615 (org-list-get-item-end (point) struct)))))))
13617 (defun org-add-log-note (&optional _purpose)
13618 "Pop up a window for taking a note, and add this note later."
13619 (remove-hook 'post-command-hook 'org-add-log-note)
13620 (setq org-log-note-window-configuration (current-window-configuration))
13621 (delete-other-windows)
13622 (move-marker org-log-note-return-to (point))
13623 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13624 (goto-char org-log-note-marker)
13625 (org-switch-to-buffer-other-window "*Org Note*")
13626 (erase-buffer)
13627 (if (memq org-log-note-how '(time state))
13628 (let (current-prefix-arg) (org-store-log-note))
13629 (let ((org-inhibit-startup t)) (org-mode))
13630 (insert (format "# Insert note for %s.
13631 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13632 (cond
13633 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13634 ((eq org-log-note-purpose 'done) "closed todo item")
13635 ((eq org-log-note-purpose 'state)
13636 (format "state change from \"%s\" to \"%s\""
13637 (or org-log-note-previous-state "")
13638 (or org-log-note-state "")))
13639 ((eq org-log-note-purpose 'reschedule)
13640 "rescheduling")
13641 ((eq org-log-note-purpose 'delschedule)
13642 "no longer scheduled")
13643 ((eq org-log-note-purpose 'redeadline)
13644 "changing deadline")
13645 ((eq org-log-note-purpose 'deldeadline)
13646 "removing deadline")
13647 ((eq org-log-note-purpose 'refile)
13648 "refiling")
13649 ((eq org-log-note-purpose 'note)
13650 "this entry")
13651 (t (error "This should not happen")))))
13652 (when org-log-note-extra (insert org-log-note-extra))
13653 (setq-local org-finish-function 'org-store-log-note)
13654 (run-hooks 'org-log-buffer-setup-hook)))
13656 (defvar org-note-abort nil) ; dynamically scoped
13657 (defun org-store-log-note ()
13658 "Finish taking a log note, and insert it to where it belongs."
13659 (let ((txt (prog1 (buffer-string)
13660 (kill-buffer)))
13661 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13662 lines)
13663 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13664 (setq txt (replace-match "" t t txt)))
13665 (when (string-match "\\s-+\\'" txt)
13666 (setq txt (replace-match "" t t txt)))
13667 (setq lines (org-split-string txt "\n"))
13668 (when (org-string-nw-p note)
13669 (setq note
13670 (org-replace-escapes
13671 note
13672 (list (cons "%u" (user-login-name))
13673 (cons "%U" user-full-name)
13674 (cons "%t" (format-time-string
13675 (org-time-stamp-format 'long 'inactive)
13676 org-log-note-effective-time))
13677 (cons "%T" (format-time-string
13678 (org-time-stamp-format 'long nil)
13679 org-log-note-effective-time))
13680 (cons "%d" (format-time-string
13681 (org-time-stamp-format nil 'inactive)
13682 org-log-note-effective-time))
13683 (cons "%D" (format-time-string
13684 (org-time-stamp-format nil nil)
13685 org-log-note-effective-time))
13686 (cons "%s" (cond
13687 ((not org-log-note-state) "")
13688 ((org-string-match-p org-ts-regexp
13689 org-log-note-state)
13690 (format "\"[%s]\""
13691 (substring org-log-note-state 1 -1)))
13692 (t (format "\"%s\"" org-log-note-state))))
13693 (cons "%S"
13694 (cond
13695 ((not org-log-note-previous-state) "")
13696 ((org-string-match-p org-ts-regexp
13697 org-log-note-previous-state)
13698 (format "\"[%s]\""
13699 (substring
13700 org-log-note-previous-state 1 -1)))
13701 (t (format "\"%s\""
13702 org-log-note-previous-state)))))))
13703 (when lines (setq note (concat note " \\\\")))
13704 (push note lines))
13705 (when (and lines (not (or current-prefix-arg org-note-abort)))
13706 (with-current-buffer (marker-buffer org-log-note-marker)
13707 (org-with-wide-buffer
13708 ;; Find location for the new note.
13709 (goto-char org-log-note-marker)
13710 (set-marker org-log-note-marker nil)
13711 (goto-char (org-log-beginning t))
13712 ;; Make sure point is at the beginning of an empty line.
13713 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13714 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13715 ;; In an existing list, add a new item at the top level.
13716 ;; Otherwise, indent line like a regular one.
13717 (let ((itemp (org-in-item-p)))
13718 (if itemp
13719 (org-indent-line-to
13720 (let ((struct (save-excursion
13721 (goto-char itemp) (org-list-struct))))
13722 (org-list-get-ind (org-list-get-top-point struct) struct)))
13723 (org-indent-line)))
13724 (insert (org-list-bullet-string "-") (pop lines))
13725 (let ((ind (org-list-item-body-column (line-beginning-position))))
13726 (dolist (line lines)
13727 (insert "\n")
13728 (org-indent-line-to ind)
13729 (insert line)))
13730 (message "Note stored")
13731 (org-back-to-heading t)
13732 (org-cycle-hide-drawers 'children))
13733 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13734 ;; from within `org-add-log-note' because `buffer-undo-list'
13735 ;; is then modified outside of `org-with-remote-undo'.
13736 (when (eq this-command 'org-agenda-todo)
13737 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13738 ;; Don't add undo information when called from `org-agenda-todo'.
13739 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13740 (set-window-configuration org-log-note-window-configuration)
13741 (with-current-buffer (marker-buffer org-log-note-return-to)
13742 (goto-char org-log-note-return-to))
13743 (move-marker org-log-note-return-to nil)
13744 (when org-log-post-message (message "%s" org-log-post-message))))
13746 (defun org-remove-empty-drawer-at (pos)
13747 "Remove an empty drawer at position POS.
13748 POS may also be a marker."
13749 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13750 (org-with-wide-buffer
13751 (goto-char pos)
13752 (let ((drawer (org-element-at-point)))
13753 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13754 (not (org-element-property :contents-begin drawer)))
13755 (delete-region (org-element-property :begin drawer)
13756 (progn (goto-char (org-element-property :end drawer))
13757 (skip-chars-backward " \r\t\n")
13758 (forward-line)
13759 (point))))))))
13761 (defvar org-ts-type nil)
13762 (defun org-sparse-tree (&optional arg type)
13763 "Create a sparse tree, prompt for the details.
13764 This command can create sparse trees. You first need to select the type
13765 of match used to create the tree:
13767 t Show all TODO entries.
13768 T Show entries with a specific TODO keyword.
13769 m Show entries selected by a tags/property match.
13770 p Enter a property name and its value (both with completion on existing
13771 names/values) and show entries with that property.
13772 r Show entries matching a regular expression (`/' can be used as well).
13773 b Show deadlines and scheduled items before a date.
13774 a Show deadlines and scheduled items after a date.
13775 d Show deadlines due within `org-deadline-warning-days'.
13776 D Show deadlines and scheduled items between a date range."
13777 (interactive "P")
13778 (setq type (or type org-sparse-tree-default-date-type))
13779 (setq org-ts-type type)
13780 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13781 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13782 \[c]ycle through date types: %s"
13783 (cl-case type
13784 (all "all timestamps")
13785 (scheduled "only scheduled")
13786 (deadline "only deadline")
13787 (active "only active timestamps")
13788 (inactive "only inactive timestamps")
13789 (closed "with a closed time-stamp")
13790 (otherwise "scheduled/deadline")))
13791 (let ((answer (read-char-exclusive)))
13792 (cl-case answer
13794 (org-sparse-tree
13796 (cadr
13797 (memq type '(nil all scheduled deadline active inactive closed)))))
13798 (?d (call-interactively 'org-check-deadlines))
13799 (?b (call-interactively 'org-check-before-date))
13800 (?a (call-interactively 'org-check-after-date))
13801 (?D (call-interactively 'org-check-dates-range))
13802 (?t (call-interactively 'org-show-todo-tree))
13803 (?T (org-show-todo-tree '(4)))
13804 (?m (call-interactively 'org-match-sparse-tree))
13805 ((?p ?P)
13806 (let* ((kwd (completing-read
13807 "Property: " (mapcar #'list (org-buffer-property-keys))))
13808 (value (completing-read
13809 "Value: " (mapcar #'list (org-property-values kwd)))))
13810 (unless (string-match "\\`{.*}\\'" value)
13811 (setq value (concat "\"" value "\"")))
13812 (org-match-sparse-tree arg (concat kwd "=" value))))
13813 ((?r ?R ?/) (call-interactively 'org-occur))
13814 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13816 (defvar-local org-occur-highlights nil
13817 "List of overlays used for occur matches.")
13818 (defvar-local org-occur-parameters nil
13819 "Parameters of the active org-occur calls.
13820 This is a list, each call to org-occur pushes as cons cell,
13821 containing the regular expression and the callback, onto the list.
13822 The list can contain several entries if `org-occur' has been called
13823 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13824 will only contain one set of parameters. When the highlights are
13825 removed (for example with `C-c C-c', or with the next edit (depending
13826 on `org-remove-highlights-with-change'), this variable is emptied
13827 as well.")
13829 (defun org-occur (regexp &optional keep-previous callback)
13830 "Make a compact tree which shows all matches of REGEXP.
13831 The tree will show the lines where the regexp matches, and all higher
13832 headlines above the match. It will also show the heading after the match,
13833 to make sure editing the matching entry is easy.
13834 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13835 call to `org-occur' will be kept, to allow stacking of calls to this
13836 command.
13837 If CALLBACK is non-nil, it is a function which is called to confirm
13838 that the match should indeed be shown."
13839 (interactive "sRegexp: \nP")
13840 (when (equal regexp "")
13841 (user-error "Regexp cannot be empty"))
13842 (unless keep-previous
13843 (org-remove-occur-highlights nil nil t))
13844 (push (cons regexp callback) org-occur-parameters)
13845 (let ((cnt 0))
13846 (save-excursion
13847 (goto-char (point-min))
13848 (when (or (not keep-previous) ; do not want to keep
13849 (not org-occur-highlights)) ; no previous matches
13850 ;; hide everything
13851 (org-overview))
13852 (while (re-search-forward regexp nil t)
13853 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13854 (when (or (not callback)
13855 (save-match-data (funcall callback)))
13856 (setq cnt (1+ cnt))
13857 (when org-highlight-sparse-tree-matches
13858 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13859 (org-show-context 'occur-tree))))
13860 (when org-remove-highlights-with-change
13861 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13862 nil 'local))
13863 (unless org-sparse-tree-open-archived-trees
13864 (org-hide-archived-subtrees (point-min) (point-max)))
13865 (run-hooks 'org-occur-hook)
13866 (when (org-called-interactively-p 'interactive)
13867 (message "%d match(es) for regexp %s" cnt regexp))
13868 cnt))
13870 (defun org-occur-next-match (&optional n _reset)
13871 "Function for `next-error-function' to find sparse tree matches.
13872 N is the number of matches to move, when negative move backwards.
13873 This function always goes back to the starting point when no
13874 match is found."
13875 (let* ((limit (if (< n 0) (point-min) (point-max)))
13876 (search-func (if (< n 0)
13877 'previous-single-char-property-change
13878 'next-single-char-property-change))
13879 (n (abs n))
13880 (pos (point))
13882 (catch 'exit
13883 (while (setq p1 (funcall search-func (point) 'org-type))
13884 (when (equal p1 limit)
13885 (goto-char pos)
13886 (user-error "No more matches"))
13887 (when (equal (get-char-property p1 'org-type) 'org-occur)
13888 (setq n (1- n))
13889 (when (= n 0)
13890 (goto-char p1)
13891 (throw 'exit (point))))
13892 (goto-char p1))
13893 (goto-char p1)
13894 (user-error "No more matches"))))
13896 (defun org-show-context (&optional key)
13897 "Make sure point and context are visible.
13898 Optional argument KEY, when non-nil, is a symbol. See
13899 `org-show-context-detail' for allowed values and how much is to
13900 be shown."
13901 (org-show-set-visibility
13902 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13903 ((cdr (assq key org-show-context-detail)))
13904 (t (cdr (assq 'default org-show-context-detail))))))
13906 (defun org-show-set-visibility (detail)
13907 "Set visibility around point according to DETAIL.
13908 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13909 `tree', `canonical' or t. See `org-show-context-detail' for more
13910 information."
13911 (unless (org-before-first-heading-p)
13912 ;; Show current heading and possibly its entry, following headline
13913 ;; or all children.
13914 (if (and (org-at-heading-p) (not (eq detail 'local)))
13915 (org-flag-heading nil)
13916 (org-show-entry)
13917 (org-with-limited-levels
13918 (cl-case detail
13919 ((tree canonical t) (org-show-children))
13920 ((nil minimal ancestors))
13921 (t (save-excursion
13922 (outline-next-heading)
13923 (org-flag-heading nil))))))
13924 ;; Show all siblings.
13925 (when (eq detail 'lineage) (org-show-siblings))
13926 ;; Show ancestors, possibly with their children.
13927 (when (memq detail '(ancestors lineage tree canonical t))
13928 (save-excursion
13929 (while (org-up-heading-safe)
13930 (org-flag-heading nil)
13931 (when (memq detail '(canonical t)) (org-show-entry))
13932 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13934 (defvar org-reveal-start-hook nil
13935 "Hook run before revealing a location.")
13937 (defun org-reveal (&optional siblings)
13938 "Show current entry, hierarchy above it, and the following headline.
13940 This can be used to show a consistent set of context around
13941 locations exposed with `org-show-context'.
13943 With optional argument SIBLINGS, on each level of the hierarchy all
13944 siblings are shown. This repairs the tree structure to what it would
13945 look like when opened with hierarchical calls to `org-cycle'.
13947 With double optional argument \\[universal-argument] \\[universal-argument], \
13948 go to the parent and show the
13949 entire tree."
13950 (interactive "P")
13951 (run-hooks 'org-reveal-start-hook)
13952 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13953 ((equal siblings '(16))
13954 (save-excursion
13955 (when (org-up-heading-safe)
13956 (org-show-subtree)
13957 (run-hook-with-args 'org-cycle-hook 'subtree))))
13958 (t (org-show-set-visibility 'lineage))))
13960 (defun org-highlight-new-match (beg end)
13961 "Highlight from BEG to END and mark the highlight is an occur headline."
13962 (let ((ov (make-overlay beg end)))
13963 (overlay-put ov 'face 'secondary-selection)
13964 (overlay-put ov 'org-type 'org-occur)
13965 (push ov org-occur-highlights)))
13967 (defun org-remove-occur-highlights (&optional _beg _end noremove)
13968 "Remove the occur highlights from the buffer.
13969 BEG and END are ignored. If NOREMOVE is nil, remove this function
13970 from the `before-change-functions' in the current buffer."
13971 (interactive)
13972 (unless org-inhibit-highlight-removal
13973 (mapc #'delete-overlay org-occur-highlights)
13974 (setq org-occur-highlights nil)
13975 (setq org-occur-parameters nil)
13976 (unless noremove
13977 (remove-hook 'before-change-functions
13978 'org-remove-occur-highlights 'local))))
13980 ;;;; Priorities
13982 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
13983 "Regular expression matching the priority indicator.")
13985 (defvar org-remove-priority-next-time nil)
13987 (defun org-priority-up ()
13988 "Increase the priority of the current item."
13989 (interactive)
13990 (org-priority 'up))
13992 (defun org-priority-down ()
13993 "Decrease the priority of the current item."
13994 (interactive)
13995 (org-priority 'down))
13997 (defun org-priority (&optional action _show)
13998 "Change the priority of an item.
13999 ACTION can be `set', `up', `down', or a character."
14000 (interactive "P")
14001 (if (equal action '(4))
14002 (org-show-priority)
14003 (unless org-enable-priority-commands
14004 (user-error "Priority commands are disabled"))
14005 (setq action (or action 'set))
14006 (let (current new news have remove)
14007 (save-excursion
14008 (org-back-to-heading t)
14009 (when (looking-at org-priority-regexp)
14010 (setq current (string-to-char (match-string 2))
14011 have t))
14012 (cond
14013 ((eq action 'remove)
14014 (setq remove t new ?\ ))
14015 ((or (eq action 'set)
14016 (if (featurep 'xemacs) (characterp action) (integerp action)))
14017 (if (not (eq action 'set))
14018 (setq new action)
14019 (message "Priority %c-%c, SPC to remove: "
14020 org-highest-priority org-lowest-priority)
14021 (save-match-data
14022 (setq new (read-char-exclusive))))
14023 (when (and (= (upcase org-highest-priority) org-highest-priority)
14024 (= (upcase org-lowest-priority) org-lowest-priority))
14025 (setq new (upcase new)))
14026 (cond ((equal new ?\ ) (setq remove t))
14027 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14028 (user-error "Priority must be between `%c' and `%c'"
14029 org-highest-priority org-lowest-priority))))
14030 ((eq action 'up)
14031 (setq new (if have
14032 (1- current) ; normal cycling
14033 ;; last priority was empty
14034 (if (eq last-command this-command)
14035 org-lowest-priority ; wrap around empty to lowest
14036 ;; default
14037 (if org-priority-start-cycle-with-default
14038 org-default-priority
14039 (1- org-default-priority))))))
14040 ((eq action 'down)
14041 (setq new (if have
14042 (1+ current) ; normal cycling
14043 ;; last priority was empty
14044 (if (eq last-command this-command)
14045 org-highest-priority ; wrap around empty to highest
14046 ;; default
14047 (if org-priority-start-cycle-with-default
14048 org-default-priority
14049 (1+ org-default-priority))))))
14050 (t (user-error "Invalid action")))
14051 (when (or (< (upcase new) org-highest-priority)
14052 (> (upcase new) org-lowest-priority))
14053 (if (and (memq action '(up down))
14054 (not have) (not (eq last-command this-command)))
14055 ;; `new' is from default priority
14056 (error
14057 "The default can not be set, see `org-default-priority' why")
14058 ;; normal cycling: `new' is beyond highest/lowest priority
14059 ;; and is wrapped around to the empty priority
14060 (setq remove t)))
14061 (setq news (format "%c" new))
14062 (if have
14063 (if remove
14064 (replace-match "" t t nil 1)
14065 (replace-match news t t nil 2))
14066 (if remove
14067 (user-error "No priority cookie found in line")
14068 (let ((case-fold-search nil))
14069 (looking-at org-todo-line-regexp))
14070 (if (match-end 2)
14071 (progn
14072 (goto-char (match-end 2))
14073 (insert " [#" news "]"))
14074 (goto-char (match-beginning 3))
14075 (insert "[#" news "] "))))
14076 (org-set-tags nil 'align))
14077 (if remove
14078 (message "Priority removed")
14079 (message "Priority of current item set to %s" news)))))
14081 (defun org-show-priority ()
14082 "Show the priority of the current item.
14083 This priority is composed of the main priority given with the [#A] cookies,
14084 and by additional input from the age of a schedules or deadline entry."
14085 (interactive)
14086 (let ((pri (if (eq major-mode 'org-agenda-mode)
14087 (org-get-at-bol 'priority)
14088 (save-excursion
14089 (save-match-data
14090 (beginning-of-line)
14091 (and (looking-at org-heading-regexp)
14092 (org-get-priority (match-string 0))))))))
14093 (message "Priority is %d" (if pri pri -1000))))
14095 (defun org-get-priority (s)
14096 "Find priority cookie and return priority."
14097 (save-match-data
14098 (if (functionp org-get-priority-function)
14099 (funcall org-get-priority-function)
14100 (if (not (string-match org-priority-regexp s))
14101 (* 1000 (- org-lowest-priority org-default-priority))
14102 (* 1000 (- org-lowest-priority
14103 (string-to-char (match-string 2 s))))))))
14105 ;;;; Tags
14107 (defvar org-agenda-archives-mode)
14108 (defvar org-map-continue-from nil
14109 "Position from where mapping should continue.
14110 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14112 (defvar org-scanner-tags nil
14113 "The current tag list while the tags scanner is running.")
14115 (defvar org-trust-scanner-tags nil
14116 "Should `org-get-tags-at' use the tags for the scanner.
14117 This is for internal dynamical scoping only.
14118 When this is non-nil, the function `org-get-tags-at' will return the value
14119 of `org-scanner-tags' instead of building the list by itself. This
14120 can lead to large speed-ups when the tags scanner is used in a file with
14121 many entries, and when the list of tags is retrieved, for example to
14122 obtain a list of properties. Building the tags list for each entry in such
14123 a file becomes an N^2 operation - but with this variable set, it scales
14124 as N.")
14126 (defvar org--matcher-tags-todo-only nil)
14128 (defun org-scan-tags (action matcher todo-only &optional start-level)
14129 "Scan headline tags with inheritance and produce output ACTION.
14131 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14132 or `agenda' to produce an entry list for an agenda view. It can also be
14133 a Lisp form or a function that should be called at each matched headline, in
14134 this case the return value is a list of all return values from these calls.
14136 MATCHER is a function accepting three arguments, returning
14137 a non-nil value whenever a given set of tags qualifies a headline
14138 for inclusion. See `org-make-tags-matcher' for more information.
14139 As a special case, it can also be set to t (respectively nil) in
14140 order to match all (respectively none) headline.
14142 When TODO-ONLY is non-nil, only lines with a not-done TODO
14143 keyword are included in the output.
14145 START-LEVEL can be a string with asterisks, reducing the scope to
14146 headlines matching this string."
14147 (require 'org-agenda)
14148 (let* ((re (concat "^"
14149 (if start-level
14150 ;; Get the correct level to match
14151 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14152 org-outline-regexp)
14153 " *\\(\\<\\("
14154 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14155 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14156 (props (list 'face 'default
14157 'done-face 'org-agenda-done
14158 'undone-face 'default
14159 'mouse-face 'highlight
14160 'org-not-done-regexp org-not-done-regexp
14161 'org-todo-regexp org-todo-regexp
14162 'org-complex-heading-regexp org-complex-heading-regexp
14163 'help-echo
14164 (format "mouse-2 or RET jump to org file %s"
14165 (abbreviate-file-name
14166 (or (buffer-file-name (buffer-base-buffer))
14167 (buffer-name (buffer-base-buffer)))))))
14168 (org-map-continue-from nil)
14169 lspos tags tags-list
14170 (tags-alist (list (cons 0 org-file-tags)))
14171 (llast 0) rtn rtn1 level category i txt
14172 todo marker entry priority
14173 ts-date ts-date-type ts-date-pair)
14174 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14175 (setq action (list 'lambda nil action)))
14176 (save-excursion
14177 (goto-char (point-min))
14178 (when (eq action 'sparse-tree)
14179 (org-overview)
14180 (org-remove-occur-highlights))
14181 (while (let (case-fold-search)
14182 (re-search-forward re nil t))
14183 (setq org-map-continue-from nil)
14184 (catch :skip
14185 (setq todo
14186 ;; TODO: is the 1-2 difference a bug?
14187 (when (match-end 1) (org-match-string-no-properties 2))
14188 tags (when (match-end 4) (org-match-string-no-properties 4)))
14189 (goto-char (setq lspos (match-beginning 0)))
14190 (setq level (org-reduced-level (org-outline-level))
14191 category (org-get-category))
14192 (when (eq action 'agenda)
14193 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14194 ts-date (car ts-date-pair)
14195 ts-date-type (cdr ts-date-pair)))
14196 (setq i llast llast level)
14197 ;; remove tag lists from same and sublevels
14198 (while (>= i level)
14199 (when (setq entry (assoc i tags-alist))
14200 (setq tags-alist (delete entry tags-alist)))
14201 (setq i (1- i)))
14202 ;; add the next tags
14203 (when tags
14204 (setq tags (org-split-string tags ":")
14205 tags-alist
14206 (cons (cons level tags) tags-alist)))
14207 ;; compile tags for current headline
14208 (setq tags-list
14209 (if org-use-tag-inheritance
14210 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14211 tags)
14212 org-scanner-tags tags-list)
14213 (when org-use-tag-inheritance
14214 (setcdr (car tags-alist)
14215 (mapcar (lambda (x)
14216 (setq x (copy-sequence x))
14217 (org-add-prop-inherited x))
14218 (cdar tags-alist))))
14219 (when (and tags org-use-tag-inheritance
14220 (or (not (eq t org-use-tag-inheritance))
14221 org-tags-exclude-from-inheritance))
14222 ;; Selective inheritance, remove uninherited ones.
14223 (setcdr (car tags-alist)
14224 (org-remove-uninherited-tags (cdar tags-alist))))
14225 (when (and
14227 ;; eval matcher only when the todo condition is OK
14228 (and (or (not todo-only) (member todo org-not-done-keywords))
14229 (if (functionp matcher)
14230 (let ((case-fold-search t) (org-trust-scanner-tags t))
14231 (funcall matcher todo tags-list level))
14232 matcher))
14234 ;; Call the skipper, but return t if it does not
14235 ;; skip, so that the `and' form continues evaluating.
14236 (progn
14237 (unless (eq action 'sparse-tree) (org-agenda-skip))
14240 ;; Check if timestamps are deselecting this entry
14241 (or (not todo-only)
14242 (and (member todo org-not-done-keywords)
14243 (or (not org-agenda-tags-todo-honor-ignore-options)
14244 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14246 ;; select this headline
14247 (cond
14248 ((eq action 'sparse-tree)
14249 (and org-highlight-sparse-tree-matches
14250 (org-get-heading) (match-end 0)
14251 (org-highlight-new-match
14252 (match-beginning 1) (match-end 1)))
14253 (org-show-context 'tags-tree))
14254 ((eq action 'agenda)
14255 (setq txt (org-agenda-format-item
14257 (concat
14258 (if (eq org-tags-match-list-sublevels 'indented)
14259 (make-string (1- level) ?.) "")
14260 (org-get-heading))
14261 (make-string level ?\s)
14262 category
14263 tags-list)
14264 priority (org-get-priority txt))
14265 (goto-char lspos)
14266 (setq marker (org-agenda-new-marker))
14267 (org-add-props txt props
14268 'org-marker marker 'org-hd-marker marker 'org-category category
14269 'todo-state todo
14270 'ts-date ts-date
14271 'priority priority
14272 'type (concat "tagsmatch" ts-date-type))
14273 (push txt rtn))
14274 ((functionp action)
14275 (setq org-map-continue-from nil)
14276 (save-excursion
14277 (setq rtn1 (funcall action))
14278 (push rtn1 rtn)))
14279 (t (user-error "Invalid action")))
14281 ;; if we are to skip sublevels, jump to end of subtree
14282 (unless org-tags-match-list-sublevels
14283 (org-end-of-subtree t)
14284 (backward-char 1))))
14285 ;; Get the correct position from where to continue
14286 (if org-map-continue-from
14287 (goto-char org-map-continue-from)
14288 (and (= (point) lspos) (end-of-line 1)))))
14289 (when (and (eq action 'sparse-tree)
14290 (not org-sparse-tree-open-archived-trees))
14291 (org-hide-archived-subtrees (point-min) (point-max)))
14292 (nreverse rtn)))
14294 (defun org-remove-uninherited-tags (tags)
14295 "Remove all tags that are not inherited from the list TAGS."
14296 (cond
14297 ((eq org-use-tag-inheritance t)
14298 (if org-tags-exclude-from-inheritance
14299 (org-delete-all org-tags-exclude-from-inheritance tags)
14300 tags))
14301 ((not org-use-tag-inheritance) nil)
14302 ((stringp org-use-tag-inheritance)
14303 (delq nil (mapcar
14304 (lambda (x)
14305 (if (and (string-match org-use-tag-inheritance x)
14306 (not (member x org-tags-exclude-from-inheritance)))
14307 x nil))
14308 tags)))
14309 ((listp org-use-tag-inheritance)
14310 (delq nil (mapcar
14311 (lambda (x)
14312 (if (member x org-use-tag-inheritance) x nil))
14313 tags)))))
14315 (defun org-match-sparse-tree (&optional todo-only match)
14316 "Create a sparse tree according to tags string MATCH.
14317 MATCH can contain positive and negative selection of tags, like
14318 \"+WORK+URGENT-WITHBOSS\".
14319 If optional argument TODO-ONLY is non-nil, only select lines that are
14320 also TODO lines."
14321 (interactive "P")
14322 (org-agenda-prepare-buffers (list (current-buffer)))
14323 (let ((org--matcher-tags-todo-only todo-only))
14324 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14325 org--matcher-tags-todo-only)))
14327 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14329 (defvar org-cached-props nil)
14330 (defun org-cached-entry-get (pom property)
14331 (if (or (eq t org-use-property-inheritance)
14332 (and (stringp org-use-property-inheritance)
14333 (let ((case-fold-search t))
14334 (org-string-match-p org-use-property-inheritance property)))
14335 (and (listp org-use-property-inheritance)
14336 (member-ignore-case property org-use-property-inheritance)))
14337 ;; Caching is not possible, check it directly.
14338 (org-entry-get pom property 'inherit)
14339 ;; Get all properties, so we can do complicated checks easily.
14340 (cdr (assoc-string property
14341 (or org-cached-props
14342 (setq org-cached-props (org-entry-properties pom)))
14343 t))))
14345 (defun org-global-tags-completion-table (&optional files)
14346 "Return the list of all tags in all agenda buffer/files.
14347 Optional FILES argument is a list of files which can be used
14348 instead of the agenda files."
14349 (save-excursion
14350 (org-uniquify
14351 (delq nil
14352 (apply 'append
14353 (mapcar
14354 (lambda (file)
14355 (set-buffer (find-file-noselect file))
14356 (append (org-get-buffer-tags)
14357 (mapcar (lambda (x) (if (stringp (car-safe x))
14358 (list (car-safe x)) nil))
14359 org-tag-alist)))
14360 (if (and files (car files))
14361 files
14362 (org-agenda-files))))))))
14364 (defun org-make-tags-matcher (match)
14365 "Create the TAGS/TODO matcher form for the selection string MATCH.
14367 Returns a cons of the selection string MATCH and a function
14368 implementing the matcher.
14370 The matcher is to be called at an Org entry, with point on the
14371 headline, and returns non-nil if the entry matches the selection
14372 string MATCH. It must be called with three arguments: the TODO
14373 keyword at the entry (or nil if none), the list of all tags at
14374 the entry including inherited ones and the reduced level of the
14375 headline. Additionally, the category of the entry, if any, must
14376 be specified as the text property `org-category' on the headline.
14378 This function sets the variable `org--matcher-tags-todo-only' to
14379 a non-nil value if the matcher restricts matching to TODO
14380 entries, otherwise it is not touched.
14382 See also `org-scan-tags'."
14383 (unless match
14384 ;; Get a new match request, with completion against the global
14385 ;; tags table and the local tags in current buffer.
14386 (let ((org-last-tags-completion-table
14387 (org-uniquify
14388 (delq nil (append (org-get-buffer-tags)
14389 (org-global-tags-completion-table))))))
14390 (setq match
14391 (completing-read
14392 "Match: "
14393 'org-tags-completion-function nil nil nil 'org-tags-history))))
14395 (let ((match0 match)
14396 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14397 (start 0)
14398 tagsmatch todomatch tagsmatcher todomatcher)
14400 ;; Expand group tags.
14401 (setq match (org-tags-expand match))
14403 ;; Check if there is a TODO part of this match, which would be the
14404 ;; part after a "/". To make sure that this slash is not part of
14405 ;; a property value to be matched against, we also check that
14406 ;; there is no / after that slash. First, find the last slash.
14407 (let ((s 0))
14408 (while (string-match "/+" match s)
14409 (setq start (match-beginning 0))
14410 (setq s (match-end 0))))
14411 (if (and (string-match "/+" match start)
14412 (not (string-match-p "\"" match start)))
14413 ;; Match contains also a TODO-matching request.
14414 (progn
14415 (setq tagsmatch (substring match 0 (match-beginning 0)))
14416 (setq todomatch (substring match (match-end 0)))
14417 (when (string-match "\\`!" todomatch)
14418 (setq org--matcher-tags-todo-only t)
14419 (setq todomatch (substring todomatch 1)))
14420 (when (string-match "\\`\\s-*\\'" todomatch)
14421 (setq todomatch nil)))
14422 ;; Only matching tags.
14423 (setq tagsmatch match)
14424 (setq todomatch nil))
14426 ;; Make the tags matcher.
14427 (when (org-string-nw-p tagsmatch)
14428 (let ((orlist nil)
14429 (orterms (org-split-string tagsmatch "|"))
14430 term)
14431 (while (setq term (pop orterms))
14432 (while (and (equal (substring term -1) "\\") orterms)
14433 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14434 (while (string-match re term)
14435 (let* ((rest (substring term (match-end 0)))
14436 (minus (and (match-end 1)
14437 (equal (match-string 1 term) "-")))
14438 (tag (save-match-data
14439 (replace-regexp-in-string
14440 "\\\\-" "-" (match-string 2 term))))
14441 (regexp (eq (string-to-char tag) ?{))
14442 (levelp (match-end 4))
14443 (propp (match-end 5))
14445 (cond
14446 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14447 (levelp
14448 `(,(org-op-to-function (match-string 3 term))
14449 level
14450 ,(string-to-number (match-string 4 term))))
14451 (propp
14452 (let* ((gv (pcase (upcase (match-string 5 term))
14453 ("CATEGORY"
14454 '(get-text-property (point) 'org-category))
14455 ("TODO" 'todo)
14456 (p `(org-cached-entry-get nil ,p))))
14457 (pv (match-string 7 term))
14458 (regexp (eq (string-to-char pv) ?{))
14459 (strp (eq (string-to-char pv) ?\"))
14460 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14461 (po (org-op-to-function (match-string 6 term)
14462 (if timep 'time strp))))
14463 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14464 (when timep (setq pv (org-matcher-time pv)))
14465 (cond ((and regexp (eq po 'org<>))
14466 `(not (string-match ,pv (or ,gv ""))))
14467 (regexp `(string-match ,pv (or ,gv "")))
14468 (strp `(,po (or ,gv "") ,pv))
14470 `(,po
14471 (string-to-number (or ,gv ""))
14472 ,(string-to-number pv))))))
14473 (t `(member ,tag tags-list)))))
14474 (push (if minus `(not ,mm) mm) tagsmatcher)
14475 (setq term rest)))
14476 (push `(and ,@tagsmatcher) orlist)
14477 (setq tagsmatcher nil))
14478 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14480 ;; Make the TODO matcher.
14481 (when (org-string-nw-p todomatch)
14482 (let ((orlist nil))
14483 (dolist (term (org-split-string todomatch "|"))
14484 (while (string-match re term)
14485 (let* ((minus (and (match-end 1)
14486 (equal (match-string 1 term) "-")))
14487 (kwd (match-string 2 term))
14488 (regexp (eq (string-to-char kwd) ?{))
14489 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14490 `(equal todo ,kwd))))
14491 (push (if minus `(not ,mm) mm) todomatcher))
14492 (setq term (substring term (match-end 0))))
14493 (push (if (> (length todomatcher) 1)
14494 (cons 'and todomatcher)
14495 (car todomatcher))
14496 orlist)
14497 (setq todomatcher nil))
14498 (setq todomatcher (cons 'or orlist))))
14500 ;; Return the string and function of the matcher. If no
14501 ;; tags-specific or todo-specific matcher exists, match
14502 ;; everything.
14503 (let ((matcher (if (and tagsmatcher todomatcher)
14504 `(and ,tagsmatcher ,todomatcher)
14505 (or tagsmatcher todomatcher t))))
14506 (when org--matcher-tags-todo-only
14507 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14508 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14510 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14511 "Expand group tags in MATCH.
14513 This replaces every group tag in MATCH with a regexp tag search.
14514 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14515 will be replaced like this:
14517 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14518 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14519 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14521 Replacing by a regexp preserves the structure of the match.
14522 E.g., this expansion
14524 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14526 will match anything tagged with \"Lab\" and \"Home\", or tagged
14527 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14529 A group tag in MATCH can contain regular expressions of its own.
14530 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14531 will be replaced like this:
14533 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14535 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14536 assumed to be a single group tag, and the function will return
14537 the list of tags in this group.
14539 When DOWNCASE is non-nil, expand downcased TAGS."
14540 (if org-group-tags
14541 (let* ((case-fold-search t)
14542 (stable org-mode-syntax-table)
14543 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14544 (taggroups (if downcased
14545 (mapcar (lambda (tg) (mapcar #'downcase tg))
14546 taggroups)
14547 taggroups))
14548 (taggroups-keys (mapcar #'car taggroups))
14549 (return-match (if downcased (downcase match) match))
14550 (count 0)
14551 (work-already-expanded tags-already-expanded)
14552 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14553 ;; @ and _ are allowed as word-components in tags.
14554 (modify-syntax-entry ?@ "w" stable)
14555 (modify-syntax-entry ?_ "w" stable)
14556 ;; Temporarily replace regexp-expressions in the match-expression.
14557 (while (string-match "{.+?}" return-match)
14558 (cl-incf count)
14559 (push (match-string 0 return-match) regexps-in-match)
14560 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14561 (while (and taggroups-keys
14562 (with-syntax-table stable
14563 (string-match
14564 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14565 (regexp-opt taggroups-keys) "\\>\\)")
14566 return-match)))
14567 (let* ((dir (match-string 1 return-match))
14568 (tag (match-string 2 return-match))
14569 (tag (if downcased (downcase tag) tag)))
14570 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14571 (member tag work-already-expanded))
14572 (setq tags-in-group (assoc tag taggroups))
14573 (push tag work-already-expanded)
14574 ;; Recursively expand each tag in the group, if the tag hasn't
14575 ;; already been expanded. Restore the match-data after all recursive calls.
14576 (save-match-data
14577 (let (tags-expanded)
14578 (dolist (x (cdr tags-in-group))
14579 (if (and (member x taggroups-keys)
14580 (not (member x work-already-expanded)))
14581 (setq tags-expanded
14582 (delete-dups
14583 (append
14584 (org-tags-expand x t downcased
14585 work-already-expanded)
14586 tags-expanded)))
14587 (setq tags-expanded
14588 (append (list x) tags-expanded)))
14589 (setq work-already-expanded
14590 (delete-dups
14591 (append tags-expanded
14592 work-already-expanded))))
14593 (setq tags-in-group
14594 (delete-dups (cons (car tags-in-group)
14595 tags-expanded)))))
14596 ;; Filter tag-regexps from tags.
14597 (setq regexp-in-group-escaped
14598 (delq nil (mapcar (lambda (x)
14599 (if (stringp x)
14600 (and (equal "{" (substring x 0 1))
14601 (equal "}" (substring x -1))
14604 tags-in-group))
14605 regexp-in-group
14606 (mapcar (lambda (x)
14607 (substring x 1 -1))
14608 regexp-in-group-escaped)
14609 tags-in-group
14610 (delq nil (mapcar (lambda (x)
14611 (if (stringp x)
14612 (and (not (equal "{" (substring x 0 1)))
14613 (not (equal "}" (substring x -1)))
14616 tags-in-group)))
14617 ;; If single-as-list, do no more in the while-loop.
14618 (if (not single-as-list)
14619 (progn
14620 (when regexp-in-group
14621 (setq regexp-in-group
14622 (concat "\\|"
14623 (mapconcat 'identity regexp-in-group
14624 "\\|"))))
14625 (setq tags-in-group
14626 (concat dir
14627 "{\\<"
14628 (regexp-opt tags-in-group)
14629 "\\>"
14630 regexp-in-group
14631 "}"))
14632 (when (stringp tags-in-group)
14633 (org-add-props tags-in-group '(grouptag t)))
14634 (setq return-match
14635 (replace-match tags-in-group t t return-match)))
14636 (setq tags-in-group
14637 (append regexp-in-group-escaped tags-in-group))))
14638 (setq taggroups-keys (delete tag taggroups-keys))))
14639 ;; Add the regular expressions back into the match-expression again.
14640 (while regexps-in-match
14641 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14642 (pop regexps-in-match)
14643 return-match t t))
14644 (cl-decf count))
14645 (if single-as-list
14646 (if tags-in-group tags-in-group (list return-match))
14647 return-match))
14648 (if single-as-list
14649 (list (if downcased (downcase match) match))
14650 match)))
14652 (defun org-op-to-function (op &optional stringp)
14653 "Turn an operator into the appropriate function."
14654 (setq op
14655 (cond
14656 ((equal op "<" ) '(< string< org-time<))
14657 ((equal op ">" ) '(> org-string> org-time>))
14658 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14659 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14660 ((member op '("=" "==")) '(= string= org-time=))
14661 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14662 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14664 (defun org<> (a b) (not (= a b)))
14665 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14666 (defun org-string>= (a b) (not (string< a b)))
14667 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14668 (defun org-string<> (a b) (not (string= a b)))
14669 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14670 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14671 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14672 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14673 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14674 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14675 (defun org-2ft (s)
14676 "Convert S to a floating point time.
14677 If S is already a number, just return it. If it is a string, parse
14678 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14679 (cond
14680 ((numberp s) s)
14681 ((stringp s)
14682 (condition-case nil
14683 (float-time (apply 'encode-time (org-parse-time-string s)))
14684 (error 0.)))
14685 (t 0.)))
14687 (defun org-time-today ()
14688 "Time in seconds today at 0:00.
14689 Returns the float number of seconds since the beginning of the
14690 epoch to the beginning of today (00:00)."
14691 (float-time (apply 'encode-time
14692 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14694 (defun org-matcher-time (s)
14695 "Interpret a time comparison value."
14696 (save-match-data
14697 (cond
14698 ((string= s "<now>") (float-time))
14699 ((string= s "<today>") (org-time-today))
14700 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14701 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14702 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14703 (+ (org-time-today)
14704 (* (string-to-number (match-string 1 s))
14705 (cdr (assoc (match-string 2 s)
14706 '(("d" . 86400.0) ("w" . 604800.0)
14707 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14708 (t (org-2ft s)))))
14710 (defun org-match-any-p (re list)
14711 "Does re match any element of list?"
14712 (setq list (mapcar (lambda (x) (string-match re x)) list))
14713 (delq nil list))
14715 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14716 (defvar org-tags-overlay (make-overlay 1 1))
14717 (org-detach-overlay org-tags-overlay)
14719 (defun org-get-local-tags-at (&optional pos)
14720 "Get a list of tags defined in the current headline."
14721 (org-get-tags-at pos 'local))
14723 (defun org-get-local-tags ()
14724 "Get a list of tags defined in the current headline."
14725 (org-get-tags-at nil 'local))
14727 (defun org-get-tags-at (&optional pos local)
14728 "Get a list of all headline tags applicable at POS.
14729 POS defaults to point. If tags are inherited, the list contains
14730 the targets in the same sequence as the headlines appear, i.e.
14731 the tags of the current headline come last.
14732 When LOCAL is non-nil, only return tags from the current headline,
14733 ignore inherited ones."
14734 (interactive)
14735 (if (and org-trust-scanner-tags
14736 (or (not pos) (equal pos (point)))
14737 (not local))
14738 org-scanner-tags
14739 (let (tags ltags lastpos parent)
14740 (save-excursion
14741 (save-restriction
14742 (widen)
14743 (goto-char (or pos (point)))
14744 (save-match-data
14745 (catch 'done
14746 (condition-case nil
14747 (progn
14748 (org-back-to-heading t)
14749 (while (not (equal lastpos (point)))
14750 (setq lastpos (point))
14751 (when (looking-at
14752 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14753 (setq ltags (org-split-string
14754 (org-match-string-no-properties 1) ":"))
14755 (when parent
14756 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14757 (setq tags (append
14758 (if parent
14759 (org-remove-uninherited-tags ltags)
14760 ltags)
14761 tags)))
14762 (or org-use-tag-inheritance (throw 'done t))
14763 (when local (throw 'done t))
14764 (or (org-up-heading-safe) (error nil))
14765 (setq parent t)))
14766 (error nil)))))
14767 (if local
14768 tags
14769 (reverse (delete-dups
14770 (reverse (append
14771 (org-remove-uninherited-tags
14772 org-file-tags)
14773 tags)))))))))
14775 (defun org-add-prop-inherited (s)
14776 (add-text-properties 0 (length s) '(inherited t) s)
14779 (defun org-toggle-tag (tag &optional onoff)
14780 "Toggle the tag TAG for the current line.
14781 If ONOFF is `on' or `off', don't toggle but set to this state."
14782 (let (res current)
14783 (save-excursion
14784 (org-back-to-heading t)
14785 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14786 (point-at-eol) t)
14787 (progn
14788 (setq current (match-string 1))
14789 (replace-match ""))
14790 (setq current ""))
14791 (setq current (nreverse (org-split-string current ":")))
14792 (cond
14793 ((eq onoff 'on)
14794 (setq res t)
14795 (or (member tag current) (push tag current)))
14796 ((eq onoff 'off)
14797 (or (not (member tag current)) (setq current (delete tag current))))
14798 (t (if (member tag current)
14799 (setq current (delete tag current))
14800 (setq res t)
14801 (push tag current))))
14802 (end-of-line 1)
14803 (if current
14804 (progn
14805 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14806 (org-set-tags nil t))
14807 (delete-horizontal-space))
14808 (run-hooks 'org-after-tags-change-hook))
14809 res))
14811 (defun org-align-tags-here (to-col)
14812 ;; Assumes that this is a headline
14813 "Align tags on the current headline to TO-COL."
14814 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14815 (beginning-of-line 1)
14816 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14817 (< pos (match-beginning 2)))
14818 (progn
14819 (setq tags-l (- (match-end 2) (match-beginning 2)))
14820 (goto-char (match-beginning 1))
14821 (insert " ")
14822 (delete-region (point) (1+ (match-beginning 2)))
14823 (setq ncol (max (current-column)
14824 (1+ col)
14825 (if (> to-col 0)
14826 to-col
14827 (- (abs to-col) tags-l))))
14828 (setq p (point))
14829 (insert (make-string (- ncol (current-column)) ?\ ))
14830 (setq ncol (current-column))
14831 (when indent-tabs-mode (tabify p (point-at-eol)))
14832 (org-move-to-column (min ncol col)))
14833 (goto-char pos))))
14835 (defun org-set-tags-command (&optional arg just-align)
14836 "Call the set-tags command for the current entry."
14837 (interactive "P")
14838 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14839 (org-set-tags arg just-align)
14840 (save-excursion
14841 (unless (and (org-region-active-p)
14842 org-loop-over-headlines-in-active-region)
14843 (org-back-to-heading t))
14844 (org-set-tags arg just-align))))
14846 (defun org-set-tags-to (data)
14847 "Set the tags of the current entry to DATA, replacing the current tags.
14848 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14849 If DATA is nil or the empty string, any tags will be removed."
14850 (interactive "sTags: ")
14851 (setq data
14852 (cond
14853 ((eq data nil) "")
14854 ((equal data "") "")
14855 ((stringp data)
14856 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14857 ":"))
14858 ((listp data)
14859 (concat ":" (mapconcat 'identity data ":") ":"))))
14860 (when data
14861 (save-excursion
14862 (org-back-to-heading t)
14863 (when (looking-at org-complex-heading-regexp)
14864 (if (match-end 5)
14865 (progn
14866 (goto-char (match-beginning 5))
14867 (insert data)
14868 (delete-region (point) (point-at-eol))
14869 (org-set-tags nil 'align))
14870 (goto-char (point-at-eol))
14871 (insert " " data)
14872 (org-set-tags nil 'align)))
14873 (beginning-of-line 1)
14874 (when (looking-at ".*?\\([ \t]+\\)$")
14875 (delete-region (match-beginning 1) (match-end 1))))))
14877 (defun org-align-all-tags ()
14878 "Align the tags in all headings."
14879 (interactive)
14880 (save-excursion
14881 (or (ignore-errors (org-back-to-heading t))
14882 (outline-next-heading))
14883 (if (org-at-heading-p)
14884 (org-set-tags t)
14885 (message "No headings"))))
14887 (defvar org-indent-indentation-per-level)
14888 (defun org-set-tags (&optional arg just-align)
14889 "Set the tags for the current headline.
14890 With prefix ARG, realign all tags in headings in the current buffer.
14891 When JUST-ALIGN is non-nil, only align tags."
14892 (interactive "P")
14893 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14894 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14895 'region-start-level
14896 'region))
14897 org-loop-over-headlines-in-active-region)
14898 (org-map-entries
14899 ;; We don't use ARG and JUST-ALIGN here because these args
14900 ;; are not useful when looping over headlines.
14901 #'org-set-tags
14902 org-loop-over-headlines-in-active-region
14904 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14905 (let ((org-setting-tags t))
14906 (if arg
14907 (save-excursion
14908 (goto-char (point-min))
14909 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14910 (while (re-search-forward org-outline-regexp-bol nil t)
14911 (org-set-tags nil t)
14912 (end-of-line)))
14913 (message "All tags realigned to column %d" org-tags-column))
14914 (let* ((current (org-get-tags-string))
14915 (col (current-column))
14916 (tags
14917 (if just-align current
14918 ;; Get a new set of tags from the user.
14919 (save-excursion
14920 (let* ((table
14921 (setq
14922 org-last-tags-completion-table
14923 (append
14924 org-tag-persistent-alist
14925 (or org-tag-alist (org-get-buffer-tags))
14926 (and
14927 org-complete-tags-always-offer-all-agenda-tags
14928 (org-global-tags-completion-table
14929 (org-agenda-files))))))
14930 (current-tags (org-split-string current ":"))
14931 (inherited-tags
14932 (nreverse (nthcdr (length current-tags)
14933 (nreverse (org-get-tags-at))))))
14934 (replace-regexp-in-string
14935 "\\([-+&]+\\|,\\)"
14937 (if (or (eq t org-use-fast-tag-selection)
14938 (and org-use-fast-tag-selection
14939 (delq nil (mapcar #'cdr table))))
14940 (org-fast-tag-selection
14941 current-tags inherited-tags table
14942 (and org-fast-tag-selection-include-todo
14943 org-todo-key-alist))
14944 (let ((org-add-colon-after-tag-completion
14945 (< 1 (length table))))
14946 (org-trim
14947 (completing-read
14948 "Tags: "
14949 #'org-tags-completion-function
14950 nil nil current 'org-tags-history))))))))))
14952 (when org-tags-sort-function
14953 (setq tags
14954 (mapconcat
14955 #'identity
14956 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
14957 org-tags-sort-function)
14958 ":")))
14960 (if (not (org-string-nw-p tags)) (setq tags "")
14961 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
14962 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
14964 ;; Insert new tags at the correct column
14965 (beginning-of-line)
14966 (let ((level (if (looking-at org-outline-regexp)
14967 (- (match-end 0) (point) 1)
14968 1)))
14969 (cond
14970 ((and (equal current "") (equal tags "")))
14971 ((re-search-forward
14972 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
14973 (line-end-position)
14975 (if (equal tags "") (replace-match "" t t)
14976 (goto-char (match-beginning 0))
14977 (let* ((c0 (current-column))
14978 ;; Compute offset for the case of org-indent-mode
14979 ;; active.
14980 (di (if (org-bound-and-true-p org-indent-mode)
14981 (* (1- org-indent-indentation-per-level)
14982 (1- level))
14984 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
14985 (tc (+ org-tags-column
14986 (if (> org-tags-column 0) (- di) di)))
14987 (c1 (max (1+ c0)
14988 (if (> tc 0) tc
14989 (- (- tc) (string-width tags)))))
14990 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
14991 (replace-match rpl t t)
14992 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
14993 (tabify p0 (point))))))
14994 (t (error "Tags alignment failed"))))
14995 (org-move-to-column col))
14996 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
14998 (defun org-change-tag-in-region (beg end tag off)
14999 "Add or remove TAG for each entry in the region.
15000 This works in the agenda, and also in an org-mode buffer."
15001 (interactive
15002 (list (region-beginning) (region-end)
15003 (let ((org-last-tags-completion-table
15004 (if (derived-mode-p 'org-mode)
15005 (org-uniquify
15006 (delq nil (append (org-get-buffer-tags)
15007 (org-global-tags-completion-table))))
15008 (org-global-tags-completion-table))))
15009 (completing-read
15010 "Tag: " 'org-tags-completion-function nil nil nil
15011 'org-tags-history))
15012 (progn
15013 (message "[s]et or [r]emove? ")
15014 (equal (read-char-exclusive) ?r))))
15015 (when (fboundp 'deactivate-mark) (deactivate-mark))
15016 (let ((agendap (equal major-mode 'org-agenda-mode))
15017 l1 l2 m buf pos newhead (cnt 0))
15018 (goto-char end)
15019 (setq l2 (1- (org-current-line)))
15020 (goto-char beg)
15021 (setq l1 (org-current-line))
15022 (cl-loop for l from l1 to l2 do
15023 (org-goto-line l)
15024 (setq m (get-text-property (point) 'org-hd-marker))
15025 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15026 (and agendap m))
15027 (setq buf (if agendap (marker-buffer m) (current-buffer))
15028 pos (if agendap m (point)))
15029 (with-current-buffer buf
15030 (save-excursion
15031 (save-restriction
15032 (goto-char pos)
15033 (setq cnt (1+ cnt))
15034 (org-toggle-tag tag (if off 'off 'on))
15035 (setq newhead (org-get-heading)))))
15036 (and agendap (org-agenda-change-all-lines newhead m))))
15037 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15039 (defun org-tags-completion-function (string _predicate &optional flag)
15040 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15041 (confirm (lambda (x) (stringp (car x)))))
15042 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15043 (setq s1 (match-string 1 string)
15044 s2 (match-string 2 string))
15045 (setq s1 "" s2 string))
15046 (cond
15047 ((eq flag nil)
15048 ;; try completion
15049 (setq rtn (try-completion s2 ctable confirm))
15050 (when (stringp rtn)
15051 (setq rtn
15052 (concat s1 s2 (substring rtn (length s2))
15053 (if (and org-add-colon-after-tag-completion
15054 (assoc rtn ctable))
15055 ":" ""))))
15056 rtn)
15057 ((eq flag t)
15058 ;; all-completions
15059 (all-completions s2 ctable confirm))
15060 ((eq flag 'lambda)
15061 ;; exact match?
15062 (assoc s2 ctable)))))
15064 (defun org-fast-tag-insert (kwd tags face &optional end)
15065 "Insert KDW, and the TAGS, the latter with face FACE.
15066 Also insert END."
15067 (insert (format "%-12s" (concat kwd ":"))
15068 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15069 (or end "")))
15071 (defun org-fast-tag-show-exit (flag)
15072 (save-excursion
15073 (org-goto-line 3)
15074 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15075 (replace-match ""))
15076 (when flag
15077 (end-of-line 1)
15078 (org-move-to-column (- (window-width) 19) t)
15079 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15081 (defun org-set-current-tags-overlay (current prefix)
15082 "Add an overlay to CURRENT tag with PREFIX."
15083 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15084 (if (featurep 'xemacs)
15085 (org-overlay-display org-tags-overlay (concat prefix s)
15086 'secondary-selection)
15087 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15088 (org-overlay-display org-tags-overlay (concat prefix s)))))
15090 (defvar org-last-tag-selection-key nil)
15091 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15092 "Fast tag selection with single keys.
15093 CURRENT is the current list of tags in the headline, INHERITED is the
15094 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15095 possibly with grouping information. TODO-TABLE is a similar table with
15096 TODO keywords, should these have keys assigned to them.
15097 If the keys are nil, a-z are automatically assigned.
15098 Returns the new tags string, or nil to not change the current settings."
15099 (let* ((fulltable (append table todo-table))
15100 (maxlen (apply 'max (mapcar
15101 (lambda (x)
15102 (if (stringp (car x)) (string-width (car x)) 0))
15103 fulltable)))
15104 (buf (current-buffer))
15105 (expert (eq org-fast-tag-selection-single-key 'expert))
15106 (buffer-tags nil)
15107 (fwidth (+ maxlen 3 1 3))
15108 (ncol (/ (- (window-width) 4) fwidth))
15109 (i-face 'org-done)
15110 (c-face 'org-todo)
15111 tg cnt e c char c1 c2 ntable tbl rtn
15112 ov-start ov-end ov-prefix
15113 (exit-after-next org-fast-tag-selection-single-key)
15114 (done-keywords org-done-keywords)
15115 groups ingroup intaggroup)
15116 (save-excursion
15117 (beginning-of-line 1)
15118 (if (looking-at
15119 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15120 (setq ov-start (match-beginning 1)
15121 ov-end (match-end 1)
15122 ov-prefix "")
15123 (setq ov-start (1- (point-at-eol))
15124 ov-end (1+ ov-start))
15125 (skip-chars-forward "^\n\r")
15126 (setq ov-prefix
15127 (concat
15128 (buffer-substring (1- (point)) (point))
15129 (if (> (current-column) org-tags-column)
15131 (make-string (- org-tags-column (current-column)) ?\ ))))))
15132 (move-overlay org-tags-overlay ov-start ov-end)
15133 (save-window-excursion
15134 (if expert
15135 (set-buffer (get-buffer-create " *Org tags*"))
15136 (delete-other-windows)
15137 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15138 (org-switch-to-buffer-other-window " *Org tags*"))
15139 (erase-buffer)
15140 (setq-local org-done-keywords done-keywords)
15141 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15142 (org-fast-tag-insert "Current" current c-face "\n\n")
15143 (org-fast-tag-show-exit exit-after-next)
15144 (org-set-current-tags-overlay current ov-prefix)
15145 (setq tbl fulltable char ?a cnt 0)
15146 (while (setq e (pop tbl))
15147 (cond
15148 ((eq (car e) :startgroup)
15149 (push '() groups) (setq ingroup t)
15150 (unless (zerop cnt)
15151 (setq cnt 0)
15152 (insert "\n"))
15153 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15154 ((eq (car e) :endgroup)
15155 (setq ingroup nil cnt 0)
15156 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15157 ((eq (car e) :startgrouptag)
15158 (setq intaggroup t)
15159 (unless (zerop cnt)
15160 (setq cnt 0)
15161 (insert "\n"))
15162 (insert "[ "))
15163 ((eq (car e) :endgrouptag)
15164 (setq intaggroup nil cnt 0)
15165 (insert "]\n"))
15166 ((equal e '(:newline))
15167 (unless (zerop cnt)
15168 (setq cnt 0)
15169 (insert "\n")
15170 (setq e (car tbl))
15171 (while (equal (car tbl) '(:newline))
15172 (insert "\n")
15173 (setq tbl (cdr tbl)))))
15174 ((equal e '(:grouptags)) (insert " : "))
15176 (setq tg (copy-sequence (car e)) c2 nil)
15177 (if (cdr e)
15178 (setq c (cdr e))
15179 ;; automatically assign a character.
15180 (setq c1 (string-to-char
15181 (downcase (substring
15182 tg (if (= (string-to-char tg) ?@) 1 0)))))
15183 (if (or (rassoc c1 ntable) (rassoc c1 table))
15184 (while (or (rassoc char ntable) (rassoc char table))
15185 (setq char (1+ char)))
15186 (setq c2 c1))
15187 (setq c (or c2 char)))
15188 (when ingroup (push tg (car groups)))
15189 (setq tg (org-add-props tg nil 'face
15190 (cond
15191 ((not (assoc tg table))
15192 (org-get-todo-face tg))
15193 ((member tg current) c-face)
15194 ((member tg inherited) i-face))))
15195 (when (equal (caar tbl) :grouptags)
15196 (org-add-props tg nil 'face 'org-tag-group))
15197 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15198 (insert "[" c "] " tg (make-string
15199 (- fwidth 4 (length tg)) ?\ ))
15200 (push (cons tg c) ntable)
15201 (when (= (cl-incf cnt) ncol)
15202 (insert "\n")
15203 (when (or ingroup intaggroup) (insert " "))
15204 (setq cnt 0)))))
15205 (setq ntable (nreverse ntable))
15206 (insert "\n")
15207 (goto-char (point-min))
15208 (unless expert (org-fit-window-to-buffer))
15209 (setq rtn
15210 (catch 'exit
15211 (while t
15212 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15213 (if (not groups) "no " "")
15214 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15215 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15216 (setq org-last-tag-selection-key c)
15217 (cond
15218 ((= c ?\r) (throw 'exit t))
15219 ((= c ?!)
15220 (setq groups (not groups))
15221 (goto-char (point-min))
15222 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15223 ((= c ?\C-c)
15224 (if (not expert)
15225 (org-fast-tag-show-exit
15226 (setq exit-after-next (not exit-after-next)))
15227 (setq expert nil)
15228 (delete-other-windows)
15229 (set-window-buffer (split-window-vertically) " *Org tags*")
15230 (org-switch-to-buffer-other-window " *Org tags*")
15231 (org-fit-window-to-buffer)))
15232 ((or (= c ?\C-g)
15233 (and (= c ?q) (not (rassoc c ntable))))
15234 (org-detach-overlay org-tags-overlay)
15235 (setq quit-flag t))
15236 ((= c ?\ )
15237 (setq current nil)
15238 (when exit-after-next (setq exit-after-next 'now)))
15239 ((= c ?\t)
15240 (condition-case nil
15241 (setq tg (completing-read
15242 "Tag: "
15243 (or buffer-tags
15244 (with-current-buffer buf
15245 (setq buffer-tags
15246 (org-get-buffer-tags))))))
15247 (quit (setq tg "")))
15248 (when (string-match "\\S-" tg)
15249 (cl-pushnew (list tg) buffer-tags :test #'equal)
15250 (if (member tg current)
15251 (setq current (delete tg current))
15252 (push tg current)))
15253 (when exit-after-next (setq exit-after-next 'now)))
15254 ((setq e (rassoc c todo-table) tg (car e))
15255 (with-current-buffer buf
15256 (save-excursion (org-todo tg)))
15257 (when exit-after-next (setq exit-after-next 'now)))
15258 ((setq e (rassoc c ntable) tg (car e))
15259 (if (member tg current)
15260 (setq current (delete tg current))
15261 (cl-loop for g in groups do
15262 (when (member tg g)
15263 (dolist (x g) (setq current (delete x current)))))
15264 (push tg current))
15265 (when exit-after-next (setq exit-after-next 'now))))
15267 ;; Create a sorted list
15268 (setq current
15269 (sort current
15270 (lambda (a b)
15271 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15272 (when (eq exit-after-next 'now) (throw 'exit t))
15273 (goto-char (point-min))
15274 (beginning-of-line 2)
15275 (delete-region (point) (point-at-eol))
15276 (org-fast-tag-insert "Current" current c-face)
15277 (org-set-current-tags-overlay current ov-prefix)
15278 (while (re-search-forward
15279 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15280 (setq tg (match-string 1))
15281 (add-text-properties
15282 (match-beginning 1) (match-end 1)
15283 (list 'face
15284 (cond
15285 ((member tg current) c-face)
15286 ((member tg inherited) i-face)
15287 (t (get-text-property (match-beginning 1) 'face))))))
15288 (goto-char (point-min)))))
15289 (org-detach-overlay org-tags-overlay)
15290 (if rtn
15291 (mapconcat 'identity current ":")
15292 nil))))
15294 (defun org-get-tags-string ()
15295 "Get the TAGS string in the current headline."
15296 (unless (org-at-heading-p t)
15297 (user-error "Not on a heading"))
15298 (save-excursion
15299 (beginning-of-line 1)
15300 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15301 (org-match-string-no-properties 1)
15302 "")))
15304 (defun org-get-tags ()
15305 "Get the list of tags specified in the current headline."
15306 (org-split-string (org-get-tags-string) ":"))
15308 (defun org-get-buffer-tags ()
15309 "Get a table of all tags used in the buffer, for completion."
15310 (org-with-wide-buffer
15311 (goto-char (point-min))
15312 (let ((tag-re (concat org-outline-regexp-bol
15313 "\\(?:.*?[ \t]\\)?"
15314 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15315 tags)
15316 (while (re-search-forward tag-re nil t)
15317 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15318 (push tag tags)))
15319 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15321 ;;;; The mapping API
15323 (defvar org-agenda-skip-comment-trees)
15324 (defvar org-agenda-skip-function)
15325 (defun org-map-entries (func &optional match scope &rest skip)
15326 "Call FUNC at each headline selected by MATCH in SCOPE.
15328 FUNC is a function or a lisp form. The function will be called without
15329 arguments, with the cursor positioned at the beginning of the headline.
15330 The return values of all calls to the function will be collected and
15331 returned as a list.
15333 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15334 does not need to preserve point. After evaluation, the cursor will be
15335 moved to the end of the line (presumably of the headline of the
15336 processed entry) and search continues from there. Under some
15337 circumstances, this may not produce the wanted results. For example,
15338 if you have removed (e.g. archived) the current (sub)tree it could
15339 mean that the next entry will be skipped entirely. In such cases, you
15340 can specify the position from where search should continue by making
15341 FUNC set the variable `org-map-continue-from' to the desired buffer
15342 position.
15344 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15345 Only headlines that are matched by this query will be considered during
15346 the iteration. When MATCH is nil or t, all headlines will be
15347 visited by the iteration.
15349 SCOPE determines the scope of this command. It can be any of:
15351 nil The current buffer, respecting the restriction if any
15352 tree The subtree started with the entry at point
15353 region The entries within the active region, if any
15354 region-start-level
15355 The entries within the active region, but only those at
15356 the same level than the first one.
15357 file The current buffer, without restriction
15358 file-with-archives
15359 The current buffer, and any archives associated with it
15360 agenda All agenda files
15361 agenda-with-archives
15362 All agenda files with any archive files associated with them
15363 \(file1 file2 ...)
15364 If this is a list, all files in the list will be scanned
15366 The remaining args are treated as settings for the skipping facilities of
15367 the scanner. The following items can be given here:
15369 archive skip trees with the archive tag
15370 comment skip trees with the COMMENT keyword
15371 function or Emacs Lisp form:
15372 will be used as value for `org-agenda-skip-function', so
15373 whenever the function returns a position, FUNC will not be
15374 called for that entry and search will continue from the
15375 position returned
15377 If your function needs to retrieve the tags including inherited tags
15378 at the *current* entry, you can use the value of the variable
15379 `org-scanner-tags' which will be much faster than getting the value
15380 with `org-get-tags-at'. If your function gets properties with
15381 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15382 to t around the call to `org-entry-properties' to get the same speedup.
15383 Note that if your function moves around to retrieve tags and properties at
15384 a *different* entry, you cannot use these techniques."
15385 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15386 (not (org-region-active-p)))
15387 (let* ((org-agenda-archives-mode nil) ; just to make sure
15388 (org-agenda-skip-archived-trees (memq 'archive skip))
15389 (org-agenda-skip-comment-trees (memq 'comment skip))
15390 (org-agenda-skip-function
15391 (car (org-delete-all '(comment archive) skip)))
15392 (org-tags-match-list-sublevels t)
15393 (start-level (eq scope 'region-start-level))
15394 matcher res
15395 org-todo-keywords-for-agenda
15396 org-done-keywords-for-agenda
15397 org-todo-keyword-alist-for-agenda
15398 org-tag-alist-for-agenda
15399 org--matcher-tags-todo-only)
15401 (cond
15402 ((eq match t) (setq matcher t))
15403 ((eq match nil) (setq matcher t))
15404 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15406 (save-excursion
15407 (save-restriction
15408 (cond ((eq scope 'tree)
15409 (org-back-to-heading t)
15410 (org-narrow-to-subtree)
15411 (setq scope nil))
15412 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15413 (org-region-active-p))
15414 ;; If needed, set start-level to a string like "2"
15415 (when start-level
15416 (save-excursion
15417 (goto-char (region-beginning))
15418 (unless (org-at-heading-p) (outline-next-heading))
15419 (setq start-level (org-current-level))))
15420 (narrow-to-region (region-beginning)
15421 (save-excursion
15422 (goto-char (region-end))
15423 (unless (and (bolp) (org-at-heading-p))
15424 (outline-next-heading))
15425 (point)))
15426 (setq scope nil)))
15428 (if (not scope)
15429 (progn
15430 (org-agenda-prepare-buffers
15431 (and buffer-file-name (list buffer-file-name)))
15432 (setq res
15433 (org-scan-tags
15434 func matcher org--matcher-tags-todo-only start-level)))
15435 ;; Get the right scope
15436 (cond
15437 ((and scope (listp scope) (symbolp (car scope)))
15438 (setq scope (eval scope)))
15439 ((eq scope 'agenda)
15440 (setq scope (org-agenda-files t)))
15441 ((eq scope 'agenda-with-archives)
15442 (setq scope (org-agenda-files t))
15443 (setq scope (org-add-archive-files scope)))
15444 ((eq scope 'file)
15445 (setq scope (and buffer-file-name (list buffer-file-name))))
15446 ((eq scope 'file-with-archives)
15447 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15448 (org-agenda-prepare-buffers scope)
15449 (dolist (file scope)
15450 (with-current-buffer (org-find-base-buffer-visiting file)
15451 (save-excursion
15452 (save-restriction
15453 (widen)
15454 (goto-char (point-min))
15455 (setq res
15456 (append
15458 (org-scan-tags
15459 func matcher org--matcher-tags-todo-only))))))))))
15460 res)))
15462 ;;; Properties API
15464 (defconst org-special-properties
15465 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15466 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15467 "The special properties valid in Org mode.
15468 These are properties that are not defined in the property drawer,
15469 but in some other way.")
15471 (defconst org-default-properties
15472 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15473 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15474 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15475 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15476 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15477 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15478 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15479 "Some properties that are used by Org mode for various purposes.
15480 Being in this list makes sure that they are offered for completion.")
15482 (defun org--valid-property-p (property)
15483 "Non nil when string PROPERTY is a valid property name."
15484 (not
15485 (or (equal property "")
15486 (org-string-match-p "\\s-" property))))
15488 (defun org--update-property-plist (key val props)
15489 "Associate KEY to VAL in alist PROPS.
15490 Modifications are made by side-effect. Return new alist."
15491 (let* ((appending (string= (substring key -1) "+"))
15492 (key (if appending (substring key 0 -1) key))
15493 (old (assoc-string key props t)))
15494 (if (not old) (cons (cons key val) props)
15495 (setcdr old (if appending (concat (cdr old) " " val) val))
15496 props)))
15498 (defun org-get-property-block (&optional beg force)
15499 "Return the (beg . end) range of the body of the property drawer.
15500 BEG is the beginning of the current subtree, or of the part
15501 before the first headline. If it is not given, it will be found.
15502 If the drawer does not exist, create it if FORCE is non-nil, or
15503 return nil."
15504 (org-with-wide-buffer
15505 (when beg (goto-char beg))
15506 (unless (org-before-first-heading-p)
15507 (let ((beg (cond (beg)
15508 ((or (not (featurep 'org-inlinetask))
15509 (org-inlinetask-in-task-p))
15510 (org-back-to-heading t))
15511 (t (org-with-limited-levels (org-back-to-heading t))))))
15512 (forward-line)
15513 (when (org-looking-at-p org-planning-line-re) (forward-line))
15514 (cond ((looking-at org-property-drawer-re)
15515 (forward-line)
15516 (cons (point) (progn (goto-char (match-end 0))
15517 (line-beginning-position))))
15518 (force
15519 (goto-char beg)
15520 (org-insert-property-drawer)
15521 (let ((pos (save-excursion (search-forward ":END:")
15522 (line-beginning-position))))
15523 (cons pos pos))))))))
15525 (defun org-at-property-p ()
15526 "Non-nil when point is inside a property drawer.
15527 See `org-property-re' for match data, if applicable."
15528 (save-excursion
15529 (beginning-of-line)
15530 (and (looking-at org-property-re)
15531 (let ((property-drawer (save-match-data (org-get-property-block))))
15532 (and property-drawer
15533 (>= (point) (car property-drawer))
15534 (< (point) (cdr property-drawer)))))))
15536 (defun org-property-action ()
15537 "Do an action on properties."
15538 (interactive)
15539 (unless (org-at-property-p) (user-error "Not at a property"))
15540 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15541 (let ((c (read-char-exclusive)))
15542 (cl-case c
15543 (?s (call-interactively #'org-set-property))
15544 (?d (call-interactively #'org-delete-property))
15545 (?D (call-interactively #'org-delete-property-globally))
15546 (?c (call-interactively #'org-compute-property-at-point))
15547 (otherwise (user-error "No such property action %c" c)))))
15549 (defun org-inc-effort ()
15550 "Increment the value of the effort property in the current entry."
15551 (interactive)
15552 (org-set-effort nil t))
15554 (defvar org-clock-effort) ; Defined in org-clock.el.
15555 (defvar org-clock-current-task) ; Defined in org-clock.el.
15556 (defun org-set-effort (&optional value increment)
15557 "Set the effort property of the current entry.
15558 With numerical prefix arg, use the nth allowed value, 0 stands for the
15559 10th allowed value.
15561 When INCREMENT is non-nil, set the property to the next allowed value."
15562 (interactive "P")
15563 (when (equal value 0) (setq value 10))
15564 (let* ((completion-ignore-case t)
15565 (prop org-effort-property)
15566 (cur (org-entry-get nil prop))
15567 (allowed (org-property-get-allowed-values nil prop 'table))
15568 (existing (mapcar 'list (org-property-values prop)))
15569 (heading (nth 4 (org-heading-components)))
15571 (val (cond
15572 ((stringp value) value)
15573 ((and allowed (integerp value))
15574 (or (car (nth (1- value) allowed))
15575 (car (org-last allowed))))
15576 ((and allowed increment)
15577 (or (cl-caadr (member (list cur) allowed))
15578 (user-error "Allowed effort values are not set")))
15579 (allowed
15580 (message "Select 1-9,0, [RET%s]: %s"
15581 (if cur (concat "=" cur) "")
15582 (mapconcat 'car allowed " "))
15583 (setq rpl (read-char-exclusive))
15584 (if (equal rpl ?\r)
15586 (setq rpl (- rpl ?0))
15587 (when (equal rpl 0) (setq rpl 10))
15588 (if (and (> rpl 0) (<= rpl (length allowed)))
15589 (car (nth (1- rpl) allowed))
15590 (org-completing-read "Effort: " allowed nil))))
15592 (org-completing-read
15593 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15594 (concat "[" cur "]") "")
15595 ": ")
15596 existing nil nil "" nil cur)))))
15597 (unless (equal (org-entry-get nil prop) val)
15598 (org-entry-put nil prop val))
15599 (org-refresh-property
15600 '((effort . identity)
15601 (effort-minutes . org-duration-string-to-minutes))
15602 val)
15603 (when (string= heading org-clock-current-task)
15604 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15605 (org-clock-update-mode-line))
15606 (message "%s is now %s" prop val)))
15608 (defun org-entry-properties (&optional pom which)
15609 "Get all properties of the current entry.
15611 When POM is a buffer position, get all properties from the entry
15612 there instead.
15614 This includes the TODO keyword, the tags, time strings for
15615 deadline, scheduled, and clocking, and any additional properties
15616 defined in the entry.
15618 If WHICH is nil or `all', get all properties. If WHICH is
15619 `special' or `standard', only get that subclass. If WHICH is
15620 a string, only get that property.
15622 Return value is an alist. Keys are properties, as upcased
15623 strings."
15624 (org-with-point-at pom
15625 (when (and (derived-mode-p 'org-mode)
15626 (ignore-errors (org-back-to-heading t)))
15627 (catch 'exit
15628 (let* ((beg (point))
15629 (specific (and (stringp which) (upcase which)))
15630 (which (cond ((not specific) which)
15631 ((member specific org-special-properties) 'special)
15632 (t 'standard)))
15633 props)
15634 ;; Get the special properties, like TODO and TAGS.
15635 (when (memq which '(nil all special))
15636 (when (or (not specific) (string= specific "CLOCKSUM"))
15637 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15638 (when clocksum
15639 (push (cons "CLOCKSUM"
15640 (org-minutes-to-clocksum-string clocksum))
15641 props)))
15642 (when specific (throw 'exit props)))
15643 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15644 (let ((clocksumt (get-text-property (point)
15645 :org-clock-minutes-today)))
15646 (when clocksumt
15647 (push (cons "CLOCKSUM_T"
15648 (org-minutes-to-clocksum-string clocksumt))
15649 props)))
15650 (when specific (throw 'exit props)))
15651 (when (or (not specific) (string= specific "ITEM"))
15652 (when (looking-at org-complex-heading-regexp)
15653 (push (cons "ITEM"
15654 (let ((title (match-string-no-properties 4)))
15655 (if (org-string-nw-p title)
15656 (org-remove-tabs title)
15657 "")))
15658 props))
15659 (when specific (throw 'exit props)))
15660 (when (or (not specific) (string= specific "TODO"))
15661 (let ((case-fold-search nil))
15662 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15663 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15664 (when specific (throw 'exit props)))
15665 (when (or (not specific) (string= specific "PRIORITY"))
15666 (push (cons "PRIORITY"
15667 (if (looking-at org-priority-regexp)
15668 (org-match-string-no-properties 2)
15669 (char-to-string org-default-priority)))
15670 props)
15671 (when specific (throw 'exit props)))
15672 (when (or (not specific) (string= specific "FILE"))
15673 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15674 props)
15675 (when specific (throw 'exit props)))
15676 (when (or (not specific) (string= specific "TAGS"))
15677 (let ((value (org-string-nw-p (org-get-tags-string))))
15678 (when value (push (cons "TAGS" value) props)))
15679 (when specific (throw 'exit props)))
15680 (when (or (not specific) (string= specific "ALLTAGS"))
15681 (let ((value (org-get-tags-at)))
15682 (when value
15683 (push (cons "ALLTAGS"
15684 (format ":%s:" (mapconcat #'identity value ":")))
15685 props)))
15686 (when specific (throw 'exit props)))
15687 (when (or (not specific) (string= specific "BLOCKED"))
15688 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15689 (when specific (throw 'exit props)))
15690 (when (or (not specific)
15691 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15692 (forward-line)
15693 (when (org-looking-at-p org-planning-line-re)
15694 (end-of-line)
15695 (let ((bol (line-beginning-position))
15696 ;; Backward compatibility: time keywords used to
15697 ;; be configurable (before 8.3). Make sure we
15698 ;; get the correct keyword.
15699 (key-assoc `(("CLOSED" . ,org-closed-string)
15700 ("DEADLINE" . ,org-deadline-string)
15701 ("SCHEDULED" . ,org-scheduled-string))))
15702 (dolist (pair (if specific (list (assoc specific key-assoc))
15703 key-assoc))
15704 (save-excursion
15705 (when (search-backward (cdr pair) bol t)
15706 (goto-char (match-end 0))
15707 (skip-chars-forward " \t")
15708 (and (looking-at org-ts-regexp-both)
15709 (push (cons (car pair)
15710 (org-match-string-no-properties 0))
15711 props)))))))
15712 (when specific (throw 'exit props)))
15713 (when (or (not specific)
15714 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15715 (let ((find-ts
15716 (lambda (end ts)
15717 ;; Fix next time-stamp before END. TS is the
15718 ;; list of time-stamps found so far.
15719 (let ((ts ts)
15720 (regexp (cond
15721 ((string= specific "TIMESTAMP")
15722 org-ts-regexp)
15723 ((string= specific "TIMESTAMP_IA")
15724 org-ts-regexp-inactive)
15725 ((assoc "TIMESTAMP_IA" ts)
15726 org-ts-regexp)
15727 ((assoc "TIMESTAMP" ts)
15728 org-ts-regexp-inactive)
15729 (t org-ts-regexp-both))))
15730 (catch 'next
15731 (while (re-search-forward regexp end t)
15732 (backward-char)
15733 (let ((object (org-element-context)))
15734 ;; Accept to match timestamps in node
15735 ;; properties, too.
15736 (when (memq (org-element-type object)
15737 '(node-property timestamp))
15738 (let ((type
15739 (org-element-property :type object)))
15740 (cond
15741 ((and (memq type '(active active-range))
15742 (not (equal specific "TIMESTAMP_IA")))
15743 (unless (assoc "TIMESTAMP" ts)
15744 (push (cons "TIMESTAMP"
15745 (org-element-property
15746 :raw-value object))
15748 (when specific (throw 'exit ts))))
15749 ((and (memq type '(inactive inactive-range))
15750 (not (string= specific "TIMESTAMP")))
15751 (unless (assoc "TIMESTAMP_IA" ts)
15752 (push (cons "TIMESTAMP_IA"
15753 (org-element-property
15754 :raw-value object))
15756 (when specific (throw 'exit ts))))))
15757 ;; Both timestamp types are found,
15758 ;; move to next part.
15759 (when (= (length ts) 2) (throw 'next ts)))))
15760 ts)))))
15761 (goto-char beg)
15762 ;; First look for timestamps within headline.
15763 (let ((ts (funcall find-ts (line-end-position) nil)))
15764 (if (= (length ts) 2) (setq props (nconc ts props))
15765 (forward-line)
15766 ;; Then find timestamps in the section, skipping
15767 ;; planning line.
15768 (when (org-looking-at-p org-planning-line-re)
15769 (forward-line))
15770 (let ((end (save-excursion (outline-next-heading))))
15771 (setq props (nconc (funcall find-ts end ts) props))))))))
15772 ;; Get the standard properties, like :PROP:.
15773 (when (memq which '(nil all standard))
15774 ;; If we are looking after a specific property, delegate
15775 ;; to `org-entry-get', which is faster. However, make an
15776 ;; exception for "CATEGORY", since it can be also set
15777 ;; through keywords (i.e. #+CATEGORY).
15778 (if (and specific (not (equal specific "CATEGORY")))
15779 (let ((value (org-entry-get beg specific nil t)))
15780 (throw 'exit (and value (list (cons specific value)))))
15781 (let ((range (org-get-property-block beg)))
15782 (when range
15783 (let ((end (cdr range)) seen-base)
15784 (goto-char (car range))
15785 ;; Unlike to `org--update-property-plist', we
15786 ;; handle the case where base values is found
15787 ;; after its extension. We also forbid standard
15788 ;; properties to be named as special properties.
15789 (while (re-search-forward org-property-re end t)
15790 (let* ((key (upcase (org-match-string-no-properties 2)))
15791 (extendp (org-string-match-p "\\+\\'" key))
15792 (key-base (if extendp (substring key 0 -1) key))
15793 (value (org-match-string-no-properties 3)))
15794 (cond
15795 ((member-ignore-case key-base org-special-properties))
15796 (extendp
15797 (setq props
15798 (org--update-property-plist key value props)))
15799 ((member key seen-base))
15800 (t (push key seen-base)
15801 (let ((p (assoc-string key props t)))
15802 (if p (setcdr p (concat value " " (cdr p)))
15803 (push (cons key value) props))))))))))))
15804 (unless (assoc "CATEGORY" props)
15805 (push (cons "CATEGORY" (org-get-category beg)) props)
15806 (when (string= specific "CATEGORY") (throw 'exit props)))
15807 ;; Return value.
15808 props)))))
15810 (defun org-property--local-values (property literal-nil)
15811 "Return value for PROPERTY in current entry.
15812 Value is a list whose care is the base value for PROPERTY and cdr
15813 a list of accumulated values. Return nil if neither is found in
15814 the entry. Also return nil when PROPERTY is set to \"nil\",
15815 unless LITERAL-NIL is non-nil."
15816 (let ((range (org-get-property-block)))
15817 (when range
15818 (goto-char (car range))
15819 (let* ((case-fold-search t)
15820 (end (cdr range))
15821 (value
15822 ;; Base value.
15823 (save-excursion
15824 (let ((v (and (re-search-forward
15825 (org-re-property property nil t) end t)
15826 (org-match-string-no-properties 3))))
15827 (list (if literal-nil v (org-not-nil v)))))))
15828 ;; Find additional values.
15829 (let* ((property+ (org-re-property (concat property "+") nil t)))
15830 (while (re-search-forward property+ end t)
15831 (push (org-match-string-no-properties 3) value)))
15832 ;; Return final values.
15833 (and (not (equal value '(nil))) (nreverse value))))))
15835 (defun org-entry-get (pom property &optional inherit literal-nil)
15836 "Get value of PROPERTY for entry or content at point-or-marker POM.
15838 If INHERIT is non-nil and the entry does not have the property,
15839 then also check higher levels of the hierarchy. If INHERIT is
15840 the symbol `selective', use inheritance only if the setting in
15841 `org-use-property-inheritance' selects PROPERTY for inheritance.
15843 If the property is present but empty, the return value is the
15844 empty string. If the property is not present at all, nil is
15845 returned. In any other case, return the value as a string.
15846 Search is case-insensitive.
15848 If LITERAL-NIL is set, return the string value \"nil\" as
15849 a string, do not interpret it as the list atom nil. This is used
15850 for inheritance when a \"nil\" value can supersede a non-nil
15851 value higher up the hierarchy."
15852 (org-with-point-at pom
15853 (cond
15854 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15855 ;; We need a special property. Use `org-entry-properties' to
15856 ;; retrieve it, but specify the wanted property.
15857 (cdr (assoc-string property (org-entry-properties nil property))))
15858 ((and inherit
15859 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15860 (org-entry-get-with-inheritance property literal-nil))
15862 (let* ((local (org-property--local-values property literal-nil))
15863 (value (and local (mapconcat #'identity (delq nil local) " "))))
15864 (if literal-nil value (org-not-nil value)))))))
15866 (defun org-property-or-variable-value (var &optional inherit)
15867 "Check if there is a property fixing the value of VAR.
15868 If yes, return this value. If not, return the current value of the variable."
15869 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15870 (if (and prop (stringp prop) (string-match "\\S-" prop))
15871 (read prop)
15872 (symbol-value var))))
15874 (defun org-entry-delete (pom property)
15875 "Delete PROPERTY from entry at point-or-marker POM.
15876 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15877 non-nil when a property was removed."
15878 (unless (member property org-special-properties)
15879 (org-with-point-at pom
15880 (let ((range (org-get-property-block)))
15881 (when range
15882 (let* ((begin (car range))
15883 (origin (cdr range))
15884 (end (copy-marker origin))
15885 (re (org-re-property
15886 (concat (regexp-quote property) "\\+?") t t)))
15887 (goto-char begin)
15888 (while (re-search-forward re end t)
15889 (delete-region (match-beginning 0) (line-beginning-position 2)))
15890 ;; If drawer is empty, remove it altogether.
15891 (when (= begin end)
15892 (delete-region (line-beginning-position 0)
15893 (line-beginning-position 2)))
15894 ;; Return non-nil if some property was removed.
15895 (prog1 (/= end origin) (set-marker end nil))))))))
15897 ;; Multi-values properties are properties that contain multiple values
15898 ;; These values are assumed to be single words, separated by whitespace.
15899 (defun org-entry-add-to-multivalued-property (pom property value)
15900 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15901 (let* ((old (org-entry-get pom property))
15902 (values (and old (org-split-string old "[ \t]"))))
15903 (setq value (org-entry-protect-space value))
15904 (unless (member value values)
15905 (setq values (append values (list value)))
15906 (org-entry-put pom property
15907 (mapconcat 'identity values " ")))))
15909 (defun org-entry-remove-from-multivalued-property (pom property value)
15910 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15911 (let* ((old (org-entry-get pom property))
15912 (values (and old (org-split-string old "[ \t]"))))
15913 (setq value (org-entry-protect-space value))
15914 (when (member value values)
15915 (setq values (delete value values))
15916 (org-entry-put pom property
15917 (mapconcat 'identity values " ")))))
15919 (defun org-entry-member-in-multivalued-property (pom property value)
15920 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15921 (let* ((old (org-entry-get pom property))
15922 (values (and old (org-split-string old "[ \t]"))))
15923 (setq value (org-entry-protect-space value))
15924 (member value values)))
15926 (defun org-entry-get-multivalued-property (pom property)
15927 "Return a list of values in a multivalued property."
15928 (let* ((value (org-entry-get pom property))
15929 (values (and value (org-split-string value "[ \t]"))))
15930 (mapcar 'org-entry-restore-space values)))
15932 (defun org-entry-put-multivalued-property (pom property &rest values)
15933 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15934 VALUES should be a list of strings. Spaces will be protected."
15935 (org-entry-put pom property
15936 (mapconcat 'org-entry-protect-space values " "))
15937 (let* ((value (org-entry-get pom property))
15938 (values (and value (org-split-string value "[ \t]"))))
15939 (mapcar 'org-entry-restore-space values)))
15941 (defun org-entry-protect-space (s)
15942 "Protect spaces and newline in string S."
15943 (while (string-match " " s)
15944 (setq s (replace-match "%20" t t s)))
15945 (while (string-match "\n" s)
15946 (setq s (replace-match "%0A" t t s)))
15949 (defun org-entry-restore-space (s)
15950 "Restore spaces and newline in string S."
15951 (while (string-match "%20" s)
15952 (setq s (replace-match " " t t s)))
15953 (while (string-match "%0A" s)
15954 (setq s (replace-match "\n" t t s)))
15957 (defvar org-entry-property-inherited-from (make-marker)
15958 "Marker pointing to the entry from where a property was inherited.
15959 Each call to `org-entry-get-with-inheritance' will set this marker to the
15960 location of the entry where the inheritance search matched. If there was
15961 no match, the marker will point nowhere.
15962 Note that also `org-entry-get' calls this function, if the INHERIT flag
15963 is set.")
15965 (defun org-entry-get-with-inheritance (property &optional literal-nil)
15966 "Get PROPERTY of entry or content at point, search higher levels if needed.
15967 The search will stop at the first ancestor which has the property defined.
15968 If the value found is \"nil\", return nil to show that the property
15969 should be considered as undefined (this is the meaning of nil here).
15970 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
15971 (move-marker org-entry-property-inherited-from nil)
15972 (org-with-wide-buffer
15973 (let (value)
15974 (catch 'exit
15975 (while t
15976 (let ((v (org-property--local-values property literal-nil)))
15977 (when v
15978 (setq value
15979 (concat (mapconcat #'identity (delq nil v) " ")
15980 (and value " ")
15981 value)))
15982 (cond
15983 ((car v)
15984 (org-back-to-heading t)
15985 (move-marker org-entry-property-inherited-from (point))
15986 (throw 'exit nil))
15987 ((org-up-heading-safe))
15989 (let ((global
15990 (cdr (or (assoc-string property org-file-properties t)
15991 (assoc-string property org-global-properties t)
15992 (assoc-string property org-global-properties-fixed t)))))
15993 (cond ((not global))
15994 (value (setq value (concat global " " value)))
15995 (t (setq value global))))
15996 (throw 'exit nil))))))
15997 (if literal-nil value (org-not-nil value)))))
15999 (defvar org-property-changed-functions nil
16000 "Hook called when the value of a property has changed.
16001 Each hook function should accept two arguments, the name of the property
16002 and the new value.")
16004 (defun org-entry-put (pom property value)
16005 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16007 If the value is nil, it is converted to the empty string. If it
16008 is not a string, an error is raised. Also raise an error on
16009 invalid property names.
16011 PROPERTY can be any regular property (see
16012 `org-special-properties'). It can also be \"TODO\",
16013 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16015 For the last two properties, VALUE may have any of the special
16016 values \"earlier\" and \"later\". The function then increases or
16017 decreases scheduled or deadline date by one day."
16018 (cond ((null value) (setq value ""))
16019 ((not (stringp value)) (error "Properties values should be strings"))
16020 ((not (org--valid-property-p property))
16021 (user-error "Invalid property name: \"%s\"" property)))
16022 (org-with-point-at pom
16023 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16024 (org-back-to-heading t)
16025 (org-with-limited-levels (org-back-to-heading t)))
16026 (let ((beg (point)))
16027 (cond
16028 ((equal property "TODO")
16029 (cond ((not (org-string-nw-p value)) (setq value 'none))
16030 ((not (member value org-todo-keywords-1))
16031 (user-error "\"%s\" is not a valid TODO state" value)))
16032 (org-todo value)
16033 (org-set-tags nil 'align))
16034 ((equal property "PRIORITY")
16035 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16036 (org-set-tags nil 'align))
16037 ((equal property "SCHEDULED")
16038 (forward-line)
16039 (if (and (org-looking-at-p org-planning-line-re)
16040 (re-search-forward
16041 org-scheduled-time-regexp (line-end-position) t))
16042 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16043 ((string= value "later") (org-timestamp-change 1 'day))
16044 ((string= value "") (org-schedule '(4)))
16045 (t (org-schedule nil value)))
16046 (if (member value '("earlier" "later" ""))
16047 (call-interactively #'org-schedule)
16048 (org-schedule nil value))))
16049 ((equal property "DEADLINE")
16050 (forward-line)
16051 (if (and (org-looking-at-p org-planning-line-re)
16052 (re-search-forward
16053 org-deadline-time-regexp (line-end-position) t))
16054 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16055 ((string= value "later") (org-timestamp-change 1 'day))
16056 ((string= value "") (org-deadline '(4)))
16057 (t (org-deadline nil value)))
16058 (if (member value '("earlier" "later" ""))
16059 (call-interactively #'org-deadline)
16060 (org-deadline nil value))))
16061 ((member property org-special-properties)
16062 (error "The %s property cannot be set with `org-entry-put'" property))
16064 (let* ((range (org-get-property-block beg 'force))
16065 (end (cdr range))
16066 (case-fold-search t))
16067 (goto-char (car range))
16068 (if (re-search-forward (org-re-property property nil t) end t)
16069 (progn (delete-region (match-beginning 0) (match-end 0))
16070 (goto-char (match-beginning 0)))
16071 (goto-char end)
16072 (insert "\n")
16073 (backward-char))
16074 (insert ":" property ":")
16075 (when value (insert " " value))
16076 (org-indent-line)))))
16077 (run-hook-with-args 'org-property-changed-functions property value)))
16079 (defun org-buffer-property-keys
16080 (&optional specials defaults columns ignore-malformed)
16081 "Get all property keys in the current buffer.
16083 When SPECIALS is non-nil, also list the special properties that
16084 reflect things like tags and TODO state.
16086 When DEFAULTS is non-nil, also include properties that has
16087 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16088 DESCRIPTION, LOCATION, and LOGGING and others.
16090 When COLUMNS in non-nil, also include property names given in
16091 COLUMN formats in the current buffer.
16093 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16094 automatically performed, such drawers will be silently ignored."
16095 (let ((case-fold-search t)
16096 (props (append
16097 (and specials org-special-properties)
16098 (and defaults (cons org-effort-property org-default-properties))
16099 nil)))
16100 (org-with-wide-buffer
16101 (goto-char (point-min))
16102 (while (re-search-forward org-property-start-re nil t)
16103 (let ((range (org-get-property-block)))
16104 (catch 'skip
16105 (unless range
16106 (when (and (not ignore-malformed)
16107 (not (org-before-first-heading-p))
16108 (y-or-n-p (format "Malformed drawer at %d, repair?"
16109 (line-beginning-position))))
16110 (org-get-property-block nil t))
16111 (throw 'skip nil))
16112 (goto-char (car range))
16113 (let ((begin (car range))
16114 (end (cdr range)))
16115 ;; Make sure that found property block is not located
16116 ;; before current point, as it would generate an infloop.
16117 ;; It can happen, for example, in the following
16118 ;; situation:
16120 ;; * Headline
16121 ;; :PROPERTIES:
16122 ;; ...
16123 ;; :END:
16124 ;; *************** Inlinetask
16125 ;; #+BEGIN_EXAMPLE
16126 ;; :PROPERTIES:
16127 ;; #+END_EXAMPLE
16129 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16130 (while (< (point) end)
16131 (let ((p (progn (looking-at org-property-re)
16132 (org-match-string-no-properties 2))))
16133 ;; Only add true property name, not extension symbol.
16134 (push (if (not (org-string-match-p "\\+\\'" p)) p
16135 (substring p 0 -1))
16136 props))
16137 (forward-line))))
16138 (outline-next-heading)))
16139 (when columns
16140 (goto-char (point-min))
16141 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16142 (let ((element (org-element-at-point)))
16143 (when (memq (org-element-type element) '(keyword node-property))
16144 (let ((value (org-element-property :value element))
16145 (start 0))
16146 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16147 (setq start (match-end 0))
16148 (let ((p (org-match-string-no-properties 1 value)))
16149 (unless (member-ignore-case p org-special-properties)
16150 (push p props))))))))))
16151 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16153 (defun org-property-values (key)
16154 "List all non-nil values of property KEY in current buffer."
16155 (org-with-wide-buffer
16156 (goto-char (point-min))
16157 (let ((case-fold-search t)
16158 (re (org-re-property key))
16159 values)
16160 (while (re-search-forward re nil t)
16161 (push (org-entry-get (point) key) values))
16162 (delete-dups values))))
16164 (defun org-insert-property-drawer ()
16165 "Insert a property drawer into the current entry."
16166 (org-with-wide-buffer
16167 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16168 (org-back-to-heading t)
16169 (org-with-limited-levels (org-back-to-heading t)))
16170 (forward-line)
16171 (when (org-looking-at-p org-planning-line-re) (forward-line))
16172 (unless (org-looking-at-p org-property-drawer-re)
16173 ;; Make sure we start editing a line from current entry, not from
16174 ;; next one. It prevents extending text properties or overlays
16175 ;; belonging to the latter.
16176 (when (bolp) (backward-char))
16177 (let ((begin (1+ (point)))
16178 (inhibit-read-only t))
16179 (insert "\n:PROPERTIES:\n:END:")
16180 (when (eobp) (insert "\n"))
16181 (org-indent-region begin (point))))))
16183 (defun org-insert-drawer (&optional arg drawer)
16184 "Insert a drawer at point.
16186 When optional argument ARG is non-nil, insert a property drawer.
16188 Optional argument DRAWER, when non-nil, is a string representing
16189 drawer's name. Otherwise, the user is prompted for a name.
16191 If a region is active, insert the drawer around that region
16192 instead.
16194 Point is left between drawer's boundaries."
16195 (interactive "P")
16196 (let* ((drawer (if arg "PROPERTIES"
16197 (or drawer (read-from-minibuffer "Drawer: ")))))
16198 (cond
16199 ;; With C-u, fall back on `org-insert-property-drawer'
16200 (arg (org-insert-property-drawer))
16201 ;; Check validity of suggested drawer's name.
16202 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16203 (user-error "Invalid drawer name"))
16204 ;; With an active region, insert a drawer at point.
16205 ((not (org-region-active-p))
16206 (progn
16207 (unless (bolp) (insert "\n"))
16208 (insert (format ":%s:\n\n:END:\n" drawer))
16209 (forward-line -2)))
16210 ;; Otherwise, insert the drawer at point
16212 (let ((rbeg (region-beginning))
16213 (rend (copy-marker (region-end))))
16214 (unwind-protect
16215 (progn
16216 (goto-char rbeg)
16217 (beginning-of-line)
16218 (when (save-excursion
16219 (re-search-forward org-outline-regexp-bol rend t))
16220 (user-error "Drawers cannot contain headlines"))
16221 ;; Position point at the beginning of the first
16222 ;; non-blank line in region. Insert drawer's opening
16223 ;; there, then indent it.
16224 (org-skip-whitespace)
16225 (beginning-of-line)
16226 (insert ":" drawer ":\n")
16227 (forward-line -1)
16228 (indent-for-tab-command)
16229 ;; Move point to the beginning of the first blank line
16230 ;; after the last non-blank line in region. Insert
16231 ;; drawer's closing, then indent it.
16232 (goto-char rend)
16233 (skip-chars-backward " \r\t\n")
16234 (insert "\n:END:")
16235 (deactivate-mark t)
16236 (indent-for-tab-command)
16237 (unless (eolp) (insert "\n")))
16238 ;; Clear marker, whatever the outcome of insertion is.
16239 (set-marker rend nil)))))))
16241 (defvar org-property-set-functions-alist nil
16242 "Property set function alist.
16243 Each entry should have the following format:
16245 (PROPERTY . READ-FUNCTION)
16247 The read function will be called with the same argument as
16248 `org-completing-read'.")
16250 (defun org-set-property-function (property)
16251 "Get the function that should be used to set PROPERTY.
16252 This is computed according to `org-property-set-functions-alist'."
16253 (or (cdr (assoc property org-property-set-functions-alist))
16254 'org-completing-read))
16256 (defun org-read-property-value (property)
16257 "Read PROPERTY value from user."
16258 (let* ((completion-ignore-case t)
16259 (allowed (org-property-get-allowed-values nil property 'table))
16260 (cur (org-entry-get nil property))
16261 (prompt (concat property " value"
16262 (if (and cur (string-match "\\S-" cur))
16263 (concat " [" cur "]") "") ": "))
16264 (set-function (org-set-property-function property))
16265 (val (if allowed
16266 (funcall set-function prompt allowed nil
16267 (not (get-text-property 0 'org-unrestricted
16268 (caar allowed))))
16269 (funcall set-function prompt
16270 (mapcar 'list (org-property-values property))
16271 nil nil "" nil cur))))
16272 (org-trim val)))
16274 (defvar org-last-set-property nil)
16275 (defvar org-last-set-property-value nil)
16276 (defun org-read-property-name ()
16277 "Read a property name."
16278 (let ((completion-ignore-case t)
16279 (default-prop (or (and (org-at-property-p)
16280 (org-match-string-no-properties 2))
16281 org-last-set-property)))
16282 (org-completing-read
16283 (concat "Property"
16284 (if default-prop (concat " [" default-prop "]") "")
16285 ": ")
16286 (mapcar #'list (org-buffer-property-keys nil t t))
16287 nil nil nil nil default-prop)))
16289 (defun org-set-property-and-value (use-last)
16290 "Allow to set [PROPERTY]: [value] direction from prompt.
16291 When use-default, don't even ask, just use the last
16292 \"[PROPERTY]: [value]\" string from the history."
16293 (interactive "P")
16294 (let* ((completion-ignore-case t)
16295 (pv (or (and use-last org-last-set-property-value)
16296 (org-completing-read
16297 "Enter a \"[Property]: [value]\" pair: "
16298 nil nil nil nil nil
16299 org-last-set-property-value)))
16300 prop val)
16301 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16302 (setq prop (match-string 1 pv)
16303 val (match-string 2 pv))
16304 (org-set-property prop val))))
16306 (defun org-set-property (property value)
16307 "In the current entry, set PROPERTY to VALUE.
16309 When called interactively, this will prompt for a property name, offering
16310 completion on existing and default properties. And then it will prompt
16311 for a value, offering completion either on allowed values (via an inherited
16312 xxx_ALL property) or on existing values in other instances of this property
16313 in the current file.
16315 Throw an error when trying to set a property with an invalid name."
16316 (interactive (list nil nil))
16317 (let ((property (or property (org-read-property-name))))
16318 ;; `org-entry-put' also makes the following check, but this one
16319 ;; avoids polluting `org-last-set-property' and
16320 ;; `org-last-set-property-value' needlessly.
16321 (unless (org--valid-property-p property)
16322 (user-error "Invalid property name: \"%s\"" property))
16323 (let ((value (or value (org-read-property-value property)))
16324 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16325 (setq org-last-set-property property)
16326 (setq org-last-set-property-value (concat property ": " value))
16327 ;; Possibly postprocess the inserted value:
16328 (when fn (setq value (funcall fn value)))
16329 (unless (equal (org-entry-get nil property) value)
16330 (org-entry-put nil property value)))))
16332 (defun org-find-property (property &optional value)
16333 "Find first entry in buffer that sets PROPERTY.
16335 When optional argument VALUE is non-nil, only consider an entry
16336 if it contains PROPERTY set to this value. If PROPERTY should be
16337 explicitly set to nil, use string \"nil\" for VALUE.
16339 Return position where the entry begins, or nil if there is no
16340 such entry. If narrowing is in effect, only search the visible
16341 part of the buffer."
16342 (save-excursion
16343 (goto-char (point-min))
16344 (let ((case-fold-search t)
16345 (re (org-re-property property nil (not value) value)))
16346 (catch 'exit
16347 (while (re-search-forward re nil t)
16348 (when (if value (org-at-property-p)
16349 (org-entry-get (point) property nil t))
16350 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16352 (defun org-delete-property (property)
16353 "In the current entry, delete PROPERTY."
16354 (interactive
16355 (let* ((completion-ignore-case t)
16356 (cat (org-entry-get (point) "CATEGORY"))
16357 (props0 (org-entry-properties nil 'standard))
16358 (props (if cat props0
16359 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16360 (prop (if (< 1 (length props))
16361 (completing-read "Property: " props nil t)
16362 (caar props))))
16363 (list prop)))
16364 (if (not property)
16365 (message "No property to delete in this entry")
16366 (org-entry-delete nil property)
16367 (message "Property \"%s\" deleted" property)))
16369 (defun org-delete-property-globally (property)
16370 "Remove PROPERTY globally, from all entries.
16371 This function ignores narrowing, if any."
16372 (interactive
16373 (let* ((completion-ignore-case t)
16374 (prop (completing-read
16375 "Globally remove property: "
16376 (mapcar #'list (org-buffer-property-keys)))))
16377 (list prop)))
16378 (org-with-wide-buffer
16379 (goto-char (point-min))
16380 (let ((count 0)
16381 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16382 (while (re-search-forward re nil t)
16383 (when (org-entry-delete (point) property) (cl-incf count)))
16384 (message "Property \"%s\" removed from %d entries" property count))))
16386 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16388 (defun org-compute-property-at-point ()
16389 "Compute the property at point.
16390 This looks for an enclosing column format, extracts the operator and
16391 then applies it to the property in the column format's scope."
16392 (interactive)
16393 (unless (org-at-property-p)
16394 (user-error "Not at a property"))
16395 (let ((prop (org-match-string-no-properties 2)))
16396 (org-columns-get-format-and-top-level)
16397 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16398 (user-error "No operator defined for property %s" prop))
16399 (org-columns-compute prop)))
16401 (defvar org-property-allowed-value-functions nil
16402 "Hook for functions supplying allowed values for a specific property.
16403 The functions must take a single argument, the name of the property, and
16404 return a flat list of allowed values. If \":ETC\" is one of
16405 the values, this means that these values are intended as defaults for
16406 completion, but that other values should be allowed too.
16407 The functions must return nil if they are not responsible for this
16408 property.")
16410 (defun org-property-get-allowed-values (pom property &optional table)
16411 "Get allowed values for the property PROPERTY.
16412 When TABLE is non-nil, return an alist that can directly be used for
16413 completion."
16414 (let (vals)
16415 (cond
16416 ((equal property "TODO")
16417 (setq vals (org-with-point-at pom
16418 (append org-todo-keywords-1 '("")))))
16419 ((equal property "PRIORITY")
16420 (let ((n org-lowest-priority))
16421 (while (>= n org-highest-priority)
16422 (push (char-to-string n) vals)
16423 (setq n (1- n)))))
16424 ((equal property "CATEGORY"))
16425 ((member property org-special-properties))
16426 ((setq vals (run-hook-with-args-until-success
16427 'org-property-allowed-value-functions property)))
16429 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16430 (when (and vals (string-match "\\S-" vals))
16431 (setq vals (car (read-from-string (concat "(" vals ")"))))
16432 (setq vals (mapcar (lambda (x)
16433 (cond ((stringp x) x)
16434 ((numberp x) (number-to-string x))
16435 ((symbolp x) (symbol-name x))
16436 (t "???")))
16437 vals)))))
16438 (when (member ":ETC" vals)
16439 (setq vals (remove ":ETC" vals))
16440 (org-add-props (car vals) '(org-unrestricted t)))
16441 (if table (mapcar 'list vals) vals)))
16443 (defun org-property-previous-allowed-value (&optional _previous)
16444 "Switch to the next allowed value for this property."
16445 (interactive)
16446 (org-property-next-allowed-value t))
16448 (defun org-property-next-allowed-value (&optional previous)
16449 "Switch to the next allowed value for this property."
16450 (interactive)
16451 (unless (org-at-property-p)
16452 (user-error "Not at a property"))
16453 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16454 (key (match-string 2))
16455 (value (match-string 3))
16456 (allowed (or (org-property-get-allowed-values (point) key)
16457 (and (member value '("[ ]" "[-]" "[X]"))
16458 '("[ ]" "[X]"))))
16459 (heading (save-match-data (nth 4 (org-heading-components))))
16460 nval)
16461 (unless allowed
16462 (user-error "Allowed values for this property have not been defined"))
16463 (when previous (setq allowed (reverse allowed)))
16464 (when (member value allowed)
16465 (setq nval (car (cdr (member value allowed)))))
16466 (setq nval (or nval (car allowed)))
16467 (when (equal nval value)
16468 (user-error "Only one allowed value for this property"))
16469 (org-at-property-p)
16470 (replace-match (concat " :" key ": " nval) t t)
16471 (org-indent-line)
16472 (beginning-of-line 1)
16473 (skip-chars-forward " \t")
16474 (when (equal prop org-effort-property)
16475 (org-refresh-property
16476 '((effort . identity)
16477 (effort-minutes . org-duration-string-to-minutes))
16478 nval)
16479 (when (string= org-clock-current-task heading)
16480 (setq org-clock-effort nval)
16481 (org-clock-update-mode-line)))
16482 (run-hook-with-args 'org-property-changed-functions key nval)))
16484 (defun org-find-olp (path &optional this-buffer)
16485 "Return a marker pointing to the entry at outline path OLP.
16486 If anything goes wrong, throw an error.
16487 You can wrap this call to catch the error like this:
16489 \(condition-case msg
16490 \(org-mobile-locate-entry (match-string 4))
16491 \(error (nth 1 msg)))
16493 The return value will then be either a string with the error message,
16494 or a marker if everything is OK.
16496 If THIS-BUFFER is set, the outline path does not contain a file,
16497 only headings."
16498 (let* ((file (if this-buffer buffer-file-name (pop path)))
16499 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16500 (level 1)
16501 (lmin 1)
16502 (lmax 1)
16503 end found flevel)
16504 (unless buffer (error "File not found :%s" file))
16505 (with-current-buffer buffer
16506 (org-with-wide-buffer
16507 (goto-char (point-min))
16508 (dolist (heading path)
16509 (let ((re (format org-complex-heading-regexp-format
16510 (regexp-quote heading)))
16511 (cnt 0))
16512 (while (re-search-forward re end t)
16513 (setq level (- (match-end 1) (match-beginning 1)))
16514 (when (and (>= level lmin) (<= level lmax))
16515 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16516 (when (= cnt 0)
16517 (error "Heading not found on level %d: %s" lmax heading))
16518 (when (> cnt 1)
16519 (error "Heading not unique on level %d: %s" lmax heading))
16520 (goto-char found)
16521 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16522 (setq end (save-excursion (org-end-of-subtree t t)))))
16523 (when (org-at-heading-p)
16524 (point-marker))))))
16526 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16527 "Find node HEADING in BUFFER.
16528 Return a marker to the heading if it was found, or nil if not.
16529 If POS-ONLY is set, return just the position instead of a marker.
16531 The heading text must match exact, but it may have a TODO keyword,
16532 a priority cookie and tags in the standard locations."
16533 (with-current-buffer (or buffer (current-buffer))
16534 (save-excursion
16535 (save-restriction
16536 (widen)
16537 (goto-char (point-min))
16538 (let (case-fold-search)
16539 (when (re-search-forward
16540 (format org-complex-heading-regexp-format
16541 (regexp-quote heading)) nil t)
16542 (if pos-only
16543 (match-beginning 0)
16544 (move-marker (make-marker) (match-beginning 0)))))))))
16546 (defun org-find-exact-heading-in-directory (heading &optional dir)
16547 "Find Org node headline HEADING in all .org files in directory DIR.
16548 When the target headline is found, return a marker to this location."
16549 (let ((files (directory-files (or dir default-directory)
16550 t "\\`[^.#].*\\.org\\'"))
16551 visiting m buffer)
16552 (catch 'found
16553 (dolist (file files)
16554 (message "trying %s" file)
16555 (setq visiting (org-find-base-buffer-visiting file))
16556 (setq buffer (or visiting (find-file-noselect file)))
16557 (setq m (org-find-exact-headline-in-buffer
16558 heading buffer))
16559 (when (and (not m) (not visiting)) (kill-buffer buffer))
16560 (and m (throw 'found m))))))
16562 (defun org-find-entry-with-id (ident)
16563 "Locate the entry that contains the ID property with exact value IDENT.
16564 IDENT can be a string, a symbol or a number, this function will search for
16565 the string representation of it.
16566 Return the position where this entry starts, or nil if there is no such entry."
16567 (interactive "sID: ")
16568 (let ((id (cond
16569 ((stringp ident) ident)
16570 ((symbolp ident) (symbol-name ident))
16571 ((numberp ident) (number-to-string ident))
16572 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16573 (org-with-wide-buffer (org-find-property "ID" id))))
16575 ;;;; Timestamps
16577 (defvar org-last-changed-timestamp nil)
16578 (defvar org-last-inserted-timestamp nil
16579 "The last time stamp inserted with `org-insert-time-stamp'.")
16580 (defvar org-ts-what) ; dynamically scoped parameter
16582 (defun org-time-stamp (arg &optional inactive)
16583 "Prompt for a date/time and insert a time stamp.
16585 If the user specifies a time like HH:MM or if this command is
16586 called with at least one prefix argument, the time stamp contains
16587 the date and the time. Otherwise, only the date is included.
16589 All parts of a date not specified by the user are filled in from
16590 the timestamp at point, if any, or the current date/time
16591 otherwise.
16593 If there is already a timestamp at the cursor, it is replaced.
16595 With two universal prefix arguments, insert an active timestamp
16596 with the current time without prompting the user.
16598 When called from lisp, the timestamp is inactive if INACTIVE is
16599 non-nil."
16600 (interactive "P")
16601 (let* ((ts (cond
16602 ((org-at-date-range-p t)
16603 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16604 ((org-at-timestamp-p t) (match-string 0))))
16605 ;; Default time is either the timestamp at point or today.
16606 ;; When entering a range, only the range start is considered.
16607 (default-time (if (not ts) (current-time)
16608 (apply #'encode-time (org-parse-time-string ts))))
16609 (default-input (and ts (org-get-compact-tod ts)))
16610 (repeater (and ts
16611 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16612 (match-string 0 ts)))
16613 org-time-was-given
16614 org-end-time-was-given
16615 (time
16616 (and (if (equal arg '(16)) (current-time)
16617 ;; Preserve `this-command' and `last-command'.
16618 (let ((this-command this-command)
16619 (last-command last-command))
16620 (org-read-date
16621 arg 'totime nil nil default-time default-input
16622 inactive))))))
16623 (cond
16624 ((and ts
16625 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16626 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16627 (insert "--")
16628 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16630 ;; Make sure we're on a timestamp. When in the middle of a date
16631 ;; range, move arbitrarily to range end.
16632 (unless (org-at-timestamp-p t)
16633 (skip-chars-forward "-")
16634 (org-at-timestamp-p t))
16635 (replace-match "")
16636 (setq org-last-changed-timestamp
16637 (org-insert-time-stamp
16638 time (or org-time-was-given arg)
16639 inactive nil nil (list org-end-time-was-given)))
16640 (when repeater
16641 (backward-char)
16642 (insert " " repeater)
16643 (setq org-last-changed-timestamp
16644 (concat (substring org-last-inserted-timestamp 0 -1)
16645 " " repeater ">")))
16646 (message "Timestamp updated"))
16647 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16648 (t (org-insert-time-stamp
16649 time (or org-time-was-given arg) inactive nil nil
16650 (list org-end-time-was-given))))))
16652 ;; FIXME: can we use this for something else, like computing time differences?
16653 (defun org-get-compact-tod (s)
16654 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16655 (let* ((t1 (match-string 1 s))
16656 (h1 (string-to-number (match-string 2 s)))
16657 (m1 (string-to-number (match-string 3 s)))
16658 (t2 (and (match-end 4) (match-string 5 s)))
16659 (h2 (and t2 (string-to-number (match-string 6 s))))
16660 (m2 (and t2 (string-to-number (match-string 7 s))))
16661 dh dm)
16662 (if (not t2)
16664 (setq dh (- h2 h1) dm (- m2 m1))
16665 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16666 (concat t1 "+" (number-to-string dh)
16667 (and (/= 0 dm) (format ":%02d" dm)))))))
16669 (defun org-time-stamp-inactive (&optional arg)
16670 "Insert an inactive time stamp.
16671 An inactive time stamp is enclosed in square brackets instead of angle
16672 brackets. It is inactive in the sense that it does not trigger agenda entries,
16673 does not link to the calendar and cannot be changed with the S-cursor keys.
16674 So these are more for recording a certain time/date."
16675 (interactive "P")
16676 (org-time-stamp arg 'inactive))
16678 (defvar org-date-ovl (make-overlay 1 1))
16679 (overlay-put org-date-ovl 'face 'org-date-selected)
16680 (org-detach-overlay org-date-ovl)
16682 (defvar org-ans1) ; dynamically scoped parameter
16683 (defvar org-ans2) ; dynamically scoped parameter
16685 (defvar org-plain-time-of-day-regexp) ; defined below
16687 (defvar org-overriding-default-time nil) ; dynamically scoped
16688 (defvar org-read-date-overlay nil)
16689 (defvar org-dcst nil) ; dynamically scoped
16690 (defvar org-read-date-history nil)
16691 (defvar org-read-date-final-answer nil)
16692 (defvar org-read-date-analyze-futurep nil)
16693 (defvar org-read-date-analyze-forced-year nil)
16694 (defvar org-read-date-inactive)
16696 (defvar org-read-date-minibuffer-local-map
16697 (let* ((map (make-sparse-keymap)))
16698 (set-keymap-parent map minibuffer-local-map)
16699 (org-defkey map (kbd ".")
16700 (lambda () (interactive)
16701 ;; Are we at the beginning of the prompt?
16702 (if (org-looking-back "^[^:]+: "
16703 (let ((inhibit-field-text-motion t))
16704 (line-beginning-position)))
16705 (org-eval-in-calendar '(calendar-goto-today))
16706 (insert "."))))
16707 (org-defkey map (kbd "C-.")
16708 (lambda () (interactive)
16709 (org-eval-in-calendar '(calendar-goto-today))))
16710 (org-defkey map [(meta shift left)]
16711 (lambda () (interactive)
16712 (org-eval-in-calendar '(calendar-backward-month 1))))
16713 (org-defkey map [(meta shift right)]
16714 (lambda () (interactive)
16715 (org-eval-in-calendar '(calendar-forward-month 1))))
16716 (org-defkey map [(meta shift up)]
16717 (lambda () (interactive)
16718 (org-eval-in-calendar '(calendar-backward-year 1))))
16719 (org-defkey map [(meta shift down)]
16720 (lambda () (interactive)
16721 (org-eval-in-calendar '(calendar-forward-year 1))))
16722 (org-defkey map [?\e (shift left)]
16723 (lambda () (interactive)
16724 (org-eval-in-calendar '(calendar-backward-month 1))))
16725 (org-defkey map [?\e (shift right)]
16726 (lambda () (interactive)
16727 (org-eval-in-calendar '(calendar-forward-month 1))))
16728 (org-defkey map [?\e (shift up)]
16729 (lambda () (interactive)
16730 (org-eval-in-calendar '(calendar-backward-year 1))))
16731 (org-defkey map [?\e (shift down)]
16732 (lambda () (interactive)
16733 (org-eval-in-calendar '(calendar-forward-year 1))))
16734 (org-defkey map [(shift up)]
16735 (lambda () (interactive)
16736 (org-eval-in-calendar '(calendar-backward-week 1))))
16737 (org-defkey map [(shift down)]
16738 (lambda () (interactive)
16739 (org-eval-in-calendar '(calendar-forward-week 1))))
16740 (org-defkey map [(shift left)]
16741 (lambda () (interactive)
16742 (org-eval-in-calendar '(calendar-backward-day 1))))
16743 (org-defkey map [(shift right)]
16744 (lambda () (interactive)
16745 (org-eval-in-calendar '(calendar-forward-day 1))))
16746 (org-defkey map "!"
16747 (lambda () (interactive)
16748 (org-eval-in-calendar '(diary-view-entries))
16749 (message "")))
16750 (org-defkey map ">"
16751 (lambda () (interactive)
16752 (org-eval-in-calendar '(calendar-scroll-left 1))))
16753 (org-defkey map "<"
16754 (lambda () (interactive)
16755 (org-eval-in-calendar '(calendar-scroll-right 1))))
16756 (org-defkey map "\C-v"
16757 (lambda () (interactive)
16758 (org-eval-in-calendar
16759 '(calendar-scroll-left-three-months 1))))
16760 (org-defkey map "\M-v"
16761 (lambda () (interactive)
16762 (org-eval-in-calendar
16763 '(calendar-scroll-right-three-months 1))))
16764 map)
16765 "Keymap for minibuffer commands when using `org-read-date'.")
16767 (defvar org-def)
16768 (defvar org-defdecode)
16769 (defvar org-with-time)
16771 (defvar calendar-setup) ; Dynamically scoped.
16772 (defun org-read-date (&optional with-time to-time from-string prompt
16773 default-time default-input inactive)
16774 "Read a date, possibly a time, and make things smooth for the user.
16775 The prompt will suggest to enter an ISO date, but you can also enter anything
16776 which will at least partially be understood by `parse-time-string'.
16777 Unrecognized parts of the date will default to the current day, month, year,
16778 hour and minute. If this command is called to replace a timestamp at point,
16779 or to enter the second timestamp of a range, the default time is taken
16780 from the existing stamp. Furthermore, the command prefers the future,
16781 so if you are giving a date where the year is not given, and the day-month
16782 combination is already past in the current year, it will assume you
16783 mean next year. For details, see the manual. A few examples:
16785 3-2-5 --> 2003-02-05
16786 feb 15 --> currentyear-02-15
16787 2/15 --> currentyear-02-15
16788 sep 12 9 --> 2009-09-12
16789 12:45 --> today 12:45
16790 22 sept 0:34 --> currentyear-09-22 0:34
16791 12 --> currentyear-currentmonth-12
16792 Fri --> nearest Friday after today
16793 -Tue --> last Tuesday
16794 etc.
16796 Furthermore you can specify a relative date by giving, as the *first* thing
16797 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16798 change in days weeks, months, years.
16799 With a single plus or minus, the date is relative to today. With a double
16800 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16801 +4d --> four days from today
16802 +4 --> same as above
16803 +2w --> two weeks from today
16804 ++5 --> five days from default date
16806 The function understands only English month and weekday abbreviations.
16808 While prompting, a calendar is popped up - you can also select the
16809 date with the mouse (button 1). The calendar shows a period of three
16810 months. To scroll it to other months, use the keys `>' and `<'.
16811 If you don't like the calendar, turn it off with
16812 (setq org-read-date-popup-calendar nil)
16814 With optional argument TO-TIME, the date will immediately be converted
16815 to an internal time.
16816 With an optional argument WITH-TIME, the prompt will suggest to
16817 also insert a time. Note that when WITH-TIME is not set, you can
16818 still enter a time, and this function will inform the calling routine
16819 about this change. The calling routine may then choose to change the
16820 format used to insert the time stamp into the buffer to include the time.
16821 With optional argument FROM-STRING, read from this string instead from
16822 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16823 the time/date that is used for everything that is not specified by the
16824 user."
16825 (require 'parse-time)
16826 (let* ((org-with-time with-time)
16827 (org-time-stamp-rounding-minutes
16828 (if (equal org-with-time '(16))
16829 '(0 0)
16830 org-time-stamp-rounding-minutes))
16831 (org-dcst org-display-custom-times)
16832 (ct (org-current-time))
16833 (org-def (or org-overriding-default-time default-time ct))
16834 (org-defdecode (decode-time org-def))
16835 (cur-frame (selected-frame))
16836 (mouse-autoselect-window nil) ; Don't let the mouse jump
16837 (calendar-setup
16838 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16839 (calendar-move-hook nil)
16840 (calendar-view-diary-initially-flag nil)
16841 (calendar-view-holidays-initially-flag nil)
16842 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16843 ;; Rationalize `org-def' and `org-defdecode', if required.
16844 (when (< (nth 2 org-defdecode) org-extend-today-until)
16845 (setf (nth 2 org-defdecode) -1)
16846 (setf (nth 1 org-defdecode) 59)
16847 (setq org-def (apply #'encode-time org-defdecode))
16848 (setq org-defdecode (decode-time org-def)))
16849 (let* ((timestr (format-time-string
16850 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16851 org-def))
16852 (prompt (concat (if prompt (concat prompt " ") "")
16853 (format "Date+time [%s]: " timestr))))
16854 (cond
16855 (from-string (setq ans from-string))
16856 (org-read-date-popup-calendar
16857 (save-excursion
16858 (save-window-excursion
16859 (calendar)
16860 (when (eq calendar-setup 'calendar-only)
16861 (setq cal-frame
16862 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16863 (select-frame cal-frame))
16864 (org-eval-in-calendar '(setq cursor-type nil) t)
16865 (unwind-protect
16866 (progn
16867 (calendar-forward-day (- (time-to-days org-def)
16868 (calendar-absolute-from-gregorian
16869 (calendar-current-date))))
16870 (org-eval-in-calendar nil t)
16871 (let* ((old-map (current-local-map))
16872 (map (copy-keymap calendar-mode-map))
16873 (minibuffer-local-map
16874 (copy-keymap org-read-date-minibuffer-local-map)))
16875 (org-defkey map (kbd "RET") 'org-calendar-select)
16876 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16877 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16878 (unwind-protect
16879 (progn
16880 (use-local-map map)
16881 (setq org-read-date-inactive inactive)
16882 (add-hook 'post-command-hook 'org-read-date-display)
16883 (setq org-ans0
16884 (read-string prompt
16885 default-input
16886 'org-read-date-history
16887 nil))
16888 ;; org-ans0: from prompt
16889 ;; org-ans1: from mouse click
16890 ;; org-ans2: from calendar motion
16891 (setq ans
16892 (concat org-ans0 " " (or org-ans1 org-ans2))))
16893 (remove-hook 'post-command-hook 'org-read-date-display)
16894 (use-local-map old-map)
16895 (when org-read-date-overlay
16896 (delete-overlay org-read-date-overlay)
16897 (setq org-read-date-overlay nil)))))
16898 (bury-buffer "*Calendar*")
16899 (when cal-frame
16900 (delete-frame cal-frame)
16901 (select-frame-set-input-focus cur-frame))))))
16903 (t ; Naked prompt only
16904 (unwind-protect
16905 (setq ans (read-string prompt default-input
16906 'org-read-date-history timestr))
16907 (when org-read-date-overlay
16908 (delete-overlay org-read-date-overlay)
16909 (setq org-read-date-overlay nil))))))
16911 (setq final (org-read-date-analyze ans org-def org-defdecode))
16913 (when org-read-date-analyze-forced-year
16914 (message "Year was forced into %s"
16915 (if org-read-date-force-compatible-dates
16916 "compatible range (1970-2037)"
16917 "range representable on this machine"))
16918 (ding))
16920 ;; One round trip to get rid of 34th of August and stuff like that....
16921 (setq final (decode-time (apply 'encode-time final)))
16923 (setq org-read-date-final-answer ans)
16925 (if to-time
16926 (apply 'encode-time final)
16927 (if (and (boundp 'org-time-was-given) org-time-was-given)
16928 (format "%04d-%02d-%02d %02d:%02d"
16929 (nth 5 final) (nth 4 final) (nth 3 final)
16930 (nth 2 final) (nth 1 final))
16931 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16933 (defun org-read-date-display ()
16934 "Display the current date prompt interpretation in the minibuffer."
16935 (when org-read-date-display-live
16936 (when org-read-date-overlay
16937 (delete-overlay org-read-date-overlay))
16938 (when (minibufferp (current-buffer))
16939 (save-excursion
16940 (end-of-line 1)
16941 (while (not (equal (buffer-substring
16942 (max (point-min) (- (point) 4)) (point))
16943 " "))
16944 (insert " ")))
16945 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16946 " " (or org-ans1 org-ans2)))
16947 (org-end-time-was-given nil)
16948 (f (org-read-date-analyze ans org-def org-defdecode))
16949 (fmts (if org-dcst
16950 org-time-stamp-custom-formats
16951 org-time-stamp-formats))
16952 (fmt (if (or org-with-time
16953 (and (boundp 'org-time-was-given) org-time-was-given))
16954 (cdr fmts)
16955 (car fmts)))
16956 (txt (format-time-string fmt (apply 'encode-time f)))
16957 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16958 (txt (concat "=> " txt)))
16959 (when (and org-end-time-was-given
16960 (string-match org-plain-time-of-day-regexp txt))
16961 (setq txt (concat (substring txt 0 (match-end 0)) "-"
16962 org-end-time-was-given
16963 (substring txt (match-end 0)))))
16964 (when org-read-date-analyze-futurep
16965 (setq txt (concat txt " (=>F)")))
16966 (setq org-read-date-overlay
16967 (make-overlay (1- (point-at-eol)) (point-at-eol)))
16968 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
16970 (defun org-read-date-analyze (ans def defdecode)
16971 "Analyze the combined answer of the date prompt."
16972 ;; FIXME: cleanup and comment
16973 ;; Pass `current-time' result to `decode-time' (instead of calling
16974 ;; without arguments) so that only `current-time' has to be
16975 ;; overriden in tests.
16976 (let ((org-def def)
16977 (org-defdecode defdecode)
16978 (nowdecode (decode-time (current-time)))
16979 delta deltan deltaw deltadef year month day
16980 hour minute second wday pm h2 m2 tl wday1
16981 iso-year iso-weekday iso-week iso-date futurep kill-year)
16982 (setq org-read-date-analyze-futurep nil
16983 org-read-date-analyze-forced-year nil)
16984 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
16985 (setq ans "+0"))
16987 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
16988 (setq ans (replace-match "" t t ans)
16989 deltan (car delta)
16990 deltaw (nth 1 delta)
16991 deltadef (nth 2 delta)))
16993 ;; Check if there is an iso week date in there. If yes, store the
16994 ;; info and postpone interpreting it until the rest of the parsing
16995 ;; is done.
16996 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
16997 (setq iso-year (when (match-end 1)
16998 (org-small-year-to-year
16999 (string-to-number (match-string 1 ans))))
17000 iso-weekday (when (match-end 3)
17001 (string-to-number (match-string 3 ans)))
17002 iso-week (string-to-number (match-string 2 ans)))
17003 (setq ans (replace-match "" t t ans)))
17005 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17006 (when (string-match
17007 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17008 (setq year (if (match-end 2)
17009 (string-to-number (match-string 2 ans))
17010 (progn (setq kill-year t)
17011 (string-to-number (format-time-string "%Y"))))
17012 month (string-to-number (match-string 3 ans))
17013 day (string-to-number (match-string 4 ans)))
17014 (when (< year 100) (setq year (+ 2000 year)))
17015 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17016 t nil ans)))
17018 ;; Help matching dotted european dates
17019 (when (string-match
17020 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17021 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17022 (setq kill-year t)
17023 (string-to-number (format-time-string "%Y")))
17024 day (string-to-number (match-string 1 ans))
17025 month (string-to-number (match-string 2 ans))
17026 ans (replace-match (format "%04d-%02d-%02d" year month day)
17027 t nil ans)))
17029 ;; Help matching american dates, like 5/30 or 5/30/7
17030 (when (string-match
17031 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17032 (setq year (if (match-end 4)
17033 (string-to-number (match-string 4 ans))
17034 (progn (setq kill-year t)
17035 (string-to-number (format-time-string "%Y"))))
17036 month (string-to-number (match-string 1 ans))
17037 day (string-to-number (match-string 2 ans)))
17038 (when (< year 100) (setq year (+ 2000 year)))
17039 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17040 t nil ans)))
17041 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17042 ;; If there is a time with am/pm, and *no* time without it, we convert
17043 ;; so that matching will be successful.
17044 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17045 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17046 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17047 (setq hour (string-to-number (match-string 1 ans))
17048 minute (if (match-end 3)
17049 (string-to-number (match-string 3 ans))
17051 pm (equal ?p
17052 (string-to-char (downcase (match-string 4 ans)))))
17053 (if (and (= hour 12) (not pm))
17054 (setq hour 0)
17055 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17056 (setq ans (replace-match (format "%02d:%02d" hour minute)
17057 t t ans))))
17059 ;; Check if a time range is given as a duration
17060 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17061 (setq hour (string-to-number (match-string 1 ans))
17062 h2 (+ hour (string-to-number (match-string 3 ans)))
17063 minute (string-to-number (match-string 2 ans))
17064 m2 (+ minute (if (match-end 5) (string-to-number
17065 (match-string 5 ans))0)))
17066 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17067 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17068 t t ans)))
17070 ;; Check if there is a time range
17071 (when (boundp 'org-end-time-was-given)
17072 (setq org-time-was-given nil)
17073 (when (and (string-match org-plain-time-of-day-regexp ans)
17074 (match-end 8))
17075 (setq org-end-time-was-given (match-string 8 ans))
17076 (setq ans (concat (substring ans 0 (match-beginning 7))
17077 (substring ans (match-end 7))))))
17079 (setq tl (parse-time-string ans)
17080 day (or (nth 3 tl) (nth 3 org-defdecode))
17081 month
17082 (cond ((nth 4 tl))
17083 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17084 ;; Day was specified. Make sure DAY+MONTH
17085 ;; combination happens in the future.
17086 ((nth 3 tl)
17087 (setq futurep t)
17088 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17089 (nth 4 nowdecode)))
17090 (t (nth 4 org-defdecode)))
17091 year
17092 (cond ((and (not kill-year) (nth 5 tl)))
17093 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17094 ;; Month was guessed in the future and is at least
17095 ;; equal to NOWDECODE's. Fix year accordingly.
17096 (futurep
17097 (if (or (> month (nth 4 nowdecode))
17098 (>= day (nth 3 nowdecode)))
17099 (nth 5 nowdecode)
17100 (1+ (nth 5 nowdecode))))
17101 ;; Month was specified. Make sure MONTH+YEAR
17102 ;; combination happens in the future.
17103 ((nth 4 tl)
17104 (setq futurep t)
17105 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17106 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17107 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17108 (t (nth 5 nowdecode))))
17109 (t (nth 5 org-defdecode)))
17110 hour (or (nth 2 tl) (nth 2 org-defdecode))
17111 minute (or (nth 1 tl) (nth 1 org-defdecode))
17112 second (or (nth 0 tl) 0)
17113 wday (nth 6 tl))
17115 (when (and (eq org-read-date-prefer-future 'time)
17116 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17117 (equal day (nth 3 nowdecode))
17118 (equal month (nth 4 nowdecode))
17119 (equal year (nth 5 nowdecode))
17120 (nth 2 tl)
17121 (or (< (nth 2 tl) (nth 2 nowdecode))
17122 (and (= (nth 2 tl) (nth 2 nowdecode))
17123 (nth 1 tl)
17124 (< (nth 1 tl) (nth 1 nowdecode)))))
17125 (setq day (1+ day)
17126 futurep t))
17128 ;; Special date definitions below
17129 (cond
17130 (iso-week
17131 ;; There was an iso week
17132 (require 'cal-iso)
17133 (setq futurep nil)
17134 (setq year (or iso-year year)
17135 day (or iso-weekday wday 1)
17136 wday nil ; to make sure that the trigger below does not match
17137 iso-date (calendar-gregorian-from-absolute
17138 (calendar-iso-to-absolute
17139 (list iso-week day year))))
17140 ; FIXME: Should we also push ISO weeks into the future?
17141 ; (when (and org-read-date-prefer-future
17142 ; (not iso-year)
17143 ; (< (calendar-absolute-from-gregorian iso-date)
17144 ; (time-to-days (current-time))))
17145 ; (setq year (1+ year)
17146 ; iso-date (calendar-gregorian-from-absolute
17147 ; (calendar-iso-to-absolute
17148 ; (list iso-week day year)))))
17149 (setq month (car iso-date)
17150 year (nth 2 iso-date)
17151 day (nth 1 iso-date)))
17152 (deltan
17153 (setq futurep nil)
17154 (unless deltadef
17155 ;; Pass `current-time' result to `decode-time' (instead of
17156 ;; calling without arguments) so that only `current-time' has
17157 ;; to be overriden in tests.
17158 (let ((now (decode-time (current-time))))
17159 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17160 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17161 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17162 ((equal deltaw "m") (setq month (+ month deltan)))
17163 ((equal deltaw "y") (setq year (+ year deltan)))))
17164 ((and wday (not (nth 3 tl)))
17165 ;; Weekday was given, but no day, so pick that day in the week
17166 ;; on or after the derived date.
17167 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17168 (unless (equal wday wday1)
17169 (setq day (+ day (% (- wday wday1 -7) 7))))))
17170 (when (and (boundp 'org-time-was-given)
17171 (nth 2 tl))
17172 (setq org-time-was-given t))
17173 (when (< year 100) (setq year (+ 2000 year)))
17174 ;; Check of the date is representable
17175 (if org-read-date-force-compatible-dates
17176 (progn
17177 (when (< year 1970)
17178 (setq year 1970 org-read-date-analyze-forced-year t))
17179 (when (> year 2037)
17180 (setq year 2037 org-read-date-analyze-forced-year t)))
17181 (condition-case nil
17182 (ignore (encode-time second minute hour day month year))
17183 (error
17184 (setq year (nth 5 org-defdecode))
17185 (setq org-read-date-analyze-forced-year t))))
17186 (setq org-read-date-analyze-futurep futurep)
17187 (list second minute hour day month year)))
17189 (defvar parse-time-weekdays)
17190 (defun org-read-date-get-relative (s today default)
17191 "Check string S for special relative date string.
17192 TODAY and DEFAULT are internal times, for today and for a default.
17193 Return shift list (N what def-flag)
17194 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17195 N is the number of WHATs to shift.
17196 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17197 the DEFAULT date rather than TODAY."
17198 (require 'parse-time)
17199 (when (and
17200 (string-match
17201 (concat
17202 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17203 "\\([0-9]+\\)?"
17204 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17205 "\\([ \t]\\|$\\)") s)
17206 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17207 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17208 (string-to-char (substring (match-string 1 s) -1))
17209 ?+))
17210 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17211 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17212 (what (if (match-end 3) (match-string 3 s) "d"))
17213 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17214 (date (if rel default today))
17215 (wday (nth 6 (decode-time date)))
17216 delta)
17217 (if wday1
17218 (progn
17219 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17220 (when (= delta 0) (setq delta 7))
17221 (when (= dir ?-)
17222 (setq delta (- delta 7))
17223 (when (= delta 0) (setq delta -7)))
17224 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17225 (list delta "d" rel))
17226 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17228 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17229 "Turn a user-specified date into the internal representation.
17230 The internal representation needed by the calendar is (month day year).
17231 This is a wrapper to handle the brain-dead convention in calendar that
17232 user function argument order change dependent on argument order."
17233 (if (boundp 'calendar-date-style)
17234 (cond
17235 ((eq calendar-date-style 'american)
17236 (list arg1 arg2 arg3))
17237 ((eq calendar-date-style 'european)
17238 (list arg2 arg1 arg3))
17239 ((eq calendar-date-style 'iso)
17240 (list arg2 arg3 arg1)))
17241 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17242 (if (org-bound-and-true-p european-calendar-style)
17243 (list arg2 arg1 arg3)
17244 (list arg1 arg2 arg3)))))
17246 (defun org-eval-in-calendar (form &optional keepdate)
17247 "Eval FORM in the calendar window and return to current window.
17248 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17249 (let ((sf (selected-frame))
17250 (sw (selected-window)))
17251 (select-window (get-buffer-window "*Calendar*" t))
17252 (eval form)
17253 (when (and (not keepdate) (calendar-cursor-to-date))
17254 (let* ((date (calendar-cursor-to-date))
17255 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17256 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17257 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17258 (select-window sw)
17259 (org-select-frame-set-input-focus sf)))
17261 (defun org-calendar-select ()
17262 "Return to `org-read-date' with the date currently selected.
17263 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17264 (interactive)
17265 (when (calendar-cursor-to-date)
17266 (let* ((date (calendar-cursor-to-date))
17267 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17268 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17269 (when (active-minibuffer-window) (exit-minibuffer))))
17271 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17272 "Insert a date stamp for the date given by the internal TIME.
17273 See `format-time-string' for the format of TIME.
17274 WITH-HM means use the stamp format that includes the time of the day.
17275 INACTIVE means use square brackets instead of angular ones, so that the
17276 stamp will not contribute to the agenda.
17277 PRE and POST are optional strings to be inserted before and after the
17278 stamp.
17279 The command returns the inserted time stamp."
17280 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17281 stamp)
17282 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17283 (insert-before-markers (or pre ""))
17284 (when (listp extra)
17285 (setq extra (car extra))
17286 (if (and (stringp extra)
17287 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17288 (setq extra (format "-%02d:%02d"
17289 (string-to-number (match-string 1 extra))
17290 (string-to-number (match-string 2 extra))))
17291 (setq extra nil)))
17292 (when extra
17293 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17294 (insert-before-markers (setq stamp (format-time-string fmt time)))
17295 (insert-before-markers (or post ""))
17296 (setq org-last-inserted-timestamp stamp)))
17298 (defun org-toggle-time-stamp-overlays ()
17299 "Toggle the use of custom time stamp formats."
17300 (interactive)
17301 (setq org-display-custom-times (not org-display-custom-times))
17302 (unless org-display-custom-times
17303 (let ((p (point-min)) (bmp (buffer-modified-p)))
17304 (while (setq p (next-single-property-change p 'display))
17305 (when (and (get-text-property p 'display)
17306 (eq (get-text-property p 'face) 'org-date))
17307 (remove-text-properties
17308 p (setq p (next-single-property-change p 'display))
17309 '(display t))))
17310 (set-buffer-modified-p bmp)))
17311 (when (featurep 'xemacs)
17312 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17313 (org-restart-font-lock)
17314 (setq org-table-may-need-update t)
17315 (if org-display-custom-times
17316 (message "Time stamps are overlaid with custom format")
17317 (message "Time stamp overlays removed")))
17319 (defun org-display-custom-time (beg end)
17320 "Overlay modified time stamp format over timestamp between BEG and END."
17321 (let* ((ts (buffer-substring beg end))
17322 t1 w1 with-hm tf time str w2 (off 0))
17323 (save-match-data
17324 (setq t1 (org-parse-time-string ts t))
17325 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17326 (setq off (- (match-end 0) (match-beginning 0)))))
17327 (setq end (- end off))
17328 (setq w1 (- end beg)
17329 with-hm (and (nth 1 t1) (nth 2 t1))
17330 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17331 time (org-fix-decoded-time t1)
17332 str (org-add-props
17333 (format-time-string
17334 (substring tf 1 -1) (apply 'encode-time time))
17335 nil 'mouse-face 'highlight)
17336 w2 (length str))
17337 (unless (= w2 w1)
17338 (add-text-properties (1+ beg) (+ 2 beg)
17339 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17340 (if (featurep 'xemacs)
17341 (progn
17342 (put-text-property beg end 'invisible t)
17343 (put-text-property beg end 'end-glyph (make-glyph str)))
17344 (put-text-property beg end 'display str))))
17346 (defun org-fix-decoded-time (time)
17347 "Set 0 instead of nil for the first 6 elements of time.
17348 Don't touch the rest."
17349 (let ((n 0))
17350 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17352 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17354 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17355 "Difference between TIMESTAMP-STRING and now in days.
17356 If SECONDS is non-nil, return the difference in seconds."
17357 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17358 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17359 (funcall fdiff (current-time)))))
17361 (defun org-deadline-close (timestamp-string &optional ndays)
17362 "Is the time in TIMESTAMP-STRING close to the current date?"
17363 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17364 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17365 (not (org-entry-is-done-p))))
17367 (defun org-get-wdays (ts &optional delay zero-delay)
17368 "Get the deadline lead time appropriate for timestring TS.
17369 When DELAY is non-nil, get the delay time for scheduled items
17370 instead of the deadline lead time. When ZERO-DELAY is non-nil
17371 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17372 don't try to find the delay cookie in the scheduled timestamp."
17373 (let ((tv (if delay org-scheduled-delay-days
17374 org-deadline-warning-days)))
17375 (cond
17376 ((or (and delay (< tv 0))
17377 (and delay zero-delay (<= tv 0))
17378 (and (not delay) (<= tv 0)))
17379 ;; Enforce this value no matter what
17380 (- tv))
17381 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17382 ;; lead time is specified.
17383 (floor (* (string-to-number (match-string 1 ts))
17384 (cdr (assoc (match-string 2 ts)
17385 '(("d" . 1) ("w" . 7)
17386 ("m" . 30.4) ("y" . 365.25)
17387 ("h" . 0.041667)))))))
17388 ;; go for the default.
17389 (t tv))))
17391 (defun org-calendar-select-mouse (ev)
17392 "Return to `org-read-date' with the date currently selected.
17393 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17394 (interactive "e")
17395 (mouse-set-point ev)
17396 (when (calendar-cursor-to-date)
17397 (let* ((date (calendar-cursor-to-date))
17398 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17399 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17400 (when (active-minibuffer-window) (exit-minibuffer))))
17402 (defun org-check-deadlines (ndays)
17403 "Check if there are any deadlines due or past due.
17404 A deadline is considered due if it happens within `org-deadline-warning-days'
17405 days from today's date. If the deadline appears in an entry marked DONE,
17406 it is not shown. The prefix arg NDAYS can be used to test that many
17407 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17408 (interactive "P")
17409 (let* ((org-warn-days
17410 (cond
17411 ((equal ndays '(4)) 100000)
17412 (ndays (prefix-numeric-value ndays))
17413 (t (abs org-deadline-warning-days))))
17414 (case-fold-search nil)
17415 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17416 (callback
17417 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17418 (message "%d deadlines past-due or due within %d days"
17419 (org-occur regexp nil callback)
17420 org-warn-days)))
17422 (defsubst org-re-timestamp (type)
17423 "Return a regexp for timestamp TYPE.
17424 Allowed values for TYPE are:
17426 all: all timestamps
17427 active: only active timestamps (<...>)
17428 inactive: only inactive timestamps ([...])
17429 scheduled: only scheduled timestamps
17430 deadline: only deadline timestamps
17431 closed: only closed time-stamps
17433 When TYPE is nil, fall back on returning a regexp that matches
17434 both scheduled and deadline timestamps."
17435 (cl-case type
17436 (all org-ts-regexp-both)
17437 (active org-ts-regexp)
17438 (inactive org-ts-regexp-inactive)
17439 (scheduled org-scheduled-time-regexp)
17440 (deadline org-deadline-time-regexp)
17441 (closed org-closed-time-regexp)
17442 (otherwise
17443 (concat "\\<"
17444 (regexp-opt (list org-deadline-string org-scheduled-string))
17445 " *<\\([^>]+\\)>"))))
17447 (defun org-check-before-date (d)
17448 "Check if there are deadlines or scheduled entries before date D."
17449 (interactive (list (org-read-date)))
17450 (let* ((case-fold-search nil)
17451 (regexp (org-re-timestamp org-ts-type))
17452 (ts-type org-ts-type)
17453 (callback
17454 (lambda ()
17455 (let ((match (match-string 1)))
17456 (and (if (memq ts-type '(active inactive all))
17457 (eq (org-element-type (org-element-context)) 'timestamp)
17458 (org-at-planning-p))
17459 (time-less-p
17460 (org-time-string-to-time match)
17461 (org-time-string-to-time d)))))))
17462 (message "%d entries before %s"
17463 (org-occur regexp nil callback)
17464 d)))
17466 (defun org-check-after-date (d)
17467 "Check if there are deadlines or scheduled entries after date D."
17468 (interactive (list (org-read-date)))
17469 (let* ((case-fold-search nil)
17470 (regexp (org-re-timestamp org-ts-type))
17471 (ts-type org-ts-type)
17472 (callback
17473 (lambda ()
17474 (let ((match (match-string 1)))
17475 (and (if (memq ts-type '(active inactive all))
17476 (eq (org-element-type (org-element-context)) 'timestamp)
17477 (org-at-planning-p))
17478 (not (time-less-p
17479 (org-time-string-to-time match)
17480 (org-time-string-to-time d))))))))
17481 (message "%d entries after %s"
17482 (org-occur regexp nil callback)
17483 d)))
17485 (defun org-check-dates-range (start-date end-date)
17486 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17487 (interactive (list (org-read-date nil nil nil "Range starts")
17488 (org-read-date nil nil nil "Range end")))
17489 (let ((case-fold-search nil)
17490 (regexp (org-re-timestamp org-ts-type))
17491 (callback
17492 `(lambda ()
17493 (let ((match (match-string 1)))
17494 (and
17495 ,(if (memq org-ts-type '(active inactive all))
17496 '(eq (org-element-type (org-element-context)) 'timestamp)
17497 '(org-at-planning-p))
17498 (not (time-less-p
17499 (org-time-string-to-time match)
17500 (org-time-string-to-time start-date)))
17501 (time-less-p
17502 (org-time-string-to-time match)
17503 (org-time-string-to-time end-date)))))))
17504 (message "%d entries between %s and %s"
17505 (org-occur regexp nil callback) start-date end-date)))
17507 (defun org-evaluate-time-range (&optional to-buffer)
17508 "Evaluate a time range by computing the difference between start and end.
17509 Normally the result is just printed in the echo area, but with prefix arg
17510 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17511 If the time range is actually in a table, the result is inserted into the
17512 next column.
17513 For time difference computation, a year is assumed to be exactly 365
17514 days in order to avoid rounding problems."
17515 (interactive "P")
17517 (org-clock-update-time-maybe)
17518 (save-excursion
17519 (unless (org-at-date-range-p t)
17520 (goto-char (point-at-bol))
17521 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17522 (unless (org-at-date-range-p t)
17523 (user-error "Not at a time-stamp range, and none found in current line")))
17524 (let* ((ts1 (match-string 1))
17525 (ts2 (match-string 2))
17526 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17527 (match-end (match-end 0))
17528 (time1 (org-time-string-to-time ts1))
17529 (time2 (org-time-string-to-time ts2))
17530 (t1 (org-float-time time1))
17531 (t2 (org-float-time time2))
17532 (diff (abs (- t2 t1)))
17533 (negative (< (- t2 t1) 0))
17534 ;; (ys (floor (* 365 24 60 60)))
17535 (ds (* 24 60 60))
17536 (hs (* 60 60))
17537 (fy "%dy %dd %02d:%02d")
17538 (fy1 "%dy %dd")
17539 (fd "%dd %02d:%02d")
17540 (fd1 "%dd")
17541 (fh "%02d:%02d")
17542 y d h m align)
17543 (if havetime
17544 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17546 d (floor (/ diff ds)) diff (mod diff ds)
17547 h (floor (/ diff hs)) diff (mod diff hs)
17548 m (floor (/ diff 60)))
17549 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17551 d (floor (+ (/ diff ds) 0.5))
17552 h 0 m 0))
17553 (if (not to-buffer)
17554 (message "%s" (org-make-tdiff-string y d h m))
17555 (if (org-at-table-p)
17556 (progn
17557 (goto-char match-end)
17558 (setq align t)
17559 (and (looking-at " *|") (goto-char (match-end 0))))
17560 (goto-char match-end))
17561 (when (looking-at
17562 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17563 (replace-match ""))
17564 (when negative (insert " -"))
17565 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17566 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17567 (insert " " (format fh h m))))
17568 (when align (org-table-align))
17569 (message "Time difference inserted")))))
17571 (defun org-make-tdiff-string (y d h m)
17572 (let ((fmt "")
17573 (l nil))
17574 (when (> y 0)
17575 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17576 (push y l))
17577 (when (> d 0)
17578 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17579 (push d l))
17580 (when (> h 0)
17581 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17582 (push h l))
17583 (when (> m 0)
17584 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17585 (push m l))
17586 (apply 'format fmt (nreverse l))))
17588 (defun org-time-string-to-time (s &optional buffer pos)
17589 "Convert a timestamp string into internal time."
17590 (condition-case errdata
17591 (apply 'encode-time (org-parse-time-string s))
17592 (error (error "Bad timestamp `%s'%s\nError was: %s"
17593 s (if (not (and buffer pos))
17595 (format-message " at %d in buffer `%s'" pos buffer))
17596 (cdr errdata)))))
17598 (defun org-time-string-to-seconds (s)
17599 "Convert a timestamp string to a number of seconds."
17600 (org-float-time (org-time-string-to-time s)))
17602 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17604 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17605 "Convert time stamp S to an absolute day number.
17607 If DAYNR in non-nil, and there is a specifier for a cyclic time
17608 stamp, get the closest date to DAYNR. If PREFER is
17609 `past' (respectively `future') return a date past (respectively
17610 after) or equal to DAYNR.
17612 POS is the location of time stamp S, as a buffer position in
17613 BUFFER.
17615 Diary sexp timestamps are matched against DAYNR, when non-nil.
17616 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17617 signalled."
17618 (cond
17619 ((string-match "\\`%%\\((.*)\\)" s)
17620 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17621 ;; only able to match individual dates. If it fails, raise an
17622 ;; error.
17623 (if (and daynr
17624 (org-diary-sexp-entry
17625 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17626 daynr
17627 (signal 'org-diary-sexp-no-match (list s))))
17628 ((and daynr show-all) (org-closest-date s daynr prefer))
17629 (t (time-to-days
17630 (condition-case errdata
17631 (apply #'encode-time (org-parse-time-string s))
17632 (error (error "Bad timestamp `%s'%s\nError was: %s"
17634 (if (not (and buffer pos)) ""
17635 (format-message " at %d in buffer `%s'" pos buffer))
17636 (cdr errdata))))))))
17638 (defun org-days-to-iso-week (days)
17639 "Return the iso week number."
17640 (require 'cal-iso)
17641 (car (calendar-iso-from-absolute days)))
17643 (defun org-small-year-to-year (year)
17644 "Convert 2-digit years into 4-digit years.
17645 YEAR is expanded into one of the 30 next years, if possible, or
17646 into a past one. Any year larger than 99 is returned unchanged."
17647 (if (>= year 100) year
17648 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17649 (century (/ current 100))
17650 (offset (- year (% current 100))))
17651 (cond ((> offset 30) (+ (* (1- century) 100) year))
17652 ((> offset -70) (+ (* century 100) year))
17653 (t (+ (* (1+ century) 100) year))))))
17655 (defun org-time-from-absolute (d)
17656 "Return the time corresponding to date D.
17657 D may be an absolute day number, or a calendar-type list (month day year)."
17658 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17659 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17661 (defvar org-agenda-current-date)
17662 (defun org-calendar-holiday ()
17663 "List of holidays, for Diary display in Org mode."
17664 (require 'holidays)
17665 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17666 (and hl (mapconcat #'identity hl "; "))))
17668 (defun org-diary-sexp-entry (sexp entry d)
17669 "Process a SEXP diary ENTRY for date D."
17670 (require 'diary-lib)
17671 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17672 ;; dynamically.
17673 (let* ((sexp `(let ((entry ,entry)
17674 (date ',d))
17675 ,(car (read-from-string sexp))))
17676 (result (if calendar-debug-sexp (eval sexp)
17677 (condition-case nil
17678 (eval sexp)
17679 (error
17680 (beep)
17681 (message "Bad sexp at line %d in %s: %s"
17682 (org-current-line)
17683 (buffer-file-name) sexp)
17684 (sleep-for 2))))))
17685 (cond ((stringp result) (split-string result "; "))
17686 ((and (consp result)
17687 (not (consp (cdr result)))
17688 (stringp (cdr result))) (cdr result))
17689 ((and (consp result)
17690 (stringp (car result))) result)
17691 (result entry))))
17693 (defun org-diary-to-ical-string (frombuf)
17694 "Get iCalendar entries from diary entries in buffer FROMBUF.
17695 This uses the icalendar.el library."
17696 (let* ((tmpdir (if (featurep 'xemacs)
17697 (temp-directory)
17698 temporary-file-directory))
17699 (tmpfile (make-temp-name
17700 (expand-file-name "orgics" tmpdir)))
17701 buf rtn b e)
17702 (with-current-buffer frombuf
17703 (icalendar-export-region (point-min) (point-max) tmpfile)
17704 (setq buf (find-buffer-visiting tmpfile))
17705 (set-buffer buf)
17706 (goto-char (point-min))
17707 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17708 (setq b (match-beginning 0)))
17709 (goto-char (point-max))
17710 (when (re-search-backward "^END:VEVENT" nil t)
17711 (setq e (match-end 0)))
17712 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17713 (kill-buffer buf)
17714 (delete-file tmpfile)
17715 rtn))
17717 (defun org-closest-date (start current prefer)
17718 "Return closest date to CURRENT starting from START.
17720 CURRENT and START are both time stamps.
17722 When PREFER is `past', return a date that is either CURRENT or
17723 past. When PREFER is `future', return a date that is either
17724 CURRENT or future.
17726 Only time stamps with a repeater are modified. Any other time
17727 stamp stay unchanged. In any case, return value is an absolute
17728 day number."
17729 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17730 ;; No repeater. Do not shift time stamp.
17731 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17732 (let ((value (string-to-number (match-string 1 start)))
17733 (type (match-string 2 start)))
17734 (if (= 0 value)
17735 ;; Repeater with a 0-value is considered as void.
17736 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17737 (let* ((base (org-date-to-gregorian start))
17738 (target (org-date-to-gregorian current))
17739 (sday (calendar-absolute-from-gregorian base))
17740 (cday (calendar-absolute-from-gregorian target))
17741 n1 n2)
17742 ;; If START is already past CURRENT, just return START.
17743 (if (<= cday sday) sday
17744 ;; Compute closest date before (N1) and closest date past
17745 ;; (N2) CURRENT.
17746 (pcase type
17747 ("h"
17748 (let ((missing-hours
17749 (mod (+ (- (* 24 (- cday sday))
17750 (nth 2 (org-parse-time-string start)))
17751 org-extend-today-until)
17752 value)))
17753 (setf n1 (if (= missing-hours 0) cday
17754 (- cday (1+ (/ missing-hours 24)))))
17755 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17756 ((or "d" "w")
17757 (let ((value (if (equal type "w") (* 7 value) value)))
17758 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17759 (setf n2 (+ n1 value))))
17760 ("m"
17761 (let* ((add-months
17762 (lambda (d n)
17763 ;; Add N months to gregorian date D, i.e.,
17764 ;; a list (MONTH DAY YEAR). Return a valid
17765 ;; gregorian date.
17766 (let ((m (+ (nth 0 d) n)))
17767 (list (mod m 12)
17768 (nth 1 d)
17769 (+ (/ m 12) (nth 2 d))))))
17770 (months ; Complete months to TARGET.
17771 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17772 (- (nth 0 target) (nth 0 base))
17773 ;; If START's day is greater than
17774 ;; TARGET's, remove incomplete month.
17775 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17776 value)
17777 value))
17778 (before (funcall add-months base months)))
17779 (setf n1 (calendar-absolute-from-gregorian before))
17780 (setf n2
17781 (calendar-absolute-from-gregorian
17782 (funcall add-months before value)))))
17784 (let* ((d (nth 1 base))
17785 (m (nth 0 base))
17786 (y (nth 2 base))
17787 (years ; Complete years to TARGET.
17788 (* (/ (- (nth 2 target)
17790 ;; If START's month and day are
17791 ;; greater than TARGET's, remove
17792 ;; incomplete year.
17793 (if (or (> (nth 0 target) m)
17794 (and (= (nth 0 target) m)
17795 (> (nth 1 target) d)))
17798 value)
17799 value))
17800 (before (list m d (+ y years))))
17801 (setf n1 (calendar-absolute-from-gregorian before))
17802 (setf n2 (calendar-absolute-from-gregorian
17803 (list m d (+ (nth 2 before) value)))))))
17804 ;; Handle PREFER parameter, if any.
17805 (cond
17806 ((eq prefer 'past) (if (= cday n2) n2 n1))
17807 ((eq prefer 'future) (if (= cday n1) n1 n2))
17808 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17810 (defun org-date-to-gregorian (d)
17811 "Turn any specification of date D into a Gregorian date for the calendar."
17812 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17813 ((and (listp d) (= (length d) 3)) d)
17814 ((stringp d)
17815 (let ((d (org-parse-time-string d)))
17816 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17817 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17819 (defun org-parse-time-string (s &optional nodefault)
17820 "Parse the standard Org-mode time string.
17821 This should be a lot faster than the normal `parse-time-string'.
17822 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17823 hour and minute fields will be nil if not given."
17824 (cond ((string-match org-ts-regexp0 s)
17825 (list 0
17826 (when (or (match-beginning 8) (not nodefault))
17827 (string-to-number (or (match-string 8 s) "0")))
17828 (when (or (match-beginning 7) (not nodefault))
17829 (string-to-number (or (match-string 7 s) "0")))
17830 (string-to-number (match-string 4 s))
17831 (string-to-number (match-string 3 s))
17832 (string-to-number (match-string 2 s))
17833 nil nil nil))
17834 ((string-match "^<[^>]+>$" s)
17835 (decode-time (seconds-to-time (org-matcher-time s))))
17836 (t (error "Not a standard Org-mode time string: %s" s))))
17838 (defun org-timestamp-up (&optional arg)
17839 "Increase the date item at the cursor by one.
17840 If the cursor is on the year, change the year. If it is on the month,
17841 the day or the time, change that.
17842 With prefix ARG, change by that many units."
17843 (interactive "p")
17844 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17846 (defun org-timestamp-down (&optional arg)
17847 "Decrease the date item at the cursor by one.
17848 If the cursor is on the year, change the year. If it is on the month,
17849 the day or the time, change that.
17850 With prefix ARG, change by that many units."
17851 (interactive "p")
17852 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17854 (defun org-timestamp-up-day (&optional arg)
17855 "Increase the date in the time stamp by one day.
17856 With prefix ARG, change that many days."
17857 (interactive "p")
17858 (if (and (not (org-at-timestamp-p t))
17859 (org-at-heading-p))
17860 (org-todo 'up)
17861 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17863 (defun org-timestamp-down-day (&optional arg)
17864 "Decrease the date in the time stamp by one day.
17865 With prefix ARG, change that many days."
17866 (interactive "p")
17867 (if (and (not (org-at-timestamp-p t))
17868 (org-at-heading-p))
17869 (org-todo 'down)
17870 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17872 (defun org-at-timestamp-p (&optional inactive-ok)
17873 "Non-nil if point is inside a timestamp.
17875 When optional argument INACTIVE-OK is non-nil, also consider
17876 inactive timestamps.
17878 When this function returns a non-nil value, match data is set
17879 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17880 INACTIVE-OK."
17881 (interactive)
17882 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17883 (pos (point))
17884 (ans (or (looking-at tsr)
17885 (save-excursion
17886 (skip-chars-backward "^[<\n\r\t")
17887 (when (> (point) (point-min)) (backward-char 1))
17888 (and (looking-at tsr)
17889 (> (- (match-end 0) pos) -1))))))
17890 (and ans
17891 (boundp 'org-ts-what)
17892 (setq org-ts-what
17893 (cond
17894 ((= pos (match-beginning 0)) 'bracket)
17895 ;; Point is considered to be "on the bracket" whether
17896 ;; it's really on it or right after it.
17897 ((= pos (1- (match-end 0))) 'bracket)
17898 ((= pos (match-end 0)) 'after)
17899 ((org-pos-in-match-range pos 2) 'year)
17900 ((org-pos-in-match-range pos 3) 'month)
17901 ((org-pos-in-match-range pos 7) 'hour)
17902 ((org-pos-in-match-range pos 8) 'minute)
17903 ((or (org-pos-in-match-range pos 4)
17904 (org-pos-in-match-range pos 5)) 'day)
17905 ((and (> pos (or (match-end 8) (match-end 5)))
17906 (< pos (match-end 0)))
17907 (- pos (or (match-end 8) (match-end 5))))
17908 (t 'day))))
17909 ans))
17911 (defun org-toggle-timestamp-type ()
17912 "Toggle the type (<active> or [inactive]) of a time stamp."
17913 (interactive)
17914 (when (org-at-timestamp-p t)
17915 (let ((beg (match-beginning 0)) (end (match-end 0))
17916 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17917 (save-excursion
17918 (goto-char beg)
17919 (while (re-search-forward "[][<>]" end t)
17920 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17921 t t)))
17922 (message "Timestamp is now %sactive"
17923 (if (equal (char-after beg) ?<) "" "in")))))
17925 (defun org-at-clock-log-p nil
17926 "Is the cursor on the clock log line?"
17927 (save-excursion
17928 (move-beginning-of-line 1)
17929 (looking-at org-clock-line-re)))
17931 (defvar org-clock-history) ; defined in org-clock.el
17932 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17933 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17934 "Change the date in the time stamp at point.
17935 The date will be changed by N times WHAT. WHAT can be `day', `month',
17936 `year', `minute', `second'. If WHAT is not given, the cursor position
17937 in the timestamp determines what will be changed.
17938 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17939 (let ((origin (point)) origin-cat
17940 with-hm inactive
17941 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17942 org-ts-what
17943 extra rem
17944 ts time time0 fixnext clrgx)
17945 (unless (org-at-timestamp-p t)
17946 (user-error "Not at a timestamp"))
17947 (if (and (not what) (eq org-ts-what 'bracket))
17948 (org-toggle-timestamp-type)
17949 ;; Point isn't on brackets. Remember the part of the time-stamp
17950 ;; the point was in. Indeed, size of time-stamps may change,
17951 ;; but point must be kept in the same category nonetheless.
17952 (setq origin-cat org-ts-what)
17953 (when (and (not what) (not (eq org-ts-what 'day))
17954 org-display-custom-times
17955 (get-text-property (point) 'display)
17956 (not (get-text-property (1- (point)) 'display)))
17957 (setq org-ts-what 'day))
17958 (setq org-ts-what (or what org-ts-what)
17959 inactive (= (char-after (match-beginning 0)) ?\[)
17960 ts (match-string 0))
17961 (replace-match "")
17962 (when (string-match
17963 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
17965 (setq extra (match-string 1 ts))
17966 (when suppress-tmp-delay
17967 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
17968 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
17969 (setq with-hm t))
17970 (setq time0 (org-parse-time-string ts))
17971 (when (and updown
17972 (eq org-ts-what 'minute)
17973 (not current-prefix-arg))
17974 ;; This looks like s-up and s-down. Change by one rounding step.
17975 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
17976 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
17977 (setcar (cdr time0) (+ (nth 1 time0)
17978 (if (> n 0) (- rem) (- dm rem))))))
17979 (setq time
17980 (encode-time (or (car time0) 0)
17981 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
17982 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
17983 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
17984 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
17985 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
17986 (nthcdr 6 time0)))
17987 (when (and (member org-ts-what '(hour minute))
17988 extra
17989 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
17990 (setq extra (org-modify-ts-extra
17991 extra
17992 (if (eq org-ts-what 'hour) 2 5)
17993 n dm)))
17994 (when (integerp org-ts-what)
17995 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
17996 (when (eq what 'calendar)
17997 (let ((cal-date (org-get-date-from-calendar)))
17998 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
17999 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18000 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18001 (setcar time0 (or (car time0) 0))
18002 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18003 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18004 (setq time (apply 'encode-time time0))))
18005 ;; Insert the new time-stamp, and ensure point stays in the same
18006 ;; category as before (i.e. not after the last position in that
18007 ;; category).
18008 (let ((pos (point)))
18009 ;; Stay before inserted string. `save-excursion' is of no use.
18010 (setq org-last-changed-timestamp
18011 (org-insert-time-stamp time with-hm inactive nil nil extra))
18012 (goto-char pos))
18013 (save-match-data
18014 (looking-at org-ts-regexp3)
18015 (goto-char (cond
18016 ;; `day' category ends before `hour' if any, or at
18017 ;; the end of the day name.
18018 ((eq origin-cat 'day)
18019 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18020 ((eq origin-cat 'hour) (min (match-end 7) origin))
18021 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18022 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18023 ;; `year' and `month' have both fixed size: point
18024 ;; couldn't have moved into another part.
18025 (t origin))))
18026 ;; Update clock if on a CLOCK line.
18027 (org-clock-update-time-maybe)
18028 ;; Maybe adjust the closest clock in `org-clock-history'
18029 (when org-clock-adjust-closest
18030 (if (not (and (org-at-clock-log-p)
18031 (< 1 (length (delq nil (mapcar 'marker-position
18032 org-clock-history))))))
18033 (message "No clock to adjust")
18034 (cond ((save-excursion ; fix previous clock?
18035 (re-search-backward org-ts-regexp0 nil t)
18036 (org-looking-back (concat org-clock-string " \\[")
18037 (line-beginning-position)))
18038 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18039 ((save-excursion ; fix next clock?
18040 (re-search-backward org-ts-regexp0 nil t)
18041 (looking-at (concat org-ts-regexp0 "\\] =>")))
18042 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18043 (save-window-excursion
18044 ;; Find closest clock to point, adjust the previous/next one in history
18045 (let* ((p (save-excursion (org-back-to-heading t)))
18046 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18047 (clfixnth
18048 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18049 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18050 (if (not clfixpos)
18051 (message "No clock to adjust")
18052 (save-excursion
18053 (org-goto-marker-or-bmk clfixpos)
18054 (org-show-subtree)
18055 (when (re-search-forward clrgx nil t)
18056 (goto-char (match-beginning 1))
18057 (let (org-clock-adjust-closest)
18058 (org-timestamp-change n org-ts-what updown))
18059 (message "Clock adjusted in %s for heading: %s"
18060 (file-name-nondirectory (buffer-file-name))
18061 (org-get-heading t t)))))))))
18062 ;; Try to recenter the calendar window, if any.
18063 (when (and org-calendar-follow-timestamp-change
18064 (get-buffer-window "*Calendar*" t)
18065 (memq org-ts-what '(day month year)))
18066 (org-recenter-calendar (time-to-days time))))))
18068 (defun org-modify-ts-extra (s pos n dm)
18069 "Change the different parts of the lead-time and repeat fields in timestamp."
18070 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18071 ng h m new rem)
18072 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18073 (cond
18074 ((or (org-pos-in-match-range pos 2)
18075 (org-pos-in-match-range pos 3))
18076 (setq m (string-to-number (match-string 3 s))
18077 h (string-to-number (match-string 2 s)))
18078 (if (org-pos-in-match-range pos 2)
18079 (setq h (+ h n))
18080 (setq n (* dm (org-no-warnings (signum n))))
18081 (unless (= 0 (setq rem (% m dm)))
18082 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18083 (setq m (+ m n)))
18084 (when (< m 0) (setq m (+ m 60) h (1- h)))
18085 (when (> m 59) (setq m (- m 60) h (1+ h)))
18086 (setq h (mod h 24))
18087 (setq ng 1 new (format "-%02d:%02d" h m)))
18088 ((org-pos-in-match-range pos 6)
18089 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18090 ((org-pos-in-match-range pos 5)
18091 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18093 ((org-pos-in-match-range pos 9)
18094 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18095 ((org-pos-in-match-range pos 8)
18096 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18098 (when ng
18099 (setq s (concat
18100 (substring s 0 (match-beginning ng))
18102 (substring s (match-end ng))))))
18105 (defun org-recenter-calendar (d)
18106 "If the calendar is visible, recenter it to date D."
18107 (let ((cwin (get-buffer-window "*Calendar*" t)))
18108 (when cwin
18109 (let ((calendar-move-hook nil))
18110 (with-selected-window cwin
18111 (calendar-goto-date
18112 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18114 (defun org-goto-calendar (&optional arg)
18115 "Go to the Emacs calendar at the current date.
18116 If there is a time stamp in the current line, go to that date.
18117 A prefix ARG can be used to force the current date."
18118 (interactive "P")
18119 (let ((tsr org-ts-regexp) diff
18120 (calendar-move-hook nil)
18121 (calendar-view-holidays-initially-flag nil)
18122 (calendar-view-diary-initially-flag nil))
18123 (when (or (org-at-timestamp-p)
18124 (save-excursion
18125 (beginning-of-line 1)
18126 (looking-at (concat ".*" tsr))))
18127 (let ((d1 (time-to-days (current-time)))
18128 (d2 (time-to-days
18129 (org-time-string-to-time (match-string 1)))))
18130 (setq diff (- d2 d1))))
18131 (calendar)
18132 (calendar-goto-today)
18133 (when (and diff (not arg)) (calendar-forward-day diff))))
18135 (defun org-get-date-from-calendar ()
18136 "Return a list (month day year) of date at point in calendar."
18137 (with-current-buffer "*Calendar*"
18138 (save-match-data
18139 (calendar-cursor-to-date))))
18141 (defun org-date-from-calendar ()
18142 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18143 If there is already a time stamp at the cursor position, update it."
18144 (interactive)
18145 (if (org-at-timestamp-p t)
18146 (org-timestamp-change 0 'calendar)
18147 (let ((cal-date (org-get-date-from-calendar)))
18148 (org-insert-time-stamp
18149 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18151 (defcustom org-effort-durations
18152 `(("min" . 1)
18153 ("h" . 60)
18154 ("d" . ,(* 60 8))
18155 ("w" . ,(* 60 8 5))
18156 ("m" . ,(* 60 8 5 4))
18157 ("y" . ,(* 60 8 5 40)))
18158 "Conversion factor to minutes for an effort modifier.
18160 Each entry has the form (MODIFIER . MINUTES).
18162 In an effort string, a number followed by MODIFIER is multiplied
18163 by the specified number of MINUTES to obtain an effort in
18164 minutes.
18166 For example, if the value of this variable is ((\"hours\" . 60)), then an
18167 effort string \"2hours\" is equivalent to 120 minutes."
18168 :group 'org-agenda
18169 :version "25.1"
18170 :package-version '(Org . "8.3")
18171 :type '(alist :key-type (string :tag "Modifier")
18172 :value-type (number :tag "Minutes")))
18174 (defun org-minutes-to-clocksum-string (m)
18175 "Format number of minutes as a clocksum string.
18176 The format is determined by `org-time-clocksum-format',
18177 `org-time-clocksum-use-fractional' and
18178 `org-time-clocksum-fractional-format' and
18179 `org-time-clocksum-use-effort-durations'."
18180 (let ((clocksum "")
18181 (m (round m)) ; Don't allow fractions of minutes
18182 h d w mo y fmt n)
18183 (setq h (if org-time-clocksum-use-effort-durations
18184 (cdr (assoc "h" org-effort-durations)) 60)
18185 d (if org-time-clocksum-use-effort-durations
18186 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18187 w (if org-time-clocksum-use-effort-durations
18188 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18189 mo (if org-time-clocksum-use-effort-durations
18190 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18191 y (if org-time-clocksum-use-effort-durations
18192 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18193 ;; fractional format
18194 (if org-time-clocksum-use-fractional
18195 (cond
18196 ;; single format string
18197 ((stringp org-time-clocksum-fractional-format)
18198 (format org-time-clocksum-fractional-format (/ m (float h))))
18199 ;; choice of fractional formats for different time units
18200 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18201 (> (/ (truncate m) (* y d h)) 0))
18202 (format fmt (/ m (* y d (float h)))))
18203 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18204 (> (/ (truncate m) (* mo d h)) 0))
18205 (format fmt (/ m (* mo d (float h)))))
18206 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18207 (> (/ (truncate m) (* w d h)) 0))
18208 (format fmt (/ m (* w d (float h)))))
18209 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18210 (> (/ (truncate m) (* d h)) 0))
18211 (format fmt (/ m (* d (float h)))))
18212 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18213 (> (/ (truncate m) h) 0))
18214 (format fmt (/ m (float h))))
18215 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18216 (format fmt m))
18217 ;; fall back to smallest time unit with a format
18218 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18219 (format fmt (/ m (float h))))
18220 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18221 (format fmt (/ m (* d (float h)))))
18222 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18223 (format fmt (/ m (* w d (float h)))))
18224 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18225 (format fmt (/ m (* mo d (float h)))))
18226 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18227 (format fmt (/ m (* y d (float h))))))
18228 ;; standard (non-fractional) format, with single format string
18229 (if (stringp org-time-clocksum-format)
18230 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18231 ;; separate formats components
18232 (and (setq fmt (plist-get org-time-clocksum-format :years))
18233 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18234 (plist-get org-time-clocksum-format :require-years))
18235 (setq clocksum (concat clocksum (format fmt n))
18236 m (- m (* n y d h))))
18237 (and (setq fmt (plist-get org-time-clocksum-format :months))
18238 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18239 (plist-get org-time-clocksum-format :require-months))
18240 (setq clocksum (concat clocksum (format fmt n))
18241 m (- m (* n mo d h))))
18242 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18243 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18244 (plist-get org-time-clocksum-format :require-weeks))
18245 (setq clocksum (concat clocksum (format fmt n))
18246 m (- m (* n w d h))))
18247 (and (setq fmt (plist-get org-time-clocksum-format :days))
18248 (or (> (setq n (/ (truncate m) (* d h))) 0)
18249 (plist-get org-time-clocksum-format :require-days))
18250 (setq clocksum (concat clocksum (format fmt n))
18251 m (- m (* n d h))))
18252 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18253 (or (> (setq n (/ (truncate m) h)) 0)
18254 (plist-get org-time-clocksum-format :require-hours))
18255 (setq clocksum (concat clocksum (format fmt n))
18256 m (- m (* n h))))
18257 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18258 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18259 (setq clocksum (concat clocksum (format fmt m))))
18260 ;; return formatted time duration
18261 clocksum))))
18263 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18264 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18265 "Org mode version 8.0")
18267 (defun org-hours-to-clocksum-string (n)
18268 (org-minutes-to-clocksum-string (* n 60)))
18270 (defun org-hh:mm-string-to-minutes (s)
18271 "Convert a string H:MM to a number of minutes.
18272 If the string is just a number, interpret it as minutes.
18273 In fact, the first hh:mm or number in the string will be taken,
18274 there can be extra stuff in the string.
18275 If no number is found, the return value is 0."
18276 (cond
18277 ((integerp s) s)
18278 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18279 (+ (* (string-to-number (match-string 1 s)) 60)
18280 (string-to-number (match-string 2 s))))
18281 ((string-match "\\([0-9]+\\)" s)
18282 (string-to-number (match-string 1 s)))
18283 (t 0)))
18285 (defcustom org-image-actual-width t
18286 "Should we use the actual width of images when inlining them?
18288 When set to t, always use the image width.
18290 When set to a number, use imagemagick (when available) to set
18291 the image's width to this value.
18293 When set to a number in a list, try to get the width from any
18294 #+ATTR.* keyword if it matches a width specification like
18296 #+ATTR_HTML: :width 300px
18298 and fall back on that number if none is found.
18300 When set to nil, try to get the width from an #+ATTR.* keyword
18301 and fall back on the original width if none is found.
18303 This requires Emacs >= 24.1, build with imagemagick support."
18304 :group 'org-appearance
18305 :version "24.4"
18306 :package-version '(Org . "8.0")
18307 :type '(choice
18308 (const :tag "Use the image width" t)
18309 (integer :tag "Use a number of pixels")
18310 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18311 (const :tag "Use #+ATTR* or don't resize" nil)))
18313 (defcustom org-agenda-inhibit-startup nil
18314 "Inhibit startup when preparing agenda buffers.
18315 When this variable is t, the initialization of the Org agenda
18316 buffers is inhibited: e.g. the visibility state is not set, the
18317 tables are not re-aligned, etc."
18318 :type 'boolean
18319 :version "24.3"
18320 :group 'org-agenda)
18322 (define-obsolete-variable-alias
18323 'org-agenda-ignore-drawer-properties
18324 'org-agenda-ignore-properties "25.1")
18326 (defcustom org-agenda-ignore-properties nil
18327 "Avoid updating text properties when building the agenda.
18328 Properties are used to prepare buffers for effort estimates,
18329 appointments, statistics and subtree-local categories.
18330 If you don't use these in the agenda, you can add them to this
18331 list and agenda building will be a bit faster.
18332 The value is a list, with zero or more of the symbols `effort', `appt',
18333 `stats' or `category'."
18334 :type '(set :greedy t
18335 (const effort)
18336 (const appt)
18337 (const stats)
18338 (const category))
18339 :version "25.1"
18340 :package-version '(Org . "8.3")
18341 :group 'org-agenda)
18343 (defun org-duration-string-to-minutes (s &optional output-to-string)
18344 "Convert a duration string S to minutes.
18346 A bare number is interpreted as minutes, modifiers can be set by
18347 customizing `org-effort-durations' (which see).
18349 Entries containing a colon are interpreted as H:MM by
18350 `org-hh:mm-string-to-minutes'."
18351 (let ((result 0)
18352 (re (concat "\\([0-9.]+\\) *\\("
18353 (regexp-opt (mapcar 'car org-effort-durations))
18354 "\\)")))
18355 (while (string-match re s)
18356 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18357 (string-to-number (match-string 1 s))))
18358 (setq s (replace-match "" nil t s)))
18359 (setq result (floor result))
18360 (cl-incf result (org-hh:mm-string-to-minutes s))
18361 (if output-to-string (number-to-string result) result)))
18363 ;;;; Files
18365 (defun org-save-all-org-buffers ()
18366 "Save all Org-mode buffers without user confirmation."
18367 (interactive)
18368 (message "Saving all Org-mode buffers...")
18369 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18370 (when (featurep 'org-id) (org-id-locations-save))
18371 (message "Saving all Org-mode buffers... done"))
18373 (defun org-revert-all-org-buffers ()
18374 "Revert all Org-mode buffers.
18375 Prompt for confirmation when there are unsaved changes.
18376 Be sure you know what you are doing before letting this function
18377 overwrite your changes.
18379 This function is useful in a setup where one tracks org files
18380 with a version control system, to revert on one machine after pulling
18381 changes from another. I believe the procedure must be like this:
18383 1. M-x org-save-all-org-buffers
18384 2. Pull changes from the other machine, resolve conflicts
18385 3. M-x org-revert-all-org-buffers"
18386 (interactive)
18387 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18388 (user-error "Abort"))
18389 (save-excursion
18390 (save-window-excursion
18391 (dolist (b (buffer-list))
18392 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18393 (with-current-buffer b buffer-file-name))
18394 (org-pop-to-buffer-same-window b)
18395 (revert-buffer t 'no-confirm)))
18396 (when (and (featurep 'org-id) org-id-track-globally)
18397 (org-id-locations-load)))))
18399 ;;;; Agenda files
18401 ;;;###autoload
18402 (defun org-switchb (&optional arg)
18403 "Switch between Org buffers.
18405 With \\[universal-argument] prefix, restrict available buffers to files.
18407 With \\[universal-argument] \\[universal-argument] \
18408 prefix, restrict available buffers to agenda files."
18409 (interactive "P")
18410 (let ((blist (org-buffer-list
18411 (cond ((equal arg '(4)) 'files)
18412 ((equal arg '(16)) 'agenda)))))
18413 (org-pop-to-buffer-same-window
18414 (completing-read "Org buffer: "
18415 (mapcar #'list (mapcar #'buffer-name blist))
18416 nil t))))
18418 (defun org-buffer-list (&optional predicate exclude-tmp)
18419 "Return a list of Org buffers.
18420 PREDICATE can be `export', `files' or `agenda'.
18422 export restrict the list to Export buffers.
18423 files restrict the list to buffers visiting Org files.
18424 agenda restrict the list to buffers visiting agenda files.
18426 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18427 (let* ((bfn nil)
18428 (agenda-files (and (eq predicate 'agenda)
18429 (mapcar 'file-truename (org-agenda-files t))))
18430 (filter
18431 (cond
18432 ((eq predicate 'files)
18433 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18434 ((eq predicate 'export)
18435 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18436 ((eq predicate 'agenda)
18437 (lambda (b)
18438 (with-current-buffer b
18439 (and (derived-mode-p 'org-mode)
18440 (setq bfn (buffer-file-name b))
18441 (member (file-truename bfn) agenda-files)))))
18442 (t (lambda (b) (with-current-buffer b
18443 (or (derived-mode-p 'org-mode)
18444 (string-match "\\*Org .*Export"
18445 (buffer-name b)))))))))
18446 (delq nil
18447 (mapcar
18448 (lambda(b)
18449 (if (and (funcall filter b)
18450 (or (not exclude-tmp)
18451 (not (string-match "tmp" (buffer-name b)))))
18453 nil))
18454 (buffer-list)))))
18456 (defun org-agenda-files (&optional unrestricted archives)
18457 "Get the list of agenda files.
18458 Optional UNRESTRICTED means return the full list even if a restriction
18459 is currently in place.
18460 When ARCHIVES is t, include all archive files that are really being
18461 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18462 `org-agenda-archives-mode' is t."
18463 (let ((files
18464 (cond
18465 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18466 ((stringp org-agenda-files) (org-read-agenda-file-list))
18467 ((listp org-agenda-files) org-agenda-files)
18468 (t (error "Invalid value of `org-agenda-files'")))))
18469 (setq files (apply 'append
18470 (mapcar (lambda (f)
18471 (if (file-directory-p f)
18472 (directory-files
18473 f t org-agenda-file-regexp)
18474 (list f)))
18475 files)))
18476 (when org-agenda-skip-unavailable-files
18477 (setq files (delq nil
18478 (mapcar (function
18479 (lambda (file)
18480 (and (file-readable-p file) file)))
18481 files))))
18482 (when (or (eq archives t)
18483 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18484 (setq files (org-add-archive-files files)))
18485 files))
18487 (defun org-agenda-file-p (&optional file)
18488 "Return non-nil, if FILE is an agenda file.
18489 If FILE is omitted, use the file associated with the current
18490 buffer."
18491 (let ((fname (or file (buffer-file-name))))
18492 (and fname
18493 (member (file-truename fname)
18494 (mapcar #'file-truename (org-agenda-files t))))))
18496 (defun org-edit-agenda-file-list ()
18497 "Edit the list of agenda files.
18498 Depending on setup, this either uses customize to edit the variable
18499 `org-agenda-files', or it visits the file that is holding the list. In the
18500 latter case, the buffer is set up in a way that saving it automatically kills
18501 the buffer and restores the previous window configuration."
18502 (interactive)
18503 (if (stringp org-agenda-files)
18504 (let ((cw (current-window-configuration)))
18505 (find-file org-agenda-files)
18506 (setq-local org-window-configuration cw)
18507 (org-add-hook 'after-save-hook
18508 (lambda ()
18509 (set-window-configuration
18510 (prog1 org-window-configuration
18511 (kill-buffer (current-buffer))))
18512 (org-install-agenda-files-menu)
18513 (message "New agenda file list installed"))
18514 nil 'local)
18515 (message "%s" (substitute-command-keys
18516 "Edit list and finish with \\[save-buffer]")))
18517 (customize-variable 'org-agenda-files)))
18519 (defun org-store-new-agenda-file-list (list)
18520 "Set new value for the agenda file list and save it correctly."
18521 (if (stringp org-agenda-files)
18522 (let ((fe (org-read-agenda-file-list t)) b u)
18523 (while (setq b (find-buffer-visiting org-agenda-files))
18524 (kill-buffer b))
18525 (with-temp-file org-agenda-files
18526 (insert
18527 (mapconcat
18528 (lambda (f) ;; Keep un-expanded entries.
18529 (if (setq u (assoc f fe))
18530 (cdr u)
18532 list "\n")
18533 "\n")))
18534 (let ((org-mode-hook nil) (org-inhibit-startup t)
18535 (org-insert-mode-line-in-empty-file nil))
18536 (setq org-agenda-files list)
18537 (customize-save-variable 'org-agenda-files org-agenda-files))))
18539 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18540 "Read the list of agenda files from a file.
18541 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18542 filenames, used by `org-store-new-agenda-file-list' to write back
18543 un-expanded file names."
18544 (when (file-directory-p org-agenda-files)
18545 (error "`org-agenda-files' cannot be a single directory"))
18546 (when (stringp org-agenda-files)
18547 (with-temp-buffer
18548 (insert-file-contents org-agenda-files)
18549 (mapcar
18550 (lambda (f)
18551 (let ((e (expand-file-name (substitute-in-file-name f)
18552 org-directory)))
18553 (if pair-with-expansion
18554 (cons e f)
18555 e)))
18556 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18558 ;;;###autoload
18559 (defun org-cycle-agenda-files ()
18560 "Cycle through the files in `org-agenda-files'.
18561 If the current buffer visits an agenda file, find the next one in the list.
18562 If the current buffer does not, find the first agenda file."
18563 (interactive)
18564 (let* ((fs (or (org-agenda-files t)
18565 (user-error "No agenda files")))
18566 (files (copy-sequence fs))
18567 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18568 file)
18569 (when tcf
18570 (while (and (setq file (pop files))
18571 (not (equal (file-truename file) tcf)))))
18572 (find-file (car (or files fs)))
18573 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18575 (defun org-agenda-file-to-front (&optional to-end)
18576 "Move/add the current file to the top of the agenda file list.
18577 If the file is not present in the list, it is added to the front. If it is
18578 present, it is moved there. With optional argument TO-END, add/move to the
18579 end of the list."
18580 (interactive "P")
18581 (let ((org-agenda-skip-unavailable-files nil)
18582 (file-alist (mapcar (lambda (x)
18583 (cons (file-truename x) x))
18584 (org-agenda-files t)))
18585 (ctf (file-truename
18586 (or buffer-file-name
18587 (user-error "Please save the current buffer to a file"))))
18588 x had)
18589 (setq x (assoc ctf file-alist) had x)
18591 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18592 (if to-end
18593 (setq file-alist (append (delq x file-alist) (list x)))
18594 (setq file-alist (cons x (delq x file-alist))))
18595 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18596 (org-install-agenda-files-menu)
18597 (message "File %s to %s of agenda file list"
18598 (if had "moved" "added") (if to-end "end" "front"))))
18600 (defun org-remove-file (&optional file)
18601 "Remove current file from the list of files in variable `org-agenda-files'.
18602 These are the files which are being checked for agenda entries.
18603 Optional argument FILE means use this file instead of the current."
18604 (interactive)
18605 (let* ((org-agenda-skip-unavailable-files nil)
18606 (file (or file buffer-file-name
18607 (user-error "Current buffer does not visit a file")))
18608 (true-file (file-truename file))
18609 (afile (abbreviate-file-name file))
18610 (files (delq nil (mapcar
18611 (lambda (x)
18612 (unless (equal true-file
18613 (file-truename x))
18615 (org-agenda-files t)))))
18616 (if (not (= (length files) (length (org-agenda-files t))))
18617 (progn
18618 (org-store-new-agenda-file-list files)
18619 (org-install-agenda-files-menu)
18620 (message "Removed from Org Agenda list: %s" afile))
18621 (message "File was not in list: %s (not removed)" afile))))
18623 (defun org-file-menu-entry (file)
18624 (vector file (list 'find-file file) t))
18626 (defun org-check-agenda-file (file)
18627 "Make sure FILE exists. If not, ask user what to do."
18628 (unless (file-exists-p file)
18629 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18630 (abbreviate-file-name file))
18631 (let ((r (downcase (read-char-exclusive))))
18632 (cond
18633 ((equal r ?r)
18634 (org-remove-file file)
18635 (throw 'nextfile t))
18636 (t (user-error "Abort"))))))
18638 (defun org-get-agenda-file-buffer (file)
18639 "Get an agenda buffer visiting FILE.
18640 If the buffer needs to be created, add it to the list of buffers
18641 which might be released later."
18642 (let ((buf (org-find-base-buffer-visiting file)))
18643 (if buf
18644 buf ; just return it
18645 ;; Make a new buffer and remember it
18646 (setq buf (find-file-noselect file))
18647 (when buf (push buf org-agenda-new-buffers))
18648 buf)))
18650 (defun org-release-buffers (blist)
18651 "Release all buffers in list, asking the user for confirmation when needed.
18652 When a buffer is unmodified, it is just killed. When modified, it is saved
18653 \(if the user agrees) and then killed."
18654 (let (file)
18655 (dolist (buf blist)
18656 (setq file (buffer-file-name buf))
18657 (when (and (buffer-modified-p buf)
18658 file
18659 (y-or-n-p (format "Save file %s? " file)))
18660 (with-current-buffer buf (save-buffer)))
18661 (kill-buffer buf))))
18663 (defun org-agenda-prepare-buffers (files)
18664 "Create buffers for all agenda files, protect archived trees and comments."
18665 (interactive)
18666 (let ((pa '(:org-archived t))
18667 (pc '(:org-comment t))
18668 (pall '(:org-archived t :org-comment t))
18669 (inhibit-read-only t)
18670 (org-inhibit-startup org-agenda-inhibit-startup)
18671 (rea (concat ":" org-archive-tag ":"))
18672 re pos)
18673 (setq org-tag-alist-for-agenda nil
18674 org-tag-groups-alist-for-agenda nil)
18675 (save-excursion
18676 (save-restriction
18677 (dolist (file files)
18678 (catch 'nextfile
18679 (if (bufferp file)
18680 (set-buffer file)
18681 (org-check-agenda-file file)
18682 (set-buffer (org-get-agenda-file-buffer file)))
18683 (widen)
18684 (org-set-regexps-and-options 'tags-only)
18685 (setq pos (point))
18686 (or (memq 'category org-agenda-ignore-properties)
18687 (org-refresh-category-properties))
18688 (or (memq 'stats org-agenda-ignore-properties)
18689 (org-refresh-stats-properties))
18690 (or (memq 'effort org-agenda-ignore-properties)
18691 (org-refresh-effort-properties))
18692 (or (memq 'appt org-agenda-ignore-properties)
18693 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18694 (setq org-todo-keywords-for-agenda
18695 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18696 (setq org-done-keywords-for-agenda
18697 (append org-done-keywords-for-agenda org-done-keywords))
18698 (setq org-todo-keyword-alist-for-agenda
18699 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18700 (setq org-tag-alist-for-agenda
18701 (org-uniquify
18702 (append org-tag-alist-for-agenda
18703 org-tag-alist
18704 org-tag-persistent-alist)))
18705 ;; Merge current file's tag groups into global
18706 ;; `org-tag-groups-alist-for-agenda'.
18707 (when org-group-tags
18708 (dolist (alist org-tag-groups-alist)
18709 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18710 (if old
18711 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18712 (push alist org-tag-groups-alist-for-agenda)))))
18713 (org-with-silent-modifications
18714 (save-excursion
18715 (remove-text-properties (point-min) (point-max) pall)
18716 (when org-agenda-skip-archived-trees
18717 (goto-char (point-min))
18718 (while (re-search-forward rea nil t)
18719 (when (org-at-heading-p t)
18720 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18721 (goto-char (point-min))
18722 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18723 (while (re-search-forward re nil t)
18724 (when (save-match-data (org-in-commented-heading-p t))
18725 (add-text-properties
18726 (match-beginning 0) (org-end-of-subtree t) pc)))))
18727 (goto-char pos)))))
18728 (setq org-todo-keywords-for-agenda
18729 (org-uniquify org-todo-keywords-for-agenda))
18730 (setq org-todo-keyword-alist-for-agenda
18731 (org-uniquify org-todo-keyword-alist-for-agenda))))
18734 ;;;; CDLaTeX minor mode
18736 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18737 "Keymap for the minor `org-cdlatex-mode'.")
18739 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18740 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18741 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18742 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18743 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18745 (defvar org-cdlatex-texmathp-advice-is-done nil
18746 "Flag remembering if we have applied the advice to texmathp already.")
18748 (define-minor-mode org-cdlatex-mode
18749 "Toggle the minor `org-cdlatex-mode'.
18750 This mode supports entering LaTeX environment and math in LaTeX fragments
18751 in Org-mode.
18752 \\{org-cdlatex-mode-map}"
18753 nil " OCDL" nil
18754 (when org-cdlatex-mode
18755 (require 'cdlatex)
18756 (run-hooks 'cdlatex-mode-hook)
18757 (cdlatex-compute-tables))
18758 (unless org-cdlatex-texmathp-advice-is-done
18759 (setq org-cdlatex-texmathp-advice-is-done t)
18760 (defadvice texmathp (around org-math-always-on activate)
18761 "Always return t in org-mode buffers.
18762 This is because we want to insert math symbols without dollars even outside
18763 the LaTeX math segments. If Orgmode thinks that point is actually inside
18764 an embedded LaTeX fragment, let texmathp do its job.
18765 \\[org-cdlatex-mode-map]"
18766 (interactive)
18767 (let (p)
18768 (cond
18769 ((not (derived-mode-p 'org-mode)) ad-do-it)
18770 ((eq this-command 'cdlatex-math-symbol)
18771 (setq ad-return-value t
18772 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18774 (let ((p (org-inside-LaTeX-fragment-p)))
18775 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18776 (setq ad-return-value t
18777 texmathp-why '("Org-mode embedded math" . 0))
18778 (when p ad-do-it)))))))))
18780 (defun turn-on-org-cdlatex ()
18781 "Unconditionally turn on `org-cdlatex-mode'."
18782 (org-cdlatex-mode 1))
18784 (defun org-try-cdlatex-tab ()
18785 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18786 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18787 - inside a LaTeX fragment, or
18788 - after the first word in a line, where an abbreviation expansion could
18789 insert a LaTeX environment."
18790 (when org-cdlatex-mode
18791 (cond
18792 ;; Before any word on the line: No expansion possible.
18793 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18794 ;; Just after first word on the line: Expand it. Make sure it
18795 ;; cannot happen on headlines, though.
18796 ((save-excursion
18797 (skip-chars-backward "a-zA-Z0-9*")
18798 (skip-chars-backward " \t")
18799 (and (bolp) (not (org-at-heading-p))))
18800 (cdlatex-tab) t)
18801 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18803 (defun org-cdlatex-underscore-caret (&optional _arg)
18804 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18805 Revert to the normal definition outside of these fragments."
18806 (interactive "P")
18807 (if (org-inside-LaTeX-fragment-p)
18808 (call-interactively 'cdlatex-sub-superscript)
18809 (let (org-cdlatex-mode)
18810 (call-interactively (key-binding (vector last-input-event))))))
18812 (defun org-cdlatex-math-modify (&optional _arg)
18813 "Execute `cdlatex-math-modify' in LaTeX fragments.
18814 Revert to the normal definition outside of these fragments."
18815 (interactive "P")
18816 (if (org-inside-LaTeX-fragment-p)
18817 (call-interactively 'cdlatex-math-modify)
18818 (let (org-cdlatex-mode)
18819 (call-interactively (key-binding (vector last-input-event))))))
18821 (defun org-cdlatex-environment-indent (&optional environment item)
18822 "Execute `cdlatex-environment' and indent the inserted environment.
18824 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18826 The inserted environment is indented to current indentation
18827 unless point is at the beginning of the line, in which the
18828 environment remains unintended."
18829 (interactive)
18830 ;; cdlatex-environment always return nil. Therefore, capture output
18831 ;; first and determine if an environment was selected.
18832 (let* ((beg (point-marker))
18833 (end (copy-marker (point) t))
18834 (inserted (progn
18835 (ignore-errors (cdlatex-environment environment item))
18836 (< beg end)))
18837 ;; Figure out how many lines to move forward after the
18838 ;; environment has been inserted.
18839 (lines (when inserted
18840 (save-excursion
18841 (- (cl-loop while (< beg (point))
18842 with x = 0
18843 do (forward-line -1)
18844 (cl-incf x)
18845 finally return x)
18846 (if (progn (goto-char beg)
18847 (and (progn (skip-chars-forward " \t") (eolp))
18848 (progn (skip-chars-backward " \t") (bolp))))
18849 1 0)))))
18850 (env (org-trim (delete-and-extract-region beg end))))
18851 (when inserted
18852 ;; Get indentation of next line unless at column 0.
18853 (let ((ind (if (bolp) 0
18854 (save-excursion
18855 (org-return-indent)
18856 (prog1 (org-get-indentation)
18857 (when (progn (skip-chars-forward " \t") (eolp))
18858 (delete-region beg (point)))))))
18859 (bol (progn (skip-chars-backward " \t") (bolp))))
18860 ;; Insert a newline before environment unless at column zero
18861 ;; to "escape" the current line. Insert a newline if
18862 ;; something is one the same line as \end{ENVIRONMENT}.
18863 (insert
18864 (concat (unless bol "\n") env
18865 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18866 (unless (zerop ind)
18867 (save-excursion
18868 (goto-char beg)
18869 (while (< (point) end)
18870 (unless (eolp) (org-indent-line-to ind))
18871 (forward-line))))
18872 (goto-char beg)
18873 (forward-line lines)
18874 (org-indent-line-to ind)))
18875 (set-marker beg nil)
18876 (set-marker end nil)))
18879 ;;;; LaTeX fragments
18881 (defun org-inside-LaTeX-fragment-p ()
18882 "Test if point is inside a LaTeX fragment.
18883 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18884 sequence appearing also before point.
18885 Even though the matchers for math are configurable, this function assumes
18886 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18887 delimiters are skipped when they have been removed by customization.
18888 The return value is nil, or a cons cell with the delimiter and the
18889 position of this delimiter.
18891 This function does a reasonably good job, but can locally be fooled by
18892 for example currency specifications. For example it will assume being in
18893 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18894 fragments that are properly closed, but during editing, we have to live
18895 with the uncertainty caused by missing closing delimiters. This function
18896 looks only before point, not after."
18897 (catch 'exit
18898 (let ((pos (point))
18899 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18900 (lim (progn
18901 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18902 (point)))
18903 dd-on str (start 0) m re)
18904 (goto-char pos)
18905 (when dodollar
18906 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18907 re (nth 1 (assoc "$" org-latex-regexps)))
18908 (while (string-match re str start)
18909 (cond
18910 ((= (match-end 0) (length str))
18911 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18912 ((= (match-end 0) (- (length str) 5))
18913 (throw 'exit nil))
18914 (t (setq start (match-end 0))))))
18915 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18916 (goto-char pos)
18917 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18918 (and (match-beginning 2) (throw 'exit nil))
18919 ;; count $$
18920 (while (re-search-backward "\\$\\$" lim t)
18921 (setq dd-on (not dd-on)))
18922 (goto-char pos)
18923 (when dd-on (cons "$$" m))))))
18925 (defun org-inside-latex-macro-p ()
18926 "Is point inside a LaTeX macro or its arguments?"
18927 (save-match-data
18928 (org-in-regexp
18929 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18931 (defun org--format-latex-make-overlay (beg end image)
18932 "Build an overlay between BEG and END using IMAGE file."
18933 (let ((ov (make-overlay beg end)))
18934 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18935 (overlay-put ov 'evaporate t)
18936 (overlay-put ov
18937 'modification-hooks
18938 (list (lambda (o _flag _beg _end &optional _l)
18939 (delete-overlay o))))
18940 (if (featurep 'xemacs)
18941 (progn
18942 (overlay-put ov 'invisible t)
18943 (overlay-put ov 'end-glyph (make-glyph (vector 'png :file image))))
18944 (overlay-put ov
18945 'display
18946 (list 'image :type 'png :file image :ascent 'center)))))
18948 (defun org--list-latex-overlays (&optional beg end)
18949 "List all Org LaTeX overlays in current buffer.
18950 Limit to overlays between BEG and END when those are provided."
18951 (cl-remove-if-not
18952 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18953 (overlays-in (or beg (point-min)) (or end (point-max)))))
18955 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18956 "Remove all overlays with LaTeX fragment images in current buffer.
18957 When optional arguments BEG and END are non-nil, remove all
18958 overlays between them instead. Return a non-nil value when some
18959 overlays were removed, nil otherwise."
18960 (let ((overlays (org--list-latex-overlays beg end)))
18961 (mapc #'delete-overlay overlays)
18962 overlays))
18964 (define-obsolete-function-alias
18965 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
18966 (defun org-toggle-latex-fragment (&optional arg)
18967 "Preview the LaTeX fragment at point, or all locally or globally.
18969 If the cursor is on a LaTeX fragment, create the image and overlay
18970 it over the source code, if there is none. Remove it otherwise.
18971 If there is no fragment at point, display all fragments in the
18972 current section.
18974 With prefix ARG, preview or clear image for all fragments in the
18975 current subtree or in the whole buffer when used before the first
18976 headline. With a double prefix ARG \\[universal-argument] \
18977 \\[universal-argument] preview or clear images
18978 for all fragments in the buffer."
18979 (interactive "P")
18980 (when (display-graphic-p)
18981 (catch 'exit
18982 (save-excursion
18983 (let ((window-start (window-start)) msg)
18984 (save-restriction
18985 (cond
18986 ((or (equal arg '(16))
18987 (and (equal arg '(4))
18988 (org-with-limited-levels (org-before-first-heading-p))))
18989 (if (org-remove-latex-fragment-image-overlays)
18990 (progn (message "LaTeX fragments images removed from buffer")
18991 (throw 'exit nil))
18992 (setq msg "Creating images for buffer...")))
18993 ((equal arg '(4))
18994 (org-with-limited-levels (org-back-to-heading t))
18995 (let ((beg (point))
18996 (end (progn (org-end-of-subtree t) (point))))
18997 (if (org-remove-latex-fragment-image-overlays beg end)
18998 (progn
18999 (message "LaTeX fragment images removed from subtree")
19000 (throw 'exit nil))
19001 (setq msg "Creating images for subtree...")
19002 (narrow-to-region beg end))))
19003 ((let ((datum (org-element-context)))
19004 (when (memq (org-element-type datum)
19005 '(latex-environment latex-fragment))
19006 (let* ((beg (org-element-property :begin datum))
19007 (end (org-element-property :end datum)))
19008 (if (org-remove-latex-fragment-image-overlays beg end)
19009 (progn (message "LaTeX fragment image removed")
19010 (throw 'exit nil))
19011 (narrow-to-region beg end)
19012 (setq msg "Creating image..."))))))
19014 (org-with-limited-levels
19015 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19016 (outline-previous-heading)
19017 (point)))
19018 (end (progn (outline-next-heading) (point))))
19019 (if (org-remove-latex-fragment-image-overlays beg end)
19020 (progn
19021 (message "LaTeX fragment images removed from section")
19022 (throw 'exit nil))
19023 (setq msg "Creating images for section...")
19024 (narrow-to-region beg end))))))
19025 (let ((file (buffer-file-name (buffer-base-buffer))))
19026 (org-format-latex
19027 (concat org-latex-preview-ltxpng-directory "org-ltxpng")
19028 ;; Emacs cannot overlay images from remote hosts.
19029 ;; Create it in `temporary-file-directory' instead.
19030 (if (or (not file) (file-remote-p file))
19031 temporary-file-directory
19032 default-directory)
19033 'overlays msg 'forbuffer
19034 org-latex-create-formula-image-program)))
19035 ;; Work around a bug that doesn't restore window's start
19036 ;; when widening back the buffer.
19037 (set-window-start nil window-start)
19038 (message (concat msg "done")))))))
19040 (defun org-format-latex
19041 (prefix &optional dir overlays msg forbuffer processing-type)
19042 "Replace LaTeX fragments with links to an image, and produce images.
19044 When optional argument OVERLAYS is non-nil, display the image on
19045 top of the fragment instead of replacing it.
19047 PROCESSING-TYPE is the conversion method to use, as a symbol.
19049 Some of the options can be changed using the variable
19050 `org-format-latex-options', which see."
19051 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19052 (unless (eq processing-type 'verbatim)
19053 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19054 (cnt 0)
19055 checkdir-flag)
19056 (goto-char (point-min))
19057 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19058 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19059 (overlay-recenter (point-max)))
19060 (while (re-search-forward math-regexp nil t)
19061 (unless (and overlays
19062 (eq (get-char-property (point) 'org-overlay-type)
19063 'org-latex-overlay))
19064 (let* ((context (org-element-context))
19065 (type (org-element-type context)))
19066 (when (memq type '(latex-environment latex-fragment))
19067 (let ((block-type (eq type 'latex-environment))
19068 (value (org-element-property :value context))
19069 (beg (org-element-property :begin context))
19070 (end (save-excursion
19071 (goto-char (org-element-property :end context))
19072 (skip-chars-backward " \r\t\n")
19073 (point))))
19074 (cl-case processing-type
19075 (mathjax
19076 ;; Prepare for MathJax processing.
19077 (if (not (string-match "\\`\\$\\$?" value))
19078 (goto-char end)
19079 (delete-region beg end)
19080 (if (string= (match-string 0 value) "$$")
19081 (insert "\\[" (substring value 2 -2) "\\]")
19082 (insert "\\(" (substring value 1 -1) "\\)"))))
19083 ((dvipng imagemagick)
19084 ;; Process to an image.
19085 (cl-incf cnt)
19086 (goto-char beg)
19087 (let* ((face (face-at-point))
19088 ;; Get the colors from the face at point.
19090 (let ((color (plist-get org-format-latex-options
19091 :foreground)))
19092 (if (and forbuffer (eq color 'auto))
19093 (face-attribute face :foreground nil 'default)
19094 color)))
19096 (let ((color (plist-get org-format-latex-options
19097 :background)))
19098 (if (and forbuffer (eq color 'auto))
19099 (face-attribute face :background nil 'default)
19100 color)))
19101 (hash (sha1 (prin1-to-string
19102 (list org-format-latex-header
19103 org-latex-default-packages-alist
19104 org-latex-packages-alist
19105 org-format-latex-options
19106 forbuffer value fg bg))))
19107 (absprefix (expand-file-name prefix dir))
19108 (linkfile (format "%s_%s.png" prefix hash))
19109 (movefile (format "%s_%s.png" absprefix hash))
19110 (sep (and block-type "\n\n"))
19111 (link (concat sep "[[file:" linkfile "]]" sep))
19112 (options
19113 (org-combine-plists
19114 org-format-latex-options
19115 `(:foreground ,fg :background ,bg))))
19116 (when msg (message msg cnt))
19117 (unless checkdir-flag ; Ensure the directory exists.
19118 (setq checkdir-flag t)
19119 (let ((todir (file-name-directory absprefix)))
19120 (unless (file-directory-p todir)
19121 (make-directory todir t))))
19122 (unless (file-exists-p movefile)
19123 (org-create-formula-image
19124 value movefile options forbuffer processing-type))
19125 (if overlays
19126 (progn
19127 (dolist (o (overlays-in beg end))
19128 (when (eq (overlay-get o 'org-overlay-type)
19129 'org-latex-overlay)
19130 (delete-overlay o)))
19131 (org--format-latex-make-overlay beg end movefile)
19132 (goto-char end))
19133 (delete-region beg end)
19134 (insert
19135 (org-add-props link
19136 (list 'org-latex-src
19137 (replace-regexp-in-string "\"" "" value)
19138 'org-latex-src-embed-type
19139 (if block-type 'paragraph 'character)))))))
19140 (mathml
19141 ;; Process to MathML.
19142 (unless (org-format-latex-mathml-available-p)
19143 (user-error "LaTeX to MathML converter not configured"))
19144 (cl-incf cnt)
19145 (when msg (message msg cnt))
19146 (goto-char beg)
19147 (delete-region beg end)
19148 (insert (org-format-latex-as-mathml
19149 value block-type prefix dir)))
19150 (otherwise
19151 (error "Unknown conversion type %s for LaTeX fragments"
19152 processing-type)))))))))))
19154 (defun org-create-math-formula (latex-frag &optional mathml-file)
19155 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19156 Use `org-latex-to-mathml-convert-command'. If the conversion is
19157 sucessful, return the portion between \"<math...> </math>\"
19158 elements otherwise return nil. When MATHML-FILE is specified,
19159 write the results in to that file. When invoked as an
19160 interactive command, prompt for LATEX-FRAG, with initial value
19161 set to the current active region and echo the results for user
19162 inspection."
19163 (interactive (list (let ((frag (when (org-region-active-p)
19164 (buffer-substring-no-properties
19165 (region-beginning) (region-end)))))
19166 (read-string "LaTeX Fragment: " frag nil frag))))
19167 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19168 (let* ((tmp-in-file
19169 (let ((file (file-relative-name
19170 (make-temp-name (expand-file-name "ltxmathml-in")))))
19171 (write-region latex-frag nil file)
19172 file))
19173 (tmp-out-file (file-relative-name
19174 (make-temp-name (expand-file-name "ltxmathml-out"))))
19175 (cmd (format-spec
19176 org-latex-to-mathml-convert-command
19177 `((?j . ,(and org-latex-to-mathml-jar-file
19178 (shell-quote-argument
19179 (expand-file-name
19180 org-latex-to-mathml-jar-file))))
19181 (?I . ,(shell-quote-argument tmp-in-file))
19182 (?i . ,latex-frag)
19183 (?o . ,(shell-quote-argument tmp-out-file)))))
19184 mathml shell-command-output)
19185 (when (org-called-interactively-p 'any)
19186 (unless (org-format-latex-mathml-available-p)
19187 (user-error "LaTeX to MathML converter not configured")))
19188 (message "Running %s" cmd)
19189 (setq shell-command-output (shell-command-to-string cmd))
19190 (setq mathml
19191 (when (file-readable-p tmp-out-file)
19192 (with-current-buffer (find-file-noselect tmp-out-file t)
19193 (goto-char (point-min))
19194 (when (re-search-forward
19195 (concat
19196 (regexp-quote
19197 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19198 "[^>]*?>"
19199 "\\(.\\|\n\\)*"
19200 "</math>")
19201 nil t)
19202 (prog1 (match-string 0) (kill-buffer))))))
19203 (cond
19204 (mathml
19205 (setq mathml
19206 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19207 (when mathml-file
19208 (write-region mathml nil mathml-file))
19209 (when (org-called-interactively-p 'any)
19210 (message mathml)))
19211 ((message "LaTeX to MathML conversion failed")
19212 (message shell-command-output)))
19213 (delete-file tmp-in-file)
19214 (when (file-exists-p tmp-out-file)
19215 (delete-file tmp-out-file))
19216 mathml))
19218 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19219 prefix &optional dir)
19220 "Use `org-create-math-formula' but check local cache first."
19221 (let* ((absprefix (expand-file-name prefix dir))
19222 (print-length nil) (print-level nil)
19223 (formula-id (concat
19224 "formula-"
19225 (sha1
19226 (prin1-to-string
19227 (list latex-frag
19228 org-latex-to-mathml-convert-command)))))
19229 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19230 (formula-cache-dir (file-name-directory formula-cache)))
19232 (unless (file-directory-p formula-cache-dir)
19233 (make-directory formula-cache-dir t))
19235 (unless (file-exists-p formula-cache)
19236 (org-create-math-formula latex-frag formula-cache))
19238 (if (file-exists-p formula-cache)
19239 ;; Successful conversion. Return the link to MathML file.
19240 (org-add-props
19241 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19242 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19243 'org-latex-src-embed-type (if latex-frag-type
19244 'paragraph 'character)))
19245 ;; Failed conversion. Return the LaTeX fragment verbatim
19246 latex-frag)))
19248 (defun org-create-formula-image (string tofile options buffer &optional type)
19249 "Create an image from LaTeX source using dvipng or convert.
19250 This function calls either `org-create-formula-image-with-dvipng'
19251 or `org-create-formula-image-with-imagemagick' depending on the
19252 value of `org-latex-create-formula-image-program' or on the value
19253 of the optional TYPE variable.
19255 Note: ultimately these two function should be combined as they
19256 share a good deal of logic."
19257 (org-check-external-command
19258 "latex" "needed to convert LaTeX fragments to images")
19259 (funcall
19260 (cl-case (or type org-latex-create-formula-image-program)
19261 (dvipng
19262 (org-check-external-command
19263 "dvipng" "needed to convert LaTeX fragments to images")
19264 #'org-create-formula-image-with-dvipng)
19265 (imagemagick
19266 (org-check-external-command
19267 "convert" "you need to install imagemagick")
19268 #'org-create-formula-image-with-imagemagick)
19269 (t (error
19270 "Invalid value of `org-latex-create-formula-image-program'")))
19271 string tofile options buffer))
19273 (declare-function org-export-get-backend "ox" (name))
19274 (declare-function org-export--get-global-options "ox" (&optional backend))
19275 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19276 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19277 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19278 (defun org-create-formula--latex-header ()
19279 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19280 (let ((info (org-combine-plists (org-export--get-global-options
19281 (org-export-get-backend 'latex))
19282 (org-export--get-inbuffer-options
19283 (org-export-get-backend 'latex)))))
19284 (org-latex-guess-babel-language
19285 (org-latex-guess-inputenc
19286 (org-splice-latex-header
19287 org-format-latex-header
19288 org-latex-default-packages-alist
19289 org-latex-packages-alist t
19290 (plist-get info :latex-header)))
19291 info)))
19293 (defun org--get-display-dpi ()
19294 "Get the DPI of the display.
19296 Assumes that the display has the same pixel width in the
19297 horizontal and vertical directions."
19298 (if (display-graphic-p)
19299 (round (/ (display-pixel-height)
19300 (/ (display-mm-height) 25.4)))
19301 (error "Attempt to calculate the dpi of a non-graphic display")))
19303 ;; This function borrows from Ganesh Swami's latex2png.el
19304 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19305 "This calls dvipng."
19306 (require 'ox-latex)
19307 (let* ((tmpdir (if (featurep 'xemacs)
19308 (temp-directory)
19309 temporary-file-directory))
19310 (texfilebase (make-temp-name
19311 (expand-file-name "orgtex" tmpdir)))
19312 (texfile (concat texfilebase ".tex"))
19313 (dvifile (concat texfilebase ".dvi"))
19314 (pngfile (concat texfilebase ".png"))
19315 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19316 ;; This assumes that the display has the same pixel width in
19317 ;; the horizontal and vertical directions
19318 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19319 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19320 "Black"))
19321 (bg (or (plist-get options (if buffer :background :html-background))
19322 "Transparent")))
19323 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19324 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19325 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19326 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19327 (let ((latex-header (org-create-formula--latex-header)))
19328 (with-temp-file texfile
19329 (insert latex-header)
19330 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19331 (let ((dir default-directory))
19332 (ignore-errors
19333 (cd tmpdir)
19334 (call-process "latex" nil nil nil texfile))
19335 (cd dir))
19336 (if (not (file-exists-p dvifile))
19337 (progn (message "Failed to create dvi file from %s" texfile) nil)
19338 (ignore-errors
19339 (if (featurep 'xemacs)
19340 (call-process "dvipng" nil nil nil
19341 "-fg" fg "-bg" bg
19342 "-T" "tight"
19343 "-o" pngfile
19344 dvifile)
19345 (call-process "dvipng" nil nil nil
19346 "-fg" fg "-bg" bg
19347 "-D" dpi
19348 ;;"-x" scale "-y" scale
19349 "-T" "tight"
19350 "-o" pngfile
19351 dvifile)))
19352 (if (not (file-exists-p pngfile))
19353 (if org-format-latex-signal-error
19354 (error "Failed to create png file from %s" texfile)
19355 (message "Failed to create png file from %s" texfile)
19356 nil)
19357 ;; Use the requested file name and clean up
19358 (copy-file pngfile tofile 'replace)
19359 (dolist (e '(".dvi" ".tex" ".aux" ".log" ".png" ".out"))
19360 (when (file-exists-p (concat texfilebase e))
19361 (delete-file (concat texfilebase e))))
19362 pngfile))))
19364 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19365 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19366 "This calls convert, which is included into imagemagick."
19367 (require 'ox-latex)
19368 (let* ((tmpdir (if (featurep 'xemacs)
19369 (temp-directory)
19370 temporary-file-directory))
19371 (texfilebase (make-temp-name
19372 (expand-file-name "orgtex" tmpdir)))
19373 (texfile (concat texfilebase ".tex"))
19374 (pdffile (concat texfilebase ".pdf"))
19375 (pngfile (concat texfilebase ".png"))
19376 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19377 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19378 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19379 "black"))
19380 (bg (or (plist-get options (if buffer :background :html-background))
19381 "white")))
19382 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19383 (setq fg (org-latex-color-format fg)))
19384 (if (eq bg 'default) (setq bg (org-latex-color :background))
19385 (setq bg (org-latex-color-format
19386 (if (string= bg "Transparent") "white" bg))))
19387 (let ((latex-header (org-create-formula--latex-header)))
19388 (with-temp-file texfile
19389 (insert latex-header)
19390 (insert "\n\\begin{document}\n"
19391 "\\definecolor{fg}{rgb}{" fg "}\n"
19392 "\\definecolor{bg}{rgb}{" bg "}\n"
19393 "\n\\pagecolor{bg}\n"
19394 "\n{\\color{fg}\n"
19395 string
19396 "\n}\n"
19397 "\n\\end{document}\n")))
19398 (org-latex-compile texfile t)
19399 (if (not (file-exists-p pdffile))
19400 (progn (message "Failed to create pdf file from %s" texfile) nil)
19401 (ignore-errors
19402 (if (featurep 'xemacs)
19403 (call-process "convert" nil nil nil
19404 "-density" "96"
19405 "-trim"
19406 "-antialias"
19407 pdffile
19408 "-quality" "100"
19409 ;; "-sharpen" "0x1.0"
19410 pngfile)
19411 (call-process "convert" nil nil nil
19412 "-density" dpi
19413 "-trim"
19414 "-antialias"
19415 pdffile
19416 "-quality" "100"
19417 ;; "-sharpen" "0x1.0"
19418 pngfile)))
19419 (if (not (file-exists-p pngfile))
19420 (if org-format-latex-signal-error
19421 (error "Failed to create png file from %s" texfile)
19422 (message "Failed to create png file from %s" texfile)
19423 nil)
19424 ;; Use the requested file name and clean up
19425 (copy-file pngfile tofile 'replace)
19426 (dolist (e '(".pdf" ".tex" ".aux" ".log" ".png"))
19427 (when (file-exists-p (concat texfilebase e))
19428 (delete-file (concat texfilebase e))))
19429 pngfile))))
19431 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19432 "Fill a LaTeX header template TPL.
19433 In the template, the following place holders will be recognized:
19435 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19436 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19437 [PACKAGES] \\usepackage statements for PKG
19438 [NO-PACKAGES] do not include PKG
19439 [EXTRA] the string EXTRA
19440 [NO-EXTRA] do not include EXTRA
19442 For backward compatibility, if both the positive and the negative place
19443 holder is missing, the positive one (without the \"NO-\") will be
19444 assumed to be present at the end of the template.
19445 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19446 EXTRA is a string.
19447 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19448 (let (rpl (end ""))
19449 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19450 (setq rpl (if (or (match-end 1) (not def-pkg))
19451 "" (org-latex-packages-to-string def-pkg snippets-p t))
19452 tpl (replace-match rpl t t tpl))
19453 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19455 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19456 (setq rpl (if (or (match-end 1) (not pkg))
19457 "" (org-latex-packages-to-string pkg snippets-p t))
19458 tpl (replace-match rpl t t tpl))
19459 (when pkg (setq end
19460 (concat end "\n"
19461 (org-latex-packages-to-string pkg snippets-p)))))
19463 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19464 (setq rpl (if (or (match-end 1) (not extra))
19465 "" (concat extra "\n"))
19466 tpl (replace-match rpl t t tpl))
19467 (when (and extra (string-match "\\S-" extra))
19468 (setq end (concat end "\n" extra))))
19470 (if (string-match "\\S-" end)
19471 (concat tpl "\n" end)
19472 tpl)))
19474 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19475 "Turn an alist of packages into a string with the \\usepackage macros."
19476 (setq pkg (mapconcat (lambda(p)
19477 (cond
19478 ((stringp p) p)
19479 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19480 (format "%% Package %s omitted" (cadr p)))
19481 ((equal "" (car p))
19482 (format "\\usepackage{%s}" (cadr p)))
19484 (format "\\usepackage[%s]{%s}"
19485 (car p) (cadr p)))))
19487 "\n"))
19488 (if newline (concat pkg "\n") pkg))
19490 (defun org-dvipng-color (attr)
19491 "Return a RGB color specification for dvipng."
19492 (apply 'format "rgb %s %s %s"
19493 (mapcar 'org-normalize-color
19494 (if (featurep 'xemacs)
19495 (color-rgb-components
19496 (face-property 'default
19497 (cond ((eq attr :foreground) 'foreground)
19498 ((eq attr :background) 'background))))
19499 (color-values (face-attribute 'default attr nil))))))
19501 (defun org-dvipng-color-format (color-name)
19502 "Convert COLOR-NAME to a RGB color value for dvipng."
19503 (apply 'format "rgb %s %s %s"
19504 (mapcar 'org-normalize-color
19505 (color-values color-name))))
19507 (defun org-latex-color (attr)
19508 "Return a RGB color for the LaTeX color package."
19509 (apply 'format "%s,%s,%s"
19510 (mapcar 'org-normalize-color
19511 (if (featurep 'xemacs)
19512 (color-rgb-components
19513 (face-property 'default
19514 (cond ((eq attr :foreground) 'foreground)
19515 ((eq attr :background) 'background))))
19516 (color-values (face-attribute 'default attr nil))))))
19518 (defun org-latex-color-format (color-name)
19519 "Convert COLOR-NAME to a RGB color value."
19520 (apply 'format "%s,%s,%s"
19521 (mapcar 'org-normalize-color
19522 (color-values color-name))))
19524 (defun org-normalize-color (value)
19525 "Return string to be used as color value for an RGB component."
19526 (format "%g" (/ value 65535.0)))
19530 ;; Image display
19532 (defvar-local org-inline-image-overlays nil)
19534 (defun org-toggle-inline-images (&optional include-linked)
19535 "Toggle the display of inline images.
19536 INCLUDE-LINKED is passed to `org-display-inline-images'."
19537 (interactive "P")
19538 (if org-inline-image-overlays
19539 (progn
19540 (org-remove-inline-images)
19541 (when (org-called-interactively-p 'interactive)
19542 (message "Inline image display turned off")))
19543 (org-display-inline-images include-linked)
19544 (when (org-called-interactively-p 'interactive)
19545 (message (if org-inline-image-overlays
19546 (format "%d images displayed inline"
19547 (length org-inline-image-overlays))
19548 "No images to display inline")))))
19550 (defun org-redisplay-inline-images ()
19551 "Refresh the display of inline images."
19552 (interactive)
19553 (if (not org-inline-image-overlays)
19554 (org-toggle-inline-images)
19555 (org-toggle-inline-images)
19556 (org-toggle-inline-images)))
19558 (defun org-display-inline-images (&optional include-linked refresh beg end)
19559 "Display inline images.
19561 An inline image is a link which follows either of these
19562 conventions:
19564 1. Its path is a file with an extension matching return value
19565 from `image-file-name-regexp' and it has no contents.
19567 2. Its description consists in a single link of the previous
19568 type.
19570 When optional argument INCLUDE-LINKED is non-nil, also links with
19571 a text description part will be inlined. This can be nice for
19572 a quick look at those images, but it does not reflect what
19573 exported files will look like.
19575 When optional argument REFRESH is non-nil, refresh existing
19576 images between BEG and END. This will create new image displays
19577 only if necessary. BEG and END default to the buffer
19578 boundaries."
19579 (interactive "P")
19580 (when (display-graphic-p)
19581 (unless refresh
19582 (org-remove-inline-images)
19583 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19584 (org-with-wide-buffer
19585 (goto-char (or beg (point-min)))
19586 (let ((case-fold-search t)
19587 (file-extension-re (image-file-name-regexp)))
19588 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19589 (let ((link (save-match-data (org-element-context))))
19590 ;; Check if we're at an inline image.
19591 (when (and (equal (org-element-property :type link) "file")
19592 (or include-linked
19593 (not (org-element-property :contents-begin link)))
19594 (let ((parent (org-element-property :parent link)))
19595 (or (not (eq (org-element-type parent) 'link))
19596 (not (cdr (org-element-contents parent)))))
19597 (org-string-match-p file-extension-re
19598 (org-element-property :path link)))
19599 (let ((file (expand-file-name
19600 (org-link-unescape
19601 (org-element-property :path link)))))
19602 (when (file-exists-p file)
19603 (let ((width
19604 ;; Apply `org-image-actual-width' specifications.
19605 (cond
19606 ((not (image-type-available-p 'imagemagick)) nil)
19607 ((eq org-image-actual-width t) nil)
19608 ((listp org-image-actual-width)
19610 ;; First try to find a width among
19611 ;; attributes associated to the paragraph
19612 ;; containing link.
19613 (let ((paragraph
19614 (let ((e link))
19615 (while (and (setq e (org-element-property
19616 :parent e))
19617 (not (eq (org-element-type e)
19618 'paragraph))))
19619 e)))
19620 (when paragraph
19621 (save-excursion
19622 (goto-char (org-element-property :begin paragraph))
19623 (when
19624 (re-search-forward
19625 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19626 (org-element-property
19627 :post-affiliated paragraph)
19629 (string-to-number (match-string 1))))))
19630 ;; Otherwise, fall-back to provided number.
19631 (car org-image-actual-width)))
19632 ((numberp org-image-actual-width)
19633 org-image-actual-width)))
19634 (old (get-char-property-and-overlay
19635 (org-element-property :begin link)
19636 'org-image-overlay)))
19637 (if (and (car-safe old) refresh)
19638 (image-refresh (overlay-get (cdr old) 'display))
19639 (let ((image (create-image file
19640 (and width 'imagemagick)
19642 :width width)))
19643 (when image
19644 (let* ((link
19645 ;; If inline image is the description
19646 ;; of another link, be sure to
19647 ;; consider the latter as the one to
19648 ;; apply the overlay on.
19649 (let ((parent
19650 (org-element-property :parent link)))
19651 (if (eq (org-element-type parent) 'link)
19652 parent
19653 link)))
19654 (ov (make-overlay
19655 (org-element-property :begin link)
19656 (progn
19657 (goto-char
19658 (org-element-property :end link))
19659 (skip-chars-backward " \t")
19660 (point)))))
19661 (overlay-put ov 'display image)
19662 (overlay-put ov 'face 'default)
19663 (overlay-put ov 'org-image-overlay t)
19664 (overlay-put
19665 ov 'modification-hooks
19666 (list 'org-display-inline-remove-overlay))
19667 (push ov org-inline-image-overlays)))))))))))))))
19669 (define-obsolete-function-alias
19670 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19672 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19673 "Remove inline-display overlay if a corresponding region is modified."
19674 (let ((inhibit-modification-hooks t))
19675 (when (and ov after)
19676 (delete ov org-inline-image-overlays)
19677 (delete-overlay ov))))
19679 (defun org-remove-inline-images ()
19680 "Remove inline display of images."
19681 (interactive)
19682 (mapc #'delete-overlay org-inline-image-overlays)
19683 (setq org-inline-image-overlays nil))
19685 ;;;; Key bindings
19687 ;; Outline functions from `outline-mode-prefix-map'
19688 ;; that can be remapped in Org:
19689 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19690 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19691 (define-key org-mode-map [remap outline-forward-same-level]
19692 'org-forward-heading-same-level)
19693 (define-key org-mode-map [remap outline-backward-same-level]
19694 'org-backward-heading-same-level)
19695 (define-key org-mode-map [remap outline-show-branches]
19696 'org-kill-note-or-show-branches)
19697 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19698 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19699 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19700 (define-key org-mode-map [remap outline-next-visible-heading]
19701 'org-next-visible-heading)
19702 (define-key org-mode-map [remap outline-previous-visible-heading]
19703 'org-previous-visible-heading)
19704 (define-key org-mode-map [remap show-children] 'org-show-children)
19706 ;; Outline functions from `outline-mode-prefix-map' that can not
19707 ;; be remapped in Org:
19709 ;; - the column "key binding" shows whether the Outline function is still
19710 ;; available in Org mode on the same key that it has been bound to in
19711 ;; Outline mode:
19712 ;; - "overridden": key used for a different functionality in Org mode
19713 ;; - else: key still bound to the same Outline function in Org mode
19715 ;; | Outline function | key binding | Org replacement |
19716 ;; |------------------------------------+-------------+--------------------------|
19717 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19718 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19719 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19720 ;; | `show-entry' | overridden | no replacement |
19721 ;; | `show-branches' | `C-c C-k' | still same function |
19722 ;; | `show-subtree' | overridden | visibility cycling |
19723 ;; | `show-all' | overridden | no replacement |
19724 ;; | `hide-subtree' | overridden | visibility cycling |
19725 ;; | `hide-body' | overridden | no replacement |
19726 ;; | `hide-entry' | overridden | visibility cycling |
19727 ;; | `hide-leaves' | overridden | no replacement |
19728 ;; | `hide-sublevels' | overridden | no replacement |
19729 ;; | `hide-other' | overridden | no replacement |
19731 ;; Make `C-c C-x' a prefix key
19732 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19734 ;; TAB key with modifiers
19735 (org-defkey org-mode-map "\C-i" 'org-cycle)
19736 (org-defkey org-mode-map [(tab)] 'org-cycle)
19737 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19738 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19739 ;; The following line is necessary under Suse GNU/Linux
19740 (unless (featurep 'xemacs)
19741 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19742 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19743 (define-key org-mode-map [backtab] 'org-shifttab)
19745 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19746 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19747 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19749 ;; Cursor keys with modifiers
19750 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19751 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19752 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19753 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19755 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19756 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19757 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19758 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19759 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19760 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19762 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19763 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19764 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19765 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19767 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19768 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19769 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19770 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19772 ;; Babel keys
19773 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19774 (dolist (pair org-babel-key-bindings)
19775 (define-key org-babel-map (car pair) (cdr pair)))
19777 ;;; Extra keys for tty access.
19778 ;; We only set them when really needed because otherwise the
19779 ;; menus don't show the simple keys
19781 (when (or org-use-extra-keys
19782 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19783 (not window-system))
19784 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19785 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19786 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19787 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19788 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19789 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19790 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19791 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19792 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19793 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19794 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19795 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19796 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19797 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19798 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19799 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19800 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19801 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19802 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19803 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19804 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19805 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19806 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19807 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19808 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19809 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19810 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19811 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19813 ;; All the other keys
19815 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19816 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19817 (if (boundp 'narrow-map)
19818 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19819 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19820 (if (boundp 'narrow-map)
19821 (org-defkey narrow-map "b" 'org-narrow-to-block)
19822 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19823 (if (boundp 'narrow-map)
19824 (org-defkey narrow-map "e" 'org-narrow-to-element)
19825 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19826 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19827 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19828 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19829 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19830 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19831 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19832 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19833 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19834 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19835 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19836 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19837 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19838 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19839 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19840 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19841 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19842 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19843 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19844 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19845 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19846 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19847 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19848 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19849 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19850 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19851 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19852 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19853 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19854 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19855 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19856 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19857 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19858 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19859 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19860 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19861 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19862 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19863 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19864 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19865 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19866 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19867 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19868 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19869 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19870 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19871 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19872 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19873 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19874 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19875 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19876 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19877 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19878 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19879 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19880 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19881 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19882 (org-defkey org-mode-map "\C-c^" 'org-sort)
19883 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19884 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19885 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19886 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19887 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19888 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19889 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19890 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19891 (org-defkey org-mode-map "\C-m" 'org-return)
19892 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19893 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19894 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19895 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19896 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19897 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19898 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19899 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19900 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19901 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19902 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19903 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19904 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19905 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19906 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19907 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19908 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19909 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19910 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19911 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19912 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19913 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19914 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19915 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19916 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19918 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19919 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19920 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19922 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19923 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19924 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19925 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19926 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19927 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19928 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19929 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19930 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19931 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19932 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19933 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19934 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19935 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19936 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19937 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19938 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19939 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19940 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19941 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19942 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19943 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19945 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19946 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19947 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19948 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19949 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19951 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19953 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19955 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19956 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19958 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
19961 (when (featurep 'xemacs)
19962 (org-defkey org-mode-map 'button3 'popup-mode-menu))
19965 (defconst org-speed-commands-default
19967 ("Outline Navigation")
19968 ("n" . (org-speed-move-safe 'org-next-visible-heading))
19969 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
19970 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
19971 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
19972 ("F" . org-next-block)
19973 ("B" . org-previous-block)
19974 ("u" . (org-speed-move-safe 'outline-up-heading))
19975 ("j" . org-goto)
19976 ("g" . (org-refile t))
19977 ("Outline Visibility")
19978 ("c" . org-cycle)
19979 ("C" . org-shifttab)
19980 (" " . org-display-outline-path)
19981 ("s" . org-narrow-to-subtree)
19982 ("=" . org-columns)
19983 ("Outline Structure Editing")
19984 ("U" . org-metaup)
19985 ("D" . org-metadown)
19986 ("r" . org-metaright)
19987 ("l" . org-metaleft)
19988 ("R" . org-shiftmetaright)
19989 ("L" . org-shiftmetaleft)
19990 ("i" . (progn (forward-char 1) (call-interactively
19991 'org-insert-heading-respect-content)))
19992 ("^" . org-sort)
19993 ("w" . org-refile)
19994 ("a" . org-archive-subtree-default-with-confirmation)
19995 ("@" . org-mark-subtree)
19996 ("#" . org-toggle-comment)
19997 ("Clock Commands")
19998 ("I" . org-clock-in)
19999 ("O" . org-clock-out)
20000 ("Meta Data Editing")
20001 ("t" . org-todo)
20002 ("," . (org-priority))
20003 ("0" . (org-priority ?\ ))
20004 ("1" . (org-priority ?A))
20005 ("2" . (org-priority ?B))
20006 ("3" . (org-priority ?C))
20007 (":" . org-set-tags-command)
20008 ("e" . org-set-effort)
20009 ("E" . org-inc-effort)
20010 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20011 (org-entry-put (point) "APPT_WARNTIME" m)))
20012 ("Agenda Views etc")
20013 ("v" . org-agenda)
20014 ("/" . org-sparse-tree)
20015 ("Misc")
20016 ("o" . org-open-at-point)
20017 ("?" . org-speed-command-help)
20018 ("<" . (org-agenda-set-restriction-lock 'subtree))
20019 (">" . (org-agenda-remove-restriction-lock))
20021 "The default speed commands.")
20023 (defun org-print-speed-command (e)
20024 (if (> (length (car e)) 1)
20025 (progn
20026 (princ "\n")
20027 (princ (car e))
20028 (princ "\n")
20029 (princ (make-string (length (car e)) ?-))
20030 (princ "\n"))
20031 (princ (car e))
20032 (princ " ")
20033 (if (symbolp (cdr e))
20034 (princ (symbol-name (cdr e)))
20035 (prin1 (cdr e)))
20036 (princ "\n")))
20038 (defun org-speed-command-help ()
20039 "Show the available speed commands."
20040 (interactive)
20041 (if (not org-use-speed-commands)
20042 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20043 (with-output-to-temp-buffer "*Help*"
20044 (princ "User-defined Speed commands\n===========================\n")
20045 (mapc #'org-print-speed-command org-speed-commands-user)
20046 (princ "\n")
20047 (princ "Built-in Speed commands\n=======================\n")
20048 (mapc #'org-print-speed-command org-speed-commands-default))
20049 (with-current-buffer "*Help*"
20050 (setq truncate-lines t))))
20052 (defun org-speed-move-safe (cmd)
20053 "Execute CMD, but make sure that the cursor always ends up in a headline.
20054 If not, return to the original position and throw an error."
20055 (interactive)
20056 (let ((pos (point)))
20057 (call-interactively cmd)
20058 (unless (and (bolp) (org-at-heading-p))
20059 (goto-char pos)
20060 (error "Boundary reached while executing %s" cmd))))
20062 (defvar org-self-insert-command-undo-counter 0)
20064 (defvar org-table-auto-blank-field) ; defined in org-table.el
20065 (defvar org-speed-command nil)
20067 (define-obsolete-function-alias
20068 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20070 (defun org-speed-command-activate (keys)
20071 "Hook for activating single-letter speed commands.
20072 `org-speed-commands-default' specifies a minimal command set.
20073 Use `org-speed-commands-user' for further customization."
20074 (when (or (and (bolp) (looking-at org-outline-regexp))
20075 (and (functionp org-use-speed-commands)
20076 (funcall org-use-speed-commands)))
20077 (cdr (assoc keys (append org-speed-commands-user
20078 org-speed-commands-default)))))
20080 (define-obsolete-function-alias
20081 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20083 (defun org-babel-speed-command-activate (keys)
20084 "Hook for activating single-letter code block commands."
20085 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20086 (cdr (assoc keys org-babel-key-bindings))))
20088 (defcustom org-speed-command-hook
20089 '(org-speed-command-default-hook org-babel-speed-command-hook)
20090 "Hook for activating speed commands at strategic locations.
20091 Hook functions are called in sequence until a valid handler is
20092 found.
20094 Each hook takes a single argument, a user-pressed command key
20095 which is also a `self-insert-command' from the global map.
20097 Within the hook, examine the cursor position and the command key
20098 and return nil or a valid handler as appropriate. Handler could
20099 be one of an interactive command, a function, or a form.
20101 Set `org-use-speed-commands' to non-nil value to enable this
20102 hook. The default setting is `org-speed-command-activate'."
20103 :group 'org-structure
20104 :version "24.1"
20105 :type 'hook)
20107 (defun org-self-insert-command (N)
20108 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20109 If the cursor is in a table looking at whitespace, the whitespace is
20110 overwritten, and the table is not marked as requiring realignment."
20111 (interactive "p")
20112 (org-check-before-invisible-edit 'insert)
20113 (cond
20114 ((and org-use-speed-commands
20115 (let ((kv (this-command-keys-vector)))
20116 (setq org-speed-command
20117 (run-hook-with-args-until-success
20118 'org-speed-command-hook
20119 (make-string 1 (aref kv (1- (length kv))))))))
20120 (cond
20121 ((commandp org-speed-command)
20122 (setq this-command org-speed-command)
20123 (call-interactively org-speed-command))
20124 ((functionp org-speed-command)
20125 (funcall org-speed-command))
20126 ((and org-speed-command (listp org-speed-command))
20127 (eval org-speed-command))
20128 (t (let (org-use-speed-commands)
20129 (call-interactively 'org-self-insert-command)))))
20130 ((and
20131 (org-at-table-p)
20132 (progn
20133 ;; Check if we blank the field, and if that triggers align.
20134 (and (featurep 'org-table) org-table-auto-blank-field
20135 (memq last-command
20136 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20137 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20138 ;; Got extra space, this field does not determine
20139 ;; column width.
20140 (let (org-table-may-need-update) (org-table-blank-field))
20141 ;; No extra space, this field may determine column
20142 ;; width.
20143 (org-table-blank-field)))
20145 (eq N 1)
20146 (looking-at "[^|\n]* \\( \\)|"))
20147 ;; There is room for insertion without re-aligning the table.
20148 (delete-region (match-beginning 1) (match-end 1))
20149 (self-insert-command N))
20151 (setq org-table-may-need-update t)
20152 (self-insert-command N)
20153 (org-fix-tags-on-the-fly)
20154 (when org-self-insert-cluster-for-undo
20155 (if (not (eq last-command 'org-self-insert-command))
20156 (setq org-self-insert-command-undo-counter 1)
20157 (if (>= org-self-insert-command-undo-counter 20)
20158 (setq org-self-insert-command-undo-counter 1)
20159 (and (> org-self-insert-command-undo-counter 0)
20160 buffer-undo-list (listp buffer-undo-list)
20161 (not (cadr buffer-undo-list)) ; remove nil entry
20162 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20163 (setq org-self-insert-command-undo-counter
20164 (1+ org-self-insert-command-undo-counter))))))))
20166 (defun org-check-before-invisible-edit (kind)
20167 "Check is editing if kind KIND would be dangerous with invisible text around.
20168 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20169 ;; First, try to get out of here as quickly as possible, to reduce overhead
20170 (when (and org-catch-invisible-edits
20171 (or (not (boundp 'visible-mode)) (not visible-mode))
20172 (or (get-char-property (point) 'invisible)
20173 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20174 ;; OK, we need to take a closer look
20175 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20176 (invisible-before-point (unless (bobp) (get-char-property
20177 (1- (point)) 'invisible)))
20178 (border-and-ok-direction
20180 ;; Check if we are acting predictably before invisible text
20181 (and invisible-at-point (not invisible-before-point)
20182 (memq kind '(insert delete-backward)))
20183 ;; Check if we are acting predictably after invisible text
20184 ;; This works not well, and I have turned it off. It seems
20185 ;; better to always show and stop after invisible text.
20186 ;; (and (not invisible-at-point) invisible-before-point
20187 ;; (memq kind '(insert delete)))
20189 (when (or (memq invisible-at-point '(outline org-hide-block t))
20190 (memq invisible-before-point '(outline org-hide-block t)))
20191 (when (eq org-catch-invisible-edits 'error)
20192 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20193 (if (and org-custom-properties-overlays
20194 (y-or-n-p "Display invisible properties in this buffer? "))
20195 (org-toggle-custom-properties-visibility)
20196 ;; Make the area visible
20197 (save-excursion
20198 (when invisible-before-point
20199 (goto-char (previous-single-char-property-change
20200 (point) 'invisible)))
20201 (outline-show-subtree))
20202 (cond
20203 ((eq org-catch-invisible-edits 'show)
20204 ;; That's it, we do the edit after showing
20205 (message
20206 "Unfolding invisible region around point before editing")
20207 (sit-for 1))
20208 ((and (eq org-catch-invisible-edits 'smart)
20209 border-and-ok-direction)
20210 (message "Unfolding invisible region around point before editing"))
20212 ;; Don't do the edit, make the user repeat it in full visibility
20213 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20215 (defun org-fix-tags-on-the-fly ()
20216 (when (and (equal (char-after (point-at-bol)) ?*)
20217 (org-at-heading-p))
20218 (org-align-tags-here org-tags-column)))
20220 (defun org-delete-backward-char (N)
20221 "Like `delete-backward-char', insert whitespace at field end in tables.
20222 When deleting backwards, in tables this function will insert whitespace in
20223 front of the next \"|\" separator, to keep the table aligned. The table will
20224 still be marked for re-alignment if the field did fill the entire column,
20225 because, in this case the deletion might narrow the column."
20226 (interactive "p")
20227 (save-match-data
20228 (org-check-before-invisible-edit 'delete-backward)
20229 (if (and (org-at-table-p)
20230 (eq N 1)
20231 (string-match "|" (buffer-substring (point-at-bol) (point)))
20232 (looking-at ".*?|"))
20233 (let ((pos (point))
20234 (noalign (looking-at "[^|\n\r]* |"))
20235 (c org-table-may-need-update))
20236 (backward-delete-char N)
20237 (unless overwrite-mode
20238 (skip-chars-forward "^|")
20239 (insert " ")
20240 (goto-char (1- pos)))
20241 ;; noalign: if there were two spaces at the end, this field
20242 ;; does not determine the width of the column.
20243 (when noalign (setq org-table-may-need-update c)))
20244 (backward-delete-char N)
20245 (org-fix-tags-on-the-fly))))
20247 (defun org-delete-char (N)
20248 "Like `delete-char', but insert whitespace at field end in tables.
20249 When deleting characters, in tables this function will insert whitespace in
20250 front of the next \"|\" separator, to keep the table aligned. The table will
20251 still be marked for re-alignment if the field did fill the entire column,
20252 because, in this case the deletion might narrow the column."
20253 (interactive "p")
20254 (save-match-data
20255 (org-check-before-invisible-edit 'delete)
20256 (if (and (org-at-table-p)
20257 (not (bolp))
20258 (not (= (char-after) ?|))
20259 (eq N 1))
20260 (if (looking-at ".*?|")
20261 (let ((pos (point))
20262 (noalign (looking-at "[^|\n\r]* |"))
20263 (c org-table-may-need-update))
20264 (replace-match
20265 (concat (substring (match-string 0) 1 -1) " |") nil t)
20266 (goto-char pos)
20267 ;; noalign: if there were two spaces at the end, this field
20268 ;; does not determine the width of the column.
20269 (when noalign (setq org-table-may-need-update c)))
20270 (delete-char N))
20271 (delete-char N)
20272 (org-fix-tags-on-the-fly))))
20274 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20275 (put 'org-self-insert-command 'delete-selection
20276 (lambda ()
20277 (not (run-hook-with-args-until-success
20278 'self-insert-uses-region-functions))))
20279 (put 'orgtbl-self-insert-command 'delete-selection
20280 (lambda ()
20281 (not (run-hook-with-args-until-success
20282 'self-insert-uses-region-functions))))
20283 (put 'org-delete-char 'delete-selection 'supersede)
20284 (put 'org-delete-backward-char 'delete-selection 'supersede)
20285 (put 'org-yank 'delete-selection 'yank)
20287 ;; Make `flyspell-mode' delay after some commands
20288 (put 'org-self-insert-command 'flyspell-delayed t)
20289 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20290 (put 'org-delete-char 'flyspell-delayed t)
20291 (put 'org-delete-backward-char 'flyspell-delayed t)
20293 ;; Make pabbrev-mode expand after org-mode commands
20294 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20295 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20297 (defun org-remap (map &rest commands)
20298 "In MAP, remap the functions given in COMMANDS.
20299 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20300 (let (new old)
20301 (while commands
20302 (setq old (pop commands) new (pop commands))
20303 (if (fboundp 'command-remapping)
20304 (org-defkey map (vector 'remap old) new)
20305 (substitute-key-definition old new map global-map)))))
20307 (defun org-transpose-words ()
20308 "Transpose words for Org.
20309 This uses the `org-mode-transpose-word-syntax-table' syntax
20310 table, which interprets characters in `org-emphasis-alist' as
20311 word constituents."
20312 (interactive)
20313 (with-syntax-table org-mode-transpose-word-syntax-table
20314 (call-interactively 'transpose-words)))
20315 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20317 (when (eq org-enable-table-editor 'optimized)
20318 ;; If the user wants maximum table support, we need to hijack
20319 ;; some standard editing functions
20320 (org-remap org-mode-map
20321 'self-insert-command 'org-self-insert-command
20322 'delete-char 'org-delete-char
20323 'delete-backward-char 'org-delete-backward-char)
20324 (org-defkey org-mode-map "|" 'org-force-self-insert))
20326 (defvar org-ctrl-c-ctrl-c-hook nil
20327 "Hook for functions attaching themselves to `C-c C-c'.
20329 This can be used to add additional functionality to the C-c C-c
20330 key which executes context-dependent commands. This hook is run
20331 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20332 run after the last test.
20334 Each function will be called with no arguments. The function
20335 must check if the context is appropriate for it to act. If yes,
20336 it should do its thing and then return a non-nil value. If the
20337 context is wrong, just do nothing and return nil.")
20339 (defvar org-ctrl-c-ctrl-c-final-hook nil
20340 "Hook for functions attaching themselves to `C-c C-c'.
20342 This can be used to add additional functionality to the C-c C-c
20343 key which executes context-dependent commands. This hook is run
20344 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20345 before the first test.
20347 Each function will be called with no arguments. The function
20348 must check if the context is appropriate for it to act. If yes,
20349 it should do its thing and then return a non-nil value. If the
20350 context is wrong, just do nothing and return nil.")
20352 (defvar org-tab-first-hook nil
20353 "Hook for functions to attach themselves to TAB.
20354 See `org-ctrl-c-ctrl-c-hook' for more information.
20355 This hook runs as the first action when TAB is pressed, even before
20356 `org-cycle' messes around with the `outline-regexp' to cater for
20357 inline tasks and plain list item folding.
20358 If any function in this hook returns t, any other actions that
20359 would have been caused by TAB (such as table field motion or visibility
20360 cycling) will not occur.")
20362 (defvar org-tab-after-check-for-table-hook nil
20363 "Hook for functions to attach themselves to TAB.
20364 See `org-ctrl-c-ctrl-c-hook' for more information.
20365 This hook runs after it has been established that the cursor is not in a
20366 table, but before checking if the cursor is in a headline or if global cycling
20367 should be done.
20368 If any function in this hook returns t, not other actions like visibility
20369 cycling will be done.")
20371 (defvar org-tab-after-check-for-cycling-hook nil
20372 "Hook for functions to attach themselves to TAB.
20373 See `org-ctrl-c-ctrl-c-hook' for more information.
20374 This hook runs after it has been established that not table field motion and
20375 not visibility should be done because of current context. This is probably
20376 the place where a package like yasnippets can hook in.")
20378 (defvar org-tab-before-tab-emulation-hook nil
20379 "Hook for functions to attach themselves to TAB.
20380 See `org-ctrl-c-ctrl-c-hook' for more information.
20381 This hook runs after every other options for TAB have been exhausted, but
20382 before indentation and \t insertion takes place.")
20384 (defvar org-metaleft-hook nil
20385 "Hook for functions attaching themselves to `M-left'.
20386 See `org-ctrl-c-ctrl-c-hook' for more information.")
20387 (defvar org-metaright-hook nil
20388 "Hook for functions attaching themselves to `M-right'.
20389 See `org-ctrl-c-ctrl-c-hook' for more information.")
20390 (defvar org-metaup-hook nil
20391 "Hook for functions attaching themselves to `M-up'.
20392 See `org-ctrl-c-ctrl-c-hook' for more information.")
20393 (defvar org-metadown-hook nil
20394 "Hook for functions attaching themselves to `M-down'.
20395 See `org-ctrl-c-ctrl-c-hook' for more information.")
20396 (defvar org-shiftmetaleft-hook nil
20397 "Hook for functions attaching themselves to `M-S-left'.
20398 See `org-ctrl-c-ctrl-c-hook' for more information.")
20399 (defvar org-shiftmetaright-hook nil
20400 "Hook for functions attaching themselves to `M-S-right'.
20401 See `org-ctrl-c-ctrl-c-hook' for more information.")
20402 (defvar org-shiftmetaup-hook nil
20403 "Hook for functions attaching themselves to `M-S-up'.
20404 See `org-ctrl-c-ctrl-c-hook' for more information.")
20405 (defvar org-shiftmetadown-hook nil
20406 "Hook for functions attaching themselves to `M-S-down'.
20407 See `org-ctrl-c-ctrl-c-hook' for more information.")
20408 (defvar org-metareturn-hook nil
20409 "Hook for functions attaching themselves to `M-RET'.
20410 See `org-ctrl-c-ctrl-c-hook' for more information.")
20411 (defvar org-shiftup-hook nil
20412 "Hook for functions attaching themselves to `S-up'.
20413 See `org-ctrl-c-ctrl-c-hook' for more information.")
20414 (defvar org-shiftup-final-hook nil
20415 "Hook for functions attaching themselves to `S-up'.
20416 This one runs after all other options except shift-select have been excluded.
20417 See `org-ctrl-c-ctrl-c-hook' for more information.")
20418 (defvar org-shiftdown-hook nil
20419 "Hook for functions attaching themselves to `S-down'.
20420 See `org-ctrl-c-ctrl-c-hook' for more information.")
20421 (defvar org-shiftdown-final-hook nil
20422 "Hook for functions attaching themselves to `S-down'.
20423 This one runs after all other options except shift-select have been excluded.
20424 See `org-ctrl-c-ctrl-c-hook' for more information.")
20425 (defvar org-shiftleft-hook nil
20426 "Hook for functions attaching themselves to `S-left'.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.")
20428 (defvar org-shiftleft-final-hook nil
20429 "Hook for functions attaching themselves to `S-left'.
20430 This one runs after all other options except shift-select have been excluded.
20431 See `org-ctrl-c-ctrl-c-hook' for more information.")
20432 (defvar org-shiftright-hook nil
20433 "Hook for functions attaching themselves to `S-right'.
20434 See `org-ctrl-c-ctrl-c-hook' for more information.")
20435 (defvar org-shiftright-final-hook nil
20436 "Hook for functions attaching themselves to `S-right'.
20437 This one runs after all other options except shift-select have been excluded.
20438 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defun org-modifier-cursor-error ()
20441 "Throw an error, a modified cursor command was applied in wrong context."
20442 (user-error "This command is active in special context like tables, headlines or items"))
20444 (defun org-shiftselect-error ()
20445 "Throw an error because Shift-Cursor command was applied in wrong context."
20446 (if (and (boundp 'shift-select-mode) shift-select-mode)
20447 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20448 (user-error "This command works only in special context like headlines or timestamps")))
20450 (defun org-call-for-shift-select (cmd)
20451 (let ((this-command-keys-shift-translated t))
20452 (call-interactively cmd)))
20454 (defun org-shifttab (&optional arg)
20455 "Global visibility cycling or move to previous table field.
20456 Call `org-table-previous-field' within a table.
20457 When ARG is nil, cycle globally through visibility states.
20458 When ARG is a numeric prefix, show contents of this level."
20459 (interactive "P")
20460 (cond
20461 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20462 ((integerp arg)
20463 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20464 (message "Content view to level: %d" arg)
20465 (org-content (prefix-numeric-value arg2))
20466 (org-cycle-show-empty-lines t)
20467 (setq org-cycle-global-status 'overview)))
20468 (t (call-interactively 'org-global-cycle))))
20470 (defun org-shiftmetaleft ()
20471 "Promote subtree or delete table column.
20472 Calls `org-promote-subtree', `org-outdent-item-tree', or
20473 `org-table-delete-column', depending on context. See the
20474 individual commands for more information."
20475 (interactive)
20476 (cond
20477 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20478 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20479 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20480 ((if (not (org-region-active-p)) (org-at-item-p)
20481 (save-excursion (goto-char (region-beginning))
20482 (org-at-item-p)))
20483 (call-interactively 'org-outdent-item-tree))
20484 (t (org-modifier-cursor-error))))
20486 (defun org-shiftmetaright ()
20487 "Demote subtree or insert table column.
20488 Calls `org-demote-subtree', `org-indent-item-tree', or
20489 `org-table-insert-column', depending on context. See the
20490 individual commands for more information."
20491 (interactive)
20492 (cond
20493 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20494 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20495 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20496 ((if (not (org-region-active-p)) (org-at-item-p)
20497 (save-excursion (goto-char (region-beginning))
20498 (org-at-item-p)))
20499 (call-interactively 'org-indent-item-tree))
20500 (t (org-modifier-cursor-error))))
20502 (defun org-shiftmetaup (&optional _arg)
20503 "Drag the line at point up.
20504 In a table, kill the current row.
20505 On a clock timestamp, update the value of the timestamp like `S-<up>'
20506 but also adjust the previous clocked item in the clock history.
20507 Everywhere else, drag the line at point up."
20508 (interactive "P")
20509 (cond
20510 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20511 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20512 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20513 (call-interactively 'org-timestamp-up)))
20514 (t (call-interactively 'org-drag-line-backward))))
20516 (defun org-shiftmetadown (&optional _arg)
20517 "Drag the line at point down.
20518 In a table, insert an empty row at the current line.
20519 On a clock timestamp, update the value of the timestamp like `S-<down>'
20520 but also adjust the previous clocked item in the clock history.
20521 Everywhere else, drag the line at point down."
20522 (interactive "P")
20523 (cond
20524 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20525 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20526 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20527 (call-interactively 'org-timestamp-down)))
20528 (t (call-interactively 'org-drag-line-forward))))
20530 (defsubst org-hidden-tree-error ()
20531 (user-error
20532 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20534 (defun org-metaleft (&optional _arg)
20535 "Promote heading, list item at point or move table column left.
20537 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20538 depending on context. With no specific context, calls the Emacs
20539 default `backward-word'. See the individual commands for more
20540 information.
20542 This function runs the hook `org-metaleft-hook' as a first step,
20543 and returns at first non-nil value."
20544 (interactive "P")
20545 (cond
20546 ((run-hook-with-args-until-success 'org-metaleft-hook))
20547 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20548 ((org-with-limited-levels
20549 (or (org-at-heading-p)
20550 (and (org-region-active-p)
20551 (save-excursion
20552 (goto-char (region-beginning))
20553 (org-at-heading-p)))))
20554 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20555 (call-interactively 'org-do-promote))
20556 ;; At an inline task.
20557 ((org-at-heading-p)
20558 (call-interactively 'org-inlinetask-promote))
20559 ((or (org-at-item-p)
20560 (and (org-region-active-p)
20561 (save-excursion
20562 (goto-char (region-beginning))
20563 (org-at-item-p))))
20564 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20565 (call-interactively 'org-outdent-item))
20566 (t (call-interactively 'backward-word))))
20568 (defun org-metaright (&optional _arg)
20569 "Demote heading, list item at point or move table column right.
20571 In front of a drawer or a block keyword, indent it correctly.
20573 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20574 `org-indnet-drawer' or `org-indent-block' depending on context.
20575 With no specific context, calls the Emacs default `forward-word'.
20576 See the individual commands for more information.
20578 This function runs the hook `org-metaright-hook' as a first step,
20579 and returns at first non-nil value."
20580 (interactive "P")
20581 (cond
20582 ((run-hook-with-args-until-success 'org-metaright-hook))
20583 ((org-at-table-p) (call-interactively 'org-table-move-column))
20584 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20585 ((org-at-block-p) (call-interactively 'org-indent-block))
20586 ((org-with-limited-levels
20587 (or (org-at-heading-p)
20588 (and (org-region-active-p)
20589 (save-excursion
20590 (goto-char (region-beginning))
20591 (org-at-heading-p)))))
20592 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20593 (call-interactively 'org-do-demote))
20594 ;; At an inline task.
20595 ((org-at-heading-p)
20596 (call-interactively 'org-inlinetask-demote))
20597 ((or (org-at-item-p)
20598 (and (org-region-active-p)
20599 (save-excursion
20600 (goto-char (region-beginning))
20601 (org-at-item-p))))
20602 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20603 (call-interactively 'org-indent-item))
20604 (t (call-interactively 'forward-word))))
20606 (defun org-check-for-hidden (what)
20607 "Check if there are hidden headlines/items in the current visual line.
20608 WHAT can be either `headlines' or `items'. If the current line is
20609 an outline or item heading and it has a folded subtree below it,
20610 this function returns t, nil otherwise."
20611 (let ((re (cond
20612 ((eq what 'headlines) org-outline-regexp-bol)
20613 ((eq what 'items) (org-item-beginning-re))
20614 (t (error "This should not happen"))))
20615 beg end)
20616 (save-excursion
20617 (catch 'exit
20618 (unless (org-region-active-p)
20619 (setq beg (point-at-bol))
20620 (beginning-of-line 2)
20621 (while (and (not (eobp)) ;; this is like `next-line'
20622 (get-char-property (1- (point)) 'invisible))
20623 (beginning-of-line 2))
20624 (setq end (point))
20625 (goto-char beg)
20626 (goto-char (point-at-eol))
20627 (setq end (max end (point)))
20628 (while (re-search-forward re end t)
20629 (when (get-char-property (match-beginning 0) 'invisible)
20630 (throw 'exit t))))
20631 nil))))
20633 (defun org-metaup (&optional _arg)
20634 "Move subtree up or move table row up.
20635 Calls `org-move-subtree-up' or `org-table-move-row' or
20636 `org-move-item-up', depending on context. See the individual commands
20637 for more information."
20638 (interactive "P")
20639 (cond
20640 ((run-hook-with-args-until-success 'org-metaup-hook))
20641 ((org-region-active-p)
20642 (let* ((a (min (region-beginning) (region-end)))
20643 (b (1- (max (region-beginning) (region-end))))
20644 (c (save-excursion (goto-char a)
20645 (move-beginning-of-line 0)))
20646 (d (save-excursion (goto-char a)
20647 (move-end-of-line 0) (point))))
20648 (transpose-regions a b c d)
20649 (goto-char c)))
20650 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20651 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20652 ((org-at-item-p) (call-interactively 'org-move-item-up))
20653 (t (org-drag-element-backward))))
20655 (defun org-metadown (&optional _arg)
20656 "Move subtree down or move table row down.
20657 Calls `org-move-subtree-down' or `org-table-move-row' or
20658 `org-move-item-down', depending on context. See the individual
20659 commands for more information."
20660 (interactive "P")
20661 (cond
20662 ((run-hook-with-args-until-success 'org-metadown-hook))
20663 ((org-region-active-p)
20664 (let* ((a (min (region-beginning) (region-end)))
20665 (b (max (region-beginning) (region-end)))
20666 (c (save-excursion (goto-char b)
20667 (move-beginning-of-line 1)))
20668 (d (save-excursion (goto-char b)
20669 (move-end-of-line 1) (1+ (point)))))
20670 (transpose-regions a b c d)
20671 (goto-char d)))
20672 ((org-at-table-p) (call-interactively 'org-table-move-row))
20673 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20674 ((org-at-item-p) (call-interactively 'org-move-item-down))
20675 (t (org-drag-element-forward))))
20677 (defun org-shiftup (&optional arg)
20678 "Increase item in timestamp or increase priority of current headline.
20679 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20680 depending on context. See the individual commands for more information."
20681 (interactive "P")
20682 (cond
20683 ((run-hook-with-args-until-success 'org-shiftup-hook))
20684 ((and org-support-shift-select (org-region-active-p))
20685 (org-call-for-shift-select 'previous-line))
20686 ((org-at-timestamp-p t)
20687 (call-interactively (if org-edit-timestamp-down-means-later
20688 'org-timestamp-down 'org-timestamp-up)))
20689 ((and (not (eq org-support-shift-select 'always))
20690 org-enable-priority-commands
20691 (org-at-heading-p))
20692 (call-interactively 'org-priority-up))
20693 ((and (not org-support-shift-select) (org-at-item-p))
20694 (call-interactively 'org-previous-item))
20695 ((org-clocktable-try-shift 'up arg))
20696 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20697 (org-support-shift-select
20698 (org-call-for-shift-select 'previous-line))
20699 (t (org-shiftselect-error))))
20701 (defun org-shiftdown (&optional arg)
20702 "Decrease item in timestamp or decrease priority of current headline.
20703 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20704 depending on context. See the individual commands for more information."
20705 (interactive "P")
20706 (cond
20707 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20708 ((and org-support-shift-select (org-region-active-p))
20709 (org-call-for-shift-select 'next-line))
20710 ((org-at-timestamp-p t)
20711 (call-interactively (if org-edit-timestamp-down-means-later
20712 'org-timestamp-up 'org-timestamp-down)))
20713 ((and (not (eq org-support-shift-select 'always))
20714 org-enable-priority-commands
20715 (org-at-heading-p))
20716 (call-interactively 'org-priority-down))
20717 ((and (not org-support-shift-select) (org-at-item-p))
20718 (call-interactively 'org-next-item))
20719 ((org-clocktable-try-shift 'down arg))
20720 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20721 (org-support-shift-select
20722 (org-call-for-shift-select 'next-line))
20723 (t (org-shiftselect-error))))
20725 (defun org-shiftright (&optional arg)
20726 "Cycle the thing at point or in the current line, depending on context.
20727 Depending on context, this does one of the following:
20729 - switch a timestamp at point one day into the future
20730 - on a headline, switch to the next TODO keyword.
20731 - on an item, switch entire list to the next bullet type
20732 - on a property line, switch to the next allowed value
20733 - on a clocktable definition line, move time block into the future"
20734 (interactive "P")
20735 (cond
20736 ((run-hook-with-args-until-success 'org-shiftright-hook))
20737 ((and org-support-shift-select (org-region-active-p))
20738 (org-call-for-shift-select 'forward-char))
20739 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20740 ((and (not (eq org-support-shift-select 'always))
20741 (org-at-heading-p))
20742 (let ((org-inhibit-logging
20743 (not org-treat-S-cursor-todo-selection-as-state-change))
20744 (org-inhibit-blocking
20745 (not org-treat-S-cursor-todo-selection-as-state-change)))
20746 (org-call-with-arg 'org-todo 'right)))
20747 ((or (and org-support-shift-select
20748 (not (eq org-support-shift-select 'always))
20749 (org-at-item-bullet-p))
20750 (and (not org-support-shift-select) (org-at-item-p)))
20751 (org-call-with-arg 'org-cycle-list-bullet nil))
20752 ((and (not (eq org-support-shift-select 'always))
20753 (org-at-property-p))
20754 (call-interactively 'org-property-next-allowed-value))
20755 ((org-clocktable-try-shift 'right arg))
20756 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20757 (org-support-shift-select
20758 (org-call-for-shift-select 'forward-char))
20759 (t (org-shiftselect-error))))
20761 (defun org-shiftleft (&optional arg)
20762 "Cycle the thing at point or in the current line, depending on context.
20763 Depending on context, this does one of the following:
20765 - switch a timestamp at point one day into the past
20766 - on a headline, switch to the previous TODO keyword.
20767 - on an item, switch entire list to the previous bullet type
20768 - on a property line, switch to the previous allowed value
20769 - on a clocktable definition line, move time block into the past"
20770 (interactive "P")
20771 (cond
20772 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20773 ((and org-support-shift-select (org-region-active-p))
20774 (org-call-for-shift-select 'backward-char))
20775 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20776 ((and (not (eq org-support-shift-select 'always))
20777 (org-at-heading-p))
20778 (let ((org-inhibit-logging
20779 (not org-treat-S-cursor-todo-selection-as-state-change))
20780 (org-inhibit-blocking
20781 (not org-treat-S-cursor-todo-selection-as-state-change)))
20782 (org-call-with-arg 'org-todo 'left)))
20783 ((or (and org-support-shift-select
20784 (not (eq org-support-shift-select 'always))
20785 (org-at-item-bullet-p))
20786 (and (not org-support-shift-select) (org-at-item-p)))
20787 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20788 ((and (not (eq org-support-shift-select 'always))
20789 (org-at-property-p))
20790 (call-interactively 'org-property-previous-allowed-value))
20791 ((org-clocktable-try-shift 'left arg))
20792 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20793 (org-support-shift-select
20794 (org-call-for-shift-select 'backward-char))
20795 (t (org-shiftselect-error))))
20797 (defun org-shiftcontrolright ()
20798 "Switch to next TODO set."
20799 (interactive)
20800 (cond
20801 ((and org-support-shift-select (org-region-active-p))
20802 (org-call-for-shift-select 'forward-word))
20803 ((and (not (eq org-support-shift-select 'always))
20804 (org-at-heading-p))
20805 (org-call-with-arg 'org-todo 'nextset))
20806 (org-support-shift-select
20807 (org-call-for-shift-select 'forward-word))
20808 (t (org-shiftselect-error))))
20810 (defun org-shiftcontrolleft ()
20811 "Switch to previous TODO set."
20812 (interactive)
20813 (cond
20814 ((and org-support-shift-select (org-region-active-p))
20815 (org-call-for-shift-select 'backward-word))
20816 ((and (not (eq org-support-shift-select 'always))
20817 (org-at-heading-p))
20818 (org-call-with-arg 'org-todo 'previousset))
20819 (org-support-shift-select
20820 (org-call-for-shift-select 'backward-word))
20821 (t (org-shiftselect-error))))
20823 (defun org-shiftcontrolup (&optional n)
20824 "Change timestamps synchronously up in CLOCK log lines.
20825 Optional argument N tells to change by that many units."
20826 (interactive "P")
20827 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20828 (let (org-support-shift-select)
20829 (org-clock-timestamps-up n))
20830 (user-error "Not at a clock log")))
20832 (defun org-shiftcontroldown (&optional n)
20833 "Change timestamps synchronously down in CLOCK log lines.
20834 Optional argument N tells to change by that many units."
20835 (interactive "P")
20836 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20837 (let (org-support-shift-select)
20838 (org-clock-timestamps-down n))
20839 (user-error "Not at a clock log")))
20841 (defun org-increase-number-at-point (&optional inc)
20842 "Increment the number at point.
20843 With an optional prefix numeric argument INC, increment using
20844 this numeric value."
20845 (interactive "p")
20846 (if (not (number-at-point))
20847 (user-error "Not on a number")
20848 (unless inc (setq inc 1))
20849 (let ((pos (point))
20850 (beg (skip-chars-backward "-+^/*0-9eE."))
20851 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20852 (setq nap (buffer-substring-no-properties
20853 (+ pos beg) (+ pos beg end)))
20854 (delete-region (+ pos beg) (+ pos beg end))
20855 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20856 (when (org-at-table-p)
20857 (org-table-align)
20858 (org-table-end-of-field 1))))
20860 (defun org-decrease-number-at-point (&optional inc)
20861 "Decrement the number at point.
20862 With an optional prefix numeric argument INC, decrement using
20863 this numeric value."
20864 (interactive "p")
20865 (org-increase-number-at-point (- (or inc 1))))
20867 (defun org-ctrl-c-ret ()
20868 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20869 (interactive)
20870 (cond
20871 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20872 (t (call-interactively 'org-insert-heading))))
20874 (defun org-find-visible ()
20875 (let ((s (point)))
20876 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20877 (get-char-property s 'invisible)))
20879 (defun org-find-invisible ()
20880 (let ((s (point)))
20881 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20882 (not (get-char-property s 'invisible))))
20885 (defun org-copy-visible (beg end)
20886 "Copy the visible parts of the region."
20887 (interactive "r")
20888 (let (snippets s)
20889 (save-excursion
20890 (save-restriction
20891 (narrow-to-region beg end)
20892 (setq s (goto-char (point-min)))
20893 (while (not (= (point) (point-max)))
20894 (goto-char (org-find-invisible))
20895 (push (buffer-substring s (point)) snippets)
20896 (setq s (goto-char (org-find-visible))))))
20897 (kill-new (apply 'concat (nreverse snippets)))))
20899 (defun org-copy-special ()
20900 "Copy region in table or copy current subtree.
20901 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20902 See the individual commands for more information."
20903 (interactive)
20904 (call-interactively
20905 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20907 (defun org-cut-special ()
20908 "Cut region in table or cut current subtree.
20909 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20910 See the individual commands for more information."
20911 (interactive)
20912 (call-interactively
20913 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20915 (defun org-paste-special (arg)
20916 "Paste rectangular region into table, or past subtree relative to level.
20917 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20918 See the individual commands for more information."
20919 (interactive "P")
20920 (if (org-at-table-p)
20921 (org-table-paste-rectangle)
20922 (org-paste-subtree arg)))
20924 (defsubst org-in-fixed-width-region-p ()
20925 "Is point in a fixed-width region?"
20926 (save-match-data
20927 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20929 (defun org-edit-special (&optional arg)
20930 "Call a special editor for the element at point.
20931 When at a table, call the formula editor with `org-table-edit-formulas'.
20932 When in a source code block, call `org-edit-src-code'.
20933 When in a fixed-width region, call `org-edit-fixed-width-region'.
20934 When in an export block, call `org-edit-export-block'.
20935 When at an #+INCLUDE keyword, visit the included file.
20936 When at a footnote reference, call `org-edit-footnote-reference'
20937 On a link, call `ffap' to visit the link at point.
20938 Otherwise, return a user error."
20939 (interactive "P")
20940 (let ((element (org-element-at-point)))
20941 (cl-assert (not buffer-read-only) nil
20942 "Buffer is read-only: %s" (buffer-name))
20943 (pcase (org-element-type element)
20944 (`src-block
20945 (if (not arg) (org-edit-src-code)
20946 (let* ((info (org-babel-get-src-block-info))
20947 (lang (nth 0 info))
20948 (params (nth 2 info))
20949 (session (cdr (assq :session params))))
20950 (if (not session) (org-edit-src-code)
20951 ;; At a src-block with a session and function called with
20952 ;; an ARG: switch to the buffer related to the inferior
20953 ;; process.
20954 (switch-to-buffer
20955 (funcall (intern (concat "org-babel-prep-session:" lang))
20956 session params))))))
20957 (`keyword
20958 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
20959 (org-open-link-from-string
20960 (format "[[%s]]"
20961 (expand-file-name
20962 (let ((value (org-element-property :value element)))
20963 (cond ((not (org-string-nw-p value))
20964 (user-error "No file to edit"))
20965 ((string-match "\\`\"\\(.*?\\)\"" value)
20966 (match-string 1 value))
20967 ((string-match "\\`[^ \t\"]\\S-*" value)
20968 (match-string 0 value))
20969 (t (user-error "No valid file specified")))))))
20970 (user-error "No special environment to edit here")))
20971 (`table
20972 (if (eq (org-element-property :type element) 'table.el)
20973 (org-edit-table.el)
20974 (call-interactively 'org-table-edit-formulas)))
20975 ;; Only Org tables contain `table-row' type elements.
20976 (`table-row (call-interactively 'org-table-edit-formulas))
20977 (`example-block (org-edit-src-code))
20978 (`export-block (org-edit-export-block))
20979 (`fixed-width (org-edit-fixed-width-region))
20981 ;; No notable element at point. Though, we may be at a link or
20982 ;; a footnote reference, which are objects. Thus, scan deeper.
20983 (let ((context (org-element-context element)))
20984 (pcase (org-element-type context)
20985 (`footnote-reference (org-edit-footnote-reference))
20986 (`inline-src-block (org-edit-inline-src-code))
20987 (`link (call-interactively #'ffap))
20988 (_ (user-error "No special environment to edit here"))))))))
20990 (defvar org-table-coordinate-overlays) ; defined in org-table.el
20991 (defun org-ctrl-c-ctrl-c (&optional arg)
20992 "Set tags in headline, or update according to changed information at point.
20994 This command does many different things, depending on context:
20996 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
20997 this is what we do.
20999 - If the cursor is on a statistics cookie, update it.
21001 - If the cursor is in a headline, prompt for tags and insert them
21002 into the current line, aligned to `org-tags-column'. When called
21003 with prefix arg, realign all tags in the current buffer.
21005 - If the cursor is in one of the special #+KEYWORD lines, this
21006 triggers scanning the buffer for these lines and updating the
21007 information.
21009 - If the cursor is inside a table, realign the table. This command
21010 works even if the automatic table editor has been turned off.
21012 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21013 the entire table.
21015 - If the cursor is at a footnote reference or definition, jump to
21016 the corresponding definition or references, respectively.
21018 - If the cursor is a the beginning of a dynamic block, update it.
21020 - If the current buffer is a capture buffer, close note and file it.
21022 - If the cursor is on a <<<target>>>, update radio targets and
21023 corresponding links in this buffer.
21025 - If the cursor is on a numbered item in a plain list, renumber the
21026 ordered list.
21028 - If the cursor is on a checkbox, toggle it.
21030 - If the cursor is on a code block, evaluate it. The variable
21031 `org-confirm-babel-evaluate' can be used to control prompting
21032 before code block evaluation, by default every code block
21033 evaluation requires confirmation. Code block evaluation can be
21034 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21035 (interactive "P")
21036 (cond
21037 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21038 org-occur-highlights)
21039 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21040 (org-remove-occur-highlights)
21041 (message "Temporary highlights/overlays removed from current buffer"))
21042 ((and (local-variable-p 'org-finish-function (current-buffer))
21043 (fboundp org-finish-function))
21044 (funcall org-finish-function))
21045 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21047 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21048 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21049 (user-error "C-c C-c can do nothing useful at this location"))
21050 (let* ((context (org-element-context))
21051 (type (org-element-type context)))
21052 (cl-case type
21053 ;; When at a link, act according to the parent instead.
21054 (link (setq context (org-element-property :parent context))
21055 (setq type (org-element-type context)))
21056 ;; Unsupported object types: refer to the first supported
21057 ;; element or object containing it.
21058 ((bold code entity export-snippet inline-babel-call inline-src-block
21059 italic latex-fragment line-break macro strike-through subscript
21060 superscript underline verbatim)
21061 (setq context
21062 (org-element-lineage
21063 context '(radio-target paragraph verse-block table-cell)))))
21064 ;; For convenience: at the first line of a paragraph on the
21065 ;; same line as an item, apply function on that item instead.
21066 (when (eq type 'paragraph)
21067 (let ((parent (org-element-property :parent context)))
21068 (when (and (eq (org-element-type parent) 'item)
21069 (= (line-beginning-position)
21070 (org-element-property :begin parent)))
21071 (setq context parent type 'item))))
21072 ;; Act according to type of element or object at point.
21073 (cl-case type
21074 (clock (org-clock-update-time-maybe))
21075 (dynamic-block
21076 (save-excursion
21077 (goto-char (org-element-property :post-affiliated context))
21078 (org-update-dblock)))
21079 (footnote-definition
21080 (goto-char (org-element-property :post-affiliated context))
21081 (call-interactively 'org-footnote-action))
21082 (footnote-reference (call-interactively 'org-footnote-action))
21083 ((headline inlinetask)
21084 (save-excursion (goto-char (org-element-property :begin context))
21085 (call-interactively 'org-set-tags)))
21086 (item
21087 ;; At an item: a double C-u set checkbox to "[-]"
21088 ;; unconditionally, whereas a single one will toggle its
21089 ;; presence. Without a universal argument, if the item
21090 ;; has a checkbox, toggle it. Otherwise repair the list.
21091 (let* ((box (org-element-property :checkbox context))
21092 (struct (org-element-property :structure context))
21093 (old-struct (copy-tree struct))
21094 (parents (org-list-parents-alist struct))
21095 (prevs (org-list-prevs-alist struct))
21096 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21097 (org-list-set-checkbox
21098 (org-element-property :begin context) struct
21099 (cond ((equal arg '(16)) "[-]")
21100 ((and (not box) (equal arg '(4))) "[ ]")
21101 ((or (not box) (equal arg '(4))) nil)
21102 ((eq box 'on) "[ ]")
21103 (t "[X]")))
21104 ;; Mimic `org-list-write-struct' but with grabbing
21105 ;; a return value from `org-list-struct-fix-box'.
21106 (org-list-struct-fix-ind struct parents 2)
21107 (org-list-struct-fix-item-end struct)
21108 (org-list-struct-fix-bul struct prevs)
21109 (org-list-struct-fix-ind struct parents)
21110 (let ((block-item
21111 (org-list-struct-fix-box struct parents prevs orderedp)))
21112 (if (and box (equal struct old-struct))
21113 (if (equal arg '(16))
21114 (message "Checkboxes already reset")
21115 (user-error "Cannot toggle this checkbox: %s"
21116 (if (eq box 'on)
21117 "all subitems checked"
21118 "unchecked subitems")))
21119 (org-list-struct-apply-struct struct old-struct)
21120 (org-update-checkbox-count-maybe))
21121 (when block-item
21122 (message "Checkboxes were removed due to empty box at line %d"
21123 (org-current-line block-item))))))
21124 (keyword
21125 (let ((org-inhibit-startup-visibility-stuff t)
21126 (org-startup-align-all-tables nil))
21127 (when (boundp 'org-table-coordinate-overlays)
21128 (mapc #'delete-overlay org-table-coordinate-overlays)
21129 (setq org-table-coordinate-overlays nil))
21130 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21131 (message "Local setup has been refreshed"))
21132 (plain-list
21133 ;; At a plain list, with a double C-u argument, set
21134 ;; checkboxes of each item to "[-]", whereas a single one
21135 ;; will toggle their presence according to the state of the
21136 ;; first item in the list. Without an argument, repair the
21137 ;; list.
21138 (let* ((begin (org-element-property :contents-begin context))
21139 (beginm (move-marker (make-marker) begin))
21140 (struct (org-element-property :structure context))
21141 (old-struct (copy-tree struct))
21142 (first-box (save-excursion
21143 (goto-char begin)
21144 (looking-at org-list-full-item-re)
21145 (match-string-no-properties 3)))
21146 (new-box (cond ((equal arg '(16)) "[-]")
21147 ((equal arg '(4)) (unless first-box "[ ]"))
21148 ((equal first-box "[X]") "[ ]")
21149 (t "[X]"))))
21150 (cond
21151 (arg
21152 (dolist (pos
21153 (org-list-get-all-items
21154 begin struct (org-list-prevs-alist struct)))
21155 (org-list-set-checkbox pos struct new-box)))
21156 ((and first-box (eq (point) begin))
21157 ;; For convenience, when point is at bol on the first
21158 ;; item of the list and no argument is provided, simply
21159 ;; toggle checkbox of that item, if any.
21160 (org-list-set-checkbox begin struct new-box)))
21161 (org-list-write-struct
21162 struct (org-list-parents-alist struct) old-struct)
21163 (org-update-checkbox-count-maybe)
21164 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21165 ((property-drawer node-property)
21166 (call-interactively 'org-property-action))
21167 ((radio-target target)
21168 (call-interactively 'org-update-radio-target-regexp))
21169 (statistics-cookie
21170 (call-interactively 'org-update-statistics-cookies))
21171 ((table table-cell table-row)
21172 ;; At a table, recalculate every field and align it. Also
21173 ;; send the table if necessary. If the table has
21174 ;; a `table.el' type, just give up. At a table row or
21175 ;; cell, maybe recalculate line but always align table.
21176 (if (eq (org-element-property :type context) 'table.el)
21177 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21178 Use \\[org-edit-special] to edit table.el tables"))
21179 (let ((org-enable-table-editor t))
21180 (if (or (eq type 'table)
21181 ;; Check if point is at a TBLFM line.
21182 (and (eq type 'table-row)
21183 (= (point) (org-element-property :end context))))
21184 (save-excursion
21185 (if (org-at-TBLFM-p)
21186 (progn (require 'org-table)
21187 (org-table-calc-current-TBLFM))
21188 (goto-char (org-element-property :contents-begin context))
21189 (org-call-with-arg 'org-table-recalculate (or arg t))
21190 (orgtbl-send-table 'maybe)))
21191 (org-table-maybe-eval-formula)
21192 (cond (arg (call-interactively 'org-table-recalculate))
21193 ((org-table-maybe-recalculate-line))
21194 (t (org-table-align)))))))
21195 (timestamp (org-timestamp-change 0 'day))
21196 (otherwise
21197 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21198 (user-error
21199 "C-c C-c can do nothing useful at this location")))))))))
21201 (defun org-mode-restart ()
21202 (interactive)
21203 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21204 (funcall major-mode)
21205 (hack-local-variables)
21206 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21207 (org-indent-mode -1)))
21208 (message "%s restarted" major-mode))
21210 (defun org-kill-note-or-show-branches ()
21211 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21212 (interactive)
21213 (if (not org-finish-function)
21214 (progn
21215 (outline-hide-subtree)
21216 (call-interactively 'outline-show-branches))
21217 (let ((org-note-abort t))
21218 (funcall org-finish-function))))
21220 (defun org-delete-indentation (&optional ARG)
21221 "Join current line to previous and fix whitespace at join.
21223 If previous line is a headline add to headline title. Otherwise
21224 the function calls `delete-indentation'.
21226 With argument, join this line to following line."
21227 (interactive "*P")
21228 (if (save-excursion
21229 (if ARG (beginning-of-line)
21230 (forward-line -1))
21231 (looking-at org-complex-heading-regexp))
21232 ;; At headline.
21233 (let ((tags-column (when (match-beginning 5)
21234 (save-excursion (goto-char (match-beginning 5))
21235 (current-column))))
21236 (string (concat " " (progn (when ARG (forward-line 1))
21237 (org-trim (delete-and-extract-region
21238 (line-beginning-position)
21239 (line-end-position)))))))
21240 (unless (bobp) (delete-region (point) (1- (point))))
21241 (goto-char (or (match-end 4)
21242 (match-beginning 5)
21243 (match-end 0)))
21244 (skip-chars-backward " \t")
21245 (save-excursion (insert string))
21246 ;; Adjust alignment of tags.
21247 (when tags-column
21248 (org-align-tags-here (if org-auto-align-tags
21249 org-tags-column
21250 tags-column))))
21251 (delete-indentation ARG)))
21253 (defun org-open-line (n)
21254 "Insert a new row in tables, call `open-line' elsewhere.
21255 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21256 (interactive "*p")
21257 (cond
21258 ((not org-special-ctrl-o)
21259 (open-line n))
21260 ((org-at-table-p)
21261 (org-table-insert-row))
21263 (open-line n))))
21265 (defun org-return (&optional indent)
21266 "Goto next table row or insert a newline.
21268 Calls `org-table-next-row' or `newline', depending on context.
21270 When optional INDENT argument is non-nil, call
21271 `newline-and-indent' instead of `newline'.
21273 When `org-return-follows-link' is non-nil and point is on
21274 a timestamp or a link, call `org-open-at-point'. However, it
21275 will not happen if point is in a table or on a \"dead\"
21276 object (e.g., within a comment). In these case, you need to use
21277 `org-open-at-point' directly."
21278 (interactive)
21279 (let ((context (if org-return-follows-link (org-element-context)
21280 (org-element-at-point))))
21281 (cond
21282 ;; In a table, call `org-table-next-row'.
21283 ((or (and (eq (org-element-type context) 'table)
21284 (>= (point) (org-element-property :contents-begin context))
21285 (< (point) (org-element-property :contents-end context)))
21286 (org-element-lineage context '(table-row table-cell) t))
21287 (org-table-justify-field-maybe)
21288 (call-interactively #'org-table-next-row))
21289 ;; On a link or a timestamp, call `org-open-at-point' if
21290 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21291 ;; locations, e.g., in a comment, as `org-open-at-point'.
21292 ((and org-return-follows-link
21293 (or (org-in-regexp org-ts-regexp-both nil t)
21294 (org-in-regexp org-tsr-regexp-both nil t)
21295 (org-in-regexp org-any-link-re nil t)))
21296 (call-interactively #'org-open-at-point))
21297 ;; Insert newline in heading, but preserve tags.
21298 ((and (not (bolp))
21299 (save-excursion (beginning-of-line)
21300 (looking-at org-complex-heading-regexp)))
21301 ;; At headline. Split line. However, if point is on keyword,
21302 ;; priority cookie or tags, do not break any of them: add
21303 ;; a newline after the headline instead.
21304 (let ((tags-column (and (match-beginning 5)
21305 (save-excursion (goto-char (match-beginning 5))
21306 (current-column))))
21307 (string
21308 (when (and (match-end 4)
21309 (>= (point)
21310 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21311 (<= (point) (match-end 4)))
21312 (delete-and-extract-region (point) (match-end 4)))))
21313 (when (and tags-column string) ; Adjust tag alignment.
21314 (org-align-tags-here
21315 (if org-auto-align-tags org-tags-column tags-column)))
21316 (end-of-line)
21317 (org-show-entry)
21318 (if indent (newline-and-indent) (newline))
21319 (when string (save-excursion (insert (org-trim string))))))
21320 ;; In a list, make sure indenting keeps trailing text within.
21321 ((and indent
21322 (not (eolp))
21323 (org-element-lineage context '(item)))
21324 (let ((trailing-data
21325 (delete-and-extract-region (point) (line-end-position))))
21326 (newline-and-indent)
21327 (save-excursion (insert trailing-data))))
21328 (t (if indent (newline-and-indent) (newline))))))
21330 (defun org-return-indent ()
21331 "Goto next table row or insert a newline and indent.
21332 Calls `org-table-next-row' or `newline-and-indent', depending on
21333 context. See the individual commands for more information."
21334 (interactive)
21335 (org-return t))
21337 (defun org-ctrl-c-star ()
21338 "Compute table, or change heading status of lines.
21339 Calls `org-table-recalculate' or `org-toggle-heading',
21340 depending on context."
21341 (interactive)
21342 (cond
21343 ((org-at-table-p)
21344 (call-interactively 'org-table-recalculate))
21346 ;; Convert all lines in region to list items
21347 (call-interactively 'org-toggle-heading))))
21349 (defun org-ctrl-c-minus ()
21350 "Insert separator line in table or modify bullet status of line.
21351 Also turns a plain line or a region of lines into list items.
21352 Calls `org-table-insert-hline', `org-toggle-item', or
21353 `org-cycle-list-bullet', depending on context."
21354 (interactive)
21355 (cond
21356 ((org-at-table-p)
21357 (call-interactively 'org-table-insert-hline))
21358 ((org-region-active-p)
21359 (call-interactively 'org-toggle-item))
21360 ((org-in-item-p)
21361 (call-interactively 'org-cycle-list-bullet))
21363 (call-interactively 'org-toggle-item))))
21365 (defun org-toggle-item (arg)
21366 "Convert headings or normal lines to items, items to normal lines.
21367 If there is no active region, only the current line is considered.
21369 If the first non blank line in the region is a headline, convert
21370 all headlines to items, shifting text accordingly.
21372 If it is an item, convert all items to normal lines.
21374 If it is normal text, change region into a list of items.
21375 With a prefix argument ARG, change the region in a single item."
21376 (interactive "P")
21377 (let ((shift-text
21378 (function
21379 ;; Shift text in current section to IND, from point to END.
21380 ;; The function leaves point to END line.
21381 (lambda (ind end)
21382 (let ((min-i 1000) (end (copy-marker end)))
21383 ;; First determine the minimum indentation (MIN-I) of
21384 ;; the text.
21385 (save-excursion
21386 (catch 'exit
21387 (while (< (point) end)
21388 (let ((i (org-get-indentation)))
21389 (cond
21390 ;; Skip blank lines and inline tasks.
21391 ((looking-at "^[ \t]*$"))
21392 ((looking-at org-outline-regexp-bol))
21393 ;; We can't find less than 0 indentation.
21394 ((zerop i) (throw 'exit (setq min-i 0)))
21395 ((< i min-i) (setq min-i i))))
21396 (forward-line))))
21397 ;; Then indent each line so that a line indented to
21398 ;; MIN-I becomes indented to IND. Ignore blank lines
21399 ;; and inline tasks in the process.
21400 (let ((delta (- ind min-i)))
21401 (while (< (point) end)
21402 (unless (or (looking-at "^[ \t]*$")
21403 (looking-at org-outline-regexp-bol))
21404 (org-indent-line-to (+ (org-get-indentation) delta)))
21405 (forward-line)))))))
21406 (skip-blanks
21407 (function
21408 ;; Return beginning of first non-blank line, starting from
21409 ;; line at POS.
21410 (lambda (pos)
21411 (save-excursion
21412 (goto-char pos)
21413 (skip-chars-forward " \r\t\n")
21414 (point-at-bol)))))
21415 beg end)
21416 ;; Determine boundaries of changes.
21417 (if (org-region-active-p)
21418 (setq beg (funcall skip-blanks (region-beginning))
21419 end (copy-marker (region-end)))
21420 (setq beg (funcall skip-blanks (point-at-bol))
21421 end (copy-marker (point-at-eol))))
21422 ;; Depending on the starting line, choose an action on the text
21423 ;; between BEG and END.
21424 (org-with-limited-levels
21425 (save-excursion
21426 (goto-char beg)
21427 (cond
21428 ;; Case 1. Start at an item: de-itemize. Note that it only
21429 ;; happens when a region is active: `org-ctrl-c-minus'
21430 ;; would call `org-cycle-list-bullet' otherwise.
21431 ((org-at-item-p)
21432 (while (< (point) end)
21433 (when (org-at-item-p)
21434 (skip-chars-forward " \t")
21435 (delete-region (point) (match-end 0)))
21436 (forward-line)))
21437 ;; Case 2. Start at an heading: convert to items.
21438 ((org-at-heading-p)
21439 (let* ((bul (org-list-bullet-string "-"))
21440 (bul-len (length bul))
21441 (done (org-entry-is-done-p))
21442 (todo (org-entry-is-todo-p))
21443 ;; Indentation of the first heading. It should be
21444 ;; relative to the indentation of its parent, if any.
21445 (start-ind (save-excursion
21446 (cond
21447 ((not org-adapt-indentation) 0)
21448 ((not (outline-previous-heading)) 0)
21449 (t (length (match-string 0))))))
21450 ;; Level of first heading. Further headings will be
21451 ;; compared to it to determine hierarchy in the list.
21452 (ref-level (org-reduced-level (org-outline-level))))
21453 (when (or done todo) (org-todo ""))
21454 (while (< (point) end)
21455 (let* ((level (org-reduced-level (org-outline-level)))
21456 (delta (max 0 (- level ref-level))))
21457 ;; If current headline is less indented than the first
21458 ;; one, set it as reference, in order to preserve
21459 ;; subtrees.
21460 (when (< level ref-level) (setq ref-level level))
21461 (replace-match bul t t)
21462 (org-indent-line-to (+ start-ind (* delta bul-len)))
21463 (when (or done todo)
21464 (let* ((struct (org-list-struct))
21465 (old (copy-tree struct)))
21466 (org-list-set-checkbox (line-beginning-position)
21467 struct
21468 (if done "[X]" "[ ]"))
21469 (org-list-write-struct struct
21470 (org-list-parents-alist struct)
21471 old)))
21472 ;; Ensure all text down to END (or SECTION-END) belongs
21473 ;; to the newly created item.
21474 (let ((section-end (save-excursion
21475 (or (outline-next-heading) (point)))))
21476 (forward-line)
21477 (funcall shift-text
21478 (+ start-ind (* (1+ delta) bul-len))
21479 (min end section-end)))))))
21480 ;; Case 3. Normal line with ARG: make the first line of region
21481 ;; an item, and shift indentation of others lines to
21482 ;; set them as item's body.
21483 (arg (let* ((bul (org-list-bullet-string "-"))
21484 (bul-len (length bul))
21485 (ref-ind (org-get-indentation)))
21486 (skip-chars-forward " \t")
21487 (insert bul)
21488 (forward-line)
21489 (while (< (point) end)
21490 ;; Ensure that lines less indented than first one
21491 ;; still get included in item body.
21492 (funcall shift-text
21493 (+ ref-ind bul-len)
21494 (min end (save-excursion (or (outline-next-heading)
21495 (point)))))
21496 (forward-line))))
21497 ;; Case 4. Normal line without ARG: turn each non-item line
21498 ;; into an item.
21500 (while (< (point) end)
21501 (unless (or (org-at-heading-p) (org-at-item-p))
21502 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21503 (replace-match
21504 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21505 (forward-line))))))))
21507 (defun org-toggle-heading (&optional nstars)
21508 "Convert headings to normal text, or items or text to headings.
21509 If there is no active region, only convert the current line.
21511 With a \\[universal-argument] prefix, convert the whole list at
21512 point into heading.
21514 In a region:
21516 - If the first non blank line is a headline, remove the stars
21517 from all headlines in the region.
21519 - If it is a normal line, turn each and every normal line (i.e.,
21520 not an heading or an item) in the region into headings. If you
21521 want to convert only the first line of this region, use one
21522 universal prefix argument.
21524 - If it is a plain list item, turn all plain list items into headings.
21526 When converting a line into a heading, the number of stars is chosen
21527 such that the lines become children of the current entry. However,
21528 when a numeric prefix argument is given, its value determines the
21529 number of stars to add."
21530 (interactive "P")
21531 (let ((skip-blanks
21532 (function
21533 ;; Return beginning of first non-blank line, starting from
21534 ;; line at POS.
21535 (lambda (pos)
21536 (save-excursion
21537 (goto-char pos)
21538 (while (org-at-comment-p) (forward-line))
21539 (skip-chars-forward " \r\t\n")
21540 (point-at-bol)))))
21541 beg end toggled)
21542 ;; Determine boundaries of changes. If a universal prefix has
21543 ;; been given, put the list in a region. If region ends at a bol,
21544 ;; do not consider the last line to be in the region.
21546 (when (and current-prefix-arg (org-at-item-p))
21547 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21548 (org-mark-element))
21550 (if (org-region-active-p)
21551 (setq beg (funcall skip-blanks (region-beginning))
21552 end (copy-marker (save-excursion
21553 (goto-char (region-end))
21554 (if (bolp) (point) (point-at-eol)))))
21555 (setq beg (funcall skip-blanks (point-at-bol))
21556 end (copy-marker (point-at-eol))))
21557 ;; Ensure inline tasks don't count as headings.
21558 (org-with-limited-levels
21559 (save-excursion
21560 (goto-char beg)
21561 (cond
21562 ;; Case 1. Started at an heading: de-star headings.
21563 ((org-at-heading-p)
21564 (while (< (point) end)
21565 (when (org-at-heading-p t)
21566 (looking-at org-outline-regexp) (replace-match "")
21567 (setq toggled t))
21568 (forward-line)))
21569 ;; Case 2. Started at an item: change items into headlines.
21570 ;; One star will be added by `org-list-to-subtree'.
21571 ((org-at-item-p)
21572 (while (< (point) end)
21573 (when (org-at-item-p)
21574 ;; Pay attention to cases when region ends before list.
21575 (let* ((struct (org-list-struct))
21576 (list-end
21577 (min (org-list-get-bottom-point struct) (1+ end))))
21578 (save-restriction
21579 (narrow-to-region (point) list-end)
21580 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21581 (setq toggled t))
21582 (forward-line)))
21583 ;; Case 3. Started at normal text: make every line an heading,
21584 ;; skipping headlines and items.
21585 (t (let* ((stars
21586 (make-string
21587 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21588 (add-stars
21589 (cond (nstars "") ; stars from prefix only
21590 ((equal stars "") "*") ; before first heading
21591 (org-odd-levels-only "**") ; inside heading, odd
21592 (t "*"))) ; inside heading, oddeven
21593 (rpl (concat stars add-stars " "))
21594 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21595 (while (< (point) (if (equal nstars '(4)) lend end))
21596 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21597 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21598 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21599 (forward-line)))))))
21600 (unless toggled (message "Cannot toggle heading from here"))))
21602 (defun org-meta-return (&optional _arg)
21603 "Insert a new heading or wrap a region in a table.
21604 Calls `org-insert-heading' or `org-table-wrap-region', depending
21605 on context. See the individual commands for more information."
21606 (interactive)
21607 (org-check-before-invisible-edit 'insert)
21608 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21609 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21610 #'org-insert-heading))))
21612 ;;; Menu entries
21614 (defsubst org-in-subtree-not-table-p ()
21615 "Are we in a subtree and not in a table?"
21616 (and (not (org-before-first-heading-p))
21617 (not (org-at-table-p))))
21619 ;; Define the Org-mode menus
21620 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21621 '("Tbl"
21622 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21623 ["Next Field" org-cycle (org-at-table-p)]
21624 ["Previous Field" org-shifttab (org-at-table-p)]
21625 ["Next Row" org-return (org-at-table-p)]
21626 "--"
21627 ["Blank Field" org-table-blank-field (org-at-table-p)]
21628 ["Edit Field" org-table-edit-field (org-at-table-p)]
21629 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21630 "--"
21631 ("Column"
21632 ["Move Column Left" org-metaleft (org-at-table-p)]
21633 ["Move Column Right" org-metaright (org-at-table-p)]
21634 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21635 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21636 ("Row"
21637 ["Move Row Up" org-metaup (org-at-table-p)]
21638 ["Move Row Down" org-metadown (org-at-table-p)]
21639 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21640 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21641 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21642 "--"
21643 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21644 ("Rectangle"
21645 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21646 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21647 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21648 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21649 "--"
21650 ("Calculate"
21651 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21652 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21653 ["Edit Formulas" org-edit-special (org-at-table-p)]
21654 "--"
21655 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21656 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21657 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21658 "--"
21659 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21660 "--"
21661 ["Sum Column/Rectangle" org-table-sum
21662 (or (org-at-table-p) (org-region-active-p))]
21663 ["Which Column?" org-table-current-column (org-at-table-p)])
21664 ["Debug Formulas"
21665 org-table-toggle-formula-debugger
21666 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21667 ["Show Col/Row Numbers"
21668 org-table-toggle-coordinate-overlays
21669 :style toggle
21670 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21671 "--"
21672 ["Create" org-table-create (and (not (org-at-table-p))
21673 org-enable-table-editor)]
21674 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21675 ["Import from File" org-table-import (not (org-at-table-p))]
21676 ["Export to File" org-table-export (org-at-table-p)]
21677 "--"
21678 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21679 "--"
21680 ("Plot"
21681 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21682 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21684 (easy-menu-define org-org-menu org-mode-map "Org menu"
21685 '("Org"
21686 ("Show/Hide"
21687 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21688 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21689 ["Sparse Tree..." org-sparse-tree t]
21690 ["Reveal Context" org-reveal t]
21691 ["Show All" outline-show-all t]
21692 "--"
21693 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21694 "--"
21695 ["New Heading" org-insert-heading t]
21696 ("Navigate Headings"
21697 ["Up" outline-up-heading t]
21698 ["Next" outline-next-visible-heading t]
21699 ["Previous" outline-previous-visible-heading t]
21700 ["Next Same Level" outline-forward-same-level t]
21701 ["Previous Same Level" outline-backward-same-level t]
21702 "--"
21703 ["Jump" org-goto t])
21704 ("Edit Structure"
21705 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21706 "--"
21707 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21708 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21709 "--"
21710 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21711 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21712 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21713 "--"
21714 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21715 "--"
21716 ["Copy visible text" org-copy-visible t]
21717 "--"
21718 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21719 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21720 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21721 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21722 "--"
21723 ["Sort Region/Children" org-sort t]
21724 "--"
21725 ["Convert to odd levels" org-convert-to-odd-levels t]
21726 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21727 ("Editing"
21728 ["Emphasis..." org-emphasize t]
21729 ["Edit Source Example" org-edit-special t]
21730 "--"
21731 ["Footnote new/jump" org-footnote-action t]
21732 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21733 ("Archive"
21734 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21735 "--"
21736 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21737 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21738 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21740 "--"
21741 ("Hyperlinks"
21742 ["Store Link (Global)" org-store-link t]
21743 ["Find existing link to here" org-occur-link-in-agenda-files t]
21744 ["Insert Link" org-insert-link t]
21745 ["Follow Link" org-open-at-point t]
21746 "--"
21747 ["Next link" org-next-link t]
21748 ["Previous link" org-previous-link t]
21749 "--"
21750 ["Descriptive Links"
21751 org-toggle-link-display
21752 :style radio
21753 :selected org-descriptive-links
21755 ["Literal Links"
21756 org-toggle-link-display
21757 :style radio
21758 :selected (not org-descriptive-links)])
21759 "--"
21760 ("TODO Lists"
21761 ["TODO/DONE/-" org-todo t]
21762 ("Select keyword"
21763 ["Next keyword" org-shiftright (org-at-heading-p)]
21764 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21765 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21766 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21767 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21768 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21769 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21770 "--"
21771 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21772 :selected org-enforce-todo-dependencies :style toggle :active t]
21773 "Settings for tree at point"
21774 ["Do Children sequentially" org-toggle-ordered-property :style radio
21775 :selected (org-entry-get nil "ORDERED")
21776 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21777 ["Do Children parallel" org-toggle-ordered-property :style radio
21778 :selected (not (org-entry-get nil "ORDERED"))
21779 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21780 "--"
21781 ["Set Priority" org-priority t]
21782 ["Priority Up" org-shiftup t]
21783 ["Priority Down" org-shiftdown t]
21784 "--"
21785 ["Get news from all feeds" org-feed-update-all t]
21786 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21787 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21788 ("TAGS and Properties"
21789 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21790 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21791 "--"
21792 ["Set property" org-set-property (not (org-before-first-heading-p))]
21793 ["Column view of properties" org-columns t]
21794 ["Insert Column View DBlock" org-columns-insert-dblock t])
21795 ("Dates and Scheduling"
21796 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21797 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21798 ("Change Date"
21799 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21800 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21801 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21802 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21803 ["Compute Time Range" org-evaluate-time-range t]
21804 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21805 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21806 "--"
21807 ["Custom time format" org-toggle-time-stamp-overlays
21808 :style radio :selected org-display-custom-times]
21809 "--"
21810 ["Goto Calendar" org-goto-calendar t]
21811 ["Date from Calendar" org-date-from-calendar t]
21812 "--"
21813 ["Start/Restart Timer" org-timer-start t]
21814 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21815 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21816 ["Insert Timer String" org-timer t]
21817 ["Insert Timer Item" org-timer-item t])
21818 ("Logging work"
21819 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21820 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21821 ["Clock out" org-clock-out t]
21822 ["Clock cancel" org-clock-cancel t]
21823 "--"
21824 ["Mark as default task" org-clock-mark-default-task t]
21825 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21826 ["Goto running clock" org-clock-goto t]
21827 "--"
21828 ["Display times" org-clock-display t]
21829 ["Create clock table" org-clock-report t]
21830 "--"
21831 ["Record DONE time"
21832 (progn (setq org-log-done (not org-log-done))
21833 (message "Switching to %s will %s record a timestamp"
21834 (car org-done-keywords)
21835 (if org-log-done "automatically" "not")))
21836 :style toggle :selected org-log-done])
21837 "--"
21838 ["Agenda Command..." org-agenda t]
21839 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21840 ("File List for Agenda")
21841 ("Special views current file"
21842 ["TODO Tree" org-show-todo-tree t]
21843 ["Check Deadlines" org-check-deadlines t]
21844 ["Timeline" org-timeline t]
21845 ["Tags/Property tree" org-match-sparse-tree t])
21846 "--"
21847 ["Export/Publish..." org-export-dispatch t]
21848 ("LaTeX"
21849 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21850 :selected org-cdlatex-mode]
21851 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21852 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21853 ["Modify math symbol" org-cdlatex-math-modify
21854 (org-inside-LaTeX-fragment-p)]
21855 ["Insert citation" org-reftex-citation t]
21856 "--"
21857 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21858 "--"
21859 ("MobileOrg"
21860 ["Push Files and Views" org-mobile-push t]
21861 ["Get Captured and Flagged" org-mobile-pull t]
21862 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21863 "--"
21864 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21865 "--"
21866 ("Documentation"
21867 ["Show Version" org-version t]
21868 ["Info Documentation" org-info t])
21869 ("Customize"
21870 ["Browse Org Group" org-customize t]
21871 "--"
21872 ["Expand This Menu" org-create-customize-menu
21873 (fboundp 'customize-menu-create)])
21874 ["Send bug report" org-submit-bug-report t]
21875 "--"
21876 ("Refresh/Reload"
21877 ["Refresh setup current buffer" org-mode-restart t]
21878 ["Reload Org (after update)" org-reload t]
21879 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21882 (defun org-info (&optional node)
21883 "Read documentation for Org-mode in the info system.
21884 With optional NODE, go directly to that node."
21885 (interactive)
21886 (info (format "(org)%s" (or node ""))))
21888 ;;;###autoload
21889 (defun org-submit-bug-report ()
21890 "Submit a bug report on Org-mode via mail.
21892 Don't hesitate to report any problems or inaccurate documentation.
21894 If you don't have setup sending mail from (X)Emacs, please copy the
21895 output buffer into your mail program, as it gives us important
21896 information about your Org-mode version and configuration."
21897 (interactive)
21898 (require 'reporter)
21899 (defvar reporter-prompt-for-summary-p)
21900 (org-load-modules-maybe)
21901 (org-require-autoloaded-modules)
21902 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21903 (reporter-submit-bug-report
21904 "emacs-orgmode@gnu.org"
21905 (org-version nil 'full)
21906 (let (list)
21907 (save-window-excursion
21908 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21909 (delete-other-windows)
21910 (erase-buffer)
21911 (insert "You are about to submit a bug report to the Org-mode mailing list.
21913 We would like to add your full Org-mode and Outline configuration to the
21914 bug report. This greatly simplifies the work of the maintainer and
21915 other experts on the mailing list.
21917 HOWEVER, some variables you have customized may contain private
21918 information. The names of customers, colleagues, or friends, might
21919 appear in the form of file names, tags, todo states, or search strings.
21920 If you answer yes to the prompt, you might want to check and remove
21921 such private information before sending the email.")
21922 (add-text-properties (point-min) (point-max) '(face org-warning))
21923 (when (yes-or-no-p "Include your Org-mode configuration ")
21924 (mapatoms
21925 (lambda (v)
21926 (and (boundp v)
21927 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21928 (or (and (symbol-value v)
21929 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21930 (and
21931 (get v 'custom-type) (get v 'standard-value)
21932 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21933 (push v list)))))
21934 (kill-buffer (get-buffer "*Warn about privacy*"))
21935 list))
21936 nil nil
21937 "Remember to cover the basics, that is, what you expected to happen and
21938 what in fact did happen. You don't know how to make a good report? See
21940 http://orgmode.org/manual/Feedback.html#Feedback
21942 Your bug report will be posted to the Org-mode mailing list.
21943 ------------------------------------------------------------------------")
21944 (save-excursion
21945 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21946 (replace-match "\\1Bug: \\3 [\\2]")))))
21949 (defun org-install-agenda-files-menu ()
21950 (let ((bl (buffer-list)))
21951 (save-excursion
21952 (while bl
21953 (set-buffer (pop bl))
21954 (when (derived-mode-p 'org-mode) (setq bl nil)))
21955 (when (derived-mode-p 'org-mode)
21956 (easy-menu-change
21957 '("Org") "File List for Agenda"
21958 (append
21959 (list
21960 ["Edit File List" (org-edit-agenda-file-list) t]
21961 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
21962 ["Remove Current File from List" org-remove-file t]
21963 ["Cycle through agenda files" org-cycle-agenda-files t]
21964 ["Occur in all agenda files" org-occur-in-agenda-files t]
21965 "--")
21966 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
21968 ;;;; Documentation
21970 (defun org-require-autoloaded-modules ()
21971 (interactive)
21972 (mapc #'require
21973 '(org-agenda org-archive org-attach org-clock org-colview org-id
21974 org-table org-timer)))
21976 ;;;###autoload
21977 (defun org-reload (&optional uncompiled)
21978 "Reload all org lisp files.
21979 With prefix arg UNCOMPILED, load the uncompiled versions."
21980 (interactive "P")
21981 (require 'loadhist)
21982 (let* ((org-dir (org-find-library-dir "org"))
21983 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
21984 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
21985 (remove-re (mapconcat 'identity
21986 (mapcar (lambda (f) (concat "^" f "$"))
21987 (list (if (featurep 'xemacs)
21988 "org-colview"
21989 "org-colview-xemacs")
21990 "org" "org-loaddefs" "org-version"))
21991 "\\|"))
21992 (feats (delete-dups
21993 (mapcar 'file-name-sans-extension
21994 (mapcar 'file-name-nondirectory
21995 (delq nil
21996 (mapcar 'feature-file
21997 features))))))
21998 (lfeat (append
21999 (sort
22000 (setq feats
22001 (delq nil (mapcar
22002 (lambda (f)
22003 (if (and (string-match feature-re f)
22004 (not (string-match remove-re f)))
22005 f nil))
22006 feats)))
22007 'string-lessp)
22008 (list "org-version" "org")))
22009 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22010 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22011 load-uncore load-misses)
22012 (setq load-misses
22013 (delq 't
22014 (mapcar (lambda (f)
22015 (or (org-load-noerror-mustsuffix (concat org-dir f))
22016 (and (string= org-dir contrib-dir)
22017 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22018 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22019 (add-to-list 'load-uncore f 'append)
22022 lfeat)))
22023 (when load-uncore
22024 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22025 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22026 (if load-misses
22027 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22028 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22029 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22031 ;;;###autoload
22032 (defun org-customize ()
22033 "Call the customize function with org as argument."
22034 (interactive)
22035 (org-load-modules-maybe)
22036 (org-require-autoloaded-modules)
22037 (customize-browse 'org))
22039 (defun org-create-customize-menu ()
22040 "Create a full customization menu for Org-mode, insert it into the menu."
22041 (interactive)
22042 (org-load-modules-maybe)
22043 (org-require-autoloaded-modules)
22044 (if (fboundp 'customize-menu-create)
22045 (progn
22046 (easy-menu-change
22047 '("Org") "Customize"
22048 `(["Browse Org group" org-customize t]
22049 "--"
22050 ,(customize-menu-create 'org)
22051 ["Set" Custom-set t]
22052 ["Save" Custom-save t]
22053 ["Reset to Current" Custom-reset-current t]
22054 ["Reset to Saved" Custom-reset-saved t]
22055 ["Reset to Standard Settings" Custom-reset-standard t]))
22056 (message "\"Org\"-menu now contains full customization menu"))
22057 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22059 ;;;; Miscellaneous stuff
22061 ;;; Generally useful functions
22063 (defun org-get-at-eol (property n)
22064 "Get text property PROPERTY at the end of line less N characters."
22065 (get-text-property (- (point-at-eol) n) property))
22067 (defun org-find-text-property-in-string (prop s)
22068 "Return the first non-nil value of property PROP in string S."
22069 (or (get-text-property 0 prop s)
22070 (get-text-property (or (next-single-property-change 0 prop s) 0)
22071 prop s)))
22073 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22074 "Display the given MESSAGE as a warning."
22075 (if (fboundp 'display-warning)
22076 (display-warning 'org message
22077 (if (featurep 'xemacs) 'warning :warning))
22078 (let ((buf (get-buffer-create "*Org warnings*")))
22079 (with-current-buffer buf
22080 (goto-char (point-max))
22081 (insert "Warning (Org): " message)
22082 (unless (bolp)
22083 (newline)))
22084 (display-buffer buf)
22085 (sit-for 0))))
22087 (defun org-eval (form)
22088 "Eval FORM and return result."
22089 (condition-case error
22090 (eval form)
22091 (error (format "%%![Error: %s]" error))))
22093 (defun org-in-clocktable-p ()
22094 "Check if the cursor is in a clocktable."
22095 (let ((pos (point)) start)
22096 (save-excursion
22097 (end-of-line 1)
22098 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22099 (setq start (match-beginning 0))
22100 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22101 (>= (match-end 0) pos)
22102 start))))
22104 (defun org-in-verbatim-emphasis ()
22105 (save-match-data
22106 (and (org-in-regexp org-emph-re 2)
22107 (>= (point) (match-beginning 3))
22108 (<= (point) (match-end 4))
22109 (member (match-string 3) '("=" "~")))))
22111 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22112 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22113 (if (and marker (marker-buffer marker)
22114 (buffer-live-p (marker-buffer marker)))
22115 (progn
22116 (org-pop-to-buffer-same-window (marker-buffer marker))
22117 (when (or (> marker (point-max)) (< marker (point-min)))
22118 (widen))
22119 (goto-char marker)
22120 (org-show-context 'org-goto))
22121 (if bookmark
22122 (bookmark-jump bookmark)
22123 (error "Cannot find location"))))
22125 (defun org-quote-csv-field (s)
22126 "Quote field for inclusion in CSV material."
22127 (if (string-match "[\",]" s)
22128 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22131 (defun org-force-self-insert (N)
22132 "Needed to enforce self-insert under remapping."
22133 (interactive "p")
22134 (self-insert-command N))
22136 (defun org-string-width (s)
22137 "Compute width of string, ignoring invisible characters.
22138 This ignores character with invisibility property `org-link', and also
22139 characters with property `org-cwidth', because these will become invisible
22140 upon the next fontification round."
22141 (let (b l)
22142 (when (or (eq t buffer-invisibility-spec)
22143 (assq 'org-link buffer-invisibility-spec))
22144 (while (setq b (text-property-any 0 (length s)
22145 'invisible 'org-link s))
22146 (setq s (concat (substring s 0 b)
22147 (substring s (or (next-single-property-change
22148 b 'invisible s)
22149 (length s)))))))
22150 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22151 (setq s (concat (substring s 0 b)
22152 (substring s (or (next-single-property-change
22153 b 'org-cwidth s)
22154 (length s))))))
22155 (setq l (string-width s) b -1)
22156 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22157 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22160 (defun org-shorten-string (s maxlength)
22161 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22162 If the string is shorter or has length MAXLENGTH, just return the
22163 original string. If it is longer, the functions finds a space in the
22164 string, breaks this string off at that locations and adds three dots
22165 as ellipsis. Including the ellipsis, the string will not be longer
22166 than MAXLENGTH. If finding a good breaking point in the string does
22167 not work, the string is just chopped off in the middle of a word
22168 if necessary."
22169 (if (<= (length s) maxlength)
22171 (let* ((n (max (- maxlength 4) 1))
22172 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22173 (if (string-match re s)
22174 (concat (match-string 1 s) "...")
22175 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22177 (defun org-get-indentation (&optional line)
22178 "Get the indentation of the current line, interpreting tabs.
22179 When LINE is given, assume it represents a line and compute its indentation."
22180 (if line
22181 (when (string-match "^ *" (org-remove-tabs line))
22182 (match-end 0))
22183 (save-excursion
22184 (beginning-of-line 1)
22185 (skip-chars-forward " \t")
22186 (current-column))))
22188 (defun org-get-string-indentation (s)
22189 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22190 (let ((n -1) (i 0) (w tab-width) c)
22191 (catch 'exit
22192 (while (< (setq n (1+ n)) (length s))
22193 (setq c (aref s n))
22194 (cond ((= c ?\ ) (setq i (1+ i)))
22195 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22196 (t (throw 'exit t)))))
22199 (defun org-remove-tabs (s &optional width)
22200 "Replace tabulators in S with spaces.
22201 Assumes that s is a single line, starting in column 0."
22202 (setq width (or width tab-width))
22203 (while (string-match "\t" s)
22204 (setq s (replace-match
22205 (make-string
22206 (- (* width (/ (+ (match-beginning 0) width) width))
22207 (match-beginning 0)) ?\ )
22208 t t s)))
22211 (defun org-fix-indentation (line ind)
22212 "Fix indentation in LINE.
22213 IND is a cons cell with target and minimum indentation.
22214 If the current indentation in LINE is smaller than the minimum,
22215 leave it alone. If it is larger than ind, set it to the target."
22216 (let* ((l (org-remove-tabs line))
22217 (i (org-get-indentation l))
22218 (i1 (car ind)) (i2 (cdr ind)))
22219 (when (>= i i2) (setq l (substring line i2)))
22220 (if (> i1 0)
22221 (concat (make-string i1 ?\ ) l)
22222 l)))
22224 (defun org-remove-indentation (code &optional n)
22225 "Remove maximum common indentation in string CODE and return it.
22226 N may optionally be the number of columns to remove. Return CODE
22227 as-is if removal failed."
22228 (with-temp-buffer
22229 (insert code)
22230 (if (org-do-remove-indentation n) (buffer-string) code)))
22232 (defun org-do-remove-indentation (&optional n)
22233 "Remove the maximum common indentation from the buffer.
22234 When optional argument N is a positive integer, remove exactly
22235 that much characters from indentation, if possible. Return nil
22236 if it fails."
22237 (catch :exit
22238 (goto-char (point-min))
22239 ;; Find maximum common indentation, if not specified.
22240 (let ((n (or n
22241 (let ((min-ind (point-max)))
22242 (save-excursion
22243 (while (re-search-forward "^[ \t]*\\S-" nil t)
22244 (let ((ind (1- (current-column))))
22245 (if (zerop ind) (throw :exit nil)
22246 (setq min-ind (min min-ind ind))))))
22247 min-ind))))
22248 (if (zerop n) (throw :exit nil)
22249 ;; Remove exactly N indentation, but give up if not possible.
22250 (while (not (eobp))
22251 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22252 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22253 ((< ind n) (throw :exit nil))
22254 (t (org-indent-line-to (- ind n))))
22255 (forward-line)))
22256 ;; Signal success.
22257 t))))
22259 (defun org-fill-template (template alist)
22260 "Find each %key of ALIST in TEMPLATE and replace it."
22261 (let ((case-fold-search nil))
22262 (dolist (entry (sort (copy-sequence alist)
22263 (lambda (a b) (< (length (car a)) (length (car b))))))
22264 (setq template
22265 (replace-regexp-in-string
22266 (concat "%" (regexp-quote (car entry)))
22267 (or (cdr entry) "") template t t)))
22268 template))
22270 (defun org-base-buffer (buffer)
22271 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22272 (if (not buffer)
22273 buffer
22274 (or (buffer-base-buffer buffer)
22275 buffer)))
22277 (defun org-wrap (string &optional width lines)
22278 "Wrap string to either a number of lines, or a width in characters.
22279 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22280 that costs. If there is a word longer than WIDTH, the text is actually
22281 wrapped to the length of that word.
22282 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22283 many lines, whatever width that takes.
22284 The return value is a list of lines, without newlines at the end."
22285 (let* ((words (org-split-string string "[ \t\n]+"))
22286 (maxword (apply 'max (mapcar 'org-string-width words)))
22287 w ll)
22288 (cond (width
22289 (org-do-wrap words (max maxword width)))
22290 (lines
22291 (setq w maxword)
22292 (setq ll (org-do-wrap words maxword))
22293 (if (<= (length ll) lines)
22295 (setq ll words)
22296 (while (> (length ll) lines)
22297 (setq w (1+ w))
22298 (setq ll (org-do-wrap words w)))
22299 ll))
22300 (t (error "Cannot wrap this")))))
22302 (defun org-do-wrap (words width)
22303 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22304 (let (lines line)
22305 (while words
22306 (setq line (pop words))
22307 (while (and words (< (+ (length line) (length (car words))) width))
22308 (setq line (concat line " " (pop words))))
22309 (setq lines (push line lines)))
22310 (nreverse lines)))
22312 (defun org-split-string (string &optional separators)
22313 "Splits STRING into substrings at SEPARATORS.
22314 SEPARATORS is a regular expression.
22315 No empty strings are returned if there are matches at the beginning
22316 and end of string."
22317 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22318 (let ((start 0) notfirst list)
22319 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22320 (if (and notfirst
22321 (= start (match-beginning 0))
22322 (< start (length string)))
22323 (1+ start) start))
22324 (< (match-beginning 0) (length string)))
22325 (setq notfirst t)
22326 (or (eq (match-beginning 0) 0)
22327 (and (eq (match-beginning 0) (match-end 0))
22328 (eq (match-beginning 0) start))
22329 (push (substring string start (match-beginning 0)) list))
22330 (setq start (match-end 0)))
22331 (or (eq start (length string))
22332 (push (substring string start) list))
22333 (nreverse list)))
22335 (defun org-quote-vert (s)
22336 "Replace \"|\" with \"\\vert\"."
22337 (while (string-match "|" s)
22338 (setq s (replace-match "\\vert" t t s)))
22341 (defun org-uuidgen-p (s)
22342 "Is S an ID created by UUIDGEN?"
22343 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22345 (defun org-in-src-block-p (&optional inside)
22346 "Whether point is in a code source block.
22347 When INSIDE is non-nil, don't consider we are within a src block
22348 when point is at #+BEGIN_SRC or #+END_SRC."
22349 (let ((case-fold-search t))
22350 (or (and (eq (get-char-property (point) 'src-block) t))
22351 (and (not inside)
22352 (save-match-data
22353 (save-excursion
22354 (beginning-of-line)
22355 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22357 (defun org-context ()
22358 "Return a list of contexts of the current cursor position.
22359 If several contexts apply, all are returned.
22360 Each context entry is a list with a symbol naming the context, and
22361 two positions indicating start and end of the context. Possible
22362 contexts are:
22364 :headline anywhere in a headline
22365 :headline-stars on the leading stars in a headline
22366 :todo-keyword on a TODO keyword (including DONE) in a headline
22367 :tags on the TAGS in a headline
22368 :priority on the priority cookie in a headline
22369 :item on the first line of a plain list item
22370 :item-bullet on the bullet/number of a plain list item
22371 :checkbox on the checkbox in a plain list item
22372 :table in an org-mode table
22373 :table-special on a special filed in a table
22374 :table-table in a table.el table
22375 :clocktable in a clocktable
22376 :src-block in a source block
22377 :link on a hyperlink
22378 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22379 :target on a <<target>>
22380 :radio-target on a <<<radio-target>>>
22381 :latex-fragment on a LaTeX fragment
22382 :latex-preview on a LaTeX fragment with overlaid preview image
22384 This function expects the position to be visible because it uses font-lock
22385 faces as a help to recognize the following contexts: :table-special, :link,
22386 and :keyword."
22387 (let* ((f (get-text-property (point) 'face))
22388 (faces (if (listp f) f (list f)))
22389 (case-fold-search t)
22390 (p (point)) clist o)
22391 ;; First the large context
22392 (cond
22393 ((org-at-heading-p t)
22394 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22395 (when (progn
22396 (beginning-of-line 1)
22397 (looking-at org-todo-line-tags-regexp))
22398 (push (org-point-in-group p 1 :headline-stars) clist)
22399 (push (org-point-in-group p 2 :todo-keyword) clist)
22400 (push (org-point-in-group p 4 :tags) clist))
22401 (goto-char p)
22402 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22403 (when (looking-at "\\[#[A-Z0-9]\\]")
22404 (push (org-point-in-group p 0 :priority) clist)))
22406 ((org-at-item-p)
22407 (push (org-point-in-group p 2 :item-bullet) clist)
22408 (push (list :item (point-at-bol)
22409 (save-excursion (org-end-of-item) (point)))
22410 clist)
22411 (and (org-at-item-checkbox-p)
22412 (push (org-point-in-group p 0 :checkbox) clist)))
22414 ((org-at-table-p)
22415 (push (list :table (org-table-begin) (org-table-end)) clist)
22416 (when (memq 'org-formula faces)
22417 (push (list :table-special
22418 (previous-single-property-change p 'face)
22419 (next-single-property-change p 'face)) clist)))
22420 ((org-at-table-p 'any)
22421 (push (list :table-table) clist)))
22422 (goto-char p)
22424 (let ((case-fold-search t))
22425 ;; New the "medium" contexts: clocktables, source blocks
22426 (cond ((org-in-clocktable-p)
22427 (push (list :clocktable
22428 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22429 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22430 (match-beginning 1))
22431 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22432 (match-end 0))) clist))
22433 ((org-in-src-block-p)
22434 (push (list :src-block
22435 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22436 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22437 (match-beginning 1))
22438 (and (search-forward "#+END_SRC" nil t)
22439 (match-beginning 0))) clist))))
22440 (goto-char p)
22442 ;; Now the small context
22443 (cond
22444 ((org-at-timestamp-p)
22445 (push (org-point-in-group p 0 :timestamp) clist))
22446 ((memq 'org-link faces)
22447 (push (list :link
22448 (previous-single-property-change p 'face)
22449 (next-single-property-change p 'face)) clist))
22450 ((memq 'org-special-keyword faces)
22451 (push (list :keyword
22452 (previous-single-property-change p 'face)
22453 (next-single-property-change p 'face)) clist))
22454 ((org-at-target-p)
22455 (push (org-point-in-group p 0 :target) clist)
22456 (goto-char (1- (match-beginning 0)))
22457 (when (looking-at org-radio-target-regexp)
22458 (push (org-point-in-group p 0 :radio-target) clist))
22459 (goto-char p))
22460 ((setq o (cl-some
22461 (lambda (o)
22462 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22464 (overlays-at (point))))
22465 (push (list :latex-fragment
22466 (overlay-start o) (overlay-end o)) clist)
22467 (push (list :latex-preview
22468 (overlay-start o) (overlay-end o)) clist))
22469 ((org-inside-LaTeX-fragment-p)
22470 ;; FIXME: positions wrong.
22471 (push (list :latex-fragment (point) (point)) clist)))
22473 (setq clist (nreverse (delq nil clist)))
22474 clist))
22476 (defun org-in-regexp (regexp &optional nlines visually)
22477 "Check if point is inside a match of REGEXP.
22479 Normally only the current line is checked, but you can include
22480 NLINES extra lines around point into the search. If VISUALLY is
22481 set, require that the cursor is not after the match but really
22482 on, so that the block visually is on the match.
22484 Return nil or a cons cell (BEG . END) where BEG and END are,
22485 respectively, the positions at the beginning and the end of the
22486 match."
22487 (catch :exit
22488 (let ((pos (point))
22489 (eol (line-end-position (if nlines (1+ nlines) 1))))
22490 (save-excursion
22491 (beginning-of-line (- 1 (or nlines 0)))
22492 (while (and (re-search-forward regexp eol t)
22493 (<= (match-beginning 0) pos))
22494 (let ((end (match-end 0)))
22495 (when (or (> end pos) (and (= end pos) (not visually)))
22496 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22497 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22498 "Org mode 8.3")
22500 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22501 "Non-nil when point is between matches of START-RE and END-RE.
22503 Also return a non-nil value when point is on one of the matches.
22505 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22506 buffer positions. Default values are the positions of headlines
22507 surrounding the point.
22509 The functions returns a cons cell whose car (resp. cdr) is the
22510 position before START-RE (resp. after END-RE)."
22511 (save-match-data
22512 (let ((pos (point))
22513 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22514 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22515 beg end)
22516 (save-excursion
22517 ;; Point is on a block when on START-RE or if START-RE can be
22518 ;; found before it...
22519 (and (or (org-in-regexp start-re)
22520 (re-search-backward start-re limit-up t))
22521 (setq beg (match-beginning 0))
22522 ;; ... and END-RE after it...
22523 (goto-char (match-end 0))
22524 (re-search-forward end-re limit-down t)
22525 (> (setq end (match-end 0)) pos)
22526 ;; ... without another START-RE in-between.
22527 (goto-char (match-beginning 0))
22528 (not (re-search-backward start-re (1+ beg) t))
22529 ;; Return value.
22530 (cons beg end))))))
22532 (defun org-in-block-p (names)
22533 "Non-nil when point belongs to a block whose name belongs to NAMES.
22535 NAMES is a list of strings containing names of blocks.
22537 Return first block name matched, or nil. Beware that in case of
22538 nested blocks, the returned name may not belong to the closest
22539 block from point."
22540 (save-match-data
22541 (catch 'exit
22542 (let ((case-fold-search t)
22543 (lim-up (save-excursion (outline-previous-heading)))
22544 (lim-down (save-excursion (outline-next-heading))))
22545 (dolist (name names)
22546 (let ((n (regexp-quote name)))
22547 (when (org-between-regexps-p
22548 (concat "^[ \t]*#\\+begin_" n)
22549 (concat "^[ \t]*#\\+end_" n)
22550 lim-up lim-down)
22551 (throw 'exit n)))))
22552 nil)))
22554 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22555 "Call `multi-occur' with buffers for all agenda files."
22556 (interactive "sOrg-files matching: ")
22557 (let* ((files (org-agenda-files))
22558 (tnames (mapcar #'file-truename files))
22559 (extra org-agenda-text-search-extra-files))
22560 (when (eq (car extra) 'agenda-archives)
22561 (setq extra (cdr extra))
22562 (setq files (org-add-archive-files files)))
22563 (dolist (f extra)
22564 (unless (member (file-truename f) tnames)
22565 (unless (member f files) (setq files (append files (list f))))
22566 (setq tnames (append tnames (list (file-truename f))))))
22567 (multi-occur
22568 (mapcar (lambda (x)
22569 (with-current-buffer
22570 ;; FIXME: Why not just (find-file-noselect x)?
22571 ;; Is it to avoid the "revert buffer" prompt?
22572 (or (get-file-buffer x) (find-file-noselect x))
22573 (widen)
22574 (current-buffer)))
22575 files)
22576 regexp)))
22578 (if (boundp 'occur-mode-find-occurrence-hook)
22579 ;; Emacs 23
22580 (add-hook 'occur-mode-find-occurrence-hook
22581 (lambda ()
22582 (when (derived-mode-p 'org-mode)
22583 (org-reveal))))
22584 ;; Emacs 22
22585 (defadvice occur-mode-goto-occurrence
22586 (after org-occur-reveal activate)
22587 (and (derived-mode-p 'org-mode) (org-reveal)))
22588 (defadvice occur-mode-goto-occurrence-other-window
22589 (after org-occur-reveal activate)
22590 (and (derived-mode-p 'org-mode) (org-reveal)))
22591 (defadvice occur-mode-display-occurrence
22592 (after org-occur-reveal activate)
22593 (when (derived-mode-p 'org-mode)
22594 (let ((pos (occur-mode-find-occurrence)))
22595 (with-current-buffer (marker-buffer pos)
22596 (save-excursion
22597 (goto-char pos)
22598 (org-reveal)))))))
22600 (defun org-occur-link-in-agenda-files ()
22601 "Create a link and search for it in the agendas.
22602 The link is not stored in `org-stored-links', it is just created
22603 for the search purpose."
22604 (interactive)
22605 (let ((link (condition-case nil
22606 (org-store-link nil)
22607 (error "Unable to create a link to here"))))
22608 (org-occur-in-agenda-files (regexp-quote link))))
22610 (defun org-reverse-string (string)
22611 "Return the reverse of STRING."
22612 (apply 'string (reverse (string-to-list string))))
22614 ;; defsubst org-uniquify must be defined before first use
22616 (defun org-uniquify-alist (alist)
22617 "Merge elements of ALIST with the same key.
22619 For example, in this alist:
22621 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22622 => \\='((a 1 3) (b 2))
22624 merge (a 1) and (a 3) into (a 1 3).
22626 The function returns the new ALIST."
22627 (let (rtn)
22628 (dolist (e alist rtn)
22629 (let (n)
22630 (if (not (assoc (car e) rtn))
22631 (push e rtn)
22632 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22633 (setq rtn (assq-delete-all (car e) rtn))
22634 (push n rtn))))))
22636 (defun org-delete-all (elts list)
22637 "Remove all elements in ELTS from LIST."
22638 (while elts
22639 (setq list (delete (pop elts) list)))
22640 list)
22642 (defun org-back-over-empty-lines ()
22643 "Move backwards over whitespace, to the beginning of the first empty line.
22644 Returns the number of empty lines passed."
22645 (let ((pos (point)))
22646 (if (cdr (assoc 'heading org-blank-before-new-entry))
22647 (skip-chars-backward " \t\n\r")
22648 (unless (eobp)
22649 (forward-line -1)))
22650 (beginning-of-line 2)
22651 (goto-char (min (point) pos))
22652 (count-lines (point) pos)))
22654 (defun org-skip-whitespace ()
22655 (skip-chars-forward " \t\n\r"))
22657 (defun org-point-in-group (point group &optional context)
22658 "Check if POINT is in match-group GROUP.
22659 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22660 match. If the match group does not exist or point is not inside it,
22661 return nil."
22662 (and (match-beginning group)
22663 (>= point (match-beginning group))
22664 (<= point (match-end group))
22665 (if context
22666 (list context (match-beginning group) (match-end group))
22667 t)))
22669 (defun org-switch-to-buffer-other-window (&rest args)
22670 "Switch to buffer in a second window on the current frame.
22671 In particular, do not allow pop-up frames.
22672 Returns the newly created buffer."
22673 (org-no-popups
22674 (apply 'switch-to-buffer-other-window args)))
22676 (defun org-combine-plists (&rest plists)
22677 "Create a single property list from all plists in PLISTS.
22678 The process starts by copying the first list, and then setting properties
22679 from the other lists. Settings in the last list are the most significant
22680 ones and overrule settings in the other lists."
22681 (let ((rtn (copy-sequence (pop plists)))
22682 p v ls)
22683 (while plists
22684 (setq ls (pop plists))
22685 (while ls
22686 (setq p (pop ls) v (pop ls))
22687 (setq rtn (plist-put rtn p v))))
22688 rtn))
22690 (defun org-replace-escapes (string table)
22691 "Replace %-escapes in STRING with values in TABLE.
22692 TABLE is an association list with keys like \"%a\" and string values.
22693 The sequences in STRING may contain normal field width and padding information,
22694 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22695 so values can contain further %-escapes if they are define later in TABLE."
22696 (let ((tbl (copy-alist table))
22697 (case-fold-search nil)
22698 (pchg 0)
22699 re rpl)
22700 (dolist (e tbl)
22701 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22702 (when (and (cdr e) (string-match re (cdr e)))
22703 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22704 (safe "SREF"))
22705 (add-text-properties 0 3 (list 'sref sref) safe)
22706 (setcdr e (replace-match safe t t (cdr e)))))
22707 (while (string-match re string)
22708 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22709 (cdr e)))
22710 (setq string (replace-match rpl t t string))))
22711 (while (setq pchg (next-property-change pchg string))
22712 (let ((sref (get-text-property pchg 'sref string)))
22713 (when (and sref (string-match "SREF" string pchg))
22714 (setq string (replace-match sref t t string)))))
22715 string))
22717 (defun org-sublist (list start end)
22718 "Return a section of LIST, from START to END.
22720 Counting starts at 1."
22721 (cl-subseq list (1- start) end))
22722 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22724 (defun org-find-base-buffer-visiting (file)
22725 "Like `find-buffer-visiting' but always return the base buffer and
22726 not an indirect buffer."
22727 (let ((buf (or (get-file-buffer file)
22728 (find-buffer-visiting file))))
22729 (if buf
22730 (or (buffer-base-buffer buf) buf)
22731 nil)))
22733 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22734 "Org 9.0")
22736 ;;; TODO: Only called once, from ox-odt which should probably use
22737 ;;; org-export-inline-image-p or something.
22738 (defun org-file-image-p (file)
22739 "Return non-nil if FILE is an image."
22740 (save-match-data
22741 (string-match (image-file-name-regexp) file)))
22743 (defun org-get-cursor-date (&optional with-time)
22744 "Return the date at cursor in as a time.
22745 This works in the calendar and in the agenda, anywhere else it just
22746 returns the current time.
22747 If WITH-TIME is non-nil, returns the time of the event at point (in
22748 the agenda) or the current time of the day."
22749 (let (date day defd tp hod mod)
22750 (when with-time
22751 (setq tp (get-text-property (point) 'time))
22752 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22753 (setq hod (string-to-number (match-string 1 tp))
22754 mod (string-to-number (match-string 2 tp))))
22755 (or tp (let ((now (decode-time)))
22756 (setq hod (nth 2 now)
22757 mod (nth 1 now)))))
22758 (cond
22759 ((eq major-mode 'calendar-mode)
22760 (setq date (calendar-cursor-to-date)
22761 defd (encode-time 0 (or mod 0) (or hod 0)
22762 (nth 1 date) (nth 0 date) (nth 2 date))))
22763 ((eq major-mode 'org-agenda-mode)
22764 (setq day (get-text-property (point) 'day))
22765 (when day
22766 (setq date (calendar-gregorian-from-absolute day)
22767 defd (encode-time 0 (or mod 0) (or hod 0)
22768 (nth 1 date) (nth 0 date) (nth 2 date))))))
22769 (or defd (current-time))))
22771 (defun org-mark-subtree (&optional up)
22772 "Mark the current subtree.
22773 This puts point at the start of the current subtree, and mark at
22774 the end. If a numeric prefix UP is given, move up into the
22775 hierarchy of headlines by UP levels before marking the subtree."
22776 (interactive "P")
22777 (org-with-limited-levels
22778 (cond ((org-at-heading-p) (beginning-of-line))
22779 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22780 (t (outline-previous-visible-heading 1))))
22781 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22782 (if (org-called-interactively-p 'any)
22783 (call-interactively 'org-mark-element)
22784 (org-mark-element)))
22787 ;;; Indentation
22789 (defun org--get-expected-indentation (element contentsp)
22790 "Expected indentation column for current line, according to ELEMENT.
22791 ELEMENT is an element containing point. CONTENTSP is non-nil
22792 when indentation is to be computed according to contents of
22793 ELEMENT."
22794 (let ((type (org-element-type element))
22795 (start (org-element-property :begin element))
22796 (post-affiliated (org-element-property :post-affiliated element)))
22797 (org-with-wide-buffer
22798 (cond
22799 (contentsp
22800 (cl-case type
22801 ((diary-sexp footnote-definition) 0)
22802 ((headline inlinetask nil)
22803 (if (not org-adapt-indentation) 0
22804 (let ((level (org-current-level)))
22805 (if level (1+ level) 0))))
22806 ((item plain-list) (org-list-item-body-column post-affiliated))
22808 (goto-char start)
22809 (org-get-indentation))))
22810 ((memq type '(headline inlinetask nil))
22811 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22812 (org--get-expected-indentation element t)
22814 ((memq type '(diary-sexp footnote-definition)) 0)
22815 ;; First paragraph of a footnote definition or an item.
22816 ;; Indent like parent.
22817 ((< (line-beginning-position) start)
22818 (org--get-expected-indentation
22819 (org-element-property :parent element) t))
22820 ;; At first line: indent according to previous sibling, if any,
22821 ;; ignoring footnote definitions and inline tasks, or parent's
22822 ;; contents.
22823 ((= (line-beginning-position) start)
22824 (catch 'exit
22825 (while t
22826 (if (= (point-min) start) (throw 'exit 0)
22827 (goto-char (1- start))
22828 (let* ((previous (org-element-at-point))
22829 (parent previous))
22830 (while (and parent (<= (org-element-property :end parent) start))
22831 (setq previous parent
22832 parent (org-element-property :parent parent)))
22833 (cond
22834 ((not previous) (throw 'exit 0))
22835 ((> (org-element-property :end previous) start)
22836 (throw 'exit (org--get-expected-indentation previous t)))
22837 ((memq (org-element-type previous)
22838 '(footnote-definition inlinetask))
22839 (setq start (org-element-property :begin previous)))
22840 (t (goto-char (org-element-property :begin previous))
22841 (throw 'exit
22842 (if (bolp) (org-get-indentation)
22843 ;; At first paragraph in an item or
22844 ;; a footnote definition.
22845 (org--get-expected-indentation
22846 (org-element-property :parent previous) t))))))))))
22847 ;; Otherwise, move to the first non-blank line above.
22849 (beginning-of-line)
22850 (let ((pos (point)))
22851 (skip-chars-backward " \r\t\n")
22852 (cond
22853 ;; Two blank lines end a footnote definition or a plain
22854 ;; list. When we indent an empty line after them, the
22855 ;; containing list or footnote definition is over, so it
22856 ;; qualifies as a previous sibling. Therefore, we indent
22857 ;; like its first line.
22858 ((and (memq type '(footnote-definition plain-list))
22859 (> (count-lines (point) pos) 2))
22860 (goto-char start)
22861 (org-get-indentation))
22862 ;; Line above is the first one of a paragraph at the
22863 ;; beginning of an item or a footnote definition. Indent
22864 ;; like parent.
22865 ((< (line-beginning-position) start)
22866 (org--get-expected-indentation
22867 (org-element-property :parent element) t))
22868 ;; Line above is the beginning of an element, i.e., point
22869 ;; was originally on the blank lines between element's start
22870 ;; and contents.
22871 ((= (line-beginning-position) post-affiliated)
22872 (org--get-expected-indentation element t))
22873 ;; POS is after contents in a greater element. Indent like
22874 ;; the beginning of the element.
22876 ;; As a special case, if point is at the end of a footnote
22877 ;; definition or an item, indent like the very last element
22878 ;; within.
22879 ((and (not (eq type 'paragraph))
22880 (let ((cend (org-element-property :contents-end element)))
22881 (and cend (<= cend pos))))
22882 (if (memq type '(footnote-definition item plain-list))
22883 (org--get-expected-indentation (org-element-at-point) t)
22884 (goto-char start)
22885 (org-get-indentation)))
22886 ;; In any other case, indent like the current line.
22887 (t (org-get-indentation)))))))))
22889 (defun org--align-node-property ()
22890 "Align node property at point.
22891 Alignment is done according to `org-property-format', which see."
22892 (when (save-excursion
22893 (beginning-of-line)
22894 (looking-at org-property-re))
22895 (replace-match
22896 (concat (match-string 4)
22897 (org-trim
22898 (format org-property-format (match-string 1) (match-string 3))))
22899 t t)))
22901 (defun org-indent-line ()
22902 "Indent line depending on context.
22904 Indentation is done according to the following rules:
22906 - Footnote definitions, diary sexps, headlines and inline tasks
22907 have to start at column 0.
22909 - On the very first line of an element, consider, in order, the
22910 next rules until one matches:
22912 1. If there's a sibling element before, ignoring footnote
22913 definitions and inline tasks, indent like its first line.
22915 2. If element has a parent, indent like its contents. More
22916 precisely, if parent is an item, indent after the
22917 description part, if any, or the bullet (see
22918 `org-list-description-max-indent'). Else, indent like
22919 parent's first line.
22921 3. Otherwise, indent relatively to current level, if
22922 `org-adapt-indentation' is non-nil, or to left margin.
22924 - On a blank line at the end of an element, indent according to
22925 the type of the element. More precisely
22927 1. If element is a plain list, an item, or a footnote
22928 definition, indent like the very last element within.
22930 2. If element is a paragraph, indent like its last non blank
22931 line.
22933 3. Otherwise, indent like its very first line.
22935 - In the code part of a source block, use language major mode
22936 to indent current line if `org-src-tab-acts-natively' is
22937 non-nil. If it is nil, do nothing.
22939 - Otherwise, indent like the first non-blank line above.
22941 The function doesn't indent an item as it could break the whole
22942 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22943 \\[org-shiftmetaright].
22945 Also align node properties according to `org-property-format'."
22946 (interactive)
22947 (cond
22948 (orgstruct-is-++
22949 (let ((indent-line-function
22950 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22951 (indent-according-to-mode)))
22952 ((org-at-heading-p) 'noindent)
22954 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22955 (type (org-element-type element)))
22956 (cond ((and (memq type '(plain-list item))
22957 (= (line-beginning-position)
22958 (org-element-property :post-affiliated element)))
22959 'noindent)
22960 ((and (eq type 'src-block)
22961 org-src-tab-acts-natively
22962 (> (line-beginning-position)
22963 (org-element-property :post-affiliated element))
22964 (< (line-beginning-position)
22965 (org-with-wide-buffer
22966 (goto-char (org-element-property :end element))
22967 (skip-chars-backward " \r\t\n")
22968 (line-beginning-position))))
22969 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
22971 (let ((column (org--get-expected-indentation element nil)))
22972 ;; Preserve current column.
22973 (if (<= (current-column) (current-indentation))
22974 (org-indent-line-to column)
22975 (save-excursion (org-indent-line-to column))))
22976 ;; Align node property. Also preserve current column.
22977 (when (eq type 'node-property)
22978 (let ((column (current-column)))
22979 (org--align-node-property)
22980 (org-move-to-column column)))))))))
22982 (defun org-indent-region (start end)
22983 "Indent each non-blank line in the region.
22984 Called from a program, START and END specify the region to
22985 indent. The function will not indent contents of example blocks,
22986 verse blocks and export blocks as leading white spaces are
22987 assumed to be significant there."
22988 (interactive "r")
22989 (save-excursion
22990 (goto-char start)
22991 (skip-chars-forward " \r\t\n")
22992 (unless (eobp) (beginning-of-line))
22993 (let ((indent-to
22994 (lambda (ind pos)
22995 ;; Set IND as indentation for all lines between point and
22996 ;; POS. Blank lines are ignored. Leave point after POS
22997 ;; once done.
22998 (let ((limit (copy-marker pos)))
22999 (while (< (point) limit)
23000 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23001 (forward-line))
23002 (set-marker limit nil))))
23003 (end (copy-marker end)))
23004 (while (< (point) end)
23005 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23006 (let* ((element (org-element-at-point))
23007 (type (org-element-type element))
23008 (element-end (copy-marker (org-element-property :end element)))
23009 (ind (org--get-expected-indentation element nil)))
23010 (cond
23011 ((or (memq type '(paragraph table table-row))
23012 (not (or (org-element-property :contents-begin element)
23013 (memq type
23014 '(example-block export-block src-block)))))
23015 ;; Elements here are indented as a single block. Also
23016 ;; align node properties.
23017 (when (eq type 'node-property)
23018 (org--align-node-property)
23019 (beginning-of-line))
23020 (funcall indent-to ind (min element-end end)))
23022 ;; Elements in this category consist of three parts:
23023 ;; before the contents, the contents, and after the
23024 ;; contents. The contents are treated specially,
23025 ;; according to the element type, or not indented at
23026 ;; all. Other parts are indented as a single block.
23027 (let* ((post (copy-marker
23028 (org-element-property :post-affiliated element)))
23029 (cbeg
23030 (copy-marker
23031 (cond
23032 ((not (org-element-property :contents-begin element))
23033 ;; Fake contents for source blocks.
23034 (org-with-wide-buffer
23035 (goto-char post)
23036 (forward-line)
23037 (point)))
23038 ((memq type '(footnote-definition item plain-list))
23039 ;; Contents in these elements could start on
23040 ;; the same line as the beginning of the
23041 ;; element. Make sure we start indenting
23042 ;; from the second line.
23043 (org-with-wide-buffer
23044 (goto-char post)
23045 (end-of-line)
23046 (skip-chars-forward " \r\t\n")
23047 (if (eobp) (point) (line-beginning-position))))
23048 (t (org-element-property :contents-begin element)))))
23049 (cend (copy-marker
23050 (or (org-element-property :contents-end element)
23051 ;; Fake contents for source blocks.
23052 (org-with-wide-buffer
23053 (goto-char element-end)
23054 (skip-chars-backward " \r\t\n")
23055 (line-beginning-position)))
23056 t)))
23057 ;; Do not change items indentation individually as it
23058 ;; might break the list as a whole. On the other
23059 ;; hand, when at a plain list, indent it as a whole.
23060 (cond ((eq type 'plain-list)
23061 (let ((offset (- ind (org-get-indentation))))
23062 (unless (zerop offset)
23063 (indent-rigidly (org-element-property :begin element)
23064 (org-element-property :end element)
23065 offset))
23066 (goto-char cbeg)))
23067 ((eq type 'item) (goto-char cbeg))
23068 (t (funcall indent-to ind (min cbeg end))))
23069 (when (< (point) end)
23070 (cl-case type
23071 ((example-block export-block verse-block))
23072 (src-block
23073 ;; In a source block, indent source code
23074 ;; according to language major mode, but only if
23075 ;; `org-src-tab-acts-natively' is non-nil.
23076 (when (and (< (point) end) org-src-tab-acts-natively)
23077 (ignore-errors
23078 (org-babel-do-in-edit-buffer
23079 (indent-region (point-min) (point-max))))))
23080 (t (org-indent-region (point) (min cend end))))
23081 (goto-char (min cend end))
23082 (when (< (point) end)
23083 (funcall indent-to ind (min element-end end))))
23084 (set-marker post nil)
23085 (set-marker cbeg nil)
23086 (set-marker cend nil))))
23087 (set-marker element-end nil))))
23088 (set-marker end nil))))
23090 (defun org-indent-drawer ()
23091 "Indent the drawer at point."
23092 (interactive)
23093 (unless (save-excursion
23094 (beginning-of-line)
23095 (org-looking-at-p org-drawer-regexp))
23096 (user-error "Not at a drawer"))
23097 (let ((element (org-element-at-point)))
23098 (unless (memq (org-element-type element) '(drawer property-drawer))
23099 (user-error "Not at a drawer"))
23100 (org-with-wide-buffer
23101 (org-indent-region (org-element-property :begin element)
23102 (org-element-property :end element))))
23103 (message "Drawer at point indented"))
23105 (defun org-indent-block ()
23106 "Indent the block at point."
23107 (interactive)
23108 (unless (save-excursion
23109 (beginning-of-line)
23110 (let ((case-fold-search t))
23111 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23112 (user-error "Not at a block"))
23113 (let ((element (org-element-at-point)))
23114 (unless (memq (org-element-type element)
23115 '(comment-block center-block dynamic-block example-block
23116 export-block quote-block special-block
23117 src-block verse-block))
23118 (user-error "Not at a block"))
23119 (org-with-wide-buffer
23120 (org-indent-region (org-element-property :begin element)
23121 (org-element-property :end element))))
23122 (message "Block at point indented"))
23125 ;;; Filling
23127 ;; We use our own fill-paragraph and auto-fill functions.
23129 ;; `org-fill-paragraph' relies on adaptive filling and context
23130 ;; checking. Appropriate `fill-prefix' is computed with
23131 ;; `org-adaptive-fill-function'.
23133 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23134 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23135 ;; `org-adaptive-fill-function' value. Internally,
23136 ;; `org-comment-line-break-function' breaks the line.
23138 ;; `org-setup-filling' installs filling and auto-filling related
23139 ;; variables during `org-mode' initialization.
23141 (defvar org-element-paragraph-separate) ; org-element.el
23142 (defun org-setup-filling ()
23143 (require 'org-element)
23144 ;; Prevent auto-fill from inserting unwanted new items.
23145 (when (boundp 'fill-nobreak-predicate)
23146 (setq-local
23147 fill-nobreak-predicate
23148 (org-uniquify
23149 (append fill-nobreak-predicate
23150 '(org-fill-line-break-nobreak-p
23151 org-fill-paragraph-with-timestamp-nobreak-p)))))
23152 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23153 (setq-local paragraph-start paragraph-ending)
23154 (setq-local paragraph-separate paragraph-ending))
23155 (setq-local fill-paragraph-function 'org-fill-paragraph)
23156 (setq-local auto-fill-inhibit-regexp nil)
23157 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23158 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23159 (setq-local comment-line-break-function 'org-comment-line-break-function))
23161 (defun org-fill-line-break-nobreak-p ()
23162 "Non-nil when a new line at point would create an Org line break."
23163 (save-excursion
23164 (skip-chars-backward "[ \t]")
23165 (skip-chars-backward "\\\\")
23166 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23168 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23169 "Non-nil when a new line at point would split a timestamp."
23170 (and (org-at-timestamp-p t)
23171 (not (looking-at org-ts-regexp-both))))
23173 (declare-function message-in-body-p "message" ())
23174 (defvar orgtbl-line-start-regexp) ; From org-table.el
23175 (defun org-adaptive-fill-function ()
23176 "Compute a fill prefix for the current line.
23177 Return fill prefix, as a string, or nil if current line isn't
23178 meant to be filled. For convenience, if `adaptive-fill-regexp'
23179 matches in paragraphs or comments, use it."
23180 (catch 'exit
23181 (when (derived-mode-p 'message-mode)
23182 (save-excursion
23183 (beginning-of-line)
23184 (cond ((not (message-in-body-p)) (throw 'exit nil))
23185 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23186 ((looking-at message-cite-prefix-regexp)
23187 (throw 'exit (match-string-no-properties 0)))
23188 ((looking-at org-outline-regexp)
23189 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23190 (org-with-wide-buffer
23191 (unless (org-at-heading-p)
23192 (let* ((p (line-beginning-position))
23193 (element (save-excursion
23194 (beginning-of-line)
23195 (org-element-at-point)))
23196 (type (org-element-type element))
23197 (post-affiliated (org-element-property :post-affiliated element)))
23198 (unless (< p post-affiliated)
23199 (cl-case type
23200 (comment
23201 (save-excursion
23202 (beginning-of-line)
23203 (looking-at "[ \t]*")
23204 (concat (match-string 0) "# ")))
23205 (footnote-definition "")
23206 ((item plain-list)
23207 (make-string (org-list-item-body-column post-affiliated) ?\s))
23208 (paragraph
23209 ;; Fill prefix is usually the same as the current line,
23210 ;; unless the paragraph is at the beginning of an item.
23211 (let ((parent (org-element-property :parent element)))
23212 (save-excursion
23213 (beginning-of-line)
23214 (cond ((eq (org-element-type parent) 'item)
23215 (make-string (org-list-item-body-column
23216 (org-element-property :begin parent))
23217 ?\s))
23218 ((and adaptive-fill-regexp
23219 ;; Locally disable
23220 ;; `adaptive-fill-function' to let
23221 ;; `fill-context-prefix' handle
23222 ;; `adaptive-fill-regexp' variable.
23223 (let (adaptive-fill-function)
23224 (fill-context-prefix
23225 post-affiliated
23226 (org-element-property :end element)))))
23227 ((looking-at "[ \t]+") (match-string 0))
23228 (t "")))))
23229 (comment-block
23230 ;; Only fill contents if P is within block boundaries.
23231 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23232 (forward-line)
23233 (point)))
23234 (cend (save-excursion
23235 (goto-char (org-element-property :end element))
23236 (skip-chars-backward " \r\t\n")
23237 (line-beginning-position))))
23238 (when (and (>= p cbeg) (< p cend))
23239 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23240 (match-string 0)
23241 "")))))))))))
23243 (declare-function message-goto-body "message" ())
23244 (defvar message-cite-prefix-regexp) ; From message.el
23245 (defun org-fill-paragraph (&optional justify)
23246 "Fill element at point, when applicable.
23248 This function only applies to comment blocks, comments, example
23249 blocks and paragraphs. Also, as a special case, re-align table
23250 when point is at one.
23252 If JUSTIFY is non-nil (interactively, with prefix argument),
23253 justify as well. If `sentence-end-double-space' is non-nil, then
23254 period followed by one space does not end a sentence, so don't
23255 break a line there. The variable `fill-column' controls the
23256 width for filling.
23258 For convenience, when point is at a plain list, an item or
23259 a footnote definition, try to fill the first paragraph within."
23260 (interactive)
23261 (if (and (derived-mode-p 'message-mode)
23262 (or (not (message-in-body-p))
23263 (save-excursion (move-beginning-of-line 1)
23264 (looking-at message-cite-prefix-regexp))))
23265 ;; First ensure filling is correct in message-mode.
23266 (let ((fill-paragraph-function
23267 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23268 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23269 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23270 (paragraph-separate
23271 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23272 (fill-paragraph nil))
23273 (with-syntax-table org-mode-transpose-word-syntax-table
23274 ;; Move to end of line in order to get the first paragraph
23275 ;; within a plain list or a footnote definition.
23276 (let ((element (save-excursion
23277 (end-of-line)
23278 (or (ignore-errors (org-element-at-point))
23279 (user-error "An element cannot be parsed line %d"
23280 (line-number-at-pos (point)))))))
23281 ;; First check if point is in a blank line at the beginning of
23282 ;; the buffer. In that case, ignore filling.
23283 (cl-case (org-element-type element)
23284 ;; Use major mode filling function is src blocks.
23285 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23286 ;; Align Org tables, leave table.el tables as-is.
23287 (table-row (org-table-align) t)
23288 (table
23289 (when (eq (org-element-property :type element) 'org)
23290 (save-excursion
23291 (goto-char (org-element-property :post-affiliated element))
23292 (org-table-align)))
23294 (paragraph
23295 ;; Paragraphs may contain `line-break' type objects.
23296 (let ((beg (max (point-min)
23297 (org-element-property :contents-begin element)))
23298 (end (min (point-max)
23299 (org-element-property :contents-end element))))
23300 ;; Do nothing if point is at an affiliated keyword.
23301 (if (< (line-end-position) beg) t
23302 (when (derived-mode-p 'message-mode)
23303 ;; In `message-mode', do not fill following citation
23304 ;; in current paragraph nor text before message body.
23305 (let ((body-start (save-excursion (message-goto-body))))
23306 (when body-start (setq beg (max body-start beg))))
23307 (when (save-excursion
23308 (re-search-forward
23309 (concat "^" message-cite-prefix-regexp) end t))
23310 (setq end (match-beginning 0))))
23311 ;; Fill paragraph, taking line breaks into account.
23312 (save-excursion
23313 (goto-char beg)
23314 (let ((cuts (list beg)))
23315 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23316 (when (eq 'line-break
23317 (org-element-type
23318 (save-excursion (backward-char)
23319 (org-element-context))))
23320 (push (point) cuts)))
23321 (dolist (c (delq end cuts))
23322 (fill-region-as-paragraph c end justify)
23323 (setq end c))))
23324 t)))
23325 ;; Contents of `comment-block' type elements should be
23326 ;; filled as plain text, but only if point is within block
23327 ;; markers.
23328 (comment-block
23329 (let* ((case-fold-search t)
23330 (beg (save-excursion
23331 (goto-char (org-element-property :begin element))
23332 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23333 (forward-line)
23334 (point)))
23335 (end (save-excursion
23336 (goto-char (org-element-property :end element))
23337 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23338 (line-beginning-position))))
23339 (if (or (< (point) beg) (> (point) end)) t
23340 (fill-region-as-paragraph
23341 (save-excursion (end-of-line)
23342 (re-search-backward "^[ \t]*$" beg 'move)
23343 (line-beginning-position))
23344 (save-excursion (beginning-of-line)
23345 (re-search-forward "^[ \t]*$" end 'move)
23346 (line-beginning-position))
23347 justify))))
23348 ;; Fill comments.
23349 (comment
23350 (let ((begin (org-element-property :post-affiliated element))
23351 (end (org-element-property :end element)))
23352 (when (and (>= (point) begin) (<= (point) end))
23353 (let ((begin (save-excursion
23354 (end-of-line)
23355 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23356 (progn (forward-line) (point))
23357 begin)))
23358 (end (save-excursion
23359 (end-of-line)
23360 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23361 (1- (line-beginning-position))
23362 (skip-chars-backward " \r\t\n")
23363 (line-end-position)))))
23364 ;; Do not fill comments when at a blank line.
23365 (when (> end begin)
23366 (let ((fill-prefix
23367 (save-excursion
23368 (beginning-of-line)
23369 (looking-at "[ \t]*#")
23370 (let ((comment-prefix (match-string 0)))
23371 (goto-char (match-end 0))
23372 (if (looking-at adaptive-fill-regexp)
23373 (concat comment-prefix (match-string 0))
23374 (concat comment-prefix " "))))))
23375 (save-excursion
23376 (fill-region-as-paragraph begin end justify))))))
23378 ;; Ignore every other element.
23379 (otherwise t))))))
23381 (defun org-auto-fill-function ()
23382 "Auto-fill function."
23383 ;; Check if auto-filling is meaningful.
23384 (let ((fc (current-fill-column)))
23385 (when (and fc (> (current-column) fc))
23386 (let* ((fill-prefix (org-adaptive-fill-function))
23387 ;; Enforce empty fill prefix, if required. Otherwise, it
23388 ;; will be computed again.
23389 (adaptive-fill-mode (not (equal fill-prefix ""))))
23390 (when fill-prefix (do-auto-fill))))))
23392 (defun org-comment-line-break-function (&optional soft)
23393 "Break line at point and indent, continuing comment if within one.
23394 The inserted newline is marked hard if variable
23395 `use-hard-newlines' is true, unless optional argument SOFT is
23396 non-nil."
23397 (if soft (insert-and-inherit ?\n) (newline 1))
23398 (save-excursion (forward-char -1) (delete-horizontal-space))
23399 (delete-horizontal-space)
23400 (indent-to-left-margin)
23401 (insert-before-markers-and-inherit fill-prefix))
23404 ;;; Fixed Width Areas
23406 (defun org-toggle-fixed-width ()
23407 "Toggle fixed-width markup.
23409 Add or remove fixed-width markup on current line, whenever it
23410 makes sense. Return an error otherwise.
23412 If a region is active and if it contains only fixed-width areas
23413 or blank lines, remove all fixed-width markup in it. If the
23414 region contains anything else, convert all non-fixed-width lines
23415 to fixed-width ones.
23417 Blank lines at the end of the region are ignored unless the
23418 region only contains such lines."
23419 (interactive)
23420 (if (not (org-region-active-p))
23421 ;; No region:
23423 ;; Remove fixed width marker only in a fixed-with element.
23425 ;; Add fixed width maker in paragraphs, in blank lines after
23426 ;; elements or at the beginning of a headline or an inlinetask,
23427 ;; and before any one-line elements (e.g., a clock).
23428 (progn
23429 (beginning-of-line)
23430 (let* ((element (org-element-at-point))
23431 (type (org-element-type element)))
23432 (cond
23433 ((and (eq type 'fixed-width)
23434 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23435 (replace-match
23436 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23437 ((and (memq type '(babel-call clock comment diary-sexp headline
23438 horizontal-rule keyword paragraph
23439 planning))
23440 (<= (org-element-property :post-affiliated element) (point)))
23441 (skip-chars-forward " \t")
23442 (insert ": "))
23443 ((and (org-looking-at-p "[ \t]*$")
23444 (or (eq type 'inlinetask)
23445 (save-excursion
23446 (skip-chars-forward " \r\t\n")
23447 (<= (org-element-property :end element) (point)))))
23448 (delete-region (point) (line-end-position))
23449 (org-indent-line)
23450 (insert ": "))
23451 (t (user-error "Cannot insert a fixed-width line here")))))
23452 ;; Region active.
23453 (let* ((begin (save-excursion
23454 (goto-char (region-beginning))
23455 (line-beginning-position)))
23456 (end (copy-marker
23457 (save-excursion
23458 (goto-char (region-end))
23459 (unless (eolp) (beginning-of-line))
23460 (if (save-excursion (re-search-backward "\\S-" begin t))
23461 (progn (skip-chars-backward " \r\t\n") (point))
23462 (point)))))
23463 (all-fixed-width-p
23464 (catch 'not-all-p
23465 (save-excursion
23466 (goto-char begin)
23467 (skip-chars-forward " \r\t\n")
23468 (when (eobp) (throw 'not-all-p nil))
23469 (while (< (point) end)
23470 (let ((element (org-element-at-point)))
23471 (if (eq (org-element-type element) 'fixed-width)
23472 (goto-char (org-element-property :end element))
23473 (throw 'not-all-p nil))))
23474 t))))
23475 (if all-fixed-width-p
23476 (save-excursion
23477 (goto-char begin)
23478 (while (< (point) end)
23479 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23480 (replace-match
23481 "" nil nil nil
23482 (if (= (line-end-position) (match-end 0)) 0 1)))
23483 (forward-line)))
23484 (let ((min-ind (point-max)))
23485 ;; Find minimum indentation across all lines.
23486 (save-excursion
23487 (goto-char begin)
23488 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23489 (setq min-ind 0)
23490 (catch 'zerop
23491 (while (< (point) end)
23492 (unless (org-looking-at-p "[ \t]*$")
23493 (let ((ind (org-get-indentation)))
23494 (setq min-ind (min min-ind ind))
23495 (when (zerop ind) (throw 'zerop t))))
23496 (forward-line)))))
23497 ;; Loop over all lines and add fixed-width markup everywhere
23498 ;; but in fixed-width lines.
23499 (save-excursion
23500 (goto-char begin)
23501 (while (< (point) end)
23502 (cond
23503 ((org-at-heading-p)
23504 (insert ": ")
23505 (forward-line)
23506 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23507 (insert ":")
23508 (forward-line)))
23509 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23510 (let* ((element (org-element-at-point))
23511 (element-end (org-element-property :end element)))
23512 (if (eq (org-element-type element) 'fixed-width)
23513 (progn (goto-char element-end)
23514 (skip-chars-backward " \r\t\n")
23515 (forward-line))
23516 (let ((limit (min end element-end)))
23517 (while (< (point) limit)
23518 (org-move-to-column min-ind t)
23519 (insert ": ")
23520 (forward-line))))))
23522 (org-move-to-column min-ind t)
23523 (insert ": ")
23524 (forward-line)))))))
23525 (set-marker end nil))))
23528 ;;; Comments
23530 ;; Org comments syntax is quite complex. It requires the entire line
23531 ;; to be just a comment. Also, even with the right syntax at the
23532 ;; beginning of line, some some elements (i.e. verse-block or
23533 ;; example-block) don't accept comments. Usual Emacs comment commands
23534 ;; cannot cope with those requirements. Therefore, Org replaces them.
23536 ;; Org still relies on `comment-dwim', but cannot trust
23537 ;; `comment-only-p'. So, `comment-region-function' and
23538 ;; `uncomment-region-function' both point
23539 ;; to`org-comment-or-uncomment-region'. Eventually,
23540 ;; `org-insert-comment' takes care of insertion of comments at the
23541 ;; beginning of line.
23543 ;; `org-setup-comments-handling' install comments related variables
23544 ;; during `org-mode' initialization.
23546 (defun org-setup-comments-handling ()
23547 (interactive)
23548 (setq-local comment-use-syntax nil)
23549 (setq-local comment-start "# ")
23550 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23551 (setq-local comment-insert-comment-function 'org-insert-comment)
23552 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23553 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23555 (defun org-insert-comment ()
23556 "Insert an empty comment above current line.
23557 If the line is empty, insert comment at its beginning. When
23558 point is within a source block, comment according to the related
23559 major mode."
23560 (if (let ((element (org-element-at-point)))
23561 (and (eq (org-element-type element) 'src-block)
23562 (< (save-excursion
23563 (goto-char (org-element-property :post-affiliated element))
23564 (line-end-position))
23565 (point))
23566 (> (save-excursion
23567 (goto-char (org-element-property :end element))
23568 (skip-chars-backward " \r\t\n")
23569 (line-beginning-position))
23570 (point))))
23571 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23572 (beginning-of-line)
23573 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23574 (open-line 1))
23575 (org-indent-line)
23576 (insert "# ")))
23578 (defvar comment-empty-lines) ; From newcomment.el.
23579 (defun org-comment-or-uncomment-region (beg end &rest _)
23580 "Comment or uncomment each non-blank line in the region.
23581 Uncomment each non-blank line between BEG and END if it only
23582 contains commented lines. Otherwise, comment them. If region is
23583 strictly within a source block, use appropriate comment syntax."
23584 (if (let ((element (org-element-at-point)))
23585 (and (eq (org-element-type element) 'src-block)
23586 (< (save-excursion
23587 (goto-char (org-element-property :post-affiliated element))
23588 (line-end-position))
23589 beg)
23590 (>= (save-excursion
23591 (goto-char (org-element-property :end element))
23592 (skip-chars-backward " \r\t\n")
23593 (line-beginning-position))
23594 end)))
23595 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23596 (save-restriction
23597 ;; Restrict region
23598 (narrow-to-region (save-excursion (goto-char beg)
23599 (skip-chars-forward " \r\t\n" end)
23600 (line-beginning-position))
23601 (save-excursion (goto-char end)
23602 (skip-chars-backward " \r\t\n" beg)
23603 (line-end-position)))
23604 (let ((uncommentp
23605 ;; UNCOMMENTP is non-nil when every non blank line between
23606 ;; BEG and END is a comment.
23607 (save-excursion
23608 (goto-char (point-min))
23609 (while (and (not (eobp))
23610 (let ((element (org-element-at-point)))
23611 (and (eq (org-element-type element) 'comment)
23612 (goto-char (min (point-max)
23613 (org-element-property
23614 :end element)))))))
23615 (eobp))))
23616 (if uncommentp
23617 ;; Only blank lines and comments in region: uncomment it.
23618 (save-excursion
23619 (goto-char (point-min))
23620 (while (not (eobp))
23621 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23622 (replace-match "" nil nil nil 1))
23623 (forward-line)))
23624 ;; Comment each line in region.
23625 (let ((min-indent (point-max)))
23626 ;; First find the minimum indentation across all lines.
23627 (save-excursion
23628 (goto-char (point-min))
23629 (while (and (not (eobp)) (not (zerop min-indent)))
23630 (unless (looking-at "[ \t]*$")
23631 (setq min-indent (min min-indent (current-indentation))))
23632 (forward-line)))
23633 ;; Then loop over all lines.
23634 (save-excursion
23635 (goto-char (point-min))
23636 (while (not (eobp))
23637 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23638 ;; Don't get fooled by invisible text (e.g. link path)
23639 ;; when moving to column MIN-INDENT.
23640 (let ((buffer-invisibility-spec nil))
23641 (org-move-to-column min-indent t))
23642 (insert comment-start))
23643 (forward-line)))))))))
23645 (defun org-comment-dwim (_arg)
23646 "Call `comment-dwim' within a source edit buffer if needed."
23647 (interactive "*P")
23648 (if (org-in-src-block-p)
23649 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23650 (call-interactively 'comment-dwim)))
23653 ;;; Timestamps API
23655 ;; This section contains tools to operate on timestamp objects, as
23656 ;; returned by, e.g. `org-element-context'.
23658 (defun org-timestamp--to-internal-time (timestamp &optional end)
23659 "Encode TIMESTAMP object into Emacs internal time.
23660 Use end of date range or time range when END is non-nil."
23661 (apply #'encode-time
23662 (cons 0
23663 (mapcar
23664 (lambda (prop) (or (org-element-property prop timestamp) 0))
23665 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23666 '(:minute-start :hour-start :day-start :month-start
23667 :year-start))))))
23669 (defun org-timestamp-has-time-p (timestamp)
23670 "Non-nil when TIMESTAMP has a time specified."
23671 (org-element-property :hour-start timestamp))
23673 (defun org-timestamp-format (timestamp format &optional end utc)
23674 "Format a TIMESTAMP object into a string.
23676 FORMAT is a format specifier to be passed to
23677 `format-time-string'.
23679 When optional argument END is non-nil, use end of date-range or
23680 time-range, if possible.
23682 When optional argument UTC is non-nil, time will be expressed as
23683 Universal Time."
23684 (format-time-string
23685 format (org-timestamp--to-internal-time timestamp end) utc))
23687 (defun org-timestamp-split-range (timestamp &optional end)
23688 "Extract a TIMESTAMP object from a date or time range.
23690 END, when non-nil, means extract the end of the range.
23691 Otherwise, extract its start.
23693 Return a new timestamp object."
23694 (let ((type (org-element-property :type timestamp)))
23695 (if (memq type '(active inactive diary)) timestamp
23696 (let ((split-ts (org-element-copy timestamp)))
23697 ;; Set new type.
23698 (org-element-put-property
23699 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23700 ;; Copy start properties over end properties if END is
23701 ;; non-nil. Otherwise, copy end properties over `start' ones.
23702 (let ((p-alist '((:minute-start . :minute-end)
23703 (:hour-start . :hour-end)
23704 (:day-start . :day-end)
23705 (:month-start . :month-end)
23706 (:year-start . :year-end))))
23707 (dolist (p-cell p-alist)
23708 (org-element-put-property
23709 split-ts
23710 (funcall (if end #'car #'cdr) p-cell)
23711 (org-element-property
23712 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23713 ;; Eventually refresh `:raw-value'.
23714 (org-element-put-property split-ts :raw-value nil)
23715 (org-element-put-property
23716 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23718 (defun org-timestamp-translate (timestamp &optional boundary)
23719 "Translate TIMESTAMP object to custom format.
23721 Format string is defined in `org-time-stamp-custom-formats',
23722 which see.
23724 When optional argument BOUNDARY is non-nil, it is either the
23725 symbol `start' or `end'. In this case, only translate the
23726 starting or ending part of TIMESTAMP if it is a date or time
23727 range. Otherwise, translate both parts.
23729 Return timestamp as-is if `org-display-custom-times' is nil or if
23730 it has a `diary' type."
23731 (let ((type (org-element-property :type timestamp)))
23732 (if (or (not org-display-custom-times) (eq type 'diary))
23733 (org-element-interpret-data timestamp)
23734 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23735 org-time-stamp-custom-formats)))
23736 (if (and (not boundary) (memq type '(active-range inactive-range)))
23737 (concat (org-timestamp-format timestamp fmt)
23738 "--"
23739 (org-timestamp-format timestamp fmt t))
23740 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23744 ;;; Other stuff.
23746 (defvar reftex-docstruct-symbol)
23747 (defvar reftex-cite-format)
23748 (defvar org--rds)
23750 (defun org-reftex-citation ()
23751 "Use reftex-citation to insert a citation into the buffer.
23752 This looks for a line like
23754 #+BIBLIOGRAPHY: foo plain option:-d
23756 and derives from it that foo.bib is the bibliography file relevant
23757 for this document. It then installs the necessary environment for RefTeX
23758 to work in this buffer and calls `reftex-citation' to insert a citation
23759 into the buffer.
23761 Export of such citations to both LaTeX and HTML is handled by the contributed
23762 package ox-bibtex by Taru Karttunen."
23763 (interactive)
23764 (let ((reftex-docstruct-symbol 'org--rds)
23765 (reftex-cite-format "\\cite{%l}")
23766 org--rds bib)
23767 (save-excursion
23768 (save-restriction
23769 (widen)
23770 (let ((case-fold-search t)
23771 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23772 (if (not (save-excursion
23773 (or (re-search-forward re nil t)
23774 (re-search-backward re nil t))))
23775 (user-error "No bibliography defined in file")
23776 (setq bib (concat (match-string 1) ".bib")
23777 org--rds (list (list 'bib bib)))))))
23778 (call-interactively 'reftex-citation)))
23780 ;;;; Functions extending outline functionality
23782 (defun org-beginning-of-line (&optional arg)
23783 "Go to the beginning of the current line. If that is invisible, continue
23784 to a visible line beginning. This makes the function of C-a more intuitive.
23785 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23786 first attempt, and only move to after the tags when the cursor is already
23787 beyond the end of the headline."
23788 (interactive "P")
23789 (let ((pos (point))
23790 (special (if (consp org-special-ctrl-a/e)
23791 (car org-special-ctrl-a/e)
23792 org-special-ctrl-a/e))
23793 deactivate-mark refpos)
23794 (if (org-bound-and-true-p visual-line-mode)
23795 (beginning-of-visual-line 1)
23796 (beginning-of-line 1))
23797 (if (and arg (fboundp 'move-beginning-of-line))
23798 (call-interactively 'move-beginning-of-line)
23799 (unless (bobp)
23800 (backward-char 1)
23801 (if (org-truely-invisible-p)
23802 (while (and (not (bobp)) (org-truely-invisible-p))
23803 (backward-char 1)
23804 (beginning-of-line 1))
23805 (forward-char 1))))
23806 (when special
23807 (cond
23808 ((and (looking-at org-complex-heading-regexp)
23809 (eq (char-after (match-end 1)) ?\s))
23810 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23811 (point-at-eol)))
23812 (goto-char
23813 (if (eq special t)
23814 (cond ((> pos refpos) refpos)
23815 ((= pos (point)) refpos)
23816 (t (point)))
23817 (cond ((> pos (point)) (point))
23818 ((not (eq last-command this-command)) (point))
23819 (t refpos)))))
23820 ((org-at-item-p)
23821 ;; Being at an item and not looking at an the item means point
23822 ;; was previously moved to beginning of a visual line, which
23823 ;; doesn't contain the item. Therefore, do nothing special,
23824 ;; just stay here.
23825 (when (looking-at org-list-full-item-re)
23826 ;; Set special position at first white space character after
23827 ;; bullet, and check-box, if any.
23828 (let ((after-bullet
23829 (let ((box (match-end 3)))
23830 (if (not box) (match-end 1)
23831 (let ((after (char-after box)))
23832 (if (and after (= after ? )) (1+ box) box))))))
23833 ;; Special case: Move point to special position when
23834 ;; currently after it or at beginning of line.
23835 (if (eq special t)
23836 (when (or (> pos after-bullet) (= (point) pos))
23837 (goto-char after-bullet))
23838 ;; Reversed case: Move point to special position when
23839 ;; point was already at beginning of line and command is
23840 ;; repeated.
23841 (when (and (= (point) pos) (eq last-command this-command))
23842 (goto-char after-bullet))))))))
23843 (org-no-warnings
23844 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23845 (setq disable-point-adjustment
23846 (or (not (invisible-p (point)))
23847 (not (invisible-p (max (point-min) (1- (point))))))))
23849 (defun org-end-of-line (&optional arg)
23850 "Go to the end of the line.
23851 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23852 tags on the first attempt, and only move to after the tags when
23853 the cursor is already beyond the end of the headline."
23854 (interactive "P")
23855 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23856 org-special-ctrl-a/e))
23857 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23858 'end-of-visual-line)
23859 ((fboundp 'move-end-of-line) 'move-end-of-line)
23860 (t 'end-of-line)))
23861 deactivate-mark)
23862 (if (or (not special) arg) (call-interactively move-fun)
23863 (let* ((element (save-excursion (beginning-of-line)
23864 (org-element-at-point)))
23865 (type (org-element-type element)))
23866 (cond
23867 ((memq type '(headline inlinetask))
23868 (let ((pos (point)))
23869 (beginning-of-line 1)
23870 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23871 (if (eq special t)
23872 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23873 (goto-char (match-beginning 1))
23874 (goto-char (match-end 0)))
23875 (if (or (< pos (match-end 0))
23876 (not (eq this-command last-command)))
23877 (goto-char (match-end 0))
23878 (goto-char (match-beginning 1))))
23879 (call-interactively move-fun))))
23880 ((outline-invisible-p (line-end-position))
23881 ;; If element is hidden, `move-end-of-line' would put point
23882 ;; after it. Use `end-of-line' to stay on current line.
23883 (call-interactively 'end-of-line))
23884 (t (call-interactively move-fun)))))
23885 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23886 (setq disable-point-adjustment
23887 (or (not (invisible-p (point)))
23888 (not (invisible-p (max (point-min) (1- (point))))))))
23890 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23891 (define-key org-mode-map "\C-e" 'org-end-of-line)
23893 (defun org-backward-sentence (&optional _arg)
23894 "Go to beginning of sentence, or beginning of table field.
23895 This will call `backward-sentence' or `org-table-beginning-of-field',
23896 depending on context."
23897 (interactive)
23898 (let* ((element (org-element-at-point))
23899 (contents-begin (org-element-property :contents-begin element))
23900 (table (org-element-lineage element '(table) t)))
23901 (if (and table
23902 (> (point) contents-begin)
23903 (<= (point) (org-element-property :contents-end table)))
23904 (call-interactively #'org-table-beginning-of-field)
23905 (save-restriction
23906 (when (and contents-begin
23907 (< (point-min) contents-begin)
23908 (> (point) contents-begin))
23909 (narrow-to-region contents-begin
23910 (org-element-property :contents-end element)))
23911 (call-interactively #'backward-sentence)))))
23913 (defun org-forward-sentence (&optional _arg)
23914 "Go to end of sentence, or end of table field.
23915 This will call `forward-sentence' or `org-table-end-of-field',
23916 depending on context."
23917 (interactive)
23918 (let* ((element (org-element-at-point))
23919 (contents-end (org-element-property :contents-end element))
23920 (table (org-element-lineage element '(table) t)))
23921 (if (and table
23922 (>= (point) (org-element-property :contents-begin table))
23923 (< (point) contents-end))
23924 (call-interactively #'org-table-end-of-field)
23925 (save-restriction
23926 (when (and contents-end
23927 (> (point-max) contents-end)
23928 ;; Skip blank lines between elements.
23929 (< (org-element-property :end element)
23930 (save-excursion (goto-char contents-end)
23931 (skip-chars-forward " \r\t\n"))))
23932 (narrow-to-region (org-element-property :contents-begin element)
23933 contents-end))
23934 (call-interactively #'forward-sentence)))))
23936 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23937 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23939 (defun org-kill-line (&optional _arg)
23940 "Kill line, to tags or end of line."
23941 (interactive)
23942 (cond
23943 ((or (not org-special-ctrl-k)
23944 (bolp)
23945 (not (org-at-heading-p)))
23946 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23947 org-ctrl-k-protect-subtree
23948 (or (eq org-ctrl-k-protect-subtree 'error)
23949 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23950 (user-error "C-k aborted as it would kill a hidden subtree"))
23951 (call-interactively
23952 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23953 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23954 (kill-region (point) (match-beginning 1))
23955 (org-set-tags nil t))
23956 (t (kill-region (point) (point-at-eol)))))
23958 (define-key org-mode-map "\C-k" 'org-kill-line)
23960 (defun org-yank (&optional arg)
23961 "Yank. If the kill is a subtree, treat it specially.
23962 This command will look at the current kill and check if is a single
23963 subtree, or a series of subtrees[1]. If it passes the test, and if the
23964 cursor is at the beginning of a line or after the stars of a currently
23965 empty headline, then the yank is handled specially. How exactly depends
23966 on the value of the following variables, both set by default.
23968 `org-yank-folded-subtrees'
23969 When set, the subtree(s) will be folded after insertion, but only
23970 if doing so would now swallow text after the yanked text.
23972 `org-yank-adjusted-subtrees'
23973 When set, the subtree will be promoted or demoted in order to
23974 fit into the local outline tree structure, which means that the
23975 level will be adjusted so that it becomes the smaller one of the
23976 two *visible* surrounding headings.
23978 Any prefix to this command will cause `yank' to be called directly with
23979 no special treatment. In particular, a simple \\[universal-argument] prefix \
23980 will just
23981 plainly yank the text as it is.
23983 \[1] The test checks if the first non-white line is a heading
23984 and if there are no other headings with fewer stars."
23985 (interactive "P")
23986 (org-yank-generic 'yank arg))
23988 (defun org-yank-generic (command arg)
23989 "Perform some yank-like command.
23991 This function implements the behavior described in the `org-yank'
23992 documentation. However, it has been generalized to work for any
23993 interactive command with similar behavior."
23995 ;; pretend to be command COMMAND
23996 (setq this-command command)
23998 (if arg
23999 (call-interactively command)
24001 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24002 (and (org-kill-is-subtree-p)
24003 (or (bolp)
24004 (and (looking-at "[ \t]*$")
24005 (string-match
24006 "\\`\\*+\\'"
24007 (buffer-substring (point-at-bol) (point)))))))
24008 swallowp)
24009 (cond
24010 ((and subtreep org-yank-folded-subtrees)
24011 (let ((beg (point))
24012 end)
24013 (if (and subtreep org-yank-adjusted-subtrees)
24014 (org-paste-subtree nil nil 'for-yank)
24015 (call-interactively command))
24017 (setq end (point))
24018 (goto-char beg)
24019 (when (and (bolp) subtreep
24020 (not (setq swallowp
24021 (org-yank-folding-would-swallow-text beg end))))
24022 (org-with-limited-levels
24023 (or (looking-at org-outline-regexp)
24024 (re-search-forward org-outline-regexp-bol end t))
24025 (while (and (< (point) end) (looking-at org-outline-regexp))
24026 (outline-hide-subtree)
24027 (org-cycle-show-empty-lines 'folded)
24028 (condition-case nil
24029 (outline-forward-same-level 1)
24030 (error (goto-char end))))))
24031 (when swallowp
24032 (message
24033 "Inserted text not folded because that would swallow text"))
24035 (goto-char end)
24036 (skip-chars-forward " \t\n\r")
24037 (beginning-of-line 1)
24038 (push-mark beg 'nomsg)))
24039 ((and subtreep org-yank-adjusted-subtrees)
24040 (let ((beg (point-at-bol)))
24041 (org-paste-subtree nil nil 'for-yank)
24042 (push-mark beg 'nomsg)))
24044 (call-interactively command))))))
24046 (defun org-yank-folding-would-swallow-text (beg end)
24047 "Would hide-subtree at BEG swallow any text after END?"
24048 (let (level)
24049 (org-with-limited-levels
24050 (save-excursion
24051 (goto-char beg)
24052 (when (or (looking-at org-outline-regexp)
24053 (re-search-forward org-outline-regexp-bol end t))
24054 (setq level (org-outline-level)))
24055 (goto-char end)
24056 (skip-chars-forward " \t\r\n\v\f")
24057 (not (or (eobp)
24058 (and (bolp) (looking-at-p org-outline-regexp)
24059 (<= (org-outline-level) level))))))))
24061 (define-key org-mode-map "\C-y" 'org-yank)
24063 (defun org-truely-invisible-p ()
24064 "Check if point is at a character currently not visible.
24065 This version does not only check the character property, but also
24066 `visible-mode'."
24067 ;; Early versions of noutline don't have `outline-invisible-p'.
24068 (unless (org-bound-and-true-p visible-mode)
24069 (outline-invisible-p)))
24071 (defun org-invisible-p2 ()
24072 "Check if point is at a character currently not visible."
24073 (save-excursion
24074 (when (and (eolp) (not (bobp))) (backward-char 1))
24075 ;; Early versions of noutline don't have `outline-invisible-p'.
24076 (outline-invisible-p)))
24078 (defun org-back-to-heading (&optional invisible-ok)
24079 "Call `outline-back-to-heading', but provide a better error message."
24080 (condition-case nil
24081 (outline-back-to-heading invisible-ok)
24082 (error (error "Before first headline at position %d in buffer %s"
24083 (point) (current-buffer)))))
24085 (defun org-before-first-heading-p ()
24086 "Before first heading?"
24087 (save-excursion
24088 (end-of-line)
24089 (null (re-search-backward org-outline-regexp-bol nil t))))
24091 (defun org-at-heading-p (&optional ignored)
24092 (outline-on-heading-p t))
24093 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24094 ;;; warning was only added in Org 9.0, which should be taken into
24095 ;;; account when deciding when to remove the alias.
24096 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24098 (defun org-in-commented-heading-p (&optional no-inheritance)
24099 "Non-nil if point is under a commented heading.
24100 This function also checks ancestors of the current headline,
24101 unless optional argument NO-INHERITANCE is non-nil."
24102 (cond
24103 ((org-before-first-heading-p) nil)
24104 ((let ((headline (nth 4 (org-heading-components))))
24105 (and headline
24106 (let ((case-fold-search nil))
24107 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24108 headline)))))
24109 (no-inheritance nil)
24111 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24113 (defun org-at-comment-p nil
24114 "Is cursor in a commented line?"
24115 (save-excursion
24116 (save-match-data
24117 (beginning-of-line)
24118 (looking-at "^[ \t]*# "))))
24120 (defun org-at-drawer-p nil
24121 "Is cursor at a drawer keyword?"
24122 (save-excursion
24123 (move-beginning-of-line 1)
24124 (looking-at org-drawer-regexp)))
24126 (defun org-at-block-p nil
24127 "Is cursor at a block keyword?"
24128 (save-excursion
24129 (move-beginning-of-line 1)
24130 (looking-at org-block-regexp)))
24132 (defun org-point-at-end-of-empty-headline ()
24133 "If point is at the end of an empty headline, return t, else nil.
24134 If the heading only contains a TODO keyword, it is still still considered
24135 empty."
24136 (and (looking-at "[ \t]*$")
24137 (when org-todo-line-regexp
24138 (save-excursion
24139 (beginning-of-line 1)
24140 (let ((case-fold-search nil))
24141 (looking-at org-todo-line-regexp)
24142 (string= (match-string 3) ""))))))
24144 (defun org-at-heading-or-item-p ()
24145 (or (org-at-heading-p) (org-at-item-p)))
24147 (defun org-at-target-p ()
24148 (or (org-in-regexp org-radio-target-regexp)
24149 (org-in-regexp org-target-regexp)))
24150 ;; Compatibility alias with Org versions < 7.8.03
24151 (defalias 'org-on-target-p 'org-at-target-p)
24153 (defun org-up-heading-all (arg)
24154 "Move to the heading line of which the present line is a subheading.
24155 This function considers both visible and invisible heading lines.
24156 With argument, move up ARG levels."
24157 (if (fboundp 'outline-up-heading-all)
24158 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24159 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24161 (defun org-up-heading-safe ()
24162 "Move to the heading line of which the present line is a subheading.
24163 This version will not throw an error. It will return the level of the
24164 headline found, or nil if no higher level is found.
24166 Also, this function will be a lot faster than `outline-up-heading',
24167 because it relies on stars being the outline starters. This can really
24168 make a significant difference in outlines with very many siblings."
24169 (when (ignore-errors (org-back-to-heading t))
24170 (let ((level-up (1- (funcall outline-level))))
24171 (and (> level-up 0)
24172 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24173 (funcall outline-level)))))
24175 (defun org-first-sibling-p ()
24176 "Is this heading the first child of its parents?"
24177 (interactive)
24178 (let ((re org-outline-regexp-bol)
24179 level l)
24180 (unless (org-at-heading-p t)
24181 (user-error "Not at a heading"))
24182 (setq level (funcall outline-level))
24183 (save-excursion
24184 (if (not (re-search-backward re nil t))
24186 (setq l (funcall outline-level))
24187 (< l level)))))
24189 (defun org-goto-sibling (&optional previous)
24190 "Goto the next sibling, even if it is invisible.
24191 When PREVIOUS is set, go to the previous sibling instead. Returns t
24192 when a sibling was found. When none is found, return nil and don't
24193 move point."
24194 (let ((fun (if previous 're-search-backward 're-search-forward))
24195 (pos (point))
24196 (re org-outline-regexp-bol)
24197 level l)
24198 (when (ignore-errors (org-back-to-heading t))
24199 (setq level (funcall outline-level))
24200 (catch 'exit
24201 (or previous (forward-char 1))
24202 (while (funcall fun re nil t)
24203 (setq l (funcall outline-level))
24204 (when (< l level) (goto-char pos) (throw 'exit nil))
24205 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24206 (goto-char pos)
24207 nil))))
24209 (defun org-show-siblings ()
24210 "Show all siblings of the current headline."
24211 (save-excursion
24212 (while (org-goto-sibling) (org-flag-heading nil)))
24213 (save-excursion
24214 (while (org-goto-sibling 'previous)
24215 (org-flag-heading nil))))
24217 (defun org-goto-first-child ()
24218 "Goto the first child, even if it is invisible.
24219 Return t when a child was found. Otherwise don't move point and
24220 return nil."
24221 (let (level (pos (point)) (re org-outline-regexp-bol))
24222 (when (ignore-errors (org-back-to-heading t))
24223 (setq level (outline-level))
24224 (forward-char 1)
24225 (if (and (re-search-forward re nil t) (> (outline-level) level))
24226 (progn (goto-char (match-beginning 0)) t)
24227 (goto-char pos) nil))))
24229 (defun org-show-hidden-entry ()
24230 "Show an entry where even the heading is hidden."
24231 (save-excursion
24232 (org-show-entry)))
24234 (defun org-flag-heading (flag &optional entry)
24235 "Flag the current heading. FLAG non-nil means make invisible.
24236 When ENTRY is non-nil, show the entire entry."
24237 (save-excursion
24238 (org-back-to-heading t)
24239 ;; Check if we should show the entire entry
24240 (if entry
24241 (progn
24242 (org-show-entry)
24243 (save-excursion
24244 (and (outline-next-heading)
24245 (org-flag-heading nil))))
24246 (outline-flag-region (max (point-min) (1- (point)))
24247 (save-excursion (outline-end-of-heading) (point))
24248 flag))))
24250 (defun org-get-next-sibling ()
24251 "Move to next heading of the same level, and return point.
24252 If there is no such heading, return nil.
24253 This is like outline-next-sibling, but invisible headings are ok."
24254 (let ((level (funcall outline-level)))
24255 (outline-next-heading)
24256 (while (and (not (eobp)) (> (funcall outline-level) level))
24257 (outline-next-heading))
24258 (unless (or (eobp) (< (funcall outline-level) level))
24259 (point))))
24261 (defun org-get-last-sibling ()
24262 "Move to previous heading of the same level, and return point.
24263 If there is no such heading, return nil."
24264 (let ((opoint (point))
24265 (level (funcall outline-level)))
24266 (outline-previous-heading)
24267 (when (and (/= (point) opoint) (outline-on-heading-p t))
24268 (while (and (> (funcall outline-level) level)
24269 (not (bobp)))
24270 (outline-previous-heading))
24271 (unless (< (funcall outline-level) level)
24272 (point)))))
24274 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24275 "Goto to the end of a subtree."
24276 ;; This contains an exact copy of the original function, but it uses
24277 ;; `org-back-to-heading', to make it work also in invisible
24278 ;; trees. And is uses an invisible-ok argument.
24279 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24280 ;; Furthermore, when used inside Org, finding the end of a large subtree
24281 ;; with many children and grandchildren etc, this can be much faster
24282 ;; than the outline version.
24283 (org-back-to-heading invisible-ok)
24284 (let ((first t)
24285 (level (funcall outline-level)))
24286 (if (and (derived-mode-p 'org-mode) (< level 1000))
24287 ;; A true heading (not a plain list item), in Org-mode
24288 ;; This means we can easily find the end by looking
24289 ;; only for the right number of stars. Using a regexp to do
24290 ;; this is so much faster than using a Lisp loop.
24291 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24292 (forward-char 1)
24293 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24294 ;; something else, do it the slow way
24295 (while (and (not (eobp))
24296 (or first (> (funcall outline-level) level)))
24297 (setq first nil)
24298 (outline-next-heading)))
24299 (unless to-heading
24300 (when (memq (preceding-char) '(?\n ?\^M))
24301 ;; Go to end of line before heading
24302 (forward-char -1)
24303 (when (memq (preceding-char) '(?\n ?\^M))
24304 ;; leave blank line before heading
24305 (forward-char -1)))))
24306 (point))
24308 (defun org-end-of-meta-data (&optional full)
24309 "Skip planning line and properties drawer in current entry.
24310 When optional argument FULL is non-nil, also skip empty lines,
24311 clocking lines and regular drawers at the beginning of the
24312 entry."
24313 (org-back-to-heading t)
24314 (forward-line)
24315 (when (org-looking-at-p org-planning-line-re) (forward-line))
24316 (when (looking-at org-property-drawer-re)
24317 (goto-char (match-end 0))
24318 (forward-line))
24319 (when (and full (not (org-at-heading-p)))
24320 (catch 'exit
24321 (let ((end (save-excursion (outline-next-heading) (point)))
24322 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24323 (while (not (eobp))
24324 (cond ((org-looking-at-p org-drawer-regexp)
24325 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24326 (forward-line)
24327 (throw 'exit t)))
24328 ((org-looking-at-p re) (forward-line))
24329 (t (throw 'exit t))))))))
24331 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24332 "Move forward to the ARG'th subheading at same level as this one.
24333 Stop at the first and last subheadings of a superior heading.
24334 Normally this only looks at visible headings, but when INVISIBLE-OK is
24335 non-nil it will also look at invisible ones."
24336 (interactive "p")
24337 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24338 (if (and arg (< arg 0))
24339 (goto-char (point-min))
24340 (outline-next-heading))
24341 (org-at-heading-p)
24342 (let ((level (- (match-end 0) (match-beginning 0) 1))
24343 (f (if (and arg (< arg 0))
24344 're-search-backward
24345 're-search-forward))
24346 (count (if arg (abs arg) 1))
24347 (result (point)))
24348 (while (and (prog1 (> count 0)
24349 (forward-char (if (and arg (< arg 0)) -1 1)))
24350 (funcall f org-outline-regexp-bol nil 'move))
24351 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24352 (cond ((< l level) (setq count 0))
24353 ((and (= l level)
24354 (or invisible-ok
24355 (progn
24356 (goto-char (line-beginning-position))
24357 (not (outline-invisible-p)))))
24358 (setq count (1- count))
24359 (when (eq l level)
24360 (setq result (point)))))))
24361 (goto-char result))
24362 (beginning-of-line 1)))
24364 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24365 "Move backward to the ARG'th subheading at same level as this one.
24366 Stop at the first and last subheadings of a superior heading."
24367 (interactive "p")
24368 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24370 (defun org-next-visible-heading (arg)
24371 "Move to the next visible heading.
24373 This function wraps `outline-next-visible-heading' with
24374 `org-with-limited-levels' in order to skip over inline tasks and
24375 respect customization of `org-odd-levels-only'."
24376 (interactive "p")
24377 (org-with-limited-levels
24378 (outline-next-visible-heading arg)))
24380 (defun org-previous-visible-heading (arg)
24381 "Move to the previous visible heading.
24383 This function wraps `outline-previous-visible-heading' with
24384 `org-with-limited-levels' in order to skip over inline tasks and
24385 respect customization of `org-odd-levels-only'."
24386 (interactive "p")
24387 (org-with-limited-levels
24388 (outline-previous-visible-heading arg)))
24390 (defun org-next-block (arg &optional backward block-regexp)
24391 "Jump to the next block.
24393 With a prefix argument ARG, jump forward ARG many blocks.
24395 When BACKWARD is non-nil, jump to the previous block.
24397 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24398 Match data is set according to this regexp when the function
24399 returns.
24401 Return point at beginning of the opening line of found block.
24402 Throw an error if no block is found."
24403 (interactive "p")
24404 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24405 (case-fold-search t)
24406 (search-fn (if backward #'re-search-backward #'re-search-forward))
24407 (count (or arg 1))
24408 (origin (point))
24409 last-element)
24410 (if backward (beginning-of-line) (end-of-line))
24411 (while (and (> count 0) (funcall search-fn re nil t))
24412 (let ((element (save-excursion
24413 (goto-char (match-beginning 0))
24414 (save-match-data (org-element-at-point)))))
24415 (when (and (memq (org-element-type element)
24416 '(center-block comment-block dynamic-block
24417 example-block export-block quote-block
24418 special-block src-block verse-block))
24419 (<= (match-beginning 0)
24420 (org-element-property :post-affiliated element)))
24421 (setq last-element element)
24422 (cl-decf count))))
24423 (if (= count 0)
24424 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24425 (save-match-data (org-show-context)))
24426 (goto-char origin)
24427 (user-error "No %s code blocks" (if backward "previous" "further")))))
24429 (defun org-previous-block (arg &optional block-regexp)
24430 "Jump to the previous block.
24431 With a prefix argument ARG, jump backward ARG many source blocks.
24432 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24433 (interactive "p")
24434 (org-next-block arg t block-regexp))
24436 (defun org-forward-paragraph ()
24437 "Move forward to beginning of next paragraph or equivalent.
24439 The function moves point to the beginning of the next visible
24440 structural element, which can be a paragraph, a table, a list
24441 item, etc. It also provides some special moves for convenience:
24443 - On an affiliated keyword, jump to the beginning of the
24444 relative element.
24445 - On an item or a footnote definition, move to the second
24446 element inside, if any.
24447 - On a table or a property drawer, jump after it.
24448 - On a verse or source block, stop after blank lines."
24449 (interactive)
24450 (when (eobp) (user-error "Cannot move further down"))
24451 (let* ((deactivate-mark nil)
24452 (element (org-element-at-point))
24453 (type (org-element-type element))
24454 (post-affiliated (org-element-property :post-affiliated element))
24455 (contents-begin (org-element-property :contents-begin element))
24456 (contents-end (org-element-property :contents-end element))
24457 (end (let ((end (org-element-property :end element)) (parent element))
24458 (while (and (setq parent (org-element-property :parent parent))
24459 (= (org-element-property :contents-end parent) end))
24460 (setq end (org-element-property :end parent)))
24461 end)))
24462 (cond ((not element)
24463 (skip-chars-forward " \r\t\n")
24464 (or (eobp) (beginning-of-line)))
24465 ;; On affiliated keywords, move to element's beginning.
24466 ((< (point) post-affiliated)
24467 (goto-char post-affiliated))
24468 ;; At a table row, move to the end of the table. Similarly,
24469 ;; at a node property, move to the end of the property
24470 ;; drawer.
24471 ((memq type '(node-property table-row))
24472 (goto-char (org-element-property
24473 :end (org-element-property :parent element))))
24474 ((memq type '(property-drawer table)) (goto-char end))
24475 ;; Consider blank lines as separators in verse and source
24476 ;; blocks to ease editing.
24477 ((memq type '(src-block verse-block))
24478 (when (eq type 'src-block)
24479 (setq contents-end
24480 (save-excursion (goto-char end)
24481 (skip-chars-backward " \r\t\n")
24482 (line-beginning-position))))
24483 (beginning-of-line)
24484 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24485 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24486 (goto-char end)
24487 (skip-chars-forward " \r\t\n")
24488 (if (= (point) contents-end) (goto-char end)
24489 (beginning-of-line))))
24490 ;; With no contents, just skip element.
24491 ((not contents-begin) (goto-char end))
24492 ;; If contents are invisible, skip the element altogether.
24493 ((outline-invisible-p (line-end-position))
24494 (cl-case type
24495 (headline
24496 (org-with-limited-levels (outline-next-visible-heading 1)))
24497 ;; At a plain list, make sure we move to the next item
24498 ;; instead of skipping the whole list.
24499 (plain-list (forward-char)
24500 (org-forward-paragraph))
24501 (otherwise (goto-char end))))
24502 ((>= (point) contents-end) (goto-char end))
24503 ((>= (point) contents-begin)
24504 ;; This can only happen on paragraphs and plain lists.
24505 (cl-case type
24506 (paragraph (goto-char end))
24507 ;; At a plain list, try to move to second element in
24508 ;; first item, if possible.
24509 (plain-list (end-of-line)
24510 (org-forward-paragraph))))
24511 ;; When contents start on the middle of a line (e.g. in
24512 ;; items and footnote definitions), try to reach first
24513 ;; element starting after current line.
24514 ((> (line-end-position) contents-begin)
24515 (end-of-line)
24516 (org-forward-paragraph))
24517 (t (goto-char contents-begin)))))
24519 (defun org-backward-paragraph ()
24520 "Move backward to start of previous paragraph or equivalent.
24522 The function moves point to the beginning of the current
24523 structural element, which can be a paragraph, a table, a list
24524 item, etc., or to the beginning of the previous visible one if
24525 point is already there. It also provides some special moves for
24526 convenience:
24528 - On an affiliated keyword, jump to the first one.
24529 - On a table or a property drawer, move to its beginning.
24530 - On a verse or source block, stop before blank lines."
24531 (interactive)
24532 (when (bobp) (user-error "Cannot move further up"))
24533 (let* ((deactivate-mark nil)
24534 (element (org-element-at-point))
24535 (type (org-element-type element))
24536 (contents-begin (org-element-property :contents-begin element))
24537 (contents-end (org-element-property :contents-end element))
24538 (post-affiliated (org-element-property :post-affiliated element))
24539 (begin (org-element-property :begin element)))
24540 (cond
24541 ((not element) (goto-char (point-min)))
24542 ((= (point) begin)
24543 (backward-char)
24544 (org-backward-paragraph))
24545 ((<= (point) post-affiliated) (goto-char begin))
24546 ((memq type '(node-property table-row))
24547 (goto-char (org-element-property
24548 :post-affiliated (org-element-property :parent element))))
24549 ((memq type '(property-drawer table)) (goto-char begin))
24550 ((memq type '(src-block verse-block))
24551 (when (eq type 'src-block)
24552 (setq contents-begin
24553 (save-excursion (goto-char begin) (forward-line) (point))))
24554 (if (= (point) contents-begin) (goto-char post-affiliated)
24555 ;; Inside a verse block, see blank lines as paragraph
24556 ;; separators.
24557 (let ((origin (point)))
24558 (skip-chars-backward " \r\t\n" contents-begin)
24559 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24560 (skip-chars-forward " \r\t\n" origin)
24561 (if (= (point) origin) (goto-char contents-begin)
24562 (beginning-of-line))))))
24563 ((not contents-begin) (goto-char (or post-affiliated begin)))
24564 ((eq type 'paragraph)
24565 (goto-char contents-begin)
24566 ;; When at first paragraph in an item or a footnote definition,
24567 ;; move directly to beginning of line.
24568 (let ((parent-contents
24569 (org-element-property
24570 :contents-begin (org-element-property :parent element))))
24571 (when (and parent-contents (= parent-contents contents-begin))
24572 (beginning-of-line))))
24573 ;; At the end of a greater element, move to the beginning of the
24574 ;; last element within.
24575 ((>= (point) contents-end)
24576 (goto-char (1- contents-end))
24577 (org-backward-paragraph))
24578 (t (goto-char (or post-affiliated begin))))
24579 ;; Ensure we never leave point invisible.
24580 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24582 (defun org-forward-element ()
24583 "Move forward by one element.
24584 Move to the next element at the same level, when possible."
24585 (interactive)
24586 (cond ((eobp) (user-error "Cannot move further down"))
24587 ((org-with-limited-levels (org-at-heading-p))
24588 (let ((origin (point)))
24589 (goto-char (org-end-of-subtree nil t))
24590 (unless (org-with-limited-levels (org-at-heading-p))
24591 (goto-char origin)
24592 (user-error "Cannot move further down"))))
24594 (let* ((elem (org-element-at-point))
24595 (end (org-element-property :end elem))
24596 (parent (org-element-property :parent elem)))
24597 (cond ((and parent (= (org-element-property :contents-end parent) end))
24598 (goto-char (org-element-property :end parent)))
24599 ((integer-or-marker-p end) (goto-char end))
24600 (t (message "No element at point")))))))
24602 (defun org-backward-element ()
24603 "Move backward by one element.
24604 Move to the previous element at the same level, when possible."
24605 (interactive)
24606 (cond ((bobp) (user-error "Cannot move further up"))
24607 ((org-with-limited-levels (org-at-heading-p))
24608 ;; At a headline, move to the previous one, if any, or stay
24609 ;; here.
24610 (let ((origin (point)))
24611 (org-with-limited-levels (org-backward-heading-same-level 1))
24612 ;; When current headline has no sibling above, move to its
24613 ;; parent.
24614 (when (= (point) origin)
24615 (or (org-with-limited-levels (org-up-heading-safe))
24616 (progn (goto-char origin)
24617 (user-error "Cannot move further up"))))))
24619 (let* ((elem (org-element-at-point))
24620 (beg (org-element-property :begin elem)))
24621 (cond
24622 ;; Move to beginning of current element if point isn't
24623 ;; there already.
24624 ((null beg) (message "No element at point"))
24625 ((/= (point) beg) (goto-char beg))
24626 (t (goto-char beg)
24627 (skip-chars-backward " \r\t\n")
24628 (unless (bobp)
24629 (let ((prev (org-element-at-point)))
24630 (goto-char (org-element-property :begin prev))
24631 (while (and (setq prev (org-element-property :parent prev))
24632 (<= (org-element-property :end prev) beg))
24633 (goto-char (org-element-property :begin prev)))))))))))
24635 (defun org-up-element ()
24636 "Move to upper element."
24637 (interactive)
24638 (if (org-with-limited-levels (org-at-heading-p))
24639 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24640 (let* ((elem (org-element-at-point))
24641 (parent (org-element-property :parent elem)))
24642 (if parent (goto-char (org-element-property :begin parent))
24643 (if (org-with-limited-levels (org-before-first-heading-p))
24644 (user-error "No surrounding element")
24645 (org-with-limited-levels (org-back-to-heading)))))))
24647 (defvar org-element-greater-elements)
24648 (defun org-down-element ()
24649 "Move to inner element."
24650 (interactive)
24651 (let ((element (org-element-at-point)))
24652 (cond
24653 ((memq (org-element-type element) '(plain-list table))
24654 (goto-char (org-element-property :contents-begin element))
24655 (forward-char))
24656 ((memq (org-element-type element) org-element-greater-elements)
24657 ;; If contents are hidden, first disclose them.
24658 (when (outline-invisible-p (line-end-position)) (org-cycle))
24659 (goto-char (or (org-element-property :contents-begin element)
24660 (user-error "No content for this element"))))
24661 (t (user-error "No inner element")))))
24663 (defun org-drag-element-backward ()
24664 "Move backward element at point."
24665 (interactive)
24666 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24667 (let* ((elem (org-element-at-point))
24668 (prev-elem
24669 (save-excursion
24670 (goto-char (org-element-property :begin elem))
24671 (skip-chars-backward " \r\t\n")
24672 (unless (bobp)
24673 (let* ((beg (org-element-property :begin elem))
24674 (prev (org-element-at-point))
24675 (up prev))
24676 (while (and (setq up (org-element-property :parent up))
24677 (<= (org-element-property :end up) beg))
24678 (setq prev up))
24679 prev)))))
24680 ;; Error out if no previous element or previous element is
24681 ;; a parent of the current one.
24682 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24683 (user-error "Cannot drag element backward")
24684 (let ((pos (point)))
24685 (org-element-swap-A-B prev-elem elem)
24686 (goto-char (+ (org-element-property :begin prev-elem)
24687 (- pos (org-element-property :begin elem)))))))))
24689 (defun org-drag-element-forward ()
24690 "Move forward element at point."
24691 (interactive)
24692 (let* ((pos (point))
24693 (elem (org-element-at-point)))
24694 (when (= (point-max) (org-element-property :end elem))
24695 (user-error "Cannot drag element forward"))
24696 (goto-char (org-element-property :end elem))
24697 (let ((next-elem (org-element-at-point)))
24698 (when (or (org-element-nested-p elem next-elem)
24699 (and (eq (org-element-type next-elem) 'headline)
24700 (not (eq (org-element-type elem) 'headline))))
24701 (goto-char pos)
24702 (user-error "Cannot drag element forward"))
24703 ;; Compute new position of point: it's shifted by NEXT-ELEM
24704 ;; body's length (without final blanks) and by the length of
24705 ;; blanks between ELEM and NEXT-ELEM.
24706 (let ((size-next (- (save-excursion
24707 (goto-char (org-element-property :end next-elem))
24708 (skip-chars-backward " \r\t\n")
24709 (forward-line)
24710 ;; Small correction if buffer doesn't end
24711 ;; with a newline character.
24712 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24713 (org-element-property :begin next-elem)))
24714 (size-blank (- (org-element-property :end elem)
24715 (save-excursion
24716 (goto-char (org-element-property :end elem))
24717 (skip-chars-backward " \r\t\n")
24718 (forward-line)
24719 (point)))))
24720 (org-element-swap-A-B elem next-elem)
24721 (goto-char (+ pos size-next size-blank))))))
24723 (defun org-drag-line-forward (arg)
24724 "Drag the line at point ARG lines forward."
24725 (interactive "p")
24726 (dotimes (_ (abs arg))
24727 (let ((c (current-column)))
24728 (if (< 0 arg)
24729 (progn
24730 (beginning-of-line 2)
24731 (transpose-lines 1)
24732 (beginning-of-line 0))
24733 (transpose-lines 1)
24734 (beginning-of-line -1))
24735 (org-move-to-column c))))
24737 (defun org-drag-line-backward (arg)
24738 "Drag the line at point ARG lines backward."
24739 (interactive "p")
24740 (org-drag-line-forward (- arg)))
24742 (defun org-mark-element ()
24743 "Put point at beginning of this element, mark at end.
24745 Interactively, if this command is repeated or (in Transient Mark
24746 mode) if the mark is active, it marks the next element after the
24747 ones already marked."
24748 (interactive)
24749 (let (deactivate-mark)
24750 (if (and (org-called-interactively-p 'any)
24751 (or (and (eq last-command this-command) (mark t))
24752 (and transient-mark-mode mark-active)))
24753 (set-mark
24754 (save-excursion
24755 (goto-char (mark))
24756 (goto-char (org-element-property :end (org-element-at-point)))))
24757 (let ((element (org-element-at-point)))
24758 (end-of-line)
24759 (push-mark (org-element-property :end element) t t)
24760 (goto-char (org-element-property :begin element))))))
24762 (defun org-narrow-to-element ()
24763 "Narrow buffer to current element."
24764 (interactive)
24765 (let ((elem (org-element-at-point)))
24766 (cond
24767 ((eq (car elem) 'headline)
24768 (narrow-to-region
24769 (org-element-property :begin elem)
24770 (org-element-property :end elem)))
24771 ((memq (car elem) org-element-greater-elements)
24772 (narrow-to-region
24773 (org-element-property :contents-begin elem)
24774 (org-element-property :contents-end elem)))
24776 (narrow-to-region
24777 (org-element-property :begin elem)
24778 (org-element-property :end elem))))))
24780 (defun org-transpose-element ()
24781 "Transpose current and previous elements, keeping blank lines between.
24782 Point is moved after both elements."
24783 (interactive)
24784 (org-skip-whitespace)
24785 (let ((end (org-element-property :end (org-element-at-point))))
24786 (org-drag-element-backward)
24787 (goto-char end)))
24789 (defun org-unindent-buffer ()
24790 "Un-indent the visible part of the buffer.
24791 Relative indentation (between items, inside blocks, etc.) isn't
24792 modified."
24793 (interactive)
24794 (unless (eq major-mode 'org-mode)
24795 (user-error "Cannot un-indent a buffer not in Org mode"))
24796 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24797 (unindent-tree
24798 (lambda (contents)
24799 (dolist (element (reverse contents))
24800 (if (memq (org-element-type element) '(headline section))
24801 (funcall unindent-tree (org-element-contents element))
24802 (save-excursion
24803 (save-restriction
24804 (narrow-to-region
24805 (org-element-property :begin element)
24806 (org-element-property :end element))
24807 (org-do-remove-indentation))))))))
24808 (funcall unindent-tree (org-element-contents parse-tree))))
24810 (defun org-show-children (&optional level)
24811 "Show all direct subheadings of this heading.
24812 Prefix arg LEVEL is how many levels below the current level
24813 should be shown. Default is enough to cause the following
24814 heading to appear."
24815 (interactive "p")
24816 ;; If `orgstruct-mode' is active, use the slower version.
24817 (if orgstruct-mode (call-interactively #'outline-show-children)
24818 (save-excursion
24819 (org-back-to-heading t)
24820 (let* ((current-level (funcall outline-level))
24821 (max-level (org-get-valid-level
24822 current-level
24823 (if level (prefix-numeric-value level) 1)))
24824 (end (save-excursion (org-end-of-subtree t t)))
24825 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24826 (past-first-child nil)
24827 ;; Make sure to skip inlinetasks.
24828 (re (format regexp-fmt
24829 current-level
24830 (cond
24831 ((not (featurep 'org-inlinetask)) "")
24832 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24834 (t (1- org-inlinetask-min-level))))))
24835 ;; Display parent heading.
24836 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24837 (forward-line)
24838 ;; Display children. First child may be deeper than expected
24839 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24840 ;; MAX-LEVEL accordingly.
24841 (while (re-search-forward re end t)
24842 (unless past-first-child
24843 (setq re (format regexp-fmt
24844 current-level
24845 (max (funcall outline-level) max-level)))
24846 (setq past-first-child t))
24847 (outline-flag-region
24848 (line-end-position 0) (line-end-position) nil))))))
24850 (defun org-show-subtree ()
24851 "Show everything after this heading at deeper levels."
24852 (interactive)
24853 (outline-flag-region
24854 (point)
24855 (save-excursion
24856 (org-end-of-subtree t t))
24857 nil))
24859 (defun org-show-entry ()
24860 "Show the body directly following this heading.
24861 Show the heading too, if it is currently invisible."
24862 (interactive)
24863 (save-excursion
24864 (ignore-errors
24865 (org-back-to-heading t)
24866 (outline-flag-region
24867 (max (point-min) (1- (point)))
24868 (save-excursion
24869 (if (re-search-forward
24870 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24871 (match-beginning 1)
24872 (point-max)))
24873 nil)
24874 (org-cycle-hide-drawers 'children))))
24876 (defun org-make-options-regexp (kwds &optional extra)
24877 "Make a regular expression for keyword lines.
24878 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24879 when non-nil, is a regexp matching keywords names."
24880 (concat "^[ \t]*#\\+\\("
24881 (regexp-opt kwds)
24882 (and extra (concat (and kwds "\\|") extra))
24883 "\\):[ \t]*\\(.*\\)"))
24885 ;;;; Integration with and fixes for other packages
24887 ;;; Imenu support
24889 (defvar-local org-imenu-markers nil
24890 "All markers currently used by Imenu.")
24892 (defun org-imenu-new-marker (&optional pos)
24893 "Return a new marker for use by Imenu, and remember the marker."
24894 (let ((m (make-marker)))
24895 (move-marker m (or pos (point)))
24896 (push m org-imenu-markers)
24899 (defun org-imenu-get-tree ()
24900 "Produce the index for Imenu."
24901 (dolist (x org-imenu-markers) (move-marker x nil))
24902 (setq org-imenu-markers nil)
24903 (let* ((n org-imenu-depth)
24904 (re (concat "^" (org-get-limited-outline-regexp)))
24905 (subs (make-vector (1+ n) nil))
24906 (last-level 0)
24907 m level head0 head)
24908 (save-excursion
24909 (save-restriction
24910 (widen)
24911 (goto-char (point-max))
24912 (while (re-search-backward re nil t)
24913 (setq level (org-reduced-level (funcall outline-level)))
24914 (when (and (<= level n)
24915 (looking-at org-complex-heading-regexp)
24916 (setq head0 (org-match-string-no-properties 4)))
24917 (setq head (org-link-display-format head0)
24918 m (org-imenu-new-marker))
24919 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24920 (if (>= level last-level)
24921 (push (cons head m) (aref subs level))
24922 (push (cons head (aref subs (1+ level))) (aref subs level))
24923 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24924 (setq last-level level)))))
24925 (aref subs 1)))
24927 (eval-after-load "imenu"
24928 '(progn
24929 (add-hook 'imenu-after-jump-hook
24930 (lambda ()
24931 (when (derived-mode-p 'org-mode)
24932 (org-show-context 'org-goto))))))
24934 (defun org-link-display-format (s)
24935 "Replace links in string S with their description.
24936 If there is no description, use the link target."
24937 (save-match-data
24938 (replace-regexp-in-string
24939 org-bracket-link-analytic-regexp
24940 (lambda (m)
24941 (if (match-end 5) (match-string 5 m)
24942 (concat (match-string 1 m) (match-string 3 m))))
24943 s nil t)))
24945 (defun org-toggle-link-display ()
24946 "Toggle the literal or descriptive display of links."
24947 (interactive)
24948 (if org-descriptive-links
24949 (progn (org-remove-from-invisibility-spec '(org-link))
24950 (org-restart-font-lock)
24951 (setq org-descriptive-links nil))
24952 (progn (add-to-invisibility-spec '(org-link))
24953 (org-restart-font-lock)
24954 (setq org-descriptive-links t))))
24956 ;; Speedbar support
24958 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
24959 "Overlay marking the agenda restriction line in speedbar.")
24960 (overlay-put org-speedbar-restriction-lock-overlay
24961 'face 'org-agenda-restriction-lock)
24962 (overlay-put org-speedbar-restriction-lock-overlay
24963 'help-echo "Agendas are currently limited to this item.")
24964 (org-detach-overlay org-speedbar-restriction-lock-overlay)
24966 (defun org-speedbar-set-agenda-restriction ()
24967 "Restrict future agenda commands to the location at point in speedbar.
24968 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
24969 (interactive)
24970 (require 'org-agenda)
24971 (let (p m tp np dir txt)
24972 (cond
24973 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24974 'org-imenu t))
24975 (setq m (get-text-property p 'org-imenu-marker))
24976 (with-current-buffer (marker-buffer m)
24977 (goto-char m)
24978 (org-agenda-set-restriction-lock 'subtree)))
24979 ((setq p (text-property-any (point-at-bol) (point-at-eol)
24980 'speedbar-function 'speedbar-find-file))
24981 (setq tp (previous-single-property-change
24982 (1+ p) 'speedbar-function)
24983 np (next-single-property-change
24984 tp 'speedbar-function)
24985 dir (speedbar-line-directory)
24986 txt (buffer-substring-no-properties (or tp (point-min))
24987 (or np (point-max))))
24988 (with-current-buffer (find-file-noselect
24989 (let ((default-directory dir))
24990 (expand-file-name txt)))
24991 (unless (derived-mode-p 'org-mode)
24992 (user-error "Cannot restrict to non-Org-mode file"))
24993 (org-agenda-set-restriction-lock 'file)))
24994 (t (user-error "Don't know how to restrict Org-mode's agenda")))
24995 (move-overlay org-speedbar-restriction-lock-overlay
24996 (point-at-bol) (point-at-eol))
24997 (setq current-prefix-arg nil)
24998 (org-agenda-maybe-redo)))
25000 (defvar speedbar-file-key-map)
25001 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25002 (eval-after-load "speedbar"
25003 '(progn
25004 (speedbar-add-supported-extension ".org")
25005 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25006 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25007 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25008 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25009 (add-hook 'speedbar-visiting-tag-hook
25010 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25012 ;;; Fixes and Hacks for problems with other packages
25014 (defun org--flyspell-object-check-p (element)
25015 "Non-nil when Flyspell can check object at point.
25016 ELEMENT is the element at point."
25017 (let ((object (save-excursion
25018 (when (org-looking-at-p "\\>") (backward-char))
25019 (org-element-context element))))
25020 (cl-case (org-element-type object)
25021 ;; Prevent checks in links due to keybinding conflict with
25022 ;; Flyspell.
25023 ((code entity export-snippet inline-babel-call
25024 inline-src-block line-break latex-fragment link macro
25025 statistics-cookie target timestamp verbatim)
25026 nil)
25027 (footnote-reference
25028 ;; Only in inline footnotes, within the definition.
25029 (and (eq (org-element-property :type object) 'inline)
25030 (< (save-excursion
25031 (goto-char (org-element-property :begin object))
25032 (search-forward ":" nil t 2))
25033 (point))))
25034 (otherwise t))))
25036 (defun org-mode-flyspell-verify ()
25037 "Function used for `flyspell-generic-check-word-predicate'."
25038 (if (org-at-heading-p)
25039 ;; At a headline or an inlinetask, check title only. This is
25040 ;; faster than relying on `org-element-at-point'.
25041 (and (save-excursion (beginning-of-line)
25042 (and (let ((case-fold-search t))
25043 (not (looking-at "\\*+ END[ \t]*$")))
25044 (looking-at org-complex-heading-regexp)))
25045 (match-beginning 4)
25046 (>= (point) (match-beginning 4))
25047 (or (not (match-beginning 5))
25048 (< (point) (match-beginning 5))))
25049 (let* ((element (org-element-at-point))
25050 (post-affiliated (org-element-property :post-affiliated element)))
25051 (cond
25052 ;; Ignore checks in all affiliated keywords but captions.
25053 ((< (point) post-affiliated)
25054 (and (save-excursion
25055 (beginning-of-line)
25056 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25057 (> (point) (match-end 0))
25058 (org--flyspell-object-check-p element)))
25059 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25060 ((let ((log (org-log-into-drawer)))
25061 (and log
25062 (let ((drawer (org-element-lineage element '(drawer))))
25063 (and drawer
25064 (eq (compare-strings
25065 log nil nil
25066 (org-element-property :drawer-name drawer) nil nil t)
25067 t)))))
25068 nil)
25070 (cl-case (org-element-type element)
25071 ((comment quote-section) t)
25072 (comment-block
25073 ;; Allow checks between block markers, not on them.
25074 (and (> (line-beginning-position) post-affiliated)
25075 (save-excursion
25076 (end-of-line)
25077 (skip-chars-forward " \r\t\n")
25078 (< (point) (org-element-property :end element)))))
25079 ;; Arbitrary list of keywords where checks are meaningful.
25080 ;; Make sure point is on the value part of the element.
25081 (keyword
25082 (and (member (org-element-property :key element)
25083 '("DESCRIPTION" "TITLE"))
25084 (save-excursion
25085 (search-backward ":" (line-beginning-position) t))))
25086 ;; Check is globally allowed in paragraphs verse blocks and
25087 ;; table rows (after affiliated keywords) but some objects
25088 ;; must not be affected.
25089 ((paragraph table-row verse-block)
25090 (let ((cbeg (org-element-property :contents-begin element))
25091 (cend (org-element-property :contents-end element)))
25092 (and cbeg (>= (point) cbeg) (< (point) cend)
25093 (org--flyspell-object-check-p element))))))))))
25094 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25096 (defun org-remove-flyspell-overlays-in (beg end)
25097 "Remove flyspell overlays in region."
25098 (and (org-bound-and-true-p flyspell-mode)
25099 (fboundp 'flyspell-delete-region-overlays)
25100 (flyspell-delete-region-overlays beg end)))
25102 (defvar flyspell-delayed-commands)
25103 (eval-after-load "flyspell"
25104 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25106 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25107 (eval-after-load "bookmark"
25108 '(if (boundp 'bookmark-after-jump-hook)
25109 ;; We can use the hook
25110 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25111 ;; Hook not available, use advice
25112 (defadvice bookmark-jump (after org-make-visible activate)
25113 "Make the position visible."
25114 (org-bookmark-jump-unhide))))
25116 ;; Make sure saveplace shows the location if it was hidden
25117 (eval-after-load "saveplace"
25118 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25119 "Make the position visible."
25120 (org-bookmark-jump-unhide)))
25122 ;; Make sure ecb shows the location if it was hidden
25123 (eval-after-load "ecb"
25124 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25125 "Make hierarchy visible when jumping into location from ECB tree buffer."
25126 (when (derived-mode-p 'org-mode)
25127 (org-show-context))))
25129 (defun org-bookmark-jump-unhide ()
25130 "Unhide the current position, to show the bookmark location."
25131 (and (derived-mode-p 'org-mode)
25132 (or (outline-invisible-p)
25133 (save-excursion (goto-char (max (point-min) (1- (point))))
25134 (outline-invisible-p)))
25135 (org-show-context 'bookmark-jump)))
25137 (defun org-mark-jump-unhide ()
25138 "Make the point visible with `org-show-context' after jumping to the mark."
25139 (when (and (derived-mode-p 'org-mode)
25140 (outline-invisible-p))
25141 (org-show-context 'mark-goto)))
25143 (eval-after-load "simple"
25144 '(defadvice pop-to-mark-command (after org-make-visible activate)
25145 "Make the point visible with `org-show-context'."
25146 (org-mark-jump-unhide)))
25148 (eval-after-load "simple"
25149 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25150 "Make the point visible with `org-show-context'."
25151 (org-mark-jump-unhide)))
25153 (eval-after-load "simple"
25154 '(defadvice pop-global-mark (after org-make-visible activate)
25155 "Make the point visible with `org-show-context'."
25156 (org-mark-jump-unhide)))
25158 ;; Make session.el ignore our circular variable
25159 (defvar session-globals-exclude)
25160 (eval-after-load "session"
25161 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25163 ;;;; Finish up
25165 (provide 'org)
25167 (run-hooks 'org-load-hook)
25169 ;;; org.el ends here