Merge branch 'maint'
[org-mode.git] / lisp / org.el
blob29224f25035869e2b5ed08e837525057ae7821ae
1 ;;; org.el --- Outline-based notes management and organizer -*- lexical-binding: t; -*-
3 ;; Carstens outline-mode for keeping track of everything.
4 ;; Copyright (C) 2004-2016 Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Maintainer: Carsten Dominik <carsten at orgmode dot org>
8 ;; Keywords: outlines, hypermedia, calendar, wp
9 ;; Homepage: http://orgmode.org
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar-local org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
69 ;;;; Require other packages
71 (require 'cl-lib)
73 (eval-when-compile (require 'gnus-sum))
75 (require 'calendar)
76 (require 'find-func)
77 (require 'format-spec)
79 (or (equal this-command 'eval-buffer)
80 (condition-case nil
81 (load (concat (file-name-directory load-file-name)
82 "org-loaddefs.el")
83 nil t t t)
84 (error
85 (message "WARNING: No org-loaddefs.el file could be found from where org.el is loaded.")
86 (sit-for 3)
87 (message "You need to run \"make\" or \"make autoloads\" from Org lisp directory")
88 (sit-for 3))))
90 (require 'org-macs)
91 (require 'org-compat)
93 ;; `org-outline-regexp' ought to be a defconst but is let-bound in
94 ;; some places -- e.g. see the macro `org-with-limited-levels'.
96 ;; In Org buffers, the value of `outline-regexp' is that of
97 ;; `org-outline-regexp'. The only function still directly relying on
98 ;; `outline-regexp' is `org-overview' so that `org-cycle' can do its
99 ;; job when `orgstruct-mode' is active.
100 (defvar org-outline-regexp "\\*+ "
101 "Regexp to match Org headlines.")
103 (defvar org-outline-regexp-bol "^\\*+ "
104 "Regexp to match Org headlines.
105 This is similar to `org-outline-regexp' but additionally makes
106 sure that we are at the beginning of the line.")
108 (defvar org-heading-regexp "^\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
109 "Matches a headline, putting stars and text into groups.
110 Stars are put in group 1 and the trimmed body in group 2.")
112 (declare-function calendar-check-holidays "holidays" (&optional date))
113 (declare-function cdlatex-environment "ext:cdlatex" (environment item))
114 (declare-function org-add-archive-files "org-archive" (files))
115 (declare-function org-agenda-entry-get-agenda-timestamp "org-agenda" (pom))
116 (declare-function org-agenda-list "org-agenda" (&optional arg start-day span))
117 (declare-function org-agenda-redo "org-agenda" (&optional all))
118 (declare-function org-babel-do-in-edit-buffer "ob-core" (&rest body))
119 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
120 (declare-function org-beamer-mode "ox-beamer" ())
121 (declare-function org-clock-get-last-clock-out-time "org-clock" ())
122 (declare-function org-clock-out "org-clock" (&optional switch-to-state fail-quietly at-time))
123 (declare-function org-clock-remove-overlays "org-clock" (&optional beg end noremove))
124 (declare-function org-clock-sum "org-clock" (&optional tstart tend headline-filter propname))
125 (declare-function org-clock-sum-current-item "org-clock" (&optional tstart))
126 (declare-function org-clock-timestamps-down "org-clock" (&optional n))
127 (declare-function org-clock-timestamps-up "org-clock" (&optional n))
128 (declare-function org-clock-update-time-maybe "org-clock" ())
129 (declare-function org-clocktable-shift "org-clock" (dir n))
130 (declare-function org-element-at-point "org-element" ())
131 (declare-function org-element-cache-refresh "org-element" (pos))
132 (declare-function org-element-cache-reset "org-element" (&optional all))
133 (declare-function org-element-contents "org-element" (element))
134 (declare-function org-element-context "org-element" (&optional element))
135 (declare-function org-element-copy "org-element" (datum))
136 (declare-function org-element-interpret-data "org-element" (data &optional parent))
137 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
138 (declare-function org-element-nested-p "org-element" (elem-a elem-b))
139 (declare-function org-element-parse-buffer "org-element" (&optional granularity visible-only))
140 (declare-function org-element-property "org-element" (property element))
141 (declare-function org-element-put-property "org-element" (element property value))
142 (declare-function org-element-swap-A-B "org-element" (elem-a elem-b))
143 (declare-function org-element-type "org-element" (element))
144 (declare-function org-element-update-syntax "org-element" ())
145 (declare-function org-id-find-id-file "org-id" (id))
146 (declare-function org-id-get-create "org-id" (&optional force))
147 (declare-function org-inlinetask-at-task-p "org-inlinetask" ())
148 (declare-function org-inlinetask-outline-regexp "org-inlinetask" ())
149 (declare-function org-inlinetask-toggle-visibility "org-inlinetask" ())
150 (declare-function org-plot/gnuplot "org-plot" (&optional params))
151 (declare-function org-pop-to-buffer-same-window "org-compat" (&optional buffer-or-name norecord label))
152 (declare-function org-table-align "org-table" ())
153 (declare-function org-table-begin "org-table" (&optional table-type))
154 (declare-function org-table-beginning-of-field "org-table" (&optional n))
155 (declare-function org-table-blank-field "org-table" ())
156 (declare-function org-table-calc-current-TBLFM "org-table" (&optional arg))
157 (declare-function org-table-edit-field "org-table" (arg))
158 (declare-function org-table-end "org-table" (&optional table-type))
159 (declare-function org-table-end-of-field "org-table" (&optional n))
160 (declare-function org-table-insert-row "org-table" (&optional arg))
161 (declare-function org-table-justify-field-maybe "org-table" (&optional new))
162 (declare-function org-table-maybe-eval-formula "org-table" ())
163 (declare-function org-table-maybe-recalculate-line "org-table" ())
164 (declare-function org-table-next-row "org-table" ())
165 (declare-function org-table-paste-rectangle "org-table" ())
166 (declare-function org-table-wrap-region "org-table" (arg))
167 (declare-function org-tags-view "org-agenda" (&optional todo-only match))
168 (declare-function orgtbl-ascii-plot "org-table" (&optional ask))
169 (declare-function orgtbl-mode "org-table" (&optional arg))
171 (defsubst org-uniquify (list)
172 "Non-destructively remove duplicate elements from LIST."
173 (let ((res (copy-sequence list))) (delete-dups res)))
175 (defsubst org-get-at-bol (property)
176 "Get text property PROPERTY at the beginning of line."
177 (get-text-property (point-at-bol) property))
179 (defsubst org-trim (s)
180 "Remove whitespace at the beginning and the end of string S."
181 (replace-regexp-in-string
182 "\\`[ \t\n\r]+" ""
183 (replace-regexp-in-string "[ \t\n\r]+\\'" "" s)))
185 ;; load languages based on value of `org-babel-load-languages'
186 (defvar org-babel-load-languages)
188 ;;;###autoload
189 (defun org-babel-do-load-languages (sym value)
190 "Load the languages defined in `org-babel-load-languages'."
191 (set-default sym value)
192 (dolist (pair org-babel-load-languages)
193 (let ((active (cdr pair)) (lang (symbol-name (car pair))))
194 (if active
195 (require (intern (concat "ob-" lang)))
196 (funcall 'fmakunbound
197 (intern (concat "org-babel-execute:" lang)))
198 (funcall 'fmakunbound
199 (intern (concat "org-babel-expand-body:" lang)))))))
201 (declare-function org-babel-tangle-file "ob-tangle" (file &optional target-file lang))
202 ;;;###autoload
203 (defun org-babel-load-file (file &optional compile)
204 "Load Emacs Lisp source code blocks in the Org-mode FILE.
205 This function exports the source code using `org-babel-tangle'
206 and then loads the resulting file using `load-file'. With prefix
207 arg (noninteractively: 2nd arg) COMPILE the tangled Emacs Lisp
208 file to byte-code before it is loaded."
209 (interactive "fFile to load: \nP")
210 (let* ((age (lambda (file)
211 (float-time
212 (time-subtract (current-time)
213 (nth 5 (or (file-attributes (file-truename file))
214 (file-attributes file)))))))
215 (base-name (file-name-sans-extension file))
216 (exported-file (concat base-name ".el")))
217 ;; tangle if the org-mode file is newer than the elisp file
218 (unless (and (file-exists-p exported-file)
219 (> (funcall age file) (funcall age exported-file)))
220 ;; Tangle-file traversal returns reversed list of tangled files
221 ;; and we want to evaluate the first target.
222 (setq exported-file
223 (car (last (org-babel-tangle-file file exported-file "emacs-lisp")))))
224 (message "%s %s"
225 (if compile
226 (progn (byte-compile-file exported-file 'load)
227 "Compiled and loaded")
228 (progn (load-file exported-file) "Loaded"))
229 exported-file)))
231 (defcustom org-babel-load-languages '((emacs-lisp . t))
232 "Languages which can be evaluated in Org-mode buffers.
233 This list can be used to load support for any of the languages
234 below, note that each language will depend on a different set of
235 system executables and/or Emacs modes. When a language is
236 \"loaded\", then code blocks in that language can be evaluated
237 with `org-babel-execute-src-block' bound by default to C-c
238 C-c (note the `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can
239 be set to remove code block evaluation from the C-c C-c
240 keybinding. By default only Emacs Lisp (which has no
241 requirements) is loaded."
242 :group 'org-babel
243 :set 'org-babel-do-load-languages
244 :version "24.1"
245 :type '(alist :tag "Babel Languages"
246 :key-type
247 (choice
248 (const :tag "Awk" awk)
249 (const :tag "C" C)
250 (const :tag "R" R)
251 (const :tag "Asymptote" asymptote)
252 (const :tag "Calc" calc)
253 (const :tag "Clojure" clojure)
254 (const :tag "CSS" css)
255 (const :tag "Ditaa" ditaa)
256 (const :tag "Dot" dot)
257 (const :tag "Emacs Lisp" emacs-lisp)
258 (const :tag "Forth" forth)
259 (const :tag "Fortran" fortran)
260 (const :tag "Gnuplot" gnuplot)
261 (const :tag "Haskell" haskell)
262 (const :tag "IO" io)
263 (const :tag "J" J)
264 (const :tag "Java" java)
265 (const :tag "Javascript" js)
266 (const :tag "LaTeX" latex)
267 (const :tag "Ledger" ledger)
268 (const :tag "Lilypond" lilypond)
269 (const :tag "Lisp" lisp)
270 (const :tag "Makefile" makefile)
271 (const :tag "Maxima" maxima)
272 (const :tag "Matlab" matlab)
273 (const :tag "Mscgen" mscgen)
274 (const :tag "Ocaml" ocaml)
275 (const :tag "Octave" octave)
276 (const :tag "Org" org)
277 (const :tag "Perl" perl)
278 (const :tag "Pico Lisp" picolisp)
279 (const :tag "PlantUML" plantuml)
280 (const :tag "Python" python)
281 (const :tag "Ruby" ruby)
282 (const :tag "Sass" sass)
283 (const :tag "Scala" scala)
284 (const :tag "Scheme" scheme)
285 (const :tag "Screen" screen)
286 (const :tag "Shell Script" shell)
287 (const :tag "Shen" shen)
288 (const :tag "Sql" sql)
289 (const :tag "Sqlite" sqlite)
290 (const :tag "Stan" stan)
291 (const :tag "ebnf2ps" ebnf2ps))
292 :value-type (boolean :tag "Activate" :value t)))
294 ;;;; Customization variables
295 (defcustom org-clone-delete-id nil
296 "Remove ID property of clones of a subtree.
297 When non-nil, clones of a subtree don't inherit the ID property.
298 Otherwise they inherit the ID property with a new unique
299 identifier."
300 :type 'boolean
301 :version "24.1"
302 :group 'org-id)
304 ;;; Version
305 (org-check-version)
307 ;;;###autoload
308 (defun org-version (&optional here full message)
309 "Show the org-mode version.
310 Interactively, or when MESSAGE is non-nil, show it in echo area.
311 With prefix argument, or when HERE is non-nil, insert it at point.
312 In non-interactive uses, a reduced version string is output unless
313 FULL is given."
314 (interactive (list current-prefix-arg t (not current-prefix-arg)))
315 (let ((org-dir (ignore-errors (org-find-library-dir "org")))
316 (save-load-suffixes (when (boundp 'load-suffixes) load-suffixes))
317 (load-suffixes (list ".el"))
318 (org-install-dir
319 (ignore-errors (org-find-library-dir "org-loaddefs"))))
320 (unless (and (fboundp 'org-release) (fboundp 'org-git-version))
321 (org-load-noerror-mustsuffix (concat org-dir "org-version")))
322 (let* ((load-suffixes save-load-suffixes)
323 (release (org-release))
324 (git-version (org-git-version))
325 (version (format "Org-mode version %s (%s @ %s)"
326 release
327 git-version
328 (if org-install-dir
329 (if (string= org-dir org-install-dir)
330 org-install-dir
331 (concat "mixed installation! "
332 org-install-dir
333 " and "
334 org-dir))
335 "org-loaddefs.el can not be found!")))
336 (version1 (if full version release)))
337 (when here (insert version1))
338 (when message (message "%s" version1))
339 version1)))
341 (defconst org-version (org-version))
344 ;;; Syntax Constants
346 ;;;; Block
348 (defconst org-block-regexp
349 "^[ \t]*#\\+begin_?\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_?\\1[ \t]*$"
350 "Regular expression for hiding blocks.")
352 (defconst org-dblock-start-re
353 "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
354 "Matches the start line of a dynamic block, with parameters.")
356 (defconst org-dblock-end-re "^[ \t]*#\\+\\(?:END\\|end\\)\\([: \t\r\n]\\|$\\)"
357 "Matches the end of a dynamic block.")
359 ;;;; Clock and Planning
361 (defconst org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item.")
364 (defvar org-closed-string "CLOSED:"
365 "String used as the prefix for timestamps logging closing a TODO entry.")
367 (defvar org-deadline-string "DEADLINE:"
368 "String to mark deadline entries.
369 A deadline is this string, followed by a time stamp. Should be a word,
370 terminated by a colon. You can insert a schedule keyword and
371 a timestamp with \\[org-deadline].")
373 (defvar org-scheduled-string "SCHEDULED:"
374 "String to mark scheduled TODO entries.
375 A schedule is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-schedule].")
379 (defconst org-ds-keyword-length
380 (+ 2
381 (apply #'max
382 (mapcar #'length
383 (list org-deadline-string org-scheduled-string
384 org-clock-string org-closed-string))))
385 "Maximum length of the DEADLINE and SCHEDULED keywords.")
387 (defconst org-planning-line-re
388 (concat "^[ \t]*"
389 (regexp-opt
390 (list org-closed-string org-deadline-string org-scheduled-string)
392 "Matches a line with planning info.
393 Matched keyword is in group 1.")
395 (defconst org-clock-line-re
396 (concat "^[ \t]*" org-clock-string)
397 "Matches a line with clock info.")
399 (defconst org-deadline-regexp (concat "\\<" org-deadline-string)
400 "Matches the DEADLINE keyword.")
402 (defconst org-deadline-time-regexp
403 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
404 "Matches the DEADLINE keyword together with a time stamp.")
406 (defconst org-deadline-time-hour-regexp
407 (concat "\\<" org-deadline-string
408 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
409 "Matches the DEADLINE keyword together with a time-and-hour stamp.")
411 (defconst org-deadline-line-regexp
412 (concat "\\<\\(" org-deadline-string "\\).*")
413 "Matches the DEADLINE keyword and the rest of the line.")
415 (defconst org-scheduled-regexp (concat "\\<" org-scheduled-string)
416 "Matches the SCHEDULED keyword.")
418 (defconst org-scheduled-time-regexp
419 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
420 "Matches the SCHEDULED keyword together with a time stamp.")
422 (defconst org-scheduled-time-hour-regexp
423 (concat "\\<" org-scheduled-string
424 " *<\\([^>]+[0-9]\\{1,2\\}:[0-9]\\{2\\}[0-9-+:hdwmy \t.]*\\)>")
425 "Matches the SCHEDULED keyword together with a time-and-hour stamp.")
427 (defconst org-closed-time-regexp
428 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
429 "Matches the CLOSED keyword together with a time stamp.")
431 (defconst org-keyword-time-regexp
432 (concat "\\<"
433 (regexp-opt
434 (list org-scheduled-string org-deadline-string org-closed-string
435 org-clock-string)
437 " *[[<]\\([^]>]+\\)[]>]")
438 "Matches any of the 4 keywords, together with the time stamp.")
440 (defconst org-keyword-time-not-clock-regexp
441 (concat
442 "\\<"
443 (regexp-opt
444 (list org-scheduled-string org-deadline-string org-closed-string) t)
445 " *[[<]\\([^]>]+\\)[]>]")
446 "Matches any of the 3 keywords, together with the time stamp.")
448 (defconst org-maybe-keyword-time-regexp
449 (concat "\\(\\<"
450 (regexp-opt
451 (list org-scheduled-string org-deadline-string org-closed-string
452 org-clock-string)
454 "\\)?"
455 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?[]>]"
456 "\\|"
457 "<%%([^\r\n>]*>\\)")
458 "Matches a timestamp, possibly preceded by a keyword.")
460 (defconst org-all-time-keywords
461 (mapcar (lambda (w) (substring w 0 -1))
462 (list org-scheduled-string org-deadline-string
463 org-clock-string org-closed-string))
464 "List of time keywords.")
466 ;;;; Drawer
468 (defconst org-drawer-regexp "^[ \t]*:\\(\\(?:\\w\\|[-_]\\)+\\):[ \t]*$"
469 "Matches first or last line of a hidden block.
470 Group 1 contains drawer's name or \"END\".")
472 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
473 "Regular expression matching the first line of a property drawer.")
475 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
476 "Regular expression matching the last line of a property drawer.")
478 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
479 "Regular expression matching the first line of a clock drawer.")
481 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
482 "Regular expression matching the last line of a clock drawer.")
484 (defconst org-property-drawer-re
485 (concat "^[ \t]*:PROPERTIES:[ \t]*\n"
486 "\\(?:[ \t]*:\\S-+:\\(?: .*\\)?[ \t]*\n\\)*?"
487 "[ \t]*:END:[ \t]*$")
488 "Matches an entire property drawer.")
490 (defconst org-clock-drawer-re
491 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*?\\("
492 org-clock-drawer-end-re "\\)\n?")
493 "Matches an entire clock drawer.")
495 ;;;; Headline
497 (defconst org-heading-keyword-regexp-format
498 "^\\(\\*+\\)\\(?: +%s\\)\\(?: +\\(.*?\\)\\)?[ \t]*$"
499 "Printf format for a regexp matching a headline with some keyword.
500 This regexp will match the headline of any node which has the
501 exact keyword that is put into the format. The keyword isn't in
502 any group by default, but the stars and the body are.")
504 (defconst org-heading-keyword-maybe-regexp-format
505 "^\\(\\*+\\)\\(?: +%s\\)?\\(?: +\\(.*?\\)\\)?[ \t]*$"
506 "Printf format for a regexp matching a headline, possibly with some keyword.
507 This regexp can match any headline with the specified keyword, or
508 without a keyword. The keyword isn't in any group by default,
509 but the stars and the body are.")
511 (defconst org-archive-tag "ARCHIVE"
512 "The tag that marks a subtree as archived.
513 An archived subtree does not open during visibility cycling, and does
514 not contribute to the agenda listings.")
516 (defconst org-comment-string "COMMENT"
517 "Entries starting with this keyword will never be exported.
518 An entry can be toggled between COMMENT and normal with
519 \\[org-toggle-comment].")
522 ;;;; LaTeX Environments and Fragments
524 (defconst org-latex-regexps
525 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
526 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
527 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
528 ("$1" "\\([^$]\\|^\\)\\(\\$[^ \r\n,;.$]\\$\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
529 ("$" "\\([^$]\\|^\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\(\\s.\\|\\s-\\|\\s(\\|\\s)\\|\\s\"\\|\000\\|$\\)" 2 nil)
530 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
531 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
532 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
533 "Regular expressions for matching embedded LaTeX.")
535 ;;;; Node Property
537 (defconst org-effort-property "Effort"
538 "The property that is being used to keep track of effort estimates.
539 Effort estimates given in this property need to have the format H:MM.")
541 ;;;; Table
543 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
544 "Detect an org-type or table-type table.")
546 (defconst org-table-line-regexp "^[ \t]*|"
547 "Detect an org-type table line.")
549 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
550 "Detect an org-type table line.")
552 (defconst org-table-hline-regexp "^[ \t]*|-"
553 "Detect an org-type table hline.")
555 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
556 "Detect a table-type table hline.")
558 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
559 "Detect the first line outside a table when searching from within it.
560 This works for both table types.")
562 (defconst org-TBLFM-regexp "^[ \t]*#\\+TBLFM: "
563 "Detect a #+TBLFM line.")
565 ;;;; Timestamp
567 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
568 "Regular expression for fast time stamp matching.")
570 (defconst org-ts-regexp-inactive
571 "\\[\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)\\]"
572 "Regular expression for fast inactive time stamp matching.")
574 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^]\r\n>]*?\\)[]>]"
575 "Regular expression for fast time stamp matching.")
577 (defconst org-ts-regexp0
578 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\( +[^]+0-9>\r\n -]+\\)?\\( +\\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
579 "Regular expression matching time strings for analysis.
580 This one does not require the space after the date, so it can be used
581 on a string that terminates immediately after the date.")
583 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]+0-9>\r\n -]*\\)\\( \\([0-9]\\{1,2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
584 "Regular expression matching time strings for analysis.")
586 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
587 "Regular expression matching time stamps, with groups.")
589 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
590 "Regular expression matching time stamps (also [..]), with groups.")
592 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
593 "Regular expression matching a time stamp range.")
595 (defconst org-tr-regexp-both
596 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
597 "Regular expression matching a time stamp range.")
599 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
600 org-ts-regexp "\\)?")
601 "Regular expression matching a time stamp or time stamp range.")
603 (defconst org-tsr-regexp-both
604 (concat org-ts-regexp-both "\\(--?-?"
605 org-ts-regexp-both "\\)?")
606 "Regular expression matching a time stamp or time stamp range.
607 The time stamps may be either active or inactive.")
609 (defconst org-repeat-re
610 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)"
611 "Regular expression for specifying repeated events.
612 After a match, group 1 contains the repeat expression.")
614 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
615 "Formats for `format-time-string' which are used for time stamps.")
618 ;;; The custom variables
620 (defgroup org nil
621 "Outline-based notes management and organizer."
622 :tag "Org"
623 :group 'outlines
624 :group 'calendar)
626 (defcustom org-mode-hook nil
627 "Mode hook for Org-mode, run after the mode was turned on."
628 :group 'org
629 :type 'hook)
631 (defcustom org-load-hook nil
632 "Hook that is run after org.el has been loaded."
633 :group 'org
634 :type 'hook)
636 (defcustom org-log-buffer-setup-hook nil
637 "Hook that is run after an Org log buffer is created."
638 :group 'org
639 :version "24.1"
640 :type 'hook)
642 (defvar org-modules) ; defined below
643 (defvar org-modules-loaded nil
644 "Have the modules been loaded already?")
646 (defun org-load-modules-maybe (&optional force)
647 "Load all extensions listed in `org-modules'."
648 (when (or force (not org-modules-loaded))
649 (dolist (ext org-modules)
650 (condition-case nil (require ext)
651 (error (message "Problems while trying to load feature `%s'" ext))))
652 (setq org-modules-loaded t)))
654 (defun org-set-modules (var value)
655 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
656 (set var value)
657 (when (featurep 'org)
658 (org-load-modules-maybe 'force)
659 (org-element-cache-reset 'all)))
661 (defcustom org-modules '(org-w3m org-bbdb org-bibtex org-docview org-gnus org-info org-irc org-mhe org-rmail)
662 "Modules that should always be loaded together with org.el.
664 If a description starts with <C>, the file is not part of Emacs
665 and loading it will require that you have downloaded and properly
666 installed the Org mode distribution.
668 You can also use this system to load external packages (i.e. neither Org
669 core modules, nor modules from the CONTRIB directory). Just add symbols
670 to the end of the list. If the package is called org-xyz.el, then you need
671 to add the symbol `xyz', and the package must have a call to:
673 (provide \\='org-xyz)
675 For export specific modules, see also `org-export-backends'."
676 :group 'org
677 :set 'org-set-modules
678 :version "24.4"
679 :package-version '(Org . "8.0")
680 :type
681 '(set :greedy t
682 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
683 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
684 (const :tag " crypt: Encryption of subtrees" org-crypt)
685 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
686 (const :tag " docview: Links to doc-view buffers" org-docview)
687 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
688 (const :tag " habit: Track your consistency with habits" org-habit)
689 (const :tag " id: Global IDs for identifying entries" org-id)
690 (const :tag " info: Links to Info nodes" org-info)
691 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
692 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
693 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
694 (const :tag " mouse: Additional mouse support" org-mouse)
695 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
696 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
697 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
699 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
700 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
701 (const :tag "C bullets: Add overlays to headlines stars" org-bullets)
702 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
703 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
704 (const :tag "C collector: Collect properties into tables" org-collector)
705 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
706 (const :tag "C drill: Flashcards and spaced repetition for Org-mode" org-drill)
707 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
708 (const :tag "C eshell Support for links to working directories in eshell" org-eshell)
709 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
710 (const :tag "C eval: Include command output as text" org-eval)
711 (const :tag "C eww: Store link to url of eww" org-eww)
712 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
713 (const :tag "C favtable: Lookup table of favorite references and links" org-favtable)
714 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
715 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
716 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
717 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
718 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
719 (const :tag "C mac-link: Grab links and url from various mac Applications" org-mac-link)
720 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
721 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
722 (const :tag "C mew: Links to Mew folders/messages" org-mew)
723 (const :tag "C mtags: Support for muse-like tags" org-mtags)
724 (const :tag "C notmuch: Provide org links to notmuch searches or messages" org-notmuch)
725 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
726 (const :tag "C registry: A registry for Org-mode links" org-registry)
727 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
728 (const :tag "C secretary: Team management with org-mode" org-secretary)
729 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
730 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
731 (const :tag "C track: Keep up with Org-mode development" org-track)
732 (const :tag "C velocity Something like Notational Velocity for Org" org-velocity)
733 (const :tag "C vm: Links to VM folders/messages" org-vm)
734 (const :tag "C wikinodes: CamelCase wiki-like links" org-wikinodes)
735 (const :tag "C wl: Links to Wanderlust folders/messages" org-wl)
736 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
738 (defvar org-export-registered-backends) ; From ox.el.
739 (declare-function org-export-derived-backend-p "ox" (backend &rest backends))
740 (declare-function org-export-backend-name "ox" (backend))
741 (defcustom org-export-backends '(ascii html icalendar latex odt)
742 "List of export back-ends that should be always available.
744 If a description starts with <C>, the file is not part of Emacs
745 and loading it will require that you have downloaded and properly
746 installed the Org mode distribution.
748 Unlike to `org-modules', libraries in this list will not be
749 loaded along with Org, but only once the export framework is
750 needed.
752 This variable needs to be set before org.el is loaded. If you
753 need to make a change while Emacs is running, use the customize
754 interface or run the following code, where VAL stands for the new
755 value of the variable, after updating it:
757 (progn
758 (setq org-export-registered-backends
759 (cl-remove-if-not
760 (lambda (backend)
761 (let ((name (org-export-backend-name backend)))
762 (or (memq name val)
763 (catch \\='parentp
764 (dolist (b val)
765 (and (org-export-derived-backend-p b name)
766 (throw \\='parentp t)))))))
767 org-export-registered-backends))
768 (let ((new-list (mapcar #\\='org-export-backend-name
769 org-export-registered-backends)))
770 (dolist (backend val)
771 (cond
772 ((not (load (format \"ox-%s\" backend) t t))
773 (message \"Problems while trying to load export back-end \\=`%s\\='\"
774 backend))
775 ((not (memq backend new-list)) (push backend new-list))))
776 (set-default \\='org-export-backends new-list)))
778 Adding a back-end to this list will also pull the back-end it
779 depends on, if any."
780 :group 'org
781 :group 'org-export
782 :version "25.1"
783 :package-version '(Org . "9.0")
784 :initialize 'custom-initialize-set
785 :set (lambda (var val)
786 (if (not (featurep 'ox)) (set-default var val)
787 ;; Any back-end not required anymore (not present in VAL and not
788 ;; a parent of any back-end in the new value) is removed from the
789 ;; list of registered back-ends.
790 (setq org-export-registered-backends
791 (cl-remove-if-not
792 (lambda (backend)
793 (let ((name (org-export-backend-name backend)))
794 (or (memq name val)
795 (catch 'parentp
796 (dolist (b val)
797 (and (org-export-derived-backend-p b name)
798 (throw 'parentp t)))))))
799 org-export-registered-backends))
800 ;; Now build NEW-LIST of both new back-ends and required
801 ;; parents.
802 (let ((new-list (mapcar #'org-export-backend-name
803 org-export-registered-backends)))
804 (dolist (backend val)
805 (cond
806 ((not (load (format "ox-%s" backend) t t))
807 (message "Problems while trying to load export back-end `%s'"
808 backend))
809 ((not (memq backend new-list)) (push backend new-list))))
810 ;; Set VAR to that list with fixed dependencies.
811 (set-default var new-list))))
812 :type '(set :greedy t
813 (const :tag " ascii Export buffer to ASCII format" ascii)
814 (const :tag " beamer Export buffer to Beamer presentation" beamer)
815 (const :tag " html Export buffer to HTML format" html)
816 (const :tag " icalendar Export buffer to iCalendar format" icalendar)
817 (const :tag " latex Export buffer to LaTeX format" latex)
818 (const :tag " man Export buffer to MAN format" man)
819 (const :tag " md Export buffer to Markdown format" md)
820 (const :tag " odt Export buffer to ODT format" odt)
821 (const :tag " org Export buffer to Org format" org)
822 (const :tag " texinfo Export buffer to Texinfo format" texinfo)
823 (const :tag "C confluence Export buffer to Confluence Wiki format" confluence)
824 (const :tag "C deck Export buffer to deck.js presentations" deck)
825 (const :tag "C freemind Export buffer to Freemind mindmap format" freemind)
826 (const :tag "C groff Export buffer to Groff format" groff)
827 (const :tag "C koma-letter Export buffer to KOMA Scrlttrl2 format" koma-letter)
828 (const :tag "C RSS 2.0 Export buffer to RSS 2.0 format" rss)
829 (const :tag "C s5 Export buffer to s5 presentations" s5)
830 (const :tag "C taskjuggler Export buffer to TaskJuggler format" taskjuggler)))
832 (eval-after-load 'ox
833 '(dolist (backend org-export-backends)
834 (condition-case nil (require (intern (format "ox-%s" backend)))
835 (error (message "Problems while trying to load export back-end `%s'"
836 backend)))))
838 (defcustom org-support-shift-select nil
839 "Non-nil means make shift-cursor commands select text when possible.
840 \\<org-mode-map>\
842 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys
843 start selecting a region, or enlarge regions started in this way.
844 In Org-mode, in special contexts, these same keys are used for
845 other purposes, important enough to compete with shift selection.
846 Org tries to balance these needs by supporting `shift-select-mode'
847 outside these special contexts, under control of this variable.
849 The default of this variable is nil, to avoid confusing behavior. Shifted
850 cursor keys will then execute Org commands in the following contexts:
851 - on a headline, changing TODO state (left/right) and priority (up/down)
852 - on a time stamp, changing the time
853 - in a plain list item, changing the bullet type
854 - in a property definition line, switching between allowed values
855 - in the BEGIN line of a clock table (changing the time block).
856 Outside these contexts, the commands will throw an error.
858 When this variable is t and the cursor is not in a special
859 context, Org-mode will support shift-selection for making and
860 enlarging regions. To make this more effective, the bullet
861 cycling will no longer happen anywhere in an item line, but only
862 if the cursor is exactly on the bullet.
864 If you set this variable to the symbol `always', then the keys
865 will not be special in headlines, property lines, and item lines,
866 to make shift selection work there as well. If this is what you
867 want, you can use the following alternative commands:
868 `\\[org-todo]' and `\\[org-priority]' \
869 to change TODO state and priority,
870 `\\[universal-argument] \\[universal-argument] \\[org-todo]' \
871 can be used to switch TODO sets,
872 `\\[org-ctrl-c-minus]' to cycle item bullet types,
873 and properties can be edited by hand or in column view.
875 However, when the cursor is on a timestamp, shift-cursor commands
876 will still edit the time stamp - this is just too good to give up.
878 XEmacs user should have this variable set to nil, because
879 `shift-select-mode' is in Emacs 23 or later only."
880 :group 'org
881 :type '(choice
882 (const :tag "Never" nil)
883 (const :tag "When outside special context" t)
884 (const :tag "Everywhere except timestamps" always)))
886 (defcustom org-loop-over-headlines-in-active-region nil
887 "Shall some commands act upon headlines in the active region?
889 When set to t, some commands will be performed in all headlines
890 within the active region.
892 When set to `start-level', some commands will be performed in all
893 headlines within the active region, provided that these headlines
894 are of the same level than the first one.
896 When set to a string, those commands will be performed on the
897 matching headlines within the active region. Such string must be
898 a tags/property/todo match as it is used in the agenda tags view.
900 The list of commands is: `org-schedule', `org-deadline',
901 `org-todo', `org-archive-subtree', `org-archive-set-tag' and
902 `org-archive-to-archive-sibling'. The archiving commands skip
903 already archived entries."
904 :type '(choice (const :tag "Don't loop" nil)
905 (const :tag "All headlines in active region" t)
906 (const :tag "In active region, headlines at the same level than the first one" start-level)
907 (string :tag "Tags/Property/Todo matcher"))
908 :version "24.1"
909 :group 'org-todo
910 :group 'org-archive)
912 (defgroup org-startup nil
913 "Options concerning startup of Org-mode."
914 :tag "Org Startup"
915 :group 'org)
917 (defcustom org-startup-folded t
918 "Non-nil means entering Org-mode will switch to OVERVIEW.
919 This can also be configured on a per-file basis by adding one of
920 the following lines anywhere in the buffer:
922 #+STARTUP: fold (or `overview', this is equivalent)
923 #+STARTUP: nofold (or `showall', this is equivalent)
924 #+STARTUP: content
925 #+STARTUP: showeverything
927 By default, this option is ignored when Org opens agenda files
928 for the first time. If you want the agenda to honor the startup
929 option, set `org-agenda-inhibit-startup' to nil."
930 :group 'org-startup
931 :type '(choice
932 (const :tag "nofold: show all" nil)
933 (const :tag "fold: overview" t)
934 (const :tag "content: all headlines" content)
935 (const :tag "show everything, even drawers" showeverything)))
937 (defcustom org-startup-truncated t
938 "Non-nil means entering Org-mode will set `truncate-lines'.
939 This is useful since some lines containing links can be very long and
940 uninteresting. Also tables look terrible when wrapped."
941 :group 'org-startup
942 :type 'boolean)
944 (defcustom org-startup-indented nil
945 "Non-nil means turn on `org-indent-mode' on startup.
946 This can also be configured on a per-file basis by adding one of
947 the following lines anywhere in the buffer:
949 #+STARTUP: indent
950 #+STARTUP: noindent"
951 :group 'org-structure
952 :type '(choice
953 (const :tag "Not" nil)
954 (const :tag "Globally (slow on startup in large files)" t)))
956 (defcustom org-use-sub-superscripts t
957 "Non-nil means interpret \"_\" and \"^\" for display.
959 If you want to control how Org exports those characters, see
960 `org-export-with-sub-superscripts'. `org-use-sub-superscripts'
961 used to be an alias for `org-export-with-sub-superscripts' in
962 Org <8.0, it is not anymore.
964 When this option is turned on, you can use TeX-like syntax for
965 sub- and superscripts within the buffer. Several characters after
966 \"_\" or \"^\" will be considered as a single item - so grouping
967 with {} is normally not needed. For example, the following things
968 will be parsed as single sub- or superscripts:
970 10^24 or 10^tau several digits will be considered 1 item.
971 10^-12 or 10^-tau a leading sign with digits or a word
972 x^2-y^3 will be read as x^2 - y^3, because items are
973 terminated by almost any nonword/nondigit char.
974 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
976 Still, ambiguity is possible. So when in doubt, use {} to enclose
977 the sub/superscript. If you set this variable to the symbol `{}',
978 the braces are *required* in order to trigger interpretations as
979 sub/superscript. This can be helpful in documents that need \"_\"
980 frequently in plain text."
981 :group 'org-startup
982 :version "24.4"
983 :package-version '(Org . "8.0")
984 :type '(choice
985 (const :tag "Always interpret" t)
986 (const :tag "Only with braces" {})
987 (const :tag "Never interpret" nil)))
989 (defcustom org-startup-with-beamer-mode nil
990 "Non-nil means turn on `org-beamer-mode' on startup.
991 This can also be configured on a per-file basis by adding one of
992 the following lines anywhere in the buffer:
994 #+STARTUP: beamer"
995 :group 'org-startup
996 :version "24.1"
997 :type 'boolean)
999 (defcustom org-startup-align-all-tables nil
1000 "Non-nil means align all tables when visiting a file.
1001 This is useful when the column width in tables is forced with <N> cookies
1002 in table fields. Such tables will look correct only after the first re-align.
1003 This can also be configured on a per-file basis by adding one of
1004 the following lines anywhere in the buffer:
1005 #+STARTUP: align
1006 #+STARTUP: noalign"
1007 :group 'org-startup
1008 :type 'boolean)
1010 (defcustom org-startup-with-inline-images nil
1011 "Non-nil means show inline images when loading a new Org file.
1012 This can also be configured on a per-file basis by adding one of
1013 the following lines anywhere in the buffer:
1014 #+STARTUP: inlineimages
1015 #+STARTUP: noinlineimages"
1016 :group 'org-startup
1017 :version "24.1"
1018 :type 'boolean)
1020 (defcustom org-startup-with-latex-preview nil
1021 "Non-nil means preview LaTeX fragments when loading a new Org file.
1023 This can also be configured on a per-file basis by adding one of
1024 the following lines anywhere in the buffer:
1025 #+STARTUP: latexpreview
1026 #+STARTUP: nolatexpreview"
1027 :group 'org-startup
1028 :version "24.4"
1029 :package-version '(Org . "8.0")
1030 :type 'boolean)
1032 (defcustom org-insert-mode-line-in-empty-file nil
1033 "Non-nil means insert the first line setting Org-mode in empty files.
1034 When the function `org-mode' is called interactively in an empty file, this
1035 normally means that the file name does not automatically trigger Org-mode.
1036 To ensure that the file will always be in Org-mode in the future, a
1037 line enforcing Org-mode will be inserted into the buffer, if this option
1038 has been set."
1039 :group 'org-startup
1040 :type 'boolean)
1042 (defcustom org-replace-disputed-keys nil
1043 "Non-nil means use alternative key bindings for some keys.
1044 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
1045 These keys are also used by other packages like shift-selection-mode'
1046 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
1047 If you want to use Org-mode together with one of these other modes,
1048 or more generally if you would like to move some Org-mode commands to
1049 other keys, set this variable and configure the keys with the variable
1050 `org-disputed-keys'.
1052 This option is only relevant at load-time of Org-mode, and must be set
1053 *before* org.el is loaded. Changing it requires a restart of Emacs to
1054 become effective."
1055 :group 'org-startup
1056 :type 'boolean)
1058 (defcustom org-use-extra-keys nil
1059 "Non-nil means use extra key sequence definitions for certain commands.
1060 This happens automatically if you run XEmacs or if `window-system'
1061 is nil. This variable lets you do the same manually. You must
1062 set it before loading org.
1064 Example: on Carbon Emacs 22 running graphically, with an external
1065 keyboard on a Powerbook, the default way of setting M-left might
1066 not work for either Alt or ESC. Setting this variable will make
1067 it work for ESC."
1068 :group 'org-startup
1069 :type 'boolean)
1071 (org-defvaralias 'org-CUA-compatible 'org-replace-disputed-keys)
1073 (defcustom org-disputed-keys
1074 '(([(shift up)] . [(meta p)])
1075 ([(shift down)] . [(meta n)])
1076 ([(shift left)] . [(meta -)])
1077 ([(shift right)] . [(meta +)])
1078 ([(control shift right)] . [(meta shift +)])
1079 ([(control shift left)] . [(meta shift -)]))
1080 "Keys for which Org-mode and other modes compete.
1081 This is an alist, cars are the default keys, second element specifies
1082 the alternative to use when `org-replace-disputed-keys' is t.
1084 Keys can be specified in any syntax supported by `define-key'.
1085 The value of this option takes effect only at Org-mode's startup,
1086 therefore you'll have to restart Emacs to apply it after changing."
1087 :group 'org-startup
1088 :type 'alist)
1090 (defun org-key (key)
1091 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
1092 Or return the original if not disputed.
1093 Also apply the translations defined in `org-xemacs-key-equivalents'."
1094 (when org-replace-disputed-keys
1095 (let* ((nkey (key-description key))
1096 (x (org-find-if (lambda (x)
1097 (equal (key-description (car x)) nkey))
1098 org-disputed-keys)))
1099 (setq key (if x (cdr x) key))))
1100 (when (featurep 'xemacs)
1101 (setq key (or (cdr (assoc key org-xemacs-key-equivalents)) key)))
1102 key)
1104 (defun org-find-if (predicate seq)
1105 (catch 'exit
1106 (while seq
1107 (if (funcall predicate (car seq))
1108 (throw 'exit (car seq))
1109 (pop seq)))))
1111 (defun org-defkey (keymap key def)
1112 "Define a key, possibly translated, as returned by `org-key'."
1113 (define-key keymap (org-key key) def))
1115 (defcustom org-ellipsis nil
1116 "The ellipsis to use in the Org-mode outline.
1117 When nil, just use the standard three dots.
1118 When a string, use that string instead.
1119 When a face, use the standard 3 dots, but with the specified face.
1120 The change affects only Org-mode (which will then use its own display table).
1121 Changing this requires executing \\[org-mode] in a buffer to become
1122 effective."
1123 :group 'org-startup
1124 :type '(choice (const :tag "Default" nil)
1125 (face :tag "Face" :value org-warning)
1126 (string :tag "String" :value "...#")))
1128 (defvar org-display-table nil
1129 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
1131 (defgroup org-keywords nil
1132 "Keywords in Org-mode."
1133 :tag "Org Keywords"
1134 :group 'org)
1136 (defcustom org-closed-keep-when-no-todo nil
1137 "Remove CLOSED: time-stamp when switching back to a non-todo state?"
1138 :group 'org-todo
1139 :group 'org-keywords
1140 :version "24.4"
1141 :package-version '(Org . "8.0")
1142 :type 'boolean)
1144 (defgroup org-structure nil
1145 "Options concerning the general structure of Org-mode files."
1146 :tag "Org Structure"
1147 :group 'org)
1149 (defgroup org-reveal-location nil
1150 "Options about how to make context of a location visible."
1151 :tag "Org Reveal Location"
1152 :group 'org-structure)
1154 (defcustom org-show-context-detail '((isearch . lineage)
1155 (bookmark-jump . lineage)
1156 (default . ancestors))
1157 "Alist between context and visibility span when revealing a location.
1159 \\<org-mode-map>Some actions may move point into invisible
1160 locations. As a consequence, Org always expose a neighborhood
1161 around point. How much is shown depends on the initial action,
1162 or context. Valid contexts are
1164 agenda when exposing an entry from the agenda
1165 org-goto when using the command `org-goto' (\\[org-goto])
1166 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1167 tags-tree when constructing a sparse tree based on tags matches
1168 link-search when exposing search matches associated with a link
1169 mark-goto when exposing the jump goal of a mark
1170 bookmark-jump when exposing a bookmark location
1171 isearch when exiting from an incremental search
1172 default default for all contexts not set explicitly
1174 Allowed visibility spans are
1176 minimal show current headline; if point is not on headline,
1177 also show entry
1179 local show current headline, entry and next headline
1181 ancestors show current headline and its direct ancestors; if
1182 point is not on headline, also show entry
1184 lineage show current headline, its direct ancestors and all
1185 their children; if point is not on headline, also show
1186 entry and first child
1188 tree show current headline, its direct ancestors and all
1189 their children; if point is not on headline, also show
1190 entry and all children
1192 canonical show current headline, its direct ancestors along with
1193 their entries and children; if point is not located on
1194 the headline, also show current entry and all children
1196 As special cases, a nil or t value means show all contexts in
1197 `minimal' or `canonical' view, respectively.
1199 Some views can make displayed information very compact, but also
1200 make it harder to edit the location of the match. In such
1201 a case, use the command `org-reveal' (\\[org-reveal]) to show
1202 more context."
1203 :group 'org-reveal-location
1204 :version "25.1"
1205 :package-version '(Org . "8.3")
1206 :type '(choice
1207 (const :tag "Canonical" t)
1208 (const :tag "Minimal" nil)
1209 (repeat :greedy t :tag "Individual contexts"
1210 (cons
1211 (choice :tag "Context"
1212 (const agenda)
1213 (const org-goto)
1214 (const occur-tree)
1215 (const tags-tree)
1216 (const link-search)
1217 (const mark-goto)
1218 (const bookmark-jump)
1219 (const isearch)
1220 (const default))
1221 (choice :tag "Detail level"
1222 (const minimal)
1223 (const local)
1224 (const ancestors)
1225 (const lineage)
1226 (const tree)
1227 (const canonical))))))
1229 (defcustom org-indirect-buffer-display 'other-window
1230 "How should indirect tree buffers be displayed?
1231 This applies to indirect buffers created with the commands
1232 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1233 Valid values are:
1234 current-window Display in the current window
1235 other-window Just display in another window.
1236 dedicated-frame Create one new frame, and re-use it each time.
1237 new-frame Make a new frame each time. Note that in this case
1238 previously-made indirect buffers are kept, and you need to
1239 kill these buffers yourself."
1240 :group 'org-structure
1241 :group 'org-agenda-windows
1242 :type '(choice
1243 (const :tag "In current window" current-window)
1244 (const :tag "In current frame, other window" other-window)
1245 (const :tag "Each time a new frame" new-frame)
1246 (const :tag "One dedicated frame" dedicated-frame)))
1248 (defcustom org-use-speed-commands nil
1249 "Non-nil means activate single letter commands at beginning of a headline.
1250 This may also be a function to test for appropriate locations where speed
1251 commands should be active.
1253 For example, to activate speed commands when the point is on any
1254 star at the beginning of the headline, you can do this:
1256 (setq org-use-speed-commands
1257 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1258 :group 'org-structure
1259 :type '(choice
1260 (const :tag "Never" nil)
1261 (const :tag "At beginning of headline stars" t)
1262 (function)))
1264 (defcustom org-speed-commands-user nil
1265 "Alist of additional speed commands.
1266 This list will be checked before `org-speed-commands-default'
1267 when the variable `org-use-speed-commands' is non-nil
1268 and when the cursor is at the beginning of a headline.
1269 The car if each entry is a string with a single letter, which must
1270 be assigned to `self-insert-command' in the global map.
1271 The cdr is either a command to be called interactively, a function
1272 to be called, or a form to be evaluated.
1273 An entry that is just a list with a single string will be interpreted
1274 as a descriptive headline that will be added when listing the speed
1275 commands in the Help buffer using the `?' speed command."
1276 :group 'org-structure
1277 :type '(repeat :value ("k" . ignore)
1278 (choice :value ("k" . ignore)
1279 (list :tag "Descriptive Headline" (string :tag "Headline"))
1280 (cons :tag "Letter and Command"
1281 (string :tag "Command letter")
1282 (choice
1283 (function)
1284 (sexp))))))
1286 (defcustom org-bookmark-names-plist
1287 '(:last-capture "org-capture-last-stored"
1288 :last-refile "org-refile-last-stored"
1289 :last-capture-marker "org-capture-last-stored-marker")
1290 "Names for bookmarks automatically set by some Org commands.
1291 This can provide strings as names for a number of bookmarks Org sets
1292 automatically. The following keys are currently implemented:
1293 :last-capture
1294 :last-capture-marker
1295 :last-refile
1296 When a key does not show up in the property list, the corresponding bookmark
1297 is not set."
1298 :group 'org-structure
1299 :type 'plist)
1301 (defgroup org-cycle nil
1302 "Options concerning visibility cycling in Org-mode."
1303 :tag "Org Cycle"
1304 :group 'org-structure)
1306 (defcustom org-cycle-skip-children-state-if-no-children t
1307 "Non-nil means skip CHILDREN state in entries that don't have any."
1308 :group 'org-cycle
1309 :type 'boolean)
1311 (defcustom org-cycle-max-level nil
1312 "Maximum level which should still be subject to visibility cycling.
1313 Levels higher than this will, for cycling, be treated as text, not a headline.
1314 When `org-odd-levels-only' is set, a value of N in this variable actually
1315 means 2N-1 stars as the limiting headline.
1316 When nil, cycle all levels.
1317 Note that the limiting level of cycling is also influenced by
1318 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1319 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1320 than its value."
1321 :group 'org-cycle
1322 :type '(choice
1323 (const :tag "No limit" nil)
1324 (integer :tag "Maximum level")))
1326 (defcustom org-hide-block-startup nil
1327 "Non-nil means entering Org-mode will fold all blocks.
1328 This can also be set in on a per-file basis with
1330 #+STARTUP: hideblocks
1331 #+STARTUP: showblocks"
1332 :group 'org-startup
1333 :group 'org-cycle
1334 :type 'boolean)
1336 (defcustom org-cycle-global-at-bob nil
1337 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1338 This makes it possible to do global cycling without having to use S-TAB or
1339 \\[universal-argument] TAB. For this special case to work, the first line
1340 of the buffer must not be a headline -- it may be empty or some other text.
1341 When used in this way, `org-cycle-hook' is disabled temporarily to make
1342 sure the cursor stays at the beginning of the buffer. When this option is
1343 nil, don't do anything special at the beginning of the buffer."
1344 :group 'org-cycle
1345 :type 'boolean)
1347 (defcustom org-cycle-level-after-item/entry-creation t
1348 "Non-nil means cycle entry level or item indentation in new empty entries.
1350 When the cursor is at the end of an empty headline, i.e., with only stars
1351 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1352 and then all possible ancestor states, before returning to the original state.
1353 This makes data entry extremely fast: M-RET to create a new headline,
1354 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1356 When the cursor is at the end of an empty plain list item, one TAB will
1357 make it a subitem, two or more tabs will back up to make this an item
1358 higher up in the item hierarchy."
1359 :group 'org-cycle
1360 :type 'boolean)
1362 (defcustom org-cycle-emulate-tab t
1363 "Where should `org-cycle' emulate TAB.
1364 nil Never
1365 white Only in completely white lines
1366 whitestart Only at the beginning of lines, before the first non-white char
1367 t Everywhere except in headlines
1368 exc-hl-bol Everywhere except at the start of a headline
1369 If TAB is used in a place where it does not emulate TAB, the current subtree
1370 visibility is cycled."
1371 :group 'org-cycle
1372 :type '(choice (const :tag "Never" nil)
1373 (const :tag "Only in completely white lines" white)
1374 (const :tag "Before first char in a line" whitestart)
1375 (const :tag "Everywhere except in headlines" t)
1376 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1378 (defcustom org-cycle-separator-lines 2
1379 "Number of empty lines needed to keep an empty line between collapsed trees.
1380 If you leave an empty line between the end of a subtree and the following
1381 headline, this empty line is hidden when the subtree is folded.
1382 Org-mode will leave (exactly) one empty line visible if the number of
1383 empty lines is equal or larger to the number given in this variable.
1384 So the default 2 means at least 2 empty lines after the end of a subtree
1385 are needed to produce free space between a collapsed subtree and the
1386 following headline.
1388 If the number is negative, and the number of empty lines is at least -N,
1389 all empty lines are shown.
1391 Special case: when 0, never leave empty lines in collapsed view."
1392 :group 'org-cycle
1393 :type 'integer)
1394 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1396 (defcustom org-pre-cycle-hook nil
1397 "Hook that is run before visibility cycling is happening.
1398 The function(s) in this hook must accept a single argument which indicates
1399 the new state that will be set right after running this hook. The
1400 argument is a symbol. Before a global state change, it can have the values
1401 `overview', `content', or `all'. Before a local state change, it can have
1402 the values `folded', `children', or `subtree'."
1403 :group 'org-cycle
1404 :type 'hook)
1406 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1407 org-cycle-hide-drawers
1408 org-cycle-show-empty-lines
1409 org-optimize-window-after-visibility-change)
1410 "Hook that is run after `org-cycle' has changed the buffer visibility.
1411 The function(s) in this hook must accept a single argument which indicates
1412 the new state that was set by the most recent `org-cycle' command. The
1413 argument is a symbol. After a global state change, it can have the values
1414 `overview', `contents', or `all'. After a local state change, it can have
1415 the values `folded', `children', or `subtree'."
1416 :group 'org-cycle
1417 :type 'hook
1418 :version "25.1"
1419 :package-version '(Org . "8.3"))
1421 (defgroup org-edit-structure nil
1422 "Options concerning structure editing in Org-mode."
1423 :tag "Org Edit Structure"
1424 :group 'org-structure)
1426 (defcustom org-odd-levels-only nil
1427 "Non-nil means skip even levels and only use odd levels for the outline.
1428 This has the effect that two stars are being added/taken away in
1429 promotion/demotion commands. It also influences how levels are
1430 handled by the exporters.
1431 Changing it requires restart of `font-lock-mode' to become effective
1432 for fontification also in regions already fontified.
1433 You may also set this on a per-file basis by adding one of the following
1434 lines to the buffer:
1436 #+STARTUP: odd
1437 #+STARTUP: oddeven"
1438 :group 'org-edit-structure
1439 :group 'org-appearance
1440 :type 'boolean)
1442 (defcustom org-adapt-indentation t
1443 "Non-nil means adapt indentation to outline node level.
1445 When this variable is set, Org assumes that you write outlines by
1446 indenting text in each node to align with the headline (after the
1447 stars). The following issues are influenced by this variable:
1449 - The indentation is increased by one space in a demotion
1450 command, and decreased by one in a promotion command. However,
1451 in the latter case, if shifting some line in the entry body
1452 would alter document structure (e.g., insert a new headline),
1453 indentation is not changed at all.
1455 - Property drawers and planning information is inserted indented
1456 when this variable is set. When nil, they will not be indented.
1458 - TAB indents a line relative to current level. The lines below
1459 a headline will be indented when this variable is set.
1461 Note that this is all about true indentation, by adding and
1462 removing space characters. See also `org-indent.el' which does
1463 level-dependent indentation in a virtual way, i.e. at display
1464 time in Emacs."
1465 :group 'org-edit-structure
1466 :type 'boolean)
1468 (defcustom org-special-ctrl-a/e nil
1469 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1471 When t, `C-a' will bring back the cursor to the beginning of the
1472 headline text, i.e. after the stars and after a possible TODO
1473 keyword. In an item, this will be the position after bullet and
1474 check-box, if any. When the cursor is already at that position,
1475 another `C-a' will bring it to the beginning of the line.
1477 `C-e' will jump to the end of the headline, ignoring the presence
1478 of tags in the headline. A second `C-e' will then jump to the
1479 true end of the line, after any tags. This also means that, when
1480 this variable is non-nil, `C-e' also will never jump beyond the
1481 end of the heading of a folded section, i.e. not after the
1482 ellipses.
1484 When set to the symbol `reversed', the first `C-a' or `C-e' works
1485 normally, going to the true line boundary first. Only a directly
1486 following, identical keypress will bring the cursor to the
1487 special positions.
1489 This may also be a cons cell where the behavior for `C-a' and
1490 `C-e' is set separately."
1491 :group 'org-edit-structure
1492 :type '(choice
1493 (const :tag "off" nil)
1494 (const :tag "on: after stars/bullet and before tags first" t)
1495 (const :tag "reversed: true line boundary first" reversed)
1496 (cons :tag "Set C-a and C-e separately"
1497 (choice :tag "Special C-a"
1498 (const :tag "off" nil)
1499 (const :tag "on: after stars/bullet first" t)
1500 (const :tag "reversed: before stars/bullet first" reversed))
1501 (choice :tag "Special C-e"
1502 (const :tag "off" nil)
1503 (const :tag "on: before tags first" t)
1504 (const :tag "reversed: after tags first" reversed)))))
1505 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1507 (defcustom org-special-ctrl-k nil
1508 "Non-nil means `C-k' will behave specially in headlines.
1509 When nil, `C-k' will call the default `kill-line' command.
1510 When t, the following will happen while the cursor is in the headline:
1512 - When the cursor is at the beginning of a headline, kill the entire
1513 line and possible the folded subtree below the line.
1514 - When in the middle of the headline text, kill the headline up to the tags.
1515 - When after the headline text, kill the tags."
1516 :group 'org-edit-structure
1517 :type 'boolean)
1519 (defcustom org-ctrl-k-protect-subtree nil
1520 "Non-nil means, do not delete a hidden subtree with C-k.
1521 When set to the symbol `error', simply throw an error when C-k is
1522 used to kill (part-of) a headline that has hidden text behind it.
1523 Any other non-nil value will result in a query to the user, if it is
1524 OK to kill that hidden subtree. When nil, kill without remorse."
1525 :group 'org-edit-structure
1526 :version "24.1"
1527 :type '(choice
1528 (const :tag "Do not protect hidden subtrees" nil)
1529 (const :tag "Protect hidden subtrees with a security query" t)
1530 (const :tag "Never kill a hidden subtree with C-k" error)))
1532 (defcustom org-special-ctrl-o t
1533 "Non-nil means, make `C-o' insert a row in tables."
1534 :group 'org-edit-structure
1535 :type 'boolean)
1537 (defcustom org-catch-invisible-edits nil
1538 "Check if in invisible region before inserting or deleting a character.
1539 Valid values are:
1541 nil Do not check, so just do invisible edits.
1542 error Throw an error and do nothing.
1543 show Make point visible, and do the requested edit.
1544 show-and-error Make point visible, then throw an error and abort the edit.
1545 smart Make point visible, and do insertion/deletion if it is
1546 adjacent to visible text and the change feels predictable.
1547 Never delete a previously invisible character or add in the
1548 middle or right after an invisible region. Basically, this
1549 allows insertion and backward-delete right before ellipses.
1550 FIXME: maybe in this case we should not even show?"
1551 :group 'org-edit-structure
1552 :version "24.1"
1553 :type '(choice
1554 (const :tag "Do not check" nil)
1555 (const :tag "Throw error when trying to edit" error)
1556 (const :tag "Unhide, but do not do the edit" show-and-error)
1557 (const :tag "Show invisible part and do the edit" show)
1558 (const :tag "Be smart and do the right thing" smart)))
1560 (defcustom org-yank-folded-subtrees t
1561 "Non-nil means when yanking subtrees, fold them.
1562 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1563 it starts with a heading and all other headings in it are either children
1564 or siblings, then fold all the subtrees. However, do this only if no
1565 text after the yank would be swallowed into a folded tree by this action."
1566 :group 'org-edit-structure
1567 :type 'boolean)
1569 (defcustom org-yank-adjusted-subtrees nil
1570 "Non-nil means when yanking subtrees, adjust the level.
1571 With this setting, `org-paste-subtree' is used to insert the subtree, see
1572 this function for details."
1573 :group 'org-edit-structure
1574 :type 'boolean)
1576 (defcustom org-M-RET-may-split-line '((default . t))
1577 "Non-nil means M-RET will split the line at the cursor position.
1578 When nil, it will go to the end of the line before making a
1579 new line.
1580 You may also set this option in a different way for different
1581 contexts. Valid contexts are:
1583 headline when creating a new headline
1584 item when creating a new item
1585 table in a table field
1586 default the value to be used for all contexts not explicitly
1587 customized"
1588 :group 'org-structure
1589 :group 'org-table
1590 :type '(choice
1591 (const :tag "Always" t)
1592 (const :tag "Never" nil)
1593 (repeat :greedy t :tag "Individual contexts"
1594 (cons
1595 (choice :tag "Context"
1596 (const headline)
1597 (const item)
1598 (const table)
1599 (const default))
1600 (boolean)))))
1603 (defcustom org-insert-heading-respect-content nil
1604 "Non-nil means insert new headings after the current subtree.
1605 When nil, the new heading is created directly after the current line.
1606 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1607 this variable on for the duration of the command."
1608 :group 'org-structure
1609 :type 'boolean)
1611 (defcustom org-blank-before-new-entry '((heading . auto)
1612 (plain-list-item . auto))
1613 "Should `org-insert-heading' leave a blank line before new heading/item?
1614 The value is an alist, with `heading' and `plain-list-item' as CAR,
1615 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1616 which case Org will look at the surrounding headings/items and try to
1617 make an intelligent decision whether to insert a blank line or not."
1618 :group 'org-edit-structure
1619 :type '(list
1620 (cons (const heading)
1621 (choice (const :tag "Never" nil)
1622 (const :tag "Always" t)
1623 (const :tag "Auto" auto)))
1624 (cons (const plain-list-item)
1625 (choice (const :tag "Never" nil)
1626 (const :tag "Always" t)
1627 (const :tag "Auto" auto)))))
1629 (defcustom org-insert-heading-hook nil
1630 "Hook being run after inserting a new heading."
1631 :group 'org-edit-structure
1632 :type 'hook)
1634 (defcustom org-enable-fixed-width-editor t
1635 "Non-nil means lines starting with \":\" are treated as fixed-width.
1636 This currently only means they are never auto-wrapped.
1637 When nil, such lines will be treated like ordinary lines."
1638 :group 'org-edit-structure
1639 :type 'boolean)
1641 (defcustom org-goto-auto-isearch t
1642 "Non-nil means typing characters in `org-goto' starts incremental search.
1643 When nil, you can use these keybindings to navigate the buffer:
1645 q Quit the org-goto interface
1646 n Go to the next visible heading
1647 p Go to the previous visible heading
1648 f Go one heading forward on same level
1649 b Go one heading backward on same level
1650 u Go one heading up"
1651 :group 'org-edit-structure
1652 :type 'boolean)
1654 (defgroup org-sparse-trees nil
1655 "Options concerning sparse trees in Org-mode."
1656 :tag "Org Sparse Trees"
1657 :group 'org-structure)
1659 (defcustom org-highlight-sparse-tree-matches t
1660 "Non-nil means highlight all matches that define a sparse tree.
1661 The highlights will automatically disappear the next time the buffer is
1662 changed by an edit command."
1663 :group 'org-sparse-trees
1664 :type 'boolean)
1666 (defcustom org-remove-highlights-with-change t
1667 "Non-nil means any change to the buffer will remove temporary highlights.
1668 \\<org-mode-map>\
1669 Such highlights are created by `org-occur' and `org-clock-display'.
1670 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1671 to get rid of the highlights.
1672 The highlights created by `org-toggle-latex-fragment' always need
1673 `\\[org-toggle-latex-fragment]' to be removed."
1674 :group 'org-sparse-trees
1675 :group 'org-time
1676 :type 'boolean)
1679 (defcustom org-occur-hook '(org-first-headline-recenter)
1680 "Hook that is run after `org-occur' has constructed a sparse tree.
1681 This can be used to recenter the window to show as much of the structure
1682 as possible."
1683 :group 'org-sparse-trees
1684 :type 'hook)
1686 (defgroup org-imenu-and-speedbar nil
1687 "Options concerning imenu and speedbar in Org-mode."
1688 :tag "Org Imenu and Speedbar"
1689 :group 'org-structure)
1691 (defcustom org-imenu-depth 2
1692 "The maximum level for Imenu access to Org-mode headlines.
1693 This also applied for speedbar access."
1694 :group 'org-imenu-and-speedbar
1695 :type 'integer)
1697 (defgroup org-table nil
1698 "Options concerning tables in Org-mode."
1699 :tag "Org Table"
1700 :group 'org)
1702 (defcustom org-enable-table-editor 'optimized
1703 "Non-nil means lines starting with \"|\" are handled by the table editor.
1704 When nil, such lines will be treated like ordinary lines.
1706 When equal to the symbol `optimized', the table editor will be optimized to
1707 do the following:
1708 - Automatic overwrite mode in front of whitespace in table fields.
1709 This makes the structure of the table stay in tact as long as the edited
1710 field does not exceed the column width.
1711 - Minimize the number of realigns. Normally, the table is aligned each time
1712 TAB or RET are pressed to move to another field. With optimization this
1713 happens only if changes to a field might have changed the column width.
1714 Optimization requires replacing the functions `self-insert-command',
1715 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1716 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1717 very good at guessing when a re-align will be necessary, but you can always
1718 force one with \\[org-ctrl-c-ctrl-c].
1720 If you would like to use the optimized version in Org-mode, but the
1721 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1723 This variable can be used to turn on and off the table editor during a session,
1724 but in order to toggle optimization, a restart is required.
1726 See also the variable `org-table-auto-blank-field'."
1727 :group 'org-table
1728 :type '(choice
1729 (const :tag "off" nil)
1730 (const :tag "on" t)
1731 (const :tag "on, optimized" optimized)))
1733 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1734 (version<= emacs-version "24.1"))
1735 "Non-nil means cluster self-insert commands for undo when possible.
1736 If this is set, then, like in the Emacs command loop, 20 consecutive
1737 characters will be undone together.
1738 This is configurable, because there is some impact on typing performance."
1739 :group 'org-table
1740 :type 'boolean)
1742 (defcustom org-table-tab-recognizes-table.el t
1743 "Non-nil means TAB will automatically notice a table.el table.
1744 When it sees such a table, it moves point into it and - if necessary -
1745 calls `table-recognize-table'."
1746 :group 'org-table-editing
1747 :type 'boolean)
1749 (defgroup org-link nil
1750 "Options concerning links in Org-mode."
1751 :tag "Org Link"
1752 :group 'org)
1754 (defvar-local org-link-abbrev-alist-local nil
1755 "Buffer-local version of `org-link-abbrev-alist', which see.
1756 The value of this is taken from the #+LINK lines.")
1758 (defcustom org-link-abbrev-alist nil
1759 "Alist of link abbreviations.
1760 The car of each element is a string, to be replaced at the start of a link.
1761 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1762 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1764 [[linkkey:tag][description]]
1766 The `linkkey' must be a word word, starting with a letter, followed
1767 by letters, numbers, `-' or `_'.
1769 If REPLACE is a string, the tag will simply be appended to create the link.
1770 If the string contains \"%s\", the tag will be inserted there. If the string
1771 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1772 at that point (see the function `url-hexify-string'). If the string contains
1773 the specifier \"%(my-function)\", then the custom function `my-function' will
1774 be invoked: this function takes the tag as its only argument and must return
1775 a string.
1777 REPLACE may also be a function that will be called with the tag as the
1778 only argument to create the link, which should be returned as a string.
1780 See the manual for examples."
1781 :group 'org-link
1782 :type '(repeat
1783 (cons
1784 (string :tag "Protocol")
1785 (choice
1786 (string :tag "Format")
1787 (function)))))
1789 (defcustom org-descriptive-links t
1790 "Non-nil means Org will display descriptive links.
1791 E.g. [[http://orgmode.org][Org website]] will be displayed as
1792 \"Org Website\", hiding the link itself and just displaying its
1793 description. When set to nil, Org will display the full links
1794 literally.
1796 You can interactively set the value of this variable by calling
1797 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1798 :group 'org-link
1799 :type 'boolean)
1801 (defcustom org-link-file-path-type 'adaptive
1802 "How the path name in file links should be stored.
1803 Valid values are:
1805 relative Relative to the current directory, i.e. the directory of the file
1806 into which the link is being inserted.
1807 absolute Absolute path, if possible with ~ for home directory.
1808 noabbrev Absolute path, no abbreviation of home directory.
1809 adaptive Use relative path for files in the current directory and sub-
1810 directories of it. For other files, use an absolute path."
1811 :group 'org-link
1812 :type '(choice
1813 (const relative)
1814 (const absolute)
1815 (const noabbrev)
1816 (const adaptive)))
1818 (defvaralias 'org-activate-links 'org-highlight-links)
1819 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1820 "Types of links that should be highlighted in Org-mode files.
1822 This is a list of symbols, each one of them leading to the
1823 highlighting of a certain link type.
1825 You can still open links that are not highlighted.
1827 In principle, it does not hurt to turn on highlighting for all
1828 link types. There may be a small gain when turning off unused
1829 link types. The types are:
1831 bracket The recommended [[link][description]] or [[link]] links with hiding.
1832 angle Links in angular brackets that may contain whitespace like
1833 <bbdb:Carsten Dominik>.
1834 plain Plain links in normal text, no whitespace, like http://google.com.
1835 radio Text that is matched by a radio target, see manual for details.
1836 tag Tag settings in a headline (link to tag search).
1837 date Time stamps (link to calendar).
1838 footnote Footnote labels.
1840 If you set this variable during an Emacs session, use `org-mode-restart'
1841 in the Org buffer so that the change takes effect."
1842 :group 'org-link
1843 :group 'org-appearance
1844 :type '(set :greedy t
1845 (const :tag "Double bracket links" bracket)
1846 (const :tag "Angular bracket links" angle)
1847 (const :tag "Plain text links" plain)
1848 (const :tag "Radio target matches" radio)
1849 (const :tag "Tags" tag)
1850 (const :tag "Timestamps" date)
1851 (const :tag "Footnotes" footnote)))
1853 (defcustom org-make-link-description-function nil
1854 "Function to use for generating link descriptions from links.
1855 When nil, the link location will be used. This function must take
1856 two parameters: the first one is the link, the second one is the
1857 description generated by `org-insert-link'. The function should
1858 return the description to use."
1859 :group 'org-link
1860 :type '(choice (const nil) (function)))
1862 (defgroup org-link-store nil
1863 "Options concerning storing links in Org-mode."
1864 :tag "Org Store Link"
1865 :group 'org-link)
1867 (defcustom org-url-hexify-p t
1868 "When non-nil, hexify URL when creating a link."
1869 :type 'boolean
1870 :version "24.3"
1871 :group 'org-link-store)
1873 (defcustom org-email-link-description-format "Email %c: %.30s"
1874 "Format of the description part of a link to an email or usenet message.
1875 The following %-escapes will be replaced by corresponding information:
1877 %F full \"From\" field
1878 %f name, taken from \"From\" field, address if no name
1879 %T full \"To\" field
1880 %t first name in \"To\" field, address if no name
1881 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1882 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1883 %s subject
1884 %d date
1885 %m message-id.
1887 You may use normal field width specification between the % and the letter.
1888 This is for example useful to limit the length of the subject.
1890 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1891 :group 'org-link-store
1892 :type 'string)
1894 (defcustom org-from-is-user-regexp
1895 (let (r1 r2)
1896 (when (and user-mail-address (not (string= user-mail-address "")))
1897 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1898 (when (and user-full-name (not (string= user-full-name "")))
1899 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1900 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1901 "Regexp matched against the \"From:\" header of an email or usenet message.
1902 It should match if the message is from the user him/herself."
1903 :group 'org-link-store
1904 :type 'regexp)
1906 (defcustom org-context-in-file-links t
1907 "Non-nil means file links from `org-store-link' contain context.
1908 A search string will be added to the file name with :: as separator and
1909 used to find the context when the link is activated by the command
1910 `org-open-at-point'. When this option is t, the entire active region
1911 will be placed in the search string of the file link. If set to a
1912 positive integer, only the first n lines of context will be stored.
1914 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1915 negates this setting for the duration of the command."
1916 :group 'org-link-store
1917 :type '(choice boolean integer))
1919 (defcustom org-keep-stored-link-after-insertion nil
1920 "Non-nil means keep link in list for entire session.
1922 The command `org-store-link' adds a link pointing to the current
1923 location to an internal list. These links accumulate during a session.
1924 The command `org-insert-link' can be used to insert links into any
1925 Org-mode file (offering completion for all stored links). When this
1926 option is nil, every link which has been inserted once using \\[org-insert-link]
1927 will be removed from the list, to make completing the unused links
1928 more efficient."
1929 :group 'org-link-store
1930 :type 'boolean)
1932 (defgroup org-link-follow nil
1933 "Options concerning following links in Org-mode."
1934 :tag "Org Follow Link"
1935 :group 'org-link)
1937 (defcustom org-link-translation-function nil
1938 "Function to translate links with different syntax to Org syntax.
1939 This can be used to translate links created for example by the Planner
1940 or emacs-wiki packages to Org syntax.
1941 The function must accept two parameters, a TYPE containing the link
1942 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1943 which is everything after the link protocol. It should return a cons
1944 with possibly modified values of type and path.
1945 Org contains a function for this, so if you set this variable to
1946 `org-translate-link-from-planner', you should be able follow many
1947 links created by planner."
1948 :group 'org-link-follow
1949 :type '(choice (const nil) (function)))
1951 (defcustom org-follow-link-hook nil
1952 "Hook that is run after a link has been followed."
1953 :group 'org-link-follow
1954 :type 'hook)
1956 (defcustom org-tab-follows-link nil
1957 "Non-nil means on links TAB will follow the link.
1958 Needs to be set before org.el is loaded.
1959 This really should not be used, it does not make sense, and the
1960 implementation is bad."
1961 :group 'org-link-follow
1962 :type 'boolean)
1964 (defcustom org-return-follows-link nil
1965 "Non-nil means on links RET will follow the link.
1966 In tables, the special behavior of RET has precedence."
1967 :group 'org-link-follow
1968 :type 'boolean)
1970 (defcustom org-mouse-1-follows-link
1971 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1972 "Non-nil means mouse-1 on a link will follow the link.
1973 A longer mouse click will still set point. Does not work on XEmacs.
1974 Needs to be set before org.el is loaded."
1975 :group 'org-link-follow
1976 :version "24.4"
1977 :package-version '(Org . "8.3")
1978 :type '(choice
1979 (const :tag "A double click follows the link" double)
1980 (const :tag "Unconditionally follow the link with mouse-1" t)
1981 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1983 (defcustom org-mark-ring-length 4
1984 "Number of different positions to be recorded in the ring.
1985 Changing this requires a restart of Emacs to work correctly."
1986 :group 'org-link-follow
1987 :type 'integer)
1989 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1990 "Non-nil means internal links in Org files must exactly match a headline.
1991 When nil, the link search tries to match a phrase with all words
1992 in the search text."
1993 :group 'org-link-follow
1994 :version "24.1"
1995 :type '(choice
1996 (const :tag "Use fuzzy text search" nil)
1997 (const :tag "Match only exact headline" t)
1998 (const :tag "Match exact headline or query to create it"
1999 query-to-create)))
2001 (defcustom org-link-frame-setup
2002 '((vm . vm-visit-folder-other-frame)
2003 (vm-imap . vm-visit-imap-folder-other-frame)
2004 (gnus . org-gnus-no-new-news)
2005 (file . find-file-other-window)
2006 (wl . wl-other-frame))
2007 "Setup the frame configuration for following links.
2008 When following a link with Emacs, it may often be useful to display
2009 this link in another window or frame. This variable can be used to
2010 set this up for the different types of links.
2011 For VM, use any of
2012 `vm-visit-folder'
2013 `vm-visit-folder-other-window'
2014 `vm-visit-folder-other-frame'
2015 For Gnus, use any of
2016 `gnus'
2017 `gnus-other-frame'
2018 `org-gnus-no-new-news'
2019 For FILE, use any of
2020 `find-file'
2021 `find-file-other-window'
2022 `find-file-other-frame'
2023 For Wanderlust use any of
2024 `wl'
2025 `wl-other-frame'
2026 For the calendar, use the variable `calendar-setup'.
2027 For BBDB, it is currently only possible to display the matches in
2028 another window."
2029 :group 'org-link-follow
2030 :type '(list
2031 (cons (const vm)
2032 (choice
2033 (const vm-visit-folder)
2034 (const vm-visit-folder-other-window)
2035 (const vm-visit-folder-other-frame)))
2036 (cons (const vm-imap)
2037 (choice
2038 (const vm-visit-imap-folder)
2039 (const vm-visit-imap-folder-other-window)
2040 (const vm-visit-imap-folder-other-frame)))
2041 (cons (const gnus)
2042 (choice
2043 (const gnus)
2044 (const gnus-other-frame)
2045 (const org-gnus-no-new-news)))
2046 (cons (const file)
2047 (choice
2048 (const find-file)
2049 (const find-file-other-window)
2050 (const find-file-other-frame)))
2051 (cons (const wl)
2052 (choice
2053 (const wl)
2054 (const wl-other-frame)))))
2056 (defcustom org-display-internal-link-with-indirect-buffer nil
2057 "Non-nil means use indirect buffer to display infile links.
2058 Activating internal links (from one location in a file to another location
2059 in the same file) normally just jumps to the location. When the link is
2060 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2061 is displayed in
2062 another window. When this option is set, the other window actually displays
2063 an indirect buffer clone of the current buffer, to avoid any visibility
2064 changes to the current buffer."
2065 :group 'org-link-follow
2066 :type 'boolean)
2068 (defcustom org-open-non-existing-files nil
2069 "Non-nil means `org-open-file' will open non-existing files.
2070 When nil, an error will be generated.
2071 This variable applies only to external applications because they
2072 might choke on non-existing files. If the link is to a file that
2073 will be opened in Emacs, the variable is ignored."
2074 :group 'org-link-follow
2075 :type 'boolean)
2077 (defcustom org-open-directory-means-index-dot-org nil
2078 "Non-nil means a link to a directory really means to index.org.
2079 When nil, following a directory link will run dired or open a finder/explorer
2080 window on that directory."
2081 :group 'org-link-follow
2082 :type 'boolean)
2084 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2085 "Non-nil means ask for confirmation before executing shell links.
2086 Shell links can be dangerous: just think about a link
2088 [[shell:rm -rf ~/*][Google Search]]
2090 This link would show up in your Org-mode document as \"Google Search\",
2091 but really it would remove your entire home directory.
2092 Therefore we advise against setting this variable to nil.
2093 Just change it to `y-or-n-p' if you want to confirm with a
2094 single keystroke rather than having to type \"yes\"."
2095 :group 'org-link-follow
2096 :type '(choice
2097 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2098 (const :tag "with y-or-n (faster)" y-or-n-p)
2099 (const :tag "no confirmation (dangerous)" nil)))
2100 (put 'org-confirm-shell-link-function
2101 'safe-local-variable
2102 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2104 (defcustom org-confirm-shell-link-not-regexp ""
2105 "A regexp to skip confirmation for shell links."
2106 :group 'org-link-follow
2107 :version "24.1"
2108 :type 'regexp)
2110 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2111 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2112 Elisp links can be dangerous: just think about a link
2114 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2116 This link would show up in your Org-mode document as \"Google Search\",
2117 but really it would remove your entire home directory.
2118 Therefore we advise against setting this variable to nil.
2119 Just change it to `y-or-n-p' if you want to confirm with a
2120 single keystroke rather than having to type \"yes\"."
2121 :group 'org-link-follow
2122 :type '(choice
2123 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2124 (const :tag "with y-or-n (faster)" y-or-n-p)
2125 (const :tag "no confirmation (dangerous)" nil)))
2126 (put 'org-confirm-shell-link-function
2127 'safe-local-variable
2128 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2130 (defcustom org-confirm-elisp-link-not-regexp ""
2131 "A regexp to skip confirmation for Elisp links."
2132 :group 'org-link-follow
2133 :version "24.1"
2134 :type 'regexp)
2136 (defconst org-file-apps-defaults-gnu
2137 '((remote . emacs)
2138 (system . mailcap)
2139 (t . mailcap))
2140 "Default file applications on a UNIX or GNU/Linux system.
2141 See `org-file-apps'.")
2143 (defconst org-file-apps-defaults-macosx
2144 '((remote . emacs)
2145 (system . "open %s")
2146 ("ps.gz" . "gv %s")
2147 ("eps.gz" . "gv %s")
2148 ("dvi" . "xdvi %s")
2149 ("fig" . "xfig %s")
2150 (t . "open %s"))
2151 "Default file applications on a MacOS X system.
2152 The system \"open\" is known as a default, but we use X11 applications
2153 for some files for which the OS does not have a good default.
2154 See `org-file-apps'.")
2156 (defconst org-file-apps-defaults-windowsnt
2157 (list '(remote . emacs)
2158 (cons 'system (lambda (file _path)
2159 (with-no-warnings (w32-shell-execute "open" file))))
2160 (cons t (lambda (file _path)
2161 (with-no-warnings (w32-shell-execute "open" file)))))
2162 "Default file applications on a Windows NT system.
2163 The system \"open\" is used for most files.
2164 See `org-file-apps'.")
2166 (defcustom org-file-apps
2167 '((auto-mode . emacs)
2168 ("\\.mm\\'" . default)
2169 ("\\.x?html?\\'" . default)
2170 ("\\.pdf\\'" . default))
2171 "External applications for opening `file:path' items in a document.
2172 \\<org-mode-map>\
2173 Org mode uses system defaults for different file types, but
2174 you can use this variable to set the application for a given file
2175 extension. The entries in this list are cons cells where the car identifies
2176 files and the cdr the corresponding command. Possible values for the
2177 file identifier are
2178 \"string\" A string as a file identifier can be interpreted in different
2179 ways, depending on its contents:
2181 - Alphanumeric characters only:
2182 Match links with this file extension.
2183 Example: (\"pdf\" . \"evince %s\")
2184 to open PDFs with evince.
2186 - Regular expression: Match links where the
2187 filename matches the regexp. If you want to
2188 use groups here, use shy groups.
2190 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2191 \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2192 to open *.html and *.xhtml with firefox.
2194 - Regular expression which contains (non-shy) groups:
2195 Match links where the whole link, including \"::\", and
2196 anything after that, matches the regexp.
2197 In a custom command string, %1, %2, etc. are replaced with
2198 the parts of the link that were matched by the groups.
2199 For backwards compatibility, if a command string is given
2200 that does not use any of the group matches, this case is
2201 handled identically to the second one (i.e. match against
2202 file name only).
2203 In a custom function, you can access the group matches with
2204 \(match-string n link).
2206 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2207 to open [[file:document.pdf::5]] with evince at page 5.
2209 `directory' Matches a directory
2210 `remote' Matches a remote file, accessible through tramp or efs.
2211 Remote files most likely should be visited through Emacs
2212 because external applications cannot handle such paths.
2213 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2214 so all files Emacs knows how to handle. Using this with
2215 command `emacs' will open most files in Emacs. Beware that this
2216 will also open html files inside Emacs, unless you add
2217 \(\"html\" . default) to the list as well.
2218 `system' The system command to open files, like `open' on Windows
2219 and Mac OS X, and mailcap under GNU/Linux. This is the command
2220 that will be selected if you call \\[org-open-at-point] with a double
2221 \\[universal-argument] \\[universal-argument] prefix.
2222 t Default for files not matched by any of the other options.
2224 Possible values for the command are:
2225 `emacs' The file will be visited by the current Emacs process.
2226 `default' Use the default application for this file type, which is the
2227 association for t in the list, most likely in the system-specific
2228 part. This can be used to overrule an unwanted setting in the
2229 system-specific variable.
2230 `system' Use the system command for opening files, like \"open\".
2231 This command is specified by the entry whose car is `system'.
2232 Most likely, the system-specific version of this variable
2233 does define this command, but you can overrule/replace it
2234 here.
2235 `mailcap' Use command specified in the mailcaps.
2236 string A command to be executed by a shell; %s will be replaced
2237 by the path to the file.
2239 function A Lisp function, which will be called with two arguments:
2240 the file path and the original link string, without the
2241 \"file:\" prefix.
2243 For more examples, see the system specific constants
2244 `org-file-apps-defaults-macosx'
2245 `org-file-apps-defaults-windowsnt'
2246 `org-file-apps-defaults-gnu'."
2247 :group 'org-link-follow
2248 :type '(repeat
2249 (cons (choice :value ""
2250 (string :tag "Extension")
2251 (const :tag "System command to open files" system)
2252 (const :tag "Default for unrecognized files" t)
2253 (const :tag "Remote file" remote)
2254 (const :tag "Links to a directory" directory)
2255 (const :tag "Any files that have Emacs modes"
2256 auto-mode))
2257 (choice :value ""
2258 (const :tag "Visit with Emacs" emacs)
2259 (const :tag "Use default" default)
2260 (const :tag "Use the system command" system)
2261 (string :tag "Command")
2262 (function :tag "Function")))))
2264 (defcustom org-doi-server-url "http://dx.doi.org/"
2265 "The URL of the DOI server."
2266 :type 'string
2267 :version "24.3"
2268 :group 'org-link-follow)
2270 (defgroup org-refile nil
2271 "Options concerning refiling entries in Org-mode."
2272 :tag "Org Refile"
2273 :group 'org)
2275 (defcustom org-directory "~/org"
2276 "Directory with Org files.
2277 This is just a default location to look for Org files. There is no need
2278 at all to put your files into this directory. It is used in the
2279 following situations:
2281 1. When a capture template specifies a target file that is not an
2282 absolute path. The path will then be interpreted relative to
2283 `org-directory'
2284 2. When the value of variable `org-agenda-files' is a single file, any
2285 relative paths in this file will be taken as relative to
2286 `org-directory'."
2287 :group 'org-refile
2288 :group 'org-capture
2289 :type 'directory)
2291 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2292 "Default target for storing notes.
2293 Used as a fall back file for org-capture.el, for templates that
2294 do not specify a target file."
2295 :group 'org-refile
2296 :group 'org-capture
2297 :type 'file)
2299 (defcustom org-goto-interface 'outline
2300 "The default interface to be used for `org-goto'.
2301 Allowed values are:
2302 outline The interface shows an outline of the relevant file
2303 and the correct heading is found by moving through
2304 the outline or by searching with incremental search.
2305 outline-path-completion Headlines in the current buffer are offered via
2306 completion. This is the interface also used by
2307 the refile command."
2308 :group 'org-refile
2309 :type '(choice
2310 (const :tag "Outline" outline)
2311 (const :tag "Outline-path-completion" outline-path-completion)))
2313 (defcustom org-goto-max-level 5
2314 "Maximum target level when running `org-goto' with refile interface."
2315 :group 'org-refile
2316 :type 'integer)
2318 (defcustom org-reverse-note-order nil
2319 "Non-nil means store new notes at the beginning of a file or entry.
2320 When nil, new notes will be filed to the end of a file or entry.
2321 This can also be a list with cons cells of regular expressions that
2322 are matched against file names, and values."
2323 :group 'org-capture
2324 :group 'org-refile
2325 :type '(choice
2326 (const :tag "Reverse always" t)
2327 (const :tag "Reverse never" nil)
2328 (repeat :tag "By file name regexp"
2329 (cons regexp boolean))))
2331 (defcustom org-log-refile nil
2332 "Information to record when a task is refiled.
2334 Possible values are:
2336 nil Don't add anything
2337 time Add a time stamp to the task
2338 note Prompt for a note and add it with template `org-log-note-headings'
2340 This option can also be set with on a per-file-basis with
2342 #+STARTUP: nologrefile
2343 #+STARTUP: logrefile
2344 #+STARTUP: lognoterefile
2346 You can have local logging settings for a subtree by setting the LOGGING
2347 property to one or more of these keywords.
2349 When bulk-refiling from the agenda, the value `note' is forbidden and
2350 will temporarily be changed to `time'."
2351 :group 'org-refile
2352 :group 'org-progress
2353 :version "24.1"
2354 :type '(choice
2355 (const :tag "No logging" nil)
2356 (const :tag "Record timestamp" time)
2357 (const :tag "Record timestamp with note." note)))
2359 (defcustom org-refile-targets nil
2360 "Targets for refiling entries with \\[org-refile].
2361 This is a list of cons cells. Each cell contains:
2362 - a specification of the files to be considered, either a list of files,
2363 or a symbol whose function or variable value will be used to retrieve
2364 a file name or a list of file names. If you use `org-agenda-files' for
2365 that, all agenda files will be scanned for targets. Nil means consider
2366 headings in the current buffer.
2367 - A specification of how to find candidate refile targets. This may be
2368 any of:
2369 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2370 This tag has to be present in all target headlines, inheritance will
2371 not be considered.
2372 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2373 todo keyword.
2374 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2375 headlines that are refiling targets.
2376 - a cons cell (:level . N). Any headline of level N is considered a target.
2377 Note that, when `org-odd-levels-only' is set, level corresponds to
2378 order in hierarchy, not to the number of stars.
2379 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2380 Note that, when `org-odd-levels-only' is set, level corresponds to
2381 order in hierarchy, not to the number of stars.
2383 Each element of this list generates a set of possible targets.
2384 The union of these sets is presented (with completion) to
2385 the user by `org-refile'.
2387 You can set the variable `org-refile-target-verify-function' to a function
2388 to verify each headline found by the simple criteria above.
2390 When this variable is nil, all top-level headlines in the current buffer
2391 are used, equivalent to the value `((nil . (:level . 1))'."
2392 :group 'org-refile
2393 :type '(repeat
2394 (cons
2395 (choice :value org-agenda-files
2396 (const :tag "All agenda files" org-agenda-files)
2397 (const :tag "Current buffer" nil)
2398 (function) (variable) (file))
2399 (choice :tag "Identify target headline by"
2400 (cons :tag "Specific tag" (const :value :tag) (string))
2401 (cons :tag "TODO keyword" (const :value :todo) (string))
2402 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2403 (cons :tag "Level number" (const :value :level) (integer))
2404 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2406 (defcustom org-refile-target-verify-function nil
2407 "Function to verify if the headline at point should be a refile target.
2408 The function will be called without arguments, with point at the
2409 beginning of the headline. It should return t and leave point
2410 where it is if the headline is a valid target for refiling.
2412 If the target should not be selected, the function must return nil.
2413 In addition to this, it may move point to a place from where the search
2414 should be continued. For example, the function may decide that the entire
2415 subtree of the current entry should be excluded and move point to the end
2416 of the subtree."
2417 :group 'org-refile
2418 :type '(choice
2419 (const nil)
2420 (function)))
2422 (defcustom org-refile-use-cache nil
2423 "Non-nil means cache refile targets to speed up the process.
2424 \\<org-mode-map>\
2425 The cache for a particular file will be updated automatically when
2426 the buffer has been killed, or when any of the marker used for flagging
2427 refile targets no longer points at a live buffer.
2428 If you have added new entries to a buffer that might themselves be targets,
2429 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2430 if you find that easier, \
2431 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2432 \\[org-refile]'."
2433 :group 'org-refile
2434 :version "24.1"
2435 :type 'boolean)
2437 (defcustom org-refile-use-outline-path nil
2438 "Non-nil means provide refile targets as paths.
2439 So a level 3 headline will be available as level1/level2/level3.
2441 When the value is `file', also include the file name (without directory)
2442 into the path. In this case, you can also stop the completion after
2443 the file name, to get entries inserted as top level in the file.
2445 When `full-file-path', include the full file path."
2446 :group 'org-refile
2447 :type '(choice
2448 (const :tag "Not" nil)
2449 (const :tag "Yes" t)
2450 (const :tag "Start with file name" file)
2451 (const :tag "Start with full file path" full-file-path)))
2453 (defcustom org-outline-path-complete-in-steps t
2454 "Non-nil means complete the outline path in hierarchical steps.
2455 When Org-mode uses the refile interface to select an outline path
2456 \(see variable `org-refile-use-outline-path'), the completion of
2457 the path can be done in a single go, or it can be done in steps down
2458 the headline hierarchy. Going in steps is probably the best if you
2459 do not use a special completion package like `ido' or `icicles'.
2460 However, when using these packages, going in one step can be very
2461 fast, while still showing the whole path to the entry."
2462 :group 'org-refile
2463 :type 'boolean)
2465 (defcustom org-refile-allow-creating-parent-nodes nil
2466 "Non-nil means allow the creation of new nodes as refile targets.
2467 New nodes are then created by adding \"/new node name\" to the completion
2468 of an existing node. When the value of this variable is `confirm',
2469 new node creation must be confirmed by the user (recommended).
2470 When nil, the completion must match an existing entry.
2472 Note that, if the new heading is not seen by the criteria
2473 listed in `org-refile-targets', multiple instances of the same
2474 heading would be created by trying again to file under the new
2475 heading."
2476 :group 'org-refile
2477 :type '(choice
2478 (const :tag "Never" nil)
2479 (const :tag "Always" t)
2480 (const :tag "Prompt for confirmation" confirm)))
2482 (defcustom org-refile-active-region-within-subtree nil
2483 "Non-nil means also refile active region within a subtree.
2485 By default `org-refile' doesn't allow refiling regions if they
2486 don't contain a set of subtrees, but it might be convenient to
2487 do so sometimes: in that case, the first line of the region is
2488 converted to a headline before refiling."
2489 :group 'org-refile
2490 :version "24.1"
2491 :type 'boolean)
2493 (defgroup org-todo nil
2494 "Options concerning TODO items in Org-mode."
2495 :tag "Org TODO"
2496 :group 'org)
2498 (defgroup org-progress nil
2499 "Options concerning Progress logging in Org-mode."
2500 :tag "Org Progress"
2501 :group 'org-time)
2503 (defvar org-todo-interpretation-widgets
2504 '((:tag "Sequence (cycling hits every state)" sequence)
2505 (:tag "Type (cycling directly to DONE)" type))
2506 "The available interpretation symbols for customizing `org-todo-keywords'.
2507 Interested libraries should add to this list.")
2509 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2510 "List of TODO entry keyword sequences and their interpretation.
2511 \\<org-mode-map>This is a list of sequences.
2513 Each sequence starts with a symbol, either `sequence' or `type',
2514 indicating if the keywords should be interpreted as a sequence of
2515 action steps, or as different types of TODO items. The first
2516 keywords are states requiring action - these states will select a headline
2517 for inclusion into the global TODO list Org-mode produces. If one of
2518 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2519 signify that no further action is necessary. If \"|\" is not found,
2520 the last keyword is treated as the only DONE state of the sequence.
2522 The command \\[org-todo] cycles an entry through these states, and one
2523 additional state where no keyword is present. For details about this
2524 cycling, see the manual.
2526 TODO keywords and interpretation can also be set on a per-file basis with
2527 the special #+SEQ_TODO and #+TYP_TODO lines.
2529 Each keyword can optionally specify a character for fast state selection
2530 \(in combination with the variable `org-use-fast-todo-selection')
2531 and specifiers for state change logging, using the same syntax that
2532 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2533 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2534 indicates to record a time stamp each time this state is selected.
2536 Each keyword may also specify if a timestamp or a note should be
2537 recorded when entering or leaving the state, by adding additional
2538 characters in the parenthesis after the keyword. This looks like this:
2539 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2540 record only the time of the state change. With X and Y being either
2541 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2542 Y when leaving the state if and only if the *target* state does not
2543 define X. You may omit any of the fast-selection key or X or /Y,
2544 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2546 For backward compatibility, this variable may also be just a list
2547 of keywords. In this case the interpretation (sequence or type) will be
2548 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2549 :group 'org-todo
2550 :group 'org-keywords
2551 :type '(choice
2552 (repeat :tag "Old syntax, just keywords"
2553 (string :tag "Keyword"))
2554 (repeat :tag "New syntax"
2555 (cons
2556 (choice
2557 :tag "Interpretation"
2558 ;;Quick and dirty way to see
2559 ;;`org-todo-interpretations'. This takes the
2560 ;;place of item arguments
2561 :convert-widget
2562 (lambda (widget)
2563 (widget-put widget
2564 :args (mapcar
2565 (lambda (x)
2566 (widget-convert
2567 (cons 'const x)))
2568 org-todo-interpretation-widgets))
2569 widget))
2570 (repeat
2571 (string :tag "Keyword"))))))
2573 (defvar-local org-todo-keywords-1 nil
2574 "All TODO and DONE keywords active in a buffer.")
2575 (defvar org-todo-keywords-for-agenda nil)
2576 (defvar org-done-keywords-for-agenda nil)
2577 (defvar org-todo-keyword-alist-for-agenda nil)
2578 (defvar org-tag-alist-for-agenda nil
2579 "Alist of all tags from all agenda files.")
2580 (defvar org-tag-groups-alist-for-agenda nil
2581 "Alist of all groups tags from all current agenda files.")
2582 (defvar-local org-tag-groups-alist nil)
2583 (defvar org-agenda-contributing-files nil)
2584 (defvar-local org-current-tag-alist nil
2585 "Alist of all tag groups in current buffer.
2586 This variable takes into consideration `org-tag-alist',
2587 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2588 (defvar-local org-not-done-keywords nil)
2589 (defvar-local org-done-keywords nil)
2590 (defvar-local org-todo-heads nil)
2591 (defvar-local org-todo-sets nil)
2592 (defvar-local org-todo-log-states nil)
2593 (defvar-local org-todo-kwd-alist nil)
2594 (defvar-local org-todo-key-alist nil)
2595 (defvar-local org-todo-key-trigger nil)
2597 (defcustom org-todo-interpretation 'sequence
2598 "Controls how TODO keywords are interpreted.
2599 This variable is in principle obsolete and is only used for
2600 backward compatibility, if the interpretation of todo keywords is
2601 not given already in `org-todo-keywords'. See that variable for
2602 more information."
2603 :group 'org-todo
2604 :group 'org-keywords
2605 :type '(choice (const sequence)
2606 (const type)))
2608 (defcustom org-use-fast-todo-selection t
2609 "\\<org-mode-map>\
2610 Non-nil means use the fast todo selection scheme with \\[org-todo].
2611 This variable describes if and under what circumstances the cycling
2612 mechanism for TODO keywords will be replaced by a single-key, direct
2613 selection scheme.
2615 When nil, fast selection is never used.
2617 When the symbol `prefix', it will be used when `org-todo' is called
2618 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2619 in an Org-mode buffer, and
2620 `\\[universal-argument] t' in an agenda buffer.
2622 When t, fast selection is used by default. In this case, the prefix
2623 argument forces cycling instead.
2625 In all cases, the special interface is only used if access keys have
2626 actually been assigned by the user, i.e. if keywords in the configuration
2627 are followed by a letter in parenthesis, like TODO(t)."
2628 :group 'org-todo
2629 :type '(choice
2630 (const :tag "Never" nil)
2631 (const :tag "By default" t)
2632 (const :tag "Only with C-u C-c C-t" prefix)))
2634 (defcustom org-provide-todo-statistics t
2635 "Non-nil means update todo statistics after insert and toggle.
2636 ALL-HEADLINES means update todo statistics by including headlines
2637 with no TODO keyword as well, counting them as not done.
2638 A list of TODO keywords means the same, but skip keywords that are
2639 not in this list.
2640 When set to a list of two lists, the first list contains keywords
2641 to consider as TODO keywords, the second list contains keywords
2642 to consider as DONE keywords.
2644 When this is set, todo statistics is updated in the parent of the
2645 current entry each time a todo state is changed."
2646 :group 'org-todo
2647 :type '(choice
2648 (const :tag "Yes, only for TODO entries" t)
2649 (const :tag "Yes, including all entries" all-headlines)
2650 (repeat :tag "Yes, for TODOs in this list"
2651 (string :tag "TODO keyword"))
2652 (list :tag "Yes, for TODOs and DONEs in these lists"
2653 (repeat (string :tag "TODO keyword"))
2654 (repeat (string :tag "DONE keyword")))
2655 (other :tag "No TODO statistics" nil)))
2657 (defcustom org-hierarchical-todo-statistics t
2658 "Non-nil means TODO statistics covers just direct children.
2659 When nil, all entries in the subtree are considered.
2660 This has only an effect if `org-provide-todo-statistics' is set.
2661 To set this to nil for only a single subtree, use a COOKIE_DATA
2662 property and include the word \"recursive\" into the value."
2663 :group 'org-todo
2664 :type 'boolean)
2666 (defcustom org-after-todo-state-change-hook nil
2667 "Hook which is run after the state of a TODO item was changed.
2668 The new state (a string with a TODO keyword, or nil) is available in the
2669 Lisp variable `org-state'."
2670 :group 'org-todo
2671 :type 'hook)
2673 (defvar org-blocker-hook nil
2674 "Hook for functions that are allowed to block a state change.
2676 Functions in this hook should not modify the buffer.
2677 Each function gets as its single argument a property list,
2678 see `org-trigger-hook' for more information about this list.
2680 If any of the functions in this hook returns nil, the state change
2681 is blocked.")
2683 (defvar org-trigger-hook nil
2684 "Hook for functions that are triggered by a state change.
2686 Each function gets as its single argument a property list with at
2687 least the following elements:
2689 (:type type-of-change :position pos-at-entry-start
2690 :from old-state :to new-state)
2692 Depending on the type, more properties may be present.
2694 This mechanism is currently implemented for:
2696 TODO state changes
2697 ------------------
2698 :type todo-state-change
2699 :from previous state (keyword as a string), or nil, or a symbol
2700 `todo' or `done', to indicate the general type of state.
2701 :to new state, like in :from")
2703 (defcustom org-enforce-todo-dependencies nil
2704 "Non-nil means undone TODO entries will block switching the parent to DONE.
2705 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2706 be blocked if any prior sibling is not yet done.
2707 Finally, if the parent is blocked because of ordered siblings of its own,
2708 the child will also be blocked."
2709 :set (lambda (var val)
2710 (set var val)
2711 (if val
2712 (add-hook 'org-blocker-hook
2713 'org-block-todo-from-children-or-siblings-or-parent)
2714 (remove-hook 'org-blocker-hook
2715 'org-block-todo-from-children-or-siblings-or-parent)))
2716 :group 'org-todo
2717 :type 'boolean)
2719 (defcustom org-enforce-todo-checkbox-dependencies nil
2720 "Non-nil means unchecked boxes will block switching the parent to DONE.
2721 When this is nil, checkboxes have no influence on switching TODO states.
2722 When non-nil, you first need to check off all check boxes before the TODO
2723 entry can be switched to DONE.
2724 This variable needs to be set before org.el is loaded, and you need to
2725 restart Emacs after a change to make the change effective. The only way
2726 to change is while Emacs is running is through the customize interface."
2727 :set (lambda (var val)
2728 (set var val)
2729 (if val
2730 (add-hook 'org-blocker-hook
2731 'org-block-todo-from-checkboxes)
2732 (remove-hook 'org-blocker-hook
2733 'org-block-todo-from-checkboxes)))
2734 :group 'org-todo
2735 :type 'boolean)
2737 (defcustom org-treat-insert-todo-heading-as-state-change nil
2738 "Non-nil means inserting a TODO heading is treated as state change.
2739 So when the command \\[org-insert-todo-heading] is used, state change
2740 logging will apply if appropriate. When nil, the new TODO item will
2741 be inserted directly, and no logging will take place."
2742 :group 'org-todo
2743 :type 'boolean)
2745 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2746 "Non-nil means switching TODO states with S-cursor counts as state change.
2747 This is the default behavior. However, setting this to nil allows a
2748 convenient way to select a TODO state and bypass any logging associated
2749 with that."
2750 :group 'org-todo
2751 :type 'boolean)
2753 (defcustom org-todo-state-tags-triggers nil
2754 "Tag changes that should be triggered by TODO state changes.
2755 This is a list. Each entry is
2757 (state-change (tag . flag) .......)
2759 State-change can be a string with a state, and empty string to indicate the
2760 state that has no TODO keyword, or it can be one of the symbols `todo'
2761 or `done', meaning any not-done or done state, respectively."
2762 :group 'org-todo
2763 :group 'org-tags
2764 :type '(repeat
2765 (cons (choice :tag "When changing to"
2766 (const :tag "Not-done state" todo)
2767 (const :tag "Done state" done)
2768 (string :tag "State"))
2769 (repeat
2770 (cons :tag "Tag action"
2771 (string :tag "Tag")
2772 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2774 (defcustom org-log-done nil
2775 "Information to record when a task moves to the DONE state.
2777 Possible values are:
2779 nil Don't add anything, just change the keyword
2780 time Add a time stamp to the task
2781 note Prompt for a note and add it with template `org-log-note-headings'
2783 This option can also be set with on a per-file-basis with
2785 #+STARTUP: nologdone
2786 #+STARTUP: logdone
2787 #+STARTUP: lognotedone
2789 You can have local logging settings for a subtree by setting the LOGGING
2790 property to one or more of these keywords."
2791 :group 'org-todo
2792 :group 'org-progress
2793 :type '(choice
2794 (const :tag "No logging" nil)
2795 (const :tag "Record CLOSED timestamp" time)
2796 (const :tag "Record CLOSED timestamp with note." note)))
2798 ;; Normalize old uses of org-log-done.
2799 (cond
2800 ((eq org-log-done t) (setq org-log-done 'time))
2801 ((and (listp org-log-done) (memq 'done org-log-done))
2802 (setq org-log-done 'note)))
2804 (defcustom org-log-reschedule nil
2805 "Information to record when the scheduling date of a tasks is modified.
2807 Possible values are:
2809 nil Don't add anything, just change the date
2810 time Add a time stamp to the task
2811 note Prompt for a note and add it with template `org-log-note-headings'
2813 This option can also be set with on a per-file-basis with
2815 #+STARTUP: nologreschedule
2816 #+STARTUP: logreschedule
2817 #+STARTUP: lognotereschedule"
2818 :group 'org-todo
2819 :group 'org-progress
2820 :type '(choice
2821 (const :tag "No logging" nil)
2822 (const :tag "Record timestamp" time)
2823 (const :tag "Record timestamp with note." note)))
2825 (defcustom org-log-redeadline nil
2826 "Information to record when the deadline date of a tasks is modified.
2828 Possible values are:
2830 nil Don't add anything, just change the date
2831 time Add a time stamp to the task
2832 note Prompt for a note and add it with template `org-log-note-headings'
2834 This option can also be set with on a per-file-basis with
2836 #+STARTUP: nologredeadline
2837 #+STARTUP: logredeadline
2838 #+STARTUP: lognoteredeadline
2840 You can have local logging settings for a subtree by setting the LOGGING
2841 property to one or more of these keywords."
2842 :group 'org-todo
2843 :group 'org-progress
2844 :type '(choice
2845 (const :tag "No logging" nil)
2846 (const :tag "Record timestamp" time)
2847 (const :tag "Record timestamp with note." note)))
2849 (defcustom org-log-note-clock-out nil
2850 "Non-nil means record a note when clocking out of an item.
2851 This can also be configured on a per-file basis by adding one of
2852 the following lines anywhere in the buffer:
2854 #+STARTUP: lognoteclock-out
2855 #+STARTUP: nolognoteclock-out"
2856 :group 'org-todo
2857 :group 'org-progress
2858 :type 'boolean)
2860 (defcustom org-log-done-with-time t
2861 "Non-nil means the CLOSED time stamp will contain date and time.
2862 When nil, only the date will be recorded."
2863 :group 'org-progress
2864 :type 'boolean)
2866 (defcustom org-log-note-headings
2867 '((done . "CLOSING NOTE %t")
2868 (state . "State %-12s from %-12S %t")
2869 (note . "Note taken on %t")
2870 (reschedule . "Rescheduled from %S on %t")
2871 (delschedule . "Not scheduled, was %S on %t")
2872 (redeadline . "New deadline from %S on %t")
2873 (deldeadline . "Removed deadline, was %S on %t")
2874 (refile . "Refiled on %t")
2875 (clock-out . ""))
2876 "Headings for notes added to entries.
2878 The value is an alist, with the car being a symbol indicating the
2879 note context, and the cdr is the heading to be used. The heading
2880 may also be the empty string. The following placeholders can be
2881 used:
2883 %t a time stamp.
2884 %T an active time stamp instead the default inactive one
2885 %d a short-format time stamp.
2886 %D an active short-format time stamp.
2887 %s the new TODO state or time stamp (inactive), in double quotes.
2888 %S the old TODO state or time stamp (inactive), in double quotes.
2889 %u the user name.
2890 %U full user name.
2892 In fact, it is not a good idea to change the `state' entry,
2893 because Agenda Log mode depends on the format of these entries."
2894 :group 'org-todo
2895 :group 'org-progress
2896 :type '(list :greedy t
2897 (cons (const :tag "Heading when closing an item" done) string)
2898 (cons (const :tag
2899 "Heading when changing todo state (todo sequence only)"
2900 state) string)
2901 (cons (const :tag "Heading when just taking a note" note) string)
2902 (cons (const :tag "Heading when rescheduling" reschedule) string)
2903 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2904 (cons (const :tag "Heading when changing deadline" redeadline) string)
2905 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2906 (cons (const :tag "Heading when refiling" refile) string)
2907 (cons (const :tag "Heading when clocking out" clock-out) string)))
2909 (unless (assq 'note org-log-note-headings)
2910 (push '(note . "%t") org-log-note-headings))
2912 (defcustom org-log-into-drawer nil
2913 "Non-nil means insert state change notes and time stamps into a drawer.
2914 When nil, state changes notes will be inserted after the headline and
2915 any scheduling and clock lines, but not inside a drawer.
2917 The value of this variable should be the name of the drawer to use.
2918 LOGBOOK is proposed as the default drawer for this purpose, you can
2919 also set this to a string to define the drawer of your choice.
2921 A value of t is also allowed, representing \"LOGBOOK\".
2923 A value of t or nil can also be set with on a per-file-basis with
2925 #+STARTUP: logdrawer
2926 #+STARTUP: nologdrawer
2928 If this variable is set, `org-log-state-notes-insert-after-drawers'
2929 will be ignored.
2931 You can set the property LOG_INTO_DRAWER to overrule this setting for
2932 a subtree.
2934 Do not check directly this variable in a Lisp program. Call
2935 function `org-log-into-drawer' instead."
2936 :group 'org-todo
2937 :group 'org-progress
2938 :type '(choice
2939 (const :tag "Not into a drawer" nil)
2940 (const :tag "LOGBOOK" t)
2941 (string :tag "Other")))
2943 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2945 (defun org-log-into-drawer ()
2946 "Name of the log drawer, as a string, or nil.
2947 This is the value of `org-log-into-drawer'. However, if the
2948 current entry has or inherits a LOG_INTO_DRAWER property, it will
2949 be used instead of the default value."
2950 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2951 (cond ((equal p "nil") nil)
2952 ((equal p "t") "LOGBOOK")
2953 ((stringp p) p)
2954 (p "LOGBOOK")
2955 ((stringp org-log-into-drawer) org-log-into-drawer)
2956 (org-log-into-drawer "LOGBOOK"))))
2958 (defcustom org-log-state-notes-insert-after-drawers nil
2959 "Non-nil means insert state change notes after any drawers in entry.
2960 Only the drawers that *immediately* follow the headline and the
2961 deadline/scheduled line are skipped.
2962 When nil, insert notes right after the heading and perhaps the line
2963 with deadline/scheduling if present.
2965 This variable will have no effect if `org-log-into-drawer' is
2966 set."
2967 :group 'org-todo
2968 :group 'org-progress
2969 :type 'boolean)
2971 (defcustom org-log-states-order-reversed t
2972 "Non-nil means the latest state note will be directly after heading.
2973 When nil, the state change notes will be ordered according to time.
2975 This option can also be set with on a per-file-basis with
2977 #+STARTUP: logstatesreversed
2978 #+STARTUP: nologstatesreversed"
2979 :group 'org-todo
2980 :group 'org-progress
2981 :type 'boolean)
2983 (defcustom org-todo-repeat-to-state nil
2984 "The TODO state to which a repeater should return the repeating task.
2985 By default this is the first task in a TODO sequence, or the previous state
2986 in a TODO_TYP set. But you can specify another task here.
2987 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2988 :group 'org-todo
2989 :version "24.1"
2990 :type '(choice (const :tag "Head of sequence" nil)
2991 (string :tag "Specific state")))
2993 (defcustom org-log-repeat 'time
2994 "Non-nil means record moving through the DONE state when triggering repeat.
2995 An auto-repeating task is immediately switched back to TODO when
2996 marked DONE. If you are not logging state changes (by adding \"@\"
2997 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2998 record a closing note, there will be no record of the task moving
2999 through DONE. This variable forces taking a note anyway.
3001 nil Don't force a record
3002 time Record a time stamp
3003 note Prompt for a note and add it with template `org-log-note-headings'
3005 This option can also be set with on a per-file-basis with
3007 #+STARTUP: nologrepeat
3008 #+STARTUP: logrepeat
3009 #+STARTUP: lognoterepeat
3011 You can have local logging settings for a subtree by setting the LOGGING
3012 property to one or more of these keywords."
3013 :group 'org-todo
3014 :group 'org-progress
3015 :type '(choice
3016 (const :tag "Don't force a record" nil)
3017 (const :tag "Force recording the DONE state" time)
3018 (const :tag "Force recording a note with the DONE state" note)))
3021 (defgroup org-priorities nil
3022 "Priorities in Org-mode."
3023 :tag "Org Priorities"
3024 :group 'org-todo)
3026 (defcustom org-enable-priority-commands t
3027 "Non-nil means priority commands are active.
3028 When nil, these commands will be disabled, so that you never accidentally
3029 set a priority."
3030 :group 'org-priorities
3031 :type 'boolean)
3033 (defcustom org-highest-priority ?A
3034 "The highest priority of TODO items. A character like ?A, ?B etc.
3035 Must have a smaller ASCII number than `org-lowest-priority'."
3036 :group 'org-priorities
3037 :type 'character)
3039 (defcustom org-lowest-priority ?C
3040 "The lowest priority of TODO items. A character like ?A, ?B etc.
3041 Must have a larger ASCII number than `org-highest-priority'."
3042 :group 'org-priorities
3043 :type 'character)
3045 (defcustom org-default-priority ?B
3046 "The default priority of TODO items.
3047 This is the priority an item gets if no explicit priority is given.
3048 When starting to cycle on an empty priority the first step in the cycle
3049 depends on `org-priority-start-cycle-with-default'. The resulting first
3050 step priority must not exceed the range from `org-highest-priority' to
3051 `org-lowest-priority' which means that `org-default-priority' has to be
3052 in this range exclusive or inclusive the range boundaries. Else the
3053 first step refuses to set the default and the second will fall back
3054 to (depending on the command used) the highest or lowest priority."
3055 :group 'org-priorities
3056 :type 'character)
3058 (defcustom org-priority-start-cycle-with-default t
3059 "Non-nil means start with default priority when starting to cycle.
3060 When this is nil, the first step in the cycle will be (depending on the
3061 command used) one higher or lower than the default priority.
3062 See also `org-default-priority'."
3063 :group 'org-priorities
3064 :type 'boolean)
3066 (defcustom org-get-priority-function nil
3067 "Function to extract the priority from a string.
3068 The string is normally the headline. If this is nil Org computes the
3069 priority from the priority cookie like [#A] in the headline. It returns
3070 an integer, increasing by 1000 for each priority level.
3071 The user can set a different function here, which should take a string
3072 as an argument and return the numeric priority."
3073 :group 'org-priorities
3074 :version "24.1"
3075 :type '(choice
3076 (const nil)
3077 (function)))
3079 (defgroup org-time nil
3080 "Options concerning time stamps and deadlines in Org-mode."
3081 :tag "Org Time"
3082 :group 'org)
3084 (defcustom org-time-stamp-rounding-minutes '(0 5)
3085 "Number of minutes to round time stamps to.
3086 \\<org-mode-map>\
3087 These are two values, the first applies when first creating a time stamp.
3088 The second applies when changing it with the commands `S-up' and `S-down'.
3089 When changing the time stamp, this means that it will change in steps
3090 of N minutes, as given by the second value.
3092 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3093 numbers should be factors of 60, so for example 5, 10, 15.
3095 When this is larger than 1, you can still force an exact time stamp by using
3096 a double prefix argument to a time stamp command like \
3097 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3098 and by using a prefix arg to `S-up/down' to specify the exact number
3099 of minutes to shift."
3100 :group 'org-time
3101 :get (lambda (var) ; Make sure both elements are there
3102 (if (integerp (default-value var))
3103 (list (default-value var) 5)
3104 (default-value var)))
3105 :type '(list
3106 (integer :tag "when inserting times")
3107 (integer :tag "when modifying times")))
3109 ;; Normalize old customizations of this variable.
3110 (when (integerp org-time-stamp-rounding-minutes)
3111 (setq org-time-stamp-rounding-minutes
3112 (list org-time-stamp-rounding-minutes
3113 org-time-stamp-rounding-minutes)))
3115 (defcustom org-display-custom-times nil
3116 "Non-nil means overlay custom formats over all time stamps.
3117 The formats are defined through the variable `org-time-stamp-custom-formats'.
3118 To turn this on on a per-file basis, insert anywhere in the file:
3119 #+STARTUP: customtime"
3120 :group 'org-time
3121 :set 'set-default
3122 :type 'sexp)
3123 (make-variable-buffer-local 'org-display-custom-times)
3125 (defcustom org-time-stamp-custom-formats
3126 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3127 "Custom formats for time stamps. See `format-time-string' for the syntax.
3128 These are overlaid over the default ISO format if the variable
3129 `org-display-custom-times' is set. Time like %H:%M should be at the
3130 end of the second format. The custom formats are also honored by export
3131 commands, if custom time display is turned on at the time of export."
3132 :group 'org-time
3133 :type 'sexp)
3135 (defun org-time-stamp-format (&optional long inactive)
3136 "Get the right format for a time string."
3137 (let ((f (if long (cdr org-time-stamp-formats)
3138 (car org-time-stamp-formats))))
3139 (if inactive
3140 (concat "[" (substring f 1 -1) "]")
3141 f)))
3143 (defcustom org-time-clocksum-format
3144 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3145 "The format string used when creating CLOCKSUM lines.
3146 This is also used when Org mode generates a time duration.
3148 The value can be a single format string containing two
3149 %-sequences, which will be filled with the number of hours and
3150 minutes in that order.
3152 Alternatively, the value can be a plist associating any of the
3153 keys :years, :months, :weeks, :days, :hours or :minutes with
3154 format strings. The time duration is formatted using only the
3155 time components that are needed and concatenating the results.
3156 If a time unit in absent, it falls back to the next smallest
3157 unit.
3159 The keys :require-years, :require-months, :require-days,
3160 :require-weeks, :require-hours, :require-minutes are also
3161 meaningful. A non-nil value for these keys indicates that the
3162 corresponding time component should always be included, even if
3163 its value is 0.
3166 For example,
3168 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3169 :require-minutes t)
3171 means durations longer than a day will be expressed in days,
3172 hours and minutes, and durations less than a day will always be
3173 expressed in hours and minutes (even for durations less than an
3174 hour).
3176 The value
3178 (:days \"%dd\" :minutes \"%dm\")
3180 means durations longer than a day will be expressed in days and
3181 minutes, and durations less than a day will be expressed entirely
3182 in minutes (even for durations longer than an hour)."
3183 :group 'org-time
3184 :group 'org-clock
3185 :version "24.4"
3186 :package-version '(Org . "8.0")
3187 :type '(choice (string :tag "Format string")
3188 (set :tag "Plist"
3189 (group :inline t (const :tag "Years" :years)
3190 (string :tag "Format string"))
3191 (group :inline t
3192 (const :tag "Always show years" :require-years)
3193 (const t))
3194 (group :inline t (const :tag "Months" :months)
3195 (string :tag "Format string"))
3196 (group :inline t
3197 (const :tag "Always show months" :require-months)
3198 (const t))
3199 (group :inline t (const :tag "Weeks" :weeks)
3200 (string :tag "Format string"))
3201 (group :inline t
3202 (const :tag "Always show weeks" :require-weeks)
3203 (const t))
3204 (group :inline t (const :tag "Days" :days)
3205 (string :tag "Format string"))
3206 (group :inline t
3207 (const :tag "Always show days" :require-days)
3208 (const t))
3209 (group :inline t (const :tag "Hours" :hours)
3210 (string :tag "Format string"))
3211 (group :inline t
3212 (const :tag "Always show hours" :require-hours)
3213 (const t))
3214 (group :inline t (const :tag "Minutes" :minutes)
3215 (string :tag "Format string"))
3216 (group :inline t
3217 (const :tag "Always show minutes" :require-minutes)
3218 (const t)))))
3220 (defcustom org-time-clocksum-use-fractional nil
3221 "When non-nil, \\[org-clock-display] uses fractional times.
3222 See `org-time-clocksum-format' for more on time clock formats."
3223 :group 'org-time
3224 :group 'org-clock
3225 :version "24.3"
3226 :type 'boolean)
3228 (defcustom org-time-clocksum-use-effort-durations nil
3229 "When non-nil, \\[org-clock-display] uses effort durations.
3230 E.g. by default, one day is considered to be a 8 hours effort,
3231 so a task that has been clocked for 16 hours will be displayed
3232 as during 2 days in the clock display or in the clocktable.
3234 See `org-effort-durations' on how to set effort durations
3235 and `org-time-clocksum-format' for more on time clock formats."
3236 :group 'org-time
3237 :group 'org-clock
3238 :version "24.4"
3239 :package-version '(Org . "8.0")
3240 :type 'boolean)
3242 (defcustom org-time-clocksum-fractional-format "%.2f"
3243 "The format string used when creating CLOCKSUM lines,
3244 or when Org mode generates a time duration, if
3245 `org-time-clocksum-use-fractional' is enabled.
3247 The value can be a single format string containing one
3248 %-sequence, which will be filled with the number of hours as
3249 a float.
3251 Alternatively, the value can be a plist associating any of the
3252 keys :years, :months, :weeks, :days, :hours or :minutes with
3253 a format string. The time duration is formatted using the
3254 largest time unit which gives a non-zero integer part. If all
3255 specified formats have zero integer part, the smallest time unit
3256 is used."
3257 :group 'org-time
3258 :type '(choice (string :tag "Format string")
3259 (set (group :inline t (const :tag "Years" :years)
3260 (string :tag "Format string"))
3261 (group :inline t (const :tag "Months" :months)
3262 (string :tag "Format string"))
3263 (group :inline t (const :tag "Weeks" :weeks)
3264 (string :tag "Format string"))
3265 (group :inline t (const :tag "Days" :days)
3266 (string :tag "Format string"))
3267 (group :inline t (const :tag "Hours" :hours)
3268 (string :tag "Format string"))
3269 (group :inline t (const :tag "Minutes" :minutes)
3270 (string :tag "Format string")))))
3272 (defcustom org-deadline-warning-days 14
3273 "Number of days before expiration during which a deadline becomes active.
3274 This variable governs the display in sparse trees and in the agenda.
3275 When 0 or negative, it means use this number (the absolute value of it)
3276 even if a deadline has a different individual lead time specified.
3278 Custom commands can set this variable in the options section."
3279 :group 'org-time
3280 :group 'org-agenda-daily/weekly
3281 :type 'integer)
3283 (defcustom org-scheduled-delay-days 0
3284 "Number of days before a scheduled item becomes active.
3285 This variable governs the display in sparse trees and in the agenda.
3286 The default value (i.e. 0) means: don't delay scheduled item.
3287 When negative, it means use this number (the absolute value of it)
3288 even if a scheduled item has a different individual delay time
3289 specified.
3291 Custom commands can set this variable in the options section."
3292 :group 'org-time
3293 :group 'org-agenda-daily/weekly
3294 :version "24.4"
3295 :package-version '(Org . "8.0")
3296 :type 'integer)
3298 (defcustom org-read-date-prefer-future t
3299 "Non-nil means assume future for incomplete date input from user.
3300 This affects the following situations:
3301 1. The user gives a month but not a year.
3302 For example, if it is April and you enter \"feb 2\", this will be read
3303 as Feb 2, *next* year. \"May 5\", however, will be this year.
3304 2. The user gives a day, but no month.
3305 For example, if today is the 15th, and you enter \"3\", Org-mode will
3306 read this as the third of *next* month. However, if you enter \"17\",
3307 it will be considered as *this* month.
3309 If you set this variable to the symbol `time', then also the following
3310 will work:
3312 3. If the user gives a time.
3313 If the time is before now, it will be interpreted as tomorrow.
3315 Currently none of this works for ISO week specifications.
3317 When this option is nil, the current day, month and year will always be
3318 used as defaults.
3320 See also `org-agenda-jump-prefer-future'."
3321 :group 'org-time
3322 :type '(choice
3323 (const :tag "Never" nil)
3324 (const :tag "Check month and day" t)
3325 (const :tag "Check month, day, and time" time)))
3327 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3328 "Should the agenda jump command prefer the future for incomplete dates?
3329 The default is to do the same as configured in `org-read-date-prefer-future'.
3330 But you can also set a deviating value here.
3331 This may t or nil, or the symbol `org-read-date-prefer-future'."
3332 :group 'org-agenda
3333 :group 'org-time
3334 :version "24.1"
3335 :type '(choice
3336 (const :tag "Use org-read-date-prefer-future"
3337 org-read-date-prefer-future)
3338 (const :tag "Never" nil)
3339 (const :tag "Always" t)))
3341 (defcustom org-read-date-force-compatible-dates t
3342 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3344 Depending on the system Emacs is running on, certain dates cannot
3345 be represented with the type used internally to represent time.
3346 Dates between 1970-1-1 and 2038-1-1 can always be represented
3347 correctly. Some systems allow for earlier dates, some for later,
3348 some for both. One way to find out it to insert any date into an
3349 Org buffer, putting the cursor on the year and hitting S-up and
3350 S-down to test the range.
3352 When this variable is set to t, the date/time prompt will not let
3353 you specify dates outside the 1970-2037 range, so it is certain that
3354 these dates will work in whatever version of Emacs you are
3355 running, and also that you can move a file from one Emacs implementation
3356 to another. WHenever Org is forcing the year for you, it will display
3357 a message and beep.
3359 When this variable is nil, Org will check if the date is
3360 representable in the specific Emacs implementation you are using.
3361 If not, it will force a year, usually the current year, and beep
3362 to remind you. Currently this setting is not recommended because
3363 the likelihood that you will open your Org files in an Emacs that
3364 has limited date range is not negligible.
3366 A workaround for this problem is to use diary sexp dates for time
3367 stamps outside of this range."
3368 :group 'org-time
3369 :version "24.1"
3370 :type 'boolean)
3372 (defcustom org-read-date-display-live t
3373 "Non-nil means display current interpretation of date prompt live.
3374 This display will be in an overlay, in the minibuffer."
3375 :group 'org-time
3376 :type 'boolean)
3378 (defcustom org-read-date-popup-calendar t
3379 "Non-nil means pop up a calendar when prompting for a date.
3380 In the calendar, the date can be selected with mouse-1. However, the
3381 minibuffer will also be active, and you can simply enter the date as well.
3382 When nil, only the minibuffer will be available."
3383 :group 'org-time
3384 :type 'boolean)
3385 (org-defvaralias 'org-popup-calendar-for-date-prompt
3386 'org-read-date-popup-calendar)
3388 (make-obsolete-variable
3389 'org-read-date-minibuffer-setup-hook
3390 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3391 (defcustom org-read-date-minibuffer-setup-hook nil
3392 "Hook to be used to set up keys for the date/time interface.
3393 Add key definitions to `minibuffer-local-map', which will be a
3394 temporary copy.
3396 WARNING: This option is obsolete, you should use
3397 `org-read-date-minibuffer-local-map' to set up keys."
3398 :group 'org-time
3399 :type 'hook)
3401 (defcustom org-extend-today-until 0
3402 "The hour when your day really ends. Must be an integer.
3403 This has influence for the following applications:
3404 - When switching the agenda to \"today\". It it is still earlier than
3405 the time given here, the day recognized as TODAY is actually yesterday.
3406 - When a date is read from the user and it is still before the time given
3407 here, the current date and time will be assumed to be yesterday, 23:59.
3408 Also, timestamps inserted in capture templates follow this rule.
3410 IMPORTANT: This is a feature whose implementation is and likely will
3411 remain incomplete. Really, it is only here because past midnight seems to
3412 be the favorite working time of John Wiegley :-)"
3413 :group 'org-time
3414 :type 'integer)
3416 (defcustom org-use-effective-time nil
3417 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3418 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3419 \"effective time\" of any timestamps between midnight and 8am will be
3420 23:59 of the previous day."
3421 :group 'org-time
3422 :version "24.1"
3423 :type 'boolean)
3425 (defcustom org-use-last-clock-out-time-as-effective-time nil
3426 "When non-nil, use the last clock out time for `org-todo'.
3427 Note that this option has precedence over the combined use of
3428 `org-use-effective-time' and `org-extend-today-until'."
3429 :group 'org-time
3430 :version "24.4"
3431 :package-version '(Org . "8.0")
3432 :type 'boolean)
3434 (defcustom org-edit-timestamp-down-means-later nil
3435 "Non-nil means S-down will increase the time in a time stamp.
3436 When nil, S-up will increase."
3437 :group 'org-time
3438 :type 'boolean)
3440 (defcustom org-calendar-follow-timestamp-change t
3441 "Non-nil means make the calendar window follow timestamp changes.
3442 When a timestamp is modified and the calendar window is visible, it will be
3443 moved to the new date."
3444 :group 'org-time
3445 :type 'boolean)
3447 (defgroup org-tags nil
3448 "Options concerning tags in Org-mode."
3449 :tag "Org Tags"
3450 :group 'org)
3452 (defcustom org-tag-alist nil
3453 "Default tags available in Org files.
3455 The value of this variable is an alist. Associations either:
3457 (TAG)
3458 (TAG . SELECT)
3459 (SPECIAL)
3461 where TAG is a tag as a string, SELECT is a character, used to
3462 select that tag through the fast tag selection interface, and
3463 SPECIAL is one of the following keywords: `:startgroup',
3464 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3465 `:newline'. These keywords are used to define a hierarchy of
3466 tags. See manual for details.
3468 When this variable is nil, Org mode bases tag input on what is
3469 already in the buffer. The value can be overridden locally by
3470 using a TAGS keyword, e.g.,
3472 #+TAGS: tag1 tag2
3474 See also `org-tag-persistent-alist' to sidestep this behavior."
3475 :group 'org-tags
3476 :type '(repeat
3477 (choice
3478 (cons (string :tag "Tag name")
3479 (character :tag "Access char"))
3480 (const :tag "Start radio group" (:startgroup))
3481 (const :tag "Start tag group, non distinct" (:startgrouptag))
3482 (const :tag "Group tags delimiter" (:grouptags))
3483 (const :tag "End radio group" (:endgroup))
3484 (const :tag "End tag group, non distinct" (:endgrouptag))
3485 (const :tag "New line" (:newline)))))
3487 (defcustom org-tag-persistent-alist nil
3488 "Tags always available in Org files.
3490 The value of this variable is an alist. Associations either:
3492 (TAG)
3493 (TAG . SELECT)
3494 (SPECIAL)
3496 where TAG is a tag as a string, SELECT is a character, used to
3497 select that tag through the fast tag selection interface, and
3498 SPECIAL is one of the following keywords: `:startgroup',
3499 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3500 `:newline'. These keywords are used to define a hierarchy of
3501 tags. See manual for details.
3503 Unlike to `org-tag-alist', tags defined in this variable do not
3504 depend on a local TAGS keyword. Instead, to disable these tags
3505 on a per-file basis, insert anywhere in the file:
3507 #+STARTUP: noptag"
3508 :group 'org-tags
3509 :type '(repeat
3510 (choice
3511 (cons (string :tag "Tag name")
3512 (character :tag "Access char"))
3513 (const :tag "Start radio group" (:startgroup))
3514 (const :tag "Start tag group, non distinct" (:startgrouptag))
3515 (const :tag "Group tags delimiter" (:grouptags))
3516 (const :tag "End radio group" (:endgroup))
3517 (const :tag "End tag group, non distinct" (:endgrouptag))
3518 (const :tag "New line" (:newline)))))
3520 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3521 "If non-nil, always offer completion for all tags of all agenda files.
3522 Instead of customizing this variable directly, you might want to
3523 set it locally for capture buffers, because there no list of
3524 tags in that file can be created dynamically (there are none).
3526 (add-hook \\='org-capture-mode-hook
3527 (lambda ()
3528 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3529 :group 'org-tags
3530 :version "24.1"
3531 :type 'boolean)
3533 (defvar org-file-tags nil
3534 "List of tags that can be inherited by all entries in the file.
3535 The tags will be inherited if the variable `org-use-tag-inheritance'
3536 says they should be.
3537 This variable is populated from #+FILETAGS lines.")
3539 (defcustom org-use-fast-tag-selection 'auto
3540 "Non-nil means use fast tag selection scheme.
3541 This is a special interface to select and deselect tags with single keys.
3542 When nil, fast selection is never used.
3543 When the symbol `auto', fast selection is used if and only if selection
3544 characters for tags have been configured, either through the variable
3545 `org-tag-alist' or through a #+TAGS line in the buffer.
3546 When t, fast selection is always used and selection keys are assigned
3547 automatically if necessary."
3548 :group 'org-tags
3549 :type '(choice
3550 (const :tag "Always" t)
3551 (const :tag "Never" nil)
3552 (const :tag "When selection characters are configured" auto)))
3554 (defcustom org-fast-tag-selection-single-key nil
3555 "Non-nil means fast tag selection exits after first change.
3556 When nil, you have to press RET to exit it.
3557 During fast tag selection, you can toggle this flag with `C-c'.
3558 This variable can also have the value `expert'. In this case, the window
3559 displaying the tags menu is not even shown, until you press C-c again."
3560 :group 'org-tags
3561 :type '(choice
3562 (const :tag "No" nil)
3563 (const :tag "Yes" t)
3564 (const :tag "Expert" expert)))
3566 (defvar org-fast-tag-selection-include-todo nil
3567 "Non-nil means fast tags selection interface will also offer TODO states.
3568 This is an undocumented feature, you should not rely on it.")
3570 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3571 "The column to which tags should be indented in a headline.
3572 If this number is positive, it specifies the column. If it is negative,
3573 it means that the tags should be flushright to that column. For example,
3574 -80 works well for a normal 80 character screen.
3575 When 0, place tags directly after headline text, with only one space in
3576 between."
3577 :group 'org-tags
3578 :type 'integer)
3580 (defcustom org-auto-align-tags t
3581 "Non-nil keeps tags aligned when modifying headlines.
3582 Some operations (i.e. demoting) change the length of a headline and
3583 therefore shift the tags around. With this option turned on, after
3584 each such operation the tags are again aligned to `org-tags-column'."
3585 :group 'org-tags
3586 :type 'boolean)
3588 (defcustom org-use-tag-inheritance t
3589 "Non-nil means tags in levels apply also for sublevels.
3590 When nil, only the tags directly given in a specific line apply there.
3591 This may also be a list of tags that should be inherited, or a regexp that
3592 matches tags that should be inherited. Additional control is possible
3593 with the variable `org-tags-exclude-from-inheritance' which gives an
3594 explicit list of tags to be excluded from inheritance, even if the value of
3595 `org-use-tag-inheritance' would select it for inheritance.
3597 If this option is t, a match early-on in a tree can lead to a large
3598 number of matches in the subtree when constructing the agenda or creating
3599 a sparse tree. If you only want to see the first match in a tree during
3600 a search, check out the variable `org-tags-match-list-sublevels'."
3601 :group 'org-tags
3602 :type '(choice
3603 (const :tag "Not" nil)
3604 (const :tag "Always" t)
3605 (repeat :tag "Specific tags" (string :tag "Tag"))
3606 (regexp :tag "Tags matched by regexp")))
3608 (defcustom org-tags-exclude-from-inheritance nil
3609 "List of tags that should never be inherited.
3610 This is a way to exclude a few tags from inheritance. For way to do
3611 the opposite, to actively allow inheritance for selected tags,
3612 see the variable `org-use-tag-inheritance'."
3613 :group 'org-tags
3614 :type '(repeat (string :tag "Tag")))
3616 (defun org-tag-inherit-p (tag)
3617 "Check if TAG is one that should be inherited."
3618 (cond
3619 ((member tag org-tags-exclude-from-inheritance) nil)
3620 ((eq org-use-tag-inheritance t) t)
3621 ((not org-use-tag-inheritance) nil)
3622 ((stringp org-use-tag-inheritance)
3623 (string-match org-use-tag-inheritance tag))
3624 ((listp org-use-tag-inheritance)
3625 (member tag org-use-tag-inheritance))
3626 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3628 (defcustom org-tags-match-list-sublevels t
3629 "Non-nil means list also sublevels of headlines matching a search.
3630 This variable applies to tags/property searches, and also to stuck
3631 projects because this search is based on a tags match as well.
3633 When set to the symbol `indented', sublevels are indented with
3634 leading dots.
3636 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3637 the sublevels of a headline matching a tag search often also match
3638 the same search. Listing all of them can create very long lists.
3639 Setting this variable to nil causes subtrees of a match to be skipped.
3641 This variable is semi-obsolete and probably should always be true. It
3642 is better to limit inheritance to certain tags using the variables
3643 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3644 :group 'org-tags
3645 :type '(choice
3646 (const :tag "No, don't list them" nil)
3647 (const :tag "Yes, do list them" t)
3648 (const :tag "List them, indented with leading dots" indented)))
3650 (defcustom org-tags-sort-function nil
3651 "When set, tags are sorted using this function as a comparator."
3652 :group 'org-tags
3653 :type '(choice
3654 (const :tag "No sorting" nil)
3655 (const :tag "Alphabetical" string<)
3656 (const :tag "Reverse alphabetical" string>)
3657 (function :tag "Custom function" nil)))
3659 (defvar org-tags-history nil
3660 "History of minibuffer reads for tags.")
3661 (defvar org-last-tags-completion-table nil
3662 "The last used completion table for tags.")
3663 (defvar org-after-tags-change-hook nil
3664 "Hook that is run after the tags in a line have changed.")
3666 (defgroup org-properties nil
3667 "Options concerning properties in Org-mode."
3668 :tag "Org Properties"
3669 :group 'org)
3671 (defcustom org-property-format "%-10s %s"
3672 "How property key/value pairs should be formatted by `indent-line'.
3673 When `indent-line' hits a property definition, it will format the line
3674 according to this format, mainly to make sure that the values are
3675 lined-up with respect to each other."
3676 :group 'org-properties
3677 :type 'string)
3679 (defcustom org-properties-postprocess-alist nil
3680 "Alist of properties and functions to adjust inserted values.
3681 Elements of this alist must be of the form
3683 ([string] [function])
3685 where [string] must be a property name and [function] must be a
3686 lambda expression: this lambda expression must take one argument,
3687 the value to adjust, and return the new value as a string.
3689 For example, this element will allow the property \"Remaining\"
3690 to be updated wrt the relation between the \"Effort\" property
3691 and the clock summary:
3693 ((\"Remaining\" (lambda(value)
3694 (let ((clocksum (org-clock-sum-current-item))
3695 (effort (org-duration-string-to-minutes
3696 (org-entry-get (point) \"Effort\"))))
3697 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3698 :group 'org-properties
3699 :version "24.1"
3700 :type '(alist :key-type (string :tag "Property")
3701 :value-type (function :tag "Function")))
3703 (defcustom org-use-property-inheritance nil
3704 "Non-nil means properties apply also for sublevels.
3706 This setting is chiefly used during property searches. Turning it on can
3707 cause significant overhead when doing a search, which is why it is not
3708 on by default.
3710 When nil, only the properties directly given in the current entry count.
3711 When t, every property is inherited. The value may also be a list of
3712 properties that should have inheritance, or a regular expression matching
3713 properties that should be inherited.
3715 However, note that some special properties use inheritance under special
3716 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3717 and the properties ending in \"_ALL\" when they are used as descriptor
3718 for valid values of a property.
3720 Note for programmers:
3721 When querying an entry with `org-entry-get', you can control if inheritance
3722 should be used. By default, `org-entry-get' looks only at the local
3723 properties. You can request inheritance by setting the inherit argument
3724 to t (to force inheritance) or to `selective' (to respect the setting
3725 in this variable)."
3726 :group 'org-properties
3727 :type '(choice
3728 (const :tag "Not" nil)
3729 (const :tag "Always" t)
3730 (repeat :tag "Specific properties" (string :tag "Property"))
3731 (regexp :tag "Properties matched by regexp")))
3733 (defun org-property-inherit-p (property)
3734 "Check if PROPERTY is one that should be inherited."
3735 (cond
3736 ((eq org-use-property-inheritance t) t)
3737 ((not org-use-property-inheritance) nil)
3738 ((stringp org-use-property-inheritance)
3739 (string-match org-use-property-inheritance property))
3740 ((listp org-use-property-inheritance)
3741 (member property org-use-property-inheritance))
3742 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3744 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3745 "The default column format, if no other format has been defined.
3746 This variable can be set on the per-file basis by inserting a line
3748 #+COLUMNS: %25ITEM ....."
3749 :group 'org-properties
3750 :type 'string)
3752 (defcustom org-columns-ellipses ".."
3753 "The ellipses to be used when a field in column view is truncated.
3754 When this is the empty string, as many characters as possible are shown,
3755 but then there will be no visual indication that the field has been truncated.
3756 When this is a string of length N, the last N characters of a truncated
3757 field are replaced by this string. If the column is narrower than the
3758 ellipses string, only part of the ellipses string will be shown."
3759 :group 'org-properties
3760 :type 'string)
3762 (defconst org-global-properties-fixed
3763 '(("VISIBILITY_ALL" . "folded children content all")
3764 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3765 "List of property/value pairs that can be inherited by any entry.
3767 These are fixed values, for the preset properties. The user variable
3768 that can be used to add to this list is `org-global-properties'.
3770 The entries in this list are cons cells where the car is a property
3771 name and cdr is a string with the value. If the value represents
3772 multiple items like an \"_ALL\" property, separate the items by
3773 spaces.")
3775 (defcustom org-global-properties nil
3776 "List of property/value pairs that can be inherited by any entry.
3778 This list will be combined with the constant `org-global-properties-fixed'.
3780 The entries in this list are cons cells where the car is a property
3781 name and cdr is a string with the value.
3783 You can set buffer-local values for the same purpose in the variable
3784 `org-file-properties' this by adding lines like
3786 #+PROPERTY: NAME VALUE"
3787 :group 'org-properties
3788 :type '(repeat
3789 (cons (string :tag "Property")
3790 (string :tag "Value"))))
3792 (defvar-local org-file-properties nil
3793 "List of property/value pairs that can be inherited by any entry.
3794 Valid for the current buffer.
3795 This variable is populated from #+PROPERTY lines.")
3797 (defgroup org-agenda nil
3798 "Options concerning agenda views in Org-mode."
3799 :tag "Org Agenda"
3800 :group 'org)
3802 (defvar-local org-category nil
3803 "Variable used by org files to set a category for agenda display.
3804 Such files should use a file variable to set it, for example
3806 # -*- mode: org; org-category: \"ELisp\"
3808 or contain a special line
3810 #+CATEGORY: ELisp
3812 If the file does not specify a category, then file's base name
3813 is used instead.")
3814 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3816 (defcustom org-agenda-files nil
3817 "The files to be used for agenda display.
3818 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3819 \\[org-remove-file]. You can also use customize to edit the list.
3821 If an entry is a directory, all files in that directory that are matched by
3822 `org-agenda-file-regexp' will be part of the file list.
3824 If the value of the variable is not a list but a single file name, then
3825 the list of agenda files is actually stored and maintained in that file, one
3826 agenda file per line. In this file paths can be given relative to
3827 `org-directory'. Tilde expansion and environment variable substitution
3828 are also made."
3829 :group 'org-agenda
3830 :type '(choice
3831 (repeat :tag "List of files and directories" file)
3832 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3834 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3835 "Regular expression to match files for `org-agenda-files'.
3836 If any element in the list in that variable contains a directory instead
3837 of a normal file, all files in that directory that are matched by this
3838 regular expression will be included."
3839 :group 'org-agenda
3840 :type 'regexp)
3842 (defcustom org-agenda-text-search-extra-files nil
3843 "List of extra files to be searched by text search commands.
3844 These files will be searched in addition to the agenda files by the
3845 commands `org-search-view' (`\\[org-agenda] s') \
3846 and `org-occur-in-agenda-files'.
3847 Note that these files will only be searched for text search commands,
3848 not for the other agenda views like todo lists, tag searches or the weekly
3849 agenda. This variable is intended to list notes and possibly archive files
3850 that should also be searched by these two commands.
3851 In fact, if the first element in the list is the symbol `agenda-archives',
3852 then all archive files of all agenda files will be added to the search
3853 scope."
3854 :group 'org-agenda
3855 :type '(set :greedy t
3856 (const :tag "Agenda Archives" agenda-archives)
3857 (repeat :inline t (file))))
3859 (org-defvaralias 'org-agenda-multi-occur-extra-files
3860 'org-agenda-text-search-extra-files)
3862 (defcustom org-agenda-skip-unavailable-files nil
3863 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3864 A nil value means to remove them, after a query, from the list."
3865 :group 'org-agenda
3866 :type 'boolean)
3868 (defcustom org-calendar-to-agenda-key [?c]
3869 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3870 The command `org-calendar-goto-agenda' will be bound to this key. The
3871 default is the character `c' because then `c' can be used to switch back and
3872 forth between agenda and calendar."
3873 :group 'org-agenda
3874 :type 'sexp)
3876 (defcustom org-calendar-insert-diary-entry-key [?i]
3877 "The key to be installed in `calendar-mode-map' for adding diary entries.
3878 This option is irrelevant until `org-agenda-diary-file' has been configured
3879 to point to an Org-mode file. When that is the case, the command
3880 `org-agenda-diary-entry' will be bound to the key given here, by default
3881 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3882 if you want to continue doing this, you need to change this to a different
3883 key."
3884 :group 'org-agenda
3885 :type 'sexp)
3887 (defcustom org-agenda-diary-file 'diary-file
3888 "File to which to add new entries with the `i' key in agenda and calendar.
3889 When this is the symbol `diary-file', the functionality in the Emacs
3890 calendar will be used to add entries to the `diary-file'. But when this
3891 points to a file, `org-agenda-diary-entry' will be used instead."
3892 :group 'org-agenda
3893 :type '(choice
3894 (const :tag "The standard Emacs diary file" diary-file)
3895 (file :tag "Special Org file diary entries")))
3897 (eval-after-load "calendar"
3898 '(progn
3899 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3900 'org-calendar-goto-agenda)
3901 (add-hook 'calendar-mode-hook
3902 (lambda ()
3903 (unless (eq org-agenda-diary-file 'diary-file)
3904 (define-key calendar-mode-map
3905 org-calendar-insert-diary-entry-key
3906 'org-agenda-diary-entry))))))
3908 (defgroup org-latex nil
3909 "Options for embedding LaTeX code into Org-mode."
3910 :tag "Org LaTeX"
3911 :group 'org)
3913 (defcustom org-format-latex-options
3914 '(:foreground default :background default :scale 1.0
3915 :html-foreground "Black" :html-background "Transparent"
3916 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3917 "Options for creating images from LaTeX fragments.
3918 This is a property list with the following properties:
3919 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3920 `default' means use the foreground of the default face.
3921 `auto' means use the foreground from the text face.
3922 :background the background color, or \"Transparent\".
3923 `default' means use the background of the default face.
3924 `auto' means use the background from the text face.
3925 :scale a scaling factor for the size of the images, to get more pixels
3926 :html-foreground, :html-background, :html-scale
3927 the same numbers for HTML export.
3928 :matchers a list indicating which matchers should be used to
3929 find LaTeX fragments. Valid members of this list are:
3930 \"begin\" find environments
3931 \"$1\" find single characters surrounded by $.$
3932 \"$\" find math expressions surrounded by $...$
3933 \"$$\" find math expressions surrounded by $$....$$
3934 \"\\(\" find math expressions surrounded by \\(...\\)
3935 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3936 :group 'org-latex
3937 :type 'plist)
3939 (defcustom org-format-latex-signal-error t
3940 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3941 When nil, just push out a message."
3942 :group 'org-latex
3943 :version "24.1"
3944 :type 'boolean)
3946 (defcustom org-latex-to-mathml-jar-file nil
3947 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3948 Use this to specify additional executable file say a jar file.
3950 When using MathToWeb as the converter, specify the full-path to
3951 your mathtoweb.jar file."
3952 :group 'org-latex
3953 :version "24.1"
3954 :type '(choice
3955 (const :tag "None" nil)
3956 (file :tag "JAR file" :must-match t)))
3958 (defcustom org-latex-to-mathml-convert-command nil
3959 "Command to convert LaTeX fragments to MathML.
3960 Replace format-specifiers in the command as noted below and use
3961 `shell-command' to convert LaTeX to MathML.
3962 %j: Executable file in fully expanded form as specified by
3963 `org-latex-to-mathml-jar-file'.
3964 %I: Input LaTeX file in fully expanded form.
3965 %i: The latex fragment to be converted.
3966 %o: Output MathML file.
3968 This command is used by `org-create-math-formula'.
3970 When using MathToWeb as the converter, set this option to
3971 \"java -jar %j -unicode -force -df %o %I\".
3973 When using LaTeXML set this option to
3974 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3975 :group 'org-latex
3976 :version "24.1"
3977 :type '(choice
3978 (const :tag "None" nil)
3979 (string :tag "\nShell command")))
3981 (defcustom org-latex-create-formula-image-program 'dvipng
3982 "Program to convert LaTeX fragments with.
3984 dvipng Process the LaTeX fragments to dvi file, then convert
3985 dvi files to png files using dvipng.
3986 This will also include processing of non-math environments.
3987 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3988 to convert pdf files to png files"
3989 :group 'org-latex
3990 :version "24.1"
3991 :type '(choice
3992 (const :tag "dvipng" dvipng)
3993 (const :tag "imagemagick" imagemagick)))
3995 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3996 "Path to store latex preview images.
3997 A relative path here creates many directories relative to the
3998 processed org files paths. An absolute path puts all preview
3999 images at the same place."
4000 :group 'org-latex
4001 :version "24.3"
4002 :type 'string)
4004 (defun org-format-latex-mathml-available-p ()
4005 "Return t if `org-latex-to-mathml-convert-command' is usable."
4006 (save-match-data
4007 (when (and (boundp 'org-latex-to-mathml-convert-command)
4008 org-latex-to-mathml-convert-command)
4009 (let ((executable (car (split-string
4010 org-latex-to-mathml-convert-command))))
4011 (when (executable-find executable)
4012 (if (string-match
4013 "%j" org-latex-to-mathml-convert-command)
4014 (file-readable-p org-latex-to-mathml-jar-file)
4015 t))))))
4017 (defcustom org-format-latex-header "\\documentclass{article}
4018 \\usepackage[usenames]{color}
4019 \[PACKAGES]
4020 \[DEFAULT-PACKAGES]
4021 \\pagestyle{empty} % do not remove
4022 % The settings below are copied from fullpage.sty
4023 \\setlength{\\textwidth}{\\paperwidth}
4024 \\addtolength{\\textwidth}{-3cm}
4025 \\setlength{\\oddsidemargin}{1.5cm}
4026 \\addtolength{\\oddsidemargin}{-2.54cm}
4027 \\setlength{\\evensidemargin}{\\oddsidemargin}
4028 \\setlength{\\textheight}{\\paperheight}
4029 \\addtolength{\\textheight}{-\\headheight}
4030 \\addtolength{\\textheight}{-\\headsep}
4031 \\addtolength{\\textheight}{-\\footskip}
4032 \\addtolength{\\textheight}{-3cm}
4033 \\setlength{\\topmargin}{1.5cm}
4034 \\addtolength{\\topmargin}{-2.54cm}"
4035 "The document header used for processing LaTeX fragments.
4036 It is imperative that this header make sure that no page number
4037 appears on the page. The package defined in the variables
4038 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4039 will either replace the placeholder \"[PACKAGES]\" in this
4040 header, or they will be appended."
4041 :group 'org-latex
4042 :type 'string)
4044 (defun org-set-packages-alist (var val)
4045 "Set the packages alist and make sure it has 3 elements per entry."
4046 (set var (mapcar (lambda (x)
4047 (if (and (consp x) (= (length x) 2))
4048 (list (car x) (nth 1 x) t)
4050 val)))
4052 (defun org-get-packages-alist (var)
4053 "Get the packages alist and make sure it has 3 elements per entry."
4054 (mapcar (lambda (x)
4055 (if (and (consp x) (= (length x) 2))
4056 (list (car x) (nth 1 x) t)
4058 (default-value var)))
4060 (defcustom org-latex-default-packages-alist
4061 '(("AUTO" "inputenc" t ("pdflatex"))
4062 ("T1" "fontenc" t ("pdflatex"))
4063 ("" "graphicx" t)
4064 ("" "grffile" t)
4065 ("" "longtable" nil)
4066 ("" "wrapfig" nil)
4067 ("" "rotating" nil)
4068 ("normalem" "ulem" t)
4069 ("" "amsmath" t)
4070 ("" "textcomp" t)
4071 ("" "amssymb" t)
4072 ("" "capt-of" nil)
4073 ("" "hyperref" nil))
4074 "Alist of default packages to be inserted in the header.
4076 Change this only if one of the packages here causes an
4077 incompatibility with another package you are using.
4079 The packages in this list are needed by one part or another of
4080 Org mode to function properly:
4082 - inputenc, fontenc: for basic font and character selection
4083 - graphicx: for including images
4084 - grffile: allow periods and spaces in graphics file names
4085 - longtable: For multipage tables
4086 - wrapfig: for figure placement
4087 - rotating: for sideways figures and tables
4088 - ulem: for underline and strike-through
4089 - amsmath: for subscript and superscript and math environments
4090 - textcomp, amssymb: for various symbols used
4091 for interpreting the entities in `org-entities'. You can skip
4092 some of these packages if you don't use any of their symbols.
4093 - capt-of: for captions outside of floats
4094 - hyperref: for cross references
4096 Therefore you should not modify this variable unless you know
4097 what you are doing. The one reason to change it anyway is that
4098 you might be loading some other package that conflicts with one
4099 of the default packages. Each element is either a cell or
4100 a string.
4102 A cell is of the format
4104 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4106 If SNIPPET-FLAG is non-nil, the package also needs to be included
4107 when compiling LaTeX snippets into images for inclusion into
4108 non-LaTeX output. COMPILERS is a list of compilers that should
4109 include the package, see `org-latex-compiler'. If the document
4110 compiler is not in the list, and the list is non-nil, the package
4111 will not be inserted in the final document.
4113 A string will be inserted as-is in the header of the document."
4114 :group 'org-latex
4115 :group 'org-export-latex
4116 :set 'org-set-packages-alist
4117 :get 'org-get-packages-alist
4118 :version "25.1"
4119 :package-version '(Org . "8.3")
4120 :type '(repeat
4121 (choice
4122 (list :tag "options/package pair"
4123 (string :tag "options")
4124 (string :tag "package")
4125 (boolean :tag "Snippet"))
4126 (string :tag "A line of LaTeX"))))
4128 (defcustom org-latex-packages-alist nil
4129 "Alist of packages to be inserted in every LaTeX header.
4131 These will be inserted after `org-latex-default-packages-alist'.
4132 Each element is either a cell or a string.
4134 A cell is of the format:
4136 (\"options\" \"package\" SNIPPET-FLAG)
4138 SNIPPET-FLAG, when non-nil, indicates that this package is also
4139 needed when turning LaTeX snippets into images for inclusion into
4140 non-LaTeX output.
4142 A string will be inserted as-is in the header of the document.
4144 Make sure that you only list packages here which:
4146 - you want in every file;
4147 - do not conflict with the setup in `org-format-latex-header';
4148 - do not conflict with the default packages in
4149 `org-latex-default-packages-alist'."
4150 :group 'org-latex
4151 :group 'org-export-latex
4152 :set 'org-set-packages-alist
4153 :get 'org-get-packages-alist
4154 :type '(repeat
4155 (choice
4156 (list :tag "options/package pair"
4157 (string :tag "options")
4158 (string :tag "package")
4159 (boolean :tag "Snippet"))
4160 (string :tag "A line of LaTeX"))))
4162 (defgroup org-appearance nil
4163 "Settings for Org-mode appearance."
4164 :tag "Org Appearance"
4165 :group 'org)
4167 (defcustom org-level-color-stars-only nil
4168 "Non-nil means fontify only the stars in each headline.
4169 When nil, the entire headline is fontified.
4170 Changing it requires restart of `font-lock-mode' to become effective
4171 also in regions already fontified."
4172 :group 'org-appearance
4173 :type 'boolean)
4175 (defcustom org-hide-leading-stars nil
4176 "Non-nil means hide the first N-1 stars in a headline.
4177 This works by using the face `org-hide' for these stars. This
4178 face is white for a light background, and black for a dark
4179 background. You may have to customize the face `org-hide' to
4180 make this work.
4181 Changing it requires restart of `font-lock-mode' to become effective
4182 also in regions already fontified.
4183 You may also set this on a per-file basis by adding one of the following
4184 lines to the buffer:
4186 #+STARTUP: hidestars
4187 #+STARTUP: showstars"
4188 :group 'org-appearance
4189 :type 'boolean)
4191 (defcustom org-hidden-keywords nil
4192 "List of symbols corresponding to keywords to be hidden the org buffer.
4193 For example, a value \\='(title) for this list will make the document's title
4194 appear in the buffer without the initial #+TITLE: keyword."
4195 :group 'org-appearance
4196 :version "24.1"
4197 :type '(set (const :tag "#+AUTHOR" author)
4198 (const :tag "#+DATE" date)
4199 (const :tag "#+EMAIL" email)
4200 (const :tag "#+TITLE" title)))
4202 (defcustom org-custom-properties nil
4203 "List of properties (as strings) with a special meaning.
4204 The default use of these custom properties is to let the user
4205 hide them with `org-toggle-custom-properties-visibility'."
4206 :group 'org-properties
4207 :group 'org-appearance
4208 :version "24.3"
4209 :type '(repeat (string :tag "Property Name")))
4211 (defcustom org-fontify-done-headline nil
4212 "Non-nil means change the face of a headline if it is marked DONE.
4213 Normally, only the TODO/DONE keyword indicates the state of a headline.
4214 When this is non-nil, the headline after the keyword is set to the
4215 `org-headline-done' as an additional indication."
4216 :group 'org-appearance
4217 :type 'boolean)
4219 (defcustom org-fontify-emphasized-text t
4220 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4221 Changing this variable requires a restart of Emacs to take effect."
4222 :group 'org-appearance
4223 :type 'boolean)
4225 (defcustom org-fontify-whole-heading-line nil
4226 "Non-nil means fontify the whole line for headings.
4227 This is useful when setting a background color for the
4228 org-level-* faces."
4229 :group 'org-appearance
4230 :type 'boolean)
4232 (defcustom org-highlight-latex-and-related nil
4233 "Non-nil means highlight LaTeX related syntax in the buffer.
4234 When non nil, the value should be a list containing any of the
4235 following symbols:
4236 `latex' Highlight LaTeX snippets and environments.
4237 `script' Highlight subscript and superscript.
4238 `entities' Highlight entities."
4239 :group 'org-appearance
4240 :version "24.4"
4241 :package-version '(Org . "8.0")
4242 :type '(choice
4243 (const :tag "No highlighting" nil)
4244 (set :greedy t :tag "Highlight"
4245 (const :tag "LaTeX snippets and environments" latex)
4246 (const :tag "Subscript and superscript" script)
4247 (const :tag "Entities" entities))))
4249 (defcustom org-hide-emphasis-markers nil
4250 "Non-nil mean font-lock should hide the emphasis marker characters."
4251 :group 'org-appearance
4252 :type 'boolean)
4254 (defcustom org-hide-macro-markers nil
4255 "Non-nil mean font-lock should hide the brackets marking macro calls."
4256 :group 'org-appearance
4257 :type 'boolean)
4259 (defcustom org-pretty-entities nil
4260 "Non-nil means show entities as UTF8 characters.
4261 When nil, the \\name form remains in the buffer."
4262 :group 'org-appearance
4263 :version "24.1"
4264 :type 'boolean)
4266 (defcustom org-pretty-entities-include-sub-superscripts t
4267 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4268 :group 'org-appearance
4269 :version "24.1"
4270 :type 'boolean)
4272 (defvar org-emph-re nil
4273 "Regular expression for matching emphasis.
4274 After a match, the match groups contain these elements:
4275 0 The match of the full regular expression, including the characters
4276 before and after the proper match
4277 1 The character before the proper match, or empty at beginning of line
4278 2 The proper match, including the leading and trailing markers
4279 3 The leading marker like * or /, indicating the type of highlighting
4280 4 The text between the emphasis markers, not including the markers
4281 5 The character after the match, empty at the end of a line")
4282 (defvar org-verbatim-re nil
4283 "Regular expression for matching verbatim text.")
4284 (defvar org-emphasis-regexp-components) ; defined just below
4285 (defvar org-emphasis-alist) ; defined just below
4286 (defun org-set-emph-re (var val)
4287 "Set variable and compute the emphasis regular expression."
4288 (set var val)
4289 (when (and (boundp 'org-emphasis-alist)
4290 (boundp 'org-emphasis-regexp-components)
4291 org-emphasis-alist org-emphasis-regexp-components)
4292 (let* ((e org-emphasis-regexp-components)
4293 (pre (car e))
4294 (post (nth 1 e))
4295 (border (nth 2 e))
4296 (body (nth 3 e))
4297 (nl (nth 4 e))
4298 (body1 (concat body "*?"))
4299 (markers (mapconcat 'car org-emphasis-alist ""))
4300 (vmarkers (mapconcat
4301 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4302 org-emphasis-alist "")))
4303 ;; make sure special characters appear at the right position in the class
4304 (if (string-match "\\^" markers)
4305 (setq markers (concat (replace-match "" t t markers) "^")))
4306 (if (string-match "-" markers)
4307 (setq markers (concat (replace-match "" t t markers) "-")))
4308 (if (string-match "\\^" vmarkers)
4309 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4310 (if (string-match "-" vmarkers)
4311 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4312 (if (> nl 0)
4313 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4314 (int-to-string nl) "\\}")))
4315 ;; Make the regexp
4316 (setq org-emph-re
4317 (concat "\\([" pre "]\\|^\\)"
4318 "\\("
4319 "\\([" markers "]\\)"
4320 "\\("
4321 "[^" border "]\\|"
4322 "[^" border "]"
4323 body1
4324 "[^" border "]"
4325 "\\)"
4326 "\\3\\)"
4327 "\\([" post "]\\|$\\)"))
4328 (setq org-verbatim-re
4329 (concat "\\([" pre "]\\|^\\)"
4330 "\\("
4331 "\\([" vmarkers "]\\)"
4332 "\\("
4333 "[^" border "]\\|"
4334 "[^" border "]"
4335 body1
4336 "[^" border "]"
4337 "\\)"
4338 "\\3\\)"
4339 "\\([" post "]\\|$\\)")))))
4341 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4342 ;; set this option proved cumbersome. See this message/thread:
4343 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4344 (defvar org-emphasis-regexp-components
4345 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4346 "Components used to build the regular expression for emphasis.
4347 This is a list with five entries. Terminology: In an emphasis string
4348 like \" *strong word* \", we call the initial space PREMATCH, the final
4349 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4350 and \"trong wor\" is the body. The different components in this variable
4351 specify what is allowed/forbidden in each part:
4353 pre Chars allowed as prematch. Beginning of line will be allowed too.
4354 post Chars allowed as postmatch. End of line will be allowed too.
4355 border The chars *forbidden* as border characters.
4356 body-regexp A regexp like \".\" to match a body character. Don't use
4357 non-shy groups here, and don't allow newline here.
4358 newline The maximum number of newlines allowed in an emphasis exp.
4360 You need to reload Org or to restart Emacs after customizing this.")
4362 (defcustom org-emphasis-alist
4363 `(("*" bold)
4364 ("/" italic)
4365 ("_" underline)
4366 ("=" org-verbatim verbatim)
4367 ("~" org-code verbatim)
4368 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4369 "Alist of characters and faces to emphasize text.
4370 Text starting and ending with a special character will be emphasized,
4371 for example *bold*, _underlined_ and /italic/. This variable sets the
4372 marker characters and the face to be used by font-lock for highlighting
4373 in Org-mode Emacs buffers.
4375 You need to reload Org or to restart Emacs after customizing this."
4376 :group 'org-appearance
4377 :set 'org-set-emph-re
4378 :version "24.4"
4379 :package-version '(Org . "8.0")
4380 :type '(repeat
4381 (list
4382 (string :tag "Marker character")
4383 (choice
4384 (face :tag "Font-lock-face")
4385 (plist :tag "Face property list"))
4386 (option (const verbatim)))))
4388 (defvar org-protecting-blocks '("src" "example" "export")
4389 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4390 This is needed for font-lock setup.")
4392 ;;; Functions and variables from their packages
4393 ;; Declared here to avoid compiler warnings
4395 ;; XEmacs only
4396 (defvar outline-mode-menu-heading)
4397 (defvar outline-mode-menu-show)
4398 (defvar outline-mode-menu-hide)
4399 (defvar zmacs-regions) ; XEmacs regions
4401 ;; Emacs only
4402 (defvar mark-active)
4404 ;; Various packages
4405 (declare-function calc-eval "calc" (str &optional separator &rest args))
4406 (declare-function calendar-forward-day "cal-move" (arg))
4407 (declare-function calendar-goto-date "cal-move" (date))
4408 (declare-function calendar-goto-today "cal-move" ())
4409 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4410 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4411 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4412 (declare-function cdlatex-tab "ext:cdlatex" ())
4413 (declare-function dired-get-filename
4414 "dired"
4415 (&optional localp no-error-if-not-filep))
4416 (declare-function iswitchb-read-buffer
4417 "iswitchb"
4418 (prompt &optional default require-match start matches-set))
4419 (declare-function org-agenda-change-all-lines
4420 "org-agenda"
4421 (newhead hdmarker &optional fixface just-this))
4422 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4423 "org-agenda"
4424 (&optional end))
4425 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4426 (declare-function org-agenda-format-item
4427 "org-agenda"
4428 (extra txt &optional level category tags dotime noprefix
4429 remove-re habitp))
4430 (declare-function org-agenda-maybe-redo "org-agenda" ())
4431 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4432 (declare-function org-agenda-save-markers-for-cut-and-paste
4433 "org-agenda"
4434 (beg end))
4435 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4436 (declare-function org-agenda-skip "org-agenda" ())
4437 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4438 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4439 (declare-function org-indent-mode "org-indent" (&optional arg))
4440 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4441 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4442 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4443 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4444 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4445 (declare-function parse-time-string "parse-time" (string))
4446 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4447 (declare-function table--at-cell-p
4448 "table"
4449 (position &optional object at-column))
4451 (defvar align-mode-rules-list)
4452 (defvar calc-embedded-close-formula)
4453 (defvar calc-embedded-open-formula)
4454 (defvar calc-embedded-open-mode)
4455 (defvar font-lock-unfontify-region-function)
4456 (defvar iswitchb-temp-buflist)
4457 (defvar org-agenda-tags-todo-honor-ignore-options)
4458 (defvar remember-data-file)
4459 (defvar texmathp-why)
4461 ;;;###autoload
4462 (defun turn-on-orgtbl ()
4463 "Unconditionally turn on `orgtbl-mode'."
4464 (require 'org-table)
4465 (orgtbl-mode 1))
4467 (defun org-at-table-p (&optional table-type)
4468 "Non-nil if the cursor is inside an Org table.
4469 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4470 If `org-enable-table-editor' is nil, return nil unconditionally."
4471 (and
4472 org-enable-table-editor
4473 (save-excursion
4474 (beginning-of-line)
4475 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4476 (or (not (derived-mode-p 'org-mode))
4477 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4478 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4479 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4481 (defun org-at-table.el-p ()
4482 "Non-nil when point is at a table.el table."
4483 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4484 (let ((element (org-element-at-point)))
4485 (and (eq (org-element-type element) 'table)
4486 (eq (org-element-property :type element) 'table.el)))))
4488 (defun org-table-recognize-table.el ()
4489 "If there is a table.el table nearby, recognize it and move into it."
4490 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4491 (beginning-of-line)
4492 (unless (or (looking-at org-table-dataline-regexp)
4493 (not (looking-at org-table1-hline-regexp)))
4494 (forward-line)
4495 (when (looking-at org-table-any-border-regexp)
4496 (forward-line -2)))
4497 (if (re-search-forward "|" (org-table-end t) t)
4498 (progn
4499 (require 'table)
4500 (if (table--at-cell-p (point)) t
4501 (message "recognizing table.el table...")
4502 (table-recognize-table)
4503 (message "recognizing table.el table...done")))
4504 (error "This should not happen"))))
4505 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4506 (make-obsolete 'org-table-recognize-table.el
4507 "please notify the org mailing list if you use this function."
4508 "Org 9.0")
4510 (defun org-at-table-hline-p ()
4511 "Non-nil when point is inside a hline in a table.
4512 Assume point is already in a table. If `org-enable-table-editor'
4513 is nil, return nil unconditionally."
4514 (and org-enable-table-editor
4515 (save-excursion
4516 (beginning-of-line)
4517 (looking-at org-table-hline-regexp))))
4519 (defun org-table-map-tables (function &optional quietly)
4520 "Apply FUNCTION to the start of all tables in the buffer."
4521 (save-excursion
4522 (save-restriction
4523 (widen)
4524 (goto-char (point-min))
4525 (while (re-search-forward org-table-any-line-regexp nil t)
4526 (unless quietly
4527 (message "Mapping tables: %d%%"
4528 (floor (* 100.0 (point)) (buffer-size))))
4529 (beginning-of-line 1)
4530 (when (and (looking-at org-table-line-regexp)
4531 ;; Exclude tables in src/example/verbatim/clocktable blocks
4532 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4533 (save-excursion (funcall function))
4534 (or (looking-at org-table-line-regexp)
4535 (forward-char 1)))
4536 (re-search-forward org-table-any-border-regexp nil 1))))
4537 (unless quietly (message "Mapping tables: done")))
4539 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4540 (declare-function org-clock-update-mode-line "org-clock" ())
4541 (declare-function org-resolve-clocks "org-clock"
4542 (&optional also-non-dangling-p prompt last-valid))
4544 (defun org-at-TBLFM-p (&optional pos)
4545 "Non-nil when point (or POS) is in #+TBLFM line."
4546 (save-excursion
4547 (goto-char (or pos (point)))
4548 (beginning-of-line)
4549 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4550 (eq (org-element-type (org-element-at-point)) 'table))))
4552 (defvar org-clock-start-time)
4553 (defvar org-clock-marker (make-marker)
4554 "Marker recording the last clock-in.")
4555 (defvar org-clock-hd-marker (make-marker)
4556 "Marker recording the last clock-in, but the headline position.")
4557 (defvar org-clock-heading ""
4558 "The heading of the current clock entry.")
4559 (defun org-clock-is-active ()
4560 "Return the buffer where the clock is currently running.
4561 Return nil if no clock is running."
4562 (marker-buffer org-clock-marker))
4564 (defun org-check-running-clock ()
4565 "Check if the current buffer contains the running clock.
4566 If yes, offer to stop it and to save the buffer with the changes."
4567 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4568 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4569 (buffer-name))))
4570 (org-clock-out)
4571 (when (y-or-n-p "Save changed buffer?")
4572 (save-buffer))))
4574 (defun org-clocktable-try-shift (dir n)
4575 "Check if this line starts a clock table, if yes, shift the time block."
4576 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4577 (org-clocktable-shift dir n)))
4579 ;;;###autoload
4580 (defun org-clock-persistence-insinuate ()
4581 "Set up hooks for clock persistence."
4582 (require 'org-clock)
4583 (add-hook 'org-mode-hook 'org-clock-load)
4584 (add-hook 'kill-emacs-hook 'org-clock-save))
4586 (defgroup org-archive nil
4587 "Options concerning archiving in Org-mode."
4588 :tag "Org Archive"
4589 :group 'org-structure)
4591 (defcustom org-archive-location "%s_archive::"
4592 "The location where subtrees should be archived.
4594 The value of this variable is a string, consisting of two parts,
4595 separated by a double-colon. The first part is a filename and
4596 the second part is a headline.
4598 When the filename is omitted, archiving happens in the same file.
4599 %s in the filename will be replaced by the current file
4600 name (without the directory part). Archiving to a different file
4601 is useful to keep archived entries from contributing to the
4602 Org-mode Agenda.
4604 The archived entries will be filed as subtrees of the specified
4605 headline. When the headline is omitted, the subtrees are simply
4606 filed away at the end of the file, as top-level entries. Also in
4607 the heading you can use %s to represent the file name, this can be
4608 useful when using the same archive for a number of different files.
4610 Here are a few examples:
4611 \"%s_archive::\"
4612 If the current file is Projects.org, archive in file
4613 Projects.org_archive, as top-level trees. This is the default.
4615 \"::* Archived Tasks\"
4616 Archive in the current file, under the top-level headline
4617 \"* Archived Tasks\".
4619 \"~/org/archive.org::\"
4620 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4622 \"~/org/archive.org::* From %s\"
4623 Archive in file ~/org/archive.org (absolute path), under headlines
4624 \"From FILENAME\" where file name is the current file name.
4626 \"~/org/datetree.org::datetree/* Finished Tasks\"
4627 The \"datetree/\" string is special, signifying to archive
4628 items to the datetree. Items are placed in either the CLOSED
4629 date of the item, or the current date if there is no CLOSED date.
4630 The heading will be a subentry to the current date. There doesn't
4631 need to be a heading, but there always needs to be a slash after
4632 datetree. For example, to store archived items directly in the
4633 datetree, use \"~/org/datetree.org::datetree/\".
4635 \"basement::** Finished Tasks\"
4636 Archive in file ./basement (relative path), as level 3 trees
4637 below the level 2 heading \"** Finished Tasks\".
4639 You may set this option on a per-file basis by adding to the buffer a
4640 line like
4642 #+ARCHIVE: basement::** Finished Tasks
4644 You may also define it locally for a subtree by setting an ARCHIVE property
4645 in the entry. If such a property is found in an entry, or anywhere up
4646 the hierarchy, it will be used."
4647 :group 'org-archive
4648 :type 'string)
4650 (defcustom org-agenda-skip-archived-trees t
4651 "Non-nil means the agenda will skip any items located in archived trees.
4652 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4653 variable is no longer recommended, you should leave it at the value t.
4654 Instead, use the key `v' to cycle the archives-mode in the agenda."
4655 :group 'org-archive
4656 :group 'org-agenda-skip
4657 :type 'boolean)
4659 (defcustom org-columns-skip-archived-trees t
4660 "Non-nil means ignore archived trees when creating column view."
4661 :group 'org-archive
4662 :group 'org-properties
4663 :type 'boolean)
4665 (defcustom org-cycle-open-archived-trees nil
4666 "Non-nil means `org-cycle' will open archived trees.
4667 An archived tree is a tree marked with the tag ARCHIVE.
4668 When nil, archived trees will stay folded. You can still open them with
4669 normal outline commands like `show-all', but not with the cycling commands."
4670 :group 'org-archive
4671 :group 'org-cycle
4672 :type 'boolean)
4674 (defcustom org-sparse-tree-open-archived-trees nil
4675 "Non-nil means sparse tree construction shows matches in archived trees.
4676 When nil, matches in these trees are highlighted, but the trees are kept in
4677 collapsed state."
4678 :group 'org-archive
4679 :group 'org-sparse-trees
4680 :type 'boolean)
4682 (defcustom org-sparse-tree-default-date-type nil
4683 "The default date type when building a sparse tree.
4684 When this is nil, a date is a scheduled or a deadline timestamp.
4685 Otherwise, these types are allowed:
4687 all: all timestamps
4688 active: only active timestamps (<...>)
4689 inactive: only inactive timestamps ([...])
4690 scheduled: only scheduled timestamps
4691 deadline: only deadline timestamps"
4692 :type '(choice (const :tag "Scheduled or deadline" nil)
4693 (const :tag "All timestamps" all)
4694 (const :tag "Only active timestamps" active)
4695 (const :tag "Only inactive timestamps" inactive)
4696 (const :tag "Only scheduled timestamps" scheduled)
4697 (const :tag "Only deadline timestamps" deadline)
4698 (const :tag "Only closed timestamps" closed))
4699 :version "25.1"
4700 :package-version '(Org . "8.3")
4701 :group 'org-sparse-trees)
4703 (defun org-cycle-hide-archived-subtrees (state)
4704 "Re-hide all archived subtrees after a visibility state change."
4705 (when (and (not org-cycle-open-archived-trees)
4706 (not (memq state '(overview folded))))
4707 (save-excursion
4708 (let* ((globalp (memq state '(contents all)))
4709 (beg (if globalp (point-min) (point)))
4710 (end (if globalp (point-max) (org-end-of-subtree t))))
4711 (org-hide-archived-subtrees beg end)
4712 (goto-char beg)
4713 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4714 (message "%s" (substitute-command-keys
4715 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4717 (defun org-force-cycle-archived ()
4718 "Cycle subtree even if it is archived."
4719 (interactive)
4720 (setq this-command 'org-cycle)
4721 (let ((org-cycle-open-archived-trees t))
4722 (call-interactively 'org-cycle)))
4724 (defun org-hide-archived-subtrees (beg end)
4725 "Re-hide all archived subtrees after a visibility state change."
4726 (org-with-wide-buffer
4727 (let ((case-fold-search nil)
4728 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4729 (goto-char beg)
4730 ;; Include headline point is currently on.
4731 (beginning-of-line)
4732 (while (and (< (point) end) (re-search-forward re end t))
4733 (when (member org-archive-tag (org-get-tags))
4734 (org-flag-subtree t)
4735 (org-end-of-subtree t))))))
4737 (declare-function outline-end-of-heading "outline" ())
4738 (declare-function outline-flag-region "outline" (from to flag))
4739 (defun org-flag-subtree (flag)
4740 (save-excursion
4741 (org-back-to-heading t)
4742 (outline-end-of-heading)
4743 (outline-flag-region (point)
4744 (progn (org-end-of-subtree t) (point))
4745 flag)))
4747 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4749 ;; Declare Column View Code
4751 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4752 (declare-function org-columns-compute "org-colview" (property))
4754 ;; Declare ID code
4756 (declare-function org-id-store-link "org-id")
4757 (declare-function org-id-locations-load "org-id")
4758 (declare-function org-id-locations-save "org-id")
4759 (defvar org-id-track-globally)
4761 ;;; Variables for pre-computed regular expressions, all buffer local
4763 (defvar-local org-todo-regexp nil
4764 "Matches any of the TODO state keywords.")
4765 (defvar-local org-not-done-regexp nil
4766 "Matches any of the TODO state keywords except the last one.")
4767 (defvar-local org-not-done-heading-regexp nil
4768 "Matches a TODO headline that is not done.")
4769 (defvar-local org-todo-line-regexp nil
4770 "Matches a headline and puts TODO state into group 2 if present.")
4771 (defvar-local org-complex-heading-regexp nil
4772 "Matches a headline and puts everything into groups:
4773 group 1: the stars
4774 group 2: The todo keyword, maybe
4775 group 3: Priority cookie
4776 group 4: True headline
4777 group 5: Tags")
4778 (defvar-local org-complex-heading-regexp-format nil
4779 "Printf format to make regexp to match an exact headline.
4780 This regexp will match the headline of any node which has the
4781 exact headline text that is put into the format, but may have any
4782 TODO state, priority and tags.")
4783 (defvar-local org-todo-line-tags-regexp nil
4784 "Matches a headline and puts TODO state into group 2 if present.
4785 Also put tags into group 4 if tags are present.")
4787 (defconst org-plain-time-of-day-regexp
4788 (concat
4789 "\\(\\<[012]?[0-9]"
4790 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4791 "\\(--?"
4792 "\\(\\<[012]?[0-9]"
4793 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4794 "\\)?")
4795 "Regular expression to match a plain time or time range.
4796 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4797 groups carry important information:
4798 0 the full match
4799 1 the first time, range or not
4800 8 the second time, if it is a range.")
4802 (defconst org-plain-time-extension-regexp
4803 (concat
4804 "\\(\\<[012]?[0-9]"
4805 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4806 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4807 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4808 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4809 groups carry important information:
4810 0 the full match
4811 7 hours of duration
4812 9 minutes of duration")
4814 (defconst org-stamp-time-of-day-regexp
4815 (concat
4816 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4817 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4818 "\\(--?"
4819 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4820 "Regular expression to match a timestamp time or time range.
4821 After a match, the following groups carry important information:
4822 0 the full match
4823 1 date plus weekday, for back referencing to make sure both times are on the same day
4824 2 the first time, range or not
4825 4 the second time, if it is a range.")
4827 (defconst org-startup-options
4828 '(("fold" org-startup-folded t)
4829 ("overview" org-startup-folded t)
4830 ("nofold" org-startup-folded nil)
4831 ("showall" org-startup-folded nil)
4832 ("showeverything" org-startup-folded showeverything)
4833 ("content" org-startup-folded content)
4834 ("indent" org-startup-indented t)
4835 ("noindent" org-startup-indented nil)
4836 ("hidestars" org-hide-leading-stars t)
4837 ("showstars" org-hide-leading-stars nil)
4838 ("odd" org-odd-levels-only t)
4839 ("oddeven" org-odd-levels-only nil)
4840 ("align" org-startup-align-all-tables t)
4841 ("noalign" org-startup-align-all-tables nil)
4842 ("inlineimages" org-startup-with-inline-images t)
4843 ("noinlineimages" org-startup-with-inline-images nil)
4844 ("latexpreview" org-startup-with-latex-preview t)
4845 ("nolatexpreview" org-startup-with-latex-preview nil)
4846 ("customtime" org-display-custom-times t)
4847 ("logdone" org-log-done time)
4848 ("lognotedone" org-log-done note)
4849 ("nologdone" org-log-done nil)
4850 ("lognoteclock-out" org-log-note-clock-out t)
4851 ("nolognoteclock-out" org-log-note-clock-out nil)
4852 ("logrepeat" org-log-repeat state)
4853 ("lognoterepeat" org-log-repeat note)
4854 ("logdrawer" org-log-into-drawer t)
4855 ("nologdrawer" org-log-into-drawer nil)
4856 ("logstatesreversed" org-log-states-order-reversed t)
4857 ("nologstatesreversed" org-log-states-order-reversed nil)
4858 ("nologrepeat" org-log-repeat nil)
4859 ("logreschedule" org-log-reschedule time)
4860 ("lognotereschedule" org-log-reschedule note)
4861 ("nologreschedule" org-log-reschedule nil)
4862 ("logredeadline" org-log-redeadline time)
4863 ("lognoteredeadline" org-log-redeadline note)
4864 ("nologredeadline" org-log-redeadline nil)
4865 ("logrefile" org-log-refile time)
4866 ("lognoterefile" org-log-refile note)
4867 ("nologrefile" org-log-refile nil)
4868 ("fninline" org-footnote-define-inline t)
4869 ("nofninline" org-footnote-define-inline nil)
4870 ("fnlocal" org-footnote-section nil)
4871 ("fnauto" org-footnote-auto-label t)
4872 ("fnprompt" org-footnote-auto-label nil)
4873 ("fnconfirm" org-footnote-auto-label confirm)
4874 ("fnplain" org-footnote-auto-label plain)
4875 ("fnadjust" org-footnote-auto-adjust t)
4876 ("nofnadjust" org-footnote-auto-adjust nil)
4877 ("constcgs" constants-unit-system cgs)
4878 ("constSI" constants-unit-system SI)
4879 ("noptag" org-tag-persistent-alist nil)
4880 ("hideblocks" org-hide-block-startup t)
4881 ("nohideblocks" org-hide-block-startup nil)
4882 ("beamer" org-startup-with-beamer-mode t)
4883 ("entitiespretty" org-pretty-entities t)
4884 ("entitiesplain" org-pretty-entities nil))
4885 "Variable associated with STARTUP options for org-mode.
4886 Each element is a list of three items: the startup options (as written
4887 in the #+STARTUP line), the corresponding variable, and the value to set
4888 this variable to if the option is found. An optional forth element PUSH
4889 means to push this value onto the list in the variable.")
4891 (defcustom org-group-tags t
4892 "When non-nil (the default), use group tags.
4893 This can be turned on/off through `org-toggle-tags-groups'."
4894 :group 'org-tags
4895 :group 'org-startup
4896 :type 'boolean)
4898 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4900 (defun org-toggle-tags-groups ()
4901 "Toggle support for group tags.
4902 Support for group tags is controlled by the option
4903 `org-group-tags', which is non-nil by default."
4904 (interactive)
4905 (setq org-group-tags (not org-group-tags))
4906 (cond ((and (derived-mode-p 'org-agenda-mode)
4907 org-group-tags)
4908 (org-agenda-redo))
4909 ((derived-mode-p 'org-mode)
4910 (let ((org-inhibit-startup t)) (org-mode))))
4911 (message "Groups tags support has been turned %s"
4912 (if org-group-tags "on" "off")))
4914 (defun org-set-regexps-and-options (&optional tags-only)
4915 "Precompute regular expressions used in the current buffer.
4916 When optional argument TAGS-ONLY is non-nil, only compute tags
4917 related expressions."
4918 (when (derived-mode-p 'org-mode)
4919 (let ((alist (org--setup-collect-keywords
4920 (org-make-options-regexp
4921 (append '("FILETAGS" "TAGS" "SETUPFILE")
4922 (and (not tags-only)
4923 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4924 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4925 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4926 ;; Startup options. Get this early since it does change
4927 ;; behavior for other options (e.g., tags).
4928 (let ((startup (cdr (assq 'startup alist))))
4929 (dolist (option startup)
4930 (let ((entry (assoc-string option org-startup-options t)))
4931 (when entry
4932 (let ((var (nth 1 entry))
4933 (val (nth 2 entry)))
4934 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4935 (unless (listp (symbol-value var))
4936 (set (make-local-variable var) nil))
4937 (add-to-list var val)))))))
4938 (setq-local org-file-tags
4939 (mapcar #'org-add-prop-inherited
4940 (cdr (assq 'filetags alist))))
4941 (setq org-current-tag-alist
4942 (append org-tag-persistent-alist
4943 (let ((tags (cdr (assq 'tags alist))))
4944 (if tags (org-tag-string-to-alist tags)
4945 org-tag-alist))))
4946 (setq org-tag-groups-alist
4947 (org-tag-alist-to-groups org-current-tag-alist))
4948 (unless tags-only
4949 ;; File properties.
4950 (setq-local org-file-properties (cdr (assq 'property alist)))
4951 ;; Archive location.
4952 (let ((archive (cdr (assq 'archive alist))))
4953 (when archive (setq-local org-archive-location archive)))
4954 ;; Category.
4955 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4956 (when cat
4957 (setq-local org-category (intern cat))
4958 (setq-local org-file-properties
4959 (org--update-property-plist
4960 "CATEGORY" cat org-file-properties))))
4961 ;; Columns.
4962 (let ((column (cdr (assq 'columns alist))))
4963 (when column (setq-local org-columns-default-format column)))
4964 ;; Constants.
4965 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4966 ;; Link abbreviations.
4967 (let ((links (cdr (assq 'link alist))))
4968 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4969 ;; Priorities.
4970 (let ((priorities (cdr (assq 'priorities alist))))
4971 (when priorities
4972 (setq-local org-highest-priority (nth 0 priorities))
4973 (setq-local org-lowest-priority (nth 1 priorities))
4974 (setq-local org-default-priority (nth 2 priorities))))
4975 ;; Scripts.
4976 (let ((scripts (assq 'scripts alist)))
4977 (when scripts
4978 (setq-local org-use-sub-superscripts (cdr scripts))))
4979 ;; TODO keywords.
4980 (setq-local org-todo-kwd-alist nil)
4981 (setq-local org-todo-key-alist nil)
4982 (setq-local org-todo-key-trigger nil)
4983 (setq-local org-todo-keywords-1 nil)
4984 (setq-local org-done-keywords nil)
4985 (setq-local org-todo-heads nil)
4986 (setq-local org-todo-sets nil)
4987 (setq-local org-todo-log-states nil)
4988 (let ((todo-sequences
4989 (or (nreverse (cdr (assq 'todo alist)))
4990 (let ((d (default-value 'org-todo-keywords)))
4991 (if (not (stringp (car d))) d
4992 ;; XXX: Backward compatibility code.
4993 (list (cons org-todo-interpretation d)))))))
4994 (dolist (sequence todo-sequences)
4995 (let* ((sequence (or (run-hook-with-args-until-success
4996 'org-todo-setup-filter-hook sequence)
4997 sequence))
4998 (sequence-type (car sequence))
4999 (keywords (cdr sequence))
5000 (sep (member "|" keywords))
5001 names alist)
5002 (dolist (k (remove "|" keywords))
5003 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5005 (error "Invalid TODO keyword %s" k))
5006 (let ((name (match-string 1 k))
5007 (key (match-string 2 k))
5008 (log (org-extract-log-state-settings k)))
5009 (push name names)
5010 (push (cons name (and key (string-to-char key))) alist)
5011 (when log (push log org-todo-log-states))))
5012 (let* ((names (nreverse names))
5013 (done (if sep (org-remove-keyword-keys (cdr sep))
5014 (last names)))
5015 (head (car names))
5016 (tail (list sequence-type head (car done) (org-last done))))
5017 (add-to-list 'org-todo-heads head 'append)
5018 (push names org-todo-sets)
5019 (setq org-done-keywords (append org-done-keywords done nil))
5020 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5021 (setq org-todo-key-alist
5022 (append org-todo-key-alist
5023 (and alist
5024 (append '((:startgroup))
5025 (nreverse alist)
5026 '((:endgroup))))))
5027 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5028 (setq org-todo-sets (nreverse org-todo-sets)
5029 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5030 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5031 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5032 ;; Compute the regular expressions and other local variables.
5033 ;; Using `org-outline-regexp-bol' would complicate them much,
5034 ;; because of the fixed white space at the end of that string.
5035 (unless org-done-keywords
5036 (setq org-done-keywords
5037 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5038 (setq org-not-done-keywords
5039 (org-delete-all org-done-keywords
5040 (copy-sequence org-todo-keywords-1))
5041 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5042 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5043 org-not-done-heading-regexp
5044 (format org-heading-keyword-regexp-format org-not-done-regexp)
5045 org-todo-line-regexp
5046 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5047 org-complex-heading-regexp
5048 (concat "^\\(\\*+\\)"
5049 "\\(?: +" org-todo-regexp "\\)?"
5050 "\\(?: +\\(\\[#.\\]\\)\\)?"
5051 "\\(?: +\\(.*?\\)\\)??"
5052 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5053 "[ \t]*$")
5054 org-complex-heading-regexp-format
5055 (concat "^\\(\\*+\\)"
5056 "\\(?: +" org-todo-regexp "\\)?"
5057 "\\(?: +\\(\\[#.\\]\\)\\)?"
5058 "\\(?: +"
5059 ;; Stats cookies can be stuck to body.
5060 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5061 "\\(%s\\)"
5062 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5063 "\\)"
5064 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5065 "[ \t]*$")
5066 org-todo-line-tags-regexp
5067 (concat "^\\(\\*+\\)"
5068 "\\(?: +" org-todo-regexp "\\)?"
5069 "\\(?: +\\(.*?\\)\\)??"
5070 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5071 "[ \t]*$"))
5072 (org-compute-latex-and-related-regexp)))))
5074 (defun org--setup-collect-keywords (regexp &optional files alist)
5075 "Return setup keywords values as an alist.
5077 REGEXP matches a subset of setup keywords. FILES is a list of
5078 file names already visited. It is used to avoid circular setup
5079 files. ALIST, when non-nil, is the alist computed so far.
5081 Return value contains the following keys: `archive', `category',
5082 `columns', `constants', `filetags', `link', `priorities',
5083 `property', `scripts', `startup', `tags' and `todo'."
5084 (org-with-wide-buffer
5085 (goto-char (point-min))
5086 (let ((case-fold-search t))
5087 (while (re-search-forward regexp nil t)
5088 (let ((element (org-element-at-point)))
5089 (when (eq (org-element-type element) 'keyword)
5090 (let ((key (org-element-property :key element))
5091 (value (org-element-property :value element)))
5092 (cond
5093 ((equal key "ARCHIVE")
5094 (when (org-string-nw-p value)
5095 (push (cons 'archive value) alist)))
5096 ((equal key "CATEGORY") (push (cons 'category value) alist))
5097 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5098 ((equal key "CONSTANTS")
5099 (let* ((constants (assq 'constants alist))
5100 (store (cdr constants)))
5101 (dolist (pair (org-split-string value))
5102 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5103 pair)
5104 (let* ((name (match-string 1 pair))
5105 (value (match-string 2 pair))
5106 (old (assoc name store)))
5107 (if old (setcdr old value)
5108 (push (cons name value) store)))))
5109 (if constants (setcdr constants store)
5110 (push (cons 'constants store) alist))))
5111 ((equal key "FILETAGS")
5112 (when (org-string-nw-p value)
5113 (let ((old (assq 'filetags alist))
5114 (new (apply #'nconc
5115 (mapcar (lambda (x) (org-split-string x ":"))
5116 (org-split-string value)))))
5117 (if old (setcdr old (append new (cdr old)))
5118 (push (cons 'filetags new) alist)))))
5119 ((equal key "LINK")
5120 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5121 (let ((links (assq 'link alist))
5122 (pair (cons (org-match-string-no-properties 1 value)
5123 (org-match-string-no-properties 2 value))))
5124 (if links (push pair (cdr links))
5125 (push (list 'link pair) alist)))))
5126 ((equal key "OPTIONS")
5127 (when (and (org-string-nw-p value)
5128 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5129 (push (cons 'scripts (read (match-string 1 value))) alist)))
5130 ((equal key "PRIORITIES")
5131 (push (cons 'priorities
5132 (let ((prio (org-split-string value)))
5133 (if (< (length prio) 3) '(?A ?C ?B)
5134 (mapcar #'string-to-char prio))))
5135 alist))
5136 ((equal key "PROPERTY")
5137 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5138 (let* ((property (assq 'property alist))
5139 (value (org--update-property-plist
5140 (org-match-string-no-properties 1 value)
5141 (org-match-string-no-properties 2 value)
5142 (cdr property))))
5143 (if property (setcdr property value)
5144 (push (cons 'property value) alist)))))
5145 ((equal key "STARTUP")
5146 (let ((startup (assq 'startup alist)))
5147 (if startup
5148 (setcdr startup
5149 (append (cdr startup) (org-split-string value)))
5150 (push (cons 'startup (org-split-string value)) alist))))
5151 ((equal key "TAGS")
5152 (let ((tag-cell (assq 'tags alist)))
5153 (if tag-cell
5154 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5155 (push (cons 'tags value) alist))))
5156 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5157 (let ((todo (assq 'todo alist))
5158 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5159 (org-split-string value))))
5160 (if todo (push value (cdr todo))
5161 (push (list 'todo value) alist))))
5162 ((equal key "SETUPFILE")
5163 (unless buffer-read-only ; Do not check in Gnus messages.
5164 (let ((f (and (org-string-nw-p value)
5165 (expand-file-name
5166 (org-remove-double-quotes value)))))
5167 (when (and f (file-readable-p f) (not (member f files)))
5168 (with-temp-buffer
5169 (setq default-directory (file-name-directory f))
5170 (insert-file-contents f)
5171 (setq alist
5172 ;; Fake Org mode to benefit from cache
5173 ;; without recurring needlessly.
5174 (let ((major-mode 'org-mode))
5175 (org--setup-collect-keywords
5176 regexp (cons f files) alist)))))))))))))))
5177 alist)
5179 (defun org-tag-string-to-alist (s)
5180 "Return tag alist associated to string S.
5181 S is a value for TAGS keyword or produced with
5182 `org-tag-alist-to-string'. Return value is an alist suitable for
5183 `org-tag-alist' or `org-tag-persistent-alist'."
5184 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5185 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5186 "\\|{.+?}\\)" ; regular expression
5187 "\\(?:(\\(.\\))\\)?\\'"))
5188 alist group-flag)
5189 (dolist (tokens lines (cdr (nreverse alist)))
5190 (push '(:newline) alist)
5191 (while tokens
5192 (let ((token (pop tokens)))
5193 (pcase token
5194 ("{"
5195 (push '(:startgroup) alist)
5196 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5197 ("}"
5198 (push '(:endgroup) alist)
5199 (setq group-flag nil))
5200 ("["
5201 (push '(:startgrouptag) alist)
5202 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5203 ("]"
5204 (push '(:endgrouptag) alist)
5205 (setq group-flag nil))
5206 (":"
5207 (push '(:grouptags) alist))
5208 ((guard (string-match tag-re token))
5209 (let ((tag (match-string 1 token))
5210 (key (and (match-beginning 2)
5211 (string-to-char (match-string 2 token)))))
5212 ;; Push all tags in groups, no matter if they already
5213 ;; appear somewhere else in the list.
5214 (when (or group-flag (not (assoc tag alist)))
5215 (push (cons tag key) alist))))))))))
5217 (defun org-tag-alist-to-string (alist &optional skip-key)
5218 "Return tag string associated to ALIST.
5220 ALIST is an alist, as defined in `org-tag-alist' or
5221 `org-tag-persistent-alist', or produced with
5222 `org-tag-string-to-alist'.
5224 Return value is a string suitable as a value for \"TAGS\"
5225 keyword.
5227 When optional argument SKIP-KEY is non-nil, skip selection keys
5228 next to tags."
5229 (mapconcat (lambda (token)
5230 (pcase token
5231 (`(:startgroup) "{")
5232 (`(:endgroup) "}")
5233 (`(:startgrouptag) "[")
5234 (`(:endgrouptag) "]")
5235 (`(:grouptags) ":")
5236 (`(:newline) "\\n")
5237 ((and
5238 (guard (not skip-key))
5239 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5240 (format "%s(%c)" tag key))
5241 (`(,(and tag (pred stringp)) . ,_) tag)
5242 (_ (user-error "Invalid tag token: %S" token))))
5243 alist
5244 " "))
5246 (defun org-tag-alist-to-groups (alist)
5247 "Return group alist from tag ALIST.
5248 ALIST is an alist, as defined in `org-tag-alist' or
5249 `org-tag-persistent-alist', or produced with
5250 `org-tag-string-to-alist'. Return value is an alist following
5251 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5252 a string, summarizing TAGS, as a list of strings."
5253 (let (groups group-status current-group)
5254 (dolist (token alist (nreverse groups))
5255 (pcase token
5256 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5257 (`(,(or :endgroup :endgrouptag))
5258 (when (eq group-status 'append)
5259 (push (nreverse current-group) groups))
5260 (setq group-status nil))
5261 (`(:grouptags) (setq group-status 'append))
5262 ((and `(,tag . ,_) (guard group-status))
5263 (if (eq group-status 'append) (push tag current-group)
5264 (setq current-group (list tag))))
5265 (_ nil)))))
5267 (defun org-file-contents (file &optional noerror)
5268 "Return the contents of FILE, as a string."
5269 (if (and file (file-readable-p file))
5270 (with-temp-buffer
5271 (insert-file-contents file)
5272 (buffer-string))
5273 (funcall (if noerror 'message 'error)
5274 "Cannot read file \"%s\"%s"
5275 file
5276 (let ((from (buffer-file-name (buffer-base-buffer))))
5277 (if from (concat " (referenced in file \"" from "\")") "")))))
5279 (defun org-extract-log-state-settings (x)
5280 "Extract the log state setting from a TODO keyword string.
5281 This will extract info from a string like \"WAIT(w@/!)\"."
5282 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5283 (let ((kw (match-string 1 x))
5284 (log1 (and (match-end 3) (match-string 3 x)))
5285 (log2 (and (match-end 4) (match-string 4 x))))
5286 (and (or log1 log2)
5287 (list kw
5288 (and log1 (if (equal log1 "!") 'time 'note))
5289 (and log2 (if (equal log2 "!") 'time 'note)))))))
5291 (defun org-remove-keyword-keys (list)
5292 "Remove a pair of parenthesis at the end of each string in LIST."
5293 (mapcar (lambda (x)
5294 (if (string-match "(.*)$" x)
5295 (substring x 0 (match-beginning 0))
5297 list))
5299 (defun org-assign-fast-keys (alist)
5300 "Assign fast keys to a keyword-key alist.
5301 Respect keys that are already there."
5302 (let (new e (alt ?0))
5303 (while (setq e (pop alist))
5304 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5305 (cdr e)) ;; Key already assigned.
5306 (push e new)
5307 (let ((clist (string-to-list (downcase (car e))))
5308 (used (append new alist)))
5309 (when (= (car clist) ?@)
5310 (pop clist))
5311 (while (and clist (rassoc (car clist) used))
5312 (pop clist))
5313 (unless clist
5314 (while (rassoc alt used)
5315 (cl-incf alt)))
5316 (push (cons (car e) (or (car clist) alt)) new))))
5317 (nreverse new)))
5319 ;;; Some variables used in various places
5321 (defvar org-window-configuration nil
5322 "Used in various places to store a window configuration.")
5323 (defvar org-selected-window nil
5324 "Used in various places to store a window configuration.")
5325 (defvar org-finish-function nil
5326 "Function to be called when `C-c C-c' is used.
5327 This is for getting out of special buffers like capture.")
5328 (defvar org-last-state)
5330 ;; Defined somewhere in this file, but used before definition.
5331 (defvar org-entities) ;; defined in org-entities.el
5332 (defvar org-struct-menu)
5333 (defvar org-org-menu)
5334 (defvar org-tbl-menu)
5336 ;;;; Define the Org-mode
5338 ;; We use a before-change function to check if a table might need
5339 ;; an update.
5340 (defvar org-table-may-need-update t
5341 "Indicates that a table might need an update.
5342 This variable is set by `org-before-change-function'.
5343 `org-table-align' sets it back to nil.")
5344 (defun org-before-change-function (_beg _end)
5345 "Every change indicates that a table might need an update."
5346 (setq org-table-may-need-update t))
5347 (defvar org-mode-map)
5348 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5349 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5350 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5351 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5352 (defvar org-table-buffer-is-an nil)
5354 (defvar bidi-paragraph-direction)
5355 (defvar buffer-face-mode-face)
5357 (require 'outline)
5358 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5359 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22"))
5360 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5362 ;; Other stuff we need.
5363 (require 'time-date)
5364 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5365 (require 'easymenu)
5366 (autoload 'easy-menu-add "easymenu")
5367 (require 'overlay)
5369 ;; (require 'org-macs) moved higher up in the file before it is first used
5370 (require 'org-entities)
5371 ;; (require 'org-compat) moved higher up in the file before it is first used
5372 (require 'org-faces)
5373 (require 'org-list)
5374 (require 'org-pcomplete)
5375 (require 'org-src)
5376 (require 'org-footnote)
5377 (require 'org-macro)
5379 ;; babel
5380 (require 'ob)
5382 ;;;###autoload
5383 (define-derived-mode org-mode outline-mode "Org"
5384 "Outline-based notes management and organizer, alias
5385 \"Carsten's outline-mode for keeping track of everything.\"
5387 Org-mode develops organizational tasks around a NOTES file which
5388 contains information about projects as plain text. Org-mode is
5389 implemented on top of outline-mode, which is ideal to keep the content
5390 of large files well structured. It supports ToDo items, deadlines and
5391 time stamps, which magically appear in the diary listing of the Emacs
5392 calendar. Tables are easily created with a built-in table editor.
5393 Plain text URL-like links connect to websites, emails (VM), Usenet
5394 messages (Gnus), BBDB entries, and any files related to the project.
5395 For printing and sharing of notes, an Org-mode file (or a part of it)
5396 can be exported as a structured ASCII or HTML file.
5398 The following commands are available:
5400 \\{org-mode-map}"
5402 ;; Get rid of Outline menus, they are not needed
5403 ;; Need to do this here because define-derived-mode sets up
5404 ;; the keymap so late. Still, it is a waste to call this each time
5405 ;; we switch another buffer into org-mode.
5406 (if (featurep 'xemacs)
5407 (when (boundp 'outline-mode-menu-heading)
5408 ;; Assume this is Greg's port, it uses easymenu
5409 (easy-menu-remove outline-mode-menu-heading)
5410 (easy-menu-remove outline-mode-menu-show)
5411 (easy-menu-remove outline-mode-menu-hide))
5412 (define-key org-mode-map [menu-bar headings] 'undefined)
5413 (define-key org-mode-map [menu-bar hide] 'undefined)
5414 (define-key org-mode-map [menu-bar show] 'undefined))
5416 (org-load-modules-maybe)
5417 (when (featurep 'xemacs)
5418 (easy-menu-add org-org-menu)
5419 (easy-menu-add org-tbl-menu))
5420 (org-install-agenda-files-menu)
5421 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5422 (add-to-invisibility-spec '(org-cwidth))
5423 (add-to-invisibility-spec '(org-hide-block . t))
5424 (when (featurep 'xemacs)
5425 (setq-local line-move-ignore-invisible t))
5426 (setq-local outline-regexp org-outline-regexp)
5427 (setq-local outline-level 'org-outline-level)
5428 (setq bidi-paragraph-direction 'left-to-right)
5429 (when (and org-ellipsis
5430 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5431 (fboundp 'make-glyph-code))
5432 (unless org-display-table
5433 (setq org-display-table (make-display-table)))
5434 (set-display-table-slot
5435 org-display-table 4
5436 (vconcat (mapcar
5437 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5438 org-ellipsis)))
5439 (if (stringp org-ellipsis) org-ellipsis "..."))))
5440 (setq buffer-display-table org-display-table))
5441 (org-set-regexps-and-options)
5442 (org-set-font-lock-defaults)
5443 (when (and org-tag-faces (not org-tags-special-faces-re))
5444 ;; tag faces set outside customize.... force initialization.
5445 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5446 ;; Calc embedded
5447 (setq-local calc-embedded-open-mode "# ")
5448 ;; Modify a few syntax entries
5449 (modify-syntax-entry ?@ "w")
5450 (modify-syntax-entry ?\" "\"")
5451 (modify-syntax-entry ?\\ "_")
5452 (modify-syntax-entry ?~ "_")
5453 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5454 ;; Activate before-change-function
5455 (setq-local org-table-may-need-update t)
5456 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5457 ;; Check for running clock before killing a buffer
5458 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5459 ;; Initialize macros templates.
5460 (org-macro-initialize-templates)
5461 ;; Initialize radio targets.
5462 (org-update-radio-target-regexp)
5463 ;; Indentation.
5464 (setq-local indent-line-function 'org-indent-line)
5465 (setq-local indent-region-function 'org-indent-region)
5466 ;; Filling and auto-filling.
5467 (org-setup-filling)
5468 ;; Comments.
5469 (org-setup-comments-handling)
5470 ;; Initialize cache.
5471 (org-element-cache-reset)
5472 ;; Beginning/end of defun
5473 (setq-local beginning-of-defun-function 'org-backward-element)
5474 (setq-local end-of-defun-function
5475 (lambda ()
5476 (if (not (org-at-heading-p))
5477 (org-forward-element)
5478 (org-forward-element)
5479 (forward-char -1))))
5480 ;; Next error for sparse trees
5481 (setq-local next-error-function 'org-occur-next-match)
5482 ;; Make sure dependence stuff works reliably, even for users who set it
5483 ;; too late :-(
5484 (if org-enforce-todo-dependencies
5485 (add-hook 'org-blocker-hook
5486 'org-block-todo-from-children-or-siblings-or-parent)
5487 (remove-hook 'org-blocker-hook
5488 'org-block-todo-from-children-or-siblings-or-parent))
5489 (if org-enforce-todo-checkbox-dependencies
5490 (add-hook 'org-blocker-hook
5491 'org-block-todo-from-checkboxes)
5492 (remove-hook 'org-blocker-hook
5493 'org-block-todo-from-checkboxes))
5495 ;; Align options lines
5496 (setq-local
5497 align-mode-rules-list
5498 '((org-in-buffer-settings
5499 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5500 (modes . '(org-mode)))))
5502 ;; Imenu
5503 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5505 ;; Make isearch reveal context
5506 (setq-local outline-isearch-open-invisible-function
5507 (lambda (&rest _) (org-show-context 'isearch)))
5509 ;; Setup the pcomplete hooks
5510 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5511 (setq-local pcomplete-command-name-function 'org-command-at-point)
5512 (setq-local pcomplete-default-completion-function 'ignore)
5513 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5514 (setq-local pcomplete-termination-string "")
5515 (setq-local buffer-face-mode-face 'org-default)
5517 ;; If empty file that did not turn on Org mode automatically, make
5518 ;; it to.
5519 (when (and org-insert-mode-line-in-empty-file
5520 (org-called-interactively-p 'any)
5521 (= (point-min) (point-max)))
5522 (insert "# -*- mode: org -*-\n\n"))
5523 (unless org-inhibit-startup
5524 (org-unmodified
5525 (when org-startup-with-beamer-mode (org-beamer-mode))
5526 (when org-startup-align-all-tables
5527 (org-table-map-tables #'org-table-align t))
5528 (when org-startup-with-inline-images (org-display-inline-images))
5529 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5530 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5531 (when org-startup-truncated (setq truncate-lines t))
5532 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5533 (org-refresh-effort-properties)))
5534 ;; Try to set `org-hide' face correctly.
5535 (let ((foreground (org-find-invisible-foreground)))
5536 (when foreground
5537 (set-face-foreground 'org-hide foreground))))
5539 ;; Update `customize-package-emacs-version-alist'
5540 (add-to-list 'customize-package-emacs-version-alist
5541 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5542 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5543 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5545 (defvar org-mode-transpose-word-syntax-table
5546 (let ((st (make-syntax-table text-mode-syntax-table)))
5547 (dolist (c org-emphasis-alist st)
5548 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5550 (when (fboundp 'abbrev-table-put)
5551 (abbrev-table-put org-mode-abbrev-table
5552 :parents (list text-mode-abbrev-table)))
5554 (defun org-find-invisible-foreground ()
5555 (let ((candidates (remove
5556 "unspecified-bg"
5557 (nconc
5558 (list (face-background 'default)
5559 (face-background 'org-default))
5560 (mapcar
5561 (lambda (alist)
5562 (when (boundp alist)
5563 (cdr (assoc 'background-color (symbol-value alist)))))
5564 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5565 (list (face-foreground 'org-hide))))))
5566 (car (remove nil candidates))))
5568 (defun org-current-time (&optional rounding-minutes past)
5569 "Current time, possibly rounded to ROUNDING-MINUTES.
5570 When ROUNDING-MINUTES is not an integer, fall back on the car of
5571 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5572 the rounding returns a past time."
5573 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5574 (car org-time-stamp-rounding-minutes)))
5575 (time (decode-time)) res)
5576 (if (< r 1)
5577 (current-time)
5578 (setq res
5579 (apply 'encode-time
5580 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5581 (nthcdr 2 time))))
5582 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5583 (seconds-to-time (- (org-float-time res) (* r 60)))
5584 res))))
5586 (defun org-today ()
5587 "Return today date, considering `org-extend-today-until'."
5588 (time-to-days
5589 (time-subtract (current-time)
5590 (list 0 (* 3600 org-extend-today-until) 0))))
5592 ;;;; Font-Lock stuff, including the activators
5594 (defvar org-mouse-map (make-sparse-keymap))
5595 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5596 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5597 (when org-mouse-1-follows-link
5598 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5599 (when org-tab-follows-link
5600 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5601 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5603 (require 'font-lock)
5605 (defconst org-non-link-chars "]\t\n\r<>")
5606 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5607 "file+sys" "news" "shell" "elisp" "doi" "message"
5608 "help"))
5609 (defvar org-link-types-re nil
5610 "Matches a link that has a url-like prefix like \"http:\"")
5611 (defvar org-link-re-with-space nil
5612 "Matches a link with spaces, optional angular brackets around it.")
5613 (defvar org-link-re-with-space2 nil
5614 "Matches a link with spaces, optional angular brackets around it.")
5615 (defvar org-link-re-with-space3 nil
5616 "Matches a link with spaces, only for internal part in bracket links.")
5617 (defvar org-angle-link-re nil
5618 "Matches link with angular brackets, spaces are allowed.")
5619 (defvar org-plain-link-re nil
5620 "Matches plain link, without spaces.")
5621 (defvar org-bracket-link-regexp nil
5622 "Matches a link in double brackets.")
5623 (defvar org-bracket-link-analytic-regexp nil
5624 "Regular expression used to analyze links.
5625 Here is what the match groups contain after a match:
5626 1: http:
5627 2: http
5628 3: path
5629 4: [desc]
5630 5: desc")
5631 (defvar org-bracket-link-analytic-regexp++ nil
5632 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5633 (defvar org-any-link-re nil
5634 "Regular expression matching any link.")
5636 (defconst org-match-sexp-depth 3
5637 "Number of stacked braces for sub/superscript matching.")
5639 (defun org-create-multibrace-regexp (left right n)
5640 "Create a regular expression which will match a balanced sexp.
5641 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5642 as single character strings.
5643 The regexp returned will match the entire expression including the
5644 delimiters. It will also define a single group which contains the
5645 match except for the outermost delimiters. The maximum depth of
5646 stacked delimiters is N. Escaping delimiters is not possible."
5647 (let* ((nothing (concat "[^" left right "]*?"))
5648 (or "\\|")
5649 (re nothing)
5650 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5651 (while (> n 1)
5652 (setq n (1- n)
5653 re (concat re or next)
5654 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5655 (concat left "\\(" re "\\)" right)))
5657 (defconst org-match-substring-regexp
5658 (concat
5659 "\\(\\S-\\)\\([_^]\\)\\("
5660 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5661 "\\|"
5662 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5663 "\\|"
5664 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5665 "The regular expression matching a sub- or superscript.")
5667 (defconst org-match-substring-with-braces-regexp
5668 (concat
5669 "\\(\\S-\\)\\([_^]\\)"
5670 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5671 "The regular expression matching a sub- or superscript, forcing braces.")
5673 (defun org-make-link-regexps ()
5674 "Update the link regular expressions.
5675 This should be called after the variable `org-link-types' has changed."
5676 (let ((types-re (regexp-opt org-link-types t)))
5677 (setq org-link-types-re
5678 (concat "\\`" types-re ":")
5679 org-link-re-with-space
5680 (concat "<?" types-re ":"
5681 "\\([^" org-non-link-chars " ]"
5682 "[^" org-non-link-chars "]*"
5683 "[^" org-non-link-chars " ]\\)>?")
5684 org-link-re-with-space2
5685 (concat "<?" types-re ":"
5686 "\\([^" org-non-link-chars " ]"
5687 "[^\t\n\r]*"
5688 "[^" org-non-link-chars " ]\\)>?")
5689 org-link-re-with-space3
5690 (concat "<?" types-re ":"
5691 "\\([^" org-non-link-chars " ]"
5692 "[^\t\n\r]*\\)")
5693 org-angle-link-re
5694 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5695 types-re)
5696 org-plain-link-re
5697 (concat
5698 "\\<" types-re ":"
5699 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5700 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5701 org-bracket-link-regexp
5702 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5703 org-bracket-link-analytic-regexp
5704 (concat
5705 "\\[\\["
5706 "\\(" types-re ":\\)?"
5707 "\\([^]]+\\)"
5708 "\\]"
5709 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5710 "\\]")
5711 org-bracket-link-analytic-regexp++
5712 (concat
5713 "\\[\\["
5714 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5715 "\\([^]]+\\)"
5716 "\\]"
5717 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5718 "\\]")
5719 org-any-link-re
5720 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5721 org-angle-link-re "\\)\\|\\("
5722 org-plain-link-re "\\)"))))
5724 (org-make-link-regexps)
5726 (defvar org-emph-face nil)
5728 (defun org-do-emphasis-faces (limit)
5729 "Run through the buffer and emphasize strings."
5730 (let (rtn a)
5731 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5732 (let* ((border (char-after (match-beginning 3)))
5733 (bre (regexp-quote (char-to-string border))))
5734 (when (and (not (= border (char-after (match-beginning 4))))
5735 (not (string-match-p (concat bre ".*" bre)
5736 (replace-regexp-in-string
5737 "\n" " "
5738 (substring (match-string 2) 1 -1)))))
5739 (setq rtn t)
5740 (setq a (assoc (match-string 3) org-emphasis-alist))
5741 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5742 'face
5743 (nth 1 a))
5744 (and (nth 2 a)
5745 (org-remove-flyspell-overlays-in
5746 (match-beginning 0) (match-end 0)))
5747 (add-text-properties (match-beginning 2) (match-end 2)
5748 '(font-lock-multiline t org-emphasis t))
5749 (when org-hide-emphasis-markers
5750 (add-text-properties (match-end 4) (match-beginning 5)
5751 '(invisible org-link))
5752 (add-text-properties (match-beginning 3) (match-end 3)
5753 '(invisible org-link)))))
5754 (goto-char (1+ (match-beginning 0))))
5755 rtn))
5757 (defun org-emphasize (&optional char)
5758 "Insert or change an emphasis, i.e. a font like bold or italic.
5759 If there is an active region, change that region to a new emphasis.
5760 If there is no region, just insert the marker characters and position
5761 the cursor between them.
5762 CHAR should be the marker character. If it is a space, it means to
5763 remove the emphasis of the selected region.
5764 If CHAR is not given (for example in an interactive call) it will be
5765 prompted for."
5766 (interactive)
5767 (let ((erc org-emphasis-regexp-components)
5768 (string "") beg end move s)
5769 (if (org-region-active-p)
5770 (setq beg (region-beginning)
5771 end (region-end)
5772 string (buffer-substring beg end))
5773 (setq move t))
5775 (unless char
5776 (message "Emphasis marker or tag: [%s]"
5777 (mapconcat #'car org-emphasis-alist ""))
5778 (setq char (read-char-exclusive)))
5779 (if (equal char ?\s)
5780 (setq s ""
5781 move nil)
5782 (unless (assoc (char-to-string char) org-emphasis-alist)
5783 (user-error "No such emphasis marker: \"%c\"" char))
5784 (setq s (char-to-string char)))
5785 (while (and (> (length string) 1)
5786 (equal (substring string 0 1) (substring string -1))
5787 (assoc (substring string 0 1) org-emphasis-alist))
5788 (setq string (substring string 1 -1)))
5789 (setq string (concat s string s))
5790 (when beg (delete-region beg end))
5791 (unless (or (bolp)
5792 (string-match (concat "[" (nth 0 erc) "\n]")
5793 (char-to-string (char-before (point)))))
5794 (insert " "))
5795 (unless (or (eobp)
5796 (string-match (concat "[" (nth 1 erc) "\n]")
5797 (char-to-string (char-after (point)))))
5798 (insert " ") (backward-char 1))
5799 (insert string)
5800 (and move (backward-char 1))))
5802 (defconst org-nonsticky-props
5803 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5805 (defsubst org-rear-nonsticky-at (pos)
5806 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5808 (defun org-activate-plain-links (limit)
5809 "Add link properties for plain links."
5810 (when (and (re-search-forward org-plain-link-re limit t)
5811 (not (org-in-src-block-p)))
5812 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5813 'face))
5814 (link (org-match-string-no-properties 0)))
5815 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5816 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5817 (add-text-properties (match-beginning 0) (match-end 0)
5818 (list 'mouse-face 'highlight
5819 'face 'org-link
5820 'htmlize-link `(:uri ,link)
5821 'keymap org-mouse-map))
5822 (org-rear-nonsticky-at (match-end 0))
5823 t))))
5825 (defun org-activate-code (limit)
5826 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5827 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5828 (remove-text-properties (match-beginning 0) (match-end 0)
5829 '(display t invisible t intangible t))
5832 (defcustom org-src-fontify-natively t
5833 "When non-nil, fontify code in code blocks."
5834 :type 'boolean
5835 :version "24.4"
5836 :package-version '(Org . "8.3")
5837 :group 'org-appearance
5838 :group 'org-babel)
5840 (defcustom org-allow-promoting-top-level-subtree nil
5841 "When non-nil, allow promoting a top level subtree.
5842 The leading star of the top level headline will be replaced
5843 by a #."
5844 :type 'boolean
5845 :version "24.1"
5846 :group 'org-appearance)
5848 (defun org-fontify-meta-lines-and-blocks (limit)
5849 (condition-case nil
5850 (org-fontify-meta-lines-and-blocks-1 limit)
5851 (error (message "org-mode fontification error"))))
5853 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5854 "Fontify #+ lines and blocks."
5855 (let ((case-fold-search t))
5856 (when (re-search-forward
5857 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5858 limit t)
5859 (let ((beg (match-beginning 0))
5860 (block-start (match-end 0))
5861 (block-end nil)
5862 (lang (match-string 7))
5863 (beg1 (line-beginning-position 2))
5864 (dc1 (downcase (match-string 2)))
5865 (dc3 (downcase (match-string 3)))
5866 end end1 quoting block-type)
5867 (cond
5868 ((and (match-end 4) (equal dc3 "+begin"))
5869 ;; Truly a block
5870 (setq block-type (downcase (match-string 5))
5871 quoting (member block-type org-protecting-blocks))
5872 (when (re-search-forward
5873 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5874 nil t) ;; on purpose, we look further than LIMIT
5875 (setq end (min (point-max) (match-end 0))
5876 end1 (min (point-max) (1- (match-beginning 0))))
5877 (setq block-end (match-beginning 0))
5878 (when quoting
5879 (org-remove-flyspell-overlays-in beg1 end1)
5880 (remove-text-properties beg end
5881 '(display t invisible t intangible t)))
5882 (add-text-properties
5883 beg end '(font-lock-fontified t font-lock-multiline t))
5884 (add-text-properties beg beg1 '(face org-meta-line))
5885 (org-remove-flyspell-overlays-in beg beg1)
5886 (add-text-properties ; For end_src
5887 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5888 (org-remove-flyspell-overlays-in end1 end)
5889 (cond
5890 ((and lang (not (string= lang "")) org-src-fontify-natively)
5891 (org-src-font-lock-fontify-block lang block-start block-end)
5892 (add-text-properties beg1 block-end '(src-block t)))
5893 (quoting
5894 (add-text-properties beg1 (min (point-max) (1+ end1))
5895 '(face org-block))) ; end of source block
5896 ((not org-fontify-quote-and-verse-blocks))
5897 ((string= block-type "quote")
5898 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5899 ((string= block-type "verse")
5900 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5901 (add-text-properties beg beg1 '(face org-block-begin-line))
5902 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5903 '(face org-block-end-line))
5905 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5906 (org-remove-flyspell-overlays-in
5907 (match-beginning 0)
5908 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5909 (add-text-properties
5910 beg (match-end 3)
5911 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5912 '(font-lock-fontified t invisible t)
5913 '(font-lock-fontified t face org-document-info-keyword)))
5914 (add-text-properties
5915 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5916 (if (string-equal dc1 "+title:")
5917 '(font-lock-fontified t face org-document-title)
5918 '(font-lock-fontified t face org-document-info))))
5919 ((equal dc1 "+caption:")
5920 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5921 (remove-text-properties (match-beginning 0) (match-end 0)
5922 '(display t invisible t intangible t))
5923 (add-text-properties (match-beginning 1) (match-end 3)
5924 '(font-lock-fontified t face org-meta-line))
5925 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5926 '(font-lock-fontified t face org-block))
5928 ((member dc3 '(" " ""))
5929 (org-remove-flyspell-overlays-in beg (match-end 0))
5930 (add-text-properties
5931 beg (match-end 0)
5932 '(font-lock-fontified t face font-lock-comment-face)))
5933 (t ;; just any other in-buffer setting, but not indented
5934 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5935 (remove-text-properties (match-beginning 0) (match-end 0)
5936 '(display t invisible t intangible t))
5937 (add-text-properties beg (match-end 0)
5938 '(font-lock-fontified t face org-meta-line))
5939 t))))))
5941 (defun org-fontify-drawers (limit)
5942 "Fontify drawers."
5943 (when (re-search-forward org-drawer-regexp limit t)
5944 (add-text-properties
5945 (match-beginning 0) (match-end 0)
5946 '(font-lock-fontified t face org-special-keyword))
5947 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5950 (defun org-fontify-macros (limit)
5951 "Fontify macros."
5952 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5953 (add-text-properties
5954 (match-beginning 0) (match-end 0)
5955 '(font-lock-fontified t face org-macro))
5956 (when org-hide-macro-markers
5957 (add-text-properties (match-end 2) (match-beginning 2)
5958 '(invisible t))
5959 (add-text-properties (match-beginning 1) (match-end 1)
5960 '(invisible t)))
5961 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5964 (defun org-activate-angle-links (limit)
5965 "Add text properties for angle links."
5966 (when (and (re-search-forward org-angle-link-re limit t)
5967 (not (org-in-src-block-p)))
5968 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5969 (add-text-properties (match-beginning 0) (match-end 0)
5970 (list 'mouse-face 'highlight
5971 'keymap org-mouse-map
5972 'font-lock-multiline t))
5973 (org-rear-nonsticky-at (match-end 0))
5976 (defun org-activate-footnote-links (limit)
5977 "Add text properties for footnotes."
5978 (let ((fn (org-footnote-next-reference-or-definition limit)))
5979 (when fn
5980 (let* ((beg (nth 1 fn))
5981 (end (nth 2 fn))
5982 (label (car fn))
5983 (referencep (/= (line-beginning-position) beg)))
5984 (when (and referencep (nth 3 fn))
5985 (save-excursion
5986 (goto-char beg)
5987 (search-forward (or label "fn:"))
5988 (org-remove-flyspell-overlays-in beg (match-end 0))))
5989 (add-text-properties beg end
5990 (list 'mouse-face 'highlight
5991 'keymap org-mouse-map
5992 'help-echo
5993 (if referencep "Footnote reference"
5994 "Footnote definition")
5995 'font-lock-fontified t
5996 'font-lock-multiline t
5997 'face 'org-footnote))))))
5999 (defun org-activate-bracket-links (limit)
6000 "Add text properties for bracketed links."
6001 (when (and (re-search-forward org-bracket-link-regexp limit t)
6002 (not (org-in-src-block-p)))
6003 (let* ((hl (org-match-string-no-properties 1))
6004 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6005 (ip (org-maybe-intangible
6006 (list 'invisible 'org-link
6007 'keymap org-mouse-map 'mouse-face 'highlight
6008 'font-lock-multiline t 'help-echo help
6009 'htmlize-link `(:uri ,hl))))
6010 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6011 'font-lock-multiline t 'help-echo help
6012 'htmlize-link `(:uri ,hl))))
6013 ;; We need to remove the invisible property here. Table narrowing
6014 ;; may have made some of this invisible.
6015 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6016 (remove-text-properties (match-beginning 0) (match-end 0)
6017 '(invisible nil))
6018 (if (match-end 3)
6019 (progn
6020 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6021 (org-rear-nonsticky-at (match-beginning 3))
6022 (add-text-properties (match-beginning 3) (match-end 3) vp)
6023 (org-rear-nonsticky-at (match-end 3))
6024 (add-text-properties (match-end 3) (match-end 0) ip)
6025 (org-rear-nonsticky-at (match-end 0)))
6026 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6027 (org-rear-nonsticky-at (match-beginning 1))
6028 (add-text-properties (match-beginning 1) (match-end 1) vp)
6029 (org-rear-nonsticky-at (match-end 1))
6030 (add-text-properties (match-end 1) (match-end 0) ip)
6031 (org-rear-nonsticky-at (match-end 0)))
6032 t)))
6034 (defun org-activate-dates (limit)
6035 "Add text properties for dates."
6036 (when (and (re-search-forward org-tsr-regexp-both limit t)
6037 (not (equal (char-before (match-beginning 0)) 91)))
6038 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6039 (add-text-properties (match-beginning 0) (match-end 0)
6040 (list 'mouse-face 'highlight
6041 'keymap org-mouse-map))
6042 (org-rear-nonsticky-at (match-end 0))
6043 (when org-display-custom-times
6044 (if (match-end 3)
6045 (org-display-custom-time (match-beginning 3) (match-end 3))
6046 (org-display-custom-time (match-beginning 1) (match-end 1))))
6049 (defvar-local org-target-link-regexp nil
6050 "Regular expression matching radio targets in plain text.")
6052 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6053 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6054 border border border))
6055 "Regular expression matching a link target.")
6057 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6058 "Regular expression matching a radio target.")
6060 (defconst org-any-target-regexp
6061 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6062 "Regular expression matching any target.")
6064 (defun org-activate-target-links (limit)
6065 "Add text properties for target matches."
6066 (when org-target-link-regexp
6067 (let ((case-fold-search t))
6068 (when (re-search-forward org-target-link-regexp limit t)
6069 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6070 (add-text-properties (match-beginning 1) (match-end 1)
6071 (list 'mouse-face 'highlight
6072 'keymap org-mouse-map
6073 'help-echo "Radio target link"
6074 'org-linked-text t))
6075 (org-rear-nonsticky-at (match-end 1))
6076 t))))
6078 (defun org-update-radio-target-regexp ()
6079 "Find all radio targets in this file and update the regular expression.
6080 Also refresh fontification if needed."
6081 (interactive)
6082 (let ((old-regexp org-target-link-regexp)
6083 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6084 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6085 (targets
6086 (org-with-wide-buffer
6087 (goto-char (point-min))
6088 (let (rtn)
6089 (while (re-search-forward org-radio-target-regexp nil t)
6090 ;; Make sure point is really within the object.
6091 (backward-char)
6092 (let ((obj (org-element-context)))
6093 (when (eq (org-element-type obj) 'radio-target)
6094 (cl-pushnew (org-element-property :value obj) rtn
6095 :test #'equal))))
6096 rtn))))
6097 (setq org-target-link-regexp
6098 (and targets
6099 (concat before-re
6100 (mapconcat
6101 (lambda (x)
6102 (replace-regexp-in-string
6103 " +" "\\s-+" (regexp-quote x) t t))
6104 targets
6105 "\\|")
6106 after-re)))
6107 (unless (equal old-regexp org-target-link-regexp)
6108 ;; Clean-up cache.
6109 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6110 ((not org-target-link-regexp) old-regexp)
6112 (concat before-re
6113 (mapconcat
6114 (lambda (re)
6115 (substring re (length before-re)
6116 (- (length after-re))))
6117 (list old-regexp org-target-link-regexp)
6118 "\\|")
6119 after-re)))))
6120 (org-with-wide-buffer
6121 (goto-char (point-min))
6122 (while (re-search-forward regexp nil t)
6123 (org-element-cache-refresh (match-beginning 1)))))
6124 ;; Re fontify buffer.
6125 (when (memq 'radio org-highlight-links)
6126 (org-restart-font-lock)))))
6128 (defun org-hide-wide-columns (limit)
6129 (let (s e)
6130 (setq s (text-property-any (point) (or limit (point-max))
6131 'org-cwidth t))
6132 (when s
6133 (setq e (next-single-property-change s 'org-cwidth))
6134 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6135 (goto-char e)
6136 t)))
6138 (defvar org-latex-and-related-regexp nil
6139 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6141 (defun org-compute-latex-and-related-regexp ()
6142 "Compute regular expression for LaTeX, entities and sub/superscript.
6143 Result depends on variable `org-highlight-latex-and-related'."
6144 (setq-local
6145 org-latex-and-related-regexp
6146 (let* ((re-sub
6147 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6148 ((eq org-use-sub-superscripts '{})
6149 (list org-match-substring-with-braces-regexp))
6150 (org-use-sub-superscripts (list org-match-substring-regexp))))
6151 (re-latex
6152 (when (memq 'latex org-highlight-latex-and-related)
6153 (let ((matchers (plist-get org-format-latex-options :matchers)))
6154 (delq nil
6155 (mapcar (lambda (x)
6156 (and (member (car x) matchers) (nth 1 x)))
6157 org-latex-regexps)))))
6158 (re-entities
6159 (when (memq 'entities org-highlight-latex-and-related)
6160 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6161 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6163 (defun org-do-latex-and-related (limit)
6164 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6165 LIMIT bounds the search for syntax to highlight. Stop at first
6166 highlighted object, if any. Return t if some highlighting was
6167 done, nil otherwise."
6168 (when (org-string-nw-p org-latex-and-related-regexp)
6169 (catch 'found
6170 (while (re-search-forward org-latex-and-related-regexp limit t)
6171 (unless
6172 (cl-some
6173 (lambda (f)
6174 (memq f '(org-code org-verbatim underline org-special-keyword)))
6175 (save-excursion
6176 (goto-char (1+ (match-beginning 0)))
6177 (face-at-point nil t)))
6178 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6179 '(?_ ?^))
6181 0)))
6182 (font-lock-prepend-text-property
6183 (+ offset (match-beginning 0)) (match-end 0)
6184 'face 'org-latex-and-related)
6185 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6186 '(font-lock-multiline t)))
6187 (throw 'found t)))
6188 nil)))
6190 (defun org-restart-font-lock ()
6191 "Restart `font-lock-mode', to force refontification."
6192 (when (and (boundp 'font-lock-mode) font-lock-mode)
6193 (font-lock-mode -1)
6194 (font-lock-mode 1)))
6196 (defun org-activate-tags (limit)
6197 (when (re-search-forward
6198 (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") limit t)
6199 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6200 (add-text-properties (match-beginning 1) (match-end 1)
6201 (list 'mouse-face 'highlight
6202 'keymap org-mouse-map))
6203 (org-rear-nonsticky-at (match-end 1))
6206 (defun org-outline-level ()
6207 "Compute the outline level of the heading at point.
6209 If this is called at a normal headline, the level is the number
6210 of stars. Use `org-reduced-level' to remove the effect of
6211 `org-odd-levels'. Unlike to `org-current-level', this function
6212 takes into consideration inlinetasks."
6213 (org-with-wide-buffer
6214 (end-of-line)
6215 (if (re-search-backward org-outline-regexp-bol nil t)
6216 (1- (- (match-end 0) (match-beginning 0)))
6217 0)))
6219 (defvar org-font-lock-keywords nil)
6221 (defsubst org-re-property (property &optional literal allow-null value)
6222 "Return a regexp matching a PROPERTY line.
6224 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6225 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6226 non-nil, match properties even without a value.
6228 Match group 3 is set to the value when it exists. If there is no
6229 value and ALLOW-NULL is non-nil, it is set to the empty string.
6231 With optional argument VALUE, match only property lines with
6232 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6233 unless LITERAL is non-nil."
6234 (concat
6235 "^\\(?4:[ \t]*\\)"
6236 (format "\\(?1::\\(?2:%s\\):\\)"
6237 (if literal property (regexp-quote property)))
6238 (cond (value
6239 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6240 (if literal value (regexp-quote value))))
6241 (allow-null
6242 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6244 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6246 (defconst org-property-re
6247 (org-re-property "\\S-+" 'literal t)
6248 "Regular expression matching a property line.
6249 There are four matching groups:
6250 1: :PROPKEY: including the leading and trailing colon,
6251 2: PROPKEY without the leading and trailing colon,
6252 3: PROPVAL without leading or trailing spaces,
6253 4: the indentation of the current line,
6254 5: trailing whitespace.")
6256 (defvar org-font-lock-hook nil
6257 "Functions to be called for special font lock stuff.")
6259 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6261 (defvar org-font-lock-set-keywords-hook nil
6262 "Functions that can manipulate `org-font-lock-extra-keywords'.
6263 This is called after `org-font-lock-extra-keywords' is defined, but before
6264 it is installed to be used by font lock. This can be useful if something
6265 needs to be inserted at a specific position in the font-lock sequence.")
6267 (defun org-font-lock-hook (limit)
6268 "Run `org-font-lock-hook' within LIMIT."
6269 (run-hook-with-args 'org-font-lock-hook limit))
6271 (defun org-set-font-lock-defaults ()
6272 "Set font lock defaults for the current buffer."
6273 (let* ((em org-fontify-emphasized-text)
6274 (lk org-highlight-links)
6275 (org-font-lock-extra-keywords
6276 (list
6277 ;; Call the hook
6278 '(org-font-lock-hook)
6279 ;; Headlines
6280 `(,(if org-fontify-whole-heading-line
6281 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6282 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6283 (1 (org-get-level-face 1))
6284 (2 (org-get-level-face 2))
6285 (3 (org-get-level-face 3)))
6286 ;; Table lines
6287 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6288 (1 'org-table t))
6289 ;; Table internals
6290 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6291 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6292 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6293 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6294 ;; Drawers
6295 '(org-fontify-drawers)
6296 ;; Properties
6297 (list org-property-re
6298 '(1 'org-special-keyword t)
6299 '(3 'org-property-value t))
6300 ;; Links
6301 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6302 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6303 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6304 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6305 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6306 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6307 (when (memq 'footnote lk) '(org-activate-footnote-links))
6308 ;; Targets.
6309 (list org-any-target-regexp '(0 'org-target t))
6310 ;; Diary sexps.
6311 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6312 ;; Macro
6313 '(org-fontify-macros)
6314 '(org-hide-wide-columns (0 nil append))
6315 ;; TODO keyword
6316 (list (format org-heading-keyword-regexp-format
6317 org-todo-regexp)
6318 '(2 (org-get-todo-face 2) t))
6319 ;; DONE
6320 (if org-fontify-done-headline
6321 (list (format org-heading-keyword-regexp-format
6322 (concat
6323 "\\(?:"
6324 (mapconcat 'regexp-quote org-done-keywords "\\|")
6325 "\\)"))
6326 '(2 'org-headline-done t))
6327 nil)
6328 ;; Priorities
6329 '(org-font-lock-add-priority-faces)
6330 ;; Tags
6331 '(org-font-lock-add-tag-faces)
6332 ;; Tags groups
6333 (when (and org-group-tags org-tag-groups-alist)
6334 (list (concat org-outline-regexp-bol ".+\\(:"
6335 (regexp-opt (mapcar 'car org-tag-groups-alist))
6336 ":\\).*$")
6337 '(1 'org-tag-group prepend)))
6338 ;; Special keywords
6339 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6340 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6341 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6342 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6343 ;; Emphasis
6344 (when em
6345 (if (featurep 'xemacs)
6346 '(org-do-emphasis-faces (0 nil append))
6347 '(org-do-emphasis-faces)))
6348 ;; Checkboxes
6349 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6350 1 'org-checkbox prepend)
6351 (when (cdr (assq 'checkbox org-list-automatic-rules))
6352 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6353 (0 (org-get-checkbox-statistics-face) t)))
6354 ;; Description list items
6355 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6356 1 'org-list-dt prepend)
6357 ;; ARCHIVEd headings
6358 (list (concat
6359 org-outline-regexp-bol
6360 "\\(.*:" org-archive-tag ":.*\\)")
6361 '(1 'org-archived prepend))
6362 ;; Specials
6363 '(org-do-latex-and-related)
6364 '(org-fontify-entities)
6365 '(org-raise-scripts)
6366 ;; Code
6367 '(org-activate-code (1 'org-code t))
6368 ;; COMMENT
6369 (list (format
6370 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6371 org-todo-regexp
6372 org-comment-string)
6373 '(9 'org-special-keyword t))
6374 ;; Blocks and meta lines
6375 '(org-fontify-meta-lines-and-blocks))))
6376 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6377 (run-hooks 'org-font-lock-set-keywords-hook)
6378 ;; Now set the full font-lock-keywords
6379 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6380 (setq-local font-lock-defaults
6381 '(org-font-lock-keywords t nil nil backward-paragraph))
6382 (kill-local-variable 'font-lock-keywords) nil))
6384 (defun org-toggle-pretty-entities ()
6385 "Toggle the composition display of entities as UTF8 characters."
6386 (interactive)
6387 (setq-local org-pretty-entities (not org-pretty-entities))
6388 (org-restart-font-lock)
6389 (if org-pretty-entities
6390 (message "Entities are now displayed as UTF8 characters")
6391 (save-restriction
6392 (widen)
6393 (org-decompose-region (point-min) (point-max))
6394 (message "Entities are now displayed as plain text"))))
6396 (defvar-local org-custom-properties-overlays nil
6397 "List of overlays used for custom properties.")
6399 (defun org-toggle-custom-properties-visibility ()
6400 "Display or hide properties in `org-custom-properties'."
6401 (interactive)
6402 (if org-custom-properties-overlays
6403 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6404 (setq org-custom-properties-overlays nil))
6405 (when org-custom-properties
6406 (org-with-wide-buffer
6407 (goto-char (point-min))
6408 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6409 (while (re-search-forward regexp nil t)
6410 (let ((end (cdr (save-match-data (org-get-property-block)))))
6411 (when (and end (< (point) end))
6412 ;; Hide first custom property in current drawer.
6413 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6414 (overlay-put o 'invisible t)
6415 (overlay-put o 'org-custom-property t)
6416 (push o org-custom-properties-overlays))
6417 ;; Hide additional custom properties in the same drawer.
6418 (while (re-search-forward regexp end t)
6419 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6420 (overlay-put o 'invisible t)
6421 (overlay-put o 'org-custom-property t)
6422 (push o org-custom-properties-overlays)))))
6423 ;; Each entry is limited to a single property drawer.
6424 (outline-next-heading)))))))
6426 (defun org-fontify-entities (limit)
6427 "Find an entity to fontify."
6428 (let (ee)
6429 (when org-pretty-entities
6430 (catch 'match
6431 ;; "\_ "-family is left out on purpose. Only the first one,
6432 ;; i.e., "\_ ", could be fontified anyway, and it would be
6433 ;; confusing when adding a second white space character.
6434 (while (re-search-forward
6435 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6436 limit t)
6437 (when (and (not (org-at-comment-p))
6438 (setq ee (org-entity-get (match-string 1)))
6439 (= (length (nth 6 ee)) 1))
6440 (let* ((end (if (equal (match-string 2) "{}")
6441 (match-end 2)
6442 (match-end 1))))
6443 (add-text-properties
6444 (match-beginning 0) end
6445 (list 'font-lock-fontified t))
6446 (compose-region (match-beginning 0) end
6447 (nth 6 ee) nil)
6448 (backward-char 1)
6449 (throw 'match t))))
6450 nil))))
6452 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6453 "Fontify string S like in Org-mode."
6454 (with-temp-buffer
6455 (insert s)
6456 (let ((org-odd-levels-only odd-levels))
6457 (org-mode)
6458 (org-font-lock-ensure)
6459 (buffer-string))))
6461 (defvar org-m nil)
6462 (defvar org-l nil)
6463 (defvar org-f nil)
6464 (defun org-get-level-face (n)
6465 "Get the right face for match N in font-lock matching of headlines."
6466 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6467 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6468 (if org-cycle-level-faces
6469 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6470 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6471 (cond
6472 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6473 ((eq n 2) org-f)
6474 (t (unless org-level-color-stars-only org-f))))
6476 (defun org-face-from-face-or-color (context inherit face-or-color)
6477 "Create a face list that inherits INHERIT, but sets the foreground color.
6478 When FACE-OR-COLOR is not a string, just return it."
6479 (if (stringp face-or-color)
6480 (list :inherit inherit
6481 (cdr (assoc context org-faces-easy-properties))
6482 face-or-color)
6483 face-or-color))
6485 (defun org-get-todo-face (kwd)
6486 "Get the right face for a TODO keyword KWD.
6487 If KWD is a number, get the corresponding match group."
6488 (when (numberp kwd) (setq kwd (match-string kwd)))
6489 (or (org-face-from-face-or-color
6490 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6491 (and (member kwd org-done-keywords) 'org-done)
6492 'org-todo))
6494 (defun org-get-priority-face (priority)
6495 "Get the right face for PRIORITY.
6496 PRIORITY is a character."
6497 (or (org-face-from-face-or-color
6498 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6499 'org-priority))
6501 (defun org-get-tag-face (tag)
6502 "Get the right face for TAG.
6503 If TAG is a number, get the corresponding match group."
6504 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6505 (or (org-face-from-face-or-color
6506 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6507 'org-tag)))
6509 (defun org-font-lock-add-priority-faces (limit)
6510 "Add the special priority faces."
6511 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6512 (add-text-properties
6513 (match-beginning 1) (match-end 1)
6514 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6515 'font-lock-fontified t))))
6517 (defun org-font-lock-add-tag-faces (limit)
6518 "Add the special tag faces."
6519 (when (and org-tag-faces org-tags-special-faces-re)
6520 (while (re-search-forward org-tags-special-faces-re limit t)
6521 (add-text-properties (match-beginning 1) (match-end 1)
6522 (list 'face (org-get-tag-face 1)
6523 'font-lock-fontified t))
6524 (backward-char 1))))
6526 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6527 "Remove fontification and activation overlays from links."
6528 (font-lock-default-unfontify-region beg end)
6529 (let* ((buffer-undo-list t)
6530 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6531 (inhibit-modification-hooks t)
6532 deactivate-mark buffer-file-name buffer-file-truename)
6533 (org-decompose-region beg end)
6534 (remove-text-properties beg end
6535 '(mouse-face t keymap t org-linked-text t
6536 invisible t intangible t
6537 org-emphasis t))
6538 (org-remove-font-lock-display-properties beg end)))
6540 (defconst org-script-display '(((raise -0.3) (height 0.7))
6541 ((raise 0.3) (height 0.7))
6542 ((raise -0.5))
6543 ((raise 0.5)))
6544 "Display properties for showing superscripts and subscripts.")
6546 (defun org-remove-font-lock-display-properties (beg end)
6547 "Remove specific display properties that have been added by font lock.
6548 The will remove the raise properties that are used to show superscripts
6549 and subscripts."
6550 (let (next prop)
6551 (while (< beg end)
6552 (setq next (next-single-property-change beg 'display nil end)
6553 prop (get-text-property beg 'display))
6554 (when (member prop org-script-display)
6555 (put-text-property beg next 'display nil))
6556 (setq beg next))))
6558 (defun org-raise-scripts (limit)
6559 "Add raise properties to sub/superscripts."
6560 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6561 (re-search-forward
6562 (if (eq org-use-sub-superscripts t)
6563 org-match-substring-regexp
6564 org-match-substring-with-braces-regexp)
6565 limit t))
6566 (let* ((pos (point)) table-p comment-p
6567 (mpos (match-beginning 3))
6568 (emph-p (get-text-property mpos 'org-emphasis))
6569 (link-p (get-text-property mpos 'mouse-face))
6570 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6571 (goto-char (point-at-bol))
6572 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6573 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6574 (goto-char pos)
6575 ;; Handle a_b^c
6576 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6577 (unless (or comment-p emph-p link-p keyw-p)
6578 (put-text-property (match-beginning 3) (match-end 0)
6579 'display
6580 (if (equal (char-after (match-beginning 2)) ?^)
6581 (nth (if table-p 3 1) org-script-display)
6582 (nth (if table-p 2 0) org-script-display)))
6583 (add-text-properties (match-beginning 2) (match-end 2)
6584 (list 'invisible t
6585 'org-dwidth t 'org-dwidth-n 1))
6586 (if (and (eq (char-after (match-beginning 3)) ?{)
6587 (eq (char-before (match-end 3)) ?}))
6588 (progn
6589 (add-text-properties
6590 (match-beginning 3) (1+ (match-beginning 3))
6591 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6592 (add-text-properties
6593 (1- (match-end 3)) (match-end 3)
6594 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6595 t)))
6597 ;;;; Visibility cycling, including org-goto and indirect buffer
6599 ;;; Cycling
6601 (defvar-local org-cycle-global-status nil)
6602 (put 'org-cycle-global-status 'org-state t)
6603 (defvar-local org-cycle-subtree-status nil)
6604 (put 'org-cycle-subtree-status 'org-state t)
6606 (defvar org-inlinetask-min-level)
6608 (defun org-unlogged-message (&rest args)
6609 "Display a message, but avoid logging it in the *Messages* buffer."
6610 (let ((message-log-max nil))
6611 (apply 'message args)))
6613 ;;;###autoload
6614 (defun org-cycle (&optional arg)
6615 "TAB-action and visibility cycling for Org-mode.
6617 This is the command invoked in Org-mode by the TAB key. Its main purpose
6618 is outline visibility cycling, but it also invokes other actions
6619 in special contexts.
6621 - When this function is called with a prefix argument, rotate the entire
6622 buffer through 3 states (global cycling)
6623 1. OVERVIEW: Show only top-level headlines.
6624 2. CONTENTS: Show all headlines of all levels, but no body text.
6625 3. SHOW ALL: Show everything.
6626 With a double \\[universal-argument] prefix argument, \
6627 switch to the startup visibility,
6628 determined by the variable `org-startup-folded', and by any VISIBILITY
6629 properties in the buffer.
6630 With a triple \\[universal-argument] prefix argument, \
6631 show the entire buffer, including any drawers.
6633 - When inside a table, re-align the table and move to the next field.
6635 - When point is at the beginning of a headline, rotate the subtree started
6636 by this line through 3 different states (local cycling)
6637 1. FOLDED: Only the main headline is shown.
6638 2. CHILDREN: The main headline and the direct children are shown.
6639 From this state, you can move to one of the children
6640 and zoom in further.
6641 3. SUBTREE: Show the entire subtree, including body text.
6642 If there is no subtree, switch directly from CHILDREN to FOLDED.
6644 - When point is at the beginning of an empty headline and the variable
6645 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6646 of the headline by demoting and promoting it to likely levels. This
6647 speeds up creation document structure by pressing TAB once or several
6648 times right after creating a new headline.
6650 - When there is a numeric prefix, go up to a heading with level ARG, do
6651 a `show-subtree' and return to the previous cursor position. If ARG
6652 is negative, go up that many levels.
6654 - When point is not at the beginning of a headline, execute the global
6655 binding for TAB, which is re-indenting the line. See the option
6656 `org-cycle-emulate-tab' for details.
6658 - Special case: if point is at the beginning of the buffer and there is
6659 no headline in line 1, this function will act as if called with prefix arg
6660 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6661 But only if also the variable `org-cycle-global-at-bob' is t."
6662 (interactive "P")
6663 (org-load-modules-maybe)
6664 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6665 (and org-cycle-level-after-item/entry-creation
6666 (or (org-cycle-level)
6667 (org-cycle-item-indentation))))
6668 (let* ((limit-level
6669 (or org-cycle-max-level
6670 (and (boundp 'org-inlinetask-min-level)
6671 org-inlinetask-min-level
6672 (1- org-inlinetask-min-level))))
6673 (nstars (and limit-level
6674 (if org-odd-levels-only
6675 (and limit-level (1- (* limit-level 2)))
6676 limit-level)))
6677 (org-outline-regexp
6678 (if (not (derived-mode-p 'org-mode))
6679 outline-regexp
6680 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6681 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6682 (not (looking-at org-outline-regexp))))
6683 (org-cycle-hook
6684 (if bob-special
6685 (delq 'org-optimize-window-after-visibility-change
6686 (copy-sequence org-cycle-hook))
6687 org-cycle-hook))
6688 (pos (point)))
6690 (when (or bob-special (equal arg '(4)))
6691 ;; special case: use global cycling
6692 (setq arg t))
6694 (cond
6696 ((equal arg '(16))
6697 (setq last-command 'dummy)
6698 (org-set-startup-visibility)
6699 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6701 ((equal arg '(64))
6702 (outline-show-all)
6703 (org-unlogged-message "Entire buffer visible, including drawers"))
6705 ;; Try cdlatex TAB completion
6706 ((org-try-cdlatex-tab))
6708 ;; Table: enter it or move to the next field.
6709 ((org-at-table-p 'any)
6710 (if (org-at-table.el-p)
6711 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6712 Use \\[org-edit-special] to edit table.el tables"))
6713 (if arg (org-table-edit-field t)
6714 (org-table-justify-field-maybe)
6715 (call-interactively 'org-table-next-field))))
6717 ((run-hook-with-args-until-success
6718 'org-tab-after-check-for-table-hook))
6720 ;; Global cycling: delegate to `org-cycle-internal-global'.
6721 ((eq arg t) (org-cycle-internal-global))
6723 ;; Drawers: delegate to `org-flag-drawer'.
6724 ((save-excursion
6725 (beginning-of-line 1)
6726 (looking-at org-drawer-regexp))
6727 (org-flag-drawer ; toggle block visibility
6728 (not (get-char-property (match-end 0) 'invisible))))
6730 ;; Show-subtree, ARG levels up from here.
6731 ((integerp arg)
6732 (save-excursion
6733 (org-back-to-heading)
6734 (outline-up-heading (if (< arg 0) (- arg)
6735 (- (funcall outline-level) arg)))
6736 (org-show-subtree)))
6738 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6739 ((and (featurep 'org-inlinetask)
6740 (org-inlinetask-at-task-p)
6741 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6742 (org-inlinetask-toggle-visibility))
6744 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6745 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6746 (save-excursion (move-beginning-of-line 1)
6747 (looking-at org-outline-regexp)))
6748 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6749 (org-cycle-internal-local))
6751 ;; From there: TAB emulation and template completion.
6752 (buffer-read-only (org-back-to-heading))
6754 ((run-hook-with-args-until-success
6755 'org-tab-after-check-for-cycling-hook))
6757 ((org-try-structure-completion))
6759 ((run-hook-with-args-until-success
6760 'org-tab-before-tab-emulation-hook))
6762 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6763 (or (not (bolp))
6764 (not (looking-at org-outline-regexp))))
6765 (call-interactively (global-key-binding "\t")))
6767 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6768 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6769 (or (and (eq org-cycle-emulate-tab 'white)
6770 (= (match-end 0) (point-at-eol)))
6771 (and (eq org-cycle-emulate-tab 'whitestart)
6772 (>= (match-end 0) pos))))
6774 (eq org-cycle-emulate-tab t))
6775 (call-interactively (global-key-binding "\t")))
6777 (t (save-excursion
6778 (org-back-to-heading)
6779 (org-cycle)))))))
6781 (defun org-cycle-internal-global ()
6782 "Do the global cycling action."
6783 ;; Hack to avoid display of messages for .org attachments in Gnus
6784 (let ((ga (string-match "\\*fontification" (buffer-name))))
6785 (cond
6786 ((and (eq last-command this-command)
6787 (eq org-cycle-global-status 'overview))
6788 ;; We just created the overview - now do table of contents
6789 ;; This can be slow in very large buffers, so indicate action
6790 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6791 (unless ga (org-unlogged-message "CONTENTS..."))
6792 (org-content)
6793 (unless ga (org-unlogged-message "CONTENTS...done"))
6794 (setq org-cycle-global-status 'contents)
6795 (run-hook-with-args 'org-cycle-hook 'contents))
6797 ((and (eq last-command this-command)
6798 (eq org-cycle-global-status 'contents))
6799 ;; We just showed the table of contents - now show everything
6800 (run-hook-with-args 'org-pre-cycle-hook 'all)
6801 (outline-show-all)
6802 (unless ga (org-unlogged-message "SHOW ALL"))
6803 (setq org-cycle-global-status 'all)
6804 (run-hook-with-args 'org-cycle-hook 'all))
6807 ;; Default action: go to overview
6808 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6809 (org-overview)
6810 (unless ga (org-unlogged-message "OVERVIEW"))
6811 (setq org-cycle-global-status 'overview)
6812 (run-hook-with-args 'org-cycle-hook 'overview)))))
6814 (defvar org-called-with-limited-levels nil
6815 "Non-nil when `org-with-limited-levels' is currently active.")
6817 (defun org-cycle-internal-local ()
6818 "Do the local cycling action."
6819 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6820 ;; First, determine end of headline (EOH), end of subtree or item
6821 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6822 (save-excursion
6823 (if (org-at-item-p)
6824 (progn
6825 (beginning-of-line)
6826 (setq struct (org-list-struct))
6827 (setq eoh (point-at-eol))
6828 (setq eos (org-list-get-item-end-before-blank (point) struct))
6829 (setq has-children (org-list-has-child-p (point) struct)))
6830 (org-back-to-heading)
6831 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6832 (setq eos (save-excursion (org-end-of-subtree t t)
6833 (when (bolp) (backward-char)) (point)))
6834 (setq has-children
6835 (or (save-excursion
6836 (let ((level (funcall outline-level)))
6837 (outline-next-heading)
6838 (and (org-at-heading-p t)
6839 (> (funcall outline-level) level))))
6840 (save-excursion
6841 (org-list-search-forward (org-item-beginning-re) eos t)))))
6842 ;; Determine end invisible part of buffer (EOL)
6843 (beginning-of-line 2)
6844 ;; XEmacs doesn't have `next-single-char-property-change'
6845 (if (featurep 'xemacs)
6846 (while (and (not (eobp)) ;; this is like `next-line'
6847 (get-char-property (1- (point)) 'invisible))
6848 (beginning-of-line 2))
6849 (while (and (not (eobp)) ;; this is like `next-line'
6850 (get-char-property (1- (point)) 'invisible))
6851 (goto-char (next-single-char-property-change (point) 'invisible))
6852 (and (eolp) (beginning-of-line 2))))
6853 (setq eol (point)))
6854 ;; Find out what to do next and set `this-command'
6855 (cond
6856 ((= eos eoh)
6857 ;; Nothing is hidden behind this heading
6858 (unless (org-before-first-heading-p)
6859 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6860 (org-unlogged-message "EMPTY ENTRY")
6861 (setq org-cycle-subtree-status nil)
6862 (save-excursion
6863 (goto-char eos)
6864 (outline-next-heading)
6865 (when (outline-invisible-p) (org-flag-heading nil))))
6866 ((and (or (>= eol eos)
6867 (not (string-match "\\S-" (buffer-substring eol eos))))
6868 (or has-children
6869 (not (setq children-skipped
6870 org-cycle-skip-children-state-if-no-children))))
6871 ;; Entire subtree is hidden in one line: children view
6872 (unless (org-before-first-heading-p)
6873 (run-hook-with-args 'org-pre-cycle-hook 'children))
6874 (if (org-at-item-p)
6875 (org-list-set-item-visibility (point-at-bol) struct 'children)
6876 (org-show-entry)
6877 (org-with-limited-levels (org-show-children))
6878 ;; FIXME: This slows down the func way too much.
6879 ;; How keep drawers hidden in subtree anyway?
6880 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6881 ;; (org-cycle-hide-drawers 'subtree))
6883 ;; Fold every list in subtree to top-level items.
6884 (when (eq org-cycle-include-plain-lists 'integrate)
6885 (save-excursion
6886 (org-back-to-heading)
6887 (while (org-list-search-forward (org-item-beginning-re) eos t)
6888 (beginning-of-line 1)
6889 (let* ((struct (org-list-struct))
6890 (prevs (org-list-prevs-alist struct))
6891 (end (org-list-get-bottom-point struct)))
6892 (dolist (e (org-list-get-all-items (point) struct prevs))
6893 (org-list-set-item-visibility e struct 'folded))
6894 (goto-char (if (< end eos) end eos)))))))
6895 (org-unlogged-message "CHILDREN")
6896 (save-excursion
6897 (goto-char eos)
6898 (outline-next-heading)
6899 (when (outline-invisible-p) (org-flag-heading nil)))
6900 (setq org-cycle-subtree-status 'children)
6901 (unless (org-before-first-heading-p)
6902 (run-hook-with-args 'org-cycle-hook 'children)))
6903 ((or children-skipped
6904 (and (eq last-command this-command)
6905 (eq org-cycle-subtree-status 'children)))
6906 ;; We just showed the children, or no children are there,
6907 ;; now show everything.
6908 (unless (org-before-first-heading-p)
6909 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6910 (outline-flag-region eoh eos nil)
6911 (org-unlogged-message
6912 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6913 (setq org-cycle-subtree-status 'subtree)
6914 (unless (org-before-first-heading-p)
6915 (run-hook-with-args 'org-cycle-hook 'subtree)))
6917 ;; Default action: hide the subtree.
6918 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6919 (outline-flag-region eoh eos t)
6920 (org-unlogged-message "FOLDED")
6921 (setq org-cycle-subtree-status 'folded)
6922 (unless (org-before-first-heading-p)
6923 (run-hook-with-args 'org-cycle-hook 'folded))))))
6925 ;;;###autoload
6926 (defun org-global-cycle (&optional arg)
6927 "Cycle the global visibility. For details see `org-cycle'.
6928 With \\[universal-argument] prefix arg, switch to startup visibility.
6929 With a numeric prefix, show all headlines up to that level."
6930 (interactive "P")
6931 (let ((org-cycle-include-plain-lists
6932 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6933 (cond
6934 ((integerp arg)
6935 (outline-show-all)
6936 (outline-hide-sublevels arg)
6937 (setq org-cycle-global-status 'contents))
6938 ((equal arg '(4))
6939 (org-set-startup-visibility)
6940 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6942 (org-cycle '(4))))))
6944 (defun org-set-startup-visibility ()
6945 "Set the visibility required by startup options and properties."
6946 (cond
6947 ((eq org-startup-folded t)
6948 (org-overview))
6949 ((eq org-startup-folded 'content)
6950 (org-content))
6951 ((or (eq org-startup-folded 'showeverything)
6952 (eq org-startup-folded nil))
6953 (outline-show-all)))
6954 (unless (eq org-startup-folded 'showeverything)
6955 (when org-hide-block-startup (org-hide-block-all))
6956 (org-set-visibility-according-to-property 'no-cleanup)
6957 (org-cycle-hide-archived-subtrees 'all)
6958 (org-cycle-hide-drawers 'all)
6959 (org-cycle-show-empty-lines t)))
6961 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6962 "Switch subtree visibilities according to :VISIBILITY: property."
6963 (interactive)
6964 (org-with-wide-buffer
6965 (goto-char (point-min))
6966 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6967 (if (not (org-at-property-p)) (outline-next-heading)
6968 (let ((state (match-string 3)))
6969 (save-excursion
6970 (org-back-to-heading t)
6971 (outline-hide-subtree)
6972 (org-reveal)
6973 (cond
6974 ((equal state "folded")
6975 (outline-hide-subtree))
6976 ((equal state "children")
6977 (org-show-hidden-entry)
6978 (org-show-children))
6979 ((equal state "content")
6980 (save-excursion
6981 (save-restriction
6982 (org-narrow-to-subtree)
6983 (org-content))))
6984 ((member state '("all" "showall"))
6985 (outline-show-subtree)))))))
6986 (unless no-cleanup
6987 (org-cycle-hide-archived-subtrees 'all)
6988 (org-cycle-hide-drawers 'all)
6989 (org-cycle-show-empty-lines 'all))))
6991 ;; This function uses outline-regexp instead of the more fundamental
6992 ;; org-outline-regexp so that org-cycle-global works outside of Org
6993 ;; buffers, where outline-regexp is needed.
6994 (defun org-overview ()
6995 "Switch to overview mode, showing only top-level headlines.
6996 This shows all headlines with a level equal or greater than the level
6997 of the first headline in the buffer. This is important, because if the
6998 first headline is not level one, then (hide-sublevels 1) gives confusing
6999 results."
7000 (interactive)
7001 (save-excursion
7002 (let ((level
7003 (save-excursion
7004 (goto-char (point-min))
7005 (when (re-search-forward (concat "^" outline-regexp) nil t)
7006 (goto-char (match-beginning 0))
7007 (funcall outline-level)))))
7008 (and level (outline-hide-sublevels level)))))
7010 (defun org-content (&optional arg)
7011 "Show all headlines in the buffer, like a table of contents.
7012 With numerical argument N, show content up to level N."
7013 (interactive "P")
7014 (org-overview)
7015 (save-excursion
7016 ;; Visit all headings and show their offspring
7017 (and (integerp arg) (org-overview))
7018 (goto-char (point-max))
7019 (catch 'exit
7020 (while (and (progn (condition-case nil
7021 (outline-previous-visible-heading 1)
7022 (error (goto-char (point-min))))
7024 (looking-at org-outline-regexp))
7025 (if (integerp arg)
7026 (org-show-children (1- arg))
7027 (outline-show-branches))
7028 (when (bobp) (throw 'exit nil))))))
7030 (defun org-optimize-window-after-visibility-change (state)
7031 "Adjust the window after a change in outline visibility.
7032 This function is the default value of the hook `org-cycle-hook'."
7033 (when (get-buffer-window (current-buffer))
7034 (cond
7035 ((eq state 'content) nil)
7036 ((eq state 'all) nil)
7037 ((eq state 'folded) nil)
7038 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7039 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7041 (defun org-remove-empty-overlays-at (pos)
7042 "Remove outline overlays that do not contain non-white stuff."
7043 (dolist (o (overlays-at pos))
7044 (and (eq 'outline (overlay-get o 'invisible))
7045 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7046 (overlay-end o))))
7047 (delete-overlay o))))
7049 (defun org-clean-visibility-after-subtree-move ()
7050 "Fix visibility issues after moving a subtree."
7051 ;; First, find a reasonable region to look at:
7052 ;; Start two siblings above, end three below
7053 (let* ((beg (save-excursion
7054 (and (org-get-last-sibling)
7055 (org-get-last-sibling))
7056 (point)))
7057 (end (save-excursion
7058 (and (org-get-next-sibling)
7059 (org-get-next-sibling)
7060 (org-get-next-sibling))
7061 (if (org-at-heading-p)
7062 (point-at-eol)
7063 (point))))
7064 (level (looking-at "\\*+"))
7065 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7066 (save-excursion
7067 (save-restriction
7068 (narrow-to-region beg end)
7069 (when re
7070 ;; Properly fold already folded siblings
7071 (goto-char (point-min))
7072 (while (re-search-forward re nil t)
7073 (when (and (not (outline-invisible-p))
7074 (save-excursion
7075 (goto-char (point-at-eol)) (outline-invisible-p)))
7076 (outline-hide-entry))))
7077 (org-cycle-show-empty-lines 'overview)
7078 (org-cycle-hide-drawers 'overview)))))
7080 (defun org-cycle-show-empty-lines (state)
7081 "Show empty lines above all visible headlines.
7082 The region to be covered depends on STATE when called through
7083 `org-cycle-hook'. Lisp program can use t for STATE to get the
7084 entire buffer covered. Note that an empty line is only shown if there
7085 are at least `org-cycle-separator-lines' empty lines before the headline."
7086 (when (/= org-cycle-separator-lines 0)
7087 (save-excursion
7088 (let* ((n (abs org-cycle-separator-lines))
7089 (re (cond
7090 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7091 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7092 (t (let ((ns (number-to-string (- n 2))))
7093 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7094 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7095 beg end)
7096 (cond
7097 ((memq state '(overview contents t))
7098 (setq beg (point-min) end (point-max)))
7099 ((memq state '(children folded))
7100 (setq beg (point)
7101 end (progn (org-end-of-subtree t t)
7102 (line-beginning-position 2)))))
7103 (when beg
7104 (goto-char beg)
7105 (while (re-search-forward re end t)
7106 (unless (get-char-property (match-end 1) 'invisible)
7107 (let ((e (match-end 1))
7108 (b (if (>= org-cycle-separator-lines 0)
7109 (match-beginning 1)
7110 (save-excursion
7111 (goto-char (match-beginning 0))
7112 (skip-chars-backward " \t\n")
7113 (line-end-position)))))
7114 (outline-flag-region b e nil))))))))
7115 ;; Never hide empty lines at the end of the file.
7116 (save-excursion
7117 (goto-char (point-max))
7118 (outline-previous-heading)
7119 (outline-end-of-heading)
7120 (when (and (looking-at "[ \t\n]+")
7121 (= (match-end 0) (point-max)))
7122 (outline-flag-region (point) (match-end 0) nil))))
7124 (defun org-show-empty-lines-in-parent ()
7125 "Move to the parent and re-show empty lines before visible headlines."
7126 (save-excursion
7127 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7128 (org-cycle-show-empty-lines context))))
7130 (defun org-files-list ()
7131 "Return `org-agenda-files' list, plus all open org-mode files.
7132 This is useful for operations that need to scan all of a user's
7133 open and agenda-wise Org files."
7134 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7135 (dolist (buf (buffer-list))
7136 (with-current-buffer buf
7137 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7138 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7139 files))
7141 (defsubst org-entry-beginning-position ()
7142 "Return the beginning position of the current entry."
7143 (save-excursion (org-back-to-heading t) (point)))
7145 (defsubst org-entry-end-position ()
7146 "Return the end position of the current entry."
7147 (save-excursion (outline-next-heading) (point)))
7149 (defun org-cycle-hide-drawers (state &optional exceptions)
7150 "Re-hide all drawers after a visibility state change.
7151 When non-nil, optional argument EXCEPTIONS is a list of strings
7152 specifying which drawers should not be hidden."
7153 (when (and (derived-mode-p 'org-mode)
7154 (not (memq state '(overview folded contents))))
7155 (save-excursion
7156 (let* ((globalp (memq state '(contents all)))
7157 (beg (if globalp (point-min) (point)))
7158 (end (if globalp (point-max)
7159 (if (eq state 'children)
7160 (save-excursion (outline-next-heading) (point))
7161 (org-end-of-subtree t)))))
7162 (goto-char beg)
7163 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7164 (unless (member-ignore-case (match-string 1) exceptions)
7165 (let ((drawer (org-element-at-point)))
7166 (when (memq (org-element-type drawer) '(drawer property-drawer))
7167 (org-flag-drawer t drawer)
7168 ;; Make sure to skip drawer entirely or we might flag
7169 ;; it another time when matching its ending line with
7170 ;; `org-drawer-regexp'.
7171 (goto-char (org-element-property :end drawer))))))))))
7173 (defun org-flag-drawer (flag &optional element)
7174 "When FLAG is non-nil, hide the drawer we are at.
7175 Otherwise make it visible. When optional argument ELEMENT is
7176 a parsed drawer, as returned by `org-element-at-point', hide or
7177 show that drawer instead."
7178 (when (save-excursion
7179 (beginning-of-line)
7180 (org-looking-at-p org-drawer-regexp))
7181 (let ((drawer (or element (org-element-at-point))))
7182 (when (memq (org-element-type drawer) '(drawer property-drawer))
7183 (let ((post (org-element-property :post-affiliated drawer)))
7184 (save-excursion
7185 (outline-flag-region
7186 (progn (goto-char post) (line-end-position))
7187 (progn (goto-char (org-element-property :end drawer))
7188 (skip-chars-backward " \r\t\n")
7189 (line-end-position))
7190 flag))
7191 ;; When the drawer is hidden away, make sure point lies in
7192 ;; a visible part of the buffer.
7193 (when (and flag (> (line-beginning-position) post))
7194 (goto-char post)))))))
7196 (defun org-subtree-end-visible-p ()
7197 "Is the end of the current subtree visible?"
7198 (pos-visible-in-window-p
7199 (save-excursion (org-end-of-subtree t) (point))))
7201 (defun org-first-headline-recenter ()
7202 "Move cursor to the first headline and recenter the headline."
7203 (goto-char (point-min))
7204 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7205 (set-window-start (selected-window) (point-at-bol))))
7207 ;;; Saving and restoring visibility
7209 (defun org-outline-overlay-data (&optional use-markers)
7210 "Return a list of the locations of all outline overlays.
7211 These are overlays with the `invisible' property value `outline'.
7212 The return value is a list of cons cells, with start and stop
7213 positions for each overlay.
7214 If USE-MARKERS is set, return the positions as markers."
7215 (let (beg end)
7216 (save-excursion
7217 (save-restriction
7218 (widen)
7219 (delq nil
7220 (mapcar (lambda (o)
7221 (when (eq (overlay-get o 'invisible) 'outline)
7222 (setq beg (overlay-start o)
7223 end (overlay-end o))
7224 (and beg end (> end beg)
7225 (if use-markers
7226 (cons (copy-marker beg)
7227 (copy-marker end t))
7228 (cons beg end)))))
7229 (overlays-in (point-min) (point-max))))))))
7231 (defun org-set-outline-overlay-data (data)
7232 "Create visibility overlays for all positions in DATA.
7233 DATA should have been made by `org-outline-overlay-data'."
7234 (org-with-wide-buffer
7235 (outline-show-all)
7236 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7238 ;;; Folding of blocks
7240 (defvar-local org-hide-block-overlays nil
7241 "Overlays hiding blocks.")
7243 (defun org-block-map (function &optional start end)
7244 "Call FUNCTION at the head of all source blocks in the current buffer.
7245 Optional arguments START and END can be used to limit the range."
7246 (let ((start (or start (point-min)))
7247 (end (or end (point-max))))
7248 (save-excursion
7249 (goto-char start)
7250 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7251 (save-excursion
7252 (save-match-data
7253 (goto-char (match-beginning 0))
7254 (funcall function)))))))
7256 (defun org-hide-block-toggle-all ()
7257 "Toggle the visibility of all blocks in the current buffer."
7258 (org-block-map 'org-hide-block-toggle))
7260 (defun org-hide-block-all ()
7261 "Fold all blocks in the current buffer."
7262 (interactive)
7263 (org-show-block-all)
7264 (org-block-map 'org-hide-block-toggle-maybe))
7266 (defun org-show-block-all ()
7267 "Unfold all blocks in the current buffer."
7268 (interactive)
7269 (mapc #'delete-overlay org-hide-block-overlays)
7270 (setq org-hide-block-overlays nil))
7272 (defun org-hide-block-toggle-maybe ()
7273 "Toggle visibility of block at point.
7274 Unlike to `org-hide-block-toggle', this function does not throw
7275 an error. Return a non-nil value when toggling is successful."
7276 (interactive)
7277 (ignore-errors (org-hide-block-toggle)))
7279 (defun org-hide-block-toggle (&optional force)
7280 "Toggle the visibility of the current block.
7281 When optional argument FORCE is `off', make block visible. If it
7282 is non-nil, hide it unconditionally. Throw an error when not at
7283 a block. Return a non-nil value when toggling is successful."
7284 (interactive)
7285 (let ((element (org-element-at-point)))
7286 (unless (memq (org-element-type element)
7287 '(center-block comment-block dynamic-block example-block
7288 export-block quote-block special-block
7289 src-block verse-block))
7290 (user-error "Not at a block"))
7291 (let* ((start (save-excursion
7292 (goto-char (org-element-property :post-affiliated element))
7293 (line-end-position)))
7294 (end (save-excursion
7295 (goto-char (org-element-property :end element))
7296 (skip-chars-backward " \r\t\n")
7297 (line-end-position)))
7298 (overlays (overlays-at start)))
7299 (cond
7300 ;; Do nothing when not before or at the block opening line or
7301 ;; at the block closing line.
7302 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7303 ((and (not (eq force 'off))
7304 (not (memq t (mapcar
7305 (lambda (o)
7306 (eq (overlay-get o 'invisible) 'org-hide-block))
7307 overlays))))
7308 (let ((ov (make-overlay start end)))
7309 (overlay-put ov 'invisible 'org-hide-block)
7310 ;; Make the block accessible to `isearch'.
7311 (overlay-put
7312 ov 'isearch-open-invisible
7313 (lambda (ov)
7314 (when (memq ov org-hide-block-overlays)
7315 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7316 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7317 (delete-overlay ov))))
7318 (push ov org-hide-block-overlays)
7319 ;; When the block is hidden away, make sure point is left in
7320 ;; a visible part of the buffer.
7321 (when (> (line-beginning-position) start)
7322 (goto-char start)
7323 (beginning-of-line))
7324 ;; Signal successful toggling.
7326 ((or (not force) (eq force 'off))
7327 (dolist (ov overlays t)
7328 (when (memq ov org-hide-block-overlays)
7329 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7330 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7331 (delete-overlay ov))))))))
7333 ;; org-tab-after-check-for-cycling-hook
7334 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7335 ;; Remove overlays when changing major mode
7336 (add-hook 'org-mode-hook
7337 (lambda () (org-add-hook 'change-major-mode-hook
7338 'org-show-block-all 'append 'local)))
7340 ;;; Org-goto
7342 (defvar org-goto-window-configuration nil)
7343 (defvar org-goto-marker nil)
7344 (defvar org-goto-map)
7345 (defun org-goto-map ()
7346 "Set the keymap `org-goto'."
7347 (setq org-goto-map
7348 (let ((map (make-sparse-keymap)))
7349 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7350 mouse-drag-region universal-argument org-occur)))
7351 (dolist (cmd cmds)
7352 (substitute-key-definition cmd cmd map global-map)))
7353 (suppress-keymap map)
7354 (org-defkey map "\C-m" 'org-goto-ret)
7355 (org-defkey map [(return)] 'org-goto-ret)
7356 (org-defkey map [(left)] 'org-goto-left)
7357 (org-defkey map [(right)] 'org-goto-right)
7358 (org-defkey map [(control ?g)] 'org-goto-quit)
7359 (org-defkey map "\C-i" 'org-cycle)
7360 (org-defkey map [(tab)] 'org-cycle)
7361 (org-defkey map [(down)] 'outline-next-visible-heading)
7362 (org-defkey map [(up)] 'outline-previous-visible-heading)
7363 (if org-goto-auto-isearch
7364 (if (fboundp 'define-key-after)
7365 (define-key-after map [t] 'org-goto-local-auto-isearch)
7366 nil)
7367 (org-defkey map "q" 'org-goto-quit)
7368 (org-defkey map "n" 'outline-next-visible-heading)
7369 (org-defkey map "p" 'outline-previous-visible-heading)
7370 (org-defkey map "f" 'outline-forward-same-level)
7371 (org-defkey map "b" 'outline-backward-same-level)
7372 (org-defkey map "u" 'outline-up-heading))
7373 (org-defkey map "/" 'org-occur)
7374 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7375 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7376 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7377 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7378 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7379 map)))
7381 (defconst org-goto-help
7382 "Browse buffer copy, to find location or copy text.%s
7383 RET=jump to location C-g=quit and return to previous location
7384 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7386 (defvar org-goto-start-pos) ; dynamically scoped parameter
7388 (defun org-goto (&optional alternative-interface)
7389 "Look up a different location in the current file, keeping current visibility.
7391 When you want look-up or go to a different location in a
7392 document, the fastest way is often to fold the entire buffer and
7393 then dive into the tree. This method has the disadvantage, that
7394 the previous location will be folded, which may not be what you
7395 want.
7397 This command works around this by showing a copy of the current
7398 buffer in an indirect buffer, in overview mode. You can dive
7399 into the tree in that copy, use org-occur and incremental search
7400 to find a location. When pressing RET or `Q', the command
7401 returns to the original buffer in which the visibility is still
7402 unchanged. After RET it will also jump to the location selected
7403 in the indirect buffer and expose the headline hierarchy above.
7405 With a prefix argument, use the alternative interface: e.g., if
7406 `org-goto-interface' is `outline' use `outline-path-completion'."
7407 (interactive "P")
7408 (org-goto-map)
7409 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7410 (org-refile-use-outline-path t)
7411 (org-refile-target-verify-function nil)
7412 (interface
7413 (if (not alternative-interface)
7414 org-goto-interface
7415 (if (eq org-goto-interface 'outline)
7416 'outline-path-completion
7417 'outline)))
7418 (org-goto-start-pos (point))
7419 (selected-point
7420 (if (eq interface 'outline)
7421 (car (org-get-location (current-buffer) org-goto-help))
7422 (let ((pa (org-refile-get-location "Goto")))
7423 (org-refile-check-position pa)
7424 (nth 3 pa)))))
7425 (if selected-point
7426 (progn
7427 (org-mark-ring-push org-goto-start-pos)
7428 (goto-char selected-point)
7429 (when (or (outline-invisible-p) (org-invisible-p2))
7430 (org-show-context 'org-goto)))
7431 (message "Quit"))))
7433 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7434 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7435 (defvar org-goto-local-auto-isearch-map) ; defined below
7437 (defun org-get-location (_buf help)
7438 "Let the user select a location in current buffer.
7439 This function uses a recursive edit. It returns the selected position
7440 or nil."
7441 (org-no-popups
7442 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7443 (isearch-hide-immediately nil)
7444 (isearch-search-fun-function
7445 (lambda () 'org-goto-local-search-headings))
7446 (org-goto-selected-point org-goto-exit-command))
7447 (save-excursion
7448 (save-window-excursion
7449 (delete-other-windows)
7450 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7451 (org-pop-to-buffer-same-window
7452 (condition-case nil
7453 (make-indirect-buffer (current-buffer) "*org-goto*")
7454 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7455 (with-output-to-temp-buffer "*Org Help*"
7456 (princ (format help (if org-goto-auto-isearch
7457 " Just type for auto-isearch."
7458 " n/p/f/b/u to navigate, q to quit."))))
7459 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7460 (setq buffer-read-only nil)
7461 (let ((org-startup-truncated t)
7462 (org-startup-folded nil)
7463 (org-startup-align-all-tables nil))
7464 (org-mode)
7465 (org-overview))
7466 (setq buffer-read-only t)
7467 (if (and (boundp 'org-goto-start-pos)
7468 (integer-or-marker-p org-goto-start-pos))
7469 (progn (goto-char org-goto-start-pos)
7470 (when (outline-invisible-p)
7471 (org-show-set-visibility 'lineage)))
7472 (goto-char (point-min)))
7473 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7474 (message "Select location and press RET")
7475 (use-local-map org-goto-map)
7476 (recursive-edit)))
7477 (kill-buffer "*org-goto*")
7478 (cons org-goto-selected-point org-goto-exit-command))))
7480 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7481 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7482 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7483 (if (fboundp 'isearch-other-control-char)
7484 (progn
7485 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7486 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7487 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7488 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7489 (define-key org-goto-local-auto-isearch-map [return] nil))
7491 (defun org-goto-local-search-headings (string bound noerror)
7492 "Search and make sure that any matches are in headlines."
7493 (catch 'return
7494 (while (if isearch-forward
7495 (search-forward string bound noerror)
7496 (search-backward string bound noerror))
7497 (when (save-match-data
7498 (and (save-excursion
7499 (beginning-of-line)
7500 (looking-at org-complex-heading-regexp))
7501 (or (not (match-beginning 5))
7502 (< (point) (match-beginning 5)))))
7503 (throw 'return (point))))))
7505 (defun org-goto-local-auto-isearch ()
7506 "Start isearch."
7507 (interactive)
7508 (goto-char (point-min))
7509 (let ((keys (this-command-keys)))
7510 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7511 (isearch-mode t)
7512 (isearch-process-search-char (string-to-char keys)))))
7514 (defun org-goto-ret (&optional _arg)
7515 "Finish `org-goto' by going to the new location."
7516 (interactive "P")
7517 (setq org-goto-selected-point (point))
7518 (setq org-goto-exit-command 'return)
7519 (throw 'exit nil))
7521 (defun org-goto-left ()
7522 "Finish `org-goto' by going to the new location."
7523 (interactive)
7524 (if (org-at-heading-p)
7525 (progn
7526 (beginning-of-line 1)
7527 (setq org-goto-selected-point (point)
7528 org-goto-exit-command 'left)
7529 (throw 'exit nil))
7530 (user-error "Not on a heading")))
7532 (defun org-goto-right ()
7533 "Finish `org-goto' by going to the new location."
7534 (interactive)
7535 (if (org-at-heading-p)
7536 (progn
7537 (setq org-goto-selected-point (point)
7538 org-goto-exit-command 'right)
7539 (throw 'exit nil))
7540 (user-error "Not on a heading")))
7542 (defun org-goto-quit ()
7543 "Finish `org-goto' without cursor motion."
7544 (interactive)
7545 (setq org-goto-selected-point nil)
7546 (setq org-goto-exit-command 'quit)
7547 (throw 'exit nil))
7549 ;;; Indirect buffer display of subtrees
7551 (defvar org-indirect-dedicated-frame nil
7552 "This is the frame being used for indirect tree display.")
7553 (defvar org-last-indirect-buffer nil)
7555 (defun org-tree-to-indirect-buffer (&optional arg)
7556 "Create indirect buffer and narrow it to current subtree.
7557 With a numerical prefix ARG, go up to this level and then take that tree.
7558 If ARG is negative, go up that many levels.
7560 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7561 indirect buffer previously made with this command, to avoid proliferation of
7562 indirect buffers. However, when you call the command with a \
7563 \\[universal-argument] prefix, or
7564 when `org-indirect-buffer-display' is `new-frame', the last buffer
7565 is kept so that you can work with several indirect buffers at the same time.
7566 If `org-indirect-buffer-display' is `dedicated-frame', the \
7567 \\[universal-argument] prefix also
7568 requests that a new frame be made for the new buffer, so that the dedicated
7569 frame is not changed."
7570 (interactive "P")
7571 (let ((cbuf (current-buffer))
7572 (cwin (selected-window))
7573 (pos (point))
7574 beg end level heading ibuf)
7575 (save-excursion
7576 (org-back-to-heading t)
7577 (when (numberp arg)
7578 (setq level (org-outline-level))
7579 (when (< arg 0) (setq arg (+ level arg)))
7580 (while (> (setq level (org-outline-level)) arg)
7581 (org-up-heading-safe)))
7582 (setq beg (point)
7583 heading (org-get-heading 'no-tags))
7584 (org-end-of-subtree t t)
7585 (when (org-at-heading-p) (backward-char 1))
7586 (setq end (point)))
7587 (when (and (buffer-live-p org-last-indirect-buffer)
7588 (not (eq org-indirect-buffer-display 'new-frame))
7589 (not arg))
7590 (kill-buffer org-last-indirect-buffer))
7591 (setq ibuf (org-get-indirect-buffer cbuf heading)
7592 org-last-indirect-buffer ibuf)
7593 (cond
7594 ((or (eq org-indirect-buffer-display 'new-frame)
7595 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7596 (select-frame (make-frame))
7597 (delete-other-windows)
7598 (org-pop-to-buffer-same-window ibuf)
7599 (org-set-frame-title heading))
7600 ((eq org-indirect-buffer-display 'dedicated-frame)
7601 (raise-frame
7602 (select-frame (or (and org-indirect-dedicated-frame
7603 (frame-live-p org-indirect-dedicated-frame)
7604 org-indirect-dedicated-frame)
7605 (setq org-indirect-dedicated-frame (make-frame)))))
7606 (delete-other-windows)
7607 (org-pop-to-buffer-same-window ibuf)
7608 (org-set-frame-title (concat "Indirect: " heading)))
7609 ((eq org-indirect-buffer-display 'current-window)
7610 (org-pop-to-buffer-same-window ibuf))
7611 ((eq org-indirect-buffer-display 'other-window)
7612 (pop-to-buffer ibuf))
7613 (t (error "Invalid value")))
7614 (when (featurep 'xemacs)
7615 (save-excursion (org-mode) (turn-on-font-lock)))
7616 (narrow-to-region beg end)
7617 (outline-show-all)
7618 (goto-char pos)
7619 (run-hook-with-args 'org-cycle-hook 'all)
7620 (and (window-live-p cwin) (select-window cwin))))
7622 (defun org-get-indirect-buffer (&optional buffer heading)
7623 (setq buffer (or buffer (current-buffer)))
7624 (let ((n 1) (base (buffer-name buffer)) bname)
7625 (while (buffer-live-p
7626 (get-buffer
7627 (setq bname
7628 (concat base "-"
7629 (if heading (concat heading "-" (number-to-string n))
7630 (number-to-string n))))))
7631 (setq n (1+ n)))
7632 (condition-case nil
7633 (make-indirect-buffer buffer bname 'clone)
7634 (error (make-indirect-buffer buffer bname)))))
7636 (defun org-set-frame-title (title)
7637 "Set the title of the current frame to the string TITLE."
7638 ;; FIXME: how to name a single frame in XEmacs???
7639 (unless (featurep 'xemacs)
7640 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7642 ;;;; Structure editing
7644 ;;; Inserting headlines
7646 (defun org--line-empty-p (n)
7647 "Is the Nth next line empty?
7649 Counts the current line as N = 1 and the previous line as N = 0;
7650 see `beginning-of-line'."
7651 (save-excursion
7652 (and (not (bobp))
7653 (or (beginning-of-line n) t)
7654 (save-match-data
7655 (looking-at "[ \t]*$")))))
7657 (defun org-previous-line-empty-p ()
7658 "Is the previous line a blank line?
7659 When NEXT is non-nil, check the next line instead."
7660 (org--line-empty-p 0))
7662 (defun org-next-line-empty-p ()
7663 "Is the previous line a blank line?
7664 When NEXT is non-nil, check the next line instead."
7665 (org--line-empty-p 2))
7667 (defun org-insert-heading (&optional arg invisible-ok top)
7668 "Insert a new heading or an item with the same depth at point.
7670 If point is at the beginning of a heading or a list item, insert
7671 a new heading or a new item above the current one. If point is
7672 at the beginning of a normal line, turn the line into a heading.
7674 If point is in the middle of a headline or a list item, split the
7675 headline or the item and create a new headline/item with the text
7676 in the current line after point \(see `org-M-RET-may-split-line'
7677 on how to modify this behavior).
7679 With one universal prefix argument, set the user option
7680 `org-insert-heading-respect-content' to t for the duration of
7681 the command. This modifies the behavior described above in this
7682 ways: on list items and at the beginning of normal lines, force
7683 the insertion of a heading after the current subtree.
7685 With two universal prefix arguments, insert the heading at the
7686 end of the grandparent subtree. For example, if point is within
7687 a 2nd-level heading, then it will insert a 2nd-level heading at
7688 the end of the 1st-level parent heading.
7690 If point is at the beginning of a headline, insert a sibling
7691 before the current headline. If point is not at the beginning,
7692 split the line and create a new headline with the text in the
7693 current line after point \(see `org-M-RET-may-split-line' on how
7694 to modify this behavior).
7696 If point is at the beginning of a normal line, turn this line
7697 into a heading.
7699 When INVISIBLE-OK is set, stop at invisible headlines when going
7700 back. This is important for non-interactive uses of the
7701 command.
7703 When optional argument TOP is non-nil, insert a level 1 heading,
7704 unconditionally."
7705 (interactive "P")
7706 (when (org-called-interactively-p 'any) (org-reveal))
7707 (let ((itemp (and (not top) (org-in-item-p)))
7708 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7709 (respect-content (or org-insert-heading-respect-content
7710 (equal arg '(4))))
7711 (initial-content ""))
7713 (cond
7715 ((or (= (buffer-size) 0)
7716 (and (not (save-excursion
7717 (and (ignore-errors (org-back-to-heading invisible-ok))
7718 (org-at-heading-p))))
7719 (or arg (not itemp))))
7720 ;; At beginning of buffer or so high up that only a heading
7721 ;; makes sense.
7722 (cond ((and (bolp) (not respect-content)) (insert "* "))
7723 ((not respect-content)
7724 (unless may-split (end-of-line))
7725 (insert "\n* "))
7726 ((re-search-forward org-outline-regexp-bol nil t)
7727 (beginning-of-line)
7728 (insert "* \n")
7729 (backward-char))
7730 (t (goto-char (point-max))
7731 (insert "\n* ")))
7732 (run-hooks 'org-insert-heading-hook))
7734 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7737 ;; Maybe move at the end of the subtree
7738 (when (equal arg '(16))
7739 (org-up-heading-safe)
7740 (org-end-of-subtree t))
7741 ;; Insert a heading
7742 (save-restriction
7743 (widen)
7744 (let* ((level nil)
7745 (on-heading (org-at-heading-p))
7746 (empty-line-p (if on-heading
7747 (org-previous-line-empty-p)
7748 ;; We will decide later
7749 nil))
7750 ;; Get a level string to fall back on.
7751 (fix-level
7752 (if (org-before-first-heading-p) "*"
7753 (save-excursion
7754 (org-back-to-heading t)
7755 (when (org-previous-line-empty-p) (setq empty-line-p t))
7756 (looking-at org-outline-regexp)
7757 (make-string (1- (length (match-string 0))) ?*))))
7758 (stars
7759 (save-excursion
7760 (condition-case nil
7761 (if top "* "
7762 (org-back-to-heading invisible-ok)
7763 (when (and (not on-heading)
7764 (featurep 'org-inlinetask)
7765 (integerp org-inlinetask-min-level)
7766 (>= (length (match-string 0))
7767 org-inlinetask-min-level))
7768 ;; Find a heading level before the inline
7769 ;; task.
7770 (while (and (setq level (org-up-heading-safe))
7771 (>= level org-inlinetask-min-level)))
7772 (if (org-at-heading-p)
7773 (org-back-to-heading invisible-ok)
7774 (error "This should not happen")))
7775 (unless (and (save-excursion
7776 (save-match-data
7777 (org-backward-heading-same-level
7778 1 invisible-ok))
7779 (= (point) (match-beginning 0)))
7780 (not (org-next-line-empty-p)))
7781 (setq empty-line-p (or empty-line-p
7782 (org-previous-line-empty-p))))
7783 (match-string 0))
7784 (error (or fix-level "* ")))))
7785 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7786 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7788 ;; If we insert after content, move there and clean up
7789 ;; whitespace.
7790 (when (and respect-content
7791 (not (org-looking-at-p org-outline-regexp-bol)))
7792 (if (not (org-before-first-heading-p))
7793 (org-end-of-subtree nil t)
7794 (re-search-forward org-outline-regexp-bol)
7795 (beginning-of-line 0))
7796 (skip-chars-backward " \r\t\n")
7797 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7798 (looking-at "[ \t]+") (replace-match ""))
7799 (unless (eobp) (forward-char 1))
7800 (when (looking-at "^\\*")
7801 (unless (bobp) (backward-char 1))
7802 (insert "\n")))
7804 ;; If we are splitting, grab the text that should be moved
7805 ;; to the new headline.
7806 (when may-split
7807 (if (org-at-heading-p)
7808 ;; This is a heading: split intelligently (keeping
7809 ;; tags).
7810 (let ((pos (point)))
7811 (beginning-of-line)
7812 (unless (looking-at org-complex-heading-regexp)
7813 (error "This should not happen"))
7814 (when (and (match-beginning 4)
7815 (> pos (match-beginning 4))
7816 (< pos (match-end 4)))
7817 (setq initial-content (buffer-substring pos (match-end 4)))
7818 (goto-char pos)
7819 (delete-region (point) (match-end 4))
7820 (if (looking-at "[ \t]*$")
7821 (replace-match "")
7822 (insert (make-string (length initial-content) ?\s)))
7823 (setq initial-content (org-trim initial-content)))
7824 (goto-char pos))
7825 ;; A normal line.
7826 (setq initial-content
7827 (org-trim
7828 (delete-and-extract-region (point) (line-end-position))))))
7830 ;; If we are at the beginning of the line, insert before it.
7831 ;; Otherwise, after it.
7832 (cond
7833 ((and (bolp) (looking-at "[ \t]*$")))
7834 ((bolp) (save-excursion (insert "\n")))
7835 (t (end-of-line)
7836 (insert "\n")))
7838 ;; Insert the new heading
7839 (insert stars)
7840 (just-one-space)
7841 (insert initial-content)
7842 (unless (and blank (org-previous-line-empty-p))
7843 (org-N-empty-lines-before-current (if blank 1 0)))
7844 ;; Adjust visibility, which may be messed up if we removed
7845 ;; blank lines while previous entry was hidden.
7846 (let ((bol (line-beginning-position)))
7847 (dolist (o (overlays-at (1- bol)))
7848 (when (and (eq (overlay-get o 'invisible) 'outline)
7849 (eq (overlay-end o) bol))
7850 (move-overlay o (overlay-start o) (1- bol)))))
7851 (run-hooks 'org-insert-heading-hook)))))))
7853 (defun org-N-empty-lines-before-current (N)
7854 "Make the number of empty lines before current exactly N.
7855 So this will delete or add empty lines."
7856 (save-excursion
7857 (beginning-of-line)
7858 (let ((p (point)))
7859 (skip-chars-backward " \r\t\n")
7860 (unless (bolp) (forward-line))
7861 (delete-region (point) p))
7862 (when (> N 0) (insert (make-string N ?\n)))))
7864 (defun org-get-heading (&optional no-tags no-todo)
7865 "Return the heading of the current entry, without the stars.
7866 When NO-TAGS is non-nil, don't include tags.
7867 When NO-TODO is non-nil, don't include TODO keywords."
7868 (save-excursion
7869 (org-back-to-heading t)
7870 (cond
7871 ((and no-tags no-todo)
7872 (looking-at org-complex-heading-regexp)
7873 (match-string 4))
7874 (no-tags
7875 (looking-at (concat org-outline-regexp
7876 "\\(.*?\\)"
7877 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7878 (match-string 1))
7879 (no-todo
7880 (looking-at org-todo-line-regexp)
7881 (match-string 3))
7882 (t (looking-at org-heading-regexp)
7883 (match-string 2)))))
7885 (defvar orgstruct-mode) ; defined below
7887 (defun org-heading-components ()
7888 "Return the components of the current heading.
7889 This is a list with the following elements:
7890 - the level as an integer
7891 - the reduced level, different if `org-odd-levels-only' is set.
7892 - the TODO keyword, or nil
7893 - the priority character, like ?A, or nil if no priority is given
7894 - the headline text itself, or the tags string if no headline text
7895 - the tags string, or nil."
7896 (save-excursion
7897 (org-back-to-heading t)
7898 (when (let (case-fold-search)
7899 (looking-at
7900 (if orgstruct-mode
7901 org-heading-regexp
7902 org-complex-heading-regexp)))
7903 (if orgstruct-mode
7904 (list (length (match-string 1))
7905 (org-reduced-level (length (match-string 1)))
7908 (match-string 2)
7909 nil)
7910 (list (length (match-string 1))
7911 (org-reduced-level (length (match-string 1)))
7912 (org-match-string-no-properties 2)
7913 (and (match-end 3) (aref (match-string 3) 2))
7914 (org-match-string-no-properties 4)
7915 (org-match-string-no-properties 5))))))
7917 (defun org-get-entry ()
7918 "Get the entry text, after heading, entire subtree."
7919 (save-excursion
7920 (org-back-to-heading t)
7921 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7923 (defun org-edit-headline (&optional heading)
7924 "Edit the current headline.
7925 Set it to HEADING when provided."
7926 (interactive)
7927 (org-with-wide-buffer
7928 (org-back-to-heading t)
7929 (when (looking-at org-complex-heading-regexp)
7930 (let* ((old (match-string-no-properties 4))
7931 (new (org-trim (or heading (read-string "Edit: " old)))))
7932 (unless (equal old new)
7933 (if old (replace-match new t t nil 4)
7934 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7935 (insert " " new))
7936 (org-set-tags nil t)
7937 (when (looking-at "[ \t]*$") (replace-match "")))))))
7939 (defun org-insert-heading-after-current ()
7940 "Insert a new heading with same level as current, after current subtree."
7941 (interactive)
7942 (org-back-to-heading)
7943 (org-insert-heading)
7944 (org-move-subtree-down)
7945 (end-of-line 1))
7947 (defun org-insert-heading-respect-content (&optional invisible-ok)
7948 "Insert heading with `org-insert-heading-respect-content' set to t."
7949 (interactive)
7950 (org-insert-heading '(4) invisible-ok))
7952 (defun org-insert-todo-heading-respect-content (&optional force-state)
7953 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7954 (interactive)
7955 (org-insert-todo-heading force-state '(4)))
7957 (defun org-insert-todo-heading (arg &optional force-heading)
7958 "Insert a new heading with the same level and TODO state as current heading.
7959 If the heading has no TODO state, or if the state is DONE, use the first
7960 state (TODO by default). Also with one prefix arg, force first state. With
7961 two prefix args, force inserting at the end of the parent subtree."
7962 (interactive "P")
7963 (when (or force-heading (not (org-insert-item 'checkbox)))
7964 (org-insert-heading (or (and (equal arg '(16)) '(16))
7965 force-heading))
7966 (save-excursion
7967 (org-back-to-heading)
7968 (outline-previous-heading)
7969 (looking-at org-todo-line-regexp))
7970 (let*
7971 ((new-mark-x
7972 (if (or (equal arg '(4))
7973 (not (match-beginning 2))
7974 (member (match-string 2) org-done-keywords))
7975 (car org-todo-keywords-1)
7976 (match-string 2)))
7977 (new-mark
7979 (run-hook-with-args-until-success
7980 'org-todo-get-default-hook new-mark-x nil)
7981 new-mark-x)))
7982 (beginning-of-line 1)
7983 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7984 (if org-treat-insert-todo-heading-as-state-change
7985 (org-todo new-mark)
7986 (insert new-mark " "))))
7987 (when org-provide-todo-statistics
7988 (org-update-parent-todo-statistics))))
7990 (defun org-insert-subheading (arg)
7991 "Insert a new subheading and demote it.
7992 Works for outline headings and for plain lists alike."
7993 (interactive "P")
7994 (org-insert-heading arg)
7995 (cond
7996 ((org-at-heading-p) (org-do-demote))
7997 ((org-at-item-p) (org-indent-item))))
7999 (defun org-insert-todo-subheading (arg)
8000 "Insert a new subheading with TODO keyword or checkbox and demote it.
8001 Works for outline headings and for plain lists alike."
8002 (interactive "P")
8003 (org-insert-todo-heading arg)
8004 (cond
8005 ((org-at-heading-p) (org-do-demote))
8006 ((org-at-item-p) (org-indent-item))))
8008 ;;; Promotion and Demotion
8010 (defvar org-after-demote-entry-hook nil
8011 "Hook run after an entry has been demoted.
8012 The cursor will be at the beginning of the entry.
8013 When a subtree is being demoted, the hook will be called for each node.")
8015 (defvar org-after-promote-entry-hook nil
8016 "Hook run after an entry has been promoted.
8017 The cursor will be at the beginning of the entry.
8018 When a subtree is being promoted, the hook will be called for each node.")
8020 (defun org-promote-subtree ()
8021 "Promote the entire subtree.
8022 See also `org-promote'."
8023 (interactive)
8024 (save-excursion
8025 (org-with-limited-levels (org-map-tree 'org-promote)))
8026 (org-fix-position-after-promote))
8028 (defun org-demote-subtree ()
8029 "Demote the entire subtree.
8030 See `org-demote' and `org-promote'."
8031 (interactive)
8032 (save-excursion
8033 (org-with-limited-levels (org-map-tree 'org-demote)))
8034 (org-fix-position-after-promote))
8036 (defun org-do-promote ()
8037 "Promote the current heading higher up the tree.
8038 If the region is active in `transient-mark-mode', promote all
8039 headings in the region."
8040 (interactive)
8041 (save-excursion
8042 (if (org-region-active-p)
8043 (org-map-region 'org-promote (region-beginning) (region-end))
8044 (org-promote)))
8045 (org-fix-position-after-promote))
8047 (defun org-do-demote ()
8048 "Demote the current heading lower down the tree.
8049 If the region is active in `transient-mark-mode', demote all
8050 headings in the region."
8051 (interactive)
8052 (save-excursion
8053 (if (org-region-active-p)
8054 (org-map-region 'org-demote (region-beginning) (region-end))
8055 (org-demote)))
8056 (org-fix-position-after-promote))
8058 (defun org-fix-position-after-promote ()
8059 "Fix cursor position and indentation after demoting/promoting."
8060 (let ((pos (point)))
8061 (when (save-excursion
8062 (beginning-of-line 1)
8063 (looking-at org-todo-line-regexp)
8064 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8065 (cond ((eobp) (insert " "))
8066 ((eolp) (insert " "))
8067 ((equal (char-after) ?\ ) (forward-char 1))))))
8069 (defun org-current-level ()
8070 "Return the level of the current entry, or nil if before the first headline.
8071 The level is the number of stars at the beginning of the
8072 headline. Use `org-reduced-level' to remove the effect of
8073 `org-odd-levels'. Unlike to `org-outline-level', this function
8074 ignores inlinetasks."
8075 (let ((level (org-with-limited-levels (org-outline-level))))
8076 (and (> level 0) level)))
8078 (defun org-get-previous-line-level ()
8079 "Return the outline depth of the last headline before the current line.
8080 Returns 0 for the first headline in the buffer, and nil if before the
8081 first headline."
8082 (and (org-current-level)
8083 (or (and (/= (line-beginning-position) (point-min))
8084 (save-excursion (beginning-of-line 0) (org-current-level)))
8085 0)))
8087 (defun org-reduced-level (l)
8088 "Compute the effective level of a heading.
8089 This takes into account the setting of `org-odd-levels-only'."
8090 (cond
8091 ((zerop l) 0)
8092 (org-odd-levels-only (1+ (floor (/ l 2))))
8093 (t l)))
8095 (defun org-level-increment ()
8096 "Return the number of stars that will be added or removed at a
8097 time to headlines when structure editing, based on the value of
8098 `org-odd-levels-only'."
8099 (if org-odd-levels-only 2 1))
8101 (defun org-get-valid-level (level &optional change)
8102 "Rectify a level change under the influence of `org-odd-levels-only'
8103 LEVEL is a current level, CHANGE is by how much the level should be
8104 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8105 even level numbers will become the next higher odd number."
8106 (if org-odd-levels-only
8107 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8108 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8109 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8110 (max 1 (+ level (or change 0)))))
8111 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8113 (defun org-promote ()
8114 "Promote the current heading higher up the tree."
8115 (org-with-wide-buffer
8116 (org-back-to-heading t)
8117 (let* ((after-change-functions (remq 'flyspell-after-change-function
8118 after-change-functions))
8119 (level (save-match-data (funcall outline-level)))
8120 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8121 (diff (abs (- level (length up-head) -1))))
8122 (cond
8123 ((and (= level 1) org-allow-promoting-top-level-subtree)
8124 (replace-match "# " nil t))
8125 ((= level 1)
8126 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8127 (t (replace-match up-head nil t)))
8128 (unless (= level 1)
8129 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8130 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8131 (run-hooks 'org-after-promote-entry-hook))))
8133 (defun org-demote ()
8134 "Demote the current heading lower down the tree."
8135 (org-with-wide-buffer
8136 (org-back-to-heading t)
8137 (let* ((after-change-functions (remq 'flyspell-after-change-function
8138 after-change-functions))
8139 (level (save-match-data (funcall outline-level)))
8140 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8141 (diff (abs (- level (length down-head) -1))))
8142 (replace-match down-head nil t)
8143 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8144 (when org-adapt-indentation (org-fixup-indentation diff))
8145 (run-hooks 'org-after-demote-entry-hook))))
8147 (defun org-cycle-level ()
8148 "Cycle the level of an empty headline through possible states.
8149 This goes first to child, then to parent, level, then up the hierarchy.
8150 After top level, it switches back to sibling level."
8151 (interactive)
8152 (let ((org-adapt-indentation nil))
8153 (when (org-point-at-end-of-empty-headline)
8154 (setq this-command 'org-cycle-level) ; Only needed for caching
8155 (let ((cur-level (org-current-level))
8156 (prev-level (org-get-previous-line-level)))
8157 (cond
8158 ;; If first headline in file, promote to top-level.
8159 ((= prev-level 0)
8160 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8161 do (org-do-promote)))
8162 ;; If same level as prev, demote one.
8163 ((= prev-level cur-level)
8164 (org-do-demote))
8165 ;; If parent is top-level, promote to top level if not already.
8166 ((= prev-level 1)
8167 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8168 do (org-do-promote)))
8169 ;; If top-level, return to prev-level.
8170 ((= cur-level 1)
8171 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8172 do (org-do-demote)))
8173 ;; If less than prev-level, promote one.
8174 ((< cur-level prev-level)
8175 (org-do-promote))
8176 ;; If deeper than prev-level, promote until higher than
8177 ;; prev-level.
8178 ((> cur-level prev-level)
8179 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8180 do (org-do-promote))))
8181 t))))
8183 (defun org-map-tree (fun)
8184 "Call FUN for every heading underneath the current one."
8185 (org-back-to-heading)
8186 (let ((level (funcall outline-level)))
8187 (save-excursion
8188 (funcall fun)
8189 (while (and (progn
8190 (outline-next-heading)
8191 (> (funcall outline-level) level))
8192 (not (eobp)))
8193 (funcall fun)))))
8195 (defun org-map-region (fun beg end)
8196 "Call FUN for every heading between BEG and END."
8197 (let ((org-ignore-region t))
8198 (save-excursion
8199 (setq end (copy-marker end))
8200 (goto-char beg)
8201 (when (and (re-search-forward org-outline-regexp-bol nil t)
8202 (< (point) end))
8203 (funcall fun))
8204 (while (and (progn
8205 (outline-next-heading)
8206 (< (point) end))
8207 (not (eobp)))
8208 (funcall fun)))))
8210 (defun org-fixup-indentation (diff)
8211 "Change the indentation in the current entry by DIFF.
8213 DIFF is an integer. Indentation is done according to the
8214 following rules:
8216 - Planning information and property drawers are always indented
8217 according to the new level of the headline;
8219 - Footnote definitions and their contents are ignored;
8221 - Inlinetasks' boundaries are not shifted;
8223 - Empty lines are ignored;
8225 - Other lines' indentation are shifted by DIFF columns, unless
8226 it would introduce a structural change in the document, in
8227 which case no shifting is done at all.
8229 Assume point is at a heading or an inlinetask beginning."
8230 (org-with-wide-buffer
8231 (narrow-to-region (line-beginning-position)
8232 (save-excursion
8233 (if (org-with-limited-levels (org-at-heading-p))
8234 (org-with-limited-levels (outline-next-heading))
8235 (org-inlinetask-goto-end))
8236 (point)))
8237 (forward-line)
8238 ;; Indent properly planning info and property drawer.
8239 (when (org-looking-at-p org-planning-line-re)
8240 (org-indent-line)
8241 (forward-line))
8242 (when (looking-at org-property-drawer-re)
8243 (goto-char (match-end 0))
8244 (forward-line)
8245 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8246 (catch 'no-shift
8247 (when (zerop diff) (throw 'no-shift nil))
8248 ;; If DIFF is negative, first check if a shift is possible at all
8249 ;; (e.g., it doesn't break structure). This can only happen if
8250 ;; some contents are not properly indented.
8251 (let ((case-fold-search t))
8252 (when (< diff 0)
8253 (let ((diff (- diff))
8254 (forbidden-re (concat org-outline-regexp
8255 "\\|"
8256 (substring org-footnote-definition-re 1))))
8257 (save-excursion
8258 (while (not (eobp))
8259 (cond
8260 ((org-looking-at-p "[ \t]*$") (forward-line))
8261 ((and (org-looking-at-p org-footnote-definition-re)
8262 (let ((e (org-element-at-point)))
8263 (and (eq (org-element-type e) 'footnote-definition)
8264 (goto-char (org-element-property :end e))))))
8265 ((org-looking-at-p org-outline-regexp) (forward-line))
8266 ;; Give up if shifting would move before column 0 or
8267 ;; if it would introduce a headline or a footnote
8268 ;; definition.
8270 (skip-chars-forward " \t")
8271 (let ((ind (current-column)))
8272 (when (or (< ind diff)
8273 (and (= ind diff) (org-looking-at-p forbidden-re)))
8274 (throw 'no-shift nil)))
8275 ;; Ignore contents of example blocks and source
8276 ;; blocks if their indentation is meant to be
8277 ;; preserved. Jump to block's closing line.
8278 (beginning-of-line)
8279 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8280 (let ((e (org-element-at-point)))
8281 (and (memq (org-element-type e)
8282 '(example-block src-block))
8283 (or org-src-preserve-indentation
8284 (org-element-property :preserve-indent e))
8285 (goto-char (org-element-property :end e))
8286 (progn (skip-chars-backward " \r\t\n")
8287 (beginning-of-line)
8288 t))))
8289 (forward-line))))))))
8290 ;; Shift lines but footnote definitions, inlinetasks boundaries
8291 ;; by DIFF. Also skip contents of source or example blocks
8292 ;; when indentation is meant to be preserved.
8293 (while (not (eobp))
8294 (cond
8295 ((and (org-looking-at-p org-footnote-definition-re)
8296 (let ((e (org-element-at-point)))
8297 (and (eq (org-element-type e) 'footnote-definition)
8298 (goto-char (org-element-property :end e))))))
8299 ((org-looking-at-p org-outline-regexp) (forward-line))
8300 ((org-looking-at-p "[ \t]*$") (forward-line))
8302 (org-indent-line-to (+ (org-get-indentation) diff))
8303 (beginning-of-line)
8304 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8305 (let ((e (org-element-at-point)))
8306 (and (memq (org-element-type e)
8307 '(example-block src-block))
8308 (or org-src-preserve-indentation
8309 (org-element-property :preserve-indent e))
8310 (goto-char (org-element-property :end e))
8311 (progn (skip-chars-backward " \r\t\n")
8312 (beginning-of-line)
8313 t))))
8314 (forward-line)))))))))
8316 (defun org-convert-to-odd-levels ()
8317 "Convert an org-mode file with all levels allowed to one with odd levels.
8318 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8319 level 5 etc."
8320 (interactive)
8321 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8322 (let ((outline-level 'org-outline-level)
8323 (org-odd-levels-only nil) n)
8324 (save-excursion
8325 (goto-char (point-min))
8326 (while (re-search-forward "^\\*\\*+ " nil t)
8327 (setq n (- (length (match-string 0)) 2))
8328 (while (>= (setq n (1- n)) 0)
8329 (org-demote))
8330 (end-of-line 1))))))
8332 (defun org-convert-to-oddeven-levels ()
8333 "Convert an org-mode file with only odd levels to one with odd/even levels.
8334 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8335 file contains a section with an even level, conversion would
8336 destroy the structure of the file. An error is signaled in this
8337 case."
8338 (interactive)
8339 (goto-char (point-min))
8340 ;; First check if there are no even levels
8341 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8342 (org-show-set-visibility 'canonical)
8343 (error "Not all levels are odd in this file. Conversion not possible"))
8344 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8345 (let ((outline-regexp org-outline-regexp)
8346 (outline-level 'org-outline-level)
8347 (org-odd-levels-only nil) n)
8348 (save-excursion
8349 (goto-char (point-min))
8350 (while (re-search-forward "^\\*\\*+ " nil t)
8351 (setq n (/ (1- (length (match-string 0))) 2))
8352 (while (>= (setq n (1- n)) 0)
8353 (org-promote))
8354 (end-of-line 1))))))
8356 (defun org-tr-level (n)
8357 "Make N odd if required."
8358 (if org-odd-levels-only (1+ (/ n 2)) n))
8360 ;;; Vertical tree motion, cutting and pasting of subtrees
8362 (defun org-move-subtree-up (&optional arg)
8363 "Move the current subtree up past ARG headlines of the same level."
8364 (interactive "p")
8365 (org-move-subtree-down (- (prefix-numeric-value arg))))
8367 (defun org-move-subtree-down (&optional arg)
8368 "Move the current subtree down past ARG headlines of the same level."
8369 (interactive "p")
8370 (setq arg (prefix-numeric-value arg))
8371 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8372 'org-get-last-sibling))
8373 (ins-point (make-marker))
8374 (cnt (abs arg))
8375 (col (current-column))
8376 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8377 ;; Select the tree
8378 (org-back-to-heading)
8379 (setq beg0 (point))
8380 (save-excursion
8381 (setq ne-beg (org-back-over-empty-lines))
8382 (setq beg (point)))
8383 (save-match-data
8384 (save-excursion (outline-end-of-heading)
8385 (setq folded (outline-invisible-p)))
8386 (progn (org-end-of-subtree nil t)
8387 (unless (eobp) (backward-char))))
8388 (outline-next-heading)
8389 (setq ne-end (org-back-over-empty-lines))
8390 (setq end (point))
8391 (goto-char beg0)
8392 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8393 ;; include less whitespace
8394 (save-excursion
8395 (goto-char beg)
8396 (forward-line (- ne-beg ne-end))
8397 (setq beg (point))))
8398 ;; Find insertion point, with error handling
8399 (while (> cnt 0)
8400 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8401 (progn (goto-char beg0)
8402 (user-error "Cannot move past superior level or buffer limit")))
8403 (setq cnt (1- cnt)))
8404 (when (> arg 0)
8405 ;; Moving forward - still need to move over subtree
8406 (org-end-of-subtree t t)
8407 (save-excursion
8408 (org-back-over-empty-lines)
8409 (or (bolp) (newline))))
8410 (setq ne-ins (org-back-over-empty-lines))
8411 (move-marker ins-point (point))
8412 (setq txt (buffer-substring beg end))
8413 (org-save-markers-in-region beg end)
8414 (delete-region beg end)
8415 (org-remove-empty-overlays-at beg)
8416 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8417 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8418 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8419 (let ((bbb (point)))
8420 (insert-before-markers txt)
8421 (org-reinstall-markers-in-region bbb)
8422 (move-marker ins-point bbb))
8423 (or (bolp) (insert "\n"))
8424 (setq ins-end (point))
8425 (goto-char ins-point)
8426 (org-skip-whitespace)
8427 (when (and (< arg 0)
8428 (org-first-sibling-p)
8429 (> ne-ins ne-beg))
8430 ;; Move whitespace back to beginning
8431 (save-excursion
8432 (goto-char ins-end)
8433 (let ((kill-whole-line t))
8434 (kill-line (- ne-ins ne-beg)) (point)))
8435 (insert (make-string (- ne-ins ne-beg) ?\n)))
8436 (move-marker ins-point nil)
8437 (if folded
8438 (outline-hide-subtree)
8439 (org-show-entry)
8440 (org-show-children)
8441 (org-cycle-hide-drawers 'children))
8442 (org-clean-visibility-after-subtree-move)
8443 ;; move back to the initial column we were at
8444 (move-to-column col)))
8446 (defvar org-subtree-clip ""
8447 "Clipboard for cut and paste of subtrees.
8448 This is actually only a copy of the kill, because we use the normal kill
8449 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8451 (defvar org-subtree-clip-folded nil
8452 "Was the last copied subtree folded?
8453 This is used to fold the tree back after pasting.")
8455 (defun org-cut-subtree (&optional n)
8456 "Cut the current subtree into the clipboard.
8457 With prefix arg N, cut this many sequential subtrees.
8458 This is a short-hand for marking the subtree and then cutting it."
8459 (interactive "p")
8460 (org-copy-subtree n 'cut))
8462 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8463 "Copy the current subtree it in the clipboard.
8464 With prefix arg N, copy this many sequential subtrees.
8465 This is a short-hand for marking the subtree and then copying it.
8466 If CUT is non-nil, actually cut the subtree.
8467 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8468 of some markers in the region, even if CUT is non-nil. This is
8469 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8470 (interactive "p")
8471 (let (beg end folded (beg0 (point)))
8472 (if (org-called-interactively-p 'any)
8473 (org-back-to-heading nil) ; take what looks like a subtree
8474 (org-back-to-heading t)) ; take what is really there
8475 (setq beg (point))
8476 (skip-chars-forward " \t\r\n")
8477 (save-match-data
8478 (if nosubtrees
8479 (outline-next-heading)
8480 (save-excursion (outline-end-of-heading)
8481 (setq folded (outline-invisible-p)))
8482 (ignore-errors (org-forward-heading-same-level (1- n) t))
8483 (org-end-of-subtree t t)))
8484 ;; Include the end of an inlinetask
8485 (when (and (featurep 'org-inlinetask)
8486 (looking-at-p (concat (org-inlinetask-outline-regexp)
8487 "END[ \t]*$")))
8488 (end-of-line))
8489 (setq end (point))
8490 (goto-char beg0)
8491 (when (> end beg)
8492 (setq org-subtree-clip-folded folded)
8493 (when (or cut force-store-markers)
8494 (org-save-markers-in-region beg end))
8495 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8496 (setq org-subtree-clip (current-kill 0))
8497 (message "%s: Subtree(s) with %d characters"
8498 (if cut "Cut" "Copied")
8499 (length org-subtree-clip)))))
8501 (defun org-paste-subtree (&optional level tree for-yank remove)
8502 "Paste the clipboard as a subtree, with modification of headline level.
8503 The entire subtree is promoted or demoted in order to match a new headline
8504 level.
8506 If the cursor is at the beginning of a headline, the same level as
8507 that headline is used to paste the tree.
8509 If not, the new level is derived from the *visible* headings
8510 before and after the insertion point, and taken to be the inferior headline
8511 level of the two. So if the previous visible heading is level 3 and the
8512 next is level 4 (or vice versa), level 4 will be used for insertion.
8513 This makes sure that the subtree remains an independent subtree and does
8514 not swallow low level entries.
8516 You can also force a different level, either by using a numeric prefix
8517 argument, or by inserting the heading marker by hand. For example, if the
8518 cursor is after \"*****\", then the tree will be shifted to level 5.
8520 If optional TREE is given, use this text instead of the kill ring.
8522 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8523 move back over whitespace before inserting, and move point to the end of
8524 the inserted text when done.
8526 When REMOVE is non-nil, remove the subtree from the clipboard."
8527 (interactive "P")
8528 (setq tree (or tree (and kill-ring (current-kill 0))))
8529 (unless (org-kill-is-subtree-p tree)
8530 (user-error "%s"
8531 (substitute-command-keys
8532 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8533 (org-with-limited-levels
8534 (let* ((visp (not (outline-invisible-p)))
8535 (txt tree)
8536 (^re_ "\\(\\*+\\)[ \t]*")
8537 (old-level (if (string-match org-outline-regexp-bol txt)
8538 (- (match-end 0) (match-beginning 0) 1)
8539 -1))
8540 (force-level (cond (level (prefix-numeric-value level))
8541 ((and (looking-at "[ \t]*$")
8542 (string-match
8543 "^\\*+$" (buffer-substring
8544 (point-at-bol) (point))))
8545 (- (match-end 0) (match-beginning 0)))
8546 ((and (bolp)
8547 (looking-at org-outline-regexp))
8548 (- (match-end 0) (point) 1))))
8549 (previous-level (save-excursion
8550 (condition-case nil
8551 (progn
8552 (outline-previous-visible-heading 1)
8553 (if (looking-at ^re_)
8554 (- (match-end 0) (match-beginning 0) 1)
8556 (error 1))))
8557 (next-level (save-excursion
8558 (condition-case nil
8559 (progn
8560 (or (looking-at org-outline-regexp)
8561 (outline-next-visible-heading 1))
8562 (if (looking-at ^re_)
8563 (- (match-end 0) (match-beginning 0) 1)
8565 (error 1))))
8566 (new-level (or force-level (max previous-level next-level)))
8567 (shift (if (or (= old-level -1)
8568 (= new-level -1)
8569 (= old-level new-level))
8571 (- new-level old-level)))
8572 (delta (if (> shift 0) -1 1))
8573 (func (if (> shift 0) 'org-demote 'org-promote))
8574 (org-odd-levels-only nil)
8575 beg end newend)
8576 ;; Remove the forced level indicator
8577 (when force-level
8578 (delete-region (point-at-bol) (point)))
8579 ;; Paste
8580 (beginning-of-line (if (bolp) 1 2))
8581 (setq beg (point))
8582 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8583 (insert-before-markers txt)
8584 (unless (string-match "\n\\'" txt) (insert "\n"))
8585 (setq newend (point))
8586 (org-reinstall-markers-in-region beg)
8587 (setq end (point))
8588 (goto-char beg)
8589 (skip-chars-forward " \t\n\r")
8590 (setq beg (point))
8591 (when (and (outline-invisible-p) visp)
8592 (save-excursion (outline-show-heading)))
8593 ;; Shift if necessary
8594 (unless (= shift 0)
8595 (save-restriction
8596 (narrow-to-region beg end)
8597 (while (not (= shift 0))
8598 (org-map-region func (point-min) (point-max))
8599 (setq shift (+ delta shift)))
8600 (goto-char (point-min))
8601 (setq newend (point-max))))
8602 (when (or (org-called-interactively-p 'interactive) for-yank)
8603 (message "Clipboard pasted as level %d subtree" new-level))
8604 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8605 kill-ring
8606 (eq org-subtree-clip (current-kill 0))
8607 org-subtree-clip-folded)
8608 ;; The tree was folded before it was killed/copied
8609 (outline-hide-subtree))
8610 (and for-yank (goto-char newend))
8611 (and remove (setq kill-ring (cdr kill-ring))))))
8613 (defun org-kill-is-subtree-p (&optional txt)
8614 "Check if the current kill is an outline subtree, or a set of trees.
8615 Returns nil if kill does not start with a headline, or if the first
8616 headline level is not the largest headline level in the tree.
8617 So this will actually accept several entries of equal levels as well,
8618 which is OK for `org-paste-subtree'.
8619 If optional TXT is given, check this string instead of the current kill."
8620 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8621 (re (org-get-limited-outline-regexp))
8622 (^re (concat "^" re))
8623 (start-level (and kill
8624 (string-match
8625 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8626 kill)
8627 (- (match-end 2) (match-beginning 2) 1)))
8628 (start (1+ (or (match-beginning 2) -1))))
8629 (if (not start-level)
8630 (progn
8631 nil) ;; does not even start with a heading
8632 (catch 'exit
8633 (while (setq start (string-match ^re kill (1+ start)))
8634 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8635 (throw 'exit nil)))
8636 t))))
8638 (defvar org-markers-to-move nil
8639 "Markers that should be moved with a cut-and-paste operation.
8640 Those markers are stored together with their positions relative to
8641 the start of the region.")
8643 (defun org-save-markers-in-region (beg end)
8644 "Check markers in region.
8645 If these markers are between BEG and END, record their position relative
8646 to BEG, so that after moving the block of text, we can put the markers back
8647 into place.
8648 This function gets called just before an entry or tree gets cut from the
8649 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8650 called immediately, to move the markers with the entries."
8651 (setq org-markers-to-move nil)
8652 (when (featurep 'org-clock)
8653 (org-clock-save-markers-for-cut-and-paste beg end))
8654 (when (featurep 'org-agenda)
8655 (org-agenda-save-markers-for-cut-and-paste beg end)))
8657 (defun org-check-and-save-marker (marker beg end)
8658 "Check if MARKER is between BEG and END.
8659 If yes, remember the marker and the distance to BEG."
8660 (when (and (marker-buffer marker)
8661 (equal (marker-buffer marker) (current-buffer))
8662 (>= marker beg) (< marker end))
8663 (push (cons marker (- marker beg)) org-markers-to-move)))
8665 (defun org-reinstall-markers-in-region (beg)
8666 "Move all remembered markers to their position relative to BEG."
8667 (dolist (x org-markers-to-move)
8668 (move-marker (car x) (+ beg (cdr x))))
8669 (setq org-markers-to-move nil))
8671 (defun org-narrow-to-subtree ()
8672 "Narrow buffer to the current subtree."
8673 (interactive)
8674 (save-excursion
8675 (save-match-data
8676 (org-with-limited-levels
8677 (narrow-to-region
8678 (progn (org-back-to-heading t) (point))
8679 (progn (org-end-of-subtree t t)
8680 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8681 (point)))))))
8683 (defun org-narrow-to-block ()
8684 "Narrow buffer to the current block."
8685 (interactive)
8686 (let* ((case-fold-search t)
8687 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8688 "^[ \t]*#\\+end_.*")))
8689 (if blockp
8690 (narrow-to-region (car blockp) (cdr blockp))
8691 (user-error "Not in a block"))))
8693 (defun org-clone-subtree-with-time-shift (n &optional shift)
8694 "Clone the task (subtree) at point N times.
8695 The clones will be inserted as siblings.
8697 In interactive use, the user will be prompted for the number of
8698 clones to be produced. If the entry has a timestamp, the user
8699 will also be prompted for a time shift, which may be a repeater
8700 as used in time stamps, for example `+3d'. To disable this,
8701 you can call the function with a universal prefix argument.
8703 When a valid repeater is given and the entry contains any time
8704 stamps, the clones will become a sequence in time, with time
8705 stamps in the subtree shifted for each clone produced. If SHIFT
8706 is nil or the empty string, time stamps will be left alone. The
8707 ID property of the original subtree is removed.
8709 If the original subtree did contain time stamps with a repeater,
8710 the following will happen:
8711 - the repeater will be removed in each clone
8712 - an additional clone will be produced, with the current, unshifted
8713 date(s) in the entry.
8714 - the original entry will be placed *after* all the clones, with
8715 repeater intact.
8716 - the start days in the repeater in the original entry will be shifted
8717 to past the last clone.
8718 In this way you can spell out a number of instances of a repeating task,
8719 and still retain the repeater to cover future instances of the task.
8721 As described above, N+1 clones are produced when the original
8722 subtree has a repeater. Setting N to 0, then, can be used to
8723 remove the repeater from a subtree and create a shifted clone
8724 with the original repeater."
8725 (interactive "nNumber of clones to produce: ")
8726 (let ((shift
8727 (or shift
8728 (if (and (not (equal current-prefix-arg '(4)))
8729 (save-excursion
8730 (re-search-forward org-ts-regexp-both
8731 (save-excursion
8732 (org-end-of-subtree t)
8733 (point)) t)))
8734 (read-from-minibuffer
8735 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8736 ""))) ;; No time shift
8737 (n-no-remove -1)
8738 (drawer-re org-drawer-regexp)
8739 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8740 beg end template task idprop
8741 shift-n shift-what doshift nmin nmax)
8742 (unless (wholenump n)
8743 (user-error "Invalid number of replications %s" n))
8744 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8745 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8746 shift)))
8747 (user-error "Invalid shift specification %s" shift))
8748 (when doshift
8749 (setq shift-n (string-to-number (match-string 1 shift))
8750 shift-what (cdr (assoc (match-string 2 shift)
8751 '(("d" . day) ("w" . week)
8752 ("m" . month) ("y" . year))))))
8753 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8754 (setq nmin 1 nmax n)
8755 (org-back-to-heading t)
8756 (setq beg (point))
8757 (setq idprop (org-entry-get nil "ID"))
8758 (org-end-of-subtree t t)
8759 (or (bolp) (insert "\n"))
8760 (setq end (point))
8761 (setq template (buffer-substring beg end))
8762 (when (and doshift
8763 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8764 (delete-region beg end)
8765 (setq end beg)
8766 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8767 (goto-char end)
8768 (cl-loop for n from nmin to nmax do
8769 ;; prepare clone
8770 (with-temp-buffer
8771 (insert template)
8772 (org-mode)
8773 (goto-char (point-min))
8774 (org-show-subtree)
8775 (and idprop (if org-clone-delete-id
8776 (org-entry-delete nil "ID")
8777 (org-id-get-create t)))
8778 (unless (= n 0)
8779 (while (re-search-forward org-clock-re nil t)
8780 (kill-whole-line))
8781 (goto-char (point-min))
8782 (while (re-search-forward drawer-re nil t)
8783 (org-remove-empty-drawer-at (point))))
8784 (goto-char (point-min))
8785 (when doshift
8786 (while (re-search-forward org-ts-regexp-both nil t)
8787 (org-timestamp-change (* n shift-n) shift-what))
8788 (unless (= n n-no-remove)
8789 (goto-char (point-min))
8790 (while (re-search-forward org-ts-regexp nil t)
8791 (save-excursion
8792 (goto-char (match-beginning 0))
8793 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8794 (delete-region (match-beginning 1) (match-end 1)))))))
8795 (setq task (buffer-string)))
8796 (insert task))
8797 (goto-char beg)))
8799 ;;; Outline Sorting
8801 (defun org-sort (with-case)
8802 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8803 Optional argument WITH-CASE means sort case-sensitively."
8804 (interactive "P")
8805 (cond
8806 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8807 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8809 (org-call-with-arg 'org-sort-entries with-case))))
8811 (defun org-sort-remove-invisible (s)
8812 "Remove invisible links from string S."
8813 (remove-text-properties 0 (length s) org-rm-props s)
8814 (while (string-match org-bracket-link-regexp s)
8815 (setq s (replace-match (if (match-end 2)
8816 (match-string 3 s)
8817 (match-string 1 s))
8818 t t s)))
8819 (let ((st (format " %s " s)))
8820 (while (string-match org-emph-re st)
8821 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8822 (setq s (substring st 1 -1)))
8825 (defvar org-priority-regexp) ; defined later in the file
8827 (defvar org-after-sorting-entries-or-items-hook nil
8828 "Hook that is run after a bunch of entries or items have been sorted.
8829 When children are sorted, the cursor is in the parent line when this
8830 hook gets called. When a region or a plain list is sorted, the cursor
8831 will be in the first entry of the sorted region/list.")
8833 (defun org-sort-entries
8834 (&optional with-case sorting-type getkey-func compare-func property)
8835 "Sort entries on a certain level of an outline tree.
8836 If there is an active region, the entries in the region are sorted.
8837 Else, if the cursor is before the first entry, sort the top-level items.
8838 Else, the children of the entry at point are sorted.
8840 Sorting can be alphabetically, numerically, by date/time as given by
8841 a time stamp, by a property, by priority order, or by a custom function.
8843 The command prompts for the sorting type unless it has been given to the
8844 function through the SORTING-TYPE argument, which needs to be a character,
8845 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8846 the precise meaning of each character:
8848 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8849 c By creation time, which is assumed to be the first inactive time stamp
8850 at the beginning of a line.
8851 d By deadline date/time.
8852 k By clocking time.
8853 n Numerically, by converting the beginning of the entry/item to a number.
8854 o By order of TODO keywords.
8855 p By priority according to the cookie.
8856 r By the value of a property.
8857 s By scheduled date/time.
8858 t By date/time, either the first active time stamp in the entry, or, if
8859 none exist, by the first inactive one.
8861 Capital letters will reverse the sort order.
8863 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8864 called with point at the beginning of the record. It must return either
8865 a string or a number that should serve as the sorting key for that record.
8867 Comparing entries ignores case by default. However, with an optional argument
8868 WITH-CASE, the sorting considers case as well.
8870 Sorting is done against the visible part of the headlines, it ignores hidden
8871 links.
8873 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8874 (interactive "P")
8875 (let ((case-func (if with-case 'identity 'downcase))
8876 (cmstr
8877 ;; The clock marker is lost when using `sort-subr', let's
8878 ;; store the clocking string.
8879 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8880 (save-excursion
8881 (goto-char org-clock-marker)
8882 (buffer-substring-no-properties (line-beginning-position)
8883 (point)))))
8884 start beg end stars re re2
8885 txt what tmp)
8886 ;; Find beginning and end of region to sort
8887 (cond
8888 ((org-region-active-p)
8889 ;; we will sort the region
8890 (setq end (region-end)
8891 what "region")
8892 (goto-char (region-beginning))
8893 (unless (org-at-heading-p) (outline-next-heading))
8894 (setq start (point)))
8895 ((or (org-at-heading-p)
8896 (ignore-errors (progn (org-back-to-heading) t)))
8897 ;; we will sort the children of the current headline
8898 (org-back-to-heading)
8899 (setq start (point)
8900 end (progn (org-end-of-subtree t t)
8901 (or (bolp) (insert "\n"))
8902 (when (>= (org-back-over-empty-lines) 1)
8903 (forward-line 1))
8904 (point))
8905 what "children")
8906 (goto-char start)
8907 (outline-show-subtree)
8908 (outline-next-heading))
8910 ;; we will sort the top-level entries in this file
8911 (goto-char (point-min))
8912 (or (org-at-heading-p) (outline-next-heading))
8913 (setq start (point))
8914 (goto-char (point-max))
8915 (beginning-of-line 1)
8916 (when (looking-at ".*?\\S-")
8917 ;; File ends in a non-white line
8918 (end-of-line 1)
8919 (insert "\n"))
8920 (setq end (point-max))
8921 (setq what "top-level")
8922 (goto-char start)
8923 (outline-show-all)))
8925 (setq beg (point))
8926 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8928 (looking-at "\\(\\*+\\)")
8929 (setq stars (match-string 1)
8930 re (concat "^" (regexp-quote stars) " +")
8931 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8932 txt (buffer-substring beg end))
8933 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8934 (when (and (not (equal stars "*")) (string-match re2 txt))
8935 (user-error "Region to sort contains a level above the first entry"))
8937 (unless sorting-type
8938 (message
8939 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8940 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8941 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8942 what)
8943 (setq sorting-type (read-char-exclusive))
8945 (unless getkey-func
8946 (and (= (downcase sorting-type) ?f)
8947 (setq getkey-func
8948 (completing-read "Sort using function: "
8949 obarray 'fboundp t nil nil))
8950 (setq getkey-func (intern getkey-func))))
8952 (and (= (downcase sorting-type) ?r)
8953 (not property)
8954 (setq property
8955 (completing-read "Property: "
8956 (mapcar #'list (org-buffer-property-keys t))
8957 nil t))))
8959 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8960 (message "Sorting entries...")
8962 (save-restriction
8963 (narrow-to-region start end)
8964 (let ((dcst (downcase sorting-type))
8965 (case-fold-search nil)
8966 (now (current-time)))
8967 (sort-subr
8968 (/= dcst sorting-type)
8969 ;; This function moves to the beginning character of the "record" to
8970 ;; be sorted.
8971 (lambda nil
8972 (if (re-search-forward re nil t)
8973 (goto-char (match-beginning 0))
8974 (goto-char (point-max))))
8975 ;; This function moves to the last character of the "record" being
8976 ;; sorted.
8977 (lambda nil
8978 (save-match-data
8979 (condition-case nil
8980 (outline-forward-same-level 1)
8981 (error
8982 (goto-char (point-max))))))
8983 ;; This function returns the value that gets sorted against.
8984 (lambda nil
8985 (cond
8986 ((= dcst ?n)
8987 (if (looking-at org-complex-heading-regexp)
8988 (string-to-number (org-sort-remove-invisible (match-string 4)))
8989 nil))
8990 ((= dcst ?a)
8991 (if (looking-at org-complex-heading-regexp)
8992 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8993 nil))
8994 ((= dcst ?k)
8995 (or (get-text-property (point) :org-clock-minutes) 0))
8996 ((= dcst ?t)
8997 (let ((end (save-excursion (outline-next-heading) (point))))
8998 (if (or (re-search-forward org-ts-regexp end t)
8999 (re-search-forward org-ts-regexp-both end t))
9000 (org-time-string-to-seconds (match-string 0))
9001 (org-float-time now))))
9002 ((= dcst ?c)
9003 (let ((end (save-excursion (outline-next-heading) (point))))
9004 (if (re-search-forward
9005 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9006 end t)
9007 (org-time-string-to-seconds (match-string 0))
9008 (org-float-time now))))
9009 ((= dcst ?s)
9010 (let ((end (save-excursion (outline-next-heading) (point))))
9011 (if (re-search-forward org-scheduled-time-regexp end t)
9012 (org-time-string-to-seconds (match-string 1))
9013 (org-float-time now))))
9014 ((= dcst ?d)
9015 (let ((end (save-excursion (outline-next-heading) (point))))
9016 (if (re-search-forward org-deadline-time-regexp end t)
9017 (org-time-string-to-seconds (match-string 1))
9018 (org-float-time now))))
9019 ((= dcst ?p)
9020 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9021 (string-to-char (match-string 2))
9022 org-default-priority))
9023 ((= dcst ?r)
9024 (or (org-entry-get nil property) ""))
9025 ((= dcst ?o)
9026 (when (looking-at org-complex-heading-regexp)
9027 (let* ((m (match-string 2))
9028 (s (if (member m org-done-keywords) '- '+)))
9029 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9030 ((= dcst ?f)
9031 (if getkey-func
9032 (progn
9033 (setq tmp (funcall getkey-func))
9034 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9035 tmp)
9036 (error "Invalid key function `%s'" getkey-func)))
9037 (t (error "Invalid sorting type `%c'" sorting-type))))
9039 (cond
9040 ((= dcst ?a) 'string<)
9041 ((= dcst ?f) compare-func)
9042 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9043 (run-hooks 'org-after-sorting-entries-or-items-hook)
9044 ;; Reset the clock marker if needed
9045 (when cmstr
9046 (save-excursion
9047 (goto-char start)
9048 (search-forward cmstr nil t)
9049 (move-marker org-clock-marker (point))))
9050 (message "Sorting entries...done")))
9052 ;;; The orgstruct minor mode
9054 ;; Define a minor mode which can be used in other modes in order to
9055 ;; integrate the org-mode structure editing commands.
9057 ;; This is really a hack, because the org-mode structure commands use
9058 ;; keys which normally belong to the major mode. Here is how it
9059 ;; works: The minor mode defines all the keys necessary to operate the
9060 ;; structure commands, but wraps the commands into a function which
9061 ;; tests if the cursor is currently at a headline or a plain list
9062 ;; item. If that is the case, the structure command is used,
9063 ;; temporarily setting many Org-mode variables like regular
9064 ;; expressions for filling etc. However, when any of those keys is
9065 ;; used at a different location, function uses `key-binding' to look
9066 ;; up if the key has an associated command in another currently active
9067 ;; keymap (minor modes, major mode, global), and executes that
9068 ;; command. There might be problems if any of the keys is otherwise
9069 ;; used as a prefix key.
9071 (defcustom orgstruct-heading-prefix-regexp ""
9072 "Regexp that matches the custom prefix of Org headlines in
9073 orgstruct(++)-mode."
9074 :group 'org
9075 :version "24.4"
9076 :package-version '(Org . "8.3")
9077 :type 'regexp)
9078 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9080 (defcustom orgstruct-setup-hook nil
9081 "Hook run after orgstruct-mode-map is filled."
9082 :group 'org
9083 :version "24.4"
9084 :package-version '(Org . "8.0")
9085 :type 'hook)
9087 (defvar orgstruct-initialized nil)
9089 (defvar org-local-vars nil
9090 "List of local variables, for use by `orgstruct-mode'.")
9092 ;;;###autoload
9093 (define-minor-mode orgstruct-mode
9094 "Toggle the minor mode `orgstruct-mode'.
9095 This mode is for using Org-mode structure commands in other
9096 modes. The following keys behave as if Org-mode were active, if
9097 the cursor is on a headline, or on a plain list item (both as
9098 defined by Org-mode)."
9099 nil " OrgStruct" (make-sparse-keymap)
9100 (funcall (if orgstruct-mode
9101 'add-to-invisibility-spec
9102 'remove-from-invisibility-spec)
9103 '(outline . t))
9104 (when orgstruct-mode
9105 (org-load-modules-maybe)
9106 (unless orgstruct-initialized
9107 (orgstruct-setup)
9108 (setq orgstruct-initialized t))))
9110 ;;;###autoload
9111 (defun turn-on-orgstruct ()
9112 "Unconditionally turn on `orgstruct-mode'."
9113 (orgstruct-mode 1))
9115 (defvar-local orgstruct-is-++ nil
9116 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9117 (defvar-local org-fb-vars nil)
9118 (defun orgstruct++-mode (&optional arg)
9119 "Toggle `orgstruct-mode', the enhanced version of it.
9120 In addition to setting orgstruct-mode, this also exports all
9121 indentation and autofilling variables from org-mode into the
9122 buffer. It will also recognize item context in multiline items."
9123 (interactive "P")
9124 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9125 (if (< arg 1)
9126 (progn (orgstruct-mode -1)
9127 (dolist (v org-fb-vars)
9128 (set (make-local-variable (car v))
9129 (if (eq (car-safe (cadr v)) 'quote)
9130 (cl-cadadr v)
9131 (nth 1 v)))))
9132 (orgstruct-mode 1)
9133 (setq org-fb-vars nil)
9134 (unless org-local-vars
9135 (setq org-local-vars (org-get-local-variables)))
9136 (let (var val)
9137 (dolist (x org-local-vars)
9138 (when (string-match
9139 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9140 \\|fill-prefix\\|indent-\\)"
9141 (symbol-name (car x)))
9142 (setq var (car x) val (nth 1 x))
9143 (push (list var `(quote ,(eval var))) org-fb-vars)
9144 (set (make-local-variable var)
9145 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9146 (setq-local orgstruct-is-++ t))))
9148 ;;;###autoload
9149 (defun turn-on-orgstruct++ ()
9150 "Unconditionally turn on `orgstruct++-mode'."
9151 (orgstruct++-mode 1))
9153 (defun orgstruct-error ()
9154 "Error when there is no default binding for a structure key."
9155 (interactive)
9156 (funcall (if (fboundp 'user-error)
9157 'user-error
9158 'error)
9159 "This key has no function outside structure elements"))
9161 (defun orgstruct-setup ()
9162 "Setup orgstruct keymap."
9163 (dolist (cell '((org-demote . t)
9164 (org-metaleft . t)
9165 (org-metaright . t)
9166 (org-promote . t)
9167 (org-shiftmetaleft . t)
9168 (org-shiftmetaright . t)
9169 org-backward-element
9170 org-backward-heading-same-level
9171 org-ctrl-c-ret
9172 org-ctrl-c-minus
9173 org-ctrl-c-star
9174 org-cycle
9175 org-force-cycle-archived
9176 org-forward-heading-same-level
9177 org-insert-heading
9178 org-insert-heading-respect-content
9179 org-kill-note-or-show-branches
9180 org-mark-subtree
9181 org-meta-return
9182 org-metadown
9183 org-metaup
9184 org-narrow-to-subtree
9185 org-promote-subtree
9186 org-reveal
9187 org-shiftdown
9188 org-shiftleft
9189 org-shiftmetadown
9190 org-shiftmetaup
9191 org-shiftright
9192 org-shifttab
9193 org-shifttab
9194 org-shiftup
9195 org-show-children
9196 org-show-subtree
9197 org-sort
9198 org-up-element
9199 outline-demote
9200 outline-next-visible-heading
9201 outline-previous-visible-heading
9202 outline-promote
9203 outline-up-heading))
9204 (let ((f (or (car-safe cell) cell))
9205 (disable-when-heading-prefix (cdr-safe cell)))
9206 (when (fboundp f)
9207 (let ((new-bindings))
9208 (dolist (binding (nconc (where-is-internal f org-mode-map)
9209 (where-is-internal f outline-mode-map)))
9210 (push binding new-bindings)
9211 ;; TODO use local-function-key-map
9212 (dolist (rep '(("<tab>" . "TAB")
9213 ("<return>" . "RET")
9214 ("<escape>" . "ESC")
9215 ("<delete>" . "DEL")))
9216 (setq binding (read-kbd-macro
9217 (let ((case-fold-search))
9218 (replace-regexp-in-string
9219 (regexp-quote (cdr rep))
9220 (car rep)
9221 (key-description binding)))))
9222 (cl-pushnew binding new-bindings :test 'equal)))
9223 (dolist (binding new-bindings)
9224 (let ((key (lookup-key orgstruct-mode-map binding)))
9225 (when (or (not key) (numberp key))
9226 (ignore-errors
9227 (org-defkey orgstruct-mode-map
9228 binding
9229 (orgstruct-make-binding
9230 f binding disable-when-heading-prefix))))))))))
9231 (run-hooks 'orgstruct-setup-hook))
9233 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9234 "Create a function for binding in the structure minor mode.
9235 FUN is the command to call inside a table. KEY is the key that
9236 should be checked in for a command to execute outside of tables.
9237 Non-nil `disable-when-heading-prefix' means to disable the command
9238 if `orgstruct-heading-prefix-regexp' is not empty."
9239 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9240 (let ((nname name)
9241 (i 0))
9242 (while (fboundp (intern nname))
9243 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9244 (setq name (intern nname)))
9245 (eval
9246 (let ((bindings '((org-heading-regexp
9247 (concat "^"
9248 orgstruct-heading-prefix-regexp
9249 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9250 (org-outline-regexp
9251 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9252 (org-outline-regexp-bol
9253 (concat "^" org-outline-regexp))
9254 (outline-regexp org-outline-regexp)
9255 (outline-heading-end-regexp "\n")
9256 (outline-level 'org-outline-level)
9257 (outline-heading-alist))))
9258 `(defun ,name (arg)
9259 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9260 "Outside of structure, run the binding of `"
9261 (key-description key) "'."
9262 (when disable-when-heading-prefix
9263 (concat
9264 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9265 "back to the default binding due to limitations of Org's implementation of\n"
9266 "`" (symbol-name fun) "'.")))
9267 (interactive "p")
9268 (let* ((disable
9269 ,(and disable-when-heading-prefix
9270 '(not (string= orgstruct-heading-prefix-regexp ""))))
9271 (fallback
9272 (or disable
9273 (not
9274 (let* ,bindings
9275 (org-context-p 'headline 'item
9276 ,(when (memq fun
9277 '(org-insert-heading
9278 org-insert-heading-respect-content
9279 org-meta-return))
9280 '(when orgstruct-is-++
9281 'item-body))))))))
9282 (if fallback
9283 (let* ((orgstruct-mode)
9284 (binding
9285 (let ((key ,key))
9286 (catch 'exit
9287 (dolist
9288 (rep
9289 '(nil
9290 ("<\\([^>]*\\)tab>" . "\\1TAB")
9291 ("<\\([^>]*\\)return>" . "\\1RET")
9292 ("<\\([^>]*\\)escape>" . "\\1ESC")
9293 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9294 nil)
9295 (when rep
9296 (setq key (read-kbd-macro
9297 (let ((case-fold-search))
9298 (replace-regexp-in-string
9299 (car rep)
9300 (cdr rep)
9301 (key-description key))))))
9302 (when (key-binding key)
9303 (throw 'exit (key-binding key))))))))
9304 (if (keymapp binding)
9305 (org-set-transient-map binding)
9306 (let ((func (or binding
9307 (unless disable
9308 'orgstruct-error))))
9309 (when func
9310 (call-interactively func)))))
9311 (org-run-like-in-org-mode
9312 (lambda ()
9313 (interactive)
9314 (let* ,bindings
9315 (call-interactively ',fun)))))))))
9316 name))
9318 (defun org-contextualize-keys (alist contexts)
9319 "Return valid elements in ALIST depending on CONTEXTS.
9321 `org-agenda-custom-commands' or `org-capture-templates' are the
9322 values used for ALIST, and `org-agenda-custom-commands-contexts'
9323 or `org-capture-templates-contexts' are the associated contexts
9324 definitions."
9325 (let ((contexts
9326 ;; normalize contexts
9327 (mapcar
9328 (lambda(c) (cond ((listp (cadr c))
9329 (list (car c) (car c) (nth 1 c)))
9330 ((string= "" (cadr c))
9331 (list (car c) (car c) (nth 2 c)))
9332 (t c)))
9333 contexts))
9334 (a alist) r s)
9335 ;; loop over all commands or templates
9336 (dolist (c a)
9337 (let (vrules repl)
9338 (cond
9339 ((not (assoc (car c) contexts))
9340 (push c r))
9341 ((and (assoc (car c) contexts)
9342 (setq vrules (org-contextualize-validate-key
9343 (car c) contexts)))
9344 (mapc (lambda (vr)
9345 (unless (equal (car vr) (cadr vr))
9346 (setq repl vr)))
9347 vrules)
9348 (if (not repl) (push c r)
9349 (push (cadr repl) s)
9350 (push
9351 (cons (car c)
9352 (cdr (or (assoc (cadr repl) alist)
9353 (error "Undefined key `%s' as contextual replacement for `%s'"
9354 (cadr repl) (car c)))))
9355 r))))))
9356 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9357 (delq
9359 (delete-dups
9360 (mapcar (lambda (x)
9361 (let ((tpl (car x)))
9362 (unless (delq
9364 (mapcar (lambda (y)
9365 (equal y tpl))
9367 x)))
9368 (reverse r))))))
9370 (defun org-contextualize-validate-key (key contexts)
9371 "Check CONTEXTS for agenda or capture KEY."
9372 (let (res)
9373 (dolist (r contexts)
9374 (dolist (rr (car (last r)))
9375 (when
9376 (and (equal key (car r))
9377 (if (functionp rr) (funcall rr)
9378 (or (and (eq (car rr) 'in-file)
9379 (buffer-file-name)
9380 (string-match (cdr rr) (buffer-file-name)))
9381 (and (eq (car rr) 'in-mode)
9382 (string-match (cdr rr) (symbol-name major-mode)))
9383 (and (eq (car rr) 'in-buffer)
9384 (string-match (cdr rr) (buffer-name)))
9385 (when (and (eq (car rr) 'not-in-file)
9386 (buffer-file-name))
9387 (not (string-match (cdr rr) (buffer-file-name))))
9388 (when (eq (car rr) 'not-in-mode)
9389 (not (string-match (cdr rr) (symbol-name major-mode))))
9390 (when (eq (car rr) 'not-in-buffer)
9391 (not (string-match (cdr rr) (buffer-name)))))))
9392 (push r res))))
9393 (delete-dups (delq nil res))))
9395 (defun org-context-p (&rest contexts)
9396 "Check if local context is any of CONTEXTS.
9397 Possible values in the list of contexts are `table', `headline', and `item'."
9398 (let ((pos (point)))
9399 (goto-char (point-at-bol))
9400 (prog1 (or (and (memq 'table contexts)
9401 (looking-at "[ \t]*|"))
9402 (and (memq 'headline contexts)
9403 (looking-at org-outline-regexp))
9404 (and (memq 'item contexts)
9405 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9406 (and (memq 'item-body contexts)
9407 (org-in-item-p)))
9408 (goto-char pos))))
9410 (defconst org-unique-local-variables
9411 '(org-element--cache
9412 org-element--cache-objects
9413 org-element--cache-sync-keys
9414 org-element--cache-sync-requests
9415 org-element--cache-sync-timer)
9416 "List of local variables that cannot be transferred to another buffer.")
9418 (defun org-get-local-variables ()
9419 "Return a list of all local variables in an Org mode buffer."
9420 (delq nil
9421 (mapcar
9422 (lambda (x)
9423 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9424 (name (car binding)))
9425 (and (not (get name 'org-state))
9426 (not (memq name org-unique-local-variables))
9427 (string-match-p
9428 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9429 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9430 (symbol-name name))
9431 binding)))
9432 (with-temp-buffer
9433 (org-mode)
9434 (buffer-local-variables)))))
9436 (defun org-clone-local-variables (from-buffer &optional regexp)
9437 "Clone local variables from FROM-BUFFER.
9438 Optional argument REGEXP selects variables to clone."
9439 (dolist (pair (buffer-local-variables from-buffer))
9440 (let ((name (car pair)))
9441 (when (and (symbolp name)
9442 (not (memq name org-unique-local-variables))
9443 (or (null regexp) (string-match regexp (symbol-name name))))
9444 (set (make-local-variable name) (cdr pair))))))
9446 ;;;###autoload
9447 (defun org-run-like-in-org-mode (cmd)
9448 "Run a command, pretending that the current buffer is in Org-mode.
9449 This will temporarily bind local variables that are typically bound in
9450 Org-mode to the values they have in Org-mode, and then interactively
9451 call CMD."
9452 (org-load-modules-maybe)
9453 (unless org-local-vars
9454 (setq org-local-vars (org-get-local-variables)))
9455 (let (binds)
9456 (dolist (var org-local-vars)
9457 (when (or (not (boundp (car var)))
9458 (eq (symbol-value (car var))
9459 (default-value (car var))))
9460 (push (list (car var) `(quote ,(cadr var))) binds)))
9461 (eval `(let ,binds
9462 (call-interactively (quote ,cmd))))))
9464 (defun org-get-category (&optional pos force-refresh)
9465 "Get the category applying to position POS."
9466 (save-match-data
9467 (when force-refresh (org-refresh-category-properties))
9468 (let ((pos (or pos (point))))
9469 (or (get-text-property pos 'org-category)
9470 (progn (org-refresh-category-properties)
9471 (get-text-property pos 'org-category))))))
9473 ;;; Refresh properties
9475 (defun org-refresh-properties (dprop tprop)
9476 "Refresh buffer text properties.
9477 DPROP is the drawer property and TPROP is either the
9478 corresponding text property to set, or an alist with each element
9479 being a text property (as a symbol) and a function to apply to
9480 the value of the drawer property."
9481 (let ((case-fold-search t)
9482 (inhibit-read-only t))
9483 (org-with-silent-modifications
9484 (save-excursion
9485 (save-restriction
9486 (widen)
9487 (goto-char (point-min))
9488 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9489 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9491 (defun org-refresh-property (tprop p)
9492 "Refresh the buffer text property TPROP from the drawer property P.
9493 The refresh happens only for the current tree (not subtree)."
9494 (unless (org-before-first-heading-p)
9495 (save-excursion
9496 (org-back-to-heading t)
9497 (if (symbolp tprop)
9498 ;; TPROP is a text property symbol
9499 (put-text-property
9500 (point) (or (outline-next-heading) (point-max)) tprop p)
9501 ;; TPROP is an alist with (properties . function) elements
9502 (dolist (al tprop)
9503 (save-excursion
9504 (put-text-property
9505 (line-beginning-position) (or (outline-next-heading) (point-max))
9506 (car al)
9507 (funcall (cdr al) p))))))))
9509 (defun org-refresh-category-properties ()
9510 "Refresh category text properties in the buffer."
9511 (let ((case-fold-search t)
9512 (inhibit-read-only t)
9513 (default-category
9514 (cond ((null org-category)
9515 (if buffer-file-name
9516 (file-name-sans-extension
9517 (file-name-nondirectory buffer-file-name))
9518 "???"))
9519 ((symbolp org-category) (symbol-name org-category))
9520 (t org-category))))
9521 (org-with-silent-modifications
9522 (org-with-wide-buffer
9523 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9524 ;; This is the default category for the buffer. If none is
9525 ;; found, fall-back to `org-category' or buffer file name.
9526 (put-text-property
9527 (point-min) (point-max)
9528 'org-category
9529 (catch 'buffer-category
9530 (goto-char (point-max))
9531 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9532 (let ((element (org-element-at-point)))
9533 (when (eq (org-element-type element) 'keyword)
9534 (throw 'buffer-category
9535 (org-element-property :value element)))))
9536 default-category))
9537 ;; Set sub-tree specific categories.
9538 (goto-char (point-min))
9539 (let ((regexp (org-re-property "CATEGORY")))
9540 (while (re-search-forward regexp nil t)
9541 (let ((value (org-match-string-no-properties 3)))
9542 (when (org-at-property-p)
9543 (put-text-property
9544 (save-excursion (org-back-to-heading t) (point))
9545 (save-excursion (org-end-of-subtree t t) (point))
9546 'org-category
9547 value)))))))))
9549 (defun org-refresh-stats-properties ()
9550 "Refresh stats text properties in the buffer."
9551 (let (stats)
9552 (org-with-silent-modifications
9553 (save-excursion
9554 (save-restriction
9555 (widen)
9556 (goto-char (point-min))
9557 (while (re-search-forward
9558 (concat org-outline-regexp-bol ".*"
9559 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9560 nil t)
9561 (setq stats (cond ((equal (match-string 3) "0") 0)
9562 ((match-string 2)
9563 (/ (* (string-to-number (match-string 2)) 100)
9564 (string-to-number (match-string 3))))
9565 (t (string-to-number (match-string 1)))))
9566 (org-back-to-heading t)
9567 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9568 'org-stats stats)))))))
9570 (defun org-refresh-effort-properties ()
9571 "Refresh effort properties"
9572 (org-refresh-properties
9573 org-effort-property
9574 '((effort . identity)
9575 (effort-minutes . org-duration-string-to-minutes))))
9577 ;;;; Link Stuff
9579 ;;; Link abbreviations
9581 (defun org-link-expand-abbrev (link)
9582 "Apply replacements as defined in `org-link-abbrev-alist'."
9583 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9584 (let* ((key (match-string 1 link))
9585 (as (or (assoc key org-link-abbrev-alist-local)
9586 (assoc key org-link-abbrev-alist)))
9587 (tag (and (match-end 2) (match-string 3 link)))
9588 rpl)
9589 (if (not as)
9590 link
9591 (setq rpl (cdr as))
9592 (cond
9593 ((symbolp rpl) (funcall rpl tag))
9594 ((string-match "%(\\([^)]+\\))" rpl)
9595 (replace-match
9596 (save-match-data
9597 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9598 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9599 ((string-match "%h" rpl)
9600 (replace-match (url-hexify-string (or tag "")) t t rpl))
9601 (t (concat rpl tag)))))
9602 link))
9604 ;;; Storing and inserting links
9606 (defvar org-insert-link-history nil
9607 "Minibuffer history for links inserted with `org-insert-link'.")
9609 (defvar org-stored-links nil
9610 "Contains the links stored with `org-store-link'.")
9612 (defvar org-store-link-plist nil
9613 "Plist with info about the most recently link created with `org-store-link'.")
9615 (defvar org-link-protocols nil
9616 "Link protocols added to Org-mode using `org-add-link-type'.")
9618 (defvar org-store-link-functions nil
9619 "List of functions that are called to create and store a link.
9620 Each function will be called in turn until one returns a non-nil
9621 value. Each function should check if it is responsible for creating
9622 this link (for example by looking at the major mode).
9623 If not, it must exit and return nil.
9624 If yes, it should return a non-nil value after a calling
9625 `org-store-link-props' with a list of properties and values.
9626 Special properties are:
9628 :type The link prefix, like \"http\". This must be given.
9629 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9630 This is obligatory as well.
9631 :description Optional default description for the second pair
9632 of brackets in an Org-mode link. The user can still change
9633 this when inserting this link into an Org-mode buffer.
9635 In addition to these, any additional properties can be specified
9636 and then used in capture templates.")
9638 (defun org-add-link-type (type &optional follow export)
9639 "Add TYPE to the list of `org-link-types'.
9640 Re-compute all regular expressions depending on `org-link-types'
9642 FOLLOW and EXPORT are two functions.
9644 FOLLOW should take the link path as the single argument and do whatever
9645 is necessary to follow the link, for example find a file or display
9646 a mail message.
9648 EXPORT should format the link path for export to one of the export formats.
9649 It should be a function accepting three arguments:
9651 path the path of the link, the text after the prefix (like \"http:\")
9652 desc the description of the link, if any
9653 format the export format, a symbol like `html' or `latex' or `ascii'.
9655 The function may use the FORMAT information to return different values
9656 depending on the format. The return value will be put literally into
9657 the exported file. If the return value is nil, this means Org should
9658 do what it normally does with links which do not have EXPORT defined.
9660 Org mode has a built-in default for exporting links. If you are happy with
9661 this default, there is no need to define an export function for the link
9662 type. For a simple example of an export function, see `org-bbdb.el'."
9663 (add-to-list 'org-link-types type t)
9664 (org-make-link-regexps)
9665 (org-element-update-syntax)
9666 (if (assoc type org-link-protocols)
9667 (setcdr (assoc type org-link-protocols) (list follow export))
9668 (push (list type follow export) org-link-protocols)))
9670 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9671 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9673 ;;;###autoload
9674 (defun org-store-link (arg)
9675 "\\<org-mode-map>Store an org-link to the current location.
9676 This link is added to `org-stored-links' and can later be inserted
9677 into an Org buffer with \\[org-insert-link].
9679 For some link types, a prefix ARG is interpreted.
9680 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9681 For file links, ARG negates `org-context-in-file-links'.
9683 A double prefix ARG force skipping storing functions that are not
9684 part of Org's core.
9686 A triple prefix ARG force storing a link for each line in the
9687 active region."
9688 (interactive "P")
9689 (org-load-modules-maybe)
9690 (if (and (equal arg '(64)) (org-region-active-p))
9691 (save-excursion
9692 (let ((end (region-end)))
9693 (goto-char (region-beginning))
9694 (set-mark (point))
9695 (while (< (point-at-eol) end)
9696 (move-end-of-line 1) (activate-mark)
9697 (let (current-prefix-arg)
9698 (call-interactively 'org-store-link))
9699 (move-beginning-of-line 2)
9700 (set-mark (point)))))
9701 (org-with-limited-levels
9702 (setq org-store-link-plist nil)
9703 (let (link cpltxt desc description search
9704 txt custom-id agenda-link sfuns sfunsn)
9705 (cond
9707 ;; Store a link using an external link type
9708 ((and (not (equal arg '(16)))
9709 (setq sfuns
9710 (delq
9711 nil (mapcar (lambda (f)
9712 (let (fs) (if (funcall f) (push f fs))))
9713 org-store-link-functions))
9714 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9715 (or (and (cdr sfuns)
9716 (funcall (intern
9717 (completing-read
9718 "Which function for creating the link? "
9719 sfunsn nil t (car sfunsn)))))
9720 (funcall (caar sfuns)))
9721 (setq link (plist-get org-store-link-plist :link)
9722 desc (or (plist-get org-store-link-plist
9723 :description)
9724 link))))
9726 ;; Store a link from a source code buffer.
9727 ((org-src-edit-buffer-p)
9728 (cond
9729 ((save-excursion
9730 (beginning-of-line)
9731 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9732 "[ \t]*$")))
9733 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9734 ((org-called-interactively-p 'any)
9735 (let (label)
9736 (while (or (not label)
9737 (org-with-wide-buffer
9738 (goto-char (point-min))
9739 (re-search-forward
9740 (regexp-quote (format org-coderef-label-format label))
9741 nil t)))
9742 (when label (message "Label exists already") (sit-for 2))
9743 (setq label (read-string "Code line label: " label)))
9744 (end-of-line)
9745 (setq link (format org-coderef-label-format label))
9746 (let ((gc (- 79 (length link))))
9747 (if (< (current-column) gc) (org-move-to-column gc t)
9748 (insert " ")))
9749 (insert link)
9750 (setq link (concat "(" label ")") desc nil)))
9751 (t (setq link nil))))
9753 ;; We are in the agenda, link to referenced location
9754 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9755 (let ((m (or (get-text-property (point) 'org-hd-marker)
9756 (get-text-property (point) 'org-marker))))
9757 (when m
9758 (org-with-point-at m
9759 (setq agenda-link
9760 (if (org-called-interactively-p 'any)
9761 (call-interactively 'org-store-link)
9762 (org-store-link nil)))))))
9764 ((eq major-mode 'calendar-mode)
9765 (let ((cd (calendar-cursor-to-date)))
9766 (setq link
9767 (format-time-string
9768 (car org-time-stamp-formats)
9769 (apply 'encode-time
9770 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9771 nil nil nil))))
9772 (org-store-link-props :type "calendar" :date cd)))
9774 ((eq major-mode 'help-mode)
9775 (setq link (concat "help:" (save-excursion
9776 (goto-char (point-min))
9777 (looking-at "^[^ ]+")
9778 (match-string 0))))
9779 (org-store-link-props :type "help"))
9781 ((eq major-mode 'w3-mode)
9782 (setq cpltxt (if (and (buffer-name)
9783 (not (string-match "Untitled" (buffer-name))))
9784 (buffer-name)
9785 (url-view-url t))
9786 link (url-view-url t))
9787 (org-store-link-props :type "w3" :url (url-view-url t)))
9789 ((eq major-mode 'image-mode)
9790 (setq cpltxt (concat "file:"
9791 (abbreviate-file-name buffer-file-name))
9792 link cpltxt)
9793 (org-store-link-props :type "image" :file buffer-file-name))
9795 ;; In dired, store a link to the file of the current line
9796 ((derived-mode-p 'dired-mode)
9797 (let ((file (dired-get-filename nil t)))
9798 (setq file (if file
9799 (abbreviate-file-name
9800 (expand-file-name (dired-get-filename nil t)))
9801 ;; otherwise, no file so use current directory.
9802 default-directory))
9803 (setq cpltxt (concat "file:" file)
9804 link cpltxt)))
9806 ((setq search (run-hook-with-args-until-success
9807 'org-create-file-search-functions))
9808 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9809 "::" search))
9810 (setq cpltxt (or description link)))
9812 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9813 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9814 (cond
9815 ;; Store a link using the target at point
9816 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9817 (setq cpltxt
9818 (concat "file:"
9819 (abbreviate-file-name
9820 (buffer-file-name (buffer-base-buffer)))
9821 "::" (match-string 1))
9822 link cpltxt))
9823 ((and (featurep 'org-id)
9824 (or (eq org-id-link-to-org-use-id t)
9825 (and (org-called-interactively-p 'any)
9826 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9827 (and (eq org-id-link-to-org-use-id
9828 'create-if-interactive-and-no-custom-id)
9829 (not custom-id))))
9830 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9831 ;; Store a link using the ID at point
9832 (setq link (condition-case nil
9833 (prog1 (org-id-store-link)
9834 (setq desc (or (plist-get org-store-link-plist
9835 :description)
9836 "")))
9837 (error
9838 ;; Probably before first headline, link only to file
9839 (concat "file:"
9840 (abbreviate-file-name
9841 (buffer-file-name (buffer-base-buffer))))))))
9843 ;; Just link to current headline
9844 (setq cpltxt (concat "file:"
9845 (abbreviate-file-name
9846 (buffer-file-name (buffer-base-buffer)))))
9847 ;; Add a context search string
9848 (when (org-xor org-context-in-file-links arg)
9849 (let* ((ee (org-element-at-point))
9850 (et (org-element-type ee))
9851 (ev (plist-get (cadr ee) :value))
9852 (ek (plist-get (cadr ee) :key))
9853 (eok (and (stringp ek) (string-match "name" ek))))
9854 (setq txt (cond
9855 ((org-at-heading-p) nil)
9856 ((and (eq et 'keyword) eok) ev)
9857 ((org-region-active-p)
9858 (buffer-substring (region-beginning) (region-end)))))
9859 (when (or (null txt) (string-match "\\S-" txt))
9860 (setq cpltxt
9861 (concat cpltxt "::"
9862 (condition-case nil
9863 (org-make-org-heading-search-string txt)
9864 (error "")))
9865 desc (or (and (eq et 'keyword) eok ev)
9866 (nth 4 (ignore-errors (org-heading-components)))
9867 "NONE")))))
9868 (when (string-match "::\\'" cpltxt)
9869 (setq cpltxt (substring cpltxt 0 -2)))
9870 (setq link cpltxt))))
9872 ((buffer-file-name (buffer-base-buffer))
9873 ;; Just link to this file here.
9874 (setq cpltxt (concat "file:"
9875 (abbreviate-file-name
9876 (buffer-file-name (buffer-base-buffer)))))
9877 ;; Add a context string.
9878 (when (org-xor org-context-in-file-links arg)
9879 (setq txt (if (org-region-active-p)
9880 (buffer-substring (region-beginning) (region-end))
9881 (buffer-substring (point-at-bol) (point-at-eol))))
9882 ;; Only use search option if there is some text.
9883 (when (string-match "\\S-" txt)
9884 (setq cpltxt
9885 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9886 desc "NONE")))
9887 (setq link cpltxt))
9889 ((org-called-interactively-p 'interactive)
9890 (user-error "No method for storing a link from this buffer"))
9892 (t (setq link nil)))
9894 ;; We're done setting link and desc, clean up
9895 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9896 (setq link (or link cpltxt)
9897 desc (or desc cpltxt))
9898 (cond ((equal desc "NONE") (setq desc nil))
9899 ((and desc (string-match org-bracket-link-analytic-regexp desc))
9900 (let ((d0 (match-string 3 desc))
9901 (p0 (match-string 5 desc)))
9902 (setq desc
9903 (replace-regexp-in-string
9904 org-bracket-link-regexp
9905 (concat (or p0 d0)
9906 (if (equal (length (match-string 0 desc))
9907 (length desc)) "*" "")) desc)))))
9909 ;; Return the link
9910 (if (not (and (or (org-called-interactively-p 'any)
9911 executing-kbd-macro)
9912 link))
9913 (or agenda-link (and link (org-make-link-string link desc)))
9914 (push (list link desc) org-stored-links)
9915 (message "Stored: %s" (or desc link))
9916 (when custom-id
9917 (setq link (concat "file:" (abbreviate-file-name
9918 (buffer-file-name)) "::#" custom-id))
9919 (push (list link desc) org-stored-links))
9920 (car org-stored-links))))))
9922 (defun org-store-link-props (&rest plist)
9923 "Store link properties, extract names, addresses and dates."
9924 (let ((x (plist-get plist :from)))
9925 (when x
9926 (let ((adr (mail-extract-address-components x)))
9927 (setq plist (plist-put plist :fromname (car adr)))
9928 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9929 (let ((x (plist-get plist :to)))
9930 (when x
9931 (let ((adr (mail-extract-address-components x)))
9932 (setq plist (plist-put plist :toname (car adr)))
9933 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9934 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9935 (when x
9936 (setq plist (plist-put plist :date-timestamp
9937 (format-time-string
9938 (org-time-stamp-format t) x)))
9939 (setq plist (plist-put plist :date-timestamp-inactive
9940 (format-time-string
9941 (org-time-stamp-format t t) x)))))
9942 (let ((from (plist-get plist :from))
9943 (to (plist-get plist :to)))
9944 (when (and from to org-from-is-user-regexp)
9945 (setq plist
9946 (plist-put plist :fromto
9947 (if (string-match org-from-is-user-regexp from)
9948 (concat "to %t")
9949 (concat "from %f"))))))
9950 (setq org-store-link-plist plist))
9952 (defun org-add-link-props (&rest plist)
9953 "Add these properties to the link property list."
9954 (let (key value)
9955 (while plist
9956 (setq key (pop plist) value (pop plist))
9957 (setq org-store-link-plist
9958 (plist-put org-store-link-plist key value)))))
9960 (defun org-email-link-description (&optional fmt)
9961 "Return the description part of an email link.
9962 This takes information from `org-store-link-plist' and formats it
9963 according to FMT (default from `org-email-link-description-format')."
9964 (setq fmt (or fmt org-email-link-description-format))
9965 (let* ((p org-store-link-plist)
9966 (to (plist-get p :toaddress))
9967 (from (plist-get p :fromaddress))
9968 (table
9969 (list
9970 (cons "%c" (plist-get p :fromto))
9971 (cons "%F" (plist-get p :from))
9972 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9973 (cons "%T" (plist-get p :to))
9974 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9975 (cons "%s" (plist-get p :subject))
9976 (cons "%d" (plist-get p :date))
9977 (cons "%m" (plist-get p :message-id)))))
9978 (when (string-match "%c" fmt)
9979 ;; Check if the user wrote this message
9980 (if (and org-from-is-user-regexp from to
9981 (save-match-data (string-match org-from-is-user-regexp from)))
9982 (setq fmt (replace-match "to %t" t t fmt))
9983 (setq fmt (replace-match "from %f" t t fmt))))
9984 (org-replace-escapes fmt table)))
9986 (defun org-make-org-heading-search-string (&optional string)
9987 "Make search string for the current headline or STRING."
9988 (let ((s (or string
9989 (and (derived-mode-p 'org-mode)
9990 (save-excursion
9991 (org-back-to-heading t)
9992 (org-element-property :raw-value (org-element-at-point))))))
9993 (lines org-context-in-file-links))
9994 (or string (setq s (concat "*" s))) ; Add * for headlines
9995 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9996 (when (and string (integerp lines) (> lines 0))
9997 (let ((slines (org-split-string s "\n")))
9998 (when (< lines (length slines))
9999 (setq s (mapconcat
10000 'identity
10001 (reverse (nthcdr (- (length slines) lines)
10002 (reverse slines))) "\n")))))
10003 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10005 (defun org-make-link-string (link &optional description)
10006 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10007 (unless (org-string-nw-p link) (error "Empty link"))
10008 (let ((uri (cond ((string-match org-link-types-re link)
10009 (concat (match-string 1 link)
10010 (org-link-escape (substring link (match-end 1)))))
10011 ;; For readability, url-encode internal links only
10012 ;; when absolutely needed (i.e, when they contain
10013 ;; square brackets). File links however, are
10014 ;; encoded since, e.g., spaces are significant.
10015 ((or (file-name-absolute-p link)
10016 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10017 (org-link-escape link))
10018 (t link)))
10019 (description
10020 (and (org-string-nw-p description)
10021 ;; Remove brackets from description, as they are fatal.
10022 (replace-regexp-in-string
10023 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10024 (org-trim description)))))
10025 (format "[[%s]%s]"
10027 (if description (format "[%s]" description) ""))))
10029 (defconst org-link-escape-chars
10030 ;;%20 %5B %5D %25
10031 '(?\s ?\[ ?\] ?%)
10032 "List of characters that should be escaped in a link when stored to Org.
10033 This is the list that is used for internal purposes.")
10035 (defconst org-link-escape-chars-browser
10036 ;;%20 %22
10037 '(?\s ?\")
10038 "List of characters to be escaped before handing over to the browser.
10039 If you consider using this constant then you probably want to use
10040 the function `org-link-escape-browser' instead. See there why
10041 this constant is a candidate to be removed once Org drops support
10042 for Emacs 24.1 and 24.2.")
10044 (defun org-link-escape (text &optional table merge)
10045 "Return percent escaped representation of TEXT.
10046 TEXT is a string with the text to escape.
10047 Optional argument TABLE is a list with characters that should be
10048 escaped. When nil, `org-link-escape-chars' is used.
10049 If optional argument MERGE is set, merge TABLE into
10050 `org-link-escape-chars'."
10051 (let ((characters-to-encode
10052 (cond ((null table) org-link-escape-chars)
10053 (merge (append org-link-escape-chars table))
10054 (t table))))
10055 (mapconcat
10056 (lambda (c)
10057 (if (or (memq c characters-to-encode)
10058 (and org-url-hexify-p (or (< c 32) (> c 126))))
10059 (mapconcat (lambda (e) (format "%%%.2X" e))
10060 (or (encode-coding-char c 'utf-8)
10061 (error "Unable to percent escape character: %c" c))
10063 (char-to-string c)))
10064 text "")))
10066 (defun org-link-escape-browser (text)
10067 "Escape some characters before handing over to the browser.
10068 This function is a candidate to be removed together with the
10069 constant `org-link-escape-chars-browser' once Org drops support
10070 for Emacs 24.1 and 24.2. All calls to this function will have to
10071 be replaced with `url-encode-url' which is available since Emacs
10072 24.3.1."
10073 ;; Example with the Org link
10074 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10075 ;; to open the browser with +subject:"Release 8.2" filled into the
10076 ;; query field: In this case the variable TEXT contains the
10077 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10078 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10079 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10080 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10081 (if (fboundp 'url-encode-url)
10082 (url-encode-url text)
10083 (if (org-string-match-p
10084 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10085 text)
10086 (org-link-escape text org-link-escape-chars-browser)
10087 text)))
10089 (defun org-link-unescape (str)
10090 "Unhex hexified Unicode parts in string STR.
10091 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10092 reciprocal of `org-link-escape', which see."
10093 (if (org-string-nw-p str)
10094 (replace-regexp-in-string
10095 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10096 str))
10098 (defun org-link-unescape-compound (hex)
10099 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10100 Note: this function also decodes single byte encodings like
10101 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10102 (save-match-data
10103 (let* ((bytes (cdr (split-string hex "%")))
10104 (ret "")
10105 (eat 0)
10106 (sum 0))
10107 (while bytes
10108 (let* ((val (string-to-number (pop bytes) 16))
10109 (shift-xor
10110 (if (= 0 eat)
10111 (cond
10112 ((>= val 252) (cons 6 252))
10113 ((>= val 248) (cons 5 248))
10114 ((>= val 240) (cons 4 240))
10115 ((>= val 224) (cons 3 224))
10116 ((>= val 192) (cons 2 192))
10117 (t (cons 0 0)))
10118 (cons 6 128))))
10119 (when (>= val 192) (setq eat (car shift-xor)))
10120 (setq val (logxor val (cdr shift-xor)))
10121 (setq sum (+ (lsh sum (car shift-xor)) val))
10122 (when (> eat 0) (setq eat (- eat 1)))
10123 (cond
10124 ((= 0 eat) ;multi byte
10125 (setq ret (concat ret (org-char-to-string sum)))
10126 (setq sum 0))
10127 ((not bytes) ; single byte(s)
10128 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10129 ret)))
10131 (defun org-link-unescape-single-byte-sequence (hex)
10132 "Unhexify hex-encoded single byte character sequences."
10133 (mapconcat (lambda (byte)
10134 (char-to-string (string-to-number byte 16)))
10135 (cdr (split-string hex "%")) ""))
10137 (defun org-xor (a b)
10138 "Exclusive or."
10139 (if a (not b) b))
10141 (defun org-fixup-message-id-for-http (s)
10142 "Replace special characters in a message id, so it can be used in an http query."
10143 (when (string-match "%" s)
10144 (setq s (mapconcat (lambda (c)
10145 (if (eq c ?%)
10146 "%25"
10147 (char-to-string c)))
10148 s "")))
10149 (while (string-match "<" s)
10150 (setq s (replace-match "%3C" t t s)))
10151 (while (string-match ">" s)
10152 (setq s (replace-match "%3E" t t s)))
10153 (while (string-match "@" s)
10154 (setq s (replace-match "%40" t t s)))
10157 (defun org-link-prettify (link)
10158 "Return a human-readable representation of LINK.
10159 The car of LINK must be a raw link.
10160 The cdr of LINK must be either a link description or nil."
10161 (let ((desc (or (cadr link) "<no description>")))
10162 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10163 "<" (car link) ">")))
10165 ;;;###autoload
10166 (defun org-insert-link-global ()
10167 "Insert a link like Org-mode does.
10168 This command can be called in any mode to insert a link in Org-mode syntax."
10169 (interactive)
10170 (org-load-modules-maybe)
10171 (org-run-like-in-org-mode 'org-insert-link))
10173 (defun org-insert-all-links (arg &optional pre post)
10174 "Insert all links in `org-stored-links'.
10175 When a universal prefix, do not delete the links from `org-stored-links'.
10176 When `ARG' is a number, insert the last N link(s).
10177 `PRE' and `POST' are optional arguments to define a string to
10178 prepend or to append."
10179 (interactive "P")
10180 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10181 (links (copy-sequence org-stored-links))
10182 (pr (or pre "- "))
10183 (po (or post "\n"))
10184 (cnt 1) l)
10185 (if (null org-stored-links)
10186 (message "No link to insert")
10187 (while (and (or (listp arg) (>= arg cnt))
10188 (setq l (if (listp arg)
10189 (pop links)
10190 (pop org-stored-links))))
10191 (setq cnt (1+ cnt))
10192 (insert pr)
10193 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10194 (insert po)))))
10196 (defun org-insert-last-stored-link (arg)
10197 "Insert the last link stored in `org-stored-links'."
10198 (interactive "p")
10199 (org-insert-all-links arg "" "\n"))
10201 (defun org-link-fontify-links-to-this-file ()
10202 "Fontify links to the current file in `org-stored-links'."
10203 (let ((f (buffer-file-name)) a b)
10204 (setq a (mapcar (lambda(l)
10205 (let ((ll (car l)))
10206 (when (and (string-match "^file:\\(.+\\)::" ll)
10207 (equal f (expand-file-name (match-string 1 ll))))
10208 ll)))
10209 org-stored-links))
10210 (when (featurep 'org-id)
10211 (setq b (mapcar (lambda(l)
10212 (let ((ll (car l)))
10213 (when (and (string-match "^id:\\(.+\\)$" ll)
10214 (equal f (expand-file-name
10215 (or (org-id-find-id-file
10216 (match-string 1 ll)) ""))))
10217 ll)))
10218 org-stored-links)))
10219 (mapcar (lambda(l)
10220 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10221 (delq nil (append a b)))))
10223 (defvar org--links-history nil)
10224 (defun org-insert-link (&optional complete-file link-location default-description)
10225 "Insert a link. At the prompt, enter the link.
10227 Completion can be used to insert any of the link protocol prefixes like
10228 http or ftp in use.
10230 The history can be used to select a link previously stored with
10231 `org-store-link'. When the empty string is entered (i.e. if you just
10232 press RET at the prompt), the link defaults to the most recently
10233 stored link. As SPC triggers completion in the minibuffer, you need to
10234 use M-SPC or C-q SPC to force the insertion of a space character.
10236 You will also be prompted for a description, and if one is given, it will
10237 be displayed in the buffer instead of the link.
10239 If there is already a link at point, this command will allow you to edit link
10240 and description parts.
10242 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10243 be selected using completion. The path to the file will be relative to the
10244 current directory if the file is in the current directory or a subdirectory.
10245 Otherwise, the link will be the absolute path as completed in the minibuffer
10246 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10247 option `org-link-file-path-type'.
10249 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10250 the current directory or below.
10252 With three \\[universal-argument] prefixes, negate the meaning of
10253 `org-keep-stored-link-after-insertion'.
10255 If `org-make-link-description-function' is non-nil, this function will be
10256 called with the link target, and the result will be the default
10257 link description.
10259 If the LINK-LOCATION parameter is non-nil, this value will be
10260 used as the link location instead of reading one interactively.
10262 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10263 be used as the default description."
10264 (interactive "P")
10265 (let* ((wcf (current-window-configuration))
10266 (origbuf (current-buffer))
10267 (region (when (org-region-active-p)
10268 (buffer-substring (region-beginning) (region-end))))
10269 (remove (and region (list (region-beginning) (region-end))))
10270 (desc region)
10271 (link link-location)
10272 (abbrevs org-link-abbrev-alist-local)
10273 entry all-prefixes auto-desc)
10274 (cond
10275 (link-location) ; specified by arg, just use it.
10276 ((org-in-regexp org-bracket-link-regexp 1)
10277 ;; We do have a link at point, and we are going to edit it.
10278 (setq remove (list (match-beginning 0) (match-end 0)))
10279 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10280 (setq link (read-string "Link: "
10281 (org-link-unescape
10282 (org-match-string-no-properties 1)))))
10283 ((or (org-in-regexp org-angle-link-re)
10284 (org-in-regexp org-plain-link-re))
10285 ;; Convert to bracket link
10286 (setq remove (list (match-beginning 0) (match-end 0))
10287 link (read-string "Link: "
10288 (org-remove-angle-brackets (match-string 0)))))
10289 ((member complete-file '((4) (16)))
10290 ;; Completing read for file names.
10291 (setq link (org-file-complete-link complete-file)))
10293 ;; Read link, with completion for stored links.
10294 (org-link-fontify-links-to-this-file)
10295 (org-switch-to-buffer-other-window "*Org Links*")
10296 (with-current-buffer "*Org Links*"
10297 (erase-buffer)
10298 (insert "Insert a link.
10299 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10300 (when org-stored-links
10301 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10302 (insert (mapconcat 'org-link-prettify
10303 (reverse org-stored-links) "\n")))
10304 (goto-char (point-min)))
10305 (let ((cw (selected-window)))
10306 (select-window (get-buffer-window "*Org Links*" 'visible))
10307 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10308 (unless (pos-visible-in-window-p (point-max))
10309 (org-fit-window-to-buffer))
10310 (and (window-live-p cw) (select-window cw)))
10311 (setq all-prefixes (append (mapcar 'car abbrevs)
10312 (mapcar 'car org-link-abbrev-alist)
10313 org-link-types))
10314 (unwind-protect
10315 ;; Fake a link history, containing the stored links.
10316 (let ((org--links-history
10317 (append (mapcar #'car org-stored-links)
10318 org-insert-link-history)))
10319 (setq link
10320 (org-completing-read
10321 "Link: "
10322 (append
10323 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10324 (mapcar #'car org-stored-links))
10325 nil nil nil
10326 'org--links-history
10327 (caar org-stored-links)))
10328 (unless (org-string-nw-p link) (user-error "No link selected"))
10329 (dolist (l org-stored-links)
10330 (when (equal link (cadr l))
10331 (setq link (car l))
10332 (setq auto-desc t)))
10333 (when (or (member link all-prefixes)
10334 (and (equal ":" (substring link -1))
10335 (member (substring link 0 -1) all-prefixes)
10336 (setq link (substring link 0 -1))))
10337 (setq link (with-current-buffer origbuf
10338 (org-link-try-special-completion link)))))
10339 (set-window-configuration wcf)
10340 (kill-buffer "*Org Links*"))
10341 (setq entry (assoc link org-stored-links))
10342 (or entry (push link org-insert-link-history))
10343 (setq desc (or desc (nth 1 entry)))))
10345 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10346 (not org-keep-stored-link-after-insertion))
10347 (setq org-stored-links (delq (assoc link org-stored-links)
10348 org-stored-links)))
10350 (when (and (string-match org-plain-link-re link)
10351 (not (string-match org-ts-regexp link)))
10352 ;; URL-like link, normalize the use of angular brackets.
10353 (setq link (org-remove-angle-brackets link)))
10355 ;; Check if we are linking to the current file with a search
10356 ;; option If yes, simplify the link by using only the search
10357 ;; option.
10358 (when (and buffer-file-name
10359 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10360 (let* ((path (match-string 1 link))
10361 (case-fold-search nil)
10362 (search (match-string 2 link)))
10363 (save-match-data
10364 (when (equal (file-truename buffer-file-name) (file-truename path))
10365 ;; We are linking to this same file, with a search option
10366 (setq link search)))))
10368 ;; Check if we can/should use a relative path. If yes, simplify the link
10369 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10370 (let* ((type (match-string 1 link))
10371 (path (match-string 2 link))
10372 (origpath path)
10373 (case-fold-search nil))
10374 (cond
10375 ((or (eq org-link-file-path-type 'absolute)
10376 (equal complete-file '(16)))
10377 (setq path (abbreviate-file-name (expand-file-name path))))
10378 ((eq org-link-file-path-type 'noabbrev)
10379 (setq path (expand-file-name path)))
10380 ((eq org-link-file-path-type 'relative)
10381 (setq path (file-relative-name path)))
10383 (save-match-data
10384 (if (string-match (concat "^" (regexp-quote
10385 (expand-file-name
10386 (file-name-as-directory
10387 default-directory))))
10388 (expand-file-name path))
10389 ;; We are linking a file with relative path name.
10390 (setq path (substring (expand-file-name path)
10391 (match-end 0)))
10392 (setq path (abbreviate-file-name (expand-file-name path)))))))
10393 (setq link (concat type path))
10394 (when (equal desc origpath)
10395 (setq desc path))))
10397 (if org-make-link-description-function
10398 (setq desc
10399 (or (condition-case nil
10400 (funcall org-make-link-description-function link desc)
10401 (error (progn (message "Can't get link description from `%s'"
10402 (symbol-name org-make-link-description-function))
10403 (sit-for 2) nil)))
10404 (read-string "Description: " default-description)))
10405 (if default-description (setq desc default-description)
10406 (setq desc (or (and auto-desc desc)
10407 (read-string "Description: " desc)))))
10409 (unless (string-match "\\S-" desc) (setq desc nil))
10410 (when remove (apply 'delete-region remove))
10411 (insert (org-make-link-string link desc))
10412 ;; Redisplay so as the new link has proper invisible characters.
10413 (sit-for 0)))
10415 (defun org-link-try-special-completion (type)
10416 "If there is completion support for link type TYPE, offer it."
10417 (let ((fun (intern (concat "org-" type "-complete-link"))))
10418 (if (functionp fun)
10419 (funcall fun)
10420 (read-string "Link (no completion support): " (concat type ":")))))
10422 (defun org-file-complete-link (&optional arg)
10423 "Create a file link using completion."
10424 (let ((file (read-file-name "File: "))
10425 (pwd (file-name-as-directory (expand-file-name ".")))
10426 (pwd1 (file-name-as-directory (abbreviate-file-name
10427 (expand-file-name ".")))))
10428 (cond ((equal arg '(16))
10429 (concat "file:"
10430 (abbreviate-file-name (expand-file-name file))))
10431 ((string-match
10432 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10433 (concat "file:" (match-string 1 file)))
10434 ((string-match
10435 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10436 (expand-file-name file))
10437 (concat "file:"
10438 (match-string 1 (expand-file-name file))))
10439 (t (concat "file:" file)))))
10441 (defun org-completing-read (&rest args)
10442 "Completing-read with SPACE being a normal character."
10443 (let ((enable-recursive-minibuffers t)
10444 (minibuffer-local-completion-map
10445 (copy-keymap minibuffer-local-completion-map)))
10446 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10447 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10448 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10449 'org-time-stamp-inactive)
10450 (apply #'completing-read args)))
10452 (define-obsolete-function-alias
10453 'org-completing-read-no-i 'completing-read "Org 9.0")
10454 (define-obsolete-function-alias
10455 'org-icompleting-read 'completing-read "Org 9.0")
10456 (define-obsolete-function-alias
10457 'org-iread-file-name 'read-file-name "Org 9.0")
10459 ;;; Opening/following a link
10461 (defvar org-link-search-failed nil)
10463 (defvar org-open-link-functions nil
10464 "Hook for functions finding a plain text link.
10465 These functions must take a single argument, the link content.
10466 They will be called for links that look like [[link text][description]]
10467 when LINK TEXT does not have a protocol like \"http:\" and does not look
10468 like a filename (e.g. \"./blue.png\").
10470 These functions will be called *before* Org attempts to resolve the
10471 link by doing text searches in the current buffer - so if you want a
10472 link \"[[target]]\" to still find \"<<target>>\", your function should
10473 handle this as a special case.
10475 When the function does handle the link, it must return a non-nil value.
10476 If it decides that it is not responsible for this link, it must return
10477 nil to indicate that that Org-mode can continue with other options
10478 like exact and fuzzy text search.")
10480 (defun org-next-link (&optional search-backward)
10481 "Move forward to the next link.
10482 If the link is in hidden text, expose it."
10483 (interactive "P")
10484 (when (and org-link-search-failed (eq this-command last-command))
10485 (goto-char (point-min))
10486 (message "Link search wrapped back to beginning of buffer"))
10487 (setq org-link-search-failed nil)
10488 (let* ((pos (point))
10489 (ct (org-context))
10490 (a (assoc :link ct))
10491 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10492 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10493 ((looking-at org-any-link-re)
10494 ;; Don't stay stuck at link without an org-link face
10495 (forward-char (if search-backward -1 1))))
10496 (if (funcall srch-fun org-any-link-re nil t)
10497 (progn
10498 (goto-char (match-beginning 0))
10499 (when (outline-invisible-p) (org-show-context)))
10500 (goto-char pos)
10501 (setq org-link-search-failed t)
10502 (message "No further link found"))))
10504 (defun org-previous-link ()
10505 "Move backward to the previous link.
10506 If the link is in hidden text, expose it."
10507 (interactive)
10508 (funcall 'org-next-link t))
10510 (defun org-translate-link (s)
10511 "Translate a link string if a translation function has been defined."
10512 (with-temp-buffer
10513 (insert (org-trim s))
10514 (org-trim (org-element-interpret-data (org-element-context)))))
10516 (defun org-translate-link-from-planner (type path)
10517 "Translate a link from Emacs Planner syntax so that Org can follow it.
10518 This is still an experimental function, your mileage may vary."
10519 (cond
10520 ((member type '("http" "https" "news" "ftp"))
10521 ;; standard Internet links are the same.
10522 nil)
10523 ((and (equal type "irc") (string-match "^//" path))
10524 ;; Planner has two / at the beginning of an irc link, we have 1.
10525 ;; We should have zero, actually....
10526 (setq path (substring path 1)))
10527 ((and (equal type "lisp") (string-match "^/" path))
10528 ;; Planner has a slash, we do not.
10529 (setq type "elisp" path (substring path 1)))
10530 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10531 ;; A typical message link. Planner has the id after the final slash,
10532 ;; we separate it with a hash mark
10533 (setq path (concat (match-string 1 path) "#"
10534 (org-remove-angle-brackets (match-string 2 path))))))
10535 (cons type path))
10537 (defun org-find-file-at-mouse (ev)
10538 "Open file link or URL at mouse."
10539 (interactive "e")
10540 (mouse-set-point ev)
10541 (org-open-at-point 'in-emacs))
10543 (defun org-open-at-mouse (ev)
10544 "Open file link or URL at mouse.
10545 See the docstring of `org-open-file' for details."
10546 (interactive "e")
10547 (mouse-set-point ev)
10548 (when (eq major-mode 'org-agenda-mode)
10549 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10550 (org-open-at-point))
10552 (defvar org-window-config-before-follow-link nil
10553 "The window configuration before following a link.
10554 This is saved in case the need arises to restore it.")
10556 ;;;###autoload
10557 (defun org-open-at-point-global ()
10558 "Follow a link like Org-mode does.
10559 This command can be called in any mode to follow a link that has
10560 Org-mode syntax."
10561 (interactive)
10562 (org-run-like-in-org-mode 'org-open-at-point))
10564 ;;;###autoload
10565 (defun org-open-link-from-string (s &optional arg reference-buffer)
10566 "Open a link in the string S, as if it was in Org-mode."
10567 (interactive "sLink: \nP")
10568 (let ((reference-buffer (or reference-buffer (current-buffer))))
10569 (with-temp-buffer
10570 (let ((org-inhibit-startup (not reference-buffer)))
10571 (org-mode)
10572 (insert s)
10573 (goto-char (point-min))
10574 (when reference-buffer
10575 (setq org-link-abbrev-alist-local
10576 (with-current-buffer reference-buffer
10577 org-link-abbrev-alist-local)))
10578 (org-open-at-point arg reference-buffer)))))
10580 (defvar org-open-at-point-functions nil
10581 "Hook that is run when following a link at point.
10583 Functions in this hook must return t if they identify and follow
10584 a link at point. If they don't find anything interesting at point,
10585 they must return nil.")
10587 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10588 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10589 (defun org-open-at-point (&optional arg reference-buffer)
10590 "Open link, timestamp, footnote or tags at point.
10592 When point is on a link, follow it. Normally, files will be
10593 opened by an appropriate application. If the optional prefix
10594 argument ARG is non-nil, Emacs will visit the file. With
10595 a double prefix argument, try to open outside of Emacs, in the
10596 application the system uses for this file type.
10598 When point is on a timestamp, open the agenda at the day
10599 specified.
10601 When point is a footnote definition, move to the first reference
10602 found. If it is on a reference, move to the associated
10603 definition.
10605 When point is on a headline, display a list of every link in the
10606 entry, so it is possible to pick one, or all, of them. If point
10607 is on a tag, call `org-tags-view' instead.
10609 When optional argument REFERENCE-BUFFER is non-nil, it should
10610 specify a buffer from where the link search should happen. This
10611 is used internally by `org-open-link-from-string'.
10613 On top of syntactically correct links, this function will open
10614 the link at point in comments or comment blocks and the first
10615 link in a property drawer line."
10616 (interactive "P")
10617 ;; On a code block, open block's results.
10618 (unless (call-interactively 'org-babel-open-src-block-result)
10619 (org-load-modules-maybe)
10620 (setq org-window-config-before-follow-link (current-window-configuration))
10621 (org-remove-occur-highlights nil nil t)
10622 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10623 (let* ((context
10624 ;; Only consider supported types, even if they are not
10625 ;; the closest one.
10626 (org-element-lineage
10627 (org-element-context)
10628 '(clock comment comment-block footnote-definition
10629 footnote-reference headline inlinetask keyword link
10630 node-property timestamp)
10632 (type (org-element-type context))
10633 (value (org-element-property :value context)))
10634 (cond
10635 ((not context) (user-error "No link found"))
10636 ;; Exception: open timestamps and links in properties
10637 ;; drawers, keywords and comments.
10638 ((memq type '(comment comment-block keyword node-property))
10639 (cond ((org-in-regexp org-any-link-re)
10640 (org-open-link-from-string (match-string-no-properties 0)))
10641 ((or (org-in-regexp org-ts-regexp-both nil t)
10642 (org-in-regexp org-tsr-regexp-both nil t))
10643 (org-follow-timestamp-link))
10644 (t (user-error "No link found"))))
10645 ;; On a headline or an inlinetask, but not on a timestamp,
10646 ;; a link, a footnote reference or on tags.
10647 ((and (memq type '(headline inlinetask))
10648 ;; Not on tags.
10649 (progn (save-excursion (beginning-of-line)
10650 (looking-at org-complex-heading-regexp))
10651 (or (not (match-beginning 5))
10652 (< (point) (match-beginning 5)))))
10653 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10654 (links (car data))
10655 (links-end (cdr data)))
10656 (if links
10657 (dolist (link (if (stringp links) (list links) links))
10658 (search-forward link nil links-end)
10659 (goto-char (match-beginning 0))
10660 (org-open-at-point))
10661 (require 'org-attach)
10662 (org-attach-reveal 'if-exists))))
10663 ;; On a clock line, make sure point is on the timestamp
10664 ;; before opening it.
10665 ((and (eq type 'clock)
10666 value
10667 (>= (point) (org-element-property :begin value))
10668 (<= (point) (org-element-property :end value)))
10669 (org-follow-timestamp-link))
10670 ;; Do nothing on white spaces after an object.
10671 ((>= (point)
10672 (save-excursion
10673 (goto-char (org-element-property :end context))
10674 (skip-chars-backward " \t")
10675 (point)))
10676 (user-error "No link found"))
10677 ((eq type 'timestamp) (org-follow-timestamp-link))
10678 ;; On tags within a headline or an inlinetask.
10679 ((and (memq type '(headline inlinetask))
10680 (progn (save-excursion (beginning-of-line)
10681 (looking-at org-complex-heading-regexp))
10682 (and (match-beginning 5)
10683 (>= (point) (match-beginning 5)))))
10684 (org-tags-view arg (substring (match-string 5) 0 -1)))
10685 ((eq type 'link)
10686 ;; When link is located within the description of another
10687 ;; link (e.g., an inline image), always open the parent
10688 ;; link.
10689 (let*((link (let ((up (org-element-property :parent context)))
10690 (if (eq (org-element-type up) 'link) up context)))
10691 (type (org-element-property :type link))
10692 (path (org-link-unescape (org-element-property :path link))))
10693 ;; Switch back to REFERENCE-BUFFER needed when called in
10694 ;; a temporary buffer through `org-open-link-from-string'.
10695 (with-current-buffer (or reference-buffer (current-buffer))
10696 (cond
10697 ((equal type "file")
10698 (if (string-match "[*?{]" (file-name-nondirectory path))
10699 (dired path)
10700 ;; Look into `org-link-protocols' in order to find
10701 ;; a DEDICATED-FUNCTION to open file. The function
10702 ;; will be applied on raw link instead of parsed
10703 ;; link due to the limitation in `org-add-link-type'
10704 ;; ("open" function called with a single argument).
10705 ;; If no such function is found, fallback to
10706 ;; `org-open-file'.
10708 ;; Note : "file+emacs" and "file+sys" types are
10709 ;; hard-coded in order to escape the previous
10710 ;; limitation.
10711 (let* ((option (org-element-property :search-option link))
10712 (app (org-element-property :application link))
10713 (dedicated-function
10714 (nth 1 (assoc app org-link-protocols))))
10715 (if dedicated-function
10716 (funcall dedicated-function
10717 (concat path
10718 (and option (concat "::" option))))
10719 (apply #'org-open-file
10720 path
10721 (cond (arg)
10722 ((equal app "emacs") 'emacs)
10723 ((equal app "sys") 'system))
10724 (cond ((not option) nil)
10725 ((org-string-match-p "\\`[0-9]+\\'" option)
10726 (list (string-to-number option)))
10727 (t (list nil
10728 (org-link-unescape option)))))))))
10729 ((assoc type org-link-protocols)
10730 (funcall (nth 1 (assoc type org-link-protocols)) path))
10731 ((equal type "help")
10732 (let ((f-or-v (intern path)))
10733 (cond ((fboundp f-or-v) (describe-function f-or-v))
10734 ((boundp f-or-v) (describe-variable f-or-v))
10735 (t (error "Not a known function or variable")))))
10736 ((member type '("http" "https" "ftp" "mailto" "news"))
10737 (browse-url (org-link-escape-browser (concat type ":" path))))
10738 ((equal type "doi")
10739 (browse-url
10740 (org-link-escape-browser (concat org-doi-server-url path))))
10741 ((equal type "message") (browse-url (concat type ":" path)))
10742 ((equal type "shell")
10743 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10744 (cmd path))
10745 (if (or (and (org-string-nw-p
10746 org-confirm-shell-link-not-regexp)
10747 (string-match
10748 org-confirm-shell-link-not-regexp cmd))
10749 (not org-confirm-shell-link-function)
10750 (funcall org-confirm-shell-link-function
10751 (format "Execute \"%s\" in shell? "
10752 (org-add-props cmd nil
10753 'face 'org-warning))))
10754 (progn
10755 (message "Executing %s" cmd)
10756 (shell-command cmd buf)
10757 (when (featurep 'midnight)
10758 (setq clean-buffer-list-kill-buffer-names
10759 (cons (buffer-name buf)
10760 clean-buffer-list-kill-buffer-names))))
10761 (user-error "Abort"))))
10762 ((equal type "elisp")
10763 (let ((cmd path))
10764 (if (or (and (org-string-nw-p
10765 org-confirm-elisp-link-not-regexp)
10766 (org-string-match-p
10767 org-confirm-elisp-link-not-regexp cmd))
10768 (not org-confirm-elisp-link-function)
10769 (funcall org-confirm-elisp-link-function
10770 (format "Execute \"%s\" as elisp? "
10771 (org-add-props cmd nil
10772 'face 'org-warning))))
10773 (message "%s => %s" cmd
10774 (if (eq (string-to-char cmd) ?\()
10775 (eval (read cmd))
10776 (call-interactively (read cmd))))
10777 (user-error "Abort"))))
10778 ((equal type "id")
10779 (require 'org-id)
10780 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10781 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10782 (unless (run-hook-with-args-until-success
10783 'org-open-link-functions path)
10784 (if (not arg) (org-mark-ring-push)
10785 (switch-to-buffer-other-window
10786 (org-get-buffer-for-internal-link (current-buffer))))
10787 (let ((destination
10788 (org-with-wide-buffer
10789 (if (equal type "radio")
10790 (org-search-radio-target
10791 (org-element-property :path link))
10792 (org-link-search
10793 (if (member type '("custom-id" "coderef"))
10794 (org-element-property :raw-link link)
10795 path)
10796 ;; Prevent fuzzy links from matching
10797 ;; themselves.
10798 (and (equal type "fuzzy")
10799 (+ 2 (org-element-property :begin link)))))
10800 (point))))
10801 (unless (and (<= (point-min) destination)
10802 (>= (point-max) destination))
10803 (widen))
10804 (goto-char destination))))
10805 (t (browse-url-at-point))))))
10806 ;; On a footnote reference or at a footnote definition's label.
10807 ((or (eq type 'footnote-reference)
10808 (and (eq type 'footnote-definition)
10809 (save-excursion
10810 ;; Do not validate action when point is on the
10811 ;; spaces right after the footnote label, in
10812 ;; order to be on par with behaviour on links.
10813 (skip-chars-forward " \t")
10814 (let ((begin
10815 (org-element-property :contents-begin context)))
10816 (if begin (< (point) begin)
10817 (= (org-element-property :post-affiliated context)
10818 (line-beginning-position)))))))
10819 (org-footnote-action))
10820 (t (user-error "No link found")))))
10821 (run-hook-with-args 'org-follow-link-hook)))
10823 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10824 "Offer links in the current entry and return the selected link.
10825 If there is only one link, return it.
10826 If NTH is an integer, return the NTH link found.
10827 If ZERO is a string, check also this string for a link, and if
10828 there is one, return it."
10829 (with-current-buffer buffer
10830 (save-excursion
10831 (save-restriction
10832 (widen)
10833 (goto-char marker)
10834 (let ((cnt ?0)
10835 have-zero end links link c)
10836 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10837 (push (match-string 0 zero) links)
10838 (setq cnt (1- cnt) have-zero t))
10839 (save-excursion
10840 (org-back-to-heading t)
10841 (setq end (save-excursion (outline-next-heading) (point)))
10842 (while (re-search-forward org-any-link-re end t)
10843 (push (match-string 0) links))
10844 (setq links (org-uniquify (reverse links))))
10845 (cond
10846 ((null links)
10847 (message "No links"))
10848 ((equal (length links) 1)
10849 (setq link (car links)))
10850 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10851 (setq link (nth (if have-zero nth (1- nth)) links)))
10852 (t ; we have to select a link
10853 (save-excursion
10854 (save-window-excursion
10855 (delete-other-windows)
10856 (with-output-to-temp-buffer "*Select Link*"
10857 (dolist (l links)
10858 (cond
10859 ((not (string-match org-bracket-link-regexp l))
10860 (princ (format "[%c] %s\n" (cl-incf cnt)
10861 (org-remove-angle-brackets l))))
10862 ((match-end 3)
10863 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10864 (match-string 3 l) (match-string 1 l))))
10865 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10866 (match-string 1 l)))))))
10867 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10868 (message "Select link to open, RET to open all:")
10869 (setq c (read-char-exclusive))
10870 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10871 (when (equal c ?q) (user-error "Abort"))
10872 (if (equal c ?\C-m)
10873 (setq link links)
10874 (setq nth (- c ?0))
10875 (when have-zero (setq nth (1+ nth)))
10876 (unless (and (integerp nth) (>= (length links) nth))
10877 (user-error "Invalid link selection"))
10878 (setq link (nth (1- nth) links)))))
10879 (cons link end))))))
10881 ;; TODO: These functions are deprecated since `org-open-at-point'
10882 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10883 (defun org-open-file-with-system (path)
10884 "Open file at PATH using the system way of opening it."
10885 (org-open-file path 'system))
10886 (defun org-open-file-with-emacs (path)
10887 "Open file at PATH in Emacs."
10888 (org-open-file path 'emacs))
10891 ;;; File search
10893 (defvar org-create-file-search-functions nil
10894 "List of functions to construct the right search string for a file link.
10895 These functions are called in turn with point at the location to
10896 which the link should point.
10898 A function in the hook should first test if it would like to
10899 handle this file type, for example by checking the `major-mode'
10900 or the file extension. If it decides not to handle this file, it
10901 should just return nil to give other functions a chance. If it
10902 does handle the file, it must return the search string to be used
10903 when following the link. The search string will be part of the
10904 file link, given after a double colon, and `org-open-at-point'
10905 will automatically search for it. If special measures must be
10906 taken to make the search successful, another function should be
10907 added to the companion hook `org-execute-file-search-functions',
10908 which see.
10910 A function in this hook may also use `setq' to set the variable
10911 `description' to provide a suggestion for the descriptive text to
10912 be used for this link when it gets inserted into an Org-mode
10913 buffer with \\[org-insert-link].")
10915 (defvar org-execute-file-search-functions nil
10916 "List of functions to execute a file search triggered by a link.
10918 Functions added to this hook must accept a single argument, the
10919 search string that was part of the file link, the part after the
10920 double colon. The function must first check if it would like to
10921 handle this search, for example by checking the `major-mode' or
10922 the file extension. If it decides not to handle this search, it
10923 should just return nil to give other functions a chance. If it
10924 does handle the search, it must return a non-nil value to keep
10925 other functions from trying.
10927 Each function can access the current prefix argument through the
10928 variable `current-prefix-arg'. Note that a single prefix is used
10929 to force opening a link in Emacs, so it may be good to only use a
10930 numeric or double prefix to guide the search function.
10932 In case this is needed, a function in this hook can also restore
10933 the window configuration before `org-open-at-point' was called using:
10935 \(set-window-configuration org-window-config-before-follow-link)")
10937 (defun org-search-radio-target (target)
10938 "Search a radio target matching TARGET in current buffer.
10939 White spaces are not significant."
10940 (let ((re (format "<<<%s>>>"
10941 (mapconcat #'regexp-quote
10942 (org-split-string target "[ \t\n]+")
10943 "[ \t]+\\(?:\n[ \t]*\\)?")))
10944 (origin (point)))
10945 (goto-char (point-min))
10946 (catch :radio-match
10947 (while (re-search-forward re nil t)
10948 (backward-char)
10949 (let ((object (org-element-context)))
10950 (when (eq (org-element-type object) 'radio-target)
10951 (goto-char (org-element-property :begin object))
10952 (org-show-context 'link-search)
10953 (throw :radio-match nil))))
10954 (goto-char origin)
10955 (user-error "No match for radio target: %s" target))))
10957 (defun org-link-search (s &optional avoid-pos stealth)
10958 "Search for a search string S.
10960 If S starts with \"#\", it triggers a custom ID search.
10962 If S is enclosed within parenthesis, it initiates a coderef
10963 search.
10965 If S is surrounded by forward slashes, it is interpreted as
10966 a regular expression. In Org mode files, this will create an
10967 `org-occur' sparse tree. In ordinary files, `occur' will be used
10968 to list matches. If the current buffer is in `dired-mode', grep
10969 will be used to search in all files.
10971 When AVOID-POS is given, ignore matches near that position.
10973 When optional argument STEALTH is non-nil, do not modify
10974 visibility around point, thus ignoring `org-show-context-detail'
10975 variable.
10977 Search is case-insensitive and ignores white spaces. Return type
10978 of matched result, with is either `dedicated' or `fuzzy'."
10979 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10980 (let* ((case-fold-search t)
10981 (origin (point))
10982 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10983 (words (org-split-string s "[ \t\n]+"))
10984 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10985 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10986 type)
10987 (cond
10988 ;; Check if there are any special search functions.
10989 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10990 ((eq (string-to-char s) ?#)
10991 ;; Look for a custom ID S if S starts with "#".
10992 (let* ((id (substring normalized 1))
10993 (match (org-find-property "CUSTOM_ID" id)))
10994 (if match (progn (goto-char match) (setf type 'dedicated))
10995 (error "No match for custom ID: %s" id))))
10996 ((string-match "\\`(\\(.*\\))\\'" normalized)
10997 ;; Look for coderef targets if S is enclosed within parenthesis.
10998 (let ((coderef (match-string-no-properties 1 normalized))
10999 (re (substring s-single-re 1 -1)))
11000 (goto-char (point-min))
11001 (catch :coderef-match
11002 (while (re-search-forward re nil t)
11003 (let ((element (org-element-at-point)))
11004 (when (and (memq (org-element-type element)
11005 '(example-block src-block))
11006 ;; Build proper regexp according to current
11007 ;; block's label format.
11008 (let ((label-fmt
11009 (regexp-quote
11010 (or (org-element-property :label-fmt element)
11011 org-coderef-label-format))))
11012 (save-excursion
11013 (beginning-of-line)
11014 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11015 (format label-fmt coderef))))))
11016 (setq type 'dedicated)
11017 (goto-char (match-beginning 1))
11018 (throw :coderef-match nil))))
11019 (goto-char origin)
11020 (error "No match for coderef: %s" coderef))))
11021 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11022 ;; Look for a regular expression.
11023 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11024 (match-string 1 s)))
11025 ;; Fuzzy links.
11027 (let ((starred (eq (string-to-char normalized) ?*)))
11028 (cond
11029 ;; Look for targets, only if not in a headline search.
11030 ((and (not starred)
11031 (let ((target (format "<<%s>>" s-multi-re)))
11032 (catch :target-match
11033 (goto-char (point-min))
11034 (while (re-search-forward target nil t)
11035 (backward-char)
11036 (let ((context (org-element-context)))
11037 (when (eq (org-element-type context) 'target)
11038 (setq type 'dedicated)
11039 (goto-char (org-element-property :begin context))
11040 (throw :target-match t))))
11041 nil))))
11042 ;; Look for elements named after S, only if not in a headline
11043 ;; search.
11044 ((and (not starred)
11045 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11046 (catch :name-match
11047 (goto-char (point-min))
11048 (while (re-search-forward name nil t)
11049 (let ((element (org-element-at-point)))
11050 (when (equal (org-split-string
11051 (org-element-property :name element)
11052 "[ \t]+")
11053 words)
11054 (setq type 'dedicated)
11055 (beginning-of-line)
11056 (throw :name-match t))))
11057 nil))))
11058 ;; Regular text search. Prefer headlines in Org mode
11059 ;; buffers.
11060 ((and (derived-mode-p 'org-mode)
11061 (let* ((wspace "[ \t]")
11062 (wspaceopt (concat wspace "*"))
11063 (cookie (concat "\\(?:"
11064 wspaceopt
11065 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11066 wspaceopt
11067 "\\)"))
11068 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11069 (re (concat
11070 org-outline-regexp-bol
11071 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11072 "\\(?:\\[#.\\][ \t]+\\)?"
11073 "\\(?:" org-comment-string "[ \t]+\\)?"
11074 sep "?"
11075 (let ((title (mapconcat #'regexp-quote
11076 words
11077 sep)))
11078 (if starred (substring title 1) title))
11079 sep "?"
11080 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11081 "[ \t]*$")))
11082 (goto-char (point-min))
11083 (re-search-forward re nil t)))
11084 (goto-char (match-beginning 0))
11085 (setq type 'dedicated))
11086 ;; Offer to create non-existent headline depending on
11087 ;; `org-link-search-must-match-exact-headline'.
11088 ((and (derived-mode-p 'org-mode)
11089 (not org-link-search-inhibit-query)
11090 (eq org-link-search-must-match-exact-headline 'query-to-create)
11091 (yes-or-no-p "No match - create this as a new heading? "))
11092 (goto-char (point-max))
11093 (unless (bolp) (newline))
11094 (org-insert-heading nil t t)
11095 (insert s "\n")
11096 (beginning-of-line 0))
11097 ;; Only headlines are looked after. No need to process
11098 ;; further: throw an error.
11099 ((and (derived-mode-p 'org-mode)
11100 (or starred org-link-search-must-match-exact-headline))
11101 (goto-char origin)
11102 (error "No match for fuzzy expression: %s" normalized))
11103 ;; Regular text search.
11104 ((catch :fuzzy-match
11105 (goto-char (point-min))
11106 (while (re-search-forward s-multi-re nil t)
11107 ;; Skip match if it contains AVOID-POS or it is included
11108 ;; in a link with a description but outside the
11109 ;; description.
11110 (unless (or (and avoid-pos
11111 (<= (match-beginning 0) avoid-pos)
11112 (> (match-end 0) avoid-pos))
11113 (and (save-match-data
11114 (org-in-regexp org-bracket-link-regexp))
11115 (match-beginning 3)
11116 (or (> (match-beginning 3) (point))
11117 (<= (match-end 3) (point)))
11118 (org-element-lineage
11119 (save-match-data (org-element-context))
11120 '(link) t)))
11121 (goto-char (match-beginning 0))
11122 (setq type 'fuzzy)
11123 (throw :fuzzy-match t)))
11124 nil))
11125 ;; All failed. Throw an error.
11126 (t (goto-char origin)
11127 (error "No match for fuzzy expression: %s" normalized))))))
11128 ;; Disclose surroundings of match, if appropriate.
11129 (when (and (derived-mode-p 'org-mode) (not stealth))
11130 (org-show-context 'link-search))
11131 type))
11133 (defun org-get-buffer-for-internal-link (buffer)
11134 "Return a buffer to be used for displaying the link target of internal links."
11135 (cond
11136 ((not org-display-internal-link-with-indirect-buffer)
11137 buffer)
11138 ((string-match "(Clone)$" (buffer-name buffer))
11139 (message "Buffer is already a clone, not making another one")
11140 ;; we also do not modify visibility in this case
11141 buffer)
11142 (t ; make a new indirect buffer for displaying the link
11143 (let* ((bn (buffer-name buffer))
11144 (ibn (concat bn "(Clone)"))
11145 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11146 (with-current-buffer ib (org-overview))
11147 ib))))
11149 (defun org-do-occur (regexp &optional cleanup)
11150 "Call the Emacs command `occur'.
11151 If CLEANUP is non-nil, remove the printout of the regular expression
11152 in the *Occur* buffer. This is useful if the regex is long and not useful
11153 to read."
11154 (occur regexp)
11155 (when cleanup
11156 (let ((cwin (selected-window)) win beg end)
11157 (when (setq win (get-buffer-window "*Occur*"))
11158 (select-window win))
11159 (goto-char (point-min))
11160 (when (re-search-forward "match[a-z]+" nil t)
11161 (setq beg (match-end 0))
11162 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11163 (setq end (1- (match-beginning 0)))))
11164 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11165 (goto-char (point-min))
11166 (select-window cwin))))
11168 ;;; The mark ring for links jumps
11170 (defvar org-mark-ring nil
11171 "Mark ring for positions before jumps in Org-mode.")
11172 (defvar org-mark-ring-last-goto nil
11173 "Last position in the mark ring used to go back.")
11174 ;; Fill and close the ring
11175 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11176 (dotimes (_ org-mark-ring-length)
11177 (push (make-marker) org-mark-ring))
11178 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11179 org-mark-ring)
11181 (defun org-mark-ring-push (&optional pos buffer)
11182 "Put the current position or POS into the mark ring and rotate it."
11183 (interactive)
11184 (setq pos (or pos (point)))
11185 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11186 (move-marker (car org-mark-ring)
11187 (or pos (point))
11188 (or buffer (current-buffer)))
11189 (message "%s"
11190 (substitute-command-keys
11191 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11193 (defun org-mark-ring-goto (&optional n)
11194 "Jump to the previous position in the mark ring.
11195 With prefix arg N, jump back that many stored positions. When
11196 called several times in succession, walk through the entire ring.
11197 Org-mode commands jumping to a different position in the current file,
11198 or to another Org-mode file, automatically push the old position
11199 onto the ring."
11200 (interactive "p")
11201 (let (p m)
11202 (if (eq last-command this-command)
11203 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11204 (setq p org-mark-ring))
11205 (setq org-mark-ring-last-goto p)
11206 (setq m (car p))
11207 (org-pop-to-buffer-same-window (marker-buffer m))
11208 (goto-char m)
11209 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11211 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11212 ;;; Emacs 24.4+
11213 (defun org-remove-angle-brackets (s)
11214 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11215 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11217 (defun org-add-angle-brackets (s)
11218 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11219 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11221 (defun org-remove-double-quotes (s)
11222 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11223 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11226 ;;; Following specific links
11228 (defvar org-agenda-buffer-tmp-name)
11229 (defvar org-agenda-start-on-weekday)
11230 (defun org-follow-timestamp-link ()
11231 "Open an agenda view for the time-stamp date/range at point."
11232 (cond
11233 ((org-at-date-range-p t)
11234 (let ((org-agenda-start-on-weekday)
11235 (t1 (match-string 1))
11236 (t2 (match-string 2)) tt1 tt2)
11237 (setq tt1 (time-to-days (org-time-string-to-time t1))
11238 tt2 (time-to-days (org-time-string-to-time t2)))
11239 (let ((org-agenda-buffer-tmp-name
11240 (format "*Org Agenda(a:%s)"
11241 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11242 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11243 ((org-at-timestamp-p t)
11244 (let ((org-agenda-buffer-tmp-name
11245 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11246 (org-agenda-list nil (time-to-days (org-time-string-to-time
11247 (substring (match-string 1) 0 10)))
11248 1)))
11249 (t (error "This should not happen"))))
11252 ;;; Following file links
11253 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11254 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11255 (declare-function mailcap-mime-info
11256 "mailcap" (string &optional request no-decode))
11257 (defvar org-wait nil)
11258 (defun org-open-file (path &optional in-emacs line search)
11259 "Open the file at PATH.
11260 First, this expands any special file name abbreviations. Then the
11261 configuration variable `org-file-apps' is checked if it contains an
11262 entry for this file type, and if yes, the corresponding command is launched.
11264 If no application is found, Emacs simply visits the file.
11266 With optional prefix argument IN-EMACS, Emacs will visit the file.
11267 With a double \\[universal-argument] \\[universal-argument] \
11268 prefix arg, Org tries to avoid opening in Emacs
11269 and to use an external application to visit the file.
11271 Optional LINE specifies a line to go to, optional SEARCH a string
11272 to search for. If LINE or SEARCH is given, the file will be
11273 opened in Emacs, unless an entry from org-file-apps that makes
11274 use of groups in a regexp matches.
11276 If you want to change the way frames are used when following a
11277 link, please customize `org-link-frame-setup'.
11279 If the file does not exist, an error is thrown."
11280 (let* ((file (if (equal path "")
11281 buffer-file-name
11282 (substitute-in-file-name (expand-file-name path))))
11283 (file-apps (append org-file-apps (org-default-apps)))
11284 (apps (cl-remove-if
11285 'org-file-apps-entry-match-against-dlink-p file-apps))
11286 (apps-dlink (cl-remove-if-not
11287 'org-file-apps-entry-match-against-dlink-p file-apps))
11288 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11289 (dirp (unless remp (file-directory-p file)))
11290 (file (if (and dirp org-open-directory-means-index-dot-org)
11291 (concat (file-name-as-directory file) "index.org")
11292 file))
11293 (a-m-a-p (assq 'auto-mode apps))
11294 (dfile (downcase file))
11295 ;; Reconstruct the original link from the PATH, LINE and
11296 ;; SEARCH args.
11297 (link (cond (line (concat file "::" (number-to-string line)))
11298 (search (concat file "::" search))
11299 (t file)))
11300 (dlink (downcase link))
11301 (old-buffer (current-buffer))
11302 (old-pos (point))
11303 (old-mode major-mode)
11304 (ext
11305 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11306 (match-string 1 dfile)))
11307 cmd link-match-data)
11308 (cond
11309 ((member in-emacs '((16) system))
11310 (setq cmd (cdr (assq 'system apps))))
11311 (in-emacs (setq cmd 'emacs))
11313 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11314 (and dirp (cdr (assq 'directory apps)))
11315 ;; First, try matching against apps-dlink if we
11316 ;; get a match here, store the match data for
11317 ;; later.
11318 (let ((match (assoc-default dlink apps-dlink
11319 'string-match)))
11320 (if match
11321 (progn (setq link-match-data (match-data))
11322 match)
11323 (progn (setq in-emacs (or in-emacs line search))
11324 nil))) ; if we have no match in apps-dlink,
11325 ; always open the file in emacs if line or search
11326 ; is given (for backwards compatibility)
11327 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11328 'string-match)
11329 (cdr (assoc ext apps))
11330 (cdr (assq t apps))))))
11331 (when (eq cmd 'system)
11332 (setq cmd (cdr (assoc 'system apps))))
11333 (when (eq cmd 'default)
11334 (setq cmd (cdr (assoc t apps))))
11335 (when (eq cmd 'mailcap)
11336 (require 'mailcap)
11337 (mailcap-parse-mailcaps)
11338 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11339 (command (mailcap-mime-info mime-type)))
11340 (if (stringp command)
11341 (setq cmd command)
11342 (setq cmd 'emacs))))
11343 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11344 (not (file-exists-p file))
11345 (not org-open-non-existing-files))
11346 (user-error "No such file: %s" file))
11347 (cond
11348 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11349 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11350 (while (string-match "['\"]%s['\"]" cmd)
11351 (setq cmd (replace-match "%s" t t cmd)))
11352 (while (string-match "%s" cmd)
11353 (setq cmd (replace-match
11354 (save-match-data
11355 (shell-quote-argument
11356 (convert-standard-filename file)))
11357 t t cmd)))
11359 ;; Replace "%1", "%2" etc. in command with group matches from regex
11360 (save-match-data
11361 (let ((match-index 1)
11362 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11363 (set-match-data link-match-data)
11364 (while (<= match-index number-of-groups)
11365 (let ((regex (concat "%" (number-to-string match-index)))
11366 (replace-with (match-string match-index dlink)))
11367 (while (string-match regex cmd)
11368 (setq cmd (replace-match replace-with t t cmd))))
11369 (setq match-index (+ match-index 1)))))
11371 (save-window-excursion
11372 (message "Running %s...done" cmd)
11373 (start-process-shell-command cmd nil cmd)
11374 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11375 ((or (stringp cmd)
11376 (eq cmd 'emacs))
11377 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11378 (widen)
11379 (cond (line (org-goto-line line)
11380 (when (derived-mode-p 'org-mode) (org-reveal)))
11381 (search (org-link-search search))))
11382 ((functionp cmd)
11383 (save-match-data
11384 (set-match-data link-match-data)
11385 (condition-case nil
11386 (funcall cmd file link)
11387 ;; FIXME: Remove this check when most default installations
11388 ;; of Emacs have at least Org 9.0.
11389 ((debug wrong-number-of-arguments wrong-type-argument
11390 invalid-function)
11391 (user-error "Please see Org News for version 9.0 about \
11392 `org-file-apps'--Lisp error: %S" cmd)))))
11393 ((consp cmd)
11394 ;; FIXME: Remove this check when most default installations of
11395 ;; Emacs have at least Org 9.0.
11396 ;; Heads-up instead of silently fall back to
11397 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11398 ;; with sexp instead of a function for `cmd'.
11399 (user-error "Please see Org News for version 9.0 about \
11400 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11401 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11402 (and (derived-mode-p 'org-mode)
11403 (eq old-mode 'org-mode)
11404 (or (not (eq old-buffer (current-buffer)))
11405 (not (eq old-pos (point))))
11406 (org-mark-ring-push old-pos old-buffer))))
11408 (defun org-file-apps-entry-match-against-dlink-p (entry)
11409 "This function returns non-nil if `entry' uses a regular
11410 expression which should be matched against the whole link by
11411 org-open-file.
11413 It assumes that is the case when the entry uses a regular
11414 expression which has at least one grouping construct and the
11415 action is either a lisp form or a command string containing
11416 `%1', i.e. using at least one subexpression match as a
11417 parameter."
11418 (let ((selector (car entry))
11419 (action (cdr entry)))
11420 (if (stringp selector)
11421 (and (> (regexp-opt-depth selector) 0)
11422 (or (and (stringp action)
11423 (string-match "%[0-9]" action))
11424 (consp action)))
11425 nil)))
11427 (defun org-default-apps ()
11428 "Return the default applications for this operating system."
11429 (cond
11430 ((eq system-type 'darwin)
11431 org-file-apps-defaults-macosx)
11432 ((eq system-type 'windows-nt)
11433 org-file-apps-defaults-windowsnt)
11434 (t org-file-apps-defaults-gnu)))
11436 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11437 "Convert extensions to regular expressions in the cars of LIST.
11438 Also, weed out any non-string entries, because the return value is used
11439 only for regexp matching.
11440 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11441 point to the symbol `emacs', indicating that the file should
11442 be opened in Emacs."
11443 (append
11444 (delq nil
11445 (mapcar (lambda (x)
11446 (unless (not (stringp (car x)))
11447 (if (string-match "\\W" (car x))
11449 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11450 list))
11451 (when add-auto-mode
11452 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11454 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11455 (defun org-file-remote-p (file)
11456 "Test whether FILE specifies a location on a remote system.
11457 Return non-nil if the location is indeed remote.
11459 For example, the filename \"/user@host:/foo\" specifies a location
11460 on the system \"/user@host:\"."
11461 (cond ((fboundp 'file-remote-p)
11462 (file-remote-p file))
11463 ((fboundp 'tramp-handle-file-remote-p)
11464 (tramp-handle-file-remote-p file))
11465 ((and (boundp 'ange-ftp-name-format)
11466 (string-match (car ange-ftp-name-format) file))
11467 t)))
11470 ;;;; Refiling
11472 (defun org-get-org-file ()
11473 "Read a filename, with default directory `org-directory'."
11474 (let ((default (or org-default-notes-file remember-data-file)))
11475 (read-file-name (format "File name [%s]: " default)
11476 (file-name-as-directory org-directory)
11477 default)))
11479 (defun org-notes-order-reversed-p ()
11480 "Check if the current file should receive notes in reversed order."
11481 (cond
11482 ((not org-reverse-note-order) nil)
11483 ((eq t org-reverse-note-order) t)
11484 ((not (listp org-reverse-note-order)) nil)
11485 (t (catch 'exit
11486 (dolist (entry org-reverse-note-order)
11487 (when (string-match (car entry) buffer-file-name)
11488 (throw 'exit (cdr entry))))))))
11490 (defvar org-refile-target-table nil
11491 "The list of refile targets, created by `org-refile'.")
11493 (defvar org-agenda-new-buffers nil
11494 "Buffers created to visit agenda files.")
11496 (defvar org-refile-cache nil
11497 "Cache for refile targets.")
11499 (defvar org-refile-markers nil
11500 "All the markers used for caching refile locations.")
11502 (defun org-refile-marker (pos)
11503 "Get a new refile marker, but only if caching is in use."
11504 (if (not org-refile-use-cache)
11506 (let ((m (make-marker)))
11507 (move-marker m pos)
11508 (push m org-refile-markers)
11509 m)))
11511 (defun org-refile-cache-clear ()
11512 "Clear the refile cache and disable all the markers."
11513 (dolist (m org-refile-markers) (move-marker m nil))
11514 (setq org-refile-markers nil)
11515 (setq org-refile-cache nil)
11516 (message "Refile cache has been cleared"))
11518 (defun org-refile-cache-check-set (set)
11519 "Check if all the markers in the cache still have live buffers."
11520 (let (marker)
11521 (catch 'exit
11522 (while (and set (setq marker (nth 3 (pop set))))
11523 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11524 (when (and marker (null (marker-buffer marker)))
11525 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11526 (sit-for 3)
11527 (throw 'exit nil)))
11528 t)))
11530 (defun org-refile-cache-put (set &rest identifiers)
11531 "Push the refile targets SET into the cache, under IDENTIFIERS."
11532 (let* ((key (sha1 (prin1-to-string identifiers)))
11533 (entry (assoc key org-refile-cache)))
11534 (if entry
11535 (setcdr entry set)
11536 (push (cons key set) org-refile-cache))))
11538 (defun org-refile-cache-get (&rest identifiers)
11539 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11540 (cond
11541 ((not org-refile-cache) nil)
11542 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11544 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11545 org-refile-cache))))
11546 (and set (org-refile-cache-check-set set) set)))))
11548 (defvar org-outline-path-cache nil
11549 "Alist between buffer positions and outline paths.
11550 It value is an alist (POSITION . PATH) where POSITION is the
11551 buffer position at the beginning of an entry and PATH is a list
11552 of strings describing the outline path for that entry, in reverse
11553 order.")
11555 (defun org-refile-get-targets (&optional default-buffer)
11556 "Produce a table with refile targets."
11557 (let ((case-fold-search nil)
11558 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11559 (entries (or org-refile-targets '((nil . (:level . 1)))))
11560 targets tgs files desc descre)
11561 (message "Getting targets...")
11562 (with-current-buffer (or default-buffer (current-buffer))
11563 (dolist (entry entries)
11564 (setq files (car entry) desc (cdr entry))
11565 (cond
11566 ((null files) (setq files (list (current-buffer))))
11567 ((eq files 'org-agenda-files)
11568 (setq files (org-agenda-files 'unrestricted)))
11569 ((and (symbolp files) (fboundp files))
11570 (setq files (funcall files)))
11571 ((and (symbolp files) (boundp files))
11572 (setq files (symbol-value files))))
11573 (when (stringp files) (setq files (list files)))
11574 (cond
11575 ((eq (car desc) :tag)
11576 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11577 ((eq (car desc) :todo)
11578 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11579 ((eq (car desc) :regexp)
11580 (setq descre (cdr desc)))
11581 ((eq (car desc) :level)
11582 (setq descre (concat "^\\*\\{" (number-to-string
11583 (if org-odd-levels-only
11584 (1- (* 2 (cdr desc)))
11585 (cdr desc)))
11586 "\\}[ \t]")))
11587 ((eq (car desc) :maxlevel)
11588 (setq descre (concat "^\\*\\{1," (number-to-string
11589 (if org-odd-levels-only
11590 (1- (* 2 (cdr desc)))
11591 (cdr desc)))
11592 "\\}[ \t]")))
11593 (t (error "Bad refiling target description %s" desc)))
11594 (dolist (f files)
11595 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11597 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11598 (progn
11599 (when (bufferp f)
11600 (setq f (buffer-file-name (buffer-base-buffer f))))
11601 (setq f (and f (expand-file-name f)))
11602 (when (eq org-refile-use-outline-path 'file)
11603 (push (list (file-name-nondirectory f) f nil nil) tgs))
11604 (org-with-wide-buffer
11605 (goto-char (point-min))
11606 (setq org-outline-path-cache nil)
11607 (while (re-search-forward descre nil t)
11608 (beginning-of-line)
11609 (looking-at org-complex-heading-regexp)
11610 (let ((begin (point))
11611 (heading (org-match-string-no-properties 4)))
11612 (unless (or (and
11613 org-refile-target-verify-function
11614 (not
11615 (funcall org-refile-target-verify-function)))
11616 (not heading))
11617 (let ((re (format org-complex-heading-regexp-format
11618 (regexp-quote heading)))
11619 (target
11620 (if (not org-refile-use-outline-path) heading
11621 (mapconcat
11622 #'org-protect-slash
11623 (append
11624 (pcase org-refile-use-outline-path
11625 (`file (list (file-name-nondirectory
11626 (buffer-file-name
11627 (buffer-base-buffer)))))
11628 (`full-file-path
11629 (list (buffer-file-name
11630 (buffer-base-buffer))))
11631 (_ nil))
11632 (org-get-outline-path t t))
11633 "/"))))
11634 (push (list target f re (org-refile-marker (point)))
11635 tgs)))
11636 (when (= (point) begin)
11637 ;; Verification function has not moved point.
11638 (end-of-line)))))))
11639 (when org-refile-use-cache
11640 (org-refile-cache-put tgs (buffer-file-name) descre))
11641 (setq targets (append tgs targets))))))
11642 (message "Getting targets...done")
11643 (nreverse targets)))
11645 (defun org-protect-slash (s)
11646 (while (string-match "/" s)
11647 (setq s (replace-match "\\" t t s)))
11650 (defun org--get-outline-path-1 (&optional use-cache)
11651 "Return outline path to current headline.
11653 Outline path is a list of strings, in reverse order. When
11654 optional argument USE-CACHE is non-nil, make use of a cache. See
11655 `org-get-outline-path' for details.
11657 Assume buffer is widened and point is on a headline."
11658 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11659 (let ((p (point))
11660 (heading (progn
11661 (looking-at org-complex-heading-regexp)
11662 (if (not (match-end 4)) ""
11663 ;; Remove statistics cookies.
11664 (org-trim
11665 (org-link-display-format
11666 (replace-regexp-in-string
11667 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11668 (org-match-string-no-properties 4))))))))
11669 (if (org-up-heading-safe)
11670 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11671 (when use-cache
11672 (push (cons p path) org-outline-path-cache))
11673 path)
11674 ;; This is a new root node. Since we assume we are moving
11675 ;; forward, we can drop previous cache so as to limit number
11676 ;; of associations there.
11677 (let ((path (list heading)))
11678 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11679 path)))))
11681 (defun org-get-outline-path (&optional with-self use-cache)
11682 "Return the outline path to the current entry.
11684 An outline path is a list of ancestors for current headline, as
11685 a list of strings. Statistics cookies are removed and links are
11686 replaced with their description, if any, or their path otherwise.
11688 When optional argument WITH-SELF is non-nil, the path also
11689 includes the current headline.
11691 When optional argument USE-CACHE is non-nil, cache outline paths
11692 between calls to this function so as to avoid backtracking. This
11693 argument is useful when planning to find more than one outline
11694 path in the same document. In that case, there are two
11695 conditions to satisfy:
11696 - `org-outline-path-cache' is set to nil before starting the
11697 process;
11698 - outline paths are computed by increasing buffer positions."
11699 (org-with-wide-buffer
11700 (and (or (and with-self (org-back-to-heading t))
11701 (org-up-heading-safe))
11702 (reverse (org--get-outline-path-1 use-cache)))))
11704 (defun org-format-outline-path (path &optional width prefix separator)
11705 "Format the outline path PATH for display.
11706 WIDTH is the maximum number of characters that is available.
11707 PREFIX is a prefix to be included in the returned string,
11708 such as the file name.
11709 SEPARATOR is inserted between the different parts of the path,
11710 the default is \"/\"."
11711 (setq width (or width 79))
11712 (setq path (delq nil path))
11713 (unless (> width 0)
11714 (user-error "Argument `width' must be positive"))
11715 (setq separator (or separator "/"))
11716 (let* ((org-odd-levels-only nil)
11717 (fpath (concat
11718 prefix (and prefix path separator)
11719 (mapconcat
11720 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11721 (cl-loop for head in path
11722 for n from 0
11723 collect (org-add-props
11724 head nil 'face
11725 (nth (% n org-n-level-faces) org-level-faces)))
11726 separator))))
11727 (when (> (length fpath) width)
11728 (if (< width 7)
11729 ;; It's unlikely that `width' will be this small, but don't
11730 ;; waste characters by adding ".." if it is.
11731 (setq fpath (substring fpath 0 width))
11732 (setf (substring fpath (- width 2)) "..")))
11733 fpath))
11735 (defun org-display-outline-path (&optional file current separator just-return-string)
11736 "Display the current outline path in the echo area.
11738 If FILE is non-nil, prepend the output with the file name.
11739 If CURRENT is non-nil, append the current heading to the output.
11740 SEPARATOR is passed through to `org-format-outline-path'. It separates
11741 the different parts of the path and defaults to \"/\".
11742 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11743 (interactive "P")
11744 (let* (case-fold-search
11745 (bfn (buffer-file-name (buffer-base-buffer)))
11746 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11747 res)
11748 (when current (setq path (append path
11749 (save-excursion
11750 (org-back-to-heading t)
11751 (when (looking-at org-complex-heading-regexp)
11752 (list (match-string 4)))))))
11753 (setq res
11754 (org-format-outline-path
11755 path
11756 (1- (frame-width))
11757 (and file bfn (concat (file-name-nondirectory bfn) separator))
11758 separator))
11759 (if just-return-string
11760 (org-no-properties res)
11761 (org-unlogged-message "%s" res))))
11763 (defvar org-refile-history nil
11764 "History for refiling operations.")
11766 (defvar org-after-refile-insert-hook nil
11767 "Hook run after `org-refile' has inserted its stuff at the new location.
11768 Note that this is still *before* the stuff will be removed from
11769 the *old* location.")
11771 (defvar org-capture-last-stored-marker)
11772 (defvar org-refile-keep nil
11773 "Non-nil means `org-refile' will copy instead of refile.")
11775 (defun org-copy ()
11776 "Like `org-refile', but copy."
11777 (interactive)
11778 (let ((org-refile-keep t))
11779 (funcall 'org-refile nil nil nil "Copy")))
11781 (defun org-refile (&optional arg default-buffer rfloc msg)
11782 "Move the entry or entries at point to another heading.
11783 The list of target headings is compiled using the information in
11784 `org-refile-targets', which see.
11786 At the target location, the entry is filed as a subitem of the
11787 target heading. Depending on `org-reverse-note-order', the new
11788 subitem will either be the first or the last subitem.
11790 If there is an active region, all entries in that region will be
11791 refiled. However, the region must fulfill the requirement that
11792 the first heading sets the top-level of the moved text.
11794 With prefix arg ARG, the command will only visit the target
11795 location and not actually move anything.
11797 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11798 refiling operation has put the subtree.
11800 With a numeric prefix argument of `2', refile to the running clock.
11802 With a numeric prefix argument of `3', emulate `org-refile-keep'
11803 being set to t and copy to the target location, don't move it.
11804 Beware that keeping refiled entries may result in duplicated ID
11805 properties.
11807 RFLOC can be a refile location obtained in a different way.
11809 MSG is a string to replace \"Refile\" in the default prompt with
11810 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11812 See also `org-refile-use-outline-path'.
11814 If you are using target caching (see `org-refile-use-cache'), you
11815 have to clear the target cache in order to find new targets.
11816 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11817 prefix argument (`C-u C-u C-u C-c C-w')."
11818 (interactive "P")
11819 (if (member arg '(0 (64)))
11820 (org-refile-cache-clear)
11821 (let* ((actionmsg (cond (msg msg)
11822 ((equal arg 3) "Refile (and keep)")
11823 (t "Refile")))
11824 (regionp (org-region-active-p))
11825 (region-start (and regionp (region-beginning)))
11826 (region-end (and regionp (region-end)))
11827 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11828 pos it nbuf file level reversed)
11829 (setq last-command nil)
11830 (when regionp
11831 (goto-char region-start)
11832 (or (bolp) (goto-char (point-at-bol)))
11833 (setq region-start (point))
11834 (unless (or (org-kill-is-subtree-p
11835 (buffer-substring region-start region-end))
11836 (prog1 org-refile-active-region-within-subtree
11837 (let ((s (point-at-eol)))
11838 (org-toggle-heading)
11839 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11840 (user-error "The region is not a (sequence of) subtree(s)")))
11841 (if (equal arg '(16))
11842 (org-refile-goto-last-stored)
11843 (when (or
11844 (and (equal arg 2)
11845 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11846 (prog1
11847 (setq it (list (or org-clock-heading "running clock")
11848 (buffer-file-name
11849 (marker-buffer org-clock-hd-marker))
11851 (marker-position org-clock-hd-marker)))
11852 (setq arg nil)))
11853 (setq it
11854 (or rfloc
11855 (let (heading-text)
11856 (save-excursion
11857 (unless (and arg (listp arg))
11858 (org-back-to-heading t)
11859 (setq heading-text
11860 (replace-regexp-in-string
11861 org-bracket-link-regexp
11862 "\\3"
11863 (nth 4 (org-heading-components)))))
11864 (org-refile-get-location
11865 (cond ((and arg (listp arg)) "Goto")
11866 (regionp (concat actionmsg " region to"))
11867 (t (concat actionmsg " subtree \""
11868 heading-text "\" to")))
11869 default-buffer
11870 (and (not (equal '(4) arg))
11871 org-refile-allow-creating-parent-nodes)))))))
11872 (setq file (nth 1 it)
11873 pos (nth 3 it))
11874 (when (and (not arg)
11876 (equal (buffer-file-name) file)
11877 (if regionp
11878 (and (>= pos region-start)
11879 (<= pos region-end))
11880 (and (>= pos (point))
11881 (< pos (save-excursion
11882 (org-end-of-subtree t t))))))
11883 (error "Cannot refile to position inside the tree or region"))
11884 (setq nbuf (or (find-buffer-visiting file)
11885 (find-file-noselect file)))
11886 (if (and arg (not (equal arg 3)))
11887 (progn
11888 (org-pop-to-buffer-same-window nbuf)
11889 (goto-char pos)
11890 (org-show-context 'org-goto))
11891 (if regionp
11892 (progn
11893 (org-kill-new (buffer-substring region-start region-end))
11894 (org-save-markers-in-region region-start region-end))
11895 (org-copy-subtree 1 nil t))
11896 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11897 (find-file-noselect file)))
11898 (setq reversed (org-notes-order-reversed-p))
11899 (save-excursion
11900 (save-restriction
11901 (widen)
11902 (if pos
11903 (progn
11904 (goto-char pos)
11905 (looking-at org-outline-regexp)
11906 (setq level (org-get-valid-level (funcall outline-level) 1))
11907 (goto-char
11908 (if reversed
11909 (or (outline-next-heading) (point-max))
11910 (or (save-excursion (org-get-next-sibling))
11911 (org-end-of-subtree t t)
11912 (point-max)))))
11913 (setq level 1)
11914 (if (not reversed)
11915 (goto-char (point-max))
11916 (goto-char (point-min))
11917 (or (outline-next-heading) (goto-char (point-max)))))
11918 (unless (bolp) (newline))
11919 (org-paste-subtree level nil nil t)
11920 (when org-log-refile
11921 (org-add-log-setup 'refile nil nil org-log-refile)
11922 (unless (eq org-log-refile 'note)
11923 (save-excursion (org-add-log-note))))
11924 (and org-auto-align-tags
11925 (let ((org-loop-over-headlines-in-active-region nil))
11926 (org-set-tags nil t)))
11927 (let ((bookmark-name (plist-get org-bookmark-names-plist
11928 :last-refile)))
11929 (when bookmark-name
11930 (with-demoted-errors
11931 (bookmark-set bookmark-name))))
11932 ;; If we are refiling for capture, make sure that the
11933 ;; last-capture pointers point here
11934 (when (org-bound-and-true-p org-capture-is-refiling)
11935 (let ((bookmark-name (plist-get org-bookmark-names-plist
11936 :last-capture-marker)))
11937 (when bookmark-name
11938 (with-demoted-errors
11939 (bookmark-set bookmark-name))))
11940 (move-marker org-capture-last-stored-marker (point)))
11941 (when (fboundp 'deactivate-mark) (deactivate-mark))
11942 (run-hooks 'org-after-refile-insert-hook))))
11943 (unless org-refile-keep
11944 (if regionp
11945 (delete-region (point) (+ (point) (- region-end region-start)))
11946 (delete-region
11947 (and (org-back-to-heading t) (point))
11948 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11949 (when (featurep 'org-inlinetask)
11950 (org-inlinetask-remove-END-maybe))
11951 (setq org-markers-to-move nil)
11952 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11954 (defun org-refile-goto-last-stored ()
11955 "Go to the location where the last refile was stored."
11956 (interactive)
11957 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11958 (message "This is the location of the last refile"))
11960 (defun org-refile--get-location (refloc tbl)
11961 "When user refile to REFLOC, find the associated target in TBL.
11962 Also check `org-refile-target-table'."
11963 (car (delq
11965 (mapcar
11966 (lambda (r) (or (assoc r tbl)
11967 (assoc r org-refile-target-table)))
11968 (list (replace-regexp-in-string "/$" "" refloc)
11969 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11971 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11972 "Prompt the user for a refile location, using PROMPT.
11973 PROMPT should not be suffixed with a colon and a space, because
11974 this function appends the default value from
11975 `org-refile-history' automatically, if that is not empty."
11976 (let ((org-refile-targets org-refile-targets)
11977 (org-refile-use-outline-path org-refile-use-outline-path))
11978 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11979 (unless org-refile-target-table
11980 (user-error "No refile targets"))
11981 (let* ((cbuf (current-buffer))
11982 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11983 (cfunc (if (and org-refile-use-outline-path
11984 org-outline-path-complete-in-steps)
11985 #'org-olpath-completing-read
11986 #'completing-read))
11987 (extra (if org-refile-use-outline-path "/" ""))
11988 (cbnex (concat (buffer-name) extra))
11989 (filename (and cfn (expand-file-name cfn)))
11990 (tbl (mapcar
11991 (lambda (x)
11992 (if (and (not (member org-refile-use-outline-path
11993 '(file full-file-path)))
11994 (not (equal filename (nth 1 x))))
11995 (cons (concat (car x) extra " ("
11996 (file-name-nondirectory (nth 1 x)) ")")
11997 (cdr x))
11998 (cons (concat (car x) extra) (cdr x))))
11999 org-refile-target-table))
12000 (completion-ignore-case t)
12001 cdef
12002 (prompt (concat prompt
12003 (or (and (car org-refile-history)
12004 (concat " (default " (car org-refile-history) ")"))
12005 (and (assoc cbnex tbl) (setq cdef cbnex)
12006 (concat " (default " cbnex ")"))) ": "))
12007 pa answ parent-target child parent old-hist)
12008 (setq old-hist org-refile-history)
12009 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12010 nil 'org-refile-history (or cdef (car org-refile-history))))
12011 (if (setq pa (org-refile--get-location answ tbl))
12012 (progn
12013 (org-refile-check-position pa)
12014 (when (or (not org-refile-history)
12015 (not (eq old-hist org-refile-history))
12016 (not (equal (car pa) (car org-refile-history))))
12017 (setq org-refile-history
12018 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12019 org-refile-history
12020 (cdr org-refile-history))))
12021 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12022 (pop org-refile-history)))
12024 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12025 (progn
12026 (setq parent (match-string 1 answ)
12027 child (match-string 2 answ))
12028 (setq parent-target (org-refile--get-location parent tbl))
12029 (when (and parent-target
12030 (or (eq new-nodes t)
12031 (and (eq new-nodes 'confirm)
12032 (y-or-n-p (format "Create new node \"%s\"? "
12033 child)))))
12034 (org-refile-new-child parent-target child)))
12035 (user-error "Invalid target location")))))
12037 (declare-function org-string-nw-p "org-macs" (s))
12038 (defun org-refile-check-position (refile-pointer)
12039 "Check if the refile pointer matches the headline to which it points."
12040 (let* ((file (nth 1 refile-pointer))
12041 (re (nth 2 refile-pointer))
12042 (pos (nth 3 refile-pointer))
12043 buffer)
12044 (if (and (not (markerp pos)) (not file))
12045 (user-error "Please indicate a target file in the refile path")
12046 (when (org-string-nw-p re)
12047 (setq buffer (if (markerp pos)
12048 (marker-buffer pos)
12049 (or (find-buffer-visiting file)
12050 (find-file-noselect file))))
12051 (with-current-buffer buffer
12052 (save-excursion
12053 (save-restriction
12054 (widen)
12055 (goto-char pos)
12056 (beginning-of-line 1)
12057 (unless (org-looking-at-p re)
12058 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12060 (defun org-refile-new-child (parent-target child)
12061 "Use refile target PARENT-TARGET to add new CHILD below it."
12062 (unless parent-target
12063 (error "Cannot find parent for new node"))
12064 (let ((file (nth 1 parent-target))
12065 (pos (nth 3 parent-target))
12066 level)
12067 (with-current-buffer (or (find-buffer-visiting file)
12068 (find-file-noselect file))
12069 (save-excursion
12070 (save-restriction
12071 (widen)
12072 (if pos
12073 (goto-char pos)
12074 (goto-char (point-max))
12075 (unless (bolp) (newline)))
12076 (when (looking-at org-outline-regexp)
12077 (setq level (funcall outline-level))
12078 (org-end-of-subtree t t))
12079 (org-back-over-empty-lines)
12080 (insert "\n" (make-string
12081 (if pos (org-get-valid-level level 1) 1) ?*)
12082 " " child "\n")
12083 (beginning-of-line 0)
12084 (list (concat (car parent-target) "/" child) file "" (point)))))))
12086 (defun org-olpath-completing-read (prompt collection &rest args)
12087 "Read an outline path like a file name."
12088 (let ((thetable collection))
12089 (apply #'completing-read
12090 prompt
12091 (lambda (string predicate &optional flag)
12092 (cond
12093 ((eq flag nil) (try-completion string thetable))
12094 ((eq flag t)
12095 (let ((l (length string)))
12096 (mapcar (lambda (x)
12097 (let ((r (substring x l))
12098 (f (if (string-match " ([^)]*)$" x)
12099 (match-string 0 x)
12100 "")))
12101 (if (string-match "/" r)
12102 (concat string (substring r 0 (match-end 0)) f)
12103 x)))
12104 (all-completions string thetable predicate))))
12105 ;; Exact match?
12106 ((eq flag 'lambda) (assoc string thetable))))
12107 args)))
12109 ;;;; Dynamic blocks
12111 (defun org-find-dblock (name)
12112 "Find the first dynamic block with name NAME in the buffer.
12113 If not found, stay at current position and return nil."
12114 (let ((case-fold-search t) pos)
12115 (save-excursion
12116 (goto-char (point-min))
12117 (setq pos (and (re-search-forward
12118 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12119 (match-beginning 0))))
12120 (when pos (goto-char pos))
12121 pos))
12123 (defun org-create-dblock (plist)
12124 "Create a dynamic block section, with parameters taken from PLIST.
12125 PLIST must contain a :name entry which is used as the name of the block."
12126 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12127 (end-of-line 1)
12128 (newline))
12129 (let ((col (current-column))
12130 (name (plist-get plist :name)))
12131 (insert "#+BEGIN: " name)
12132 (while plist
12133 (if (eq (car plist) :name)
12134 (setq plist (cddr plist))
12135 (insert " " (prin1-to-string (pop plist)))))
12136 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12137 (beginning-of-line -2)))
12139 (defun org-prepare-dblock ()
12140 "Prepare dynamic block for refresh.
12141 This empties the block, puts the cursor at the insert position and returns
12142 the property list including an extra property :name with the block name."
12143 (unless (looking-at org-dblock-start-re)
12144 (user-error "Not at a dynamic block"))
12145 (let* ((begdel (1+ (match-end 0)))
12146 (name (org-no-properties (match-string 1)))
12147 (params (append (list :name name)
12148 (read (concat "(" (match-string 3) ")")))))
12149 (save-excursion
12150 (beginning-of-line 1)
12151 (skip-chars-forward " \t")
12152 (setq params (plist-put params :indentation-column (current-column))))
12153 (unless (re-search-forward org-dblock-end-re nil t)
12154 (error "Dynamic block not terminated"))
12155 (setq params
12156 (append params
12157 (list :content (buffer-substring
12158 begdel (match-beginning 0)))))
12159 (delete-region begdel (match-beginning 0))
12160 (goto-char begdel)
12161 (open-line 1)
12162 params))
12164 (defun org-map-dblocks (&optional command)
12165 "Apply COMMAND to all dynamic blocks in the current buffer.
12166 If COMMAND is not given, use `org-update-dblock'."
12167 (let ((cmd (or command 'org-update-dblock)))
12168 (save-excursion
12169 (goto-char (point-min))
12170 (while (re-search-forward org-dblock-start-re nil t)
12171 (goto-char (match-beginning 0))
12172 (save-excursion
12173 (condition-case nil
12174 (funcall cmd)
12175 (error (message "Error during update of dynamic block"))))
12176 (unless (re-search-forward org-dblock-end-re nil t)
12177 (error "Dynamic block not terminated"))))))
12179 (defun org-dblock-update (&optional arg)
12180 "User command for updating dynamic blocks.
12181 Update the dynamic block at point. With prefix ARG, update all dynamic
12182 blocks in the buffer."
12183 (interactive "P")
12184 (if arg
12185 (org-update-all-dblocks)
12186 (or (looking-at org-dblock-start-re)
12187 (org-beginning-of-dblock))
12188 (org-update-dblock)))
12190 (defun org-update-dblock ()
12191 "Update the dynamic block at point.
12192 This means to empty the block, parse for parameters and then call
12193 the correct writing function."
12194 (interactive)
12195 (save-excursion
12196 (let* ((win (selected-window))
12197 (pos (point))
12198 (line (org-current-line))
12199 (params (org-prepare-dblock))
12200 (name (plist-get params :name))
12201 (indent (plist-get params :indentation-column))
12202 (cmd (intern (concat "org-dblock-write:" name))))
12203 (message "Updating dynamic block `%s' at line %d..." name line)
12204 (funcall cmd params)
12205 (message "Updating dynamic block `%s' at line %d...done" name line)
12206 (goto-char pos)
12207 (when (and indent (> indent 0))
12208 (setq indent (make-string indent ?\ ))
12209 (save-excursion
12210 (select-window win)
12211 (org-beginning-of-dblock)
12212 (forward-line 1)
12213 (while (not (looking-at org-dblock-end-re))
12214 (insert indent)
12215 (beginning-of-line 2))
12216 (when (looking-at org-dblock-end-re)
12217 (and (looking-at "[ \t]+")
12218 (replace-match ""))
12219 (insert indent)))))))
12221 (defun org-beginning-of-dblock ()
12222 "Find the beginning of the dynamic block at point.
12223 Error if there is no such block at point."
12224 (let ((pos (point))
12225 beg)
12226 (end-of-line 1)
12227 (if (and (re-search-backward org-dblock-start-re nil t)
12228 (setq beg (match-beginning 0))
12229 (re-search-forward org-dblock-end-re nil t)
12230 (> (match-end 0) pos))
12231 (goto-char beg)
12232 (goto-char pos)
12233 (error "Not in a dynamic block"))))
12235 (defun org-update-all-dblocks ()
12236 "Update all dynamic blocks in the buffer.
12237 This function can be used in a hook."
12238 (interactive)
12239 (when (derived-mode-p 'org-mode)
12240 (org-map-dblocks 'org-update-dblock)))
12243 ;;;; Completion
12245 (declare-function org-export-backend-name "org-export" (cl-x))
12246 (declare-function org-export-backend-options "org-export" (cl-x))
12247 (defun org-get-export-keywords ()
12248 "Return a list of all currently understood export keywords.
12249 Export keywords include options, block names, attributes and
12250 keywords relative to each registered export back-end."
12251 (let (keywords)
12252 (dolist (backend
12253 (org-bound-and-true-p org-export-registered-backends)
12254 (delq nil keywords))
12255 ;; Back-end name (for keywords, like #+LATEX:)
12256 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12257 (dolist (option-entry (org-export-backend-options backend))
12258 ;; Back-end options.
12259 (push (nth 1 option-entry) keywords)))))
12261 (defconst org-options-keywords
12262 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12263 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12264 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12265 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12266 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12268 (defcustom org-structure-template-alist
12269 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12270 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12271 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12272 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12273 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12274 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12275 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12276 ("L" "#+LaTeX: ")
12277 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12278 ("H" "#+HTML: ")
12279 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12280 ("A" "#+ASCII: ")
12281 ("i" "#+INDEX: ?")
12282 ("I" "#+INCLUDE: %file ?"))
12283 "Structure completion elements.
12284 This is a list of abbreviation keys and values. The value gets inserted
12285 if you type `<' followed by the key and then press the completion key,
12286 usually `TAB'. %file will be replaced by a file name after prompting
12287 for the file using completion. The cursor will be placed at the position
12288 of the `?' in the template.
12289 There are two templates for each key, the first uses the original Org syntax,
12290 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12291 the default when the /org-mtags.el/ module has been loaded. See also the
12292 variable `org-mtags-prefer-muse-templates'."
12293 :group 'org-completion
12294 :type '(repeat
12295 (list
12296 (string :tag "Key")
12297 (string :tag "Template")))
12298 :version "25.1"
12299 :package-version '(Org . "8.3"))
12301 (defun org-try-structure-completion ()
12302 "Try to complete a structure template before point.
12303 This looks for strings like \"<e\" on an otherwise empty line and
12304 expands them."
12305 (let ((l (buffer-substring (point-at-bol) (point)))
12307 (when (and (looking-at "[ \t]*$")
12308 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12309 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12310 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12311 (match-beginning 1)) a)
12312 t)))
12314 (defun org-complete-expand-structure-template (start cell)
12315 "Expand a structure template."
12316 (let ((rpl (nth 1 cell))
12317 (ind ""))
12318 (delete-region start (point))
12319 (when (string-match "\\`[ \t]*#\\+" rpl)
12320 (cond
12321 ((bolp))
12322 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12323 (setq ind (buffer-substring (point-at-bol) (point))))
12324 (t (newline))))
12325 (setq start (point))
12326 (when (string-match "%file" rpl)
12327 (setq rpl (replace-match
12328 (concat
12329 "\""
12330 (save-match-data
12331 (abbreviate-file-name (read-file-name "Include file: ")))
12332 "\"")
12333 t t rpl)))
12334 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12335 (concat "\n" ind)))
12336 (insert rpl)
12337 (when (re-search-backward "\\?" start t) (delete-char 1))))
12339 ;;;; TODO, DEADLINE, Comments
12341 (defun org-toggle-comment ()
12342 "Change the COMMENT state of an entry."
12343 (interactive)
12344 (save-excursion
12345 (org-back-to-heading)
12346 (looking-at org-complex-heading-regexp)
12347 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12348 (skip-chars-forward " \t")
12349 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12350 (if (org-in-commented-heading-p t)
12351 (delete-region (point)
12352 (progn (search-forward " " (line-end-position) 'move)
12353 (skip-chars-forward " \t")
12354 (point)))
12355 (insert org-comment-string)
12356 (unless (eolp) (insert " ")))))
12358 (defvar org-last-todo-state-is-todo nil
12359 "This is non-nil when the last TODO state change led to a TODO state.
12360 If the last change removed the TODO tag or switched to DONE, then
12361 this is nil.")
12363 (defvar org-setting-tags nil) ; dynamically skipped
12365 (defvar org-todo-setup-filter-hook nil
12366 "Hook for functions that pre-filter todo specs.
12367 Each function takes a todo spec and returns either nil or the spec
12368 transformed into canonical form." )
12370 (defvar org-todo-get-default-hook nil
12371 "Hook for functions that get a default item for todo.
12372 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12373 nil or a string to be used for the todo mark." )
12375 (defvar org-agenda-headline-snapshot-before-repeat)
12377 (defun org-current-effective-time ()
12378 "Return current time adjusted for `org-extend-today-until' variable."
12379 (let* ((ct (org-current-time))
12380 (dct (decode-time ct))
12381 (ct1
12382 (cond
12383 (org-use-last-clock-out-time-as-effective-time
12384 (or (org-clock-get-last-clock-out-time) ct))
12385 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12386 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12387 (t ct))))
12388 ct1))
12390 (defun org-todo-yesterday (&optional arg)
12391 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12392 (interactive "P")
12393 (if (eq major-mode 'org-agenda-mode)
12394 (apply 'org-agenda-todo-yesterday arg)
12395 (let* ((org-use-effective-time t)
12396 (hour (nth 2 (decode-time (org-current-time))))
12397 (org-extend-today-until (1+ hour)))
12398 (org-todo arg))))
12400 (defvar org-block-entry-blocking ""
12401 "First entry preventing the TODO state change.")
12403 (defun org-cancel-repeater ()
12404 "Cancel a repeater by setting its numeric value to zero."
12405 (interactive)
12406 (save-excursion
12407 (org-back-to-heading t)
12408 (let ((bound1 (point))
12409 (bound0 (save-excursion (outline-next-heading) (point))))
12410 (when (and (re-search-forward
12411 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12412 org-deadline-time-regexp "\\)\\|\\("
12413 org-ts-regexp "\\)")
12414 bound0 t)
12415 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12416 bound1 t))
12417 (replace-match "0" t nil nil 1)))))
12419 (defvar org-state) ;; dynamically scoped into this function
12420 (defun org-todo (&optional arg)
12421 "Change the TODO state of an item.
12422 The state of an item is given by a keyword at the start of the heading,
12423 like
12424 *** TODO Write paper
12425 *** DONE Call mom
12427 The different keywords are specified in the variable `org-todo-keywords'.
12428 By default the available states are \"TODO\" and \"DONE\".
12429 So for this example: when the item starts with TODO, it is changed to DONE.
12430 When it starts with DONE, the DONE is removed. And when neither TODO nor
12431 DONE are present, add TODO at the beginning of the heading.
12433 With \\[universal-argument] prefix arg, use completion to determine the new \
12434 state.
12435 With numeric prefix arg, switch to that state.
12436 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12437 keywords (nextset).
12438 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12439 With a numeric prefix arg of 0, inhibit note taking for the change.
12440 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12442 When called through ELisp, arg is also interpreted in the following way:
12443 `none' -> empty state
12444 \"\"(empty string) -> switch to empty state
12445 `done' -> switch to DONE
12446 `nextset' -> switch to the next set of keywords
12447 `previousset' -> switch to the previous set of keywords
12448 \"WAITING\" -> switch to the specified keyword, but only if it
12449 really is a member of `org-todo-keywords'."
12450 (interactive "P")
12451 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12452 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12453 'region-start-level 'region))
12454 org-loop-over-headlines-in-active-region)
12455 (org-map-entries
12456 `(org-todo ,arg)
12457 org-loop-over-headlines-in-active-region
12458 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12459 (when (equal arg '(16)) (setq arg 'nextset))
12460 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12461 (let ((org-blocker-hook org-blocker-hook)
12462 commentp
12463 case-fold-search)
12464 (when (equal arg '(64))
12465 (setq arg nil org-blocker-hook nil))
12466 (when (and org-blocker-hook
12467 (or org-inhibit-blocking
12468 (org-entry-get nil "NOBLOCKING")))
12469 (setq org-blocker-hook nil))
12470 (save-excursion
12471 (catch 'exit
12472 (org-back-to-heading t)
12473 (when (org-in-commented-heading-p t)
12474 (org-toggle-comment)
12475 (setq commentp t))
12476 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12477 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12478 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12479 (let* ((match-data (match-data))
12480 (startpos (point-at-bol))
12481 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12482 (org-log-done org-log-done)
12483 (org-log-repeat org-log-repeat)
12484 (org-todo-log-states org-todo-log-states)
12485 (org-inhibit-logging
12486 (if (equal arg 0)
12487 (progn (setq arg nil) 'note) org-inhibit-logging))
12488 (this (match-string 1))
12489 (hl-pos (match-beginning 0))
12490 (head (org-get-todo-sequence-head this))
12491 (ass (assoc head org-todo-kwd-alist))
12492 (interpret (nth 1 ass))
12493 (done-word (nth 3 ass))
12494 (final-done-word (nth 4 ass))
12495 (org-last-state (or this ""))
12496 (completion-ignore-case t)
12497 (member (member this org-todo-keywords-1))
12498 (tail (cdr member))
12499 (org-state (cond
12500 ((and org-todo-key-trigger
12501 (or (and (equal arg '(4))
12502 (eq org-use-fast-todo-selection 'prefix))
12503 (and (not arg) org-use-fast-todo-selection
12504 (not (eq org-use-fast-todo-selection
12505 'prefix)))))
12506 ;; Use fast selection
12507 (org-fast-todo-selection))
12508 ((and (equal arg '(4))
12509 (or (not org-use-fast-todo-selection)
12510 (not org-todo-key-trigger)))
12511 ;; Read a state with completion
12512 (completing-read
12513 "State: " (mapcar #'list org-todo-keywords-1)
12514 nil t))
12515 ((eq arg 'right)
12516 (if this
12517 (if tail (car tail) nil)
12518 (car org-todo-keywords-1)))
12519 ((eq arg 'left)
12520 (unless (equal member org-todo-keywords-1)
12521 (if this
12522 (nth (- (length org-todo-keywords-1)
12523 (length tail) 2)
12524 org-todo-keywords-1)
12525 (org-last org-todo-keywords-1))))
12526 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12527 (setq arg nil))) ; hack to fall back to cycling
12528 (arg
12529 ;; user or caller requests a specific state
12530 (cond
12531 ((equal arg "") nil)
12532 ((eq arg 'none) nil)
12533 ((eq arg 'done) (or done-word (car org-done-keywords)))
12534 ((eq arg 'nextset)
12535 (or (car (cdr (member head org-todo-heads)))
12536 (car org-todo-heads)))
12537 ((eq arg 'previousset)
12538 (let ((org-todo-heads (reverse org-todo-heads)))
12539 (or (car (cdr (member head org-todo-heads)))
12540 (car org-todo-heads))))
12541 ((car (member arg org-todo-keywords-1)))
12542 ((stringp arg)
12543 (user-error "State `%s' not valid in this file" arg))
12544 ((nth (1- (prefix-numeric-value arg))
12545 org-todo-keywords-1))))
12546 ((null member) (or head (car org-todo-keywords-1)))
12547 ((equal this final-done-word) nil) ;; -> make empty
12548 ((null tail) nil) ;; -> first entry
12549 ((memq interpret '(type priority))
12550 (if (eq this-command last-command)
12551 (car tail)
12552 (if (> (length tail) 0)
12553 (or done-word (car org-done-keywords))
12554 nil)))
12556 (car tail))))
12557 (org-state (or
12558 (run-hook-with-args-until-success
12559 'org-todo-get-default-hook org-state org-last-state)
12560 org-state))
12561 (next (if org-state (concat " " org-state " ") " "))
12562 (change-plist (list :type 'todo-state-change :from this :to org-state
12563 :position startpos))
12564 dolog now-done-p)
12565 (when org-blocker-hook
12566 (setq org-last-todo-state-is-todo
12567 (not (member this org-done-keywords)))
12568 (unless (save-excursion
12569 (save-match-data
12570 (org-with-wide-buffer
12571 (run-hook-with-args-until-failure
12572 'org-blocker-hook change-plist))))
12573 (if (org-called-interactively-p 'interactive)
12574 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12575 this org-state org-block-entry-blocking)
12576 ;; fail silently
12577 (message "TODO state change from %s to %s blocked (by \"%s\")"
12578 this org-state org-block-entry-blocking)
12579 (throw 'exit nil))))
12580 (store-match-data match-data)
12581 (replace-match next t t)
12582 (cond ((equal this org-state)
12583 (message "TODO state was already %s" (org-trim next)))
12584 ((pos-visible-in-window-p hl-pos)
12585 (message "TODO state changed to %s" (org-trim next))))
12586 (unless head
12587 (setq head (org-get-todo-sequence-head org-state)
12588 ass (assoc head org-todo-kwd-alist)
12589 interpret (nth 1 ass)
12590 done-word (nth 3 ass)
12591 final-done-word (nth 4 ass)))
12592 (when (memq arg '(nextset previousset))
12593 (message "Keyword-Set %d/%d: %s"
12594 (- (length org-todo-sets) -1
12595 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12596 (length org-todo-sets)
12597 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12598 (setq org-last-todo-state-is-todo
12599 (not (member org-state org-done-keywords)))
12600 (setq now-done-p (and (member org-state org-done-keywords)
12601 (not (member this org-done-keywords))))
12602 (and logging (org-local-logging logging))
12603 (when (and (or org-todo-log-states org-log-done)
12604 (not (eq org-inhibit-logging t))
12605 (not (memq arg '(nextset previousset))))
12606 ;; we need to look at recording a time and note
12607 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12608 (nth 2 (assoc this org-todo-log-states))))
12609 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12610 (setq dolog 'time))
12611 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12612 (and org-state
12613 (member org-state org-not-done-keywords)
12614 (not (member this org-not-done-keywords))))
12615 ;; This is now a todo state and was not one before
12616 ;; If there was a CLOSED time stamp, get rid of it.
12617 (org-add-planning-info nil nil 'closed))
12618 (when (and now-done-p org-log-done)
12619 ;; It is now done, and it was not done before
12620 (org-add-planning-info 'closed (org-current-effective-time))
12621 (when (and (not dolog) (eq 'note org-log-done))
12622 (org-add-log-setup 'done org-state this 'note)))
12623 (when (and org-state dolog)
12624 ;; This is a non-nil state, and we need to log it
12625 (org-add-log-setup 'state org-state this dolog)))
12626 ;; Fixup tag positioning
12627 (org-todo-trigger-tag-changes org-state)
12628 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12629 (when org-provide-todo-statistics
12630 (org-update-parent-todo-statistics))
12631 (run-hooks 'org-after-todo-state-change-hook)
12632 (when (and arg (not (member org-state org-done-keywords)))
12633 (setq head (org-get-todo-sequence-head org-state)))
12634 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12635 ;; Do we need to trigger a repeat?
12636 (when now-done-p
12637 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12638 ;; This is for the agenda, take a snapshot of the headline.
12639 (save-match-data
12640 (setq org-agenda-headline-snapshot-before-repeat
12641 (org-get-heading))))
12642 (org-auto-repeat-maybe org-state))
12643 ;; Fixup cursor location if close to the keyword
12644 (when (and (outline-on-heading-p)
12645 (not (bolp))
12646 (save-excursion (beginning-of-line 1)
12647 (looking-at org-todo-line-regexp))
12648 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12649 (goto-char (or (match-end 2) (match-end 1)))
12650 (and (looking-at " ") (just-one-space)))
12651 (when org-trigger-hook
12652 (save-excursion
12653 (run-hook-with-args 'org-trigger-hook change-plist)))
12654 (when commentp (org-toggle-comment))))))))
12656 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12657 "Block turning an entry into a TODO, using the hierarchy.
12658 This checks whether the current task should be blocked from state
12659 changes. Such blocking occurs when:
12661 1. The task has children which are not all in a completed state.
12663 2. A task has a parent with the property :ORDERED:, and there
12664 are siblings prior to the current task with incomplete
12665 status.
12667 3. The parent of the task is blocked because it has siblings that should
12668 be done first, or is child of a block grandparent TODO entry."
12670 (if (not org-enforce-todo-dependencies)
12671 t ; if locally turned off don't block
12672 (catch 'dont-block
12673 ;; If this is not a todo state change, or if this entry is already DONE,
12674 ;; do not block
12675 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12676 (member (plist-get change-plist :from)
12677 (cons 'done org-done-keywords))
12678 (member (plist-get change-plist :to)
12679 (cons 'todo org-not-done-keywords))
12680 (not (plist-get change-plist :to)))
12681 (throw 'dont-block t))
12682 ;; If this task has children, and any are undone, it's blocked
12683 (save-excursion
12684 (org-back-to-heading t)
12685 (let ((this-level (funcall outline-level)))
12686 (outline-next-heading)
12687 (let ((child-level (funcall outline-level)))
12688 (while (and (not (eobp))
12689 (> child-level this-level))
12690 ;; this todo has children, check whether they are all
12691 ;; completed
12692 (when (and (not (org-entry-is-done-p))
12693 (org-entry-is-todo-p))
12694 (setq org-block-entry-blocking (org-get-heading))
12695 (throw 'dont-block nil))
12696 (outline-next-heading)
12697 (setq child-level (funcall outline-level))))))
12698 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12699 ;; any previous siblings are undone, it's blocked
12700 (save-excursion
12701 (org-back-to-heading t)
12702 (let* ((pos (point))
12703 (parent-pos (and (org-up-heading-safe) (point))))
12704 (unless parent-pos (throw 'dont-block t)) ; no parent
12705 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12706 (forward-line 1)
12707 (re-search-forward org-not-done-heading-regexp pos t))
12708 (setq org-block-entry-blocking (match-string 0))
12709 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12710 ;; Search further up the hierarchy, to see if an ancestor is blocked
12711 (while t
12712 (goto-char parent-pos)
12713 (unless (looking-at org-not-done-heading-regexp)
12714 (throw 'dont-block t)) ; do not block, parent is not a TODO
12715 (setq pos (point))
12716 (setq parent-pos (and (org-up-heading-safe) (point)))
12717 (unless parent-pos (throw 'dont-block t)) ; no parent
12718 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12719 (forward-line 1)
12720 (re-search-forward org-not-done-heading-regexp pos t)
12721 (setq org-block-entry-blocking (org-get-heading)))
12722 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12724 (defcustom org-track-ordered-property-with-tag nil
12725 "Should the ORDERED property also be shown as a tag?
12726 The ORDERED property decides if an entry should require subtasks to be
12727 completed in sequence. Since a property is not very visible, setting
12728 this option means that toggling the ORDERED property with the command
12729 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12730 not relevant for the behavior, but it makes things more visible.
12732 Note that toggling the tag with tags commands will not change the property
12733 and therefore not influence behavior!
12735 This can be t, meaning the tag ORDERED should be used, It can also be a
12736 string to select a different tag for this task."
12737 :group 'org-todo
12738 :type '(choice
12739 (const :tag "No tracking" nil)
12740 (const :tag "Track with ORDERED tag" t)
12741 (string :tag "Use other tag")))
12743 (defun org-toggle-ordered-property ()
12744 "Toggle the ORDERED property of the current entry.
12745 For better visibility, you can track the value of this property with a tag.
12746 See variable `org-track-ordered-property-with-tag'."
12747 (interactive)
12748 (let* ((t1 org-track-ordered-property-with-tag)
12749 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12750 (save-excursion
12751 (org-back-to-heading)
12752 (if (org-entry-get nil "ORDERED")
12753 (progn
12754 (org-delete-property "ORDERED")
12755 (and tag (org-toggle-tag tag 'off))
12756 (message "Subtasks can be completed in arbitrary order"))
12757 (org-entry-put nil "ORDERED" "t")
12758 (and tag (org-toggle-tag tag 'on))
12759 (message "Subtasks must be completed in sequence")))))
12761 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12762 (defun org-block-todo-from-checkboxes (change-plist)
12763 "Block turning an entry into a TODO, using checkboxes.
12764 This checks whether the current task should be blocked from state
12765 changes because there are unchecked boxes in this entry."
12766 (if (not org-enforce-todo-checkbox-dependencies)
12767 t ; if locally turned off don't block
12768 (catch 'dont-block
12769 ;; If this is not a todo state change, or if this entry is already DONE,
12770 ;; do not block
12771 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12772 (member (plist-get change-plist :from)
12773 (cons 'done org-done-keywords))
12774 (member (plist-get change-plist :to)
12775 (cons 'todo org-not-done-keywords))
12776 (not (plist-get change-plist :to)))
12777 (throw 'dont-block t))
12778 ;; If this task has checkboxes that are not checked, it's blocked
12779 (save-excursion
12780 (org-back-to-heading t)
12781 (let ((beg (point)) end)
12782 (outline-next-heading)
12783 (setq end (point))
12784 (goto-char beg)
12785 (when (org-list-search-forward
12786 (concat (org-item-beginning-re)
12787 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12788 "\\[[- ]\\]")
12789 end t)
12790 (when (boundp 'org-blocked-by-checkboxes)
12791 (setq org-blocked-by-checkboxes t))
12792 (throw 'dont-block nil))))
12793 t))) ; do not block
12795 (defun org-entry-blocked-p ()
12796 "Non-nil if entry at point is blocked."
12797 (and (not (org-entry-get nil "NOBLOCKING"))
12798 (member (org-entry-get nil "TODO") org-not-done-keywords)
12799 (not (run-hook-with-args-until-failure
12800 'org-blocker-hook
12801 (list :type 'todo-state-change
12802 :position (point)
12803 :from 'todo
12804 :to 'done)))))
12806 (defun org-update-statistics-cookies (all)
12807 "Update the statistics cookie, either from TODO or from checkboxes.
12808 This should be called with the cursor in a line with a statistics cookie."
12809 (interactive "P")
12810 (if all
12811 (progn
12812 (org-update-checkbox-count 'all)
12813 (org-map-entries 'org-update-parent-todo-statistics))
12814 (if (not (org-at-heading-p))
12815 (org-update-checkbox-count)
12816 (let ((pos (point-marker))
12817 end l1 l2)
12818 (ignore-errors (org-back-to-heading t))
12819 (if (not (org-at-heading-p))
12820 (org-update-checkbox-count)
12821 (setq l1 (org-outline-level))
12822 (setq end (save-excursion
12823 (outline-next-heading)
12824 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12825 (point)))
12826 (if (and (save-excursion
12827 (re-search-forward
12828 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12829 (not (save-excursion (re-search-forward
12830 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12831 (org-update-checkbox-count)
12832 (if (and l2 (> l2 l1))
12833 (progn
12834 (goto-char end)
12835 (org-update-parent-todo-statistics))
12836 (goto-char pos)
12837 (beginning-of-line 1)
12838 (while (re-search-forward
12839 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12840 (point-at-eol) t)
12841 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12842 (goto-char pos)
12843 (move-marker pos nil)))))
12845 (defvar org-entry-property-inherited-from) ;; defined below
12846 (defun org-update-parent-todo-statistics ()
12847 "Update any statistics cookie in the parent of the current headline.
12848 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12849 the entire subtree and this will travel up the hierarchy and update
12850 statistics everywhere."
12851 (let* ((prop (save-excursion (org-up-heading-safe)
12852 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12853 (recursive (or (not org-hierarchical-todo-statistics)
12854 (and prop (string-match "\\<recursive\\>" prop))))
12855 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12857 (first t)
12858 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12859 level ltoggle l1 new ndel
12860 (cnt-all 0) (cnt-done 0) is-percent kwd
12861 checkbox-beg ov ovs ove cookie-present)
12862 (catch 'exit
12863 (save-excursion
12864 (beginning-of-line 1)
12865 (setq ltoggle (funcall outline-level))
12866 ;; Three situations are to consider:
12868 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12869 ;; to the top-level ancestor on the headline;
12871 ;; 2. If parent has "recursive" property, repeat up to the
12872 ;; headline setting that property, taking inheritance into
12873 ;; account;
12875 ;; 3. Else, move up to direct parent and proceed only once.
12876 (while (and (setq level (org-up-heading-safe))
12877 (or recursive first)
12878 (>= (point) lim))
12879 (setq first nil cookie-present nil)
12880 (unless (and level
12881 (not (string-match
12882 "\\<checkbox\\>"
12883 (downcase (or (org-entry-get nil "COOKIE_DATA")
12884 "")))))
12885 (throw 'exit nil))
12886 (while (re-search-forward box-re (point-at-eol) t)
12887 (setq cnt-all 0 cnt-done 0 cookie-present t)
12888 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12889 (save-match-data
12890 (unless (outline-next-heading) (throw 'exit nil))
12891 (while (and (looking-at org-complex-heading-regexp)
12892 (> (setq l1 (length (match-string 1))) level))
12893 (setq kwd (and (or recursive (= l1 ltoggle))
12894 (match-string 2)))
12895 (if (or (eq org-provide-todo-statistics 'all-headlines)
12896 (and (eq org-provide-todo-statistics t)
12897 (or (member kwd org-done-keywords)))
12898 (and (listp org-provide-todo-statistics)
12899 (stringp (car org-provide-todo-statistics))
12900 (or (member kwd org-provide-todo-statistics)
12901 (member kwd org-done-keywords)))
12902 (and (listp org-provide-todo-statistics)
12903 (listp (car org-provide-todo-statistics))
12904 (or (member kwd (car org-provide-todo-statistics))
12905 (and (member kwd org-done-keywords)
12906 (member kwd (cadr org-provide-todo-statistics))))))
12907 (setq cnt-all (1+ cnt-all))
12908 (and (eq org-provide-todo-statistics t)
12910 (setq cnt-all (1+ cnt-all))))
12911 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12912 (member kwd org-done-keywords))
12913 (and (listp org-provide-todo-statistics)
12914 (listp (car org-provide-todo-statistics))
12915 (member kwd org-done-keywords)
12916 (member kwd (cadr org-provide-todo-statistics)))
12917 (and (listp org-provide-todo-statistics)
12918 (stringp (car org-provide-todo-statistics))
12919 (member kwd org-done-keywords)))
12920 (setq cnt-done (1+ cnt-done)))
12921 (outline-next-heading)))
12922 (setq new
12923 (if is-percent
12924 (format "[%d%%]" (floor (* 100.0 cnt-done)
12925 (max 1 cnt-all)))
12926 (format "[%d/%d]" cnt-done cnt-all))
12927 ndel (- (match-end 0) checkbox-beg))
12928 ;; handle overlays when updating cookie from column view
12929 (when (setq ov (car (overlays-at checkbox-beg)))
12930 (setq ovs (overlay-start ov) ove (overlay-end ov))
12931 (delete-overlay ov))
12932 (goto-char checkbox-beg)
12933 (insert new)
12934 (delete-region (point) (+ (point) ndel))
12935 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12936 (when ov (move-overlay ov ovs ove)))
12937 (when cookie-present
12938 (run-hook-with-args 'org-after-todo-statistics-hook
12939 cnt-done (- cnt-all cnt-done))))))
12940 (run-hooks 'org-todo-statistics-hook)))
12942 (defvar org-after-todo-statistics-hook nil
12943 "Hook that is called after a TODO statistics cookie has been updated.
12944 Each function is called with two arguments: the number of not-done entries
12945 and the number of done entries.
12947 For example, the following function, when added to this hook, will switch
12948 an entry to DONE when all children are done, and back to TODO when new
12949 entries are set to a TODO status. Note that this hook is only called
12950 when there is a statistics cookie in the headline!
12952 \(defun org-summary-todo (n-done n-not-done)
12953 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12954 \(let (org-log-done org-log-states) ; turn off logging
12955 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12958 (defvar org-todo-statistics-hook nil
12959 "Hook that is run whenever Org thinks TODO statistics should be updated.
12960 This hook runs even if there is no statistics cookie present, in which case
12961 `org-after-todo-statistics-hook' would not run.")
12963 (defun org-todo-trigger-tag-changes (state)
12964 "Apply the changes defined in `org-todo-state-tags-triggers'."
12965 (let ((l org-todo-state-tags-triggers)
12966 changes)
12967 (when (or (not state) (equal state ""))
12968 (setq changes (append changes (cdr (assoc "" l)))))
12969 (when (and (stringp state) (> (length state) 0))
12970 (setq changes (append changes (cdr (assoc state l)))))
12971 (when (member state org-not-done-keywords)
12972 (setq changes (append changes (cdr (assoc 'todo l)))))
12973 (when (member state org-done-keywords)
12974 (setq changes (append changes (cdr (assoc 'done l)))))
12975 (dolist (c changes)
12976 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12978 (defun org-local-logging (value)
12979 "Get logging settings from a property VALUE."
12980 ;; Directly set the variables, they are already local.
12981 (setq org-log-done nil
12982 org-log-repeat nil
12983 org-todo-log-states nil)
12984 (dolist (w (org-split-string value))
12985 (let (a)
12986 (cond
12987 ((setq a (assoc w org-startup-options))
12988 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12989 (set (nth 1 a) (nth 2 a))))
12990 ((setq a (org-extract-log-state-settings w))
12991 (and (member (car a) org-todo-keywords-1)
12992 (push a org-todo-log-states)))))))
12994 (defun org-get-todo-sequence-head (kwd)
12995 "Return the head of the TODO sequence to which KWD belongs.
12996 If KWD is not set, check if there is a text property remembering the
12997 right sequence."
12998 (let (p)
12999 (cond
13000 ((not kwd)
13001 (or (get-text-property (point-at-bol) 'org-todo-head)
13002 (progn
13003 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13004 nil (point-at-eol)))
13005 (get-text-property p 'org-todo-head))))
13006 ((not (member kwd org-todo-keywords-1))
13007 (car org-todo-keywords-1))
13008 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13010 (defun org-fast-todo-selection ()
13011 "Fast TODO keyword selection with single keys.
13012 Returns the new TODO keyword, or nil if no state change should occur."
13013 (let* ((fulltable org-todo-key-alist)
13014 (done-keywords org-done-keywords) ;; needed for the faces.
13015 (maxlen (apply 'max (mapcar
13016 (lambda (x)
13017 (if (stringp (car x)) (string-width (car x)) 0))
13018 fulltable)))
13019 (expert nil)
13020 (fwidth (+ maxlen 3 1 3))
13021 (ncol (/ (- (window-width) 4) fwidth))
13022 tg cnt e c tbl
13023 groups ingroup)
13024 (save-excursion
13025 (save-window-excursion
13026 (if expert
13027 (set-buffer (get-buffer-create " *Org todo*"))
13028 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13029 (erase-buffer)
13030 (setq-local org-done-keywords done-keywords)
13031 (setq tbl fulltable cnt 0)
13032 (while (setq e (pop tbl))
13033 (cond
13034 ((equal e '(:startgroup))
13035 (push '() groups) (setq ingroup t)
13036 (unless (= cnt 0)
13037 (setq cnt 0)
13038 (insert "\n"))
13039 (insert "{ "))
13040 ((equal e '(:endgroup))
13041 (setq ingroup nil cnt 0)
13042 (insert "}\n"))
13043 ((equal e '(:newline))
13044 (unless (= cnt 0)
13045 (setq cnt 0)
13046 (insert "\n")
13047 (setq e (car tbl))
13048 (while (equal (car tbl) '(:newline))
13049 (insert "\n")
13050 (setq tbl (cdr tbl)))))
13052 (setq tg (car e) c (cdr e))
13053 (when ingroup (push tg (car groups)))
13054 (setq tg (org-add-props tg nil 'face
13055 (org-get-todo-face tg)))
13056 (when (and (= cnt 0) (not ingroup)) (insert " "))
13057 (insert "[" c "] " tg (make-string
13058 (- fwidth 4 (length tg)) ?\ ))
13059 (when (= (setq cnt (1+ cnt)) ncol)
13060 (insert "\n")
13061 (when ingroup (insert " "))
13062 (setq cnt 0)))))
13063 (insert "\n")
13064 (goto-char (point-min))
13065 (unless expert (org-fit-window-to-buffer))
13066 (message "[a-z..]:Set [SPC]:clear")
13067 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13068 (cond
13069 ((or (= c ?\C-g)
13070 (and (= c ?q) (not (rassoc c fulltable))))
13071 (setq quit-flag t))
13072 ((= c ?\ ) nil)
13073 ((setq e (rassoc c fulltable) tg (car e))
13075 (t (setq quit-flag t)))))))
13077 (defun org-entry-is-todo-p ()
13078 (member (org-get-todo-state) org-not-done-keywords))
13080 (defun org-entry-is-done-p ()
13081 (member (org-get-todo-state) org-done-keywords))
13083 (defun org-get-todo-state ()
13084 "Return the TODO keyword of the current subtree."
13085 (save-excursion
13086 (org-back-to-heading t)
13087 (and (looking-at org-todo-line-regexp)
13088 (match-end 2)
13089 (match-string 2))))
13091 (defun org-at-date-range-p (&optional inactive-ok)
13092 "Non-nil if point is inside a date range.
13094 When optional argument INACTIVE-OK is non-nil, also consider
13095 inactive time ranges.
13097 When this function returns a non-nil value, match data is set
13098 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13099 on INACTIVE-OK."
13100 (interactive)
13101 (save-excursion
13102 (catch 'exit
13103 (let ((pos (point)))
13104 (skip-chars-backward "^[<\r\n")
13105 (skip-chars-backward "<[")
13106 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13107 (>= (match-end 0) pos)
13108 (throw 'exit t))
13109 (skip-chars-backward "^<[\r\n")
13110 (skip-chars-backward "<[")
13111 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13112 (>= (match-end 0) pos)
13113 (throw 'exit t)))
13114 nil)))
13116 (defun org-get-repeat (&optional tagline)
13117 "Check if there is a deadline/schedule with repeater in this entry."
13118 (save-match-data
13119 (save-excursion
13120 (org-back-to-heading t)
13121 (and (re-search-forward (if tagline
13122 (concat tagline "\\s-*" org-repeat-re)
13123 org-repeat-re)
13124 (org-entry-end-position) t)
13125 (match-string-no-properties 1)))))
13127 (defvar org-last-changed-timestamp)
13128 (defvar org-last-inserted-timestamp)
13129 (defvar org-log-post-message)
13130 (defvar org-log-note-purpose)
13131 (defvar org-log-note-how nil)
13132 (defvar org-log-note-extra)
13133 (defun org-auto-repeat-maybe (done-word)
13134 "Check if the current headline contains a repeated time-stamp.
13136 If yes, set TODO state back to what it was and change the base date
13137 of repeating deadline/scheduled time stamps to new date.
13139 This function is run automatically after each state change to a DONE state."
13140 (let* ((repeat (org-get-repeat))
13141 (aa (assoc org-last-state org-todo-kwd-alist))
13142 (interpret (nth 1 aa))
13143 (head (nth 2 aa))
13144 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13145 (msg "Entry repeats: ")
13146 (org-log-done nil)
13147 (org-todo-log-states nil))
13148 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13149 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13150 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13151 org-todo-repeat-to-state)))
13152 (unless (and to-state (member to-state org-todo-keywords-1))
13153 (setq to-state (if (eq interpret 'type) org-last-state head)))
13154 (org-todo to-state))
13155 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13156 (org-entry-put nil "LAST_REPEAT" (format-time-string
13157 (org-time-stamp-format t t))))
13158 (when org-log-repeat
13159 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13160 (memq 'org-add-log-note post-command-hook))
13161 ;; We are already setup for some record.
13162 (when (eq org-log-repeat 'note)
13163 ;; Make sure we take a note, not only a time stamp.
13164 (setq org-log-note-how 'note))
13165 ;; Set up for taking a record.
13166 (org-add-log-setup 'state
13167 (or done-word (car org-done-keywords))
13168 org-last-state
13169 org-log-repeat)))
13170 (org-back-to-heading t)
13171 (org-add-planning-info nil nil 'closed)
13172 (let ((end (save-excursion (outline-next-heading) (point))))
13173 (while (re-search-forward org-ts-regexp end t)
13174 (when (save-match-data
13175 (or (org-at-planning-p)
13176 (org-at-property-p)
13177 (eq (org-element-type (save-excursion
13178 (backward-char)
13179 (org-element-context)))
13180 'timestamp)))
13181 (let ((type (cond ((match-end 1) org-scheduled-string)
13182 ((match-end 3) org-deadline-string)
13183 (t "Plain:")))
13184 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13185 (cond
13186 ((not
13187 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13188 ;; Time-stamps without a repeater are usually skipped.
13189 ;; However, a SCHEDULED time-stamp without one is
13190 ;; removed, as it is considered as no longer relevant.
13191 (when (equal type org-scheduled-string)
13192 (org-remove-timestamp-with-keyword type)))
13194 (let ((n (string-to-number (match-string 2 ts)))
13195 (what (match-string 3 ts)))
13196 (when (equal what "w") (setq n (* n 7) what "d"))
13197 (when (and (equal what "h")
13198 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13199 ts)))
13200 (user-error
13201 "Cannot repeat in Repeat in %d hour(s) because no hour \
13202 has been set"
13204 ;; Preparation, see if we need to modify the start
13205 ;; date for the change.
13206 (when (match-end 1)
13207 (let ((time (save-match-data (org-time-string-to-time ts))))
13208 (cond
13209 ((equal (match-string 1 ts) ".")
13210 ;; Shift starting date to today
13211 (org-timestamp-change
13212 (- (org-today) (time-to-days time))
13213 'day))
13214 ((equal (match-string 1 ts) "+")
13215 (let ((nshiftmax 10)
13216 (nshift 0))
13217 (while (or (= nshift 0)
13218 (<= (time-to-days time)
13219 (time-to-days (current-time))))
13220 (when (= (cl-incf nshift) nshiftmax)
13221 (or (y-or-n-p
13222 (format "%d repeater intervals were not \
13223 enough to shift date past today. Continue? "
13224 nshift))
13225 (user-error "Abort")))
13226 (org-timestamp-change n (cdr (assoc what whata)))
13227 (org-at-timestamp-p t)
13228 (setq ts (match-string 1))
13229 (setq time
13230 (save-match-data
13231 (org-time-string-to-time ts)))))
13232 (org-timestamp-change (- n) (cdr (assoc what whata)))
13233 ;; Rematch, so that we have everything in
13234 ;; place for the real shift.
13235 (org-at-timestamp-p t)
13236 (setq ts (match-string 1))
13237 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13238 ts)))))
13239 (save-excursion
13240 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13241 (setq msg
13242 (concat
13243 msg type " " org-last-changed-timestamp " ")))))))))
13244 (setq org-log-post-message msg)
13245 (message "%s" msg))))
13247 (defun org-show-todo-tree (arg)
13248 "Make a compact tree which shows all headlines marked with TODO.
13249 The tree will show the lines where the regexp matches, and all higher
13250 headlines above the match.
13251 With a \\[universal-argument] prefix, prompt for a regexp to match.
13252 With a numeric prefix N, construct a sparse tree for the Nth element
13253 of `org-todo-keywords-1'."
13254 (interactive "P")
13255 (let ((case-fold-search nil)
13256 (kwd-re
13257 (cond ((null arg) org-not-done-regexp)
13258 ((equal arg '(4))
13259 (let ((kwd
13260 (completing-read "Keyword (or KWD1|KWD2|...): "
13261 (mapcar #'list org-todo-keywords-1))))
13262 (concat "\\("
13263 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13264 "\\)\\>")))
13265 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13266 (regexp-quote (nth (1- (prefix-numeric-value arg))
13267 org-todo-keywords-1)))
13268 (t (user-error "Invalid prefix argument: %s" arg)))))
13269 (message "%d TODO entries found"
13270 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13272 (defun org-deadline (arg &optional time)
13273 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13274 With one universal prefix argument, remove any deadline from the item.
13275 With two universal prefix arguments, prompt for a warning delay.
13276 With argument TIME, set the deadline at the corresponding date. TIME
13277 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13278 (interactive "P")
13279 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13280 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13281 'region-start-level 'region))
13282 org-loop-over-headlines-in-active-region)
13283 (org-map-entries
13284 `(org-deadline ',arg ,time)
13285 org-loop-over-headlines-in-active-region
13286 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13287 (let* ((old-date (org-entry-get nil "DEADLINE"))
13288 (old-date-time (when old-date (org-time-string-to-time old-date)))
13289 (repeater (and old-date
13290 (string-match
13291 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13292 old-date)
13293 (match-string 1 old-date))))
13294 (cond
13295 ((equal arg '(4))
13296 (when (and old-date org-log-redeadline)
13297 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13298 (org-remove-timestamp-with-keyword org-deadline-string)
13299 (message "Item no longer has a deadline."))
13300 ((equal arg '(16))
13301 (save-excursion
13302 (org-back-to-heading t)
13303 (if (re-search-forward
13304 org-deadline-time-regexp
13305 (save-excursion (outline-next-heading) (point)) t)
13306 (let* ((rpl0 (match-string 1))
13307 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13308 (replace-match
13309 (concat org-deadline-string
13310 " <" rpl
13311 (format " -%dd"
13312 (abs
13313 (- (time-to-days
13314 (save-match-data
13315 (org-read-date nil t nil "Warn starting from" old-date-time)))
13316 (time-to-days old-date-time))))
13317 ">") t t))
13318 (user-error "No deadline information to update"))))
13320 (org-add-planning-info 'deadline time 'closed)
13321 (when (and old-date
13322 org-log-redeadline
13323 (not (equal old-date org-last-inserted-timestamp)))
13324 (org-add-log-setup
13325 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13326 (when repeater
13327 (save-excursion
13328 (org-back-to-heading t)
13329 (when (re-search-forward (concat org-deadline-string " "
13330 org-last-inserted-timestamp)
13331 (save-excursion
13332 (outline-next-heading) (point)) t)
13333 (goto-char (1- (match-end 0)))
13334 (insert " " repeater)
13335 (setq org-last-inserted-timestamp
13336 (concat (substring org-last-inserted-timestamp 0 -1)
13337 " " repeater
13338 (substring org-last-inserted-timestamp -1))))))
13339 (message "Deadline on %s" org-last-inserted-timestamp))))))
13341 (defun org-schedule (arg &optional time)
13342 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13343 With one universal prefix argument, remove any scheduling date from the item.
13344 With two universal prefix arguments, prompt for a delay cookie.
13345 With argument TIME, scheduled at the corresponding date. TIME can
13346 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13347 (interactive "P")
13348 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13349 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13350 'region-start-level 'region))
13351 org-loop-over-headlines-in-active-region)
13352 (org-map-entries
13353 `(org-schedule ',arg ,time)
13354 org-loop-over-headlines-in-active-region
13355 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13356 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13357 (old-date-time (when old-date (org-time-string-to-time old-date)))
13358 (repeater (and old-date
13359 (string-match
13360 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13361 old-date)
13362 (match-string 1 old-date))))
13363 (cond
13364 ((equal arg '(4))
13365 (progn
13366 (when (and old-date org-log-reschedule)
13367 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13368 (org-remove-timestamp-with-keyword org-scheduled-string)
13369 (message "Item is no longer scheduled.")))
13370 ((equal arg '(16))
13371 (save-excursion
13372 (org-back-to-heading t)
13373 (if (re-search-forward
13374 org-scheduled-time-regexp
13375 (save-excursion (outline-next-heading) (point)) t)
13376 (let* ((rpl0 (match-string 1))
13377 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13378 (replace-match
13379 (concat org-scheduled-string
13380 " <" rpl
13381 (format " -%dd"
13382 (abs
13383 (- (time-to-days
13384 (save-match-data
13385 (org-read-date nil t nil "Delay until" old-date-time)))
13386 (time-to-days old-date-time))))
13387 ">") t t))
13388 (user-error "No scheduled information to update"))))
13390 (org-add-planning-info 'scheduled time 'closed)
13391 (when (and old-date
13392 org-log-reschedule
13393 (not (equal old-date org-last-inserted-timestamp)))
13394 (org-add-log-setup
13395 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13396 (when repeater
13397 (save-excursion
13398 (org-back-to-heading t)
13399 (when (re-search-forward (concat org-scheduled-string " "
13400 org-last-inserted-timestamp)
13401 (save-excursion
13402 (outline-next-heading) (point)) t)
13403 (goto-char (1- (match-end 0)))
13404 (insert " " repeater)
13405 (setq org-last-inserted-timestamp
13406 (concat (substring org-last-inserted-timestamp 0 -1)
13407 " " repeater
13408 (substring org-last-inserted-timestamp -1))))))
13409 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13411 (defun org-get-scheduled-time (pom &optional inherit)
13412 "Get the scheduled time as a time tuple, of a format suitable
13413 for calling org-schedule with, or if there is no scheduling,
13414 returns nil."
13415 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13416 (when time
13417 (apply 'encode-time (org-parse-time-string time)))))
13419 (defun org-get-deadline-time (pom &optional inherit)
13420 "Get the deadline as a time tuple, of a format suitable for
13421 calling org-deadline with, or if there is no scheduling, returns
13422 nil."
13423 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13424 (when time
13425 (apply 'encode-time (org-parse-time-string time)))))
13427 (defun org-remove-timestamp-with-keyword (keyword)
13428 "Remove all time stamps with KEYWORD in the current entry."
13429 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13430 beg)
13431 (save-excursion
13432 (org-back-to-heading t)
13433 (setq beg (point))
13434 (outline-next-heading)
13435 (while (re-search-backward re beg t)
13436 (replace-match "")
13437 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13438 (equal (char-before) ?\ ))
13439 (backward-delete-char 1)
13440 (when (string-match "^[ \t]*$" (buffer-substring
13441 (point-at-bol) (point-at-eol)))
13442 (delete-region (point-at-bol)
13443 (min (point-max) (1+ (point-at-eol))))))))))
13445 (defvar org-time-was-given) ; dynamically scoped parameter
13446 (defvar org-end-time-was-given) ; dynamically scoped parameter
13448 (defun org-at-planning-p ()
13449 "Non-nil when point is on a planning info line."
13450 ;; This is as accurate and faster than `org-element-at-point' since
13451 ;; planning info location is fixed in the section.
13452 (org-with-wide-buffer
13453 (beginning-of-line)
13454 (and (org-looking-at-p org-planning-line-re)
13455 (eq (point)
13456 (ignore-errors
13457 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13458 (org-back-to-heading t)
13459 (org-with-limited-levels (org-back-to-heading t)))
13460 (line-beginning-position 2))))))
13462 (defun org-add-planning-info (what &optional time &rest remove)
13463 "Insert new timestamp with keyword in the planning line.
13464 WHAT indicates what kind of time stamp to add. It is a symbol
13465 among `closed', `deadline', `scheduled' and nil. TIME indicates
13466 the time to use. If none is given, the user is prompted for
13467 a date. REMOVE indicates what kind of entries to remove. An old
13468 WHAT entry will also be removed."
13469 (let (org-time-was-given org-end-time-was-given default-time default-input)
13470 (catch 'exit
13471 (when (and (memq what '(scheduled deadline))
13472 (or (not time)
13473 (and (stringp time)
13474 (string-match "^[-+]+[0-9]" time))))
13475 ;; Try to get a default date/time from existing timestamp
13476 (save-excursion
13477 (org-back-to-heading t)
13478 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13479 (when (re-search-forward (if (eq what 'scheduled)
13480 org-scheduled-time-regexp
13481 org-deadline-time-regexp)
13482 end t)
13483 (setq ts (match-string 1)
13484 default-time (apply 'encode-time (org-parse-time-string ts))
13485 default-input (and ts (org-get-compact-tod ts)))))))
13486 (when what
13487 (setq time
13488 (if (stringp time)
13489 ;; This is a string (relative or absolute), set
13490 ;; proper date.
13491 (apply #'encode-time
13492 (org-read-date-analyze
13493 time default-time (decode-time default-time)))
13494 ;; If necessary, get the time from the user
13495 (or time (org-read-date nil 'to-time nil nil
13496 default-time default-input)))))
13498 (org-with-wide-buffer
13499 (org-back-to-heading t)
13500 (forward-line)
13501 (unless (bolp) (insert "\n"))
13502 (cond ((org-looking-at-p org-planning-line-re)
13503 ;; Move to current indentation.
13504 (skip-chars-forward " \t")
13505 ;; Check if we have to remove something.
13506 (dolist (type (if what (cons what remove) remove))
13507 (save-excursion
13508 (when (re-search-forward
13509 (cl-case type
13510 (closed org-closed-time-regexp)
13511 (deadline org-deadline-time-regexp)
13512 (scheduled org-scheduled-time-regexp)
13513 (otherwise
13514 (error "Invalid planning type: %s" type)))
13515 (line-end-position) t)
13516 ;; Delete until next keyword or end of line.
13517 (delete-region
13518 (match-beginning 0)
13519 (if (re-search-forward org-keyword-time-not-clock-regexp
13520 (line-end-position)
13522 (match-beginning 0)
13523 (line-end-position))))))
13524 ;; If there is nothing more to add and no more keyword
13525 ;; is left, remove the line completely.
13526 (if (and (org-looking-at-p "[ \t]*$") (not what))
13527 (delete-region (line-beginning-position)
13528 (line-beginning-position 2))
13529 ;; If we removed last keyword, do not leave trailing
13530 ;; white space at the end of line.
13531 (let ((p (point)))
13532 (save-excursion
13533 (end-of-line)
13534 (unless (= (skip-chars-backward " \t" p) 0)
13535 (delete-region (point) (line-end-position)))))))
13536 ((not what) (throw 'exit nil)) ; Nothing to do.
13537 (t (insert-before-markers "\n")
13538 (backward-char 1)
13539 (when org-adapt-indentation
13540 (org-indent-to-column (1+ (org-outline-level))))))
13541 (when what
13542 ;; Insert planning keyword.
13543 (insert (cl-case what
13544 (closed org-closed-string)
13545 (deadline org-deadline-string)
13546 (scheduled org-scheduled-string)
13547 (otherwise (error "Invalid planning type: %s" what)))
13548 " ")
13549 ;; Insert associated timestamp.
13550 (let ((ts (org-insert-time-stamp
13551 time
13552 (or org-time-was-given
13553 (and (eq what 'closed) org-log-done-with-time))
13554 (eq what 'closed)
13555 nil nil (list org-end-time-was-given))))
13556 (unless (eolp) (insert " "))
13557 ts))))))
13559 (defvar org-log-note-marker (make-marker)
13560 "Marker pointing at the entry where the note is to be inserted.")
13561 (defvar org-log-note-purpose nil)
13562 (defvar org-log-note-state nil)
13563 (defvar org-log-note-previous-state nil)
13564 (defvar org-log-note-extra nil)
13565 (defvar org-log-note-window-configuration nil)
13566 (defvar org-log-note-return-to (make-marker))
13567 (defvar org-log-note-effective-time nil
13568 "Remembered current time so that dynamically scoped
13569 `org-extend-today-until' affects timestamps in state change log")
13571 (defvar org-log-post-message nil
13572 "Message to be displayed after a log note has been stored.
13573 The auto-repeater uses this.")
13575 (defun org-add-note ()
13576 "Add a note to the current entry.
13577 This is done in the same way as adding a state change note."
13578 (interactive)
13579 (org-add-log-setup 'note))
13581 (defun org-log-beginning (&optional create)
13582 "Return expected start of log notes in current entry.
13583 When optional argument CREATE is non-nil, the function creates
13584 a drawer to store notes, if necessary. Returned position ignores
13585 narrowing."
13586 (org-with-wide-buffer
13587 (let ((drawer (org-log-into-drawer)))
13588 (cond
13589 (drawer
13590 (org-end-of-meta-data)
13591 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13592 (end (if (org-at-heading-p) (point)
13593 (save-excursion (outline-next-heading) (point))))
13594 (case-fold-search t))
13595 (catch 'exit
13596 ;; Try to find existing drawer.
13597 (while (re-search-forward regexp end t)
13598 (let ((element (org-element-at-point)))
13599 (when (eq (org-element-type element) 'drawer)
13600 (let ((cend (org-element-property :contents-end element)))
13601 (when (and (not org-log-states-order-reversed) cend)
13602 (goto-char cend)))
13603 (throw 'exit nil))))
13604 ;; No drawer found. Create one, if permitted.
13605 (when create
13606 (unless (bolp) (insert "\n"))
13607 (let ((beg (point)))
13608 (insert ":" drawer ":\n:END:\n")
13609 (org-indent-region beg (point)))
13610 (end-of-line -1)))))
13612 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13613 (skip-chars-forward " \t\n")
13614 (beginning-of-line)
13615 (unless org-log-states-order-reversed
13616 (org-skip-over-state-notes)
13617 (skip-chars-backward " \t\n")
13618 (forward-line)))))
13619 (if (bolp) (point) (line-beginning-position 2))))
13621 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13622 "Set up the post command hook to take a note.
13623 If this is about to TODO state change, the new state is expected in STATE.
13624 HOW is an indicator what kind of note should be created.
13625 EXTRA is additional text that will be inserted into the notes buffer."
13626 (move-marker org-log-note-marker (point))
13627 (setq org-log-note-purpose purpose
13628 org-log-note-state state
13629 org-log-note-previous-state prev-state
13630 org-log-note-how how
13631 org-log-note-extra extra
13632 org-log-note-effective-time (org-current-effective-time))
13633 (add-hook 'post-command-hook 'org-add-log-note 'append))
13635 (defun org-skip-over-state-notes ()
13636 "Skip past the list of State notes in an entry."
13637 (when (ignore-errors (goto-char (org-in-item-p)))
13638 (let* ((struct (org-list-struct))
13639 (prevs (org-list-prevs-alist struct))
13640 (regexp
13641 (concat "[ \t]*- +"
13642 (replace-regexp-in-string
13643 " +" " +"
13644 (org-replace-escapes
13645 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13646 `(("%d" . ,org-ts-regexp-inactive)
13647 ("%D" . ,org-ts-regexp)
13648 ("%s" . "\"\\S-+\"")
13649 ("%S" . "\"\\S-+\"")
13650 ("%t" . ,org-ts-regexp-inactive)
13651 ("%T" . ,org-ts-regexp)
13652 ("%u" . ".*?")
13653 ("%U" . ".*?")))))))
13654 (while (org-looking-at-p regexp)
13655 (goto-char (or (org-list-get-next-item (point) struct prevs)
13656 (org-list-get-item-end (point) struct)))))))
13658 (defun org-add-log-note (&optional _purpose)
13659 "Pop up a window for taking a note, and add this note later."
13660 (remove-hook 'post-command-hook 'org-add-log-note)
13661 (setq org-log-note-window-configuration (current-window-configuration))
13662 (delete-other-windows)
13663 (move-marker org-log-note-return-to (point))
13664 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13665 (goto-char org-log-note-marker)
13666 (org-switch-to-buffer-other-window "*Org Note*")
13667 (erase-buffer)
13668 (if (memq org-log-note-how '(time state))
13669 (let (current-prefix-arg) (org-store-log-note))
13670 (let ((org-inhibit-startup t)) (org-mode))
13671 (insert (format "# Insert note for %s.
13672 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13673 (cond
13674 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13675 ((eq org-log-note-purpose 'done) "closed todo item")
13676 ((eq org-log-note-purpose 'state)
13677 (format "state change from \"%s\" to \"%s\""
13678 (or org-log-note-previous-state "")
13679 (or org-log-note-state "")))
13680 ((eq org-log-note-purpose 'reschedule)
13681 "rescheduling")
13682 ((eq org-log-note-purpose 'delschedule)
13683 "no longer scheduled")
13684 ((eq org-log-note-purpose 'redeadline)
13685 "changing deadline")
13686 ((eq org-log-note-purpose 'deldeadline)
13687 "removing deadline")
13688 ((eq org-log-note-purpose 'refile)
13689 "refiling")
13690 ((eq org-log-note-purpose 'note)
13691 "this entry")
13692 (t (error "This should not happen")))))
13693 (when org-log-note-extra (insert org-log-note-extra))
13694 (setq-local org-finish-function 'org-store-log-note)
13695 (run-hooks 'org-log-buffer-setup-hook)))
13697 (defvar org-note-abort nil) ; dynamically scoped
13698 (defun org-store-log-note ()
13699 "Finish taking a log note, and insert it to where it belongs."
13700 (let ((txt (prog1 (buffer-string)
13701 (kill-buffer)))
13702 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13703 lines)
13704 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13705 (setq txt (replace-match "" t t txt)))
13706 (when (string-match "\\s-+\\'" txt)
13707 (setq txt (replace-match "" t t txt)))
13708 (setq lines (org-split-string txt "\n"))
13709 (when (org-string-nw-p note)
13710 (setq note
13711 (org-replace-escapes
13712 note
13713 (list (cons "%u" (user-login-name))
13714 (cons "%U" user-full-name)
13715 (cons "%t" (format-time-string
13716 (org-time-stamp-format 'long 'inactive)
13717 org-log-note-effective-time))
13718 (cons "%T" (format-time-string
13719 (org-time-stamp-format 'long nil)
13720 org-log-note-effective-time))
13721 (cons "%d" (format-time-string
13722 (org-time-stamp-format nil 'inactive)
13723 org-log-note-effective-time))
13724 (cons "%D" (format-time-string
13725 (org-time-stamp-format nil nil)
13726 org-log-note-effective-time))
13727 (cons "%s" (cond
13728 ((not org-log-note-state) "")
13729 ((org-string-match-p org-ts-regexp
13730 org-log-note-state)
13731 (format "\"[%s]\""
13732 (substring org-log-note-state 1 -1)))
13733 (t (format "\"%s\"" org-log-note-state))))
13734 (cons "%S"
13735 (cond
13736 ((not org-log-note-previous-state) "")
13737 ((org-string-match-p org-ts-regexp
13738 org-log-note-previous-state)
13739 (format "\"[%s]\""
13740 (substring
13741 org-log-note-previous-state 1 -1)))
13742 (t (format "\"%s\""
13743 org-log-note-previous-state)))))))
13744 (when lines (setq note (concat note " \\\\")))
13745 (push note lines))
13746 (when (and lines (not (or current-prefix-arg org-note-abort)))
13747 (with-current-buffer (marker-buffer org-log-note-marker)
13748 (org-with-wide-buffer
13749 ;; Find location for the new note.
13750 (goto-char org-log-note-marker)
13751 (set-marker org-log-note-marker nil)
13752 (goto-char (org-log-beginning t))
13753 ;; Make sure point is at the beginning of an empty line.
13754 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13755 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13756 ;; In an existing list, add a new item at the top level.
13757 ;; Otherwise, indent line like a regular one.
13758 (let ((itemp (org-in-item-p)))
13759 (if itemp
13760 (org-indent-line-to
13761 (let ((struct (save-excursion
13762 (goto-char itemp) (org-list-struct))))
13763 (org-list-get-ind (org-list-get-top-point struct) struct)))
13764 (org-indent-line)))
13765 (insert (org-list-bullet-string "-") (pop lines))
13766 (let ((ind (org-list-item-body-column (line-beginning-position))))
13767 (dolist (line lines)
13768 (insert "\n")
13769 (org-indent-line-to ind)
13770 (insert line)))
13771 (message "Note stored")
13772 (org-back-to-heading t)
13773 (org-cycle-hide-drawers 'children))
13774 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13775 ;; from within `org-add-log-note' because `buffer-undo-list'
13776 ;; is then modified outside of `org-with-remote-undo'.
13777 (when (eq this-command 'org-agenda-todo)
13778 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13779 ;; Don't add undo information when called from `org-agenda-todo'.
13780 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13781 (set-window-configuration org-log-note-window-configuration)
13782 (with-current-buffer (marker-buffer org-log-note-return-to)
13783 (goto-char org-log-note-return-to))
13784 (move-marker org-log-note-return-to nil)
13785 (when org-log-post-message (message "%s" org-log-post-message))))
13787 (defun org-remove-empty-drawer-at (pos)
13788 "Remove an empty drawer at position POS.
13789 POS may also be a marker."
13790 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13791 (org-with-wide-buffer
13792 (goto-char pos)
13793 (let ((drawer (org-element-at-point)))
13794 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13795 (not (org-element-property :contents-begin drawer)))
13796 (delete-region (org-element-property :begin drawer)
13797 (progn (goto-char (org-element-property :end drawer))
13798 (skip-chars-backward " \r\t\n")
13799 (forward-line)
13800 (point))))))))
13802 (defvar org-ts-type nil)
13803 (defun org-sparse-tree (&optional arg type)
13804 "Create a sparse tree, prompt for the details.
13805 This command can create sparse trees. You first need to select the type
13806 of match used to create the tree:
13808 t Show all TODO entries.
13809 T Show entries with a specific TODO keyword.
13810 m Show entries selected by a tags/property match.
13811 p Enter a property name and its value (both with completion on existing
13812 names/values) and show entries with that property.
13813 r Show entries matching a regular expression (`/' can be used as well).
13814 b Show deadlines and scheduled items before a date.
13815 a Show deadlines and scheduled items after a date.
13816 d Show deadlines due within `org-deadline-warning-days'.
13817 D Show deadlines and scheduled items between a date range."
13818 (interactive "P")
13819 (setq type (or type org-sparse-tree-default-date-type))
13820 (setq org-ts-type type)
13821 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13822 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13823 \[c]ycle through date types: %s"
13824 (cl-case type
13825 (all "all timestamps")
13826 (scheduled "only scheduled")
13827 (deadline "only deadline")
13828 (active "only active timestamps")
13829 (inactive "only inactive timestamps")
13830 (closed "with a closed time-stamp")
13831 (otherwise "scheduled/deadline")))
13832 (let ((answer (read-char-exclusive)))
13833 (cl-case answer
13835 (org-sparse-tree
13837 (cadr
13838 (memq type '(nil all scheduled deadline active inactive closed)))))
13839 (?d (call-interactively 'org-check-deadlines))
13840 (?b (call-interactively 'org-check-before-date))
13841 (?a (call-interactively 'org-check-after-date))
13842 (?D (call-interactively 'org-check-dates-range))
13843 (?t (call-interactively 'org-show-todo-tree))
13844 (?T (org-show-todo-tree '(4)))
13845 (?m (call-interactively 'org-match-sparse-tree))
13846 ((?p ?P)
13847 (let* ((kwd (completing-read
13848 "Property: " (mapcar #'list (org-buffer-property-keys))))
13849 (value (completing-read
13850 "Value: " (mapcar #'list (org-property-values kwd)))))
13851 (unless (string-match "\\`{.*}\\'" value)
13852 (setq value (concat "\"" value "\"")))
13853 (org-match-sparse-tree arg (concat kwd "=" value))))
13854 ((?r ?R ?/) (call-interactively 'org-occur))
13855 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13857 (defvar-local org-occur-highlights nil
13858 "List of overlays used for occur matches.")
13859 (defvar-local org-occur-parameters nil
13860 "Parameters of the active org-occur calls.
13861 This is a list, each call to org-occur pushes as cons cell,
13862 containing the regular expression and the callback, onto the list.
13863 The list can contain several entries if `org-occur' has been called
13864 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13865 will only contain one set of parameters. When the highlights are
13866 removed (for example with `C-c C-c', or with the next edit (depending
13867 on `org-remove-highlights-with-change'), this variable is emptied
13868 as well.")
13870 (defun org-occur (regexp &optional keep-previous callback)
13871 "Make a compact tree which shows all matches of REGEXP.
13872 The tree will show the lines where the regexp matches, and all higher
13873 headlines above the match. It will also show the heading after the match,
13874 to make sure editing the matching entry is easy.
13875 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13876 call to `org-occur' will be kept, to allow stacking of calls to this
13877 command.
13878 If CALLBACK is non-nil, it is a function which is called to confirm
13879 that the match should indeed be shown."
13880 (interactive "sRegexp: \nP")
13881 (when (equal regexp "")
13882 (user-error "Regexp cannot be empty"))
13883 (unless keep-previous
13884 (org-remove-occur-highlights nil nil t))
13885 (push (cons regexp callback) org-occur-parameters)
13886 (let ((cnt 0))
13887 (save-excursion
13888 (goto-char (point-min))
13889 (when (or (not keep-previous) ; do not want to keep
13890 (not org-occur-highlights)) ; no previous matches
13891 ;; hide everything
13892 (org-overview))
13893 (while (re-search-forward regexp nil t)
13894 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13895 (when (or (not callback)
13896 (save-match-data (funcall callback)))
13897 (setq cnt (1+ cnt))
13898 (when org-highlight-sparse-tree-matches
13899 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13900 (org-show-context 'occur-tree))))
13901 (when org-remove-highlights-with-change
13902 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13903 nil 'local))
13904 (unless org-sparse-tree-open-archived-trees
13905 (org-hide-archived-subtrees (point-min) (point-max)))
13906 (run-hooks 'org-occur-hook)
13907 (when (org-called-interactively-p 'interactive)
13908 (message "%d match(es) for regexp %s" cnt regexp))
13909 cnt))
13911 (defun org-occur-next-match (&optional n _reset)
13912 "Function for `next-error-function' to find sparse tree matches.
13913 N is the number of matches to move, when negative move backwards.
13914 This function always goes back to the starting point when no
13915 match is found."
13916 (let* ((limit (if (< n 0) (point-min) (point-max)))
13917 (search-func (if (< n 0)
13918 'previous-single-char-property-change
13919 'next-single-char-property-change))
13920 (n (abs n))
13921 (pos (point))
13923 (catch 'exit
13924 (while (setq p1 (funcall search-func (point) 'org-type))
13925 (when (equal p1 limit)
13926 (goto-char pos)
13927 (user-error "No more matches"))
13928 (when (equal (get-char-property p1 'org-type) 'org-occur)
13929 (setq n (1- n))
13930 (when (= n 0)
13931 (goto-char p1)
13932 (throw 'exit (point))))
13933 (goto-char p1))
13934 (goto-char p1)
13935 (user-error "No more matches"))))
13937 (defun org-show-context (&optional key)
13938 "Make sure point and context are visible.
13939 Optional argument KEY, when non-nil, is a symbol. See
13940 `org-show-context-detail' for allowed values and how much is to
13941 be shown."
13942 (org-show-set-visibility
13943 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13944 ((cdr (assq key org-show-context-detail)))
13945 (t (cdr (assq 'default org-show-context-detail))))))
13947 (defun org-show-set-visibility (detail)
13948 "Set visibility around point according to DETAIL.
13949 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13950 `tree', `canonical' or t. See `org-show-context-detail' for more
13951 information."
13952 (unless (org-before-first-heading-p)
13953 ;; Show current heading and possibly its entry, following headline
13954 ;; or all children.
13955 (if (and (org-at-heading-p) (not (eq detail 'local)))
13956 (org-flag-heading nil)
13957 (org-show-entry)
13958 (org-with-limited-levels
13959 (cl-case detail
13960 ((tree canonical t) (org-show-children))
13961 ((nil minimal ancestors))
13962 (t (save-excursion
13963 (outline-next-heading)
13964 (org-flag-heading nil))))))
13965 ;; Show all siblings.
13966 (when (eq detail 'lineage) (org-show-siblings))
13967 ;; Show ancestors, possibly with their children.
13968 (when (memq detail '(ancestors lineage tree canonical t))
13969 (save-excursion
13970 (while (org-up-heading-safe)
13971 (org-flag-heading nil)
13972 (when (memq detail '(canonical t)) (org-show-entry))
13973 (when (memq detail '(tree canonical t)) (org-show-children)))))))
13975 (defvar org-reveal-start-hook nil
13976 "Hook run before revealing a location.")
13978 (defun org-reveal (&optional siblings)
13979 "Show current entry, hierarchy above it, and the following headline.
13981 This can be used to show a consistent set of context around
13982 locations exposed with `org-show-context'.
13984 With optional argument SIBLINGS, on each level of the hierarchy all
13985 siblings are shown. This repairs the tree structure to what it would
13986 look like when opened with hierarchical calls to `org-cycle'.
13988 With double optional argument \\[universal-argument] \\[universal-argument], \
13989 go to the parent and show the
13990 entire tree."
13991 (interactive "P")
13992 (run-hooks 'org-reveal-start-hook)
13993 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13994 ((equal siblings '(16))
13995 (save-excursion
13996 (when (org-up-heading-safe)
13997 (org-show-subtree)
13998 (run-hook-with-args 'org-cycle-hook 'subtree))))
13999 (t (org-show-set-visibility 'lineage))))
14001 (defun org-highlight-new-match (beg end)
14002 "Highlight from BEG to END and mark the highlight is an occur headline."
14003 (let ((ov (make-overlay beg end)))
14004 (overlay-put ov 'face 'secondary-selection)
14005 (overlay-put ov 'org-type 'org-occur)
14006 (push ov org-occur-highlights)))
14008 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14009 "Remove the occur highlights from the buffer.
14010 BEG and END are ignored. If NOREMOVE is nil, remove this function
14011 from the `before-change-functions' in the current buffer."
14012 (interactive)
14013 (unless org-inhibit-highlight-removal
14014 (mapc #'delete-overlay org-occur-highlights)
14015 (setq org-occur-highlights nil)
14016 (setq org-occur-parameters nil)
14017 (unless noremove
14018 (remove-hook 'before-change-functions
14019 'org-remove-occur-highlights 'local))))
14021 ;;;; Priorities
14023 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14024 "Regular expression matching the priority indicator.")
14026 (defvar org-remove-priority-next-time nil)
14028 (defun org-priority-up ()
14029 "Increase the priority of the current item."
14030 (interactive)
14031 (org-priority 'up))
14033 (defun org-priority-down ()
14034 "Decrease the priority of the current item."
14035 (interactive)
14036 (org-priority 'down))
14038 (defun org-priority (&optional action _show)
14039 "Change the priority of an item.
14040 ACTION can be `set', `up', `down', or a character."
14041 (interactive "P")
14042 (if (equal action '(4))
14043 (org-show-priority)
14044 (unless org-enable-priority-commands
14045 (user-error "Priority commands are disabled"))
14046 (setq action (or action 'set))
14047 (let (current new news have remove)
14048 (save-excursion
14049 (org-back-to-heading t)
14050 (when (looking-at org-priority-regexp)
14051 (setq current (string-to-char (match-string 2))
14052 have t))
14053 (cond
14054 ((eq action 'remove)
14055 (setq remove t new ?\ ))
14056 ((or (eq action 'set)
14057 (if (featurep 'xemacs) (characterp action) (integerp action)))
14058 (if (not (eq action 'set))
14059 (setq new action)
14060 (message "Priority %c-%c, SPC to remove: "
14061 org-highest-priority org-lowest-priority)
14062 (save-match-data
14063 (setq new (read-char-exclusive))))
14064 (when (and (= (upcase org-highest-priority) org-highest-priority)
14065 (= (upcase org-lowest-priority) org-lowest-priority))
14066 (setq new (upcase new)))
14067 (cond ((equal new ?\ ) (setq remove t))
14068 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14069 (user-error "Priority must be between `%c' and `%c'"
14070 org-highest-priority org-lowest-priority))))
14071 ((eq action 'up)
14072 (setq new (if have
14073 (1- current) ; normal cycling
14074 ;; last priority was empty
14075 (if (eq last-command this-command)
14076 org-lowest-priority ; wrap around empty to lowest
14077 ;; default
14078 (if org-priority-start-cycle-with-default
14079 org-default-priority
14080 (1- org-default-priority))))))
14081 ((eq action 'down)
14082 (setq new (if have
14083 (1+ current) ; normal cycling
14084 ;; last priority was empty
14085 (if (eq last-command this-command)
14086 org-highest-priority ; wrap around empty to highest
14087 ;; default
14088 (if org-priority-start-cycle-with-default
14089 org-default-priority
14090 (1+ org-default-priority))))))
14091 (t (user-error "Invalid action")))
14092 (when (or (< (upcase new) org-highest-priority)
14093 (> (upcase new) org-lowest-priority))
14094 (if (and (memq action '(up down))
14095 (not have) (not (eq last-command this-command)))
14096 ;; `new' is from default priority
14097 (error
14098 "The default can not be set, see `org-default-priority' why")
14099 ;; normal cycling: `new' is beyond highest/lowest priority
14100 ;; and is wrapped around to the empty priority
14101 (setq remove t)))
14102 (setq news (format "%c" new))
14103 (if have
14104 (if remove
14105 (replace-match "" t t nil 1)
14106 (replace-match news t t nil 2))
14107 (if remove
14108 (user-error "No priority cookie found in line")
14109 (let ((case-fold-search nil))
14110 (looking-at org-todo-line-regexp))
14111 (if (match-end 2)
14112 (progn
14113 (goto-char (match-end 2))
14114 (insert " [#" news "]"))
14115 (goto-char (match-beginning 3))
14116 (insert "[#" news "] "))))
14117 (org-set-tags nil 'align))
14118 (if remove
14119 (message "Priority removed")
14120 (message "Priority of current item set to %s" news)))))
14122 (defun org-show-priority ()
14123 "Show the priority of the current item.
14124 This priority is composed of the main priority given with the [#A] cookies,
14125 and by additional input from the age of a schedules or deadline entry."
14126 (interactive)
14127 (let ((pri (if (eq major-mode 'org-agenda-mode)
14128 (org-get-at-bol 'priority)
14129 (save-excursion
14130 (save-match-data
14131 (beginning-of-line)
14132 (and (looking-at org-heading-regexp)
14133 (org-get-priority (match-string 0))))))))
14134 (message "Priority is %d" (if pri pri -1000))))
14136 (defun org-get-priority (s)
14137 "Find priority cookie and return priority."
14138 (save-match-data
14139 (if (functionp org-get-priority-function)
14140 (funcall org-get-priority-function)
14141 (if (not (string-match org-priority-regexp s))
14142 (* 1000 (- org-lowest-priority org-default-priority))
14143 (* 1000 (- org-lowest-priority
14144 (string-to-char (match-string 2 s))))))))
14146 ;;;; Tags
14148 (defvar org-agenda-archives-mode)
14149 (defvar org-map-continue-from nil
14150 "Position from where mapping should continue.
14151 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14153 (defvar org-scanner-tags nil
14154 "The current tag list while the tags scanner is running.")
14156 (defvar org-trust-scanner-tags nil
14157 "Should `org-get-tags-at' use the tags for the scanner.
14158 This is for internal dynamical scoping only.
14159 When this is non-nil, the function `org-get-tags-at' will return the value
14160 of `org-scanner-tags' instead of building the list by itself. This
14161 can lead to large speed-ups when the tags scanner is used in a file with
14162 many entries, and when the list of tags is retrieved, for example to
14163 obtain a list of properties. Building the tags list for each entry in such
14164 a file becomes an N^2 operation - but with this variable set, it scales
14165 as N.")
14167 (defvar org--matcher-tags-todo-only nil)
14169 (defun org-scan-tags (action matcher todo-only &optional start-level)
14170 "Scan headline tags with inheritance and produce output ACTION.
14172 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14173 or `agenda' to produce an entry list for an agenda view. It can also be
14174 a Lisp form or a function that should be called at each matched headline, in
14175 this case the return value is a list of all return values from these calls.
14177 MATCHER is a function accepting three arguments, returning
14178 a non-nil value whenever a given set of tags qualifies a headline
14179 for inclusion. See `org-make-tags-matcher' for more information.
14180 As a special case, it can also be set to t (respectively nil) in
14181 order to match all (respectively none) headline.
14183 When TODO-ONLY is non-nil, only lines with a not-done TODO
14184 keyword are included in the output.
14186 START-LEVEL can be a string with asterisks, reducing the scope to
14187 headlines matching this string."
14188 (require 'org-agenda)
14189 (let* ((re (concat "^"
14190 (if start-level
14191 ;; Get the correct level to match
14192 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14193 org-outline-regexp)
14194 " *\\(\\<\\("
14195 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14196 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14197 (props (list 'face 'default
14198 'done-face 'org-agenda-done
14199 'undone-face 'default
14200 'mouse-face 'highlight
14201 'org-not-done-regexp org-not-done-regexp
14202 'org-todo-regexp org-todo-regexp
14203 'org-complex-heading-regexp org-complex-heading-regexp
14204 'help-echo
14205 (format "mouse-2 or RET jump to org file %s"
14206 (abbreviate-file-name
14207 (or (buffer-file-name (buffer-base-buffer))
14208 (buffer-name (buffer-base-buffer)))))))
14209 (org-map-continue-from nil)
14210 lspos tags tags-list
14211 (tags-alist (list (cons 0 org-file-tags)))
14212 (llast 0) rtn rtn1 level category i txt
14213 todo marker entry priority
14214 ts-date ts-date-type ts-date-pair)
14215 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14216 (setq action (list 'lambda nil action)))
14217 (save-excursion
14218 (goto-char (point-min))
14219 (when (eq action 'sparse-tree)
14220 (org-overview)
14221 (org-remove-occur-highlights))
14222 (while (let (case-fold-search)
14223 (re-search-forward re nil t))
14224 (setq org-map-continue-from nil)
14225 (catch :skip
14226 (setq todo
14227 ;; TODO: is the 1-2 difference a bug?
14228 (when (match-end 1) (org-match-string-no-properties 2))
14229 tags (when (match-end 4) (org-match-string-no-properties 4)))
14230 (goto-char (setq lspos (match-beginning 0)))
14231 (setq level (org-reduced-level (org-outline-level))
14232 category (org-get-category))
14233 (when (eq action 'agenda)
14234 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14235 ts-date (car ts-date-pair)
14236 ts-date-type (cdr ts-date-pair)))
14237 (setq i llast llast level)
14238 ;; remove tag lists from same and sublevels
14239 (while (>= i level)
14240 (when (setq entry (assoc i tags-alist))
14241 (setq tags-alist (delete entry tags-alist)))
14242 (setq i (1- i)))
14243 ;; add the next tags
14244 (when tags
14245 (setq tags (org-split-string tags ":")
14246 tags-alist
14247 (cons (cons level tags) tags-alist)))
14248 ;; compile tags for current headline
14249 (setq tags-list
14250 (if org-use-tag-inheritance
14251 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14252 tags)
14253 org-scanner-tags tags-list)
14254 (when org-use-tag-inheritance
14255 (setcdr (car tags-alist)
14256 (mapcar (lambda (x)
14257 (setq x (copy-sequence x))
14258 (org-add-prop-inherited x))
14259 (cdar tags-alist))))
14260 (when (and tags org-use-tag-inheritance
14261 (or (not (eq t org-use-tag-inheritance))
14262 org-tags-exclude-from-inheritance))
14263 ;; Selective inheritance, remove uninherited ones.
14264 (setcdr (car tags-alist)
14265 (org-remove-uninherited-tags (cdar tags-alist))))
14266 (when (and
14268 ;; eval matcher only when the todo condition is OK
14269 (and (or (not todo-only) (member todo org-not-done-keywords))
14270 (if (functionp matcher)
14271 (let ((case-fold-search t) (org-trust-scanner-tags t))
14272 (funcall matcher todo tags-list level))
14273 matcher))
14275 ;; Call the skipper, but return t if it does not
14276 ;; skip, so that the `and' form continues evaluating.
14277 (progn
14278 (unless (eq action 'sparse-tree) (org-agenda-skip))
14281 ;; Check if timestamps are deselecting this entry
14282 (or (not todo-only)
14283 (and (member todo org-not-done-keywords)
14284 (or (not org-agenda-tags-todo-honor-ignore-options)
14285 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14287 ;; select this headline
14288 (cond
14289 ((eq action 'sparse-tree)
14290 (and org-highlight-sparse-tree-matches
14291 (org-get-heading) (match-end 0)
14292 (org-highlight-new-match
14293 (match-beginning 1) (match-end 1)))
14294 (org-show-context 'tags-tree))
14295 ((eq action 'agenda)
14296 (setq txt (org-agenda-format-item
14298 (concat
14299 (if (eq org-tags-match-list-sublevels 'indented)
14300 (make-string (1- level) ?.) "")
14301 (org-get-heading))
14302 (make-string level ?\s)
14303 category
14304 tags-list)
14305 priority (org-get-priority txt))
14306 (goto-char lspos)
14307 (setq marker (org-agenda-new-marker))
14308 (org-add-props txt props
14309 'org-marker marker 'org-hd-marker marker 'org-category category
14310 'todo-state todo
14311 'ts-date ts-date
14312 'priority priority
14313 'type (concat "tagsmatch" ts-date-type))
14314 (push txt rtn))
14315 ((functionp action)
14316 (setq org-map-continue-from nil)
14317 (save-excursion
14318 (setq rtn1 (funcall action))
14319 (push rtn1 rtn)))
14320 (t (user-error "Invalid action")))
14322 ;; if we are to skip sublevels, jump to end of subtree
14323 (unless org-tags-match-list-sublevels
14324 (org-end-of-subtree t)
14325 (backward-char 1))))
14326 ;; Get the correct position from where to continue
14327 (if org-map-continue-from
14328 (goto-char org-map-continue-from)
14329 (and (= (point) lspos) (end-of-line 1)))))
14330 (when (and (eq action 'sparse-tree)
14331 (not org-sparse-tree-open-archived-trees))
14332 (org-hide-archived-subtrees (point-min) (point-max)))
14333 (nreverse rtn)))
14335 (defun org-remove-uninherited-tags (tags)
14336 "Remove all tags that are not inherited from the list TAGS."
14337 (cond
14338 ((eq org-use-tag-inheritance t)
14339 (if org-tags-exclude-from-inheritance
14340 (org-delete-all org-tags-exclude-from-inheritance tags)
14341 tags))
14342 ((not org-use-tag-inheritance) nil)
14343 ((stringp org-use-tag-inheritance)
14344 (delq nil (mapcar
14345 (lambda (x)
14346 (if (and (string-match org-use-tag-inheritance x)
14347 (not (member x org-tags-exclude-from-inheritance)))
14348 x nil))
14349 tags)))
14350 ((listp org-use-tag-inheritance)
14351 (delq nil (mapcar
14352 (lambda (x)
14353 (if (member x org-use-tag-inheritance) x nil))
14354 tags)))))
14356 (defun org-match-sparse-tree (&optional todo-only match)
14357 "Create a sparse tree according to tags string MATCH.
14358 MATCH can contain positive and negative selection of tags, like
14359 \"+WORK+URGENT-WITHBOSS\".
14360 If optional argument TODO-ONLY is non-nil, only select lines that are
14361 also TODO lines."
14362 (interactive "P")
14363 (org-agenda-prepare-buffers (list (current-buffer)))
14364 (let ((org--matcher-tags-todo-only todo-only))
14365 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14366 org--matcher-tags-todo-only)))
14368 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14370 (defvar org-cached-props nil)
14371 (defun org-cached-entry-get (pom property)
14372 (if (or (eq t org-use-property-inheritance)
14373 (and (stringp org-use-property-inheritance)
14374 (let ((case-fold-search t))
14375 (org-string-match-p org-use-property-inheritance property)))
14376 (and (listp org-use-property-inheritance)
14377 (member-ignore-case property org-use-property-inheritance)))
14378 ;; Caching is not possible, check it directly.
14379 (org-entry-get pom property 'inherit)
14380 ;; Get all properties, so we can do complicated checks easily.
14381 (cdr (assoc-string property
14382 (or org-cached-props
14383 (setq org-cached-props (org-entry-properties pom)))
14384 t))))
14386 (defun org-global-tags-completion-table (&optional files)
14387 "Return the list of all tags in all agenda buffer/files.
14388 Optional FILES argument is a list of files which can be used
14389 instead of the agenda files."
14390 (save-excursion
14391 (org-uniquify
14392 (delq nil
14393 (apply #'append
14394 (mapcar
14395 (lambda (file)
14396 (set-buffer (find-file-noselect file))
14397 (mapcar (lambda (x)
14398 (and (stringp (car-safe x))
14399 (list (car-safe x))))
14400 (or org-current-tag-alist (org-get-buffer-tags))))
14401 (if (car-safe files) files
14402 (org-agenda-files))))))))
14404 (defun org-make-tags-matcher (match)
14405 "Create the TAGS/TODO matcher form for the selection string MATCH.
14407 Returns a cons of the selection string MATCH and a function
14408 implementing the matcher.
14410 The matcher is to be called at an Org entry, with point on the
14411 headline, and returns non-nil if the entry matches the selection
14412 string MATCH. It must be called with three arguments: the TODO
14413 keyword at the entry (or nil if none), the list of all tags at
14414 the entry including inherited ones and the reduced level of the
14415 headline. Additionally, the category of the entry, if any, must
14416 be specified as the text property `org-category' on the headline.
14418 This function sets the variable `org--matcher-tags-todo-only' to
14419 a non-nil value if the matcher restricts matching to TODO
14420 entries, otherwise it is not touched.
14422 See also `org-scan-tags'."
14423 (unless match
14424 ;; Get a new match request, with completion against the global
14425 ;; tags table and the local tags in current buffer.
14426 (let ((org-last-tags-completion-table
14427 (org-uniquify
14428 (delq nil (append (org-get-buffer-tags)
14429 (org-global-tags-completion-table))))))
14430 (setq match
14431 (completing-read
14432 "Match: "
14433 'org-tags-completion-function nil nil nil 'org-tags-history))))
14435 (let ((match0 match)
14436 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14437 (start 0)
14438 tagsmatch todomatch tagsmatcher todomatcher)
14440 ;; Expand group tags.
14441 (setq match (org-tags-expand match))
14443 ;; Check if there is a TODO part of this match, which would be the
14444 ;; part after a "/". To make sure that this slash is not part of
14445 ;; a property value to be matched against, we also check that
14446 ;; there is no / after that slash. First, find the last slash.
14447 (let ((s 0))
14448 (while (string-match "/+" match s)
14449 (setq start (match-beginning 0))
14450 (setq s (match-end 0))))
14451 (if (and (string-match "/+" match start)
14452 (not (string-match-p "\"" match start)))
14453 ;; Match contains also a TODO-matching request.
14454 (progn
14455 (setq tagsmatch (substring match 0 (match-beginning 0)))
14456 (setq todomatch (substring match (match-end 0)))
14457 (when (string-match "\\`!" todomatch)
14458 (setq org--matcher-tags-todo-only t)
14459 (setq todomatch (substring todomatch 1)))
14460 (when (string-match "\\`\\s-*\\'" todomatch)
14461 (setq todomatch nil)))
14462 ;; Only matching tags.
14463 (setq tagsmatch match)
14464 (setq todomatch nil))
14466 ;; Make the tags matcher.
14467 (when (org-string-nw-p tagsmatch)
14468 (let ((orlist nil)
14469 (orterms (org-split-string tagsmatch "|"))
14470 term)
14471 (while (setq term (pop orterms))
14472 (while (and (equal (substring term -1) "\\") orterms)
14473 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14474 (while (string-match re term)
14475 (let* ((rest (substring term (match-end 0)))
14476 (minus (and (match-end 1)
14477 (equal (match-string 1 term) "-")))
14478 (tag (save-match-data
14479 (replace-regexp-in-string
14480 "\\\\-" "-" (match-string 2 term))))
14481 (regexp (eq (string-to-char tag) ?{))
14482 (levelp (match-end 4))
14483 (propp (match-end 5))
14485 (cond
14486 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14487 (levelp
14488 `(,(org-op-to-function (match-string 3 term))
14489 level
14490 ,(string-to-number (match-string 4 term))))
14491 (propp
14492 (let* ((gv (pcase (upcase (match-string 5 term))
14493 ("CATEGORY"
14494 '(get-text-property (point) 'org-category))
14495 ("TODO" 'todo)
14496 (p `(org-cached-entry-get nil ,p))))
14497 (pv (match-string 7 term))
14498 (regexp (eq (string-to-char pv) ?{))
14499 (strp (eq (string-to-char pv) ?\"))
14500 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14501 (po (org-op-to-function (match-string 6 term)
14502 (if timep 'time strp))))
14503 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14504 (when timep (setq pv (org-matcher-time pv)))
14505 (cond ((and regexp (eq po 'org<>))
14506 `(not (string-match ,pv (or ,gv ""))))
14507 (regexp `(string-match ,pv (or ,gv "")))
14508 (strp `(,po (or ,gv "") ,pv))
14510 `(,po
14511 (string-to-number (or ,gv ""))
14512 ,(string-to-number pv))))))
14513 (t `(member ,tag tags-list)))))
14514 (push (if minus `(not ,mm) mm) tagsmatcher)
14515 (setq term rest)))
14516 (push `(and ,@tagsmatcher) orlist)
14517 (setq tagsmatcher nil))
14518 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14520 ;; Make the TODO matcher.
14521 (when (org-string-nw-p todomatch)
14522 (let ((orlist nil))
14523 (dolist (term (org-split-string todomatch "|"))
14524 (while (string-match re term)
14525 (let* ((minus (and (match-end 1)
14526 (equal (match-string 1 term) "-")))
14527 (kwd (match-string 2 term))
14528 (regexp (eq (string-to-char kwd) ?{))
14529 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14530 `(equal todo ,kwd))))
14531 (push (if minus `(not ,mm) mm) todomatcher))
14532 (setq term (substring term (match-end 0))))
14533 (push (if (> (length todomatcher) 1)
14534 (cons 'and todomatcher)
14535 (car todomatcher))
14536 orlist)
14537 (setq todomatcher nil))
14538 (setq todomatcher (cons 'or orlist))))
14540 ;; Return the string and function of the matcher. If no
14541 ;; tags-specific or todo-specific matcher exists, match
14542 ;; everything.
14543 (let ((matcher (if (and tagsmatcher todomatcher)
14544 `(and ,tagsmatcher ,todomatcher)
14545 (or tagsmatcher todomatcher t))))
14546 (when org--matcher-tags-todo-only
14547 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14548 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14550 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14551 "Expand group tags in MATCH.
14553 This replaces every group tag in MATCH with a regexp tag search.
14554 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14555 will be replaced like this:
14557 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14558 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14559 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14561 Replacing by a regexp preserves the structure of the match.
14562 E.g., this expansion
14564 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14566 will match anything tagged with \"Lab\" and \"Home\", or tagged
14567 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14569 A group tag in MATCH can contain regular expressions of its own.
14570 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14571 will be replaced like this:
14573 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14575 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14576 assumed to be a single group tag, and the function will return
14577 the list of tags in this group.
14579 When DOWNCASE is non-nil, expand downcased TAGS."
14580 (if org-group-tags
14581 (let* ((case-fold-search t)
14582 (stable org-mode-syntax-table)
14583 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14584 (taggroups (if downcased
14585 (mapcar (lambda (tg) (mapcar #'downcase tg))
14586 taggroups)
14587 taggroups))
14588 (taggroups-keys (mapcar #'car taggroups))
14589 (return-match (if downcased (downcase match) match))
14590 (count 0)
14591 (work-already-expanded tags-already-expanded)
14592 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14593 ;; @ and _ are allowed as word-components in tags.
14594 (modify-syntax-entry ?@ "w" stable)
14595 (modify-syntax-entry ?_ "w" stable)
14596 ;; Temporarily replace regexp-expressions in the match-expression.
14597 (while (string-match "{.+?}" return-match)
14598 (cl-incf count)
14599 (push (match-string 0 return-match) regexps-in-match)
14600 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14601 (while (and taggroups-keys
14602 (with-syntax-table stable
14603 (string-match
14604 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14605 (regexp-opt taggroups-keys) "\\>\\)")
14606 return-match)))
14607 (let* ((dir (match-string 1 return-match))
14608 (tag (match-string 2 return-match))
14609 (tag (if downcased (downcase tag) tag)))
14610 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14611 (member tag work-already-expanded))
14612 (setq tags-in-group (assoc tag taggroups))
14613 (push tag work-already-expanded)
14614 ;; Recursively expand each tag in the group, if the tag hasn't
14615 ;; already been expanded. Restore the match-data after all recursive calls.
14616 (save-match-data
14617 (let (tags-expanded)
14618 (dolist (x (cdr tags-in-group))
14619 (if (and (member x taggroups-keys)
14620 (not (member x work-already-expanded)))
14621 (setq tags-expanded
14622 (delete-dups
14623 (append
14624 (org-tags-expand x t downcased
14625 work-already-expanded)
14626 tags-expanded)))
14627 (setq tags-expanded
14628 (append (list x) tags-expanded)))
14629 (setq work-already-expanded
14630 (delete-dups
14631 (append tags-expanded
14632 work-already-expanded))))
14633 (setq tags-in-group
14634 (delete-dups (cons (car tags-in-group)
14635 tags-expanded)))))
14636 ;; Filter tag-regexps from tags.
14637 (setq regexp-in-group-escaped
14638 (delq nil (mapcar (lambda (x)
14639 (if (stringp x)
14640 (and (equal "{" (substring x 0 1))
14641 (equal "}" (substring x -1))
14644 tags-in-group))
14645 regexp-in-group
14646 (mapcar (lambda (x)
14647 (substring x 1 -1))
14648 regexp-in-group-escaped)
14649 tags-in-group
14650 (delq nil (mapcar (lambda (x)
14651 (if (stringp x)
14652 (and (not (equal "{" (substring x 0 1)))
14653 (not (equal "}" (substring x -1)))
14656 tags-in-group)))
14657 ;; If single-as-list, do no more in the while-loop.
14658 (if (not single-as-list)
14659 (progn
14660 (when regexp-in-group
14661 (setq regexp-in-group
14662 (concat "\\|"
14663 (mapconcat 'identity regexp-in-group
14664 "\\|"))))
14665 (setq tags-in-group
14666 (concat dir
14667 "{\\<"
14668 (regexp-opt tags-in-group)
14669 "\\>"
14670 regexp-in-group
14671 "}"))
14672 (when (stringp tags-in-group)
14673 (org-add-props tags-in-group '(grouptag t)))
14674 (setq return-match
14675 (replace-match tags-in-group t t return-match)))
14676 (setq tags-in-group
14677 (append regexp-in-group-escaped tags-in-group))))
14678 (setq taggroups-keys (delete tag taggroups-keys))))
14679 ;; Add the regular expressions back into the match-expression again.
14680 (while regexps-in-match
14681 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14682 (pop regexps-in-match)
14683 return-match t t))
14684 (cl-decf count))
14685 (if single-as-list
14686 (if tags-in-group tags-in-group (list return-match))
14687 return-match))
14688 (if single-as-list
14689 (list (if downcased (downcase match) match))
14690 match)))
14692 (defun org-op-to-function (op &optional stringp)
14693 "Turn an operator into the appropriate function."
14694 (setq op
14695 (cond
14696 ((equal op "<" ) '(< string< org-time<))
14697 ((equal op ">" ) '(> org-string> org-time>))
14698 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14699 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14700 ((member op '("=" "==")) '(= string= org-time=))
14701 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14702 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14704 (defun org<> (a b) (not (= a b)))
14705 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14706 (defun org-string>= (a b) (not (string< a b)))
14707 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14708 (defun org-string<> (a b) (not (string= a b)))
14709 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
14710 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
14711 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
14712 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
14713 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14714 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14715 (defun org-2ft (s)
14716 "Convert S to a floating point time.
14717 If S is already a number, just return it. If it is a string, parse
14718 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14719 (cond
14720 ((numberp s) s)
14721 ((stringp s)
14722 (condition-case nil
14723 (float-time (apply 'encode-time (org-parse-time-string s)))
14724 (error 0.)))
14725 (t 0.)))
14727 (defun org-time-today ()
14728 "Time in seconds today at 0:00.
14729 Returns the float number of seconds since the beginning of the
14730 epoch to the beginning of today (00:00)."
14731 (float-time (apply 'encode-time
14732 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14734 (defun org-matcher-time (s)
14735 "Interpret a time comparison value."
14736 (save-match-data
14737 (cond
14738 ((string= s "<now>") (float-time))
14739 ((string= s "<today>") (org-time-today))
14740 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14741 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14742 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14743 (+ (org-time-today)
14744 (* (string-to-number (match-string 1 s))
14745 (cdr (assoc (match-string 2 s)
14746 '(("d" . 86400.0) ("w" . 604800.0)
14747 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14748 (t (org-2ft s)))))
14750 (defun org-match-any-p (re list)
14751 "Does re match any element of list?"
14752 (setq list (mapcar (lambda (x) (string-match re x)) list))
14753 (delq nil list))
14755 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14756 (defvar org-tags-overlay (make-overlay 1 1))
14757 (org-detach-overlay org-tags-overlay)
14759 (defun org-get-local-tags-at (&optional pos)
14760 "Get a list of tags defined in the current headline."
14761 (org-get-tags-at pos 'local))
14763 (defun org-get-local-tags ()
14764 "Get a list of tags defined in the current headline."
14765 (org-get-tags-at nil 'local))
14767 (defun org-get-tags-at (&optional pos local)
14768 "Get a list of all headline tags applicable at POS.
14769 POS defaults to point. If tags are inherited, the list contains
14770 the targets in the same sequence as the headlines appear, i.e.
14771 the tags of the current headline come last.
14772 When LOCAL is non-nil, only return tags from the current headline,
14773 ignore inherited ones."
14774 (interactive)
14775 (if (and org-trust-scanner-tags
14776 (or (not pos) (equal pos (point)))
14777 (not local))
14778 org-scanner-tags
14779 (let (tags ltags lastpos parent)
14780 (save-excursion
14781 (save-restriction
14782 (widen)
14783 (goto-char (or pos (point)))
14784 (save-match-data
14785 (catch 'done
14786 (condition-case nil
14787 (progn
14788 (org-back-to-heading t)
14789 (while (not (equal lastpos (point)))
14790 (setq lastpos (point))
14791 (when (looking-at
14792 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14793 (setq ltags (org-split-string
14794 (org-match-string-no-properties 1) ":"))
14795 (when parent
14796 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14797 (setq tags (append
14798 (if parent
14799 (org-remove-uninherited-tags ltags)
14800 ltags)
14801 tags)))
14802 (or org-use-tag-inheritance (throw 'done t))
14803 (when local (throw 'done t))
14804 (or (org-up-heading-safe) (error nil))
14805 (setq parent t)))
14806 (error nil)))))
14807 (if local
14808 tags
14809 (reverse (delete-dups
14810 (reverse (append
14811 (org-remove-uninherited-tags
14812 org-file-tags)
14813 tags)))))))))
14815 (defun org-add-prop-inherited (s)
14816 (add-text-properties 0 (length s) '(inherited t) s)
14819 (defun org-toggle-tag (tag &optional onoff)
14820 "Toggle the tag TAG for the current line.
14821 If ONOFF is `on' or `off', don't toggle but set to this state."
14822 (let (res current)
14823 (save-excursion
14824 (org-back-to-heading t)
14825 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14826 (point-at-eol) t)
14827 (progn
14828 (setq current (match-string 1))
14829 (replace-match ""))
14830 (setq current ""))
14831 (setq current (nreverse (org-split-string current ":")))
14832 (cond
14833 ((eq onoff 'on)
14834 (setq res t)
14835 (or (member tag current) (push tag current)))
14836 ((eq onoff 'off)
14837 (or (not (member tag current)) (setq current (delete tag current))))
14838 (t (if (member tag current)
14839 (setq current (delete tag current))
14840 (setq res t)
14841 (push tag current))))
14842 (end-of-line 1)
14843 (if current
14844 (progn
14845 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14846 (org-set-tags nil t))
14847 (delete-horizontal-space))
14848 (run-hooks 'org-after-tags-change-hook))
14849 res))
14851 (defun org-align-tags-here (to-col)
14852 ;; Assumes that this is a headline
14853 "Align tags on the current headline to TO-COL."
14854 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14855 (beginning-of-line 1)
14856 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14857 (< pos (match-beginning 2)))
14858 (progn
14859 (setq tags-l (- (match-end 2) (match-beginning 2)))
14860 (goto-char (match-beginning 1))
14861 (insert " ")
14862 (delete-region (point) (1+ (match-beginning 2)))
14863 (setq ncol (max (current-column)
14864 (1+ col)
14865 (if (> to-col 0)
14866 to-col
14867 (- (abs to-col) tags-l))))
14868 (setq p (point))
14869 (insert (make-string (- ncol (current-column)) ?\ ))
14870 (setq ncol (current-column))
14871 (when indent-tabs-mode (tabify p (point-at-eol)))
14872 (org-move-to-column (min ncol col)))
14873 (goto-char pos))))
14875 (defun org-set-tags-command (&optional arg just-align)
14876 "Call the set-tags command for the current entry."
14877 (interactive "P")
14878 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14879 (org-set-tags arg just-align)
14880 (save-excursion
14881 (unless (and (org-region-active-p)
14882 org-loop-over-headlines-in-active-region)
14883 (org-back-to-heading t))
14884 (org-set-tags arg just-align))))
14886 (defun org-set-tags-to (data)
14887 "Set the tags of the current entry to DATA, replacing the current tags.
14888 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14889 If DATA is nil or the empty string, any tags will be removed."
14890 (interactive "sTags: ")
14891 (setq data
14892 (cond
14893 ((eq data nil) "")
14894 ((equal data "") "")
14895 ((stringp data)
14896 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14897 ":"))
14898 ((listp data)
14899 (concat ":" (mapconcat 'identity data ":") ":"))))
14900 (when data
14901 (save-excursion
14902 (org-back-to-heading t)
14903 (when (looking-at org-complex-heading-regexp)
14904 (if (match-end 5)
14905 (progn
14906 (goto-char (match-beginning 5))
14907 (insert data)
14908 (delete-region (point) (point-at-eol))
14909 (org-set-tags nil 'align))
14910 (goto-char (point-at-eol))
14911 (insert " " data)
14912 (org-set-tags nil 'align)))
14913 (beginning-of-line 1)
14914 (when (looking-at ".*?\\([ \t]+\\)$")
14915 (delete-region (match-beginning 1) (match-end 1))))))
14917 (defun org-align-all-tags ()
14918 "Align the tags in all headings."
14919 (interactive)
14920 (save-excursion
14921 (or (ignore-errors (org-back-to-heading t))
14922 (outline-next-heading))
14923 (if (org-at-heading-p)
14924 (org-set-tags t)
14925 (message "No headings"))))
14927 (defvar org-indent-indentation-per-level)
14928 (defun org-set-tags (&optional arg just-align)
14929 "Set the tags for the current headline.
14930 With prefix ARG, realign all tags in headings in the current buffer.
14931 When JUST-ALIGN is non-nil, only align tags."
14932 (interactive "P")
14933 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14934 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14935 'region-start-level
14936 'region))
14937 org-loop-over-headlines-in-active-region)
14938 (org-map-entries
14939 ;; We don't use ARG and JUST-ALIGN here because these args
14940 ;; are not useful when looping over headlines.
14941 #'org-set-tags
14942 org-loop-over-headlines-in-active-region
14944 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14945 (let ((org-setting-tags t))
14946 (if arg
14947 (save-excursion
14948 (goto-char (point-min))
14949 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14950 (while (re-search-forward org-outline-regexp-bol nil t)
14951 (org-set-tags nil t)
14952 (end-of-line)))
14953 (message "All tags realigned to column %d" org-tags-column))
14954 (let* ((current (org-get-tags-string))
14955 (col (current-column))
14956 (tags
14957 (if just-align current
14958 ;; Get a new set of tags from the user.
14959 (save-excursion
14960 (let* ((table
14961 (setq
14962 org-last-tags-completion-table
14963 (delete-dups
14964 (append
14965 (or org-current-tag-alist (org-get-buffer-tags))
14966 (and
14967 org-complete-tags-always-offer-all-agenda-tags
14968 (org-global-tags-completion-table
14969 (org-agenda-files)))))))
14970 (current-tags (org-split-string current ":"))
14971 (inherited-tags
14972 (nreverse (nthcdr (length current-tags)
14973 (nreverse (org-get-tags-at))))))
14974 (replace-regexp-in-string
14975 "\\([-+&]+\\|,\\)"
14977 (if (or (eq t org-use-fast-tag-selection)
14978 (and org-use-fast-tag-selection
14979 (delq nil (mapcar #'cdr table))))
14980 (org-fast-tag-selection
14981 current-tags inherited-tags table
14982 (and org-fast-tag-selection-include-todo
14983 org-todo-key-alist))
14984 (let ((org-add-colon-after-tag-completion
14985 (< 1 (length table))))
14986 (org-trim
14987 (completing-read
14988 "Tags: "
14989 #'org-tags-completion-function
14990 nil nil current 'org-tags-history))))))))))
14992 (when org-tags-sort-function
14993 (setq tags
14994 (mapconcat
14995 #'identity
14996 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
14997 org-tags-sort-function)
14998 ":")))
15000 (if (not (org-string-nw-p tags)) (setq tags "")
15001 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15002 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15004 ;; Insert new tags at the correct column
15005 (beginning-of-line)
15006 (let ((level (if (looking-at org-outline-regexp)
15007 (- (match-end 0) (point) 1)
15008 1)))
15009 (cond
15010 ((and (equal current "") (equal tags "")))
15011 ((re-search-forward
15012 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15013 (line-end-position)
15015 (if (equal tags "") (replace-match "" t t)
15016 (goto-char (match-beginning 0))
15017 (let* ((c0 (current-column))
15018 ;; Compute offset for the case of org-indent-mode
15019 ;; active.
15020 (di (if (org-bound-and-true-p org-indent-mode)
15021 (* (1- org-indent-indentation-per-level)
15022 (1- level))
15024 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15025 (tc (+ org-tags-column
15026 (if (> org-tags-column 0) (- di) di)))
15027 (c1 (max (1+ c0)
15028 (if (> tc 0) tc
15029 (- (- tc) (string-width tags)))))
15030 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15031 (replace-match rpl t t)
15032 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
15033 (tabify p0 (point))))))
15034 (t (error "Tags alignment failed"))))
15035 (org-move-to-column col))
15036 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15038 (defun org-change-tag-in-region (beg end tag off)
15039 "Add or remove TAG for each entry in the region.
15040 This works in the agenda, and also in an org-mode buffer."
15041 (interactive
15042 (list (region-beginning) (region-end)
15043 (let ((org-last-tags-completion-table
15044 (if (derived-mode-p 'org-mode)
15045 (org-uniquify
15046 (delq nil (append (org-get-buffer-tags)
15047 (org-global-tags-completion-table))))
15048 (org-global-tags-completion-table))))
15049 (completing-read
15050 "Tag: " 'org-tags-completion-function nil nil nil
15051 'org-tags-history))
15052 (progn
15053 (message "[s]et or [r]emove? ")
15054 (equal (read-char-exclusive) ?r))))
15055 (when (fboundp 'deactivate-mark) (deactivate-mark))
15056 (let ((agendap (equal major-mode 'org-agenda-mode))
15057 l1 l2 m buf pos newhead (cnt 0))
15058 (goto-char end)
15059 (setq l2 (1- (org-current-line)))
15060 (goto-char beg)
15061 (setq l1 (org-current-line))
15062 (cl-loop for l from l1 to l2 do
15063 (org-goto-line l)
15064 (setq m (get-text-property (point) 'org-hd-marker))
15065 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15066 (and agendap m))
15067 (setq buf (if agendap (marker-buffer m) (current-buffer))
15068 pos (if agendap m (point)))
15069 (with-current-buffer buf
15070 (save-excursion
15071 (save-restriction
15072 (goto-char pos)
15073 (setq cnt (1+ cnt))
15074 (org-toggle-tag tag (if off 'off 'on))
15075 (setq newhead (org-get-heading)))))
15076 (and agendap (org-agenda-change-all-lines newhead m))))
15077 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15079 (defun org-tags-completion-function (string _predicate &optional flag)
15080 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15081 (confirm (lambda (x) (stringp (car x)))))
15082 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15083 (setq s1 (match-string 1 string)
15084 s2 (match-string 2 string))
15085 (setq s1 "" s2 string))
15086 (cond
15087 ((eq flag nil)
15088 ;; try completion
15089 (setq rtn (try-completion s2 ctable confirm))
15090 (when (stringp rtn)
15091 (setq rtn
15092 (concat s1 s2 (substring rtn (length s2))
15093 (if (and org-add-colon-after-tag-completion
15094 (assoc rtn ctable))
15095 ":" ""))))
15096 rtn)
15097 ((eq flag t)
15098 ;; all-completions
15099 (all-completions s2 ctable confirm))
15100 ((eq flag 'lambda)
15101 ;; exact match?
15102 (assoc s2 ctable)))))
15104 (defun org-fast-tag-insert (kwd tags face &optional end)
15105 "Insert KDW, and the TAGS, the latter with face FACE.
15106 Also insert END."
15107 (insert (format "%-12s" (concat kwd ":"))
15108 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15109 (or end "")))
15111 (defun org-fast-tag-show-exit (flag)
15112 (save-excursion
15113 (org-goto-line 3)
15114 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15115 (replace-match ""))
15116 (when flag
15117 (end-of-line 1)
15118 (org-move-to-column (- (window-width) 19) t)
15119 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15121 (defun org-set-current-tags-overlay (current prefix)
15122 "Add an overlay to CURRENT tag with PREFIX."
15123 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15124 (if (featurep 'xemacs)
15125 (org-overlay-display org-tags-overlay (concat prefix s)
15126 'secondary-selection)
15127 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15128 (org-overlay-display org-tags-overlay (concat prefix s)))))
15130 (defvar org-last-tag-selection-key nil)
15131 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15132 "Fast tag selection with single keys.
15133 CURRENT is the current list of tags in the headline, INHERITED is the
15134 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15135 possibly with grouping information. TODO-TABLE is a similar table with
15136 TODO keywords, should these have keys assigned to them.
15137 If the keys are nil, a-z are automatically assigned.
15138 Returns the new tags string, or nil to not change the current settings."
15139 (let* ((fulltable (append table todo-table))
15140 (maxlen (apply 'max (mapcar
15141 (lambda (x)
15142 (if (stringp (car x)) (string-width (car x)) 0))
15143 fulltable)))
15144 (buf (current-buffer))
15145 (expert (eq org-fast-tag-selection-single-key 'expert))
15146 (buffer-tags nil)
15147 (fwidth (+ maxlen 3 1 3))
15148 (ncol (/ (- (window-width) 4) fwidth))
15149 (i-face 'org-done)
15150 (c-face 'org-todo)
15151 tg cnt e c char c1 c2 ntable tbl rtn
15152 ov-start ov-end ov-prefix
15153 (exit-after-next org-fast-tag-selection-single-key)
15154 (done-keywords org-done-keywords)
15155 groups ingroup intaggroup)
15156 (save-excursion
15157 (beginning-of-line 1)
15158 (if (looking-at
15159 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15160 (setq ov-start (match-beginning 1)
15161 ov-end (match-end 1)
15162 ov-prefix "")
15163 (setq ov-start (1- (point-at-eol))
15164 ov-end (1+ ov-start))
15165 (skip-chars-forward "^\n\r")
15166 (setq ov-prefix
15167 (concat
15168 (buffer-substring (1- (point)) (point))
15169 (if (> (current-column) org-tags-column)
15171 (make-string (- org-tags-column (current-column)) ?\ ))))))
15172 (move-overlay org-tags-overlay ov-start ov-end)
15173 (save-window-excursion
15174 (if expert
15175 (set-buffer (get-buffer-create " *Org tags*"))
15176 (delete-other-windows)
15177 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15178 (org-switch-to-buffer-other-window " *Org tags*"))
15179 (erase-buffer)
15180 (setq-local org-done-keywords done-keywords)
15181 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15182 (org-fast-tag-insert "Current" current c-face "\n\n")
15183 (org-fast-tag-show-exit exit-after-next)
15184 (org-set-current-tags-overlay current ov-prefix)
15185 (setq tbl fulltable char ?a cnt 0)
15186 (while (setq e (pop tbl))
15187 (cond
15188 ((eq (car e) :startgroup)
15189 (push '() groups) (setq ingroup t)
15190 (unless (zerop cnt)
15191 (setq cnt 0)
15192 (insert "\n"))
15193 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15194 ((eq (car e) :endgroup)
15195 (setq ingroup nil cnt 0)
15196 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15197 ((eq (car e) :startgrouptag)
15198 (setq intaggroup t)
15199 (unless (zerop cnt)
15200 (setq cnt 0)
15201 (insert "\n"))
15202 (insert "[ "))
15203 ((eq (car e) :endgrouptag)
15204 (setq intaggroup nil cnt 0)
15205 (insert "]\n"))
15206 ((equal e '(:newline))
15207 (unless (zerop cnt)
15208 (setq cnt 0)
15209 (insert "\n")
15210 (setq e (car tbl))
15211 (while (equal (car tbl) '(:newline))
15212 (insert "\n")
15213 (setq tbl (cdr tbl)))))
15214 ((equal e '(:grouptags)) (insert " : "))
15216 (setq tg (copy-sequence (car e)) c2 nil)
15217 (if (cdr e)
15218 (setq c (cdr e))
15219 ;; automatically assign a character.
15220 (setq c1 (string-to-char
15221 (downcase (substring
15222 tg (if (= (string-to-char tg) ?@) 1 0)))))
15223 (if (or (rassoc c1 ntable) (rassoc c1 table))
15224 (while (or (rassoc char ntable) (rassoc char table))
15225 (setq char (1+ char)))
15226 (setq c2 c1))
15227 (setq c (or c2 char)))
15228 (when ingroup (push tg (car groups)))
15229 (setq tg (org-add-props tg nil 'face
15230 (cond
15231 ((not (assoc tg table))
15232 (org-get-todo-face tg))
15233 ((member tg current) c-face)
15234 ((member tg inherited) i-face))))
15235 (when (equal (caar tbl) :grouptags)
15236 (org-add-props tg nil 'face 'org-tag-group))
15237 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15238 (insert "[" c "] " tg (make-string
15239 (- fwidth 4 (length tg)) ?\ ))
15240 (push (cons tg c) ntable)
15241 (when (= (cl-incf cnt) ncol)
15242 (insert "\n")
15243 (when (or ingroup intaggroup) (insert " "))
15244 (setq cnt 0)))))
15245 (setq ntable (nreverse ntable))
15246 (insert "\n")
15247 (goto-char (point-min))
15248 (unless expert (org-fit-window-to-buffer))
15249 (setq rtn
15250 (catch 'exit
15251 (while t
15252 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15253 (if (not groups) "no " "")
15254 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15255 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15256 (setq org-last-tag-selection-key c)
15257 (cond
15258 ((= c ?\r) (throw 'exit t))
15259 ((= c ?!)
15260 (setq groups (not groups))
15261 (goto-char (point-min))
15262 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15263 ((= c ?\C-c)
15264 (if (not expert)
15265 (org-fast-tag-show-exit
15266 (setq exit-after-next (not exit-after-next)))
15267 (setq expert nil)
15268 (delete-other-windows)
15269 (set-window-buffer (split-window-vertically) " *Org tags*")
15270 (org-switch-to-buffer-other-window " *Org tags*")
15271 (org-fit-window-to-buffer)))
15272 ((or (= c ?\C-g)
15273 (and (= c ?q) (not (rassoc c ntable))))
15274 (org-detach-overlay org-tags-overlay)
15275 (setq quit-flag t))
15276 ((= c ?\ )
15277 (setq current nil)
15278 (when exit-after-next (setq exit-after-next 'now)))
15279 ((= c ?\t)
15280 (condition-case nil
15281 (setq tg (completing-read
15282 "Tag: "
15283 (or buffer-tags
15284 (with-current-buffer buf
15285 (setq buffer-tags
15286 (org-get-buffer-tags))))))
15287 (quit (setq tg "")))
15288 (when (string-match "\\S-" tg)
15289 (cl-pushnew (list tg) buffer-tags :test #'equal)
15290 (if (member tg current)
15291 (setq current (delete tg current))
15292 (push tg current)))
15293 (when exit-after-next (setq exit-after-next 'now)))
15294 ((setq e (rassoc c todo-table) tg (car e))
15295 (with-current-buffer buf
15296 (save-excursion (org-todo tg)))
15297 (when exit-after-next (setq exit-after-next 'now)))
15298 ((setq e (rassoc c ntable) tg (car e))
15299 (if (member tg current)
15300 (setq current (delete tg current))
15301 (cl-loop for g in groups do
15302 (when (member tg g)
15303 (dolist (x g) (setq current (delete x current)))))
15304 (push tg current))
15305 (when exit-after-next (setq exit-after-next 'now))))
15307 ;; Create a sorted list
15308 (setq current
15309 (sort current
15310 (lambda (a b)
15311 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15312 (when (eq exit-after-next 'now) (throw 'exit t))
15313 (goto-char (point-min))
15314 (beginning-of-line 2)
15315 (delete-region (point) (point-at-eol))
15316 (org-fast-tag-insert "Current" current c-face)
15317 (org-set-current-tags-overlay current ov-prefix)
15318 (while (re-search-forward
15319 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15320 (setq tg (match-string 1))
15321 (add-text-properties
15322 (match-beginning 1) (match-end 1)
15323 (list 'face
15324 (cond
15325 ((member tg current) c-face)
15326 ((member tg inherited) i-face)
15327 (t (get-text-property (match-beginning 1) 'face))))))
15328 (goto-char (point-min)))))
15329 (org-detach-overlay org-tags-overlay)
15330 (if rtn
15331 (mapconcat 'identity current ":")
15332 nil))))
15334 (defun org-get-tags-string ()
15335 "Get the TAGS string in the current headline."
15336 (unless (org-at-heading-p t)
15337 (user-error "Not on a heading"))
15338 (save-excursion
15339 (beginning-of-line 1)
15340 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15341 (org-match-string-no-properties 1)
15342 "")))
15344 (defun org-get-tags ()
15345 "Get the list of tags specified in the current headline."
15346 (org-split-string (org-get-tags-string) ":"))
15348 (defun org-get-buffer-tags ()
15349 "Get a table of all tags used in the buffer, for completion."
15350 (org-with-wide-buffer
15351 (goto-char (point-min))
15352 (let ((tag-re (concat org-outline-regexp-bol
15353 "\\(?:.*?[ \t]\\)?"
15354 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15355 tags)
15356 (while (re-search-forward tag-re nil t)
15357 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15358 (push tag tags)))
15359 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15361 ;;;; The mapping API
15363 (defvar org-agenda-skip-comment-trees)
15364 (defvar org-agenda-skip-function)
15365 (defun org-map-entries (func &optional match scope &rest skip)
15366 "Call FUNC at each headline selected by MATCH in SCOPE.
15368 FUNC is a function or a lisp form. The function will be called without
15369 arguments, with the cursor positioned at the beginning of the headline.
15370 The return values of all calls to the function will be collected and
15371 returned as a list.
15373 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15374 does not need to preserve point. After evaluation, the cursor will be
15375 moved to the end of the line (presumably of the headline of the
15376 processed entry) and search continues from there. Under some
15377 circumstances, this may not produce the wanted results. For example,
15378 if you have removed (e.g. archived) the current (sub)tree it could
15379 mean that the next entry will be skipped entirely. In such cases, you
15380 can specify the position from where search should continue by making
15381 FUNC set the variable `org-map-continue-from' to the desired buffer
15382 position.
15384 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15385 Only headlines that are matched by this query will be considered during
15386 the iteration. When MATCH is nil or t, all headlines will be
15387 visited by the iteration.
15389 SCOPE determines the scope of this command. It can be any of:
15391 nil The current buffer, respecting the restriction if any
15392 tree The subtree started with the entry at point
15393 region The entries within the active region, if any
15394 region-start-level
15395 The entries within the active region, but only those at
15396 the same level than the first one.
15397 file The current buffer, without restriction
15398 file-with-archives
15399 The current buffer, and any archives associated with it
15400 agenda All agenda files
15401 agenda-with-archives
15402 All agenda files with any archive files associated with them
15403 \(file1 file2 ...)
15404 If this is a list, all files in the list will be scanned
15406 The remaining args are treated as settings for the skipping facilities of
15407 the scanner. The following items can be given here:
15409 archive skip trees with the archive tag
15410 comment skip trees with the COMMENT keyword
15411 function or Emacs Lisp form:
15412 will be used as value for `org-agenda-skip-function', so
15413 whenever the function returns a position, FUNC will not be
15414 called for that entry and search will continue from the
15415 position returned
15417 If your function needs to retrieve the tags including inherited tags
15418 at the *current* entry, you can use the value of the variable
15419 `org-scanner-tags' which will be much faster than getting the value
15420 with `org-get-tags-at'. If your function gets properties with
15421 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15422 to t around the call to `org-entry-properties' to get the same speedup.
15423 Note that if your function moves around to retrieve tags and properties at
15424 a *different* entry, you cannot use these techniques."
15425 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15426 (not (org-region-active-p)))
15427 (let* ((org-agenda-archives-mode nil) ; just to make sure
15428 (org-agenda-skip-archived-trees (memq 'archive skip))
15429 (org-agenda-skip-comment-trees (memq 'comment skip))
15430 (org-agenda-skip-function
15431 (car (org-delete-all '(comment archive) skip)))
15432 (org-tags-match-list-sublevels t)
15433 (start-level (eq scope 'region-start-level))
15434 matcher res
15435 org-todo-keywords-for-agenda
15436 org-done-keywords-for-agenda
15437 org-todo-keyword-alist-for-agenda
15438 org-tag-alist-for-agenda
15439 org--matcher-tags-todo-only)
15441 (cond
15442 ((eq match t) (setq matcher t))
15443 ((eq match nil) (setq matcher t))
15444 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15446 (save-excursion
15447 (save-restriction
15448 (cond ((eq scope 'tree)
15449 (org-back-to-heading t)
15450 (org-narrow-to-subtree)
15451 (setq scope nil))
15452 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15453 (org-region-active-p))
15454 ;; If needed, set start-level to a string like "2"
15455 (when start-level
15456 (save-excursion
15457 (goto-char (region-beginning))
15458 (unless (org-at-heading-p) (outline-next-heading))
15459 (setq start-level (org-current-level))))
15460 (narrow-to-region (region-beginning)
15461 (save-excursion
15462 (goto-char (region-end))
15463 (unless (and (bolp) (org-at-heading-p))
15464 (outline-next-heading))
15465 (point)))
15466 (setq scope nil)))
15468 (if (not scope)
15469 (progn
15470 (org-agenda-prepare-buffers
15471 (and buffer-file-name (list buffer-file-name)))
15472 (setq res
15473 (org-scan-tags
15474 func matcher org--matcher-tags-todo-only start-level)))
15475 ;; Get the right scope
15476 (cond
15477 ((and scope (listp scope) (symbolp (car scope)))
15478 (setq scope (eval scope)))
15479 ((eq scope 'agenda)
15480 (setq scope (org-agenda-files t)))
15481 ((eq scope 'agenda-with-archives)
15482 (setq scope (org-agenda-files t))
15483 (setq scope (org-add-archive-files scope)))
15484 ((eq scope 'file)
15485 (setq scope (and buffer-file-name (list buffer-file-name))))
15486 ((eq scope 'file-with-archives)
15487 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15488 (org-agenda-prepare-buffers scope)
15489 (dolist (file scope)
15490 (with-current-buffer (org-find-base-buffer-visiting file)
15491 (save-excursion
15492 (save-restriction
15493 (widen)
15494 (goto-char (point-min))
15495 (setq res
15496 (append
15498 (org-scan-tags
15499 func matcher org--matcher-tags-todo-only))))))))))
15500 res)))
15502 ;;; Properties API
15504 (defconst org-special-properties
15505 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15506 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15507 "The special properties valid in Org mode.
15508 These are properties that are not defined in the property drawer,
15509 but in some other way.")
15511 (defconst org-default-properties
15512 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15513 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15514 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15515 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15516 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15517 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15518 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15519 "Some properties that are used by Org mode for various purposes.
15520 Being in this list makes sure that they are offered for completion.")
15522 (defun org--valid-property-p (property)
15523 "Non nil when string PROPERTY is a valid property name."
15524 (not
15525 (or (equal property "")
15526 (org-string-match-p "\\s-" property))))
15528 (defun org--update-property-plist (key val props)
15529 "Associate KEY to VAL in alist PROPS.
15530 Modifications are made by side-effect. Return new alist."
15531 (let* ((appending (string= (substring key -1) "+"))
15532 (key (if appending (substring key 0 -1) key))
15533 (old (assoc-string key props t)))
15534 (if (not old) (cons (cons key val) props)
15535 (setcdr old (if appending (concat (cdr old) " " val) val))
15536 props)))
15538 (defun org-get-property-block (&optional beg force)
15539 "Return the (beg . end) range of the body of the property drawer.
15540 BEG is the beginning of the current subtree, or of the part
15541 before the first headline. If it is not given, it will be found.
15542 If the drawer does not exist, create it if FORCE is non-nil, or
15543 return nil."
15544 (org-with-wide-buffer
15545 (when beg (goto-char beg))
15546 (unless (org-before-first-heading-p)
15547 (let ((beg (cond (beg)
15548 ((or (not (featurep 'org-inlinetask))
15549 (org-inlinetask-in-task-p))
15550 (org-back-to-heading t))
15551 (t (org-with-limited-levels (org-back-to-heading t))))))
15552 (forward-line)
15553 (when (org-looking-at-p org-planning-line-re) (forward-line))
15554 (cond ((looking-at org-property-drawer-re)
15555 (forward-line)
15556 (cons (point) (progn (goto-char (match-end 0))
15557 (line-beginning-position))))
15558 (force
15559 (goto-char beg)
15560 (org-insert-property-drawer)
15561 (let ((pos (save-excursion (search-forward ":END:")
15562 (line-beginning-position))))
15563 (cons pos pos))))))))
15565 (defun org-at-property-p ()
15566 "Non-nil when point is inside a property drawer.
15567 See `org-property-re' for match data, if applicable."
15568 (save-excursion
15569 (beginning-of-line)
15570 (and (looking-at org-property-re)
15571 (let ((property-drawer (save-match-data (org-get-property-block))))
15572 (and property-drawer
15573 (>= (point) (car property-drawer))
15574 (< (point) (cdr property-drawer)))))))
15576 (defun org-property-action ()
15577 "Do an action on properties."
15578 (interactive)
15579 (unless (org-at-property-p) (user-error "Not at a property"))
15580 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15581 (let ((c (read-char-exclusive)))
15582 (cl-case c
15583 (?s (call-interactively #'org-set-property))
15584 (?d (call-interactively #'org-delete-property))
15585 (?D (call-interactively #'org-delete-property-globally))
15586 (?c (call-interactively #'org-compute-property-at-point))
15587 (otherwise (user-error "No such property action %c" c)))))
15589 (defun org-inc-effort ()
15590 "Increment the value of the effort property in the current entry."
15591 (interactive)
15592 (org-set-effort nil t))
15594 (defvar org-clock-effort) ; Defined in org-clock.el.
15595 (defvar org-clock-current-task) ; Defined in org-clock.el.
15596 (defun org-set-effort (&optional value increment)
15597 "Set the effort property of the current entry.
15598 With numerical prefix arg, use the nth allowed value, 0 stands for the
15599 10th allowed value.
15601 When INCREMENT is non-nil, set the property to the next allowed value."
15602 (interactive "P")
15603 (when (equal value 0) (setq value 10))
15604 (let* ((completion-ignore-case t)
15605 (prop org-effort-property)
15606 (cur (org-entry-get nil prop))
15607 (allowed (org-property-get-allowed-values nil prop 'table))
15608 (existing (mapcar 'list (org-property-values prop)))
15609 (heading (nth 4 (org-heading-components)))
15611 (val (cond
15612 ((stringp value) value)
15613 ((and allowed (integerp value))
15614 (or (car (nth (1- value) allowed))
15615 (car (org-last allowed))))
15616 ((and allowed increment)
15617 (or (cl-caadr (member (list cur) allowed))
15618 (user-error "Allowed effort values are not set")))
15619 (allowed
15620 (message "Select 1-9,0, [RET%s]: %s"
15621 (if cur (concat "=" cur) "")
15622 (mapconcat 'car allowed " "))
15623 (setq rpl (read-char-exclusive))
15624 (if (equal rpl ?\r)
15626 (setq rpl (- rpl ?0))
15627 (when (equal rpl 0) (setq rpl 10))
15628 (if (and (> rpl 0) (<= rpl (length allowed)))
15629 (car (nth (1- rpl) allowed))
15630 (org-completing-read "Effort: " allowed nil))))
15632 (org-completing-read
15633 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15634 (concat "[" cur "]") "")
15635 ": ")
15636 existing nil nil "" nil cur)))))
15637 (unless (equal (org-entry-get nil prop) val)
15638 (org-entry-put nil prop val))
15639 (org-refresh-property
15640 '((effort . identity)
15641 (effort-minutes . org-duration-string-to-minutes))
15642 val)
15643 (when (string= heading org-clock-current-task)
15644 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15645 (org-clock-update-mode-line))
15646 (message "%s is now %s" prop val)))
15648 (defun org-entry-properties (&optional pom which)
15649 "Get all properties of the current entry.
15651 When POM is a buffer position, get all properties from the entry
15652 there instead.
15654 This includes the TODO keyword, the tags, time strings for
15655 deadline, scheduled, and clocking, and any additional properties
15656 defined in the entry.
15658 If WHICH is nil or `all', get all properties. If WHICH is
15659 `special' or `standard', only get that subclass. If WHICH is
15660 a string, only get that property.
15662 Return value is an alist. Keys are properties, as upcased
15663 strings."
15664 (org-with-point-at pom
15665 (when (and (derived-mode-p 'org-mode)
15666 (ignore-errors (org-back-to-heading t)))
15667 (catch 'exit
15668 (let* ((beg (point))
15669 (specific (and (stringp which) (upcase which)))
15670 (which (cond ((not specific) which)
15671 ((member specific org-special-properties) 'special)
15672 (t 'standard)))
15673 props)
15674 ;; Get the special properties, like TODO and TAGS.
15675 (when (memq which '(nil all special))
15676 (when (or (not specific) (string= specific "CLOCKSUM"))
15677 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15678 (when clocksum
15679 (push (cons "CLOCKSUM"
15680 (org-minutes-to-clocksum-string clocksum))
15681 props)))
15682 (when specific (throw 'exit props)))
15683 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15684 (let ((clocksumt (get-text-property (point)
15685 :org-clock-minutes-today)))
15686 (when clocksumt
15687 (push (cons "CLOCKSUM_T"
15688 (org-minutes-to-clocksum-string clocksumt))
15689 props)))
15690 (when specific (throw 'exit props)))
15691 (when (or (not specific) (string= specific "ITEM"))
15692 (when (looking-at org-complex-heading-regexp)
15693 (push (cons "ITEM"
15694 (let ((title (match-string-no-properties 4)))
15695 (if (org-string-nw-p title)
15696 (org-remove-tabs title)
15697 "")))
15698 props))
15699 (when specific (throw 'exit props)))
15700 (when (or (not specific) (string= specific "TODO"))
15701 (let ((case-fold-search nil))
15702 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15703 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15704 (when specific (throw 'exit props)))
15705 (when (or (not specific) (string= specific "PRIORITY"))
15706 (push (cons "PRIORITY"
15707 (if (looking-at org-priority-regexp)
15708 (org-match-string-no-properties 2)
15709 (char-to-string org-default-priority)))
15710 props)
15711 (when specific (throw 'exit props)))
15712 (when (or (not specific) (string= specific "FILE"))
15713 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15714 props)
15715 (when specific (throw 'exit props)))
15716 (when (or (not specific) (string= specific "TAGS"))
15717 (let ((value (org-string-nw-p (org-get-tags-string))))
15718 (when value (push (cons "TAGS" value) props)))
15719 (when specific (throw 'exit props)))
15720 (when (or (not specific) (string= specific "ALLTAGS"))
15721 (let ((value (org-get-tags-at)))
15722 (when value
15723 (push (cons "ALLTAGS"
15724 (format ":%s:" (mapconcat #'identity value ":")))
15725 props)))
15726 (when specific (throw 'exit props)))
15727 (when (or (not specific) (string= specific "BLOCKED"))
15728 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15729 (when specific (throw 'exit props)))
15730 (when (or (not specific)
15731 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15732 (forward-line)
15733 (when (org-looking-at-p org-planning-line-re)
15734 (end-of-line)
15735 (let ((bol (line-beginning-position))
15736 ;; Backward compatibility: time keywords used to
15737 ;; be configurable (before 8.3). Make sure we
15738 ;; get the correct keyword.
15739 (key-assoc `(("CLOSED" . ,org-closed-string)
15740 ("DEADLINE" . ,org-deadline-string)
15741 ("SCHEDULED" . ,org-scheduled-string))))
15742 (dolist (pair (if specific (list (assoc specific key-assoc))
15743 key-assoc))
15744 (save-excursion
15745 (when (search-backward (cdr pair) bol t)
15746 (goto-char (match-end 0))
15747 (skip-chars-forward " \t")
15748 (and (looking-at org-ts-regexp-both)
15749 (push (cons (car pair)
15750 (org-match-string-no-properties 0))
15751 props)))))))
15752 (when specific (throw 'exit props)))
15753 (when (or (not specific)
15754 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15755 (let ((find-ts
15756 (lambda (end ts)
15757 ;; Fix next time-stamp before END. TS is the
15758 ;; list of time-stamps found so far.
15759 (let ((ts ts)
15760 (regexp (cond
15761 ((string= specific "TIMESTAMP")
15762 org-ts-regexp)
15763 ((string= specific "TIMESTAMP_IA")
15764 org-ts-regexp-inactive)
15765 ((assoc "TIMESTAMP_IA" ts)
15766 org-ts-regexp)
15767 ((assoc "TIMESTAMP" ts)
15768 org-ts-regexp-inactive)
15769 (t org-ts-regexp-both))))
15770 (catch 'next
15771 (while (re-search-forward regexp end t)
15772 (backward-char)
15773 (let ((object (org-element-context)))
15774 ;; Accept to match timestamps in node
15775 ;; properties, too.
15776 (when (memq (org-element-type object)
15777 '(node-property timestamp))
15778 (let ((type
15779 (org-element-property :type object)))
15780 (cond
15781 ((and (memq type '(active active-range))
15782 (not (equal specific "TIMESTAMP_IA")))
15783 (unless (assoc "TIMESTAMP" ts)
15784 (push (cons "TIMESTAMP"
15785 (org-element-property
15786 :raw-value object))
15788 (when specific (throw 'exit ts))))
15789 ((and (memq type '(inactive inactive-range))
15790 (not (string= specific "TIMESTAMP")))
15791 (unless (assoc "TIMESTAMP_IA" ts)
15792 (push (cons "TIMESTAMP_IA"
15793 (org-element-property
15794 :raw-value object))
15796 (when specific (throw 'exit ts))))))
15797 ;; Both timestamp types are found,
15798 ;; move to next part.
15799 (when (= (length ts) 2) (throw 'next ts)))))
15800 ts)))))
15801 (goto-char beg)
15802 ;; First look for timestamps within headline.
15803 (let ((ts (funcall find-ts (line-end-position) nil)))
15804 (if (= (length ts) 2) (setq props (nconc ts props))
15805 (forward-line)
15806 ;; Then find timestamps in the section, skipping
15807 ;; planning line.
15808 (when (org-looking-at-p org-planning-line-re)
15809 (forward-line))
15810 (let ((end (save-excursion (outline-next-heading))))
15811 (setq props (nconc (funcall find-ts end ts) props))))))))
15812 ;; Get the standard properties, like :PROP:.
15813 (when (memq which '(nil all standard))
15814 ;; If we are looking after a specific property, delegate
15815 ;; to `org-entry-get', which is faster. However, make an
15816 ;; exception for "CATEGORY", since it can be also set
15817 ;; through keywords (i.e. #+CATEGORY).
15818 (if (and specific (not (equal specific "CATEGORY")))
15819 (let ((value (org-entry-get beg specific nil t)))
15820 (throw 'exit (and value (list (cons specific value)))))
15821 (let ((range (org-get-property-block beg)))
15822 (when range
15823 (let ((end (cdr range)) seen-base)
15824 (goto-char (car range))
15825 ;; Unlike to `org--update-property-plist', we
15826 ;; handle the case where base values is found
15827 ;; after its extension. We also forbid standard
15828 ;; properties to be named as special properties.
15829 (while (re-search-forward org-property-re end t)
15830 (let* ((key (upcase (org-match-string-no-properties 2)))
15831 (extendp (org-string-match-p "\\+\\'" key))
15832 (key-base (if extendp (substring key 0 -1) key))
15833 (value (org-match-string-no-properties 3)))
15834 (cond
15835 ((member-ignore-case key-base org-special-properties))
15836 (extendp
15837 (setq props
15838 (org--update-property-plist key value props)))
15839 ((member key seen-base))
15840 (t (push key seen-base)
15841 (let ((p (assoc-string key props t)))
15842 (if p (setcdr p (concat value " " (cdr p)))
15843 (push (cons key value) props))))))))))))
15844 (unless (assoc "CATEGORY" props)
15845 (push (cons "CATEGORY" (org-get-category beg)) props)
15846 (when (string= specific "CATEGORY") (throw 'exit props)))
15847 ;; Return value.
15848 props)))))
15850 (defun org-property--local-values (property literal-nil)
15851 "Return value for PROPERTY in current entry.
15852 Value is a list whose car is the base value for PROPERTY and cdr
15853 a list of accumulated values. Return nil if neither is found in
15854 the entry. Also return nil when PROPERTY is set to \"nil\",
15855 unless LITERAL-NIL is non-nil."
15856 (let ((range (org-get-property-block)))
15857 (when range
15858 (goto-char (car range))
15859 (let* ((case-fold-search t)
15860 (end (cdr range))
15861 (value
15862 ;; Base value.
15863 (save-excursion
15864 (let ((v (and (re-search-forward
15865 (org-re-property property nil t) end t)
15866 (org-match-string-no-properties 3))))
15867 (list (if literal-nil v (org-not-nil v)))))))
15868 ;; Find additional values.
15869 (let* ((property+ (org-re-property (concat property "+") nil t)))
15870 (while (re-search-forward property+ end t)
15871 (push (org-match-string-no-properties 3) value)))
15872 ;; Return final values.
15873 (and (not (equal value '(nil))) (nreverse value))))))
15875 (defun org-entry-get (pom property &optional inherit literal-nil)
15876 "Get value of PROPERTY for entry or content at point-or-marker POM.
15878 If INHERIT is non-nil and the entry does not have the property,
15879 then also check higher levels of the hierarchy. If INHERIT is
15880 the symbol `selective', use inheritance only if the setting in
15881 `org-use-property-inheritance' selects PROPERTY for inheritance.
15883 If the property is present but empty, the return value is the
15884 empty string. If the property is not present at all, nil is
15885 returned. In any other case, return the value as a string.
15886 Search is case-insensitive.
15888 If LITERAL-NIL is set, return the string value \"nil\" as
15889 a string, do not interpret it as the list atom nil. This is used
15890 for inheritance when a \"nil\" value can supersede a non-nil
15891 value higher up the hierarchy."
15892 (org-with-point-at pom
15893 (cond
15894 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15895 ;; We need a special property. Use `org-entry-properties' to
15896 ;; retrieve it, but specify the wanted property.
15897 (cdr (assoc-string property (org-entry-properties nil property))))
15898 ((and inherit
15899 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15900 (org-entry-get-with-inheritance property literal-nil))
15902 (let* ((local (org-property--local-values property literal-nil))
15903 (value (and local (mapconcat #'identity (delq nil local) " "))))
15904 (if literal-nil value (org-not-nil value)))))))
15906 (defun org-property-or-variable-value (var &optional inherit)
15907 "Check if there is a property fixing the value of VAR.
15908 If yes, return this value. If not, return the current value of the variable."
15909 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15910 (if (and prop (stringp prop) (string-match "\\S-" prop))
15911 (read prop)
15912 (symbol-value var))))
15914 (defun org-entry-delete (pom property)
15915 "Delete PROPERTY from entry at point-or-marker POM.
15916 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15917 non-nil when a property was removed."
15918 (unless (member property org-special-properties)
15919 (org-with-point-at pom
15920 (let ((range (org-get-property-block)))
15921 (when range
15922 (let* ((begin (car range))
15923 (origin (cdr range))
15924 (end (copy-marker origin))
15925 (re (org-re-property
15926 (concat (regexp-quote property) "\\+?") t t)))
15927 (goto-char begin)
15928 (while (re-search-forward re end t)
15929 (delete-region (match-beginning 0) (line-beginning-position 2)))
15930 ;; If drawer is empty, remove it altogether.
15931 (when (= begin end)
15932 (delete-region (line-beginning-position 0)
15933 (line-beginning-position 2)))
15934 ;; Return non-nil if some property was removed.
15935 (prog1 (/= end origin) (set-marker end nil))))))))
15937 ;; Multi-values properties are properties that contain multiple values
15938 ;; These values are assumed to be single words, separated by whitespace.
15939 (defun org-entry-add-to-multivalued-property (pom property value)
15940 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15941 (let* ((old (org-entry-get pom property))
15942 (values (and old (org-split-string old "[ \t]"))))
15943 (setq value (org-entry-protect-space value))
15944 (unless (member value values)
15945 (setq values (append values (list value)))
15946 (org-entry-put pom property
15947 (mapconcat 'identity values " ")))))
15949 (defun org-entry-remove-from-multivalued-property (pom property value)
15950 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15951 (let* ((old (org-entry-get pom property))
15952 (values (and old (org-split-string old "[ \t]"))))
15953 (setq value (org-entry-protect-space value))
15954 (when (member value values)
15955 (setq values (delete value values))
15956 (org-entry-put pom property
15957 (mapconcat 'identity values " ")))))
15959 (defun org-entry-member-in-multivalued-property (pom property value)
15960 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15961 (let* ((old (org-entry-get pom property))
15962 (values (and old (org-split-string old "[ \t]"))))
15963 (setq value (org-entry-protect-space value))
15964 (member value values)))
15966 (defun org-entry-get-multivalued-property (pom property)
15967 "Return a list of values in a multivalued property."
15968 (let* ((value (org-entry-get pom property))
15969 (values (and value (org-split-string value "[ \t]"))))
15970 (mapcar 'org-entry-restore-space values)))
15972 (defun org-entry-put-multivalued-property (pom property &rest values)
15973 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15974 VALUES should be a list of strings. Spaces will be protected."
15975 (org-entry-put pom property
15976 (mapconcat 'org-entry-protect-space values " "))
15977 (let* ((value (org-entry-get pom property))
15978 (values (and value (org-split-string value "[ \t]"))))
15979 (mapcar 'org-entry-restore-space values)))
15981 (defun org-entry-protect-space (s)
15982 "Protect spaces and newline in string S."
15983 (while (string-match " " s)
15984 (setq s (replace-match "%20" t t s)))
15985 (while (string-match "\n" s)
15986 (setq s (replace-match "%0A" t t s)))
15989 (defun org-entry-restore-space (s)
15990 "Restore spaces and newline in string S."
15991 (while (string-match "%20" s)
15992 (setq s (replace-match " " t t s)))
15993 (while (string-match "%0A" s)
15994 (setq s (replace-match "\n" t t s)))
15997 (defvar org-entry-property-inherited-from (make-marker)
15998 "Marker pointing to the entry from where a property was inherited.
15999 Each call to `org-entry-get-with-inheritance' will set this marker to the
16000 location of the entry where the inheritance search matched. If there was
16001 no match, the marker will point nowhere.
16002 Note that also `org-entry-get' calls this function, if the INHERIT flag
16003 is set.")
16005 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16006 "Get PROPERTY of entry or content at point, search higher levels if needed.
16007 The search will stop at the first ancestor which has the property defined.
16008 If the value found is \"nil\", return nil to show that the property
16009 should be considered as undefined (this is the meaning of nil here).
16010 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16011 (move-marker org-entry-property-inherited-from nil)
16012 (org-with-wide-buffer
16013 (let (value)
16014 (catch 'exit
16015 (while t
16016 (let ((v (org-property--local-values property literal-nil)))
16017 (when v
16018 (setq value
16019 (concat (mapconcat #'identity (delq nil v) " ")
16020 (and value " ")
16021 value)))
16022 (cond
16023 ((car v)
16024 (org-back-to-heading t)
16025 (move-marker org-entry-property-inherited-from (point))
16026 (throw 'exit nil))
16027 ((org-up-heading-safe))
16029 (let ((global
16030 (cdr (or (assoc-string property org-file-properties t)
16031 (assoc-string property org-global-properties t)
16032 (assoc-string property org-global-properties-fixed t)))))
16033 (cond ((not global))
16034 (value (setq value (concat global " " value)))
16035 (t (setq value global))))
16036 (throw 'exit nil))))))
16037 (if literal-nil value (org-not-nil value)))))
16039 (defvar org-property-changed-functions nil
16040 "Hook called when the value of a property has changed.
16041 Each hook function should accept two arguments, the name of the property
16042 and the new value.")
16044 (defun org-entry-put (pom property value)
16045 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16047 If the value is nil, it is converted to the empty string. If it
16048 is not a string, an error is raised. Also raise an error on
16049 invalid property names.
16051 PROPERTY can be any regular property (see
16052 `org-special-properties'). It can also be \"TODO\",
16053 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16055 For the last two properties, VALUE may have any of the special
16056 values \"earlier\" and \"later\". The function then increases or
16057 decreases scheduled or deadline date by one day."
16058 (cond ((null value) (setq value ""))
16059 ((not (stringp value)) (error "Properties values should be strings"))
16060 ((not (org--valid-property-p property))
16061 (user-error "Invalid property name: \"%s\"" property)))
16062 (org-with-point-at pom
16063 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16064 (org-back-to-heading t)
16065 (org-with-limited-levels (org-back-to-heading t)))
16066 (let ((beg (point)))
16067 (cond
16068 ((equal property "TODO")
16069 (cond ((not (org-string-nw-p value)) (setq value 'none))
16070 ((not (member value org-todo-keywords-1))
16071 (user-error "\"%s\" is not a valid TODO state" value)))
16072 (org-todo value)
16073 (org-set-tags nil 'align))
16074 ((equal property "PRIORITY")
16075 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16076 (org-set-tags nil 'align))
16077 ((equal property "SCHEDULED")
16078 (forward-line)
16079 (if (and (org-looking-at-p org-planning-line-re)
16080 (re-search-forward
16081 org-scheduled-time-regexp (line-end-position) t))
16082 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16083 ((string= value "later") (org-timestamp-change 1 'day))
16084 ((string= value "") (org-schedule '(4)))
16085 (t (org-schedule nil value)))
16086 (if (member value '("earlier" "later" ""))
16087 (call-interactively #'org-schedule)
16088 (org-schedule nil value))))
16089 ((equal property "DEADLINE")
16090 (forward-line)
16091 (if (and (org-looking-at-p org-planning-line-re)
16092 (re-search-forward
16093 org-deadline-time-regexp (line-end-position) t))
16094 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16095 ((string= value "later") (org-timestamp-change 1 'day))
16096 ((string= value "") (org-deadline '(4)))
16097 (t (org-deadline nil value)))
16098 (if (member value '("earlier" "later" ""))
16099 (call-interactively #'org-deadline)
16100 (org-deadline nil value))))
16101 ((member property org-special-properties)
16102 (error "The %s property cannot be set with `org-entry-put'" property))
16104 (let* ((range (org-get-property-block beg 'force))
16105 (end (cdr range))
16106 (case-fold-search t))
16107 (goto-char (car range))
16108 (if (re-search-forward (org-re-property property nil t) end t)
16109 (progn (delete-region (match-beginning 0) (match-end 0))
16110 (goto-char (match-beginning 0)))
16111 (goto-char end)
16112 (insert "\n")
16113 (backward-char))
16114 (insert ":" property ":")
16115 (when value (insert " " value))
16116 (org-indent-line)))))
16117 (run-hook-with-args 'org-property-changed-functions property value)))
16119 (defun org-buffer-property-keys
16120 (&optional specials defaults columns ignore-malformed)
16121 "Get all property keys in the current buffer.
16123 When SPECIALS is non-nil, also list the special properties that
16124 reflect things like tags and TODO state.
16126 When DEFAULTS is non-nil, also include properties that has
16127 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16128 DESCRIPTION, LOCATION, and LOGGING and others.
16130 When COLUMNS in non-nil, also include property names given in
16131 COLUMN formats in the current buffer.
16133 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16134 automatically performed, such drawers will be silently ignored."
16135 (let ((case-fold-search t)
16136 (props (append
16137 (and specials org-special-properties)
16138 (and defaults (cons org-effort-property org-default-properties))
16139 nil)))
16140 (org-with-wide-buffer
16141 (goto-char (point-min))
16142 (while (re-search-forward org-property-start-re nil t)
16143 (let ((range (org-get-property-block)))
16144 (catch 'skip
16145 (unless range
16146 (when (and (not ignore-malformed)
16147 (not (org-before-first-heading-p))
16148 (y-or-n-p (format "Malformed drawer at %d, repair?"
16149 (line-beginning-position))))
16150 (org-get-property-block nil t))
16151 (throw 'skip nil))
16152 (goto-char (car range))
16153 (let ((begin (car range))
16154 (end (cdr range)))
16155 ;; Make sure that found property block is not located
16156 ;; before current point, as it would generate an infloop.
16157 ;; It can happen, for example, in the following
16158 ;; situation:
16160 ;; * Headline
16161 ;; :PROPERTIES:
16162 ;; ...
16163 ;; :END:
16164 ;; *************** Inlinetask
16165 ;; #+BEGIN_EXAMPLE
16166 ;; :PROPERTIES:
16167 ;; #+END_EXAMPLE
16169 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16170 (while (< (point) end)
16171 (let ((p (progn (looking-at org-property-re)
16172 (org-match-string-no-properties 2))))
16173 ;; Only add true property name, not extension symbol.
16174 (push (if (not (org-string-match-p "\\+\\'" p)) p
16175 (substring p 0 -1))
16176 props))
16177 (forward-line))))
16178 (outline-next-heading)))
16179 (when columns
16180 (goto-char (point-min))
16181 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16182 (let ((element (org-element-at-point)))
16183 (when (memq (org-element-type element) '(keyword node-property))
16184 (let ((value (org-element-property :value element))
16185 (start 0))
16186 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16187 (setq start (match-end 0))
16188 (let ((p (org-match-string-no-properties 1 value)))
16189 (unless (member-ignore-case p org-special-properties)
16190 (push p props))))))))))
16191 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16193 (defun org-property-values (key)
16194 "List all non-nil values of property KEY in current buffer."
16195 (org-with-wide-buffer
16196 (goto-char (point-min))
16197 (let ((case-fold-search t)
16198 (re (org-re-property key))
16199 values)
16200 (while (re-search-forward re nil t)
16201 (push (org-entry-get (point) key) values))
16202 (delete-dups values))))
16204 (defun org-insert-property-drawer ()
16205 "Insert a property drawer into the current entry."
16206 (org-with-wide-buffer
16207 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16208 (org-back-to-heading t)
16209 (org-with-limited-levels (org-back-to-heading t)))
16210 (forward-line)
16211 (when (org-looking-at-p org-planning-line-re) (forward-line))
16212 (unless (org-looking-at-p org-property-drawer-re)
16213 ;; Make sure we start editing a line from current entry, not from
16214 ;; next one. It prevents extending text properties or overlays
16215 ;; belonging to the latter.
16216 (when (bolp) (backward-char))
16217 (let ((begin (1+ (point)))
16218 (inhibit-read-only t))
16219 (insert "\n:PROPERTIES:\n:END:")
16220 (when (eobp) (insert "\n"))
16221 (org-indent-region begin (point))))))
16223 (defun org-insert-drawer (&optional arg drawer)
16224 "Insert a drawer at point.
16226 When optional argument ARG is non-nil, insert a property drawer.
16228 Optional argument DRAWER, when non-nil, is a string representing
16229 drawer's name. Otherwise, the user is prompted for a name.
16231 If a region is active, insert the drawer around that region
16232 instead.
16234 Point is left between drawer's boundaries."
16235 (interactive "P")
16236 (let* ((drawer (if arg "PROPERTIES"
16237 (or drawer (read-from-minibuffer "Drawer: ")))))
16238 (cond
16239 ;; With C-u, fall back on `org-insert-property-drawer'
16240 (arg (org-insert-property-drawer))
16241 ;; Check validity of suggested drawer's name.
16242 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16243 (user-error "Invalid drawer name"))
16244 ;; With an active region, insert a drawer at point.
16245 ((not (org-region-active-p))
16246 (progn
16247 (unless (bolp) (insert "\n"))
16248 (insert (format ":%s:\n\n:END:\n" drawer))
16249 (forward-line -2)))
16250 ;; Otherwise, insert the drawer at point
16252 (let ((rbeg (region-beginning))
16253 (rend (copy-marker (region-end))))
16254 (unwind-protect
16255 (progn
16256 (goto-char rbeg)
16257 (beginning-of-line)
16258 (when (save-excursion
16259 (re-search-forward org-outline-regexp-bol rend t))
16260 (user-error "Drawers cannot contain headlines"))
16261 ;; Position point at the beginning of the first
16262 ;; non-blank line in region. Insert drawer's opening
16263 ;; there, then indent it.
16264 (org-skip-whitespace)
16265 (beginning-of-line)
16266 (insert ":" drawer ":\n")
16267 (forward-line -1)
16268 (indent-for-tab-command)
16269 ;; Move point to the beginning of the first blank line
16270 ;; after the last non-blank line in region. Insert
16271 ;; drawer's closing, then indent it.
16272 (goto-char rend)
16273 (skip-chars-backward " \r\t\n")
16274 (insert "\n:END:")
16275 (deactivate-mark t)
16276 (indent-for-tab-command)
16277 (unless (eolp) (insert "\n")))
16278 ;; Clear marker, whatever the outcome of insertion is.
16279 (set-marker rend nil)))))))
16281 (defvar org-property-set-functions-alist nil
16282 "Property set function alist.
16283 Each entry should have the following format:
16285 (PROPERTY . READ-FUNCTION)
16287 The read function will be called with the same argument as
16288 `org-completing-read'.")
16290 (defun org-set-property-function (property)
16291 "Get the function that should be used to set PROPERTY.
16292 This is computed according to `org-property-set-functions-alist'."
16293 (or (cdr (assoc property org-property-set-functions-alist))
16294 'org-completing-read))
16296 (defun org-read-property-value (property)
16297 "Read PROPERTY value from user."
16298 (let* ((completion-ignore-case t)
16299 (allowed (org-property-get-allowed-values nil property 'table))
16300 (cur (org-entry-get nil property))
16301 (prompt (concat property " value"
16302 (if (and cur (string-match "\\S-" cur))
16303 (concat " [" cur "]") "") ": "))
16304 (set-function (org-set-property-function property))
16305 (val (if allowed
16306 (funcall set-function prompt allowed nil
16307 (not (get-text-property 0 'org-unrestricted
16308 (caar allowed))))
16309 (funcall set-function prompt
16310 (mapcar 'list (org-property-values property))
16311 nil nil "" nil cur))))
16312 (org-trim val)))
16314 (defvar org-last-set-property nil)
16315 (defvar org-last-set-property-value nil)
16316 (defun org-read-property-name ()
16317 "Read a property name."
16318 (let ((completion-ignore-case t)
16319 (default-prop (or (and (org-at-property-p)
16320 (org-match-string-no-properties 2))
16321 org-last-set-property)))
16322 (org-completing-read
16323 (concat "Property"
16324 (if default-prop (concat " [" default-prop "]") "")
16325 ": ")
16326 (mapcar #'list (org-buffer-property-keys nil t t))
16327 nil nil nil nil default-prop)))
16329 (defun org-set-property-and-value (use-last)
16330 "Allow to set [PROPERTY]: [value] direction from prompt.
16331 When use-default, don't even ask, just use the last
16332 \"[PROPERTY]: [value]\" string from the history."
16333 (interactive "P")
16334 (let* ((completion-ignore-case t)
16335 (pv (or (and use-last org-last-set-property-value)
16336 (org-completing-read
16337 "Enter a \"[Property]: [value]\" pair: "
16338 nil nil nil nil nil
16339 org-last-set-property-value)))
16340 prop val)
16341 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16342 (setq prop (match-string 1 pv)
16343 val (match-string 2 pv))
16344 (org-set-property prop val))))
16346 (defun org-set-property (property value)
16347 "In the current entry, set PROPERTY to VALUE.
16349 When called interactively, this will prompt for a property name, offering
16350 completion on existing and default properties. And then it will prompt
16351 for a value, offering completion either on allowed values (via an inherited
16352 xxx_ALL property) or on existing values in other instances of this property
16353 in the current file.
16355 Throw an error when trying to set a property with an invalid name."
16356 (interactive (list nil nil))
16357 (let ((property (or property (org-read-property-name))))
16358 ;; `org-entry-put' also makes the following check, but this one
16359 ;; avoids polluting `org-last-set-property' and
16360 ;; `org-last-set-property-value' needlessly.
16361 (unless (org--valid-property-p property)
16362 (user-error "Invalid property name: \"%s\"" property))
16363 (let ((value (or value (org-read-property-value property)))
16364 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16365 (setq org-last-set-property property)
16366 (setq org-last-set-property-value (concat property ": " value))
16367 ;; Possibly postprocess the inserted value:
16368 (when fn (setq value (funcall fn value)))
16369 (unless (equal (org-entry-get nil property) value)
16370 (org-entry-put nil property value)))))
16372 (defun org-find-property (property &optional value)
16373 "Find first entry in buffer that sets PROPERTY.
16375 When optional argument VALUE is non-nil, only consider an entry
16376 if it contains PROPERTY set to this value. If PROPERTY should be
16377 explicitly set to nil, use string \"nil\" for VALUE.
16379 Return position where the entry begins, or nil if there is no
16380 such entry. If narrowing is in effect, only search the visible
16381 part of the buffer."
16382 (save-excursion
16383 (goto-char (point-min))
16384 (let ((case-fold-search t)
16385 (re (org-re-property property nil (not value) value)))
16386 (catch 'exit
16387 (while (re-search-forward re nil t)
16388 (when (if value (org-at-property-p)
16389 (org-entry-get (point) property nil t))
16390 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16392 (defun org-delete-property (property)
16393 "In the current entry, delete PROPERTY."
16394 (interactive
16395 (let* ((completion-ignore-case t)
16396 (cat (org-entry-get (point) "CATEGORY"))
16397 (props0 (org-entry-properties nil 'standard))
16398 (props (if cat props0
16399 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16400 (prop (if (< 1 (length props))
16401 (completing-read "Property: " props nil t)
16402 (caar props))))
16403 (list prop)))
16404 (if (not property)
16405 (message "No property to delete in this entry")
16406 (org-entry-delete nil property)
16407 (message "Property \"%s\" deleted" property)))
16409 (defun org-delete-property-globally (property)
16410 "Remove PROPERTY globally, from all entries.
16411 This function ignores narrowing, if any."
16412 (interactive
16413 (let* ((completion-ignore-case t)
16414 (prop (completing-read
16415 "Globally remove property: "
16416 (mapcar #'list (org-buffer-property-keys)))))
16417 (list prop)))
16418 (org-with-wide-buffer
16419 (goto-char (point-min))
16420 (let ((count 0)
16421 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16422 (while (re-search-forward re nil t)
16423 (when (org-entry-delete (point) property) (cl-incf count)))
16424 (message "Property \"%s\" removed from %d entries" property count))))
16426 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16428 (defun org-compute-property-at-point ()
16429 "Compute the property at point.
16430 This looks for an enclosing column format, extracts the operator and
16431 then applies it to the property in the column format's scope."
16432 (interactive)
16433 (unless (org-at-property-p)
16434 (user-error "Not at a property"))
16435 (let ((prop (org-match-string-no-properties 2)))
16436 (org-columns-get-format-and-top-level)
16437 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16438 (user-error "No operator defined for property %s" prop))
16439 (org-columns-compute prop)))
16441 (defvar org-property-allowed-value-functions nil
16442 "Hook for functions supplying allowed values for a specific property.
16443 The functions must take a single argument, the name of the property, and
16444 return a flat list of allowed values. If \":ETC\" is one of
16445 the values, this means that these values are intended as defaults for
16446 completion, but that other values should be allowed too.
16447 The functions must return nil if they are not responsible for this
16448 property.")
16450 (defun org-property-get-allowed-values (pom property &optional table)
16451 "Get allowed values for the property PROPERTY.
16452 When TABLE is non-nil, return an alist that can directly be used for
16453 completion."
16454 (let (vals)
16455 (cond
16456 ((equal property "TODO")
16457 (setq vals (org-with-point-at pom
16458 (append org-todo-keywords-1 '("")))))
16459 ((equal property "PRIORITY")
16460 (let ((n org-lowest-priority))
16461 (while (>= n org-highest-priority)
16462 (push (char-to-string n) vals)
16463 (setq n (1- n)))))
16464 ((equal property "CATEGORY"))
16465 ((member property org-special-properties))
16466 ((setq vals (run-hook-with-args-until-success
16467 'org-property-allowed-value-functions property)))
16469 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16470 (when (and vals (string-match "\\S-" vals))
16471 (setq vals (car (read-from-string (concat "(" vals ")"))))
16472 (setq vals (mapcar (lambda (x)
16473 (cond ((stringp x) x)
16474 ((numberp x) (number-to-string x))
16475 ((symbolp x) (symbol-name x))
16476 (t "???")))
16477 vals)))))
16478 (when (member ":ETC" vals)
16479 (setq vals (remove ":ETC" vals))
16480 (org-add-props (car vals) '(org-unrestricted t)))
16481 (if table (mapcar 'list vals) vals)))
16483 (defun org-property-previous-allowed-value (&optional _previous)
16484 "Switch to the next allowed value for this property."
16485 (interactive)
16486 (org-property-next-allowed-value t))
16488 (defun org-property-next-allowed-value (&optional previous)
16489 "Switch to the next allowed value for this property."
16490 (interactive)
16491 (unless (org-at-property-p)
16492 (user-error "Not at a property"))
16493 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16494 (key (match-string 2))
16495 (value (match-string 3))
16496 (allowed (or (org-property-get-allowed-values (point) key)
16497 (and (member value '("[ ]" "[-]" "[X]"))
16498 '("[ ]" "[X]"))))
16499 (heading (save-match-data (nth 4 (org-heading-components))))
16500 nval)
16501 (unless allowed
16502 (user-error "Allowed values for this property have not been defined"))
16503 (when previous (setq allowed (reverse allowed)))
16504 (when (member value allowed)
16505 (setq nval (car (cdr (member value allowed)))))
16506 (setq nval (or nval (car allowed)))
16507 (when (equal nval value)
16508 (user-error "Only one allowed value for this property"))
16509 (org-at-property-p)
16510 (replace-match (concat " :" key ": " nval) t t)
16511 (org-indent-line)
16512 (beginning-of-line 1)
16513 (skip-chars-forward " \t")
16514 (when (equal prop org-effort-property)
16515 (org-refresh-property
16516 '((effort . identity)
16517 (effort-minutes . org-duration-string-to-minutes))
16518 nval)
16519 (when (string= org-clock-current-task heading)
16520 (setq org-clock-effort nval)
16521 (org-clock-update-mode-line)))
16522 (run-hook-with-args 'org-property-changed-functions key nval)))
16524 (defun org-find-olp (path &optional this-buffer)
16525 "Return a marker pointing to the entry at outline path OLP.
16526 If anything goes wrong, throw an error.
16527 You can wrap this call to catch the error like this:
16529 \(condition-case msg
16530 \(org-mobile-locate-entry (match-string 4))
16531 \(error (nth 1 msg)))
16533 The return value will then be either a string with the error message,
16534 or a marker if everything is OK.
16536 If THIS-BUFFER is set, the outline path does not contain a file,
16537 only headings."
16538 (let* ((file (if this-buffer buffer-file-name (pop path)))
16539 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16540 (level 1)
16541 (lmin 1)
16542 (lmax 1)
16543 end found flevel)
16544 (unless buffer (error "File not found :%s" file))
16545 (with-current-buffer buffer
16546 (org-with-wide-buffer
16547 (goto-char (point-min))
16548 (dolist (heading path)
16549 (let ((re (format org-complex-heading-regexp-format
16550 (regexp-quote heading)))
16551 (cnt 0))
16552 (while (re-search-forward re end t)
16553 (setq level (- (match-end 1) (match-beginning 1)))
16554 (when (and (>= level lmin) (<= level lmax))
16555 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16556 (when (= cnt 0)
16557 (error "Heading not found on level %d: %s" lmax heading))
16558 (when (> cnt 1)
16559 (error "Heading not unique on level %d: %s" lmax heading))
16560 (goto-char found)
16561 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16562 (setq end (save-excursion (org-end-of-subtree t t)))))
16563 (when (org-at-heading-p)
16564 (point-marker))))))
16566 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16567 "Find node HEADING in BUFFER.
16568 Return a marker to the heading if it was found, or nil if not.
16569 If POS-ONLY is set, return just the position instead of a marker.
16571 The heading text must match exact, but it may have a TODO keyword,
16572 a priority cookie and tags in the standard locations."
16573 (with-current-buffer (or buffer (current-buffer))
16574 (save-excursion
16575 (save-restriction
16576 (widen)
16577 (goto-char (point-min))
16578 (let (case-fold-search)
16579 (when (re-search-forward
16580 (format org-complex-heading-regexp-format
16581 (regexp-quote heading)) nil t)
16582 (if pos-only
16583 (match-beginning 0)
16584 (move-marker (make-marker) (match-beginning 0)))))))))
16586 (defun org-find-exact-heading-in-directory (heading &optional dir)
16587 "Find Org node headline HEADING in all .org files in directory DIR.
16588 When the target headline is found, return a marker to this location."
16589 (let ((files (directory-files (or dir default-directory)
16590 t "\\`[^.#].*\\.org\\'"))
16591 visiting m buffer)
16592 (catch 'found
16593 (dolist (file files)
16594 (message "trying %s" file)
16595 (setq visiting (org-find-base-buffer-visiting file))
16596 (setq buffer (or visiting (find-file-noselect file)))
16597 (setq m (org-find-exact-headline-in-buffer
16598 heading buffer))
16599 (when (and (not m) (not visiting)) (kill-buffer buffer))
16600 (and m (throw 'found m))))))
16602 (defun org-find-entry-with-id (ident)
16603 "Locate the entry that contains the ID property with exact value IDENT.
16604 IDENT can be a string, a symbol or a number, this function will search for
16605 the string representation of it.
16606 Return the position where this entry starts, or nil if there is no such entry."
16607 (interactive "sID: ")
16608 (let ((id (cond
16609 ((stringp ident) ident)
16610 ((symbolp ident) (symbol-name ident))
16611 ((numberp ident) (number-to-string ident))
16612 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16613 (org-with-wide-buffer (org-find-property "ID" id))))
16615 ;;;; Timestamps
16617 (defvar org-last-changed-timestamp nil)
16618 (defvar org-last-inserted-timestamp nil
16619 "The last time stamp inserted with `org-insert-time-stamp'.")
16620 (defvar org-ts-what) ; dynamically scoped parameter
16622 (defun org-time-stamp (arg &optional inactive)
16623 "Prompt for a date/time and insert a time stamp.
16625 If the user specifies a time like HH:MM or if this command is
16626 called with at least one prefix argument, the time stamp contains
16627 the date and the time. Otherwise, only the date is included.
16629 All parts of a date not specified by the user are filled in from
16630 the timestamp at point, if any, or the current date/time
16631 otherwise.
16633 If there is already a timestamp at the cursor, it is replaced.
16635 With two universal prefix arguments, insert an active timestamp
16636 with the current time without prompting the user.
16638 When called from lisp, the timestamp is inactive if INACTIVE is
16639 non-nil."
16640 (interactive "P")
16641 (let* ((ts (cond
16642 ((org-at-date-range-p t)
16643 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16644 ((org-at-timestamp-p t) (match-string 0))))
16645 ;; Default time is either the timestamp at point or today.
16646 ;; When entering a range, only the range start is considered.
16647 (default-time (if (not ts) (current-time)
16648 (apply #'encode-time (org-parse-time-string ts))))
16649 (default-input (and ts (org-get-compact-tod ts)))
16650 (repeater (and ts
16651 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16652 (match-string 0 ts)))
16653 org-time-was-given
16654 org-end-time-was-given
16655 (time
16656 (and (if (equal arg '(16)) (current-time)
16657 ;; Preserve `this-command' and `last-command'.
16658 (let ((this-command this-command)
16659 (last-command last-command))
16660 (org-read-date
16661 arg 'totime nil nil default-time default-input
16662 inactive))))))
16663 (cond
16664 ((and ts
16665 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16666 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16667 (insert "--")
16668 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16670 ;; Make sure we're on a timestamp. When in the middle of a date
16671 ;; range, move arbitrarily to range end.
16672 (unless (org-at-timestamp-p t)
16673 (skip-chars-forward "-")
16674 (org-at-timestamp-p t))
16675 (replace-match "")
16676 (setq org-last-changed-timestamp
16677 (org-insert-time-stamp
16678 time (or org-time-was-given arg)
16679 inactive nil nil (list org-end-time-was-given)))
16680 (when repeater
16681 (backward-char)
16682 (insert " " repeater)
16683 (setq org-last-changed-timestamp
16684 (concat (substring org-last-inserted-timestamp 0 -1)
16685 " " repeater ">")))
16686 (message "Timestamp updated"))
16687 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16688 (t (org-insert-time-stamp
16689 time (or org-time-was-given arg) inactive nil nil
16690 (list org-end-time-was-given))))))
16692 ;; FIXME: can we use this for something else, like computing time differences?
16693 (defun org-get-compact-tod (s)
16694 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16695 (let* ((t1 (match-string 1 s))
16696 (h1 (string-to-number (match-string 2 s)))
16697 (m1 (string-to-number (match-string 3 s)))
16698 (t2 (and (match-end 4) (match-string 5 s)))
16699 (h2 (and t2 (string-to-number (match-string 6 s))))
16700 (m2 (and t2 (string-to-number (match-string 7 s))))
16701 dh dm)
16702 (if (not t2)
16704 (setq dh (- h2 h1) dm (- m2 m1))
16705 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16706 (concat t1 "+" (number-to-string dh)
16707 (and (/= 0 dm) (format ":%02d" dm)))))))
16709 (defun org-time-stamp-inactive (&optional arg)
16710 "Insert an inactive time stamp.
16711 An inactive time stamp is enclosed in square brackets instead of angle
16712 brackets. It is inactive in the sense that it does not trigger agenda entries,
16713 does not link to the calendar and cannot be changed with the S-cursor keys.
16714 So these are more for recording a certain time/date."
16715 (interactive "P")
16716 (org-time-stamp arg 'inactive))
16718 (defvar org-date-ovl (make-overlay 1 1))
16719 (overlay-put org-date-ovl 'face 'org-date-selected)
16720 (org-detach-overlay org-date-ovl)
16722 (defvar org-ans1) ; dynamically scoped parameter
16723 (defvar org-ans2) ; dynamically scoped parameter
16725 (defvar org-plain-time-of-day-regexp) ; defined below
16727 (defvar org-overriding-default-time nil) ; dynamically scoped
16728 (defvar org-read-date-overlay nil)
16729 (defvar org-dcst nil) ; dynamically scoped
16730 (defvar org-read-date-history nil)
16731 (defvar org-read-date-final-answer nil)
16732 (defvar org-read-date-analyze-futurep nil)
16733 (defvar org-read-date-analyze-forced-year nil)
16734 (defvar org-read-date-inactive)
16736 (defvar org-read-date-minibuffer-local-map
16737 (let* ((map (make-sparse-keymap)))
16738 (set-keymap-parent map minibuffer-local-map)
16739 (org-defkey map (kbd ".")
16740 (lambda () (interactive)
16741 ;; Are we at the beginning of the prompt?
16742 (if (org-looking-back "^[^:]+: "
16743 (let ((inhibit-field-text-motion t))
16744 (line-beginning-position)))
16745 (org-eval-in-calendar '(calendar-goto-today))
16746 (insert "."))))
16747 (org-defkey map (kbd "C-.")
16748 (lambda () (interactive)
16749 (org-eval-in-calendar '(calendar-goto-today))))
16750 (org-defkey map [(meta shift left)]
16751 (lambda () (interactive)
16752 (org-eval-in-calendar '(calendar-backward-month 1))))
16753 (org-defkey map [(meta shift right)]
16754 (lambda () (interactive)
16755 (org-eval-in-calendar '(calendar-forward-month 1))))
16756 (org-defkey map [(meta shift up)]
16757 (lambda () (interactive)
16758 (org-eval-in-calendar '(calendar-backward-year 1))))
16759 (org-defkey map [(meta shift down)]
16760 (lambda () (interactive)
16761 (org-eval-in-calendar '(calendar-forward-year 1))))
16762 (org-defkey map [?\e (shift left)]
16763 (lambda () (interactive)
16764 (org-eval-in-calendar '(calendar-backward-month 1))))
16765 (org-defkey map [?\e (shift right)]
16766 (lambda () (interactive)
16767 (org-eval-in-calendar '(calendar-forward-month 1))))
16768 (org-defkey map [?\e (shift up)]
16769 (lambda () (interactive)
16770 (org-eval-in-calendar '(calendar-backward-year 1))))
16771 (org-defkey map [?\e (shift down)]
16772 (lambda () (interactive)
16773 (org-eval-in-calendar '(calendar-forward-year 1))))
16774 (org-defkey map [(shift up)]
16775 (lambda () (interactive)
16776 (org-eval-in-calendar '(calendar-backward-week 1))))
16777 (org-defkey map [(shift down)]
16778 (lambda () (interactive)
16779 (org-eval-in-calendar '(calendar-forward-week 1))))
16780 (org-defkey map [(shift left)]
16781 (lambda () (interactive)
16782 (org-eval-in-calendar '(calendar-backward-day 1))))
16783 (org-defkey map [(shift right)]
16784 (lambda () (interactive)
16785 (org-eval-in-calendar '(calendar-forward-day 1))))
16786 (org-defkey map "!"
16787 (lambda () (interactive)
16788 (org-eval-in-calendar '(diary-view-entries))
16789 (message "")))
16790 (org-defkey map ">"
16791 (lambda () (interactive)
16792 (org-eval-in-calendar '(calendar-scroll-left 1))))
16793 (org-defkey map "<"
16794 (lambda () (interactive)
16795 (org-eval-in-calendar '(calendar-scroll-right 1))))
16796 (org-defkey map "\C-v"
16797 (lambda () (interactive)
16798 (org-eval-in-calendar
16799 '(calendar-scroll-left-three-months 1))))
16800 (org-defkey map "\M-v"
16801 (lambda () (interactive)
16802 (org-eval-in-calendar
16803 '(calendar-scroll-right-three-months 1))))
16804 map)
16805 "Keymap for minibuffer commands when using `org-read-date'.")
16807 (defvar org-def)
16808 (defvar org-defdecode)
16809 (defvar org-with-time)
16811 (defvar calendar-setup) ; Dynamically scoped.
16812 (defun org-read-date (&optional with-time to-time from-string prompt
16813 default-time default-input inactive)
16814 "Read a date, possibly a time, and make things smooth for the user.
16815 The prompt will suggest to enter an ISO date, but you can also enter anything
16816 which will at least partially be understood by `parse-time-string'.
16817 Unrecognized parts of the date will default to the current day, month, year,
16818 hour and minute. If this command is called to replace a timestamp at point,
16819 or to enter the second timestamp of a range, the default time is taken
16820 from the existing stamp. Furthermore, the command prefers the future,
16821 so if you are giving a date where the year is not given, and the day-month
16822 combination is already past in the current year, it will assume you
16823 mean next year. For details, see the manual. A few examples:
16825 3-2-5 --> 2003-02-05
16826 feb 15 --> currentyear-02-15
16827 2/15 --> currentyear-02-15
16828 sep 12 9 --> 2009-09-12
16829 12:45 --> today 12:45
16830 22 sept 0:34 --> currentyear-09-22 0:34
16831 12 --> currentyear-currentmonth-12
16832 Fri --> nearest Friday after today
16833 -Tue --> last Tuesday
16834 etc.
16836 Furthermore you can specify a relative date by giving, as the *first* thing
16837 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16838 change in days weeks, months, years.
16839 With a single plus or minus, the date is relative to today. With a double
16840 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16841 +4d --> four days from today
16842 +4 --> same as above
16843 +2w --> two weeks from today
16844 ++5 --> five days from default date
16846 The function understands only English month and weekday abbreviations.
16848 While prompting, a calendar is popped up - you can also select the
16849 date with the mouse (button 1). The calendar shows a period of three
16850 months. To scroll it to other months, use the keys `>' and `<'.
16851 If you don't like the calendar, turn it off with
16852 (setq org-read-date-popup-calendar nil)
16854 With optional argument TO-TIME, the date will immediately be converted
16855 to an internal time.
16856 With an optional argument WITH-TIME, the prompt will suggest to
16857 also insert a time. Note that when WITH-TIME is not set, you can
16858 still enter a time, and this function will inform the calling routine
16859 about this change. The calling routine may then choose to change the
16860 format used to insert the time stamp into the buffer to include the time.
16861 With optional argument FROM-STRING, read from this string instead from
16862 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16863 the time/date that is used for everything that is not specified by the
16864 user."
16865 (require 'parse-time)
16866 (let* ((org-with-time with-time)
16867 (org-time-stamp-rounding-minutes
16868 (if (equal org-with-time '(16))
16869 '(0 0)
16870 org-time-stamp-rounding-minutes))
16871 (org-dcst org-display-custom-times)
16872 (ct (org-current-time))
16873 (org-def (or org-overriding-default-time default-time ct))
16874 (org-defdecode (decode-time org-def))
16875 (cur-frame (selected-frame))
16876 (mouse-autoselect-window nil) ; Don't let the mouse jump
16877 (calendar-setup
16878 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16879 (calendar-move-hook nil)
16880 (calendar-view-diary-initially-flag nil)
16881 (calendar-view-holidays-initially-flag nil)
16882 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16883 ;; Rationalize `org-def' and `org-defdecode', if required.
16884 (when (< (nth 2 org-defdecode) org-extend-today-until)
16885 (setf (nth 2 org-defdecode) -1)
16886 (setf (nth 1 org-defdecode) 59)
16887 (setq org-def (apply #'encode-time org-defdecode))
16888 (setq org-defdecode (decode-time org-def)))
16889 (let* ((timestr (format-time-string
16890 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16891 org-def))
16892 (prompt (concat (if prompt (concat prompt " ") "")
16893 (format "Date+time [%s]: " timestr))))
16894 (cond
16895 (from-string (setq ans from-string))
16896 (org-read-date-popup-calendar
16897 (save-excursion
16898 (save-window-excursion
16899 (calendar)
16900 (when (eq calendar-setup 'calendar-only)
16901 (setq cal-frame
16902 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16903 (select-frame cal-frame))
16904 (org-eval-in-calendar '(setq cursor-type nil) t)
16905 (unwind-protect
16906 (progn
16907 (calendar-forward-day (- (time-to-days org-def)
16908 (calendar-absolute-from-gregorian
16909 (calendar-current-date))))
16910 (org-eval-in-calendar nil t)
16911 (let* ((old-map (current-local-map))
16912 (map (copy-keymap calendar-mode-map))
16913 (minibuffer-local-map
16914 (copy-keymap org-read-date-minibuffer-local-map)))
16915 (org-defkey map (kbd "RET") 'org-calendar-select)
16916 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16917 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16918 (unwind-protect
16919 (progn
16920 (use-local-map map)
16921 (setq org-read-date-inactive inactive)
16922 (add-hook 'post-command-hook 'org-read-date-display)
16923 (setq org-ans0
16924 (read-string prompt
16925 default-input
16926 'org-read-date-history
16927 nil))
16928 ;; org-ans0: from prompt
16929 ;; org-ans1: from mouse click
16930 ;; org-ans2: from calendar motion
16931 (setq ans
16932 (concat org-ans0 " " (or org-ans1 org-ans2))))
16933 (remove-hook 'post-command-hook 'org-read-date-display)
16934 (use-local-map old-map)
16935 (when org-read-date-overlay
16936 (delete-overlay org-read-date-overlay)
16937 (setq org-read-date-overlay nil)))))
16938 (bury-buffer "*Calendar*")
16939 (when cal-frame
16940 (delete-frame cal-frame)
16941 (select-frame-set-input-focus cur-frame))))))
16943 (t ; Naked prompt only
16944 (unwind-protect
16945 (setq ans (read-string prompt default-input
16946 'org-read-date-history timestr))
16947 (when org-read-date-overlay
16948 (delete-overlay org-read-date-overlay)
16949 (setq org-read-date-overlay nil))))))
16951 (setq final (org-read-date-analyze ans org-def org-defdecode))
16953 (when org-read-date-analyze-forced-year
16954 (message "Year was forced into %s"
16955 (if org-read-date-force-compatible-dates
16956 "compatible range (1970-2037)"
16957 "range representable on this machine"))
16958 (ding))
16960 ;; One round trip to get rid of 34th of August and stuff like that....
16961 (setq final (decode-time (apply 'encode-time final)))
16963 (setq org-read-date-final-answer ans)
16965 (if to-time
16966 (apply 'encode-time final)
16967 (if (and (boundp 'org-time-was-given) org-time-was-given)
16968 (format "%04d-%02d-%02d %02d:%02d"
16969 (nth 5 final) (nth 4 final) (nth 3 final)
16970 (nth 2 final) (nth 1 final))
16971 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16973 (defun org-read-date-display ()
16974 "Display the current date prompt interpretation in the minibuffer."
16975 (when org-read-date-display-live
16976 (when org-read-date-overlay
16977 (delete-overlay org-read-date-overlay))
16978 (when (minibufferp (current-buffer))
16979 (save-excursion
16980 (end-of-line 1)
16981 (while (not (equal (buffer-substring
16982 (max (point-min) (- (point) 4)) (point))
16983 " "))
16984 (insert " ")))
16985 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16986 " " (or org-ans1 org-ans2)))
16987 (org-end-time-was-given nil)
16988 (f (org-read-date-analyze ans org-def org-defdecode))
16989 (fmts (if org-dcst
16990 org-time-stamp-custom-formats
16991 org-time-stamp-formats))
16992 (fmt (if (or org-with-time
16993 (and (boundp 'org-time-was-given) org-time-was-given))
16994 (cdr fmts)
16995 (car fmts)))
16996 (txt (format-time-string fmt (apply 'encode-time f)))
16997 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
16998 (txt (concat "=> " txt)))
16999 (when (and org-end-time-was-given
17000 (string-match org-plain-time-of-day-regexp txt))
17001 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17002 org-end-time-was-given
17003 (substring txt (match-end 0)))))
17004 (when org-read-date-analyze-futurep
17005 (setq txt (concat txt " (=>F)")))
17006 (setq org-read-date-overlay
17007 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17008 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17010 (defun org-read-date-analyze (ans def defdecode)
17011 "Analyze the combined answer of the date prompt."
17012 ;; FIXME: cleanup and comment
17013 ;; Pass `current-time' result to `decode-time' (instead of calling
17014 ;; without arguments) so that only `current-time' has to be
17015 ;; overriden in tests.
17016 (let ((org-def def)
17017 (org-defdecode defdecode)
17018 (nowdecode (decode-time (current-time)))
17019 delta deltan deltaw deltadef year month day
17020 hour minute second wday pm h2 m2 tl wday1
17021 iso-year iso-weekday iso-week iso-date futurep kill-year)
17022 (setq org-read-date-analyze-futurep nil
17023 org-read-date-analyze-forced-year nil)
17024 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17025 (setq ans "+0"))
17027 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17028 (setq ans (replace-match "" t t ans)
17029 deltan (car delta)
17030 deltaw (nth 1 delta)
17031 deltadef (nth 2 delta)))
17033 ;; Check if there is an iso week date in there. If yes, store the
17034 ;; info and postpone interpreting it until the rest of the parsing
17035 ;; is done.
17036 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17037 (setq iso-year (when (match-end 1)
17038 (org-small-year-to-year
17039 (string-to-number (match-string 1 ans))))
17040 iso-weekday (when (match-end 3)
17041 (string-to-number (match-string 3 ans)))
17042 iso-week (string-to-number (match-string 2 ans)))
17043 (setq ans (replace-match "" t t ans)))
17045 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17046 (when (string-match
17047 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17048 (setq year (if (match-end 2)
17049 (string-to-number (match-string 2 ans))
17050 (progn (setq kill-year t)
17051 (string-to-number (format-time-string "%Y"))))
17052 month (string-to-number (match-string 3 ans))
17053 day (string-to-number (match-string 4 ans)))
17054 (setq year (org-small-year-to-year year))
17055 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17056 t nil ans)))
17058 ;; Help matching dotted european dates
17059 (when (string-match
17060 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17061 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17062 (setq kill-year t)
17063 (string-to-number (format-time-string "%Y")))
17064 day (string-to-number (match-string 1 ans))
17065 month (string-to-number (match-string 2 ans))
17066 ans (replace-match (format "%04d-%02d-%02d" year month day)
17067 t nil ans)))
17069 ;; Help matching american dates, like 5/30 or 5/30/7
17070 (when (string-match
17071 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17072 (setq year (if (match-end 4)
17073 (string-to-number (match-string 4 ans))
17074 (progn (setq kill-year t)
17075 (string-to-number (format-time-string "%Y"))))
17076 month (string-to-number (match-string 1 ans))
17077 day (string-to-number (match-string 2 ans)))
17078 (setq year (org-small-year-to-year year))
17079 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17080 t nil ans)))
17081 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17082 ;; If there is a time with am/pm, and *no* time without it, we convert
17083 ;; so that matching will be successful.
17084 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17085 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17086 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17087 (setq hour (string-to-number (match-string 1 ans))
17088 minute (if (match-end 3)
17089 (string-to-number (match-string 3 ans))
17091 pm (equal ?p
17092 (string-to-char (downcase (match-string 4 ans)))))
17093 (if (and (= hour 12) (not pm))
17094 (setq hour 0)
17095 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17096 (setq ans (replace-match (format "%02d:%02d" hour minute)
17097 t t ans))))
17099 ;; Check if a time range is given as a duration
17100 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17101 (setq hour (string-to-number (match-string 1 ans))
17102 h2 (+ hour (string-to-number (match-string 3 ans)))
17103 minute (string-to-number (match-string 2 ans))
17104 m2 (+ minute (if (match-end 5) (string-to-number
17105 (match-string 5 ans))0)))
17106 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17107 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17108 t t ans)))
17110 ;; Check if there is a time range
17111 (when (boundp 'org-end-time-was-given)
17112 (setq org-time-was-given nil)
17113 (when (and (string-match org-plain-time-of-day-regexp ans)
17114 (match-end 8))
17115 (setq org-end-time-was-given (match-string 8 ans))
17116 (setq ans (concat (substring ans 0 (match-beginning 7))
17117 (substring ans (match-end 7))))))
17119 (setq tl (parse-time-string ans)
17120 day (or (nth 3 tl) (nth 3 org-defdecode))
17121 month
17122 (cond ((nth 4 tl))
17123 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17124 ;; Day was specified. Make sure DAY+MONTH
17125 ;; combination happens in the future.
17126 ((nth 3 tl)
17127 (setq futurep t)
17128 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17129 (nth 4 nowdecode)))
17130 (t (nth 4 org-defdecode)))
17131 year
17132 (cond ((and (not kill-year) (nth 5 tl)))
17133 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17134 ;; Month was guessed in the future and is at least
17135 ;; equal to NOWDECODE's. Fix year accordingly.
17136 (futurep
17137 (if (or (> month (nth 4 nowdecode))
17138 (>= day (nth 3 nowdecode)))
17139 (nth 5 nowdecode)
17140 (1+ (nth 5 nowdecode))))
17141 ;; Month was specified. Make sure MONTH+YEAR
17142 ;; combination happens in the future.
17143 ((nth 4 tl)
17144 (setq futurep t)
17145 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17146 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17147 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17148 (t (nth 5 nowdecode))))
17149 (t (nth 5 org-defdecode)))
17150 hour (or (nth 2 tl) (nth 2 org-defdecode))
17151 minute (or (nth 1 tl) (nth 1 org-defdecode))
17152 second (or (nth 0 tl) 0)
17153 wday (nth 6 tl))
17155 (when (and (eq org-read-date-prefer-future 'time)
17156 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17157 (equal day (nth 3 nowdecode))
17158 (equal month (nth 4 nowdecode))
17159 (equal year (nth 5 nowdecode))
17160 (nth 2 tl)
17161 (or (< (nth 2 tl) (nth 2 nowdecode))
17162 (and (= (nth 2 tl) (nth 2 nowdecode))
17163 (nth 1 tl)
17164 (< (nth 1 tl) (nth 1 nowdecode)))))
17165 (setq day (1+ day)
17166 futurep t))
17168 ;; Special date definitions below
17169 (cond
17170 (iso-week
17171 ;; There was an iso week
17172 (require 'cal-iso)
17173 (setq futurep nil)
17174 (setq year (or iso-year year)
17175 day (or iso-weekday wday 1)
17176 wday nil ; to make sure that the trigger below does not match
17177 iso-date (calendar-gregorian-from-absolute
17178 (calendar-iso-to-absolute
17179 (list iso-week day year))))
17180 ; FIXME: Should we also push ISO weeks into the future?
17181 ; (when (and org-read-date-prefer-future
17182 ; (not iso-year)
17183 ; (< (calendar-absolute-from-gregorian iso-date)
17184 ; (time-to-days (current-time))))
17185 ; (setq year (1+ year)
17186 ; iso-date (calendar-gregorian-from-absolute
17187 ; (calendar-iso-to-absolute
17188 ; (list iso-week day year)))))
17189 (setq month (car iso-date)
17190 year (nth 2 iso-date)
17191 day (nth 1 iso-date)))
17192 (deltan
17193 (setq futurep nil)
17194 (unless deltadef
17195 ;; Pass `current-time' result to `decode-time' (instead of
17196 ;; calling without arguments) so that only `current-time' has
17197 ;; to be overriden in tests.
17198 (let ((now (decode-time (current-time))))
17199 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17200 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17201 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17202 ((equal deltaw "m") (setq month (+ month deltan)))
17203 ((equal deltaw "y") (setq year (+ year deltan)))))
17204 ((and wday (not (nth 3 tl)))
17205 ;; Weekday was given, but no day, so pick that day in the week
17206 ;; on or after the derived date.
17207 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17208 (unless (equal wday wday1)
17209 (setq day (+ day (% (- wday wday1 -7) 7))))))
17210 (when (and (boundp 'org-time-was-given)
17211 (nth 2 tl))
17212 (setq org-time-was-given t))
17213 (when (< year 100) (setq year (+ 2000 year)))
17214 ;; Check of the date is representable
17215 (if org-read-date-force-compatible-dates
17216 (progn
17217 (when (< year 1970)
17218 (setq year 1970 org-read-date-analyze-forced-year t))
17219 (when (> year 2037)
17220 (setq year 2037 org-read-date-analyze-forced-year t)))
17221 (condition-case nil
17222 (ignore (encode-time second minute hour day month year))
17223 (error
17224 (setq year (nth 5 org-defdecode))
17225 (setq org-read-date-analyze-forced-year t))))
17226 (setq org-read-date-analyze-futurep futurep)
17227 (list second minute hour day month year)))
17229 (defvar parse-time-weekdays)
17230 (defun org-read-date-get-relative (s today default)
17231 "Check string S for special relative date string.
17232 TODAY and DEFAULT are internal times, for today and for a default.
17233 Return shift list (N what def-flag)
17234 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17235 N is the number of WHATs to shift.
17236 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17237 the DEFAULT date rather than TODAY."
17238 (require 'parse-time)
17239 (when (and
17240 (string-match
17241 (concat
17242 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17243 "\\([0-9]+\\)?"
17244 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17245 "\\([ \t]\\|$\\)") s)
17246 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17247 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17248 (string-to-char (substring (match-string 1 s) -1))
17249 ?+))
17250 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17251 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17252 (what (if (match-end 3) (match-string 3 s) "d"))
17253 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17254 (date (if rel default today))
17255 (wday (nth 6 (decode-time date)))
17256 delta)
17257 (if wday1
17258 (progn
17259 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17260 (when (= delta 0) (setq delta 7))
17261 (when (= dir ?-)
17262 (setq delta (- delta 7))
17263 (when (= delta 0) (setq delta -7)))
17264 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17265 (list delta "d" rel))
17266 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17268 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17269 "Turn a user-specified date into the internal representation.
17270 The internal representation needed by the calendar is (month day year).
17271 This is a wrapper to handle the brain-dead convention in calendar that
17272 user function argument order change dependent on argument order."
17273 (if (boundp 'calendar-date-style)
17274 (cond
17275 ((eq calendar-date-style 'american)
17276 (list arg1 arg2 arg3))
17277 ((eq calendar-date-style 'european)
17278 (list arg2 arg1 arg3))
17279 ((eq calendar-date-style 'iso)
17280 (list arg2 arg3 arg1)))
17281 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17282 (if (org-bound-and-true-p european-calendar-style)
17283 (list arg2 arg1 arg3)
17284 (list arg1 arg2 arg3)))))
17286 (defun org-eval-in-calendar (form &optional keepdate)
17287 "Eval FORM in the calendar window and return to current window.
17288 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17289 (let ((sf (selected-frame))
17290 (sw (selected-window)))
17291 (select-window (get-buffer-window "*Calendar*" t))
17292 (eval form)
17293 (when (and (not keepdate) (calendar-cursor-to-date))
17294 (let* ((date (calendar-cursor-to-date))
17295 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17296 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17297 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17298 (select-window sw)
17299 (org-select-frame-set-input-focus sf)))
17301 (defun org-calendar-select ()
17302 "Return to `org-read-date' with the date currently selected.
17303 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17304 (interactive)
17305 (when (calendar-cursor-to-date)
17306 (let* ((date (calendar-cursor-to-date))
17307 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17308 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17309 (when (active-minibuffer-window) (exit-minibuffer))))
17311 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17312 "Insert a date stamp for the date given by the internal TIME.
17313 See `format-time-string' for the format of TIME.
17314 WITH-HM means use the stamp format that includes the time of the day.
17315 INACTIVE means use square brackets instead of angular ones, so that the
17316 stamp will not contribute to the agenda.
17317 PRE and POST are optional strings to be inserted before and after the
17318 stamp.
17319 The command returns the inserted time stamp."
17320 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17321 stamp)
17322 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17323 (insert-before-markers (or pre ""))
17324 (when (listp extra)
17325 (setq extra (car extra))
17326 (if (and (stringp extra)
17327 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17328 (setq extra (format "-%02d:%02d"
17329 (string-to-number (match-string 1 extra))
17330 (string-to-number (match-string 2 extra))))
17331 (setq extra nil)))
17332 (when extra
17333 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17334 (insert-before-markers (setq stamp (format-time-string fmt time)))
17335 (insert-before-markers (or post ""))
17336 (setq org-last-inserted-timestamp stamp)))
17338 (defun org-toggle-time-stamp-overlays ()
17339 "Toggle the use of custom time stamp formats."
17340 (interactive)
17341 (setq org-display-custom-times (not org-display-custom-times))
17342 (unless org-display-custom-times
17343 (let ((p (point-min)) (bmp (buffer-modified-p)))
17344 (while (setq p (next-single-property-change p 'display))
17345 (when (and (get-text-property p 'display)
17346 (eq (get-text-property p 'face) 'org-date))
17347 (remove-text-properties
17348 p (setq p (next-single-property-change p 'display))
17349 '(display t))))
17350 (set-buffer-modified-p bmp)))
17351 (when (featurep 'xemacs)
17352 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17353 (org-restart-font-lock)
17354 (setq org-table-may-need-update t)
17355 (if org-display-custom-times
17356 (message "Time stamps are overlaid with custom format")
17357 (message "Time stamp overlays removed")))
17359 (defun org-display-custom-time (beg end)
17360 "Overlay modified time stamp format over timestamp between BEG and END."
17361 (let* ((ts (buffer-substring beg end))
17362 t1 w1 with-hm tf time str w2 (off 0))
17363 (save-match-data
17364 (setq t1 (org-parse-time-string ts t))
17365 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17366 (setq off (- (match-end 0) (match-beginning 0)))))
17367 (setq end (- end off))
17368 (setq w1 (- end beg)
17369 with-hm (and (nth 1 t1) (nth 2 t1))
17370 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17371 time (org-fix-decoded-time t1)
17372 str (org-add-props
17373 (format-time-string
17374 (substring tf 1 -1) (apply 'encode-time time))
17375 nil 'mouse-face 'highlight)
17376 w2 (length str))
17377 (unless (= w2 w1)
17378 (add-text-properties (1+ beg) (+ 2 beg)
17379 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17380 (if (featurep 'xemacs)
17381 (progn
17382 (put-text-property beg end 'invisible t)
17383 (put-text-property beg end 'end-glyph (make-glyph str)))
17384 (put-text-property beg end 'display str))))
17386 (defun org-fix-decoded-time (time)
17387 "Set 0 instead of nil for the first 6 elements of time.
17388 Don't touch the rest."
17389 (let ((n 0))
17390 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17392 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17394 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17395 "Difference between TIMESTAMP-STRING and now in days.
17396 If SECONDS is non-nil, return the difference in seconds."
17397 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17398 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17399 (funcall fdiff (current-time)))))
17401 (defun org-deadline-close (timestamp-string &optional ndays)
17402 "Is the time in TIMESTAMP-STRING close to the current date?"
17403 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17404 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17405 (not (org-entry-is-done-p))))
17407 (defun org-get-wdays (ts &optional delay zero-delay)
17408 "Get the deadline lead time appropriate for timestring TS.
17409 When DELAY is non-nil, get the delay time for scheduled items
17410 instead of the deadline lead time. When ZERO-DELAY is non-nil
17411 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17412 don't try to find the delay cookie in the scheduled timestamp."
17413 (let ((tv (if delay org-scheduled-delay-days
17414 org-deadline-warning-days)))
17415 (cond
17416 ((or (and delay (< tv 0))
17417 (and delay zero-delay (<= tv 0))
17418 (and (not delay) (<= tv 0)))
17419 ;; Enforce this value no matter what
17420 (- tv))
17421 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17422 ;; lead time is specified.
17423 (floor (* (string-to-number (match-string 1 ts))
17424 (cdr (assoc (match-string 2 ts)
17425 '(("d" . 1) ("w" . 7)
17426 ("m" . 30.4) ("y" . 365.25)
17427 ("h" . 0.041667)))))))
17428 ;; go for the default.
17429 (t tv))))
17431 (defun org-calendar-select-mouse (ev)
17432 "Return to `org-read-date' with the date currently selected.
17433 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17434 (interactive "e")
17435 (mouse-set-point ev)
17436 (when (calendar-cursor-to-date)
17437 (let* ((date (calendar-cursor-to-date))
17438 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17439 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17440 (when (active-minibuffer-window) (exit-minibuffer))))
17442 (defun org-check-deadlines (ndays)
17443 "Check if there are any deadlines due or past due.
17444 A deadline is considered due if it happens within `org-deadline-warning-days'
17445 days from today's date. If the deadline appears in an entry marked DONE,
17446 it is not shown. The prefix arg NDAYS can be used to test that many
17447 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17448 (interactive "P")
17449 (let* ((org-warn-days
17450 (cond
17451 ((equal ndays '(4)) 100000)
17452 (ndays (prefix-numeric-value ndays))
17453 (t (abs org-deadline-warning-days))))
17454 (case-fold-search nil)
17455 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17456 (callback
17457 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17458 (message "%d deadlines past-due or due within %d days"
17459 (org-occur regexp nil callback)
17460 org-warn-days)))
17462 (defsubst org-re-timestamp (type)
17463 "Return a regexp for timestamp TYPE.
17464 Allowed values for TYPE are:
17466 all: all timestamps
17467 active: only active timestamps (<...>)
17468 inactive: only inactive timestamps ([...])
17469 scheduled: only scheduled timestamps
17470 deadline: only deadline timestamps
17471 closed: only closed time-stamps
17473 When TYPE is nil, fall back on returning a regexp that matches
17474 both scheduled and deadline timestamps."
17475 (cl-case type
17476 (all org-ts-regexp-both)
17477 (active org-ts-regexp)
17478 (inactive org-ts-regexp-inactive)
17479 (scheduled org-scheduled-time-regexp)
17480 (deadline org-deadline-time-regexp)
17481 (closed org-closed-time-regexp)
17482 (otherwise
17483 (concat "\\<"
17484 (regexp-opt (list org-deadline-string org-scheduled-string))
17485 " *<\\([^>]+\\)>"))))
17487 (defun org-check-before-date (d)
17488 "Check if there are deadlines or scheduled entries before date D."
17489 (interactive (list (org-read-date)))
17490 (let* ((case-fold-search nil)
17491 (regexp (org-re-timestamp org-ts-type))
17492 (ts-type org-ts-type)
17493 (callback
17494 (lambda ()
17495 (let ((match (match-string 1)))
17496 (and (if (memq ts-type '(active inactive all))
17497 (eq (org-element-type (org-element-context)) 'timestamp)
17498 (org-at-planning-p))
17499 (time-less-p
17500 (org-time-string-to-time match)
17501 (org-time-string-to-time d)))))))
17502 (message "%d entries before %s"
17503 (org-occur regexp nil callback)
17504 d)))
17506 (defun org-check-after-date (d)
17507 "Check if there are deadlines or scheduled entries after date D."
17508 (interactive (list (org-read-date)))
17509 (let* ((case-fold-search nil)
17510 (regexp (org-re-timestamp org-ts-type))
17511 (ts-type org-ts-type)
17512 (callback
17513 (lambda ()
17514 (let ((match (match-string 1)))
17515 (and (if (memq ts-type '(active inactive all))
17516 (eq (org-element-type (org-element-context)) 'timestamp)
17517 (org-at-planning-p))
17518 (not (time-less-p
17519 (org-time-string-to-time match)
17520 (org-time-string-to-time d))))))))
17521 (message "%d entries after %s"
17522 (org-occur regexp nil callback)
17523 d)))
17525 (defun org-check-dates-range (start-date end-date)
17526 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17527 (interactive (list (org-read-date nil nil nil "Range starts")
17528 (org-read-date nil nil nil "Range end")))
17529 (let ((case-fold-search nil)
17530 (regexp (org-re-timestamp org-ts-type))
17531 (callback
17532 (let ((type org-ts-type))
17533 (lambda ()
17534 (let ((match (match-string 1)))
17535 (and
17536 (if (memq type '(active inactive all))
17537 (eq (org-element-type (org-element-context)) 'timestamp)
17538 (org-at-planning-p))
17539 (not (time-less-p
17540 (org-time-string-to-time match)
17541 (org-time-string-to-time start-date)))
17542 (time-less-p
17543 (org-time-string-to-time match)
17544 (org-time-string-to-time end-date))))))))
17545 (message "%d entries between %s and %s"
17546 (org-occur regexp nil callback) start-date end-date)))
17548 (defun org-evaluate-time-range (&optional to-buffer)
17549 "Evaluate a time range by computing the difference between start and end.
17550 Normally the result is just printed in the echo area, but with prefix arg
17551 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17552 If the time range is actually in a table, the result is inserted into the
17553 next column.
17554 For time difference computation, a year is assumed to be exactly 365
17555 days in order to avoid rounding problems."
17556 (interactive "P")
17558 (org-clock-update-time-maybe)
17559 (save-excursion
17560 (unless (org-at-date-range-p t)
17561 (goto-char (point-at-bol))
17562 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17563 (unless (org-at-date-range-p t)
17564 (user-error "Not at a time-stamp range, and none found in current line")))
17565 (let* ((ts1 (match-string 1))
17566 (ts2 (match-string 2))
17567 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17568 (match-end (match-end 0))
17569 (time1 (org-time-string-to-time ts1))
17570 (time2 (org-time-string-to-time ts2))
17571 (t1 (org-float-time time1))
17572 (t2 (org-float-time time2))
17573 (diff (abs (- t2 t1)))
17574 (negative (< (- t2 t1) 0))
17575 ;; (ys (floor (* 365 24 60 60)))
17576 (ds (* 24 60 60))
17577 (hs (* 60 60))
17578 (fy "%dy %dd %02d:%02d")
17579 (fy1 "%dy %dd")
17580 (fd "%dd %02d:%02d")
17581 (fd1 "%dd")
17582 (fh "%02d:%02d")
17583 y d h m align)
17584 (if havetime
17585 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17587 d (floor (/ diff ds)) diff (mod diff ds)
17588 h (floor (/ diff hs)) diff (mod diff hs)
17589 m (floor (/ diff 60)))
17590 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17592 d (floor (+ (/ diff ds) 0.5))
17593 h 0 m 0))
17594 (if (not to-buffer)
17595 (message "%s" (org-make-tdiff-string y d h m))
17596 (if (org-at-table-p)
17597 (progn
17598 (goto-char match-end)
17599 (setq align t)
17600 (and (looking-at " *|") (goto-char (match-end 0))))
17601 (goto-char match-end))
17602 (when (looking-at
17603 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17604 (replace-match ""))
17605 (when negative (insert " -"))
17606 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17607 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17608 (insert " " (format fh h m))))
17609 (when align (org-table-align))
17610 (message "Time difference inserted")))))
17612 (defun org-make-tdiff-string (y d h m)
17613 (let ((fmt "")
17614 (l nil))
17615 (when (> y 0)
17616 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17617 (push y l))
17618 (when (> d 0)
17619 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17620 (push d l))
17621 (when (> h 0)
17622 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17623 (push h l))
17624 (when (> m 0)
17625 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17626 (push m l))
17627 (apply 'format fmt (nreverse l))))
17629 (defun org-time-string-to-time (s &optional buffer pos)
17630 "Convert a timestamp string into internal time."
17631 (condition-case errdata
17632 (apply 'encode-time (org-parse-time-string s))
17633 (error (error "Bad timestamp `%s'%s\nError was: %s"
17634 s (if (not (and buffer pos))
17636 (format-message " at %d in buffer `%s'" pos buffer))
17637 (cdr errdata)))))
17639 (defun org-time-string-to-seconds (s)
17640 "Convert a timestamp string to a number of seconds."
17641 (org-float-time (org-time-string-to-time s)))
17643 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17645 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17646 "Convert time stamp S to an absolute day number.
17648 If DAYNR in non-nil, and there is a specifier for a cyclic time
17649 stamp, get the closest date to DAYNR. If PREFER is
17650 `past' (respectively `future') return a date past (respectively
17651 after) or equal to DAYNR.
17653 POS is the location of time stamp S, as a buffer position in
17654 BUFFER.
17656 Diary sexp timestamps are matched against DAYNR, when non-nil.
17657 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17658 signalled."
17659 (cond
17660 ((string-match "\\`%%\\((.*)\\)" s)
17661 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17662 ;; only able to match individual dates. If it fails, raise an
17663 ;; error.
17664 (if (and daynr
17665 (org-diary-sexp-entry
17666 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17667 daynr
17668 (signal 'org-diary-sexp-no-match (list s))))
17669 ((and daynr show-all) (org-closest-date s daynr prefer))
17670 (t (time-to-days
17671 (condition-case errdata
17672 (apply #'encode-time (org-parse-time-string s))
17673 (error (error "Bad timestamp `%s'%s\nError was: %s"
17675 (if (not (and buffer pos)) ""
17676 (format-message " at %d in buffer `%s'" pos buffer))
17677 (cdr errdata))))))))
17679 (defun org-days-to-iso-week (days)
17680 "Return the iso week number."
17681 (require 'cal-iso)
17682 (car (calendar-iso-from-absolute days)))
17684 (defun org-small-year-to-year (year)
17685 "Convert 2-digit years into 4-digit years.
17686 YEAR is expanded into one of the 30 next years, if possible, or
17687 into a past one. Any year larger than 99 is returned unchanged."
17688 (if (>= year 100) year
17689 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17690 (century (/ current 100))
17691 (offset (- year (% current 100))))
17692 (cond ((> offset 30) (+ (* (1- century) 100) year))
17693 ((> offset -70) (+ (* century 100) year))
17694 (t (+ (* (1+ century) 100) year))))))
17696 (defun org-time-from-absolute (d)
17697 "Return the time corresponding to date D.
17698 D may be an absolute day number, or a calendar-type list (month day year)."
17699 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17700 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17702 (defvar org-agenda-current-date)
17703 (defun org-calendar-holiday ()
17704 "List of holidays, for Diary display in Org mode."
17705 (require 'holidays)
17706 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17707 (and hl (mapconcat #'identity hl "; "))))
17709 (defun org-diary-sexp-entry (sexp entry d)
17710 "Process a SEXP diary ENTRY for date D."
17711 (require 'diary-lib)
17712 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17713 ;; dynamically.
17714 (let* ((sexp `(let ((entry ,entry)
17715 (date ',d))
17716 ,(car (read-from-string sexp))))
17717 (result (if calendar-debug-sexp (eval sexp)
17718 (condition-case nil
17719 (eval sexp)
17720 (error
17721 (beep)
17722 (message "Bad sexp at line %d in %s: %s"
17723 (org-current-line)
17724 (buffer-file-name) sexp)
17725 (sleep-for 2))))))
17726 (cond ((stringp result) (split-string result "; "))
17727 ((and (consp result)
17728 (not (consp (cdr result)))
17729 (stringp (cdr result))) (cdr result))
17730 ((and (consp result)
17731 (stringp (car result))) result)
17732 (result entry))))
17734 (defun org-diary-to-ical-string (frombuf)
17735 "Get iCalendar entries from diary entries in buffer FROMBUF.
17736 This uses the icalendar.el library."
17737 (let* ((tmpdir (if (featurep 'xemacs)
17738 (temp-directory)
17739 temporary-file-directory))
17740 (tmpfile (make-temp-name
17741 (expand-file-name "orgics" tmpdir)))
17742 buf rtn b e)
17743 (with-current-buffer frombuf
17744 (icalendar-export-region (point-min) (point-max) tmpfile)
17745 (setq buf (find-buffer-visiting tmpfile))
17746 (set-buffer buf)
17747 (goto-char (point-min))
17748 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17749 (setq b (match-beginning 0)))
17750 (goto-char (point-max))
17751 (when (re-search-backward "^END:VEVENT" nil t)
17752 (setq e (match-end 0)))
17753 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17754 (kill-buffer buf)
17755 (delete-file tmpfile)
17756 rtn))
17758 (defun org-closest-date (start current prefer)
17759 "Return closest date to CURRENT starting from START.
17761 CURRENT and START are both time stamps.
17763 When PREFER is `past', return a date that is either CURRENT or
17764 past. When PREFER is `future', return a date that is either
17765 CURRENT or future.
17767 Only time stamps with a repeater are modified. Any other time
17768 stamp stay unchanged. In any case, return value is an absolute
17769 day number."
17770 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17771 ;; No repeater. Do not shift time stamp.
17772 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17773 (let ((value (string-to-number (match-string 1 start)))
17774 (type (match-string 2 start)))
17775 (if (= 0 value)
17776 ;; Repeater with a 0-value is considered as void.
17777 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17778 (let* ((base (org-date-to-gregorian start))
17779 (target (org-date-to-gregorian current))
17780 (sday (calendar-absolute-from-gregorian base))
17781 (cday (calendar-absolute-from-gregorian target))
17782 n1 n2)
17783 ;; If START is already past CURRENT, just return START.
17784 (if (<= cday sday) sday
17785 ;; Compute closest date before (N1) and closest date past
17786 ;; (N2) CURRENT.
17787 (pcase type
17788 ("h"
17789 (let ((missing-hours
17790 (mod (+ (- (* 24 (- cday sday))
17791 (nth 2 (org-parse-time-string start)))
17792 org-extend-today-until)
17793 value)))
17794 (setf n1 (if (= missing-hours 0) cday
17795 (- cday (1+ (/ missing-hours 24)))))
17796 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17797 ((or "d" "w")
17798 (let ((value (if (equal type "w") (* 7 value) value)))
17799 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17800 (setf n2 (+ n1 value))))
17801 ("m"
17802 (let* ((add-months
17803 (lambda (d n)
17804 ;; Add N months to gregorian date D, i.e.,
17805 ;; a list (MONTH DAY YEAR). Return a valid
17806 ;; gregorian date.
17807 (let ((m (+ (nth 0 d) n)))
17808 (list (mod m 12)
17809 (nth 1 d)
17810 (+ (/ m 12) (nth 2 d))))))
17811 (months ; Complete months to TARGET.
17812 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17813 (- (nth 0 target) (nth 0 base))
17814 ;; If START's day is greater than
17815 ;; TARGET's, remove incomplete month.
17816 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17817 value)
17818 value))
17819 (before (funcall add-months base months)))
17820 (setf n1 (calendar-absolute-from-gregorian before))
17821 (setf n2
17822 (calendar-absolute-from-gregorian
17823 (funcall add-months before value)))))
17825 (let* ((d (nth 1 base))
17826 (m (nth 0 base))
17827 (y (nth 2 base))
17828 (years ; Complete years to TARGET.
17829 (* (/ (- (nth 2 target)
17831 ;; If START's month and day are
17832 ;; greater than TARGET's, remove
17833 ;; incomplete year.
17834 (if (or (> (nth 0 target) m)
17835 (and (= (nth 0 target) m)
17836 (> (nth 1 target) d)))
17839 value)
17840 value))
17841 (before (list m d (+ y years))))
17842 (setf n1 (calendar-absolute-from-gregorian before))
17843 (setf n2 (calendar-absolute-from-gregorian
17844 (list m d (+ (nth 2 before) value)))))))
17845 ;; Handle PREFER parameter, if any.
17846 (cond
17847 ((eq prefer 'past) (if (= cday n2) n2 n1))
17848 ((eq prefer 'future) (if (= cday n1) n1 n2))
17849 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17851 (defun org-date-to-gregorian (d)
17852 "Turn any specification of date D into a Gregorian date for the calendar."
17853 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17854 ((and (listp d) (= (length d) 3)) d)
17855 ((stringp d)
17856 (let ((d (org-parse-time-string d)))
17857 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17858 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17860 (defun org-parse-time-string (s &optional nodefault)
17861 "Parse the standard Org-mode time string.
17862 This should be a lot faster than the normal `parse-time-string'.
17863 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17864 hour and minute fields will be nil if not given."
17865 (cond ((string-match org-ts-regexp0 s)
17866 (list 0
17867 (when (or (match-beginning 8) (not nodefault))
17868 (string-to-number (or (match-string 8 s) "0")))
17869 (when (or (match-beginning 7) (not nodefault))
17870 (string-to-number (or (match-string 7 s) "0")))
17871 (string-to-number (match-string 4 s))
17872 (string-to-number (match-string 3 s))
17873 (string-to-number (match-string 2 s))
17874 nil nil nil))
17875 ((string-match "^<[^>]+>$" s)
17876 (decode-time (seconds-to-time (org-matcher-time s))))
17877 (t (error "Not a standard Org-mode time string: %s" s))))
17879 (defun org-timestamp-up (&optional arg)
17880 "Increase the date item at the cursor by one.
17881 If the cursor is on the year, change the year. If it is on the month,
17882 the day or the time, change that.
17883 With prefix ARG, change by that many units."
17884 (interactive "p")
17885 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17887 (defun org-timestamp-down (&optional arg)
17888 "Decrease the date item at the cursor by one.
17889 If the cursor is on the year, change the year. If it is on the month,
17890 the day or the time, change that.
17891 With prefix ARG, change by that many units."
17892 (interactive "p")
17893 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17895 (defun org-timestamp-up-day (&optional arg)
17896 "Increase the date in the time stamp by one day.
17897 With prefix ARG, change that many days."
17898 (interactive "p")
17899 (if (and (not (org-at-timestamp-p t))
17900 (org-at-heading-p))
17901 (org-todo 'up)
17902 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17904 (defun org-timestamp-down-day (&optional arg)
17905 "Decrease the date in the time stamp by one day.
17906 With prefix ARG, change that many days."
17907 (interactive "p")
17908 (if (and (not (org-at-timestamp-p t))
17909 (org-at-heading-p))
17910 (org-todo 'down)
17911 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17913 (defun org-at-timestamp-p (&optional inactive-ok)
17914 "Non-nil if point is inside a timestamp.
17916 When optional argument INACTIVE-OK is non-nil, also consider
17917 inactive timestamps.
17919 When this function returns a non-nil value, match data is set
17920 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17921 INACTIVE-OK."
17922 (interactive)
17923 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17924 (pos (point))
17925 (ans (or (looking-at tsr)
17926 (save-excursion
17927 (skip-chars-backward "^[<\n\r\t")
17928 (when (> (point) (point-min)) (backward-char 1))
17929 (and (looking-at tsr)
17930 (> (- (match-end 0) pos) -1))))))
17931 (and ans
17932 (boundp 'org-ts-what)
17933 (setq org-ts-what
17934 (cond
17935 ((= pos (match-beginning 0)) 'bracket)
17936 ;; Point is considered to be "on the bracket" whether
17937 ;; it's really on it or right after it.
17938 ((= pos (1- (match-end 0))) 'bracket)
17939 ((= pos (match-end 0)) 'after)
17940 ((org-pos-in-match-range pos 2) 'year)
17941 ((org-pos-in-match-range pos 3) 'month)
17942 ((org-pos-in-match-range pos 7) 'hour)
17943 ((org-pos-in-match-range pos 8) 'minute)
17944 ((or (org-pos-in-match-range pos 4)
17945 (org-pos-in-match-range pos 5)) 'day)
17946 ((and (> pos (or (match-end 8) (match-end 5)))
17947 (< pos (match-end 0)))
17948 (- pos (or (match-end 8) (match-end 5))))
17949 (t 'day))))
17950 ans))
17952 (defun org-toggle-timestamp-type ()
17953 "Toggle the type (<active> or [inactive]) of a time stamp."
17954 (interactive)
17955 (when (org-at-timestamp-p t)
17956 (let ((beg (match-beginning 0)) (end (match-end 0))
17957 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17958 (save-excursion
17959 (goto-char beg)
17960 (while (re-search-forward "[][<>]" end t)
17961 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17962 t t)))
17963 (message "Timestamp is now %sactive"
17964 (if (equal (char-after beg) ?<) "" "in")))))
17966 (defun org-at-clock-log-p nil
17967 "Is the cursor on the clock log line?"
17968 (save-excursion
17969 (move-beginning-of-line 1)
17970 (looking-at org-clock-line-re)))
17972 (defvar org-clock-history) ; defined in org-clock.el
17973 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17974 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17975 "Change the date in the time stamp at point.
17976 The date will be changed by N times WHAT. WHAT can be `day', `month',
17977 `year', `minute', `second'. If WHAT is not given, the cursor position
17978 in the timestamp determines what will be changed.
17979 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17980 (let ((origin (point)) origin-cat
17981 with-hm inactive
17982 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17983 org-ts-what
17984 extra rem
17985 ts time time0 fixnext clrgx)
17986 (unless (org-at-timestamp-p t)
17987 (user-error "Not at a timestamp"))
17988 (if (and (not what) (eq org-ts-what 'bracket))
17989 (org-toggle-timestamp-type)
17990 ;; Point isn't on brackets. Remember the part of the time-stamp
17991 ;; the point was in. Indeed, size of time-stamps may change,
17992 ;; but point must be kept in the same category nonetheless.
17993 (setq origin-cat org-ts-what)
17994 (when (and (not what) (not (eq org-ts-what 'day))
17995 org-display-custom-times
17996 (get-text-property (point) 'display)
17997 (not (get-text-property (1- (point)) 'display)))
17998 (setq org-ts-what 'day))
17999 (setq org-ts-what (or what org-ts-what)
18000 inactive (= (char-after (match-beginning 0)) ?\[)
18001 ts (match-string 0))
18002 (replace-match "")
18003 (when (string-match
18004 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18006 (setq extra (match-string 1 ts))
18007 (when suppress-tmp-delay
18008 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18009 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18010 (setq with-hm t))
18011 (setq time0 (org-parse-time-string ts))
18012 (when (and updown
18013 (eq org-ts-what 'minute)
18014 (not current-prefix-arg))
18015 ;; This looks like s-up and s-down. Change by one rounding step.
18016 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18017 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18018 (setcar (cdr time0) (+ (nth 1 time0)
18019 (if (> n 0) (- rem) (- dm rem))))))
18020 (setq time
18021 (apply #'encode-time
18022 (or (car time0) 0)
18023 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18024 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18025 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18026 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18027 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18028 (nthcdr 6 time0)))
18029 (when (and (member org-ts-what '(hour minute))
18030 extra
18031 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18032 (setq extra (org-modify-ts-extra
18033 extra
18034 (if (eq org-ts-what 'hour) 2 5)
18035 n dm)))
18036 (when (integerp org-ts-what)
18037 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18038 (when (eq what 'calendar)
18039 (let ((cal-date (org-get-date-from-calendar)))
18040 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18041 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18042 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18043 (setcar time0 (or (car time0) 0))
18044 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18045 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18046 (setq time (apply 'encode-time time0))))
18047 ;; Insert the new time-stamp, and ensure point stays in the same
18048 ;; category as before (i.e. not after the last position in that
18049 ;; category).
18050 (let ((pos (point)))
18051 ;; Stay before inserted string. `save-excursion' is of no use.
18052 (setq org-last-changed-timestamp
18053 (org-insert-time-stamp time with-hm inactive nil nil extra))
18054 (goto-char pos))
18055 (save-match-data
18056 (looking-at org-ts-regexp3)
18057 (goto-char (cond
18058 ;; `day' category ends before `hour' if any, or at
18059 ;; the end of the day name.
18060 ((eq origin-cat 'day)
18061 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18062 ((eq origin-cat 'hour) (min (match-end 7) origin))
18063 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18064 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18065 ;; `year' and `month' have both fixed size: point
18066 ;; couldn't have moved into another part.
18067 (t origin))))
18068 ;; Update clock if on a CLOCK line.
18069 (org-clock-update-time-maybe)
18070 ;; Maybe adjust the closest clock in `org-clock-history'
18071 (when org-clock-adjust-closest
18072 (if (not (and (org-at-clock-log-p)
18073 (< 1 (length (delq nil (mapcar 'marker-position
18074 org-clock-history))))))
18075 (message "No clock to adjust")
18076 (cond ((save-excursion ; fix previous clock?
18077 (re-search-backward org-ts-regexp0 nil t)
18078 (org-looking-back (concat org-clock-string " \\[")
18079 (line-beginning-position)))
18080 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18081 ((save-excursion ; fix next clock?
18082 (re-search-backward org-ts-regexp0 nil t)
18083 (looking-at (concat org-ts-regexp0 "\\] =>")))
18084 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18085 (save-window-excursion
18086 ;; Find closest clock to point, adjust the previous/next one in history
18087 (let* ((p (save-excursion (org-back-to-heading t)))
18088 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18089 (clfixnth
18090 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18091 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18092 (if (not clfixpos)
18093 (message "No clock to adjust")
18094 (save-excursion
18095 (org-goto-marker-or-bmk clfixpos)
18096 (org-show-subtree)
18097 (when (re-search-forward clrgx nil t)
18098 (goto-char (match-beginning 1))
18099 (let (org-clock-adjust-closest)
18100 (org-timestamp-change n org-ts-what updown))
18101 (message "Clock adjusted in %s for heading: %s"
18102 (file-name-nondirectory (buffer-file-name))
18103 (org-get-heading t t)))))))))
18104 ;; Try to recenter the calendar window, if any.
18105 (when (and org-calendar-follow-timestamp-change
18106 (get-buffer-window "*Calendar*" t)
18107 (memq org-ts-what '(day month year)))
18108 (org-recenter-calendar (time-to-days time))))))
18110 (defun org-modify-ts-extra (s pos n dm)
18111 "Change the different parts of the lead-time and repeat fields in timestamp."
18112 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18113 ng h m new rem)
18114 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18115 (cond
18116 ((or (org-pos-in-match-range pos 2)
18117 (org-pos-in-match-range pos 3))
18118 (setq m (string-to-number (match-string 3 s))
18119 h (string-to-number (match-string 2 s)))
18120 (if (org-pos-in-match-range pos 2)
18121 (setq h (+ h n))
18122 (setq n (* dm (org-no-warnings (signum n))))
18123 (unless (= 0 (setq rem (% m dm)))
18124 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18125 (setq m (+ m n)))
18126 (when (< m 0) (setq m (+ m 60) h (1- h)))
18127 (when (> m 59) (setq m (- m 60) h (1+ h)))
18128 (setq h (mod h 24))
18129 (setq ng 1 new (format "-%02d:%02d" h m)))
18130 ((org-pos-in-match-range pos 6)
18131 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18132 ((org-pos-in-match-range pos 5)
18133 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18135 ((org-pos-in-match-range pos 9)
18136 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18137 ((org-pos-in-match-range pos 8)
18138 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18140 (when ng
18141 (setq s (concat
18142 (substring s 0 (match-beginning ng))
18144 (substring s (match-end ng))))))
18147 (defun org-recenter-calendar (d)
18148 "If the calendar is visible, recenter it to date D."
18149 (let ((cwin (get-buffer-window "*Calendar*" t)))
18150 (when cwin
18151 (let ((calendar-move-hook nil))
18152 (with-selected-window cwin
18153 (calendar-goto-date
18154 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18156 (defun org-goto-calendar (&optional arg)
18157 "Go to the Emacs calendar at the current date.
18158 If there is a time stamp in the current line, go to that date.
18159 A prefix ARG can be used to force the current date."
18160 (interactive "P")
18161 (let ((tsr org-ts-regexp) diff
18162 (calendar-move-hook nil)
18163 (calendar-view-holidays-initially-flag nil)
18164 (calendar-view-diary-initially-flag nil))
18165 (when (or (org-at-timestamp-p)
18166 (save-excursion
18167 (beginning-of-line 1)
18168 (looking-at (concat ".*" tsr))))
18169 (let ((d1 (time-to-days (current-time)))
18170 (d2 (time-to-days
18171 (org-time-string-to-time (match-string 1)))))
18172 (setq diff (- d2 d1))))
18173 (calendar)
18174 (calendar-goto-today)
18175 (when (and diff (not arg)) (calendar-forward-day diff))))
18177 (defun org-get-date-from-calendar ()
18178 "Return a list (month day year) of date at point in calendar."
18179 (with-current-buffer "*Calendar*"
18180 (save-match-data
18181 (calendar-cursor-to-date))))
18183 (defun org-date-from-calendar ()
18184 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18185 If there is already a time stamp at the cursor position, update it."
18186 (interactive)
18187 (if (org-at-timestamp-p t)
18188 (org-timestamp-change 0 'calendar)
18189 (let ((cal-date (org-get-date-from-calendar)))
18190 (org-insert-time-stamp
18191 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18193 (defcustom org-effort-durations
18194 `(("min" . 1)
18195 ("h" . 60)
18196 ("d" . ,(* 60 8))
18197 ("w" . ,(* 60 8 5))
18198 ("m" . ,(* 60 8 5 4))
18199 ("y" . ,(* 60 8 5 40)))
18200 "Conversion factor to minutes for an effort modifier.
18202 Each entry has the form (MODIFIER . MINUTES).
18204 In an effort string, a number followed by MODIFIER is multiplied
18205 by the specified number of MINUTES to obtain an effort in
18206 minutes.
18208 For example, if the value of this variable is ((\"hours\" . 60)), then an
18209 effort string \"2hours\" is equivalent to 120 minutes."
18210 :group 'org-agenda
18211 :version "25.1"
18212 :package-version '(Org . "8.3")
18213 :type '(alist :key-type (string :tag "Modifier")
18214 :value-type (number :tag "Minutes")))
18216 (defun org-minutes-to-clocksum-string (m)
18217 "Format number of minutes as a clocksum string.
18218 The format is determined by `org-time-clocksum-format',
18219 `org-time-clocksum-use-fractional' and
18220 `org-time-clocksum-fractional-format' and
18221 `org-time-clocksum-use-effort-durations'."
18222 (let ((clocksum "")
18223 (m (round m)) ; Don't allow fractions of minutes
18224 h d w mo y fmt n)
18225 (setq h (if org-time-clocksum-use-effort-durations
18226 (cdr (assoc "h" org-effort-durations)) 60)
18227 d (if org-time-clocksum-use-effort-durations
18228 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18229 w (if org-time-clocksum-use-effort-durations
18230 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18231 mo (if org-time-clocksum-use-effort-durations
18232 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18233 y (if org-time-clocksum-use-effort-durations
18234 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18235 ;; fractional format
18236 (if org-time-clocksum-use-fractional
18237 (cond
18238 ;; single format string
18239 ((stringp org-time-clocksum-fractional-format)
18240 (format org-time-clocksum-fractional-format (/ m (float h))))
18241 ;; choice of fractional formats for different time units
18242 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18243 (> (/ (truncate m) (* y d h)) 0))
18244 (format fmt (/ m (* y d (float h)))))
18245 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18246 (> (/ (truncate m) (* mo d h)) 0))
18247 (format fmt (/ m (* mo d (float h)))))
18248 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18249 (> (/ (truncate m) (* w d h)) 0))
18250 (format fmt (/ m (* w d (float h)))))
18251 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18252 (> (/ (truncate m) (* d h)) 0))
18253 (format fmt (/ m (* d (float h)))))
18254 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18255 (> (/ (truncate m) h) 0))
18256 (format fmt (/ m (float h))))
18257 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18258 (format fmt m))
18259 ;; fall back to smallest time unit with a format
18260 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18261 (format fmt (/ m (float h))))
18262 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18263 (format fmt (/ m (* d (float h)))))
18264 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18265 (format fmt (/ m (* w d (float h)))))
18266 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18267 (format fmt (/ m (* mo d (float h)))))
18268 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18269 (format fmt (/ m (* y d (float h))))))
18270 ;; standard (non-fractional) format, with single format string
18271 (if (stringp org-time-clocksum-format)
18272 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18273 ;; separate formats components
18274 (and (setq fmt (plist-get org-time-clocksum-format :years))
18275 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18276 (plist-get org-time-clocksum-format :require-years))
18277 (setq clocksum (concat clocksum (format fmt n))
18278 m (- m (* n y d h))))
18279 (and (setq fmt (plist-get org-time-clocksum-format :months))
18280 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18281 (plist-get org-time-clocksum-format :require-months))
18282 (setq clocksum (concat clocksum (format fmt n))
18283 m (- m (* n mo d h))))
18284 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18285 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18286 (plist-get org-time-clocksum-format :require-weeks))
18287 (setq clocksum (concat clocksum (format fmt n))
18288 m (- m (* n w d h))))
18289 (and (setq fmt (plist-get org-time-clocksum-format :days))
18290 (or (> (setq n (/ (truncate m) (* d h))) 0)
18291 (plist-get org-time-clocksum-format :require-days))
18292 (setq clocksum (concat clocksum (format fmt n))
18293 m (- m (* n d h))))
18294 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18295 (or (> (setq n (/ (truncate m) h)) 0)
18296 (plist-get org-time-clocksum-format :require-hours))
18297 (setq clocksum (concat clocksum (format fmt n))
18298 m (- m (* n h))))
18299 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18300 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18301 (setq clocksum (concat clocksum (format fmt m))))
18302 ;; return formatted time duration
18303 clocksum))))
18305 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18306 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18307 "Org mode version 8.0")
18309 (defun org-hours-to-clocksum-string (n)
18310 (org-minutes-to-clocksum-string (* n 60)))
18312 (defun org-hh:mm-string-to-minutes (s)
18313 "Convert a string H:MM to a number of minutes.
18314 If the string is just a number, interpret it as minutes.
18315 In fact, the first hh:mm or number in the string will be taken,
18316 there can be extra stuff in the string.
18317 If no number is found, the return value is 0."
18318 (cond
18319 ((integerp s) s)
18320 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18321 (+ (* (string-to-number (match-string 1 s)) 60)
18322 (string-to-number (match-string 2 s))))
18323 ((string-match "\\([0-9]+\\)" s)
18324 (string-to-number (match-string 1 s)))
18325 (t 0)))
18327 (defcustom org-image-actual-width t
18328 "Should we use the actual width of images when inlining them?
18330 When set to t, always use the image width.
18332 When set to a number, use imagemagick (when available) to set
18333 the image's width to this value.
18335 When set to a number in a list, try to get the width from any
18336 #+ATTR.* keyword if it matches a width specification like
18338 #+ATTR_HTML: :width 300px
18340 and fall back on that number if none is found.
18342 When set to nil, try to get the width from an #+ATTR.* keyword
18343 and fall back on the original width if none is found.
18345 This requires Emacs >= 24.1, build with imagemagick support."
18346 :group 'org-appearance
18347 :version "24.4"
18348 :package-version '(Org . "8.0")
18349 :type '(choice
18350 (const :tag "Use the image width" t)
18351 (integer :tag "Use a number of pixels")
18352 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18353 (const :tag "Use #+ATTR* or don't resize" nil)))
18355 (defcustom org-agenda-inhibit-startup nil
18356 "Inhibit startup when preparing agenda buffers.
18357 When this variable is t, the initialization of the Org agenda
18358 buffers is inhibited: e.g. the visibility state is not set, the
18359 tables are not re-aligned, etc."
18360 :type 'boolean
18361 :version "24.3"
18362 :group 'org-agenda)
18364 (define-obsolete-variable-alias
18365 'org-agenda-ignore-drawer-properties
18366 'org-agenda-ignore-properties "25.1")
18368 (defcustom org-agenda-ignore-properties nil
18369 "Avoid updating text properties when building the agenda.
18370 Properties are used to prepare buffers for effort estimates,
18371 appointments, statistics and subtree-local categories.
18372 If you don't use these in the agenda, you can add them to this
18373 list and agenda building will be a bit faster.
18374 The value is a list, with zero or more of the symbols `effort', `appt',
18375 `stats' or `category'."
18376 :type '(set :greedy t
18377 (const effort)
18378 (const appt)
18379 (const stats)
18380 (const category))
18381 :version "25.1"
18382 :package-version '(Org . "8.3")
18383 :group 'org-agenda)
18385 (defun org-duration-string-to-minutes (s &optional output-to-string)
18386 "Convert a duration string S to minutes.
18388 A bare number is interpreted as minutes, modifiers can be set by
18389 customizing `org-effort-durations' (which see).
18391 Entries containing a colon are interpreted as H:MM by
18392 `org-hh:mm-string-to-minutes'."
18393 (let ((result 0)
18394 (re (concat "\\([0-9.]+\\) *\\("
18395 (regexp-opt (mapcar 'car org-effort-durations))
18396 "\\)")))
18397 (while (string-match re s)
18398 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18399 (string-to-number (match-string 1 s))))
18400 (setq s (replace-match "" nil t s)))
18401 (setq result (floor result))
18402 (cl-incf result (org-hh:mm-string-to-minutes s))
18403 (if output-to-string (number-to-string result) result)))
18405 ;;;; Files
18407 (defun org-save-all-org-buffers ()
18408 "Save all Org-mode buffers without user confirmation."
18409 (interactive)
18410 (message "Saving all Org-mode buffers...")
18411 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18412 (when (featurep 'org-id) (org-id-locations-save))
18413 (message "Saving all Org-mode buffers... done"))
18415 (defun org-revert-all-org-buffers ()
18416 "Revert all Org-mode buffers.
18417 Prompt for confirmation when there are unsaved changes.
18418 Be sure you know what you are doing before letting this function
18419 overwrite your changes.
18421 This function is useful in a setup where one tracks org files
18422 with a version control system, to revert on one machine after pulling
18423 changes from another. I believe the procedure must be like this:
18425 1. M-x org-save-all-org-buffers
18426 2. Pull changes from the other machine, resolve conflicts
18427 3. M-x org-revert-all-org-buffers"
18428 (interactive)
18429 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18430 (user-error "Abort"))
18431 (save-excursion
18432 (save-window-excursion
18433 (dolist (b (buffer-list))
18434 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18435 (with-current-buffer b buffer-file-name))
18436 (org-pop-to-buffer-same-window b)
18437 (revert-buffer t 'no-confirm)))
18438 (when (and (featurep 'org-id) org-id-track-globally)
18439 (org-id-locations-load)))))
18441 ;;;; Agenda files
18443 ;;;###autoload
18444 (defun org-switchb (&optional arg)
18445 "Switch between Org buffers.
18447 With \\[universal-argument] prefix, restrict available buffers to files.
18449 With \\[universal-argument] \\[universal-argument] \
18450 prefix, restrict available buffers to agenda files."
18451 (interactive "P")
18452 (let ((blist (org-buffer-list
18453 (cond ((equal arg '(4)) 'files)
18454 ((equal arg '(16)) 'agenda)))))
18455 (org-pop-to-buffer-same-window
18456 (completing-read "Org buffer: "
18457 (mapcar #'list (mapcar #'buffer-name blist))
18458 nil t))))
18460 (defun org-buffer-list (&optional predicate exclude-tmp)
18461 "Return a list of Org buffers.
18462 PREDICATE can be `export', `files' or `agenda'.
18464 export restrict the list to Export buffers.
18465 files restrict the list to buffers visiting Org files.
18466 agenda restrict the list to buffers visiting agenda files.
18468 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18469 (let* ((bfn nil)
18470 (agenda-files (and (eq predicate 'agenda)
18471 (mapcar 'file-truename (org-agenda-files t))))
18472 (filter
18473 (cond
18474 ((eq predicate 'files)
18475 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18476 ((eq predicate 'export)
18477 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18478 ((eq predicate 'agenda)
18479 (lambda (b)
18480 (with-current-buffer b
18481 (and (derived-mode-p 'org-mode)
18482 (setq bfn (buffer-file-name b))
18483 (member (file-truename bfn) agenda-files)))))
18484 (t (lambda (b) (with-current-buffer b
18485 (or (derived-mode-p 'org-mode)
18486 (string-match "\\*Org .*Export"
18487 (buffer-name b)))))))))
18488 (delq nil
18489 (mapcar
18490 (lambda(b)
18491 (if (and (funcall filter b)
18492 (or (not exclude-tmp)
18493 (not (string-match "tmp" (buffer-name b)))))
18495 nil))
18496 (buffer-list)))))
18498 (defun org-agenda-files (&optional unrestricted archives)
18499 "Get the list of agenda files.
18500 Optional UNRESTRICTED means return the full list even if a restriction
18501 is currently in place.
18502 When ARCHIVES is t, include all archive files that are really being
18503 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18504 `org-agenda-archives-mode' is t."
18505 (let ((files
18506 (cond
18507 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18508 ((stringp org-agenda-files) (org-read-agenda-file-list))
18509 ((listp org-agenda-files) org-agenda-files)
18510 (t (error "Invalid value of `org-agenda-files'")))))
18511 (setq files (apply 'append
18512 (mapcar (lambda (f)
18513 (if (file-directory-p f)
18514 (directory-files
18515 f t org-agenda-file-regexp)
18516 (list f)))
18517 files)))
18518 (when org-agenda-skip-unavailable-files
18519 (setq files (delq nil
18520 (mapcar (function
18521 (lambda (file)
18522 (and (file-readable-p file) file)))
18523 files))))
18524 (when (or (eq archives t)
18525 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18526 (setq files (org-add-archive-files files)))
18527 files))
18529 (defun org-agenda-file-p (&optional file)
18530 "Return non-nil, if FILE is an agenda file.
18531 If FILE is omitted, use the file associated with the current
18532 buffer."
18533 (let ((fname (or file (buffer-file-name))))
18534 (and fname
18535 (member (file-truename fname)
18536 (mapcar #'file-truename (org-agenda-files t))))))
18538 (defun org-edit-agenda-file-list ()
18539 "Edit the list of agenda files.
18540 Depending on setup, this either uses customize to edit the variable
18541 `org-agenda-files', or it visits the file that is holding the list. In the
18542 latter case, the buffer is set up in a way that saving it automatically kills
18543 the buffer and restores the previous window configuration."
18544 (interactive)
18545 (if (stringp org-agenda-files)
18546 (let ((cw (current-window-configuration)))
18547 (find-file org-agenda-files)
18548 (setq-local org-window-configuration cw)
18549 (org-add-hook 'after-save-hook
18550 (lambda ()
18551 (set-window-configuration
18552 (prog1 org-window-configuration
18553 (kill-buffer (current-buffer))))
18554 (org-install-agenda-files-menu)
18555 (message "New agenda file list installed"))
18556 nil 'local)
18557 (message "%s" (substitute-command-keys
18558 "Edit list and finish with \\[save-buffer]")))
18559 (customize-variable 'org-agenda-files)))
18561 (defun org-store-new-agenda-file-list (list)
18562 "Set new value for the agenda file list and save it correctly."
18563 (if (stringp org-agenda-files)
18564 (let ((fe (org-read-agenda-file-list t)) b u)
18565 (while (setq b (find-buffer-visiting org-agenda-files))
18566 (kill-buffer b))
18567 (with-temp-file org-agenda-files
18568 (insert
18569 (mapconcat
18570 (lambda (f) ;; Keep un-expanded entries.
18571 (if (setq u (assoc f fe))
18572 (cdr u)
18574 list "\n")
18575 "\n")))
18576 (let ((org-mode-hook nil) (org-inhibit-startup t)
18577 (org-insert-mode-line-in-empty-file nil))
18578 (setq org-agenda-files list)
18579 (customize-save-variable 'org-agenda-files org-agenda-files))))
18581 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18582 "Read the list of agenda files from a file.
18583 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18584 filenames, used by `org-store-new-agenda-file-list' to write back
18585 un-expanded file names."
18586 (when (file-directory-p org-agenda-files)
18587 (error "`org-agenda-files' cannot be a single directory"))
18588 (when (stringp org-agenda-files)
18589 (with-temp-buffer
18590 (insert-file-contents org-agenda-files)
18591 (mapcar
18592 (lambda (f)
18593 (let ((e (expand-file-name (substitute-in-file-name f)
18594 org-directory)))
18595 (if pair-with-expansion
18596 (cons e f)
18597 e)))
18598 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18600 ;;;###autoload
18601 (defun org-cycle-agenda-files ()
18602 "Cycle through the files in `org-agenda-files'.
18603 If the current buffer visits an agenda file, find the next one in the list.
18604 If the current buffer does not, find the first agenda file."
18605 (interactive)
18606 (let* ((fs (or (org-agenda-files t)
18607 (user-error "No agenda files")))
18608 (files (copy-sequence fs))
18609 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18610 file)
18611 (when tcf
18612 (while (and (setq file (pop files))
18613 (not (equal (file-truename file) tcf)))))
18614 (find-file (car (or files fs)))
18615 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18617 (defun org-agenda-file-to-front (&optional to-end)
18618 "Move/add the current file to the top of the agenda file list.
18619 If the file is not present in the list, it is added to the front. If it is
18620 present, it is moved there. With optional argument TO-END, add/move to the
18621 end of the list."
18622 (interactive "P")
18623 (let ((org-agenda-skip-unavailable-files nil)
18624 (file-alist (mapcar (lambda (x)
18625 (cons (file-truename x) x))
18626 (org-agenda-files t)))
18627 (ctf (file-truename
18628 (or buffer-file-name
18629 (user-error "Please save the current buffer to a file"))))
18630 x had)
18631 (setq x (assoc ctf file-alist) had x)
18633 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18634 (if to-end
18635 (setq file-alist (append (delq x file-alist) (list x)))
18636 (setq file-alist (cons x (delq x file-alist))))
18637 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18638 (org-install-agenda-files-menu)
18639 (message "File %s to %s of agenda file list"
18640 (if had "moved" "added") (if to-end "end" "front"))))
18642 (defun org-remove-file (&optional file)
18643 "Remove current file from the list of files in variable `org-agenda-files'.
18644 These are the files which are being checked for agenda entries.
18645 Optional argument FILE means use this file instead of the current."
18646 (interactive)
18647 (let* ((org-agenda-skip-unavailable-files nil)
18648 (file (or file buffer-file-name
18649 (user-error "Current buffer does not visit a file")))
18650 (true-file (file-truename file))
18651 (afile (abbreviate-file-name file))
18652 (files (delq nil (mapcar
18653 (lambda (x)
18654 (unless (equal true-file
18655 (file-truename x))
18657 (org-agenda-files t)))))
18658 (if (not (= (length files) (length (org-agenda-files t))))
18659 (progn
18660 (org-store-new-agenda-file-list files)
18661 (org-install-agenda-files-menu)
18662 (message "Removed from Org Agenda list: %s" afile))
18663 (message "File was not in list: %s (not removed)" afile))))
18665 (defun org-file-menu-entry (file)
18666 (vector file (list 'find-file file) t))
18668 (defun org-check-agenda-file (file)
18669 "Make sure FILE exists. If not, ask user what to do."
18670 (unless (file-exists-p file)
18671 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18672 (abbreviate-file-name file))
18673 (let ((r (downcase (read-char-exclusive))))
18674 (cond
18675 ((equal r ?r)
18676 (org-remove-file file)
18677 (throw 'nextfile t))
18678 (t (user-error "Abort"))))))
18680 (defun org-get-agenda-file-buffer (file)
18681 "Get an agenda buffer visiting FILE.
18682 If the buffer needs to be created, add it to the list of buffers
18683 which might be released later."
18684 (let ((buf (org-find-base-buffer-visiting file)))
18685 (if buf
18686 buf ; just return it
18687 ;; Make a new buffer and remember it
18688 (setq buf (find-file-noselect file))
18689 (when buf (push buf org-agenda-new-buffers))
18690 buf)))
18692 (defun org-release-buffers (blist)
18693 "Release all buffers in list, asking the user for confirmation when needed.
18694 When a buffer is unmodified, it is just killed. When modified, it is saved
18695 \(if the user agrees) and then killed."
18696 (let (file)
18697 (dolist (buf blist)
18698 (setq file (buffer-file-name buf))
18699 (when (and (buffer-modified-p buf)
18700 file
18701 (y-or-n-p (format "Save file %s? " file)))
18702 (with-current-buffer buf (save-buffer)))
18703 (kill-buffer buf))))
18705 (defun org-agenda-prepare-buffers (files)
18706 "Create buffers for all agenda files, protect archived trees and comments."
18707 (interactive)
18708 (let ((pa '(:org-archived t))
18709 (pc '(:org-comment t))
18710 (pall '(:org-archived t :org-comment t))
18711 (inhibit-read-only t)
18712 (org-inhibit-startup org-agenda-inhibit-startup)
18713 (rea (concat ":" org-archive-tag ":"))
18714 re pos)
18715 (setq org-tag-alist-for-agenda nil
18716 org-tag-groups-alist-for-agenda nil)
18717 (save-excursion
18718 (save-restriction
18719 (dolist (file files)
18720 (catch 'nextfile
18721 (if (bufferp file)
18722 (set-buffer file)
18723 (org-check-agenda-file file)
18724 (set-buffer (org-get-agenda-file-buffer file)))
18725 (widen)
18726 (org-set-regexps-and-options 'tags-only)
18727 (setq pos (point))
18728 (or (memq 'category org-agenda-ignore-properties)
18729 (org-refresh-category-properties))
18730 (or (memq 'stats org-agenda-ignore-properties)
18731 (org-refresh-stats-properties))
18732 (or (memq 'effort org-agenda-ignore-properties)
18733 (org-refresh-effort-properties))
18734 (or (memq 'appt org-agenda-ignore-properties)
18735 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18736 (setq org-todo-keywords-for-agenda
18737 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18738 (setq org-done-keywords-for-agenda
18739 (append org-done-keywords-for-agenda org-done-keywords))
18740 (setq org-todo-keyword-alist-for-agenda
18741 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18742 (setq org-tag-alist-for-agenda
18743 (org-uniquify
18744 (append org-tag-alist-for-agenda
18745 org-current-tag-alist)))
18746 ;; Merge current file's tag groups into global
18747 ;; `org-tag-groups-alist-for-agenda'.
18748 (when org-group-tags
18749 (dolist (alist org-tag-groups-alist)
18750 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18751 (if old
18752 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18753 (push alist org-tag-groups-alist-for-agenda)))))
18754 (org-with-silent-modifications
18755 (save-excursion
18756 (remove-text-properties (point-min) (point-max) pall)
18757 (when org-agenda-skip-archived-trees
18758 (goto-char (point-min))
18759 (while (re-search-forward rea nil t)
18760 (when (org-at-heading-p t)
18761 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18762 (goto-char (point-min))
18763 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18764 (while (re-search-forward re nil t)
18765 (when (save-match-data (org-in-commented-heading-p t))
18766 (add-text-properties
18767 (match-beginning 0) (org-end-of-subtree t) pc)))))
18768 (goto-char pos)))))
18769 (setq org-todo-keywords-for-agenda
18770 (org-uniquify org-todo-keywords-for-agenda))
18771 (setq org-todo-keyword-alist-for-agenda
18772 (org-uniquify org-todo-keyword-alist-for-agenda))))
18775 ;;;; CDLaTeX minor mode
18777 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18778 "Keymap for the minor `org-cdlatex-mode'.")
18780 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18781 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18782 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18783 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18784 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18786 (defvar org-cdlatex-texmathp-advice-is-done nil
18787 "Flag remembering if we have applied the advice to texmathp already.")
18789 (define-minor-mode org-cdlatex-mode
18790 "Toggle the minor `org-cdlatex-mode'.
18791 This mode supports entering LaTeX environment and math in LaTeX fragments
18792 in Org-mode.
18793 \\{org-cdlatex-mode-map}"
18794 nil " OCDL" nil
18795 (when org-cdlatex-mode
18796 (require 'cdlatex)
18797 (run-hooks 'cdlatex-mode-hook)
18798 (cdlatex-compute-tables))
18799 (unless org-cdlatex-texmathp-advice-is-done
18800 (setq org-cdlatex-texmathp-advice-is-done t)
18801 (defadvice texmathp (around org-math-always-on activate)
18802 "Always return t in org-mode buffers.
18803 This is because we want to insert math symbols without dollars even outside
18804 the LaTeX math segments. If Orgmode thinks that point is actually inside
18805 an embedded LaTeX fragment, let texmathp do its job.
18806 \\[org-cdlatex-mode-map]"
18807 (interactive)
18808 (let (p)
18809 (cond
18810 ((not (derived-mode-p 'org-mode)) ad-do-it)
18811 ((eq this-command 'cdlatex-math-symbol)
18812 (setq ad-return-value t
18813 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18815 (let ((p (org-inside-LaTeX-fragment-p)))
18816 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18817 (setq ad-return-value t
18818 texmathp-why '("Org-mode embedded math" . 0))
18819 (when p ad-do-it)))))))))
18821 (defun turn-on-org-cdlatex ()
18822 "Unconditionally turn on `org-cdlatex-mode'."
18823 (org-cdlatex-mode 1))
18825 (defun org-try-cdlatex-tab ()
18826 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18827 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18828 - inside a LaTeX fragment, or
18829 - after the first word in a line, where an abbreviation expansion could
18830 insert a LaTeX environment."
18831 (when org-cdlatex-mode
18832 (cond
18833 ;; Before any word on the line: No expansion possible.
18834 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18835 ;; Just after first word on the line: Expand it. Make sure it
18836 ;; cannot happen on headlines, though.
18837 ((save-excursion
18838 (skip-chars-backward "a-zA-Z0-9*")
18839 (skip-chars-backward " \t")
18840 (and (bolp) (not (org-at-heading-p))))
18841 (cdlatex-tab) t)
18842 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18844 (defun org-cdlatex-underscore-caret (&optional _arg)
18845 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18846 Revert to the normal definition outside of these fragments."
18847 (interactive "P")
18848 (if (org-inside-LaTeX-fragment-p)
18849 (call-interactively 'cdlatex-sub-superscript)
18850 (let (org-cdlatex-mode)
18851 (call-interactively (key-binding (vector last-input-event))))))
18853 (defun org-cdlatex-math-modify (&optional _arg)
18854 "Execute `cdlatex-math-modify' in LaTeX fragments.
18855 Revert to the normal definition outside of these fragments."
18856 (interactive "P")
18857 (if (org-inside-LaTeX-fragment-p)
18858 (call-interactively 'cdlatex-math-modify)
18859 (let (org-cdlatex-mode)
18860 (call-interactively (key-binding (vector last-input-event))))))
18862 (defun org-cdlatex-environment-indent (&optional environment item)
18863 "Execute `cdlatex-environment' and indent the inserted environment.
18865 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18867 The inserted environment is indented to current indentation
18868 unless point is at the beginning of the line, in which the
18869 environment remains unintended."
18870 (interactive)
18871 ;; cdlatex-environment always return nil. Therefore, capture output
18872 ;; first and determine if an environment was selected.
18873 (let* ((beg (point-marker))
18874 (end (copy-marker (point) t))
18875 (inserted (progn
18876 (ignore-errors (cdlatex-environment environment item))
18877 (< beg end)))
18878 ;; Figure out how many lines to move forward after the
18879 ;; environment has been inserted.
18880 (lines (when inserted
18881 (save-excursion
18882 (- (cl-loop while (< beg (point))
18883 with x = 0
18884 do (forward-line -1)
18885 (cl-incf x)
18886 finally return x)
18887 (if (progn (goto-char beg)
18888 (and (progn (skip-chars-forward " \t") (eolp))
18889 (progn (skip-chars-backward " \t") (bolp))))
18890 1 0)))))
18891 (env (org-trim (delete-and-extract-region beg end))))
18892 (when inserted
18893 ;; Get indentation of next line unless at column 0.
18894 (let ((ind (if (bolp) 0
18895 (save-excursion
18896 (org-return-indent)
18897 (prog1 (org-get-indentation)
18898 (when (progn (skip-chars-forward " \t") (eolp))
18899 (delete-region beg (point)))))))
18900 (bol (progn (skip-chars-backward " \t") (bolp))))
18901 ;; Insert a newline before environment unless at column zero
18902 ;; to "escape" the current line. Insert a newline if
18903 ;; something is one the same line as \end{ENVIRONMENT}.
18904 (insert
18905 (concat (unless bol "\n") env
18906 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18907 (unless (zerop ind)
18908 (save-excursion
18909 (goto-char beg)
18910 (while (< (point) end)
18911 (unless (eolp) (org-indent-line-to ind))
18912 (forward-line))))
18913 (goto-char beg)
18914 (forward-line lines)
18915 (org-indent-line-to ind)))
18916 (set-marker beg nil)
18917 (set-marker end nil)))
18920 ;;;; LaTeX fragments
18922 (defun org-inside-LaTeX-fragment-p ()
18923 "Test if point is inside a LaTeX fragment.
18924 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18925 sequence appearing also before point.
18926 Even though the matchers for math are configurable, this function assumes
18927 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18928 delimiters are skipped when they have been removed by customization.
18929 The return value is nil, or a cons cell with the delimiter and the
18930 position of this delimiter.
18932 This function does a reasonably good job, but can locally be fooled by
18933 for example currency specifications. For example it will assume being in
18934 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18935 fragments that are properly closed, but during editing, we have to live
18936 with the uncertainty caused by missing closing delimiters. This function
18937 looks only before point, not after."
18938 (catch 'exit
18939 (let ((pos (point))
18940 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18941 (lim (progn
18942 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18943 (point)))
18944 dd-on str (start 0) m re)
18945 (goto-char pos)
18946 (when dodollar
18947 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18948 re (nth 1 (assoc "$" org-latex-regexps)))
18949 (while (string-match re str start)
18950 (cond
18951 ((= (match-end 0) (length str))
18952 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18953 ((= (match-end 0) (- (length str) 5))
18954 (throw 'exit nil))
18955 (t (setq start (match-end 0))))))
18956 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18957 (goto-char pos)
18958 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18959 (and (match-beginning 2) (throw 'exit nil))
18960 ;; count $$
18961 (while (re-search-backward "\\$\\$" lim t)
18962 (setq dd-on (not dd-on)))
18963 (goto-char pos)
18964 (when dd-on (cons "$$" m))))))
18966 (defun org-inside-latex-macro-p ()
18967 "Is point inside a LaTeX macro or its arguments?"
18968 (save-match-data
18969 (org-in-regexp
18970 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18972 (defun org--format-latex-make-overlay (beg end image)
18973 "Build an overlay between BEG and END using IMAGE file."
18974 (let ((ov (make-overlay beg end)))
18975 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18976 (overlay-put ov 'evaporate t)
18977 (overlay-put ov
18978 'modification-hooks
18979 (list (lambda (o _flag _beg _end &optional _l)
18980 (delete-overlay o))))
18981 (if (featurep 'xemacs)
18982 (progn
18983 (overlay-put ov 'invisible t)
18984 (overlay-put ov 'end-glyph (make-glyph (vector 'png :file image))))
18985 (overlay-put ov
18986 'display
18987 (list 'image :type 'png :file image :ascent 'center)))))
18989 (defun org--list-latex-overlays (&optional beg end)
18990 "List all Org LaTeX overlays in current buffer.
18991 Limit to overlays between BEG and END when those are provided."
18992 (cl-remove-if-not
18993 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
18994 (overlays-in (or beg (point-min)) (or end (point-max)))))
18996 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
18997 "Remove all overlays with LaTeX fragment images in current buffer.
18998 When optional arguments BEG and END are non-nil, remove all
18999 overlays between them instead. Return a non-nil value when some
19000 overlays were removed, nil otherwise."
19001 (let ((overlays (org--list-latex-overlays beg end)))
19002 (mapc #'delete-overlay overlays)
19003 overlays))
19005 (define-obsolete-function-alias
19006 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
19007 (defun org-toggle-latex-fragment (&optional arg)
19008 "Preview the LaTeX fragment at point, or all locally or globally.
19010 If the cursor is on a LaTeX fragment, create the image and overlay
19011 it over the source code, if there is none. Remove it otherwise.
19012 If there is no fragment at point, display all fragments in the
19013 current section.
19015 With prefix ARG, preview or clear image for all fragments in the
19016 current subtree or in the whole buffer when used before the first
19017 headline. With a double prefix ARG \\[universal-argument] \
19018 \\[universal-argument] preview or clear images
19019 for all fragments in the buffer."
19020 (interactive "P")
19021 (when (display-graphic-p)
19022 (catch 'exit
19023 (save-excursion
19024 (let ((window-start (window-start)) msg)
19025 (save-restriction
19026 (cond
19027 ((or (equal arg '(16))
19028 (and (equal arg '(4))
19029 (org-with-limited-levels (org-before-first-heading-p))))
19030 (if (org-remove-latex-fragment-image-overlays)
19031 (progn (message "LaTeX fragments images removed from buffer")
19032 (throw 'exit nil))
19033 (setq msg "Creating images for buffer...")))
19034 ((equal arg '(4))
19035 (org-with-limited-levels (org-back-to-heading t))
19036 (let ((beg (point))
19037 (end (progn (org-end-of-subtree t) (point))))
19038 (if (org-remove-latex-fragment-image-overlays beg end)
19039 (progn
19040 (message "LaTeX fragment images removed from subtree")
19041 (throw 'exit nil))
19042 (setq msg "Creating images for subtree...")
19043 (narrow-to-region beg end))))
19044 ((let ((datum (org-element-context)))
19045 (when (memq (org-element-type datum)
19046 '(latex-environment latex-fragment))
19047 (let* ((beg (org-element-property :begin datum))
19048 (end (org-element-property :end datum)))
19049 (if (org-remove-latex-fragment-image-overlays beg end)
19050 (progn (message "LaTeX fragment image removed")
19051 (throw 'exit nil))
19052 (narrow-to-region beg end)
19053 (setq msg "Creating image..."))))))
19055 (org-with-limited-levels
19056 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19057 (outline-previous-heading)
19058 (point)))
19059 (end (progn (outline-next-heading) (point))))
19060 (if (org-remove-latex-fragment-image-overlays beg end)
19061 (progn
19062 (message "LaTeX fragment images removed from section")
19063 (throw 'exit nil))
19064 (setq msg "Creating images for section...")
19065 (narrow-to-region beg end))))))
19066 (let ((file (buffer-file-name (buffer-base-buffer))))
19067 (org-format-latex
19068 (concat org-latex-preview-ltxpng-directory "org-ltxpng")
19069 ;; Emacs cannot overlay images from remote hosts.
19070 ;; Create it in `temporary-file-directory' instead.
19071 (if (or (not file) (file-remote-p file))
19072 temporary-file-directory
19073 default-directory)
19074 'overlays msg 'forbuffer
19075 org-latex-create-formula-image-program)))
19076 ;; Work around a bug that doesn't restore window's start
19077 ;; when widening back the buffer.
19078 (set-window-start nil window-start)
19079 (message (concat msg "done")))))))
19081 (defun org-format-latex
19082 (prefix &optional dir overlays msg forbuffer processing-type)
19083 "Replace LaTeX fragments with links to an image, and produce images.
19085 When optional argument OVERLAYS is non-nil, display the image on
19086 top of the fragment instead of replacing it.
19088 PROCESSING-TYPE is the conversion method to use, as a symbol.
19090 Some of the options can be changed using the variable
19091 `org-format-latex-options', which see."
19092 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19093 (unless (eq processing-type 'verbatim)
19094 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19095 (cnt 0)
19096 checkdir-flag)
19097 (goto-char (point-min))
19098 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19099 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19100 (overlay-recenter (point-max)))
19101 (while (re-search-forward math-regexp nil t)
19102 (unless (and overlays
19103 (eq (get-char-property (point) 'org-overlay-type)
19104 'org-latex-overlay))
19105 (let* ((context (org-element-context))
19106 (type (org-element-type context)))
19107 (when (memq type '(latex-environment latex-fragment))
19108 (let ((block-type (eq type 'latex-environment))
19109 (value (org-element-property :value context))
19110 (beg (org-element-property :begin context))
19111 (end (save-excursion
19112 (goto-char (org-element-property :end context))
19113 (skip-chars-backward " \r\t\n")
19114 (point))))
19115 (cl-case processing-type
19116 (mathjax
19117 ;; Prepare for MathJax processing.
19118 (if (not (string-match "\\`\\$\\$?" value))
19119 (goto-char end)
19120 (delete-region beg end)
19121 (if (string= (match-string 0 value) "$$")
19122 (insert "\\[" (substring value 2 -2) "\\]")
19123 (insert "\\(" (substring value 1 -1) "\\)"))))
19124 ((dvipng imagemagick)
19125 ;; Process to an image.
19126 (cl-incf cnt)
19127 (goto-char beg)
19128 (let* ((face (face-at-point))
19129 ;; Get the colors from the face at point.
19131 (let ((color (plist-get org-format-latex-options
19132 :foreground)))
19133 (if (and forbuffer (eq color 'auto))
19134 (face-attribute face :foreground nil 'default)
19135 color)))
19137 (let ((color (plist-get org-format-latex-options
19138 :background)))
19139 (if (and forbuffer (eq color 'auto))
19140 (face-attribute face :background nil 'default)
19141 color)))
19142 (hash (sha1 (prin1-to-string
19143 (list org-format-latex-header
19144 org-latex-default-packages-alist
19145 org-latex-packages-alist
19146 org-format-latex-options
19147 forbuffer value fg bg))))
19148 (absprefix (expand-file-name prefix dir))
19149 (linkfile (format "%s_%s.png" prefix hash))
19150 (movefile (format "%s_%s.png" absprefix hash))
19151 (sep (and block-type "\n\n"))
19152 (link (concat sep "[[file:" linkfile "]]" sep))
19153 (options
19154 (org-combine-plists
19155 org-format-latex-options
19156 `(:foreground ,fg :background ,bg))))
19157 (when msg (message msg cnt))
19158 (unless checkdir-flag ; Ensure the directory exists.
19159 (setq checkdir-flag t)
19160 (let ((todir (file-name-directory absprefix)))
19161 (unless (file-directory-p todir)
19162 (make-directory todir t))))
19163 (unless (file-exists-p movefile)
19164 (org-create-formula-image
19165 value movefile options forbuffer processing-type))
19166 (if overlays
19167 (progn
19168 (dolist (o (overlays-in beg end))
19169 (when (eq (overlay-get o 'org-overlay-type)
19170 'org-latex-overlay)
19171 (delete-overlay o)))
19172 (org--format-latex-make-overlay beg end movefile)
19173 (goto-char end))
19174 (delete-region beg end)
19175 (insert
19176 (org-add-props link
19177 (list 'org-latex-src
19178 (replace-regexp-in-string "\"" "" value)
19179 'org-latex-src-embed-type
19180 (if block-type 'paragraph 'character)))))))
19181 (mathml
19182 ;; Process to MathML.
19183 (unless (org-format-latex-mathml-available-p)
19184 (user-error "LaTeX to MathML converter not configured"))
19185 (cl-incf cnt)
19186 (when msg (message msg cnt))
19187 (goto-char beg)
19188 (delete-region beg end)
19189 (insert (org-format-latex-as-mathml
19190 value block-type prefix dir)))
19191 (otherwise
19192 (error "Unknown conversion type %s for LaTeX fragments"
19193 processing-type)))))))))))
19195 (defun org-create-math-formula (latex-frag &optional mathml-file)
19196 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19197 Use `org-latex-to-mathml-convert-command'. If the conversion is
19198 sucessful, return the portion between \"<math...> </math>\"
19199 elements otherwise return nil. When MATHML-FILE is specified,
19200 write the results in to that file. When invoked as an
19201 interactive command, prompt for LATEX-FRAG, with initial value
19202 set to the current active region and echo the results for user
19203 inspection."
19204 (interactive (list (let ((frag (when (org-region-active-p)
19205 (buffer-substring-no-properties
19206 (region-beginning) (region-end)))))
19207 (read-string "LaTeX Fragment: " frag nil frag))))
19208 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19209 (let* ((tmp-in-file
19210 (let ((file (file-relative-name
19211 (make-temp-name (expand-file-name "ltxmathml-in")))))
19212 (write-region latex-frag nil file)
19213 file))
19214 (tmp-out-file (file-relative-name
19215 (make-temp-name (expand-file-name "ltxmathml-out"))))
19216 (cmd (format-spec
19217 org-latex-to-mathml-convert-command
19218 `((?j . ,(and org-latex-to-mathml-jar-file
19219 (shell-quote-argument
19220 (expand-file-name
19221 org-latex-to-mathml-jar-file))))
19222 (?I . ,(shell-quote-argument tmp-in-file))
19223 (?i . ,latex-frag)
19224 (?o . ,(shell-quote-argument tmp-out-file)))))
19225 mathml shell-command-output)
19226 (when (org-called-interactively-p 'any)
19227 (unless (org-format-latex-mathml-available-p)
19228 (user-error "LaTeX to MathML converter not configured")))
19229 (message "Running %s" cmd)
19230 (setq shell-command-output (shell-command-to-string cmd))
19231 (setq mathml
19232 (when (file-readable-p tmp-out-file)
19233 (with-current-buffer (find-file-noselect tmp-out-file t)
19234 (goto-char (point-min))
19235 (when (re-search-forward
19236 (concat
19237 (regexp-quote
19238 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19239 "[^>]*?>"
19240 "\\(.\\|\n\\)*"
19241 "</math>")
19242 nil t)
19243 (prog1 (match-string 0) (kill-buffer))))))
19244 (cond
19245 (mathml
19246 (setq mathml
19247 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19248 (when mathml-file
19249 (write-region mathml nil mathml-file))
19250 (when (org-called-interactively-p 'any)
19251 (message mathml)))
19252 ((message "LaTeX to MathML conversion failed")
19253 (message shell-command-output)))
19254 (delete-file tmp-in-file)
19255 (when (file-exists-p tmp-out-file)
19256 (delete-file tmp-out-file))
19257 mathml))
19259 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19260 prefix &optional dir)
19261 "Use `org-create-math-formula' but check local cache first."
19262 (let* ((absprefix (expand-file-name prefix dir))
19263 (print-length nil) (print-level nil)
19264 (formula-id (concat
19265 "formula-"
19266 (sha1
19267 (prin1-to-string
19268 (list latex-frag
19269 org-latex-to-mathml-convert-command)))))
19270 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19271 (formula-cache-dir (file-name-directory formula-cache)))
19273 (unless (file-directory-p formula-cache-dir)
19274 (make-directory formula-cache-dir t))
19276 (unless (file-exists-p formula-cache)
19277 (org-create-math-formula latex-frag formula-cache))
19279 (if (file-exists-p formula-cache)
19280 ;; Successful conversion. Return the link to MathML file.
19281 (org-add-props
19282 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19283 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19284 'org-latex-src-embed-type (if latex-frag-type
19285 'paragraph 'character)))
19286 ;; Failed conversion. Return the LaTeX fragment verbatim
19287 latex-frag)))
19289 (defun org-create-formula-image (string tofile options buffer &optional type)
19290 "Create an image from LaTeX source using dvipng or convert.
19291 This function calls either `org-create-formula-image-with-dvipng'
19292 or `org-create-formula-image-with-imagemagick' depending on the
19293 value of `org-latex-create-formula-image-program' or on the value
19294 of the optional TYPE variable.
19296 Note: ultimately these two function should be combined as they
19297 share a good deal of logic."
19298 (org-check-external-command
19299 "latex" "needed to convert LaTeX fragments to images")
19300 (funcall
19301 (cl-case (or type org-latex-create-formula-image-program)
19302 (dvipng
19303 (org-check-external-command
19304 "dvipng" "needed to convert LaTeX fragments to images")
19305 #'org-create-formula-image-with-dvipng)
19306 (imagemagick
19307 (org-check-external-command
19308 "convert" "you need to install imagemagick")
19309 #'org-create-formula-image-with-imagemagick)
19310 (t (error
19311 "Invalid value of `org-latex-create-formula-image-program'")))
19312 string tofile options buffer))
19314 (declare-function org-export-get-backend "ox" (name))
19315 (declare-function org-export--get-global-options "ox" (&optional backend))
19316 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19317 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19318 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19319 (defun org-create-formula--latex-header ()
19320 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19321 (let ((info (org-combine-plists (org-export--get-global-options
19322 (org-export-get-backend 'latex))
19323 (org-export--get-inbuffer-options
19324 (org-export-get-backend 'latex)))))
19325 (org-latex-guess-babel-language
19326 (org-latex-guess-inputenc
19327 (org-splice-latex-header
19328 org-format-latex-header
19329 org-latex-default-packages-alist
19330 org-latex-packages-alist t
19331 (plist-get info :latex-header)))
19332 info)))
19334 (defun org--get-display-dpi ()
19335 "Get the DPI of the display.
19337 Assumes that the display has the same pixel width in the
19338 horizontal and vertical directions."
19339 (if (display-graphic-p)
19340 (round (/ (display-pixel-height)
19341 (/ (display-mm-height) 25.4)))
19342 (error "Attempt to calculate the dpi of a non-graphic display")))
19344 ;; This function borrows from Ganesh Swami's latex2png.el
19345 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19346 "This calls dvipng."
19347 (require 'ox-latex)
19348 (let* ((tmpdir (if (featurep 'xemacs)
19349 (temp-directory)
19350 temporary-file-directory))
19351 (texfilebase (make-temp-name
19352 (expand-file-name "orgtex" tmpdir)))
19353 (texfile (concat texfilebase ".tex"))
19354 (dvifile (concat texfilebase ".dvi"))
19355 (pngfile (concat texfilebase ".png"))
19356 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19357 ;; This assumes that the display has the same pixel width in
19358 ;; the horizontal and vertical directions
19359 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19360 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19361 "Black"))
19362 (bg (or (plist-get options (if buffer :background :html-background))
19363 "Transparent")))
19364 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19365 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19366 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19367 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19368 (let ((latex-header (org-create-formula--latex-header)))
19369 (with-temp-file texfile
19370 (insert latex-header)
19371 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19372 (let ((dir default-directory))
19373 (ignore-errors
19374 (cd tmpdir)
19375 (call-process "latex" nil nil nil texfile))
19376 (cd dir))
19377 (if (not (file-exists-p dvifile))
19378 (progn (message "Failed to create dvi file from %s" texfile) nil)
19379 (ignore-errors
19380 (if (featurep 'xemacs)
19381 (call-process "dvipng" nil nil nil
19382 "-fg" fg "-bg" bg
19383 "-T" "tight"
19384 "-o" pngfile
19385 dvifile)
19386 (call-process "dvipng" nil nil nil
19387 "-fg" fg "-bg" bg
19388 "-D" dpi
19389 ;;"-x" scale "-y" scale
19390 "-T" "tight"
19391 "-o" pngfile
19392 dvifile)))
19393 (if (not (file-exists-p pngfile))
19394 (if org-format-latex-signal-error
19395 (error "Failed to create png file from %s" texfile)
19396 (message "Failed to create png file from %s" texfile)
19397 nil)
19398 ;; Use the requested file name and clean up
19399 (copy-file pngfile tofile 'replace)
19400 (dolist (e '(".dvi" ".tex" ".aux" ".log" ".png" ".out"))
19401 (when (file-exists-p (concat texfilebase e))
19402 (delete-file (concat texfilebase e))))
19403 pngfile))))
19405 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19406 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19407 "This calls convert, which is included into imagemagick."
19408 (require 'ox-latex)
19409 (let* ((tmpdir (if (featurep 'xemacs)
19410 (temp-directory)
19411 temporary-file-directory))
19412 (texfilebase (make-temp-name
19413 (expand-file-name "orgtex" tmpdir)))
19414 (texfile (concat texfilebase ".tex"))
19415 (pdffile (concat texfilebase ".pdf"))
19416 (pngfile (concat texfilebase ".png"))
19417 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19418 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19419 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19420 "black"))
19421 (bg (or (plist-get options (if buffer :background :html-background))
19422 "white")))
19423 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19424 (setq fg (org-latex-color-format fg)))
19425 (if (eq bg 'default) (setq bg (org-latex-color :background))
19426 (setq bg (org-latex-color-format
19427 (if (string= bg "Transparent") "white" bg))))
19428 (let ((latex-header (org-create-formula--latex-header)))
19429 (with-temp-file texfile
19430 (insert latex-header)
19431 (insert "\n\\begin{document}\n"
19432 "\\definecolor{fg}{rgb}{" fg "}\n"
19433 "\\definecolor{bg}{rgb}{" bg "}\n"
19434 "\n\\pagecolor{bg}\n"
19435 "\n{\\color{fg}\n"
19436 string
19437 "\n}\n"
19438 "\n\\end{document}\n")))
19439 (org-latex-compile texfile t)
19440 (if (not (file-exists-p pdffile))
19441 (progn (message "Failed to create pdf file from %s" texfile) nil)
19442 (ignore-errors
19443 (if (featurep 'xemacs)
19444 (call-process "convert" nil nil nil
19445 "-density" "96"
19446 "-trim"
19447 "-antialias"
19448 pdffile
19449 "-quality" "100"
19450 ;; "-sharpen" "0x1.0"
19451 pngfile)
19452 (call-process "convert" nil nil nil
19453 "-density" dpi
19454 "-trim"
19455 "-antialias"
19456 pdffile
19457 "-quality" "100"
19458 ;; "-sharpen" "0x1.0"
19459 pngfile)))
19460 (if (not (file-exists-p pngfile))
19461 (if org-format-latex-signal-error
19462 (error "Failed to create png file from %s" texfile)
19463 (message "Failed to create png file from %s" texfile)
19464 nil)
19465 ;; Use the requested file name and clean up
19466 (copy-file pngfile tofile 'replace)
19467 (dolist (e '(".pdf" ".tex" ".aux" ".log" ".png"))
19468 (when (file-exists-p (concat texfilebase e))
19469 (delete-file (concat texfilebase e))))
19470 pngfile))))
19472 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19473 "Fill a LaTeX header template TPL.
19474 In the template, the following place holders will be recognized:
19476 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19477 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19478 [PACKAGES] \\usepackage statements for PKG
19479 [NO-PACKAGES] do not include PKG
19480 [EXTRA] the string EXTRA
19481 [NO-EXTRA] do not include EXTRA
19483 For backward compatibility, if both the positive and the negative place
19484 holder is missing, the positive one (without the \"NO-\") will be
19485 assumed to be present at the end of the template.
19486 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19487 EXTRA is a string.
19488 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19489 (let (rpl (end ""))
19490 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19491 (setq rpl (if (or (match-end 1) (not def-pkg))
19492 "" (org-latex-packages-to-string def-pkg snippets-p t))
19493 tpl (replace-match rpl t t tpl))
19494 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19496 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19497 (setq rpl (if (or (match-end 1) (not pkg))
19498 "" (org-latex-packages-to-string pkg snippets-p t))
19499 tpl (replace-match rpl t t tpl))
19500 (when pkg (setq end
19501 (concat end "\n"
19502 (org-latex-packages-to-string pkg snippets-p)))))
19504 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19505 (setq rpl (if (or (match-end 1) (not extra))
19506 "" (concat extra "\n"))
19507 tpl (replace-match rpl t t tpl))
19508 (when (and extra (string-match "\\S-" extra))
19509 (setq end (concat end "\n" extra))))
19511 (if (string-match "\\S-" end)
19512 (concat tpl "\n" end)
19513 tpl)))
19515 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19516 "Turn an alist of packages into a string with the \\usepackage macros."
19517 (setq pkg (mapconcat (lambda(p)
19518 (cond
19519 ((stringp p) p)
19520 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19521 (format "%% Package %s omitted" (cadr p)))
19522 ((equal "" (car p))
19523 (format "\\usepackage{%s}" (cadr p)))
19525 (format "\\usepackage[%s]{%s}"
19526 (car p) (cadr p)))))
19528 "\n"))
19529 (if newline (concat pkg "\n") pkg))
19531 (defun org-dvipng-color (attr)
19532 "Return a RGB color specification for dvipng."
19533 (apply 'format "rgb %s %s %s"
19534 (mapcar 'org-normalize-color
19535 (if (featurep 'xemacs)
19536 (color-rgb-components
19537 (face-property 'default
19538 (cond ((eq attr :foreground) 'foreground)
19539 ((eq attr :background) 'background))))
19540 (color-values (face-attribute 'default attr nil))))))
19542 (defun org-dvipng-color-format (color-name)
19543 "Convert COLOR-NAME to a RGB color value for dvipng."
19544 (apply 'format "rgb %s %s %s"
19545 (mapcar 'org-normalize-color
19546 (color-values color-name))))
19548 (defun org-latex-color (attr)
19549 "Return a RGB color for the LaTeX color package."
19550 (apply 'format "%s,%s,%s"
19551 (mapcar 'org-normalize-color
19552 (if (featurep 'xemacs)
19553 (color-rgb-components
19554 (face-property 'default
19555 (cond ((eq attr :foreground) 'foreground)
19556 ((eq attr :background) 'background))))
19557 (color-values (face-attribute 'default attr nil))))))
19559 (defun org-latex-color-format (color-name)
19560 "Convert COLOR-NAME to a RGB color value."
19561 (apply 'format "%s,%s,%s"
19562 (mapcar 'org-normalize-color
19563 (color-values color-name))))
19565 (defun org-normalize-color (value)
19566 "Return string to be used as color value for an RGB component."
19567 (format "%g" (/ value 65535.0)))
19571 ;; Image display
19573 (defvar-local org-inline-image-overlays nil)
19575 (defun org-toggle-inline-images (&optional include-linked)
19576 "Toggle the display of inline images.
19577 INCLUDE-LINKED is passed to `org-display-inline-images'."
19578 (interactive "P")
19579 (if org-inline-image-overlays
19580 (progn
19581 (org-remove-inline-images)
19582 (when (org-called-interactively-p 'interactive)
19583 (message "Inline image display turned off")))
19584 (org-display-inline-images include-linked)
19585 (when (org-called-interactively-p 'interactive)
19586 (message (if org-inline-image-overlays
19587 (format "%d images displayed inline"
19588 (length org-inline-image-overlays))
19589 "No images to display inline")))))
19591 (defun org-redisplay-inline-images ()
19592 "Refresh the display of inline images."
19593 (interactive)
19594 (if (not org-inline-image-overlays)
19595 (org-toggle-inline-images)
19596 (org-toggle-inline-images)
19597 (org-toggle-inline-images)))
19599 (defun org-display-inline-images (&optional include-linked refresh beg end)
19600 "Display inline images.
19602 An inline image is a link which follows either of these
19603 conventions:
19605 1. Its path is a file with an extension matching return value
19606 from `image-file-name-regexp' and it has no contents.
19608 2. Its description consists in a single link of the previous
19609 type.
19611 When optional argument INCLUDE-LINKED is non-nil, also links with
19612 a text description part will be inlined. This can be nice for
19613 a quick look at those images, but it does not reflect what
19614 exported files will look like.
19616 When optional argument REFRESH is non-nil, refresh existing
19617 images between BEG and END. This will create new image displays
19618 only if necessary. BEG and END default to the buffer
19619 boundaries."
19620 (interactive "P")
19621 (when (display-graphic-p)
19622 (unless refresh
19623 (org-remove-inline-images)
19624 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19625 (org-with-wide-buffer
19626 (goto-char (or beg (point-min)))
19627 (let ((case-fold-search t)
19628 (file-extension-re (image-file-name-regexp)))
19629 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19630 (let ((link (save-match-data (org-element-context))))
19631 ;; Check if we're at an inline image.
19632 (when (and (equal (org-element-property :type link) "file")
19633 (or include-linked
19634 (not (org-element-property :contents-begin link)))
19635 (let ((parent (org-element-property :parent link)))
19636 (or (not (eq (org-element-type parent) 'link))
19637 (not (cdr (org-element-contents parent)))))
19638 (org-string-match-p file-extension-re
19639 (org-element-property :path link)))
19640 (let ((file (expand-file-name
19641 (org-link-unescape
19642 (org-element-property :path link)))))
19643 (when (file-exists-p file)
19644 (let ((width
19645 ;; Apply `org-image-actual-width' specifications.
19646 (cond
19647 ((not (image-type-available-p 'imagemagick)) nil)
19648 ((eq org-image-actual-width t) nil)
19649 ((listp org-image-actual-width)
19651 ;; First try to find a width among
19652 ;; attributes associated to the paragraph
19653 ;; containing link.
19654 (let ((paragraph
19655 (let ((e link))
19656 (while (and (setq e (org-element-property
19657 :parent e))
19658 (not (eq (org-element-type e)
19659 'paragraph))))
19660 e)))
19661 (when paragraph
19662 (save-excursion
19663 (goto-char (org-element-property :begin paragraph))
19664 (when
19665 (re-search-forward
19666 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19667 (org-element-property
19668 :post-affiliated paragraph)
19670 (string-to-number (match-string 1))))))
19671 ;; Otherwise, fall-back to provided number.
19672 (car org-image-actual-width)))
19673 ((numberp org-image-actual-width)
19674 org-image-actual-width)))
19675 (old (get-char-property-and-overlay
19676 (org-element-property :begin link)
19677 'org-image-overlay)))
19678 (if (and (car-safe old) refresh)
19679 (image-refresh (overlay-get (cdr old) 'display))
19680 (let ((image (create-image file
19681 (and width 'imagemagick)
19683 :width width)))
19684 (when image
19685 (let* ((link
19686 ;; If inline image is the description
19687 ;; of another link, be sure to
19688 ;; consider the latter as the one to
19689 ;; apply the overlay on.
19690 (let ((parent
19691 (org-element-property :parent link)))
19692 (if (eq (org-element-type parent) 'link)
19693 parent
19694 link)))
19695 (ov (make-overlay
19696 (org-element-property :begin link)
19697 (progn
19698 (goto-char
19699 (org-element-property :end link))
19700 (skip-chars-backward " \t")
19701 (point)))))
19702 (overlay-put ov 'display image)
19703 (overlay-put ov 'face 'default)
19704 (overlay-put ov 'org-image-overlay t)
19705 (overlay-put
19706 ov 'modification-hooks
19707 (list 'org-display-inline-remove-overlay))
19708 (push ov org-inline-image-overlays)))))))))))))))
19710 (define-obsolete-function-alias
19711 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19713 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19714 "Remove inline-display overlay if a corresponding region is modified."
19715 (let ((inhibit-modification-hooks t))
19716 (when (and ov after)
19717 (delete ov org-inline-image-overlays)
19718 (delete-overlay ov))))
19720 (defun org-remove-inline-images ()
19721 "Remove inline display of images."
19722 (interactive)
19723 (mapc #'delete-overlay org-inline-image-overlays)
19724 (setq org-inline-image-overlays nil))
19726 ;;;; Key bindings
19728 ;; Outline functions from `outline-mode-prefix-map'
19729 ;; that can be remapped in Org:
19730 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19731 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19732 (define-key org-mode-map [remap outline-forward-same-level]
19733 'org-forward-heading-same-level)
19734 (define-key org-mode-map [remap outline-backward-same-level]
19735 'org-backward-heading-same-level)
19736 (define-key org-mode-map [remap outline-show-branches]
19737 'org-kill-note-or-show-branches)
19738 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19739 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19740 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19741 (define-key org-mode-map [remap outline-next-visible-heading]
19742 'org-next-visible-heading)
19743 (define-key org-mode-map [remap outline-previous-visible-heading]
19744 'org-previous-visible-heading)
19745 (define-key org-mode-map [remap show-children] 'org-show-children)
19747 ;; Outline functions from `outline-mode-prefix-map' that can not
19748 ;; be remapped in Org:
19750 ;; - the column "key binding" shows whether the Outline function is still
19751 ;; available in Org mode on the same key that it has been bound to in
19752 ;; Outline mode:
19753 ;; - "overridden": key used for a different functionality in Org mode
19754 ;; - else: key still bound to the same Outline function in Org mode
19756 ;; | Outline function | key binding | Org replacement |
19757 ;; |------------------------------------+-------------+--------------------------|
19758 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19759 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19760 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19761 ;; | `show-entry' | overridden | no replacement |
19762 ;; | `show-branches' | `C-c C-k' | still same function |
19763 ;; | `show-subtree' | overridden | visibility cycling |
19764 ;; | `show-all' | overridden | no replacement |
19765 ;; | `hide-subtree' | overridden | visibility cycling |
19766 ;; | `hide-body' | overridden | no replacement |
19767 ;; | `hide-entry' | overridden | visibility cycling |
19768 ;; | `hide-leaves' | overridden | no replacement |
19769 ;; | `hide-sublevels' | overridden | no replacement |
19770 ;; | `hide-other' | overridden | no replacement |
19772 ;; Make `C-c C-x' a prefix key
19773 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19775 ;; TAB key with modifiers
19776 (org-defkey org-mode-map "\C-i" 'org-cycle)
19777 (org-defkey org-mode-map [(tab)] 'org-cycle)
19778 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19779 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19780 ;; The following line is necessary under Suse GNU/Linux
19781 (unless (featurep 'xemacs)
19782 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19783 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19784 (define-key org-mode-map [backtab] 'org-shifttab)
19786 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19787 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19788 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19790 ;; Cursor keys with modifiers
19791 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19792 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19793 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19794 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19796 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19797 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19798 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19799 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19800 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19801 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19803 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19804 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19805 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19806 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19808 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19809 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19810 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19811 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19813 ;; Babel keys
19814 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19815 (dolist (pair org-babel-key-bindings)
19816 (define-key org-babel-map (car pair) (cdr pair)))
19818 ;;; Extra keys for tty access.
19819 ;; We only set them when really needed because otherwise the
19820 ;; menus don't show the simple keys
19822 (when (or org-use-extra-keys
19823 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19824 (not window-system))
19825 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19826 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19827 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19828 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19829 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19830 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19831 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19832 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19833 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19834 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19835 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19836 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19837 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19838 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19839 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19840 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19841 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19842 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19843 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19844 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19845 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19846 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19847 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19848 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19849 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19850 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19851 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19852 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19854 ;; All the other keys
19856 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19857 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19858 (if (boundp 'narrow-map)
19859 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19860 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19861 (if (boundp 'narrow-map)
19862 (org-defkey narrow-map "b" 'org-narrow-to-block)
19863 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19864 (if (boundp 'narrow-map)
19865 (org-defkey narrow-map "e" 'org-narrow-to-element)
19866 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19867 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19868 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19869 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19870 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19871 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19872 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19873 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19874 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19875 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19876 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19877 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19878 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19879 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19880 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19881 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19882 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19883 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19884 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19885 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19886 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19887 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19888 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19889 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19890 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19891 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19892 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19893 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19894 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19895 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19896 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19897 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19898 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19899 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19900 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19901 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19902 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19903 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19904 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19905 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19906 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19907 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19908 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19909 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19910 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19911 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19912 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19913 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19914 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19915 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19916 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19917 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19918 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19919 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19920 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19921 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19922 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19923 (org-defkey org-mode-map "\C-c^" 'org-sort)
19924 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19925 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19926 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19927 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19928 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19929 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19930 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19931 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19932 (org-defkey org-mode-map "\C-m" 'org-return)
19933 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19934 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19935 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19936 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19937 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19938 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19939 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19940 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19941 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19942 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19943 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19944 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19945 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19946 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19947 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19948 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19949 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19950 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19951 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19952 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19953 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19954 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19955 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19956 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19957 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19959 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19960 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19961 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19963 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19964 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19965 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19966 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19967 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19968 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19969 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19970 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19971 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19972 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19973 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19974 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19975 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19976 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19977 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19978 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19979 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19980 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19981 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19982 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19983 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19984 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19986 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
19987 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
19988 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
19989 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
19990 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
19992 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
19994 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
19996 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
19997 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
19999 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20002 (when (featurep 'xemacs)
20003 (org-defkey org-mode-map 'button3 'popup-mode-menu))
20006 (defconst org-speed-commands-default
20008 ("Outline Navigation")
20009 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20010 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20011 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20012 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20013 ("F" . org-next-block)
20014 ("B" . org-previous-block)
20015 ("u" . (org-speed-move-safe 'outline-up-heading))
20016 ("j" . org-goto)
20017 ("g" . (org-refile t))
20018 ("Outline Visibility")
20019 ("c" . org-cycle)
20020 ("C" . org-shifttab)
20021 (" " . org-display-outline-path)
20022 ("s" . org-narrow-to-subtree)
20023 ("=" . org-columns)
20024 ("Outline Structure Editing")
20025 ("U" . org-metaup)
20026 ("D" . org-metadown)
20027 ("r" . org-metaright)
20028 ("l" . org-metaleft)
20029 ("R" . org-shiftmetaright)
20030 ("L" . org-shiftmetaleft)
20031 ("i" . (progn (forward-char 1) (call-interactively
20032 'org-insert-heading-respect-content)))
20033 ("^" . org-sort)
20034 ("w" . org-refile)
20035 ("a" . org-archive-subtree-default-with-confirmation)
20036 ("@" . org-mark-subtree)
20037 ("#" . org-toggle-comment)
20038 ("Clock Commands")
20039 ("I" . org-clock-in)
20040 ("O" . org-clock-out)
20041 ("Meta Data Editing")
20042 ("t" . org-todo)
20043 ("," . (org-priority))
20044 ("0" . (org-priority ?\ ))
20045 ("1" . (org-priority ?A))
20046 ("2" . (org-priority ?B))
20047 ("3" . (org-priority ?C))
20048 (":" . org-set-tags-command)
20049 ("e" . org-set-effort)
20050 ("E" . org-inc-effort)
20051 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20052 (org-entry-put (point) "APPT_WARNTIME" m)))
20053 ("Agenda Views etc")
20054 ("v" . org-agenda)
20055 ("/" . org-sparse-tree)
20056 ("Misc")
20057 ("o" . org-open-at-point)
20058 ("?" . org-speed-command-help)
20059 ("<" . (org-agenda-set-restriction-lock 'subtree))
20060 (">" . (org-agenda-remove-restriction-lock))
20062 "The default speed commands.")
20064 (defun org-print-speed-command (e)
20065 (if (> (length (car e)) 1)
20066 (progn
20067 (princ "\n")
20068 (princ (car e))
20069 (princ "\n")
20070 (princ (make-string (length (car e)) ?-))
20071 (princ "\n"))
20072 (princ (car e))
20073 (princ " ")
20074 (if (symbolp (cdr e))
20075 (princ (symbol-name (cdr e)))
20076 (prin1 (cdr e)))
20077 (princ "\n")))
20079 (defun org-speed-command-help ()
20080 "Show the available speed commands."
20081 (interactive)
20082 (if (not org-use-speed-commands)
20083 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20084 (with-output-to-temp-buffer "*Help*"
20085 (princ "User-defined Speed commands\n===========================\n")
20086 (mapc #'org-print-speed-command org-speed-commands-user)
20087 (princ "\n")
20088 (princ "Built-in Speed commands\n=======================\n")
20089 (mapc #'org-print-speed-command org-speed-commands-default))
20090 (with-current-buffer "*Help*"
20091 (setq truncate-lines t))))
20093 (defun org-speed-move-safe (cmd)
20094 "Execute CMD, but make sure that the cursor always ends up in a headline.
20095 If not, return to the original position and throw an error."
20096 (interactive)
20097 (let ((pos (point)))
20098 (call-interactively cmd)
20099 (unless (and (bolp) (org-at-heading-p))
20100 (goto-char pos)
20101 (error "Boundary reached while executing %s" cmd))))
20103 (defvar org-self-insert-command-undo-counter 0)
20105 (defvar org-table-auto-blank-field) ; defined in org-table.el
20106 (defvar org-speed-command nil)
20108 (define-obsolete-function-alias
20109 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20111 (defun org-speed-command-activate (keys)
20112 "Hook for activating single-letter speed commands.
20113 `org-speed-commands-default' specifies a minimal command set.
20114 Use `org-speed-commands-user' for further customization."
20115 (when (or (and (bolp) (looking-at org-outline-regexp))
20116 (and (functionp org-use-speed-commands)
20117 (funcall org-use-speed-commands)))
20118 (cdr (assoc keys (append org-speed-commands-user
20119 org-speed-commands-default)))))
20121 (define-obsolete-function-alias
20122 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20124 (defun org-babel-speed-command-activate (keys)
20125 "Hook for activating single-letter code block commands."
20126 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20127 (cdr (assoc keys org-babel-key-bindings))))
20129 (defcustom org-speed-command-hook
20130 '(org-speed-command-default-hook org-babel-speed-command-hook)
20131 "Hook for activating speed commands at strategic locations.
20132 Hook functions are called in sequence until a valid handler is
20133 found.
20135 Each hook takes a single argument, a user-pressed command key
20136 which is also a `self-insert-command' from the global map.
20138 Within the hook, examine the cursor position and the command key
20139 and return nil or a valid handler as appropriate. Handler could
20140 be one of an interactive command, a function, or a form.
20142 Set `org-use-speed-commands' to non-nil value to enable this
20143 hook. The default setting is `org-speed-command-activate'."
20144 :group 'org-structure
20145 :version "24.1"
20146 :type 'hook)
20148 (defun org-self-insert-command (N)
20149 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20150 If the cursor is in a table looking at whitespace, the whitespace is
20151 overwritten, and the table is not marked as requiring realignment."
20152 (interactive "p")
20153 (org-check-before-invisible-edit 'insert)
20154 (cond
20155 ((and org-use-speed-commands
20156 (let ((kv (this-command-keys-vector)))
20157 (setq org-speed-command
20158 (run-hook-with-args-until-success
20159 'org-speed-command-hook
20160 (make-string 1 (aref kv (1- (length kv))))))))
20161 (cond
20162 ((commandp org-speed-command)
20163 (setq this-command org-speed-command)
20164 (call-interactively org-speed-command))
20165 ((functionp org-speed-command)
20166 (funcall org-speed-command))
20167 ((and org-speed-command (listp org-speed-command))
20168 (eval org-speed-command))
20169 (t (let (org-use-speed-commands)
20170 (call-interactively 'org-self-insert-command)))))
20171 ((and
20172 (org-at-table-p)
20173 (progn
20174 ;; Check if we blank the field, and if that triggers align.
20175 (and (featurep 'org-table) org-table-auto-blank-field
20176 (memq last-command
20177 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20178 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20179 ;; Got extra space, this field does not determine
20180 ;; column width.
20181 (let (org-table-may-need-update) (org-table-blank-field))
20182 ;; No extra space, this field may determine column
20183 ;; width.
20184 (org-table-blank-field)))
20186 (eq N 1)
20187 (looking-at "[^|\n]* \\( \\)|"))
20188 ;; There is room for insertion without re-aligning the table.
20189 (delete-region (match-beginning 1) (match-end 1))
20190 (self-insert-command N))
20192 (setq org-table-may-need-update t)
20193 (self-insert-command N)
20194 (org-fix-tags-on-the-fly)
20195 (when org-self-insert-cluster-for-undo
20196 (if (not (eq last-command 'org-self-insert-command))
20197 (setq org-self-insert-command-undo-counter 1)
20198 (if (>= org-self-insert-command-undo-counter 20)
20199 (setq org-self-insert-command-undo-counter 1)
20200 (and (> org-self-insert-command-undo-counter 0)
20201 buffer-undo-list (listp buffer-undo-list)
20202 (not (cadr buffer-undo-list)) ; remove nil entry
20203 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20204 (setq org-self-insert-command-undo-counter
20205 (1+ org-self-insert-command-undo-counter))))))))
20207 (defun org-check-before-invisible-edit (kind)
20208 "Check is editing if kind KIND would be dangerous with invisible text around.
20209 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20210 ;; First, try to get out of here as quickly as possible, to reduce overhead
20211 (when (and org-catch-invisible-edits
20212 (or (not (boundp 'visible-mode)) (not visible-mode))
20213 (or (get-char-property (point) 'invisible)
20214 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20215 ;; OK, we need to take a closer look
20216 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20217 (invisible-before-point (unless (bobp) (get-char-property
20218 (1- (point)) 'invisible)))
20219 (border-and-ok-direction
20221 ;; Check if we are acting predictably before invisible text
20222 (and invisible-at-point (not invisible-before-point)
20223 (memq kind '(insert delete-backward)))
20224 ;; Check if we are acting predictably after invisible text
20225 ;; This works not well, and I have turned it off. It seems
20226 ;; better to always show and stop after invisible text.
20227 ;; (and (not invisible-at-point) invisible-before-point
20228 ;; (memq kind '(insert delete)))
20230 (when (or (memq invisible-at-point '(outline org-hide-block t))
20231 (memq invisible-before-point '(outline org-hide-block t)))
20232 (when (eq org-catch-invisible-edits 'error)
20233 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20234 (if (and org-custom-properties-overlays
20235 (y-or-n-p "Display invisible properties in this buffer? "))
20236 (org-toggle-custom-properties-visibility)
20237 ;; Make the area visible
20238 (save-excursion
20239 (when invisible-before-point
20240 (goto-char (previous-single-char-property-change
20241 (point) 'invisible)))
20242 (outline-show-subtree))
20243 (cond
20244 ((eq org-catch-invisible-edits 'show)
20245 ;; That's it, we do the edit after showing
20246 (message
20247 "Unfolding invisible region around point before editing")
20248 (sit-for 1))
20249 ((and (eq org-catch-invisible-edits 'smart)
20250 border-and-ok-direction)
20251 (message "Unfolding invisible region around point before editing"))
20253 ;; Don't do the edit, make the user repeat it in full visibility
20254 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20256 (defun org-fix-tags-on-the-fly ()
20257 (when (and (equal (char-after (point-at-bol)) ?*)
20258 (org-at-heading-p))
20259 (org-align-tags-here org-tags-column)))
20261 (defun org-delete-backward-char (N)
20262 "Like `delete-backward-char', insert whitespace at field end in tables.
20263 When deleting backwards, in tables this function will insert whitespace in
20264 front of the next \"|\" separator, to keep the table aligned. The table will
20265 still be marked for re-alignment if the field did fill the entire column,
20266 because, in this case the deletion might narrow the column."
20267 (interactive "p")
20268 (save-match-data
20269 (org-check-before-invisible-edit 'delete-backward)
20270 (if (and (org-at-table-p)
20271 (eq N 1)
20272 (string-match "|" (buffer-substring (point-at-bol) (point)))
20273 (looking-at ".*?|"))
20274 (let ((pos (point))
20275 (noalign (looking-at "[^|\n\r]* |"))
20276 (c org-table-may-need-update))
20277 (backward-delete-char N)
20278 (unless overwrite-mode
20279 (skip-chars-forward "^|")
20280 (insert " ")
20281 (goto-char (1- pos)))
20282 ;; noalign: if there were two spaces at the end, this field
20283 ;; does not determine the width of the column.
20284 (when noalign (setq org-table-may-need-update c)))
20285 (backward-delete-char N)
20286 (org-fix-tags-on-the-fly))))
20288 (defun org-delete-char (N)
20289 "Like `delete-char', but insert whitespace at field end in tables.
20290 When deleting characters, in tables this function will insert whitespace in
20291 front of the next \"|\" separator, to keep the table aligned. The table will
20292 still be marked for re-alignment if the field did fill the entire column,
20293 because, in this case the deletion might narrow the column."
20294 (interactive "p")
20295 (save-match-data
20296 (org-check-before-invisible-edit 'delete)
20297 (if (and (org-at-table-p)
20298 (not (bolp))
20299 (not (= (char-after) ?|))
20300 (eq N 1))
20301 (if (looking-at ".*?|")
20302 (let ((pos (point))
20303 (noalign (looking-at "[^|\n\r]* |"))
20304 (c org-table-may-need-update))
20305 (replace-match
20306 (concat (substring (match-string 0) 1 -1) " |") nil t)
20307 (goto-char pos)
20308 ;; noalign: if there were two spaces at the end, this field
20309 ;; does not determine the width of the column.
20310 (when noalign (setq org-table-may-need-update c)))
20311 (delete-char N))
20312 (delete-char N)
20313 (org-fix-tags-on-the-fly))))
20315 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20316 (put 'org-self-insert-command 'delete-selection
20317 (lambda ()
20318 (not (run-hook-with-args-until-success
20319 'self-insert-uses-region-functions))))
20320 (put 'orgtbl-self-insert-command 'delete-selection
20321 (lambda ()
20322 (not (run-hook-with-args-until-success
20323 'self-insert-uses-region-functions))))
20324 (put 'org-delete-char 'delete-selection 'supersede)
20325 (put 'org-delete-backward-char 'delete-selection 'supersede)
20326 (put 'org-yank 'delete-selection 'yank)
20328 ;; Make `flyspell-mode' delay after some commands
20329 (put 'org-self-insert-command 'flyspell-delayed t)
20330 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20331 (put 'org-delete-char 'flyspell-delayed t)
20332 (put 'org-delete-backward-char 'flyspell-delayed t)
20334 ;; Make pabbrev-mode expand after org-mode commands
20335 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20336 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20338 (defun org-remap (map &rest commands)
20339 "In MAP, remap the functions given in COMMANDS.
20340 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20341 (let (new old)
20342 (while commands
20343 (setq old (pop commands) new (pop commands))
20344 (if (fboundp 'command-remapping)
20345 (org-defkey map (vector 'remap old) new)
20346 (substitute-key-definition old new map global-map)))))
20348 (defun org-transpose-words ()
20349 "Transpose words for Org.
20350 This uses the `org-mode-transpose-word-syntax-table' syntax
20351 table, which interprets characters in `org-emphasis-alist' as
20352 word constituents."
20353 (interactive)
20354 (with-syntax-table org-mode-transpose-word-syntax-table
20355 (call-interactively 'transpose-words)))
20356 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20358 (when (eq org-enable-table-editor 'optimized)
20359 ;; If the user wants maximum table support, we need to hijack
20360 ;; some standard editing functions
20361 (org-remap org-mode-map
20362 'self-insert-command 'org-self-insert-command
20363 'delete-char 'org-delete-char
20364 'delete-backward-char 'org-delete-backward-char)
20365 (org-defkey org-mode-map "|" 'org-force-self-insert))
20367 (defvar org-ctrl-c-ctrl-c-hook nil
20368 "Hook for functions attaching themselves to `C-c C-c'.
20370 This can be used to add additional functionality to the C-c C-c
20371 key which executes context-dependent commands. This hook is run
20372 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20373 run after the last test.
20375 Each function will be called with no arguments. The function
20376 must check if the context is appropriate for it to act. If yes,
20377 it should do its thing and then return a non-nil value. If the
20378 context is wrong, just do nothing and return nil.")
20380 (defvar org-ctrl-c-ctrl-c-final-hook nil
20381 "Hook for functions attaching themselves to `C-c C-c'.
20383 This can be used to add additional functionality to the C-c C-c
20384 key which executes context-dependent commands. This hook is run
20385 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20386 before the first test.
20388 Each function will be called with no arguments. The function
20389 must check if the context is appropriate for it to act. If yes,
20390 it should do its thing and then return a non-nil value. If the
20391 context is wrong, just do nothing and return nil.")
20393 (defvar org-tab-first-hook nil
20394 "Hook for functions to attach themselves to TAB.
20395 See `org-ctrl-c-ctrl-c-hook' for more information.
20396 This hook runs as the first action when TAB is pressed, even before
20397 `org-cycle' messes around with the `outline-regexp' to cater for
20398 inline tasks and plain list item folding.
20399 If any function in this hook returns t, any other actions that
20400 would have been caused by TAB (such as table field motion or visibility
20401 cycling) will not occur.")
20403 (defvar org-tab-after-check-for-table-hook nil
20404 "Hook for functions to attach themselves to TAB.
20405 See `org-ctrl-c-ctrl-c-hook' for more information.
20406 This hook runs after it has been established that the cursor is not in a
20407 table, but before checking if the cursor is in a headline or if global cycling
20408 should be done.
20409 If any function in this hook returns t, not other actions like visibility
20410 cycling will be done.")
20412 (defvar org-tab-after-check-for-cycling-hook nil
20413 "Hook for functions to attach themselves to TAB.
20414 See `org-ctrl-c-ctrl-c-hook' for more information.
20415 This hook runs after it has been established that not table field motion and
20416 not visibility should be done because of current context. This is probably
20417 the place where a package like yasnippets can hook in.")
20419 (defvar org-tab-before-tab-emulation-hook nil
20420 "Hook for functions to attach themselves to TAB.
20421 See `org-ctrl-c-ctrl-c-hook' for more information.
20422 This hook runs after every other options for TAB have been exhausted, but
20423 before indentation and \t insertion takes place.")
20425 (defvar org-metaleft-hook nil
20426 "Hook for functions attaching themselves to `M-left'.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.")
20428 (defvar org-metaright-hook nil
20429 "Hook for functions attaching themselves to `M-right'.
20430 See `org-ctrl-c-ctrl-c-hook' for more information.")
20431 (defvar org-metaup-hook nil
20432 "Hook for functions attaching themselves to `M-up'.
20433 See `org-ctrl-c-ctrl-c-hook' for more information.")
20434 (defvar org-metadown-hook nil
20435 "Hook for functions attaching themselves to `M-down'.
20436 See `org-ctrl-c-ctrl-c-hook' for more information.")
20437 (defvar org-shiftmetaleft-hook nil
20438 "Hook for functions attaching themselves to `M-S-left'.
20439 See `org-ctrl-c-ctrl-c-hook' for more information.")
20440 (defvar org-shiftmetaright-hook nil
20441 "Hook for functions attaching themselves to `M-S-right'.
20442 See `org-ctrl-c-ctrl-c-hook' for more information.")
20443 (defvar org-shiftmetaup-hook nil
20444 "Hook for functions attaching themselves to `M-S-up'.
20445 See `org-ctrl-c-ctrl-c-hook' for more information.")
20446 (defvar org-shiftmetadown-hook nil
20447 "Hook for functions attaching themselves to `M-S-down'.
20448 See `org-ctrl-c-ctrl-c-hook' for more information.")
20449 (defvar org-metareturn-hook nil
20450 "Hook for functions attaching themselves to `M-RET'.
20451 See `org-ctrl-c-ctrl-c-hook' for more information.")
20452 (defvar org-shiftup-hook nil
20453 "Hook for functions attaching themselves to `S-up'.
20454 See `org-ctrl-c-ctrl-c-hook' for more information.")
20455 (defvar org-shiftup-final-hook nil
20456 "Hook for functions attaching themselves to `S-up'.
20457 This one runs after all other options except shift-select have been excluded.
20458 See `org-ctrl-c-ctrl-c-hook' for more information.")
20459 (defvar org-shiftdown-hook nil
20460 "Hook for functions attaching themselves to `S-down'.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.")
20462 (defvar org-shiftdown-final-hook nil
20463 "Hook for functions attaching themselves to `S-down'.
20464 This one runs after all other options except shift-select have been excluded.
20465 See `org-ctrl-c-ctrl-c-hook' for more information.")
20466 (defvar org-shiftleft-hook nil
20467 "Hook for functions attaching themselves to `S-left'.
20468 See `org-ctrl-c-ctrl-c-hook' for more information.")
20469 (defvar org-shiftleft-final-hook nil
20470 "Hook for functions attaching themselves to `S-left'.
20471 This one runs after all other options except shift-select have been excluded.
20472 See `org-ctrl-c-ctrl-c-hook' for more information.")
20473 (defvar org-shiftright-hook nil
20474 "Hook for functions attaching themselves to `S-right'.
20475 See `org-ctrl-c-ctrl-c-hook' for more information.")
20476 (defvar org-shiftright-final-hook nil
20477 "Hook for functions attaching themselves to `S-right'.
20478 This one runs after all other options except shift-select have been excluded.
20479 See `org-ctrl-c-ctrl-c-hook' for more information.")
20481 (defun org-modifier-cursor-error ()
20482 "Throw an error, a modified cursor command was applied in wrong context."
20483 (user-error "This command is active in special context like tables, headlines or items"))
20485 (defun org-shiftselect-error ()
20486 "Throw an error because Shift-Cursor command was applied in wrong context."
20487 (if (and (boundp 'shift-select-mode) shift-select-mode)
20488 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20489 (user-error "This command works only in special context like headlines or timestamps")))
20491 (defun org-call-for-shift-select (cmd)
20492 (let ((this-command-keys-shift-translated t))
20493 (call-interactively cmd)))
20495 (defun org-shifttab (&optional arg)
20496 "Global visibility cycling or move to previous table field.
20497 Call `org-table-previous-field' within a table.
20498 When ARG is nil, cycle globally through visibility states.
20499 When ARG is a numeric prefix, show contents of this level."
20500 (interactive "P")
20501 (cond
20502 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20503 ((integerp arg)
20504 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20505 (message "Content view to level: %d" arg)
20506 (org-content (prefix-numeric-value arg2))
20507 (org-cycle-show-empty-lines t)
20508 (setq org-cycle-global-status 'overview)))
20509 (t (call-interactively 'org-global-cycle))))
20511 (defun org-shiftmetaleft ()
20512 "Promote subtree or delete table column.
20513 Calls `org-promote-subtree', `org-outdent-item-tree', or
20514 `org-table-delete-column', depending on context. See the
20515 individual commands for more information."
20516 (interactive)
20517 (cond
20518 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20519 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20520 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20521 ((if (not (org-region-active-p)) (org-at-item-p)
20522 (save-excursion (goto-char (region-beginning))
20523 (org-at-item-p)))
20524 (call-interactively 'org-outdent-item-tree))
20525 (t (org-modifier-cursor-error))))
20527 (defun org-shiftmetaright ()
20528 "Demote subtree or insert table column.
20529 Calls `org-demote-subtree', `org-indent-item-tree', or
20530 `org-table-insert-column', depending on context. See the
20531 individual commands for more information."
20532 (interactive)
20533 (cond
20534 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20535 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20536 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20537 ((if (not (org-region-active-p)) (org-at-item-p)
20538 (save-excursion (goto-char (region-beginning))
20539 (org-at-item-p)))
20540 (call-interactively 'org-indent-item-tree))
20541 (t (org-modifier-cursor-error))))
20543 (defun org-shiftmetaup (&optional _arg)
20544 "Drag the line at point up.
20545 In a table, kill the current row.
20546 On a clock timestamp, update the value of the timestamp like `S-<up>'
20547 but also adjust the previous clocked item in the clock history.
20548 Everywhere else, drag the line at point up."
20549 (interactive "P")
20550 (cond
20551 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20552 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20553 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20554 (call-interactively 'org-timestamp-up)))
20555 (t (call-interactively 'org-drag-line-backward))))
20557 (defun org-shiftmetadown (&optional _arg)
20558 "Drag the line at point down.
20559 In a table, insert an empty row at the current line.
20560 On a clock timestamp, update the value of the timestamp like `S-<down>'
20561 but also adjust the previous clocked item in the clock history.
20562 Everywhere else, drag the line at point down."
20563 (interactive "P")
20564 (cond
20565 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20566 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20567 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20568 (call-interactively 'org-timestamp-down)))
20569 (t (call-interactively 'org-drag-line-forward))))
20571 (defsubst org-hidden-tree-error ()
20572 (user-error
20573 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20575 (defun org-metaleft (&optional _arg)
20576 "Promote heading, list item at point or move table column left.
20578 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20579 depending on context. With no specific context, calls the Emacs
20580 default `backward-word'. See the individual commands for more
20581 information.
20583 This function runs the hook `org-metaleft-hook' as a first step,
20584 and returns at first non-nil value."
20585 (interactive "P")
20586 (cond
20587 ((run-hook-with-args-until-success 'org-metaleft-hook))
20588 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20589 ((org-with-limited-levels
20590 (or (org-at-heading-p)
20591 (and (org-region-active-p)
20592 (save-excursion
20593 (goto-char (region-beginning))
20594 (org-at-heading-p)))))
20595 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20596 (call-interactively 'org-do-promote))
20597 ;; At an inline task.
20598 ((org-at-heading-p)
20599 (call-interactively 'org-inlinetask-promote))
20600 ((or (org-at-item-p)
20601 (and (org-region-active-p)
20602 (save-excursion
20603 (goto-char (region-beginning))
20604 (org-at-item-p))))
20605 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20606 (call-interactively 'org-outdent-item))
20607 (t (call-interactively 'backward-word))))
20609 (defun org-metaright (&optional _arg)
20610 "Demote heading, list item at point or move table column right.
20612 In front of a drawer or a block keyword, indent it correctly.
20614 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20615 `org-indnet-drawer' or `org-indent-block' depending on context.
20616 With no specific context, calls the Emacs default `forward-word'.
20617 See the individual commands for more information.
20619 This function runs the hook `org-metaright-hook' as a first step,
20620 and returns at first non-nil value."
20621 (interactive "P")
20622 (cond
20623 ((run-hook-with-args-until-success 'org-metaright-hook))
20624 ((org-at-table-p) (call-interactively 'org-table-move-column))
20625 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20626 ((org-at-block-p) (call-interactively 'org-indent-block))
20627 ((org-with-limited-levels
20628 (or (org-at-heading-p)
20629 (and (org-region-active-p)
20630 (save-excursion
20631 (goto-char (region-beginning))
20632 (org-at-heading-p)))))
20633 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20634 (call-interactively 'org-do-demote))
20635 ;; At an inline task.
20636 ((org-at-heading-p)
20637 (call-interactively 'org-inlinetask-demote))
20638 ((or (org-at-item-p)
20639 (and (org-region-active-p)
20640 (save-excursion
20641 (goto-char (region-beginning))
20642 (org-at-item-p))))
20643 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20644 (call-interactively 'org-indent-item))
20645 (t (call-interactively 'forward-word))))
20647 (defun org-check-for-hidden (what)
20648 "Check if there are hidden headlines/items in the current visual line.
20649 WHAT can be either `headlines' or `items'. If the current line is
20650 an outline or item heading and it has a folded subtree below it,
20651 this function returns t, nil otherwise."
20652 (let ((re (cond
20653 ((eq what 'headlines) org-outline-regexp-bol)
20654 ((eq what 'items) (org-item-beginning-re))
20655 (t (error "This should not happen"))))
20656 beg end)
20657 (save-excursion
20658 (catch 'exit
20659 (unless (org-region-active-p)
20660 (setq beg (point-at-bol))
20661 (beginning-of-line 2)
20662 (while (and (not (eobp)) ;; this is like `next-line'
20663 (get-char-property (1- (point)) 'invisible))
20664 (beginning-of-line 2))
20665 (setq end (point))
20666 (goto-char beg)
20667 (goto-char (point-at-eol))
20668 (setq end (max end (point)))
20669 (while (re-search-forward re end t)
20670 (when (get-char-property (match-beginning 0) 'invisible)
20671 (throw 'exit t))))
20672 nil))))
20674 (defun org-metaup (&optional _arg)
20675 "Move subtree up or move table row up.
20676 Calls `org-move-subtree-up' or `org-table-move-row' or
20677 `org-move-item-up', depending on context. See the individual commands
20678 for more information."
20679 (interactive "P")
20680 (cond
20681 ((run-hook-with-args-until-success 'org-metaup-hook))
20682 ((org-region-active-p)
20683 (let* ((a (min (region-beginning) (region-end)))
20684 (b (1- (max (region-beginning) (region-end))))
20685 (c (save-excursion (goto-char a)
20686 (move-beginning-of-line 0)))
20687 (d (save-excursion (goto-char a)
20688 (move-end-of-line 0) (point))))
20689 (transpose-regions a b c d)
20690 (goto-char c)))
20691 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20692 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20693 ((org-at-item-p) (call-interactively 'org-move-item-up))
20694 (t (org-drag-element-backward))))
20696 (defun org-metadown (&optional _arg)
20697 "Move subtree down or move table row down.
20698 Calls `org-move-subtree-down' or `org-table-move-row' or
20699 `org-move-item-down', depending on context. See the individual
20700 commands for more information."
20701 (interactive "P")
20702 (cond
20703 ((run-hook-with-args-until-success 'org-metadown-hook))
20704 ((org-region-active-p)
20705 (let* ((a (min (region-beginning) (region-end)))
20706 (b (max (region-beginning) (region-end)))
20707 (c (save-excursion (goto-char b)
20708 (move-beginning-of-line 1)))
20709 (d (save-excursion (goto-char b)
20710 (move-end-of-line 1) (1+ (point)))))
20711 (transpose-regions a b c d)
20712 (goto-char d)))
20713 ((org-at-table-p) (call-interactively 'org-table-move-row))
20714 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20715 ((org-at-item-p) (call-interactively 'org-move-item-down))
20716 (t (org-drag-element-forward))))
20718 (defun org-shiftup (&optional arg)
20719 "Increase item in timestamp or increase priority of current headline.
20720 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20721 depending on context. See the individual commands for more information."
20722 (interactive "P")
20723 (cond
20724 ((run-hook-with-args-until-success 'org-shiftup-hook))
20725 ((and org-support-shift-select (org-region-active-p))
20726 (org-call-for-shift-select 'previous-line))
20727 ((org-at-timestamp-p t)
20728 (call-interactively (if org-edit-timestamp-down-means-later
20729 'org-timestamp-down 'org-timestamp-up)))
20730 ((and (not (eq org-support-shift-select 'always))
20731 org-enable-priority-commands
20732 (org-at-heading-p))
20733 (call-interactively 'org-priority-up))
20734 ((and (not org-support-shift-select) (org-at-item-p))
20735 (call-interactively 'org-previous-item))
20736 ((org-clocktable-try-shift 'up arg))
20737 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20738 (org-support-shift-select
20739 (org-call-for-shift-select 'previous-line))
20740 (t (org-shiftselect-error))))
20742 (defun org-shiftdown (&optional arg)
20743 "Decrease item in timestamp or decrease priority of current headline.
20744 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20745 depending on context. See the individual commands for more information."
20746 (interactive "P")
20747 (cond
20748 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20749 ((and org-support-shift-select (org-region-active-p))
20750 (org-call-for-shift-select 'next-line))
20751 ((org-at-timestamp-p t)
20752 (call-interactively (if org-edit-timestamp-down-means-later
20753 'org-timestamp-up 'org-timestamp-down)))
20754 ((and (not (eq org-support-shift-select 'always))
20755 org-enable-priority-commands
20756 (org-at-heading-p))
20757 (call-interactively 'org-priority-down))
20758 ((and (not org-support-shift-select) (org-at-item-p))
20759 (call-interactively 'org-next-item))
20760 ((org-clocktable-try-shift 'down arg))
20761 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20762 (org-support-shift-select
20763 (org-call-for-shift-select 'next-line))
20764 (t (org-shiftselect-error))))
20766 (defun org-shiftright (&optional arg)
20767 "Cycle the thing at point or in the current line, depending on context.
20768 Depending on context, this does one of the following:
20770 - switch a timestamp at point one day into the future
20771 - on a headline, switch to the next TODO keyword.
20772 - on an item, switch entire list to the next bullet type
20773 - on a property line, switch to the next allowed value
20774 - on a clocktable definition line, move time block into the future"
20775 (interactive "P")
20776 (cond
20777 ((run-hook-with-args-until-success 'org-shiftright-hook))
20778 ((and org-support-shift-select (org-region-active-p))
20779 (org-call-for-shift-select 'forward-char))
20780 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20781 ((and (not (eq org-support-shift-select 'always))
20782 (org-at-heading-p))
20783 (let ((org-inhibit-logging
20784 (not org-treat-S-cursor-todo-selection-as-state-change))
20785 (org-inhibit-blocking
20786 (not org-treat-S-cursor-todo-selection-as-state-change)))
20787 (org-call-with-arg 'org-todo 'right)))
20788 ((or (and org-support-shift-select
20789 (not (eq org-support-shift-select 'always))
20790 (org-at-item-bullet-p))
20791 (and (not org-support-shift-select) (org-at-item-p)))
20792 (org-call-with-arg 'org-cycle-list-bullet nil))
20793 ((and (not (eq org-support-shift-select 'always))
20794 (org-at-property-p))
20795 (call-interactively 'org-property-next-allowed-value))
20796 ((org-clocktable-try-shift 'right arg))
20797 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20798 (org-support-shift-select
20799 (org-call-for-shift-select 'forward-char))
20800 (t (org-shiftselect-error))))
20802 (defun org-shiftleft (&optional arg)
20803 "Cycle the thing at point or in the current line, depending on context.
20804 Depending on context, this does one of the following:
20806 - switch a timestamp at point one day into the past
20807 - on a headline, switch to the previous TODO keyword.
20808 - on an item, switch entire list to the previous bullet type
20809 - on a property line, switch to the previous allowed value
20810 - on a clocktable definition line, move time block into the past"
20811 (interactive "P")
20812 (cond
20813 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20814 ((and org-support-shift-select (org-region-active-p))
20815 (org-call-for-shift-select 'backward-char))
20816 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20817 ((and (not (eq org-support-shift-select 'always))
20818 (org-at-heading-p))
20819 (let ((org-inhibit-logging
20820 (not org-treat-S-cursor-todo-selection-as-state-change))
20821 (org-inhibit-blocking
20822 (not org-treat-S-cursor-todo-selection-as-state-change)))
20823 (org-call-with-arg 'org-todo 'left)))
20824 ((or (and org-support-shift-select
20825 (not (eq org-support-shift-select 'always))
20826 (org-at-item-bullet-p))
20827 (and (not org-support-shift-select) (org-at-item-p)))
20828 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20829 ((and (not (eq org-support-shift-select 'always))
20830 (org-at-property-p))
20831 (call-interactively 'org-property-previous-allowed-value))
20832 ((org-clocktable-try-shift 'left arg))
20833 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20834 (org-support-shift-select
20835 (org-call-for-shift-select 'backward-char))
20836 (t (org-shiftselect-error))))
20838 (defun org-shiftcontrolright ()
20839 "Switch to next TODO set."
20840 (interactive)
20841 (cond
20842 ((and org-support-shift-select (org-region-active-p))
20843 (org-call-for-shift-select 'forward-word))
20844 ((and (not (eq org-support-shift-select 'always))
20845 (org-at-heading-p))
20846 (org-call-with-arg 'org-todo 'nextset))
20847 (org-support-shift-select
20848 (org-call-for-shift-select 'forward-word))
20849 (t (org-shiftselect-error))))
20851 (defun org-shiftcontrolleft ()
20852 "Switch to previous TODO set."
20853 (interactive)
20854 (cond
20855 ((and org-support-shift-select (org-region-active-p))
20856 (org-call-for-shift-select 'backward-word))
20857 ((and (not (eq org-support-shift-select 'always))
20858 (org-at-heading-p))
20859 (org-call-with-arg 'org-todo 'previousset))
20860 (org-support-shift-select
20861 (org-call-for-shift-select 'backward-word))
20862 (t (org-shiftselect-error))))
20864 (defun org-shiftcontrolup (&optional n)
20865 "Change timestamps synchronously up in CLOCK log lines.
20866 Optional argument N tells to change by that many units."
20867 (interactive "P")
20868 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20869 (let (org-support-shift-select)
20870 (org-clock-timestamps-up n))
20871 (user-error "Not at a clock log")))
20873 (defun org-shiftcontroldown (&optional n)
20874 "Change timestamps synchronously down in CLOCK log lines.
20875 Optional argument N tells to change by that many units."
20876 (interactive "P")
20877 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20878 (let (org-support-shift-select)
20879 (org-clock-timestamps-down n))
20880 (user-error "Not at a clock log")))
20882 (defun org-increase-number-at-point (&optional inc)
20883 "Increment the number at point.
20884 With an optional prefix numeric argument INC, increment using
20885 this numeric value."
20886 (interactive "p")
20887 (if (not (number-at-point))
20888 (user-error "Not on a number")
20889 (unless inc (setq inc 1))
20890 (let ((pos (point))
20891 (beg (skip-chars-backward "-+^/*0-9eE."))
20892 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20893 (setq nap (buffer-substring-no-properties
20894 (+ pos beg) (+ pos beg end)))
20895 (delete-region (+ pos beg) (+ pos beg end))
20896 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20897 (when (org-at-table-p)
20898 (org-table-align)
20899 (org-table-end-of-field 1))))
20901 (defun org-decrease-number-at-point (&optional inc)
20902 "Decrement the number at point.
20903 With an optional prefix numeric argument INC, decrement using
20904 this numeric value."
20905 (interactive "p")
20906 (org-increase-number-at-point (- (or inc 1))))
20908 (defun org-ctrl-c-ret ()
20909 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20910 (interactive)
20911 (cond
20912 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20913 (t (call-interactively 'org-insert-heading))))
20915 (defun org-find-visible ()
20916 (let ((s (point)))
20917 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20918 (get-char-property s 'invisible)))
20920 (defun org-find-invisible ()
20921 (let ((s (point)))
20922 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20923 (not (get-char-property s 'invisible))))
20926 (defun org-copy-visible (beg end)
20927 "Copy the visible parts of the region."
20928 (interactive "r")
20929 (let (snippets s)
20930 (save-excursion
20931 (save-restriction
20932 (narrow-to-region beg end)
20933 (setq s (goto-char (point-min)))
20934 (while (not (= (point) (point-max)))
20935 (goto-char (org-find-invisible))
20936 (push (buffer-substring s (point)) snippets)
20937 (setq s (goto-char (org-find-visible))))))
20938 (kill-new (apply 'concat (nreverse snippets)))))
20940 (defun org-copy-special ()
20941 "Copy region in table or copy current subtree.
20942 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20943 See the individual commands for more information."
20944 (interactive)
20945 (call-interactively
20946 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20948 (defun org-cut-special ()
20949 "Cut region in table or cut current subtree.
20950 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20951 See the individual commands for more information."
20952 (interactive)
20953 (call-interactively
20954 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20956 (defun org-paste-special (arg)
20957 "Paste rectangular region into table, or past subtree relative to level.
20958 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20959 See the individual commands for more information."
20960 (interactive "P")
20961 (if (org-at-table-p)
20962 (org-table-paste-rectangle)
20963 (org-paste-subtree arg)))
20965 (defsubst org-in-fixed-width-region-p ()
20966 "Is point in a fixed-width region?"
20967 (save-match-data
20968 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20970 (defun org-edit-special (&optional arg)
20971 "Call a special editor for the element at point.
20972 When at a table, call the formula editor with `org-table-edit-formulas'.
20973 When in a source code block, call `org-edit-src-code'.
20974 When in a fixed-width region, call `org-edit-fixed-width-region'.
20975 When in an export block, call `org-edit-export-block'.
20976 When at an #+INCLUDE keyword, visit the included file.
20977 When at a footnote reference, call `org-edit-footnote-reference'
20978 On a link, call `ffap' to visit the link at point.
20979 Otherwise, return a user error."
20980 (interactive "P")
20981 (let ((element (org-element-at-point)))
20982 (cl-assert (not buffer-read-only) nil
20983 "Buffer is read-only: %s" (buffer-name))
20984 (pcase (org-element-type element)
20985 (`src-block
20986 (if (not arg) (org-edit-src-code)
20987 (let* ((info (org-babel-get-src-block-info))
20988 (lang (nth 0 info))
20989 (params (nth 2 info))
20990 (session (cdr (assq :session params))))
20991 (if (not session) (org-edit-src-code)
20992 ;; At a src-block with a session and function called with
20993 ;; an ARG: switch to the buffer related to the inferior
20994 ;; process.
20995 (switch-to-buffer
20996 (funcall (intern (concat "org-babel-prep-session:" lang))
20997 session params))))))
20998 (`keyword
20999 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21000 (org-open-link-from-string
21001 (format "[[%s]]"
21002 (expand-file-name
21003 (let ((value (org-element-property :value element)))
21004 (cond ((not (org-string-nw-p value))
21005 (user-error "No file to edit"))
21006 ((string-match "\\`\"\\(.*?\\)\"" value)
21007 (match-string 1 value))
21008 ((string-match "\\`[^ \t\"]\\S-*" value)
21009 (match-string 0 value))
21010 (t (user-error "No valid file specified")))))))
21011 (user-error "No special environment to edit here")))
21012 (`table
21013 (if (eq (org-element-property :type element) 'table.el)
21014 (org-edit-table.el)
21015 (call-interactively 'org-table-edit-formulas)))
21016 ;; Only Org tables contain `table-row' type elements.
21017 (`table-row (call-interactively 'org-table-edit-formulas))
21018 (`example-block (org-edit-src-code))
21019 (`export-block (org-edit-export-block))
21020 (`fixed-width (org-edit-fixed-width-region))
21022 ;; No notable element at point. Though, we may be at a link or
21023 ;; a footnote reference, which are objects. Thus, scan deeper.
21024 (let ((context (org-element-context element)))
21025 (pcase (org-element-type context)
21026 (`footnote-reference (org-edit-footnote-reference))
21027 (`inline-src-block (org-edit-inline-src-code))
21028 (`link (call-interactively #'ffap))
21029 (_ (user-error "No special environment to edit here"))))))))
21031 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21032 (defun org-ctrl-c-ctrl-c (&optional arg)
21033 "Set tags in headline, or update according to changed information at point.
21035 This command does many different things, depending on context:
21037 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21038 this is what we do.
21040 - If the cursor is on a statistics cookie, update it.
21042 - If the cursor is in a headline, prompt for tags and insert them
21043 into the current line, aligned to `org-tags-column'. When called
21044 with prefix arg, realign all tags in the current buffer.
21046 - If the cursor is in one of the special #+KEYWORD lines, this
21047 triggers scanning the buffer for these lines and updating the
21048 information.
21050 - If the cursor is inside a table, realign the table. This command
21051 works even if the automatic table editor has been turned off.
21053 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21054 the entire table.
21056 - If the cursor is at a footnote reference or definition, jump to
21057 the corresponding definition or references, respectively.
21059 - If the cursor is a the beginning of a dynamic block, update it.
21061 - If the current buffer is a capture buffer, close note and file it.
21063 - If the cursor is on a <<<target>>>, update radio targets and
21064 corresponding links in this buffer.
21066 - If the cursor is on a numbered item in a plain list, renumber the
21067 ordered list.
21069 - If the cursor is on a checkbox, toggle it.
21071 - If the cursor is on a code block, evaluate it. The variable
21072 `org-confirm-babel-evaluate' can be used to control prompting
21073 before code block evaluation, by default every code block
21074 evaluation requires confirmation. Code block evaluation can be
21075 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21076 (interactive "P")
21077 (cond
21078 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21079 org-occur-highlights)
21080 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21081 (org-remove-occur-highlights)
21082 (message "Temporary highlights/overlays removed from current buffer"))
21083 ((and (local-variable-p 'org-finish-function (current-buffer))
21084 (fboundp org-finish-function))
21085 (funcall org-finish-function))
21086 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21088 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21089 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21090 (user-error "C-c C-c can do nothing useful at this location"))
21091 (let* ((context (org-element-context))
21092 (type (org-element-type context)))
21093 (cl-case type
21094 ;; When at a link, act according to the parent instead.
21095 (link (setq context (org-element-property :parent context))
21096 (setq type (org-element-type context)))
21097 ;; Unsupported object types: refer to the first supported
21098 ;; element or object containing it.
21099 ((bold code entity export-snippet inline-babel-call inline-src-block
21100 italic latex-fragment line-break macro strike-through subscript
21101 superscript underline verbatim)
21102 (setq context
21103 (org-element-lineage
21104 context '(radio-target paragraph verse-block table-cell)))))
21105 ;; For convenience: at the first line of a paragraph on the
21106 ;; same line as an item, apply function on that item instead.
21107 (when (eq type 'paragraph)
21108 (let ((parent (org-element-property :parent context)))
21109 (when (and (eq (org-element-type parent) 'item)
21110 (= (line-beginning-position)
21111 (org-element-property :begin parent)))
21112 (setq context parent type 'item))))
21113 ;; Act according to type of element or object at point.
21114 (cl-case type
21115 (clock (org-clock-update-time-maybe))
21116 (dynamic-block
21117 (save-excursion
21118 (goto-char (org-element-property :post-affiliated context))
21119 (org-update-dblock)))
21120 (footnote-definition
21121 (goto-char (org-element-property :post-affiliated context))
21122 (call-interactively 'org-footnote-action))
21123 (footnote-reference (call-interactively 'org-footnote-action))
21124 ((headline inlinetask)
21125 (save-excursion (goto-char (org-element-property :begin context))
21126 (call-interactively 'org-set-tags)))
21127 (item
21128 ;; At an item: a double C-u set checkbox to "[-]"
21129 ;; unconditionally, whereas a single one will toggle its
21130 ;; presence. Without a universal argument, if the item
21131 ;; has a checkbox, toggle it. Otherwise repair the list.
21132 (let* ((box (org-element-property :checkbox context))
21133 (struct (org-element-property :structure context))
21134 (old-struct (copy-tree struct))
21135 (parents (org-list-parents-alist struct))
21136 (prevs (org-list-prevs-alist struct))
21137 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21138 (org-list-set-checkbox
21139 (org-element-property :begin context) struct
21140 (cond ((equal arg '(16)) "[-]")
21141 ((and (not box) (equal arg '(4))) "[ ]")
21142 ((or (not box) (equal arg '(4))) nil)
21143 ((eq box 'on) "[ ]")
21144 (t "[X]")))
21145 ;; Mimic `org-list-write-struct' but with grabbing
21146 ;; a return value from `org-list-struct-fix-box'.
21147 (org-list-struct-fix-ind struct parents 2)
21148 (org-list-struct-fix-item-end struct)
21149 (org-list-struct-fix-bul struct prevs)
21150 (org-list-struct-fix-ind struct parents)
21151 (let ((block-item
21152 (org-list-struct-fix-box struct parents prevs orderedp)))
21153 (if (and box (equal struct old-struct))
21154 (if (equal arg '(16))
21155 (message "Checkboxes already reset")
21156 (user-error "Cannot toggle this checkbox: %s"
21157 (if (eq box 'on)
21158 "all subitems checked"
21159 "unchecked subitems")))
21160 (org-list-struct-apply-struct struct old-struct)
21161 (org-update-checkbox-count-maybe))
21162 (when block-item
21163 (message "Checkboxes were removed due to empty box at line %d"
21164 (org-current-line block-item))))))
21165 (keyword
21166 (let ((org-inhibit-startup-visibility-stuff t)
21167 (org-startup-align-all-tables nil))
21168 (when (boundp 'org-table-coordinate-overlays)
21169 (mapc #'delete-overlay org-table-coordinate-overlays)
21170 (setq org-table-coordinate-overlays nil))
21171 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21172 (message "Local setup has been refreshed"))
21173 (plain-list
21174 ;; At a plain list, with a double C-u argument, set
21175 ;; checkboxes of each item to "[-]", whereas a single one
21176 ;; will toggle their presence according to the state of the
21177 ;; first item in the list. Without an argument, repair the
21178 ;; list.
21179 (let* ((begin (org-element-property :contents-begin context))
21180 (beginm (move-marker (make-marker) begin))
21181 (struct (org-element-property :structure context))
21182 (old-struct (copy-tree struct))
21183 (first-box (save-excursion
21184 (goto-char begin)
21185 (looking-at org-list-full-item-re)
21186 (match-string-no-properties 3)))
21187 (new-box (cond ((equal arg '(16)) "[-]")
21188 ((equal arg '(4)) (unless first-box "[ ]"))
21189 ((equal first-box "[X]") "[ ]")
21190 (t "[X]"))))
21191 (cond
21192 (arg
21193 (dolist (pos
21194 (org-list-get-all-items
21195 begin struct (org-list-prevs-alist struct)))
21196 (org-list-set-checkbox pos struct new-box)))
21197 ((and first-box (eq (point) begin))
21198 ;; For convenience, when point is at bol on the first
21199 ;; item of the list and no argument is provided, simply
21200 ;; toggle checkbox of that item, if any.
21201 (org-list-set-checkbox begin struct new-box)))
21202 (org-list-write-struct
21203 struct (org-list-parents-alist struct) old-struct)
21204 (org-update-checkbox-count-maybe)
21205 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21206 ((property-drawer node-property)
21207 (call-interactively 'org-property-action))
21208 ((radio-target target)
21209 (call-interactively 'org-update-radio-target-regexp))
21210 (statistics-cookie
21211 (call-interactively 'org-update-statistics-cookies))
21212 ((table table-cell table-row)
21213 ;; At a table, recalculate every field and align it. Also
21214 ;; send the table if necessary. If the table has
21215 ;; a `table.el' type, just give up. At a table row or
21216 ;; cell, maybe recalculate line but always align table.
21217 (if (eq (org-element-property :type context) 'table.el)
21218 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21219 Use \\[org-edit-special] to edit table.el tables"))
21220 (let ((org-enable-table-editor t))
21221 (if (or (eq type 'table)
21222 ;; Check if point is at a TBLFM line.
21223 (and (eq type 'table-row)
21224 (= (point) (org-element-property :end context))))
21225 (save-excursion
21226 (if (org-at-TBLFM-p)
21227 (progn (require 'org-table)
21228 (org-table-calc-current-TBLFM))
21229 (goto-char (org-element-property :contents-begin context))
21230 (org-call-with-arg 'org-table-recalculate (or arg t))
21231 (orgtbl-send-table 'maybe)))
21232 (org-table-maybe-eval-formula)
21233 (cond (arg (call-interactively 'org-table-recalculate))
21234 ((org-table-maybe-recalculate-line))
21235 (t (org-table-align)))))))
21236 (timestamp (org-timestamp-change 0 'day))
21237 (otherwise
21238 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21239 (user-error
21240 "C-c C-c can do nothing useful at this location")))))))))
21242 (defun org-mode-restart ()
21243 (interactive)
21244 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21245 (funcall major-mode)
21246 (hack-local-variables)
21247 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21248 (org-indent-mode -1)))
21249 (message "%s restarted" major-mode))
21251 (defun org-kill-note-or-show-branches ()
21252 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21253 (interactive)
21254 (if (not org-finish-function)
21255 (progn
21256 (outline-hide-subtree)
21257 (call-interactively 'outline-show-branches))
21258 (let ((org-note-abort t))
21259 (funcall org-finish-function))))
21261 (defun org-delete-indentation (&optional ARG)
21262 "Join current line to previous and fix whitespace at join.
21264 If previous line is a headline add to headline title. Otherwise
21265 the function calls `delete-indentation'.
21267 With argument, join this line to following line."
21268 (interactive "*P")
21269 (if (save-excursion
21270 (if ARG (beginning-of-line)
21271 (forward-line -1))
21272 (looking-at org-complex-heading-regexp))
21273 ;; At headline.
21274 (let ((tags-column (when (match-beginning 5)
21275 (save-excursion (goto-char (match-beginning 5))
21276 (current-column))))
21277 (string (concat " " (progn (when ARG (forward-line 1))
21278 (org-trim (delete-and-extract-region
21279 (line-beginning-position)
21280 (line-end-position)))))))
21281 (unless (bobp) (delete-region (point) (1- (point))))
21282 (goto-char (or (match-end 4)
21283 (match-beginning 5)
21284 (match-end 0)))
21285 (skip-chars-backward " \t")
21286 (save-excursion (insert string))
21287 ;; Adjust alignment of tags.
21288 (when tags-column
21289 (org-align-tags-here (if org-auto-align-tags
21290 org-tags-column
21291 tags-column))))
21292 (delete-indentation ARG)))
21294 (defun org-open-line (n)
21295 "Insert a new row in tables, call `open-line' elsewhere.
21296 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21297 (interactive "*p")
21298 (cond
21299 ((not org-special-ctrl-o)
21300 (open-line n))
21301 ((org-at-table-p)
21302 (org-table-insert-row))
21304 (open-line n))))
21306 (defun org-return (&optional indent)
21307 "Goto next table row or insert a newline.
21309 Calls `org-table-next-row' or `newline', depending on context.
21311 When optional INDENT argument is non-nil, call
21312 `newline-and-indent' instead of `newline'.
21314 When `org-return-follows-link' is non-nil and point is on
21315 a timestamp or a link, call `org-open-at-point'. However, it
21316 will not happen if point is in a table or on a \"dead\"
21317 object (e.g., within a comment). In these case, you need to use
21318 `org-open-at-point' directly."
21319 (interactive)
21320 (let ((context (if org-return-follows-link (org-element-context)
21321 (org-element-at-point))))
21322 (cond
21323 ;; In a table, call `org-table-next-row'.
21324 ((or (and (eq (org-element-type context) 'table)
21325 (>= (point) (org-element-property :contents-begin context))
21326 (< (point) (org-element-property :contents-end context)))
21327 (org-element-lineage context '(table-row table-cell) t))
21328 (org-table-justify-field-maybe)
21329 (call-interactively #'org-table-next-row))
21330 ;; On a link or a timestamp, call `org-open-at-point' if
21331 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21332 ;; locations, e.g., in a comment, as `org-open-at-point'.
21333 ((and org-return-follows-link
21334 (or (org-in-regexp org-ts-regexp-both nil t)
21335 (org-in-regexp org-tsr-regexp-both nil t)
21336 (org-in-regexp org-any-link-re nil t)))
21337 (call-interactively #'org-open-at-point))
21338 ;; Insert newline in heading, but preserve tags.
21339 ((and (not (bolp))
21340 (save-excursion (beginning-of-line)
21341 (looking-at org-complex-heading-regexp)))
21342 ;; At headline. Split line. However, if point is on keyword,
21343 ;; priority cookie or tags, do not break any of them: add
21344 ;; a newline after the headline instead.
21345 (let ((tags-column (and (match-beginning 5)
21346 (save-excursion (goto-char (match-beginning 5))
21347 (current-column))))
21348 (string
21349 (when (and (match-end 4)
21350 (>= (point)
21351 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21352 (<= (point) (match-end 4)))
21353 (delete-and-extract-region (point) (match-end 4)))))
21354 (when (and tags-column string) ; Adjust tag alignment.
21355 (org-align-tags-here
21356 (if org-auto-align-tags org-tags-column tags-column)))
21357 (end-of-line)
21358 (org-show-entry)
21359 (if indent (newline-and-indent) (newline))
21360 (when string (save-excursion (insert (org-trim string))))))
21361 ;; In a list, make sure indenting keeps trailing text within.
21362 ((and indent
21363 (not (eolp))
21364 (org-element-lineage context '(item)))
21365 (let ((trailing-data
21366 (delete-and-extract-region (point) (line-end-position))))
21367 (newline-and-indent)
21368 (save-excursion (insert trailing-data))))
21369 (t (if indent (newline-and-indent) (newline))))))
21371 (defun org-return-indent ()
21372 "Goto next table row or insert a newline and indent.
21373 Calls `org-table-next-row' or `newline-and-indent', depending on
21374 context. See the individual commands for more information."
21375 (interactive)
21376 (org-return t))
21378 (defun org-ctrl-c-star ()
21379 "Compute table, or change heading status of lines.
21380 Calls `org-table-recalculate' or `org-toggle-heading',
21381 depending on context."
21382 (interactive)
21383 (cond
21384 ((org-at-table-p)
21385 (call-interactively 'org-table-recalculate))
21387 ;; Convert all lines in region to list items
21388 (call-interactively 'org-toggle-heading))))
21390 (defun org-ctrl-c-minus ()
21391 "Insert separator line in table or modify bullet status of line.
21392 Also turns a plain line or a region of lines into list items.
21393 Calls `org-table-insert-hline', `org-toggle-item', or
21394 `org-cycle-list-bullet', depending on context."
21395 (interactive)
21396 (cond
21397 ((org-at-table-p)
21398 (call-interactively 'org-table-insert-hline))
21399 ((org-region-active-p)
21400 (call-interactively 'org-toggle-item))
21401 ((org-in-item-p)
21402 (call-interactively 'org-cycle-list-bullet))
21404 (call-interactively 'org-toggle-item))))
21406 (defun org-toggle-item (arg)
21407 "Convert headings or normal lines to items, items to normal lines.
21408 If there is no active region, only the current line is considered.
21410 If the first non blank line in the region is a headline, convert
21411 all headlines to items, shifting text accordingly.
21413 If it is an item, convert all items to normal lines.
21415 If it is normal text, change region into a list of items.
21416 With a prefix argument ARG, change the region in a single item."
21417 (interactive "P")
21418 (let ((shift-text
21419 (function
21420 ;; Shift text in current section to IND, from point to END.
21421 ;; The function leaves point to END line.
21422 (lambda (ind end)
21423 (let ((min-i 1000) (end (copy-marker end)))
21424 ;; First determine the minimum indentation (MIN-I) of
21425 ;; the text.
21426 (save-excursion
21427 (catch 'exit
21428 (while (< (point) end)
21429 (let ((i (org-get-indentation)))
21430 (cond
21431 ;; Skip blank lines and inline tasks.
21432 ((looking-at "^[ \t]*$"))
21433 ((looking-at org-outline-regexp-bol))
21434 ;; We can't find less than 0 indentation.
21435 ((zerop i) (throw 'exit (setq min-i 0)))
21436 ((< i min-i) (setq min-i i))))
21437 (forward-line))))
21438 ;; Then indent each line so that a line indented to
21439 ;; MIN-I becomes indented to IND. Ignore blank lines
21440 ;; and inline tasks in the process.
21441 (let ((delta (- ind min-i)))
21442 (while (< (point) end)
21443 (unless (or (looking-at "^[ \t]*$")
21444 (looking-at org-outline-regexp-bol))
21445 (org-indent-line-to (+ (org-get-indentation) delta)))
21446 (forward-line)))))))
21447 (skip-blanks
21448 (function
21449 ;; Return beginning of first non-blank line, starting from
21450 ;; line at POS.
21451 (lambda (pos)
21452 (save-excursion
21453 (goto-char pos)
21454 (skip-chars-forward " \r\t\n")
21455 (point-at-bol)))))
21456 beg end)
21457 ;; Determine boundaries of changes.
21458 (if (org-region-active-p)
21459 (setq beg (funcall skip-blanks (region-beginning))
21460 end (copy-marker (region-end)))
21461 (setq beg (funcall skip-blanks (point-at-bol))
21462 end (copy-marker (point-at-eol))))
21463 ;; Depending on the starting line, choose an action on the text
21464 ;; between BEG and END.
21465 (org-with-limited-levels
21466 (save-excursion
21467 (goto-char beg)
21468 (cond
21469 ;; Case 1. Start at an item: de-itemize. Note that it only
21470 ;; happens when a region is active: `org-ctrl-c-minus'
21471 ;; would call `org-cycle-list-bullet' otherwise.
21472 ((org-at-item-p)
21473 (while (< (point) end)
21474 (when (org-at-item-p)
21475 (skip-chars-forward " \t")
21476 (delete-region (point) (match-end 0)))
21477 (forward-line)))
21478 ;; Case 2. Start at an heading: convert to items.
21479 ((org-at-heading-p)
21480 (let* ((bul (org-list-bullet-string "-"))
21481 (bul-len (length bul))
21482 (done (org-entry-is-done-p))
21483 (todo (org-entry-is-todo-p))
21484 ;; Indentation of the first heading. It should be
21485 ;; relative to the indentation of its parent, if any.
21486 (start-ind (save-excursion
21487 (cond
21488 ((not org-adapt-indentation) 0)
21489 ((not (outline-previous-heading)) 0)
21490 (t (length (match-string 0))))))
21491 ;; Level of first heading. Further headings will be
21492 ;; compared to it to determine hierarchy in the list.
21493 (ref-level (org-reduced-level (org-outline-level))))
21494 (when (or done todo) (org-todo ""))
21495 (while (< (point) end)
21496 (let* ((level (org-reduced-level (org-outline-level)))
21497 (delta (max 0 (- level ref-level))))
21498 ;; If current headline is less indented than the first
21499 ;; one, set it as reference, in order to preserve
21500 ;; subtrees.
21501 (when (< level ref-level) (setq ref-level level))
21502 (replace-match bul t t)
21503 (org-indent-line-to (+ start-ind (* delta bul-len)))
21504 (when (or done todo)
21505 (let* ((struct (org-list-struct))
21506 (old (copy-tree struct)))
21507 (org-list-set-checkbox (line-beginning-position)
21508 struct
21509 (if done "[X]" "[ ]"))
21510 (org-list-write-struct struct
21511 (org-list-parents-alist struct)
21512 old)))
21513 ;; Ensure all text down to END (or SECTION-END) belongs
21514 ;; to the newly created item.
21515 (let ((section-end (save-excursion
21516 (or (outline-next-heading) (point)))))
21517 (forward-line)
21518 (funcall shift-text
21519 (+ start-ind (* (1+ delta) bul-len))
21520 (min end section-end)))))))
21521 ;; Case 3. Normal line with ARG: make the first line of region
21522 ;; an item, and shift indentation of others lines to
21523 ;; set them as item's body.
21524 (arg (let* ((bul (org-list-bullet-string "-"))
21525 (bul-len (length bul))
21526 (ref-ind (org-get-indentation)))
21527 (skip-chars-forward " \t")
21528 (insert bul)
21529 (forward-line)
21530 (while (< (point) end)
21531 ;; Ensure that lines less indented than first one
21532 ;; still get included in item body.
21533 (funcall shift-text
21534 (+ ref-ind bul-len)
21535 (min end (save-excursion (or (outline-next-heading)
21536 (point)))))
21537 (forward-line))))
21538 ;; Case 4. Normal line without ARG: turn each non-item line
21539 ;; into an item.
21541 (while (< (point) end)
21542 (unless (or (org-at-heading-p) (org-at-item-p))
21543 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21544 (replace-match
21545 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21546 (forward-line))))))))
21548 (defun org-toggle-heading (&optional nstars)
21549 "Convert headings to normal text, or items or text to headings.
21550 If there is no active region, only convert the current line.
21552 With a \\[universal-argument] prefix, convert the whole list at
21553 point into heading.
21555 In a region:
21557 - If the first non blank line is a headline, remove the stars
21558 from all headlines in the region.
21560 - If it is a normal line, turn each and every normal line (i.e.,
21561 not an heading or an item) in the region into headings. If you
21562 want to convert only the first line of this region, use one
21563 universal prefix argument.
21565 - If it is a plain list item, turn all plain list items into headings.
21567 When converting a line into a heading, the number of stars is chosen
21568 such that the lines become children of the current entry. However,
21569 when a numeric prefix argument is given, its value determines the
21570 number of stars to add."
21571 (interactive "P")
21572 (let ((skip-blanks
21573 (function
21574 ;; Return beginning of first non-blank line, starting from
21575 ;; line at POS.
21576 (lambda (pos)
21577 (save-excursion
21578 (goto-char pos)
21579 (while (org-at-comment-p) (forward-line))
21580 (skip-chars-forward " \r\t\n")
21581 (point-at-bol)))))
21582 beg end toggled)
21583 ;; Determine boundaries of changes. If a universal prefix has
21584 ;; been given, put the list in a region. If region ends at a bol,
21585 ;; do not consider the last line to be in the region.
21587 (when (and current-prefix-arg (org-at-item-p))
21588 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21589 (org-mark-element))
21591 (if (org-region-active-p)
21592 (setq beg (funcall skip-blanks (region-beginning))
21593 end (copy-marker (save-excursion
21594 (goto-char (region-end))
21595 (if (bolp) (point) (point-at-eol)))))
21596 (setq beg (funcall skip-blanks (point-at-bol))
21597 end (copy-marker (point-at-eol))))
21598 ;; Ensure inline tasks don't count as headings.
21599 (org-with-limited-levels
21600 (save-excursion
21601 (goto-char beg)
21602 (cond
21603 ;; Case 1. Started at an heading: de-star headings.
21604 ((org-at-heading-p)
21605 (while (< (point) end)
21606 (when (org-at-heading-p t)
21607 (looking-at org-outline-regexp) (replace-match "")
21608 (setq toggled t))
21609 (forward-line)))
21610 ;; Case 2. Started at an item: change items into headlines.
21611 ;; One star will be added by `org-list-to-subtree'.
21612 ((org-at-item-p)
21613 (while (< (point) end)
21614 (when (org-at-item-p)
21615 ;; Pay attention to cases when region ends before list.
21616 (let* ((struct (org-list-struct))
21617 (list-end
21618 (min (org-list-get-bottom-point struct) (1+ end))))
21619 (save-restriction
21620 (narrow-to-region (point) list-end)
21621 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21622 (setq toggled t))
21623 (forward-line)))
21624 ;; Case 3. Started at normal text: make every line an heading,
21625 ;; skipping headlines and items.
21626 (t (let* ((stars
21627 (make-string
21628 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21629 (add-stars
21630 (cond (nstars "") ; stars from prefix only
21631 ((equal stars "") "*") ; before first heading
21632 (org-odd-levels-only "**") ; inside heading, odd
21633 (t "*"))) ; inside heading, oddeven
21634 (rpl (concat stars add-stars " "))
21635 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21636 (while (< (point) (if (equal nstars '(4)) lend end))
21637 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21638 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21639 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21640 (forward-line)))))))
21641 (unless toggled (message "Cannot toggle heading from here"))))
21643 (defun org-meta-return (&optional _arg)
21644 "Insert a new heading or wrap a region in a table.
21645 Calls `org-insert-heading' or `org-table-wrap-region', depending
21646 on context. See the individual commands for more information."
21647 (interactive)
21648 (org-check-before-invisible-edit 'insert)
21649 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21650 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21651 #'org-insert-heading))))
21653 ;;; Menu entries
21655 (defsubst org-in-subtree-not-table-p ()
21656 "Are we in a subtree and not in a table?"
21657 (and (not (org-before-first-heading-p))
21658 (not (org-at-table-p))))
21660 ;; Define the Org-mode menus
21661 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21662 '("Tbl"
21663 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21664 ["Next Field" org-cycle (org-at-table-p)]
21665 ["Previous Field" org-shifttab (org-at-table-p)]
21666 ["Next Row" org-return (org-at-table-p)]
21667 "--"
21668 ["Blank Field" org-table-blank-field (org-at-table-p)]
21669 ["Edit Field" org-table-edit-field (org-at-table-p)]
21670 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21671 "--"
21672 ("Column"
21673 ["Move Column Left" org-metaleft (org-at-table-p)]
21674 ["Move Column Right" org-metaright (org-at-table-p)]
21675 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21676 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21677 ("Row"
21678 ["Move Row Up" org-metaup (org-at-table-p)]
21679 ["Move Row Down" org-metadown (org-at-table-p)]
21680 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21681 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21682 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21683 "--"
21684 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21685 ("Rectangle"
21686 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21687 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21688 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21689 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21690 "--"
21691 ("Calculate"
21692 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21693 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21694 ["Edit Formulas" org-edit-special (org-at-table-p)]
21695 "--"
21696 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21697 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21698 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21699 "--"
21700 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21701 "--"
21702 ["Sum Column/Rectangle" org-table-sum
21703 (or (org-at-table-p) (org-region-active-p))]
21704 ["Which Column?" org-table-current-column (org-at-table-p)])
21705 ["Debug Formulas"
21706 org-table-toggle-formula-debugger
21707 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21708 ["Show Col/Row Numbers"
21709 org-table-toggle-coordinate-overlays
21710 :style toggle
21711 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21712 "--"
21713 ["Create" org-table-create (and (not (org-at-table-p))
21714 org-enable-table-editor)]
21715 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21716 ["Import from File" org-table-import (not (org-at-table-p))]
21717 ["Export to File" org-table-export (org-at-table-p)]
21718 "--"
21719 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21720 "--"
21721 ("Plot"
21722 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21723 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21725 (easy-menu-define org-org-menu org-mode-map "Org menu"
21726 '("Org"
21727 ("Show/Hide"
21728 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21729 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21730 ["Sparse Tree..." org-sparse-tree t]
21731 ["Reveal Context" org-reveal t]
21732 ["Show All" outline-show-all t]
21733 "--"
21734 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21735 "--"
21736 ["New Heading" org-insert-heading t]
21737 ("Navigate Headings"
21738 ["Up" outline-up-heading t]
21739 ["Next" outline-next-visible-heading t]
21740 ["Previous" outline-previous-visible-heading t]
21741 ["Next Same Level" outline-forward-same-level t]
21742 ["Previous Same Level" outline-backward-same-level t]
21743 "--"
21744 ["Jump" org-goto t])
21745 ("Edit Structure"
21746 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21747 "--"
21748 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21749 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21750 "--"
21751 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21752 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21753 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21754 "--"
21755 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21756 "--"
21757 ["Copy visible text" org-copy-visible t]
21758 "--"
21759 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21760 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21761 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21762 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21763 "--"
21764 ["Sort Region/Children" org-sort t]
21765 "--"
21766 ["Convert to odd levels" org-convert-to-odd-levels t]
21767 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21768 ("Editing"
21769 ["Emphasis..." org-emphasize t]
21770 ["Edit Source Example" org-edit-special t]
21771 "--"
21772 ["Footnote new/jump" org-footnote-action t]
21773 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21774 ("Archive"
21775 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21776 "--"
21777 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21778 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21779 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21781 "--"
21782 ("Hyperlinks"
21783 ["Store Link (Global)" org-store-link t]
21784 ["Find existing link to here" org-occur-link-in-agenda-files t]
21785 ["Insert Link" org-insert-link t]
21786 ["Follow Link" org-open-at-point t]
21787 "--"
21788 ["Next link" org-next-link t]
21789 ["Previous link" org-previous-link t]
21790 "--"
21791 ["Descriptive Links"
21792 org-toggle-link-display
21793 :style radio
21794 :selected org-descriptive-links
21796 ["Literal Links"
21797 org-toggle-link-display
21798 :style radio
21799 :selected (not org-descriptive-links)])
21800 "--"
21801 ("TODO Lists"
21802 ["TODO/DONE/-" org-todo t]
21803 ("Select keyword"
21804 ["Next keyword" org-shiftright (org-at-heading-p)]
21805 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21806 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21807 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21808 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21809 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21810 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21811 "--"
21812 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21813 :selected org-enforce-todo-dependencies :style toggle :active t]
21814 "Settings for tree at point"
21815 ["Do Children sequentially" org-toggle-ordered-property :style radio
21816 :selected (org-entry-get nil "ORDERED")
21817 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21818 ["Do Children parallel" org-toggle-ordered-property :style radio
21819 :selected (not (org-entry-get nil "ORDERED"))
21820 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21821 "--"
21822 ["Set Priority" org-priority t]
21823 ["Priority Up" org-shiftup t]
21824 ["Priority Down" org-shiftdown t]
21825 "--"
21826 ["Get news from all feeds" org-feed-update-all t]
21827 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21828 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21829 ("TAGS and Properties"
21830 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21831 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21832 "--"
21833 ["Set property" org-set-property (not (org-before-first-heading-p))]
21834 ["Column view of properties" org-columns t]
21835 ["Insert Column View DBlock" org-columns-insert-dblock t])
21836 ("Dates and Scheduling"
21837 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21838 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21839 ("Change Date"
21840 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21841 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21842 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21843 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21844 ["Compute Time Range" org-evaluate-time-range t]
21845 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21846 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21847 "--"
21848 ["Custom time format" org-toggle-time-stamp-overlays
21849 :style radio :selected org-display-custom-times]
21850 "--"
21851 ["Goto Calendar" org-goto-calendar t]
21852 ["Date from Calendar" org-date-from-calendar t]
21853 "--"
21854 ["Start/Restart Timer" org-timer-start t]
21855 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21856 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21857 ["Insert Timer String" org-timer t]
21858 ["Insert Timer Item" org-timer-item t])
21859 ("Logging work"
21860 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21861 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21862 ["Clock out" org-clock-out t]
21863 ["Clock cancel" org-clock-cancel t]
21864 "--"
21865 ["Mark as default task" org-clock-mark-default-task t]
21866 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21867 ["Goto running clock" org-clock-goto t]
21868 "--"
21869 ["Display times" org-clock-display t]
21870 ["Create clock table" org-clock-report t]
21871 "--"
21872 ["Record DONE time"
21873 (progn (setq org-log-done (not org-log-done))
21874 (message "Switching to %s will %s record a timestamp"
21875 (car org-done-keywords)
21876 (if org-log-done "automatically" "not")))
21877 :style toggle :selected org-log-done])
21878 "--"
21879 ["Agenda Command..." org-agenda t]
21880 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21881 ("File List for Agenda")
21882 ("Special views current file"
21883 ["TODO Tree" org-show-todo-tree t]
21884 ["Check Deadlines" org-check-deadlines t]
21885 ["Timeline" org-timeline t]
21886 ["Tags/Property tree" org-match-sparse-tree t])
21887 "--"
21888 ["Export/Publish..." org-export-dispatch t]
21889 ("LaTeX"
21890 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21891 :selected org-cdlatex-mode]
21892 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21893 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21894 ["Modify math symbol" org-cdlatex-math-modify
21895 (org-inside-LaTeX-fragment-p)]
21896 ["Insert citation" org-reftex-citation t]
21897 "--"
21898 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21899 "--"
21900 ("MobileOrg"
21901 ["Push Files and Views" org-mobile-push t]
21902 ["Get Captured and Flagged" org-mobile-pull t]
21903 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21904 "--"
21905 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21906 "--"
21907 ("Documentation"
21908 ["Show Version" org-version t]
21909 ["Info Documentation" org-info t])
21910 ("Customize"
21911 ["Browse Org Group" org-customize t]
21912 "--"
21913 ["Expand This Menu" org-create-customize-menu
21914 (fboundp 'customize-menu-create)])
21915 ["Send bug report" org-submit-bug-report t]
21916 "--"
21917 ("Refresh/Reload"
21918 ["Refresh setup current buffer" org-mode-restart t]
21919 ["Reload Org (after update)" org-reload t]
21920 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21923 (defun org-info (&optional node)
21924 "Read documentation for Org-mode in the info system.
21925 With optional NODE, go directly to that node."
21926 (interactive)
21927 (info (format "(org)%s" (or node ""))))
21929 ;;;###autoload
21930 (defun org-submit-bug-report ()
21931 "Submit a bug report on Org-mode via mail.
21933 Don't hesitate to report any problems or inaccurate documentation.
21935 If you don't have setup sending mail from (X)Emacs, please copy the
21936 output buffer into your mail program, as it gives us important
21937 information about your Org-mode version and configuration."
21938 (interactive)
21939 (require 'reporter)
21940 (defvar reporter-prompt-for-summary-p)
21941 (org-load-modules-maybe)
21942 (org-require-autoloaded-modules)
21943 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21944 (reporter-submit-bug-report
21945 "emacs-orgmode@gnu.org"
21946 (org-version nil 'full)
21947 (let (list)
21948 (save-window-excursion
21949 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21950 (delete-other-windows)
21951 (erase-buffer)
21952 (insert "You are about to submit a bug report to the Org-mode mailing list.
21954 We would like to add your full Org-mode and Outline configuration to the
21955 bug report. This greatly simplifies the work of the maintainer and
21956 other experts on the mailing list.
21958 HOWEVER, some variables you have customized may contain private
21959 information. The names of customers, colleagues, or friends, might
21960 appear in the form of file names, tags, todo states, or search strings.
21961 If you answer yes to the prompt, you might want to check and remove
21962 such private information before sending the email.")
21963 (add-text-properties (point-min) (point-max) '(face org-warning))
21964 (when (yes-or-no-p "Include your Org-mode configuration ")
21965 (mapatoms
21966 (lambda (v)
21967 (and (boundp v)
21968 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21969 (or (and (symbol-value v)
21970 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21971 (and
21972 (get v 'custom-type) (get v 'standard-value)
21973 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21974 (push v list)))))
21975 (kill-buffer (get-buffer "*Warn about privacy*"))
21976 list))
21977 nil nil
21978 "Remember to cover the basics, that is, what you expected to happen and
21979 what in fact did happen. You don't know how to make a good report? See
21981 http://orgmode.org/manual/Feedback.html#Feedback
21983 Your bug report will be posted to the Org-mode mailing list.
21984 ------------------------------------------------------------------------")
21985 (save-excursion
21986 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
21987 (replace-match "\\1Bug: \\3 [\\2]")))))
21990 (defun org-install-agenda-files-menu ()
21991 (let ((bl (buffer-list)))
21992 (save-excursion
21993 (while bl
21994 (set-buffer (pop bl))
21995 (when (derived-mode-p 'org-mode) (setq bl nil)))
21996 (when (derived-mode-p 'org-mode)
21997 (easy-menu-change
21998 '("Org") "File List for Agenda"
21999 (append
22000 (list
22001 ["Edit File List" (org-edit-agenda-file-list) t]
22002 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
22003 ["Remove Current File from List" org-remove-file t]
22004 ["Cycle through agenda files" org-cycle-agenda-files t]
22005 ["Occur in all agenda files" org-occur-in-agenda-files t]
22006 "--")
22007 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22009 ;;;; Documentation
22011 (defun org-require-autoloaded-modules ()
22012 (interactive)
22013 (mapc #'require
22014 '(org-agenda org-archive org-attach org-clock org-colview org-id
22015 org-table org-timer)))
22017 ;;;###autoload
22018 (defun org-reload (&optional uncompiled)
22019 "Reload all org lisp files.
22020 With prefix arg UNCOMPILED, load the uncompiled versions."
22021 (interactive "P")
22022 (require 'loadhist)
22023 (let* ((org-dir (org-find-library-dir "org"))
22024 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22025 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22026 (remove-re (mapconcat 'identity
22027 (mapcar (lambda (f) (concat "^" f "$"))
22028 (list (if (featurep 'xemacs)
22029 "org-colview"
22030 "org-colview-xemacs")
22031 "org" "org-loaddefs" "org-version"))
22032 "\\|"))
22033 (feats (delete-dups
22034 (mapcar 'file-name-sans-extension
22035 (mapcar 'file-name-nondirectory
22036 (delq nil
22037 (mapcar 'feature-file
22038 features))))))
22039 (lfeat (append
22040 (sort
22041 (setq feats
22042 (delq nil (mapcar
22043 (lambda (f)
22044 (if (and (string-match feature-re f)
22045 (not (string-match remove-re f)))
22046 f nil))
22047 feats)))
22048 'string-lessp)
22049 (list "org-version" "org")))
22050 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22051 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22052 load-uncore load-misses)
22053 (setq load-misses
22054 (delq 't
22055 (mapcar (lambda (f)
22056 (or (org-load-noerror-mustsuffix (concat org-dir f))
22057 (and (string= org-dir contrib-dir)
22058 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22059 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22060 (add-to-list 'load-uncore f 'append)
22063 lfeat)))
22064 (when load-uncore
22065 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22066 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22067 (if load-misses
22068 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22069 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22070 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22072 ;;;###autoload
22073 (defun org-customize ()
22074 "Call the customize function with org as argument."
22075 (interactive)
22076 (org-load-modules-maybe)
22077 (org-require-autoloaded-modules)
22078 (customize-browse 'org))
22080 (defun org-create-customize-menu ()
22081 "Create a full customization menu for Org-mode, insert it into the menu."
22082 (interactive)
22083 (org-load-modules-maybe)
22084 (org-require-autoloaded-modules)
22085 (if (fboundp 'customize-menu-create)
22086 (progn
22087 (easy-menu-change
22088 '("Org") "Customize"
22089 `(["Browse Org group" org-customize t]
22090 "--"
22091 ,(customize-menu-create 'org)
22092 ["Set" Custom-set t]
22093 ["Save" Custom-save t]
22094 ["Reset to Current" Custom-reset-current t]
22095 ["Reset to Saved" Custom-reset-saved t]
22096 ["Reset to Standard Settings" Custom-reset-standard t]))
22097 (message "\"Org\"-menu now contains full customization menu"))
22098 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22100 ;;;; Miscellaneous stuff
22102 ;;; Generally useful functions
22104 (defun org-get-at-eol (property n)
22105 "Get text property PROPERTY at the end of line less N characters."
22106 (get-text-property (- (point-at-eol) n) property))
22108 (defun org-find-text-property-in-string (prop s)
22109 "Return the first non-nil value of property PROP in string S."
22110 (or (get-text-property 0 prop s)
22111 (get-text-property (or (next-single-property-change 0 prop s) 0)
22112 prop s)))
22114 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22115 "Display the given MESSAGE as a warning."
22116 (if (fboundp 'display-warning)
22117 (display-warning 'org message
22118 (if (featurep 'xemacs) 'warning :warning))
22119 (let ((buf (get-buffer-create "*Org warnings*")))
22120 (with-current-buffer buf
22121 (goto-char (point-max))
22122 (insert "Warning (Org): " message)
22123 (unless (bolp)
22124 (newline)))
22125 (display-buffer buf)
22126 (sit-for 0))))
22128 (defun org-eval (form)
22129 "Eval FORM and return result."
22130 (condition-case error
22131 (eval form)
22132 (error (format "%%![Error: %s]" error))))
22134 (defun org-in-clocktable-p ()
22135 "Check if the cursor is in a clocktable."
22136 (let ((pos (point)) start)
22137 (save-excursion
22138 (end-of-line 1)
22139 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22140 (setq start (match-beginning 0))
22141 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22142 (>= (match-end 0) pos)
22143 start))))
22145 (defun org-in-verbatim-emphasis ()
22146 (save-match-data
22147 (and (org-in-regexp org-emph-re 2)
22148 (>= (point) (match-beginning 3))
22149 (<= (point) (match-end 4))
22150 (member (match-string 3) '("=" "~")))))
22152 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22153 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22154 (if (and marker (marker-buffer marker)
22155 (buffer-live-p (marker-buffer marker)))
22156 (progn
22157 (org-pop-to-buffer-same-window (marker-buffer marker))
22158 (when (or (> marker (point-max)) (< marker (point-min)))
22159 (widen))
22160 (goto-char marker)
22161 (org-show-context 'org-goto))
22162 (if bookmark
22163 (bookmark-jump bookmark)
22164 (error "Cannot find location"))))
22166 (defun org-quote-csv-field (s)
22167 "Quote field for inclusion in CSV material."
22168 (if (string-match "[\",]" s)
22169 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22172 (defun org-force-self-insert (N)
22173 "Needed to enforce self-insert under remapping."
22174 (interactive "p")
22175 (self-insert-command N))
22177 (defun org-string-width (s)
22178 "Compute width of string, ignoring invisible characters.
22179 This ignores character with invisibility property `org-link', and also
22180 characters with property `org-cwidth', because these will become invisible
22181 upon the next fontification round."
22182 (let (b l)
22183 (when (or (eq t buffer-invisibility-spec)
22184 (assq 'org-link buffer-invisibility-spec))
22185 (while (setq b (text-property-any 0 (length s)
22186 'invisible 'org-link s))
22187 (setq s (concat (substring s 0 b)
22188 (substring s (or (next-single-property-change
22189 b 'invisible s)
22190 (length s)))))))
22191 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22192 (setq s (concat (substring s 0 b)
22193 (substring s (or (next-single-property-change
22194 b 'org-cwidth s)
22195 (length s))))))
22196 (setq l (string-width s) b -1)
22197 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22198 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22201 (defun org-shorten-string (s maxlength)
22202 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22203 If the string is shorter or has length MAXLENGTH, just return the
22204 original string. If it is longer, the functions finds a space in the
22205 string, breaks this string off at that locations and adds three dots
22206 as ellipsis. Including the ellipsis, the string will not be longer
22207 than MAXLENGTH. If finding a good breaking point in the string does
22208 not work, the string is just chopped off in the middle of a word
22209 if necessary."
22210 (if (<= (length s) maxlength)
22212 (let* ((n (max (- maxlength 4) 1))
22213 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22214 (if (string-match re s)
22215 (concat (match-string 1 s) "...")
22216 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22218 (defun org-get-indentation (&optional line)
22219 "Get the indentation of the current line, interpreting tabs.
22220 When LINE is given, assume it represents a line and compute its indentation."
22221 (if line
22222 (when (string-match "^ *" (org-remove-tabs line))
22223 (match-end 0))
22224 (save-excursion
22225 (beginning-of-line 1)
22226 (skip-chars-forward " \t")
22227 (current-column))))
22229 (defun org-get-string-indentation (s)
22230 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22231 (let ((n -1) (i 0) (w tab-width) c)
22232 (catch 'exit
22233 (while (< (setq n (1+ n)) (length s))
22234 (setq c (aref s n))
22235 (cond ((= c ?\ ) (setq i (1+ i)))
22236 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22237 (t (throw 'exit t)))))
22240 (defun org-remove-tabs (s &optional width)
22241 "Replace tabulators in S with spaces.
22242 Assumes that s is a single line, starting in column 0."
22243 (setq width (or width tab-width))
22244 (while (string-match "\t" s)
22245 (setq s (replace-match
22246 (make-string
22247 (- (* width (/ (+ (match-beginning 0) width) width))
22248 (match-beginning 0)) ?\ )
22249 t t s)))
22252 (defun org-fix-indentation (line ind)
22253 "Fix indentation in LINE.
22254 IND is a cons cell with target and minimum indentation.
22255 If the current indentation in LINE is smaller than the minimum,
22256 leave it alone. If it is larger than ind, set it to the target."
22257 (let* ((l (org-remove-tabs line))
22258 (i (org-get-indentation l))
22259 (i1 (car ind)) (i2 (cdr ind)))
22260 (when (>= i i2) (setq l (substring line i2)))
22261 (if (> i1 0)
22262 (concat (make-string i1 ?\ ) l)
22263 l)))
22265 (defun org-remove-indentation (code &optional n)
22266 "Remove maximum common indentation in string CODE and return it.
22267 N may optionally be the number of columns to remove. Return CODE
22268 as-is if removal failed."
22269 (with-temp-buffer
22270 (insert code)
22271 (if (org-do-remove-indentation n) (buffer-string) code)))
22273 (defun org-do-remove-indentation (&optional n)
22274 "Remove the maximum common indentation from the buffer.
22275 When optional argument N is a positive integer, remove exactly
22276 that much characters from indentation, if possible. Return nil
22277 if it fails."
22278 (catch :exit
22279 (goto-char (point-min))
22280 ;; Find maximum common indentation, if not specified.
22281 (let ((n (or n
22282 (let ((min-ind (point-max)))
22283 (save-excursion
22284 (while (re-search-forward "^[ \t]*\\S-" nil t)
22285 (let ((ind (1- (current-column))))
22286 (if (zerop ind) (throw :exit nil)
22287 (setq min-ind (min min-ind ind))))))
22288 min-ind))))
22289 (if (zerop n) (throw :exit nil)
22290 ;; Remove exactly N indentation, but give up if not possible.
22291 (while (not (eobp))
22292 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22293 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22294 ((< ind n) (throw :exit nil))
22295 (t (org-indent-line-to (- ind n))))
22296 (forward-line)))
22297 ;; Signal success.
22298 t))))
22300 (defun org-fill-template (template alist)
22301 "Find each %key of ALIST in TEMPLATE and replace it."
22302 (let ((case-fold-search nil))
22303 (dolist (entry (sort (copy-sequence alist)
22304 (lambda (a b) (< (length (car a)) (length (car b))))))
22305 (setq template
22306 (replace-regexp-in-string
22307 (concat "%" (regexp-quote (car entry)))
22308 (or (cdr entry) "") template t t)))
22309 template))
22311 (defun org-base-buffer (buffer)
22312 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22313 (if (not buffer)
22314 buffer
22315 (or (buffer-base-buffer buffer)
22316 buffer)))
22318 (defun org-wrap (string &optional width lines)
22319 "Wrap string to either a number of lines, or a width in characters.
22320 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22321 that costs. If there is a word longer than WIDTH, the text is actually
22322 wrapped to the length of that word.
22323 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22324 many lines, whatever width that takes.
22325 The return value is a list of lines, without newlines at the end."
22326 (let* ((words (org-split-string string "[ \t\n]+"))
22327 (maxword (apply 'max (mapcar 'org-string-width words)))
22328 w ll)
22329 (cond (width
22330 (org-do-wrap words (max maxword width)))
22331 (lines
22332 (setq w maxword)
22333 (setq ll (org-do-wrap words maxword))
22334 (if (<= (length ll) lines)
22336 (setq ll words)
22337 (while (> (length ll) lines)
22338 (setq w (1+ w))
22339 (setq ll (org-do-wrap words w)))
22340 ll))
22341 (t (error "Cannot wrap this")))))
22343 (defun org-do-wrap (words width)
22344 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22345 (let (lines line)
22346 (while words
22347 (setq line (pop words))
22348 (while (and words (< (+ (length line) (length (car words))) width))
22349 (setq line (concat line " " (pop words))))
22350 (setq lines (push line lines)))
22351 (nreverse lines)))
22353 (defun org-split-string (string &optional separators)
22354 "Splits STRING into substrings at SEPARATORS.
22355 SEPARATORS is a regular expression.
22356 No empty strings are returned if there are matches at the beginning
22357 and end of string."
22358 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22359 (let ((start 0) notfirst list)
22360 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22361 (if (and notfirst
22362 (= start (match-beginning 0))
22363 (< start (length string)))
22364 (1+ start) start))
22365 (< (match-beginning 0) (length string)))
22366 (setq notfirst t)
22367 (or (eq (match-beginning 0) 0)
22368 (and (eq (match-beginning 0) (match-end 0))
22369 (eq (match-beginning 0) start))
22370 (push (substring string start (match-beginning 0)) list))
22371 (setq start (match-end 0)))
22372 (or (eq start (length string))
22373 (push (substring string start) list))
22374 (nreverse list)))
22376 (defun org-quote-vert (s)
22377 "Replace \"|\" with \"\\vert\"."
22378 (while (string-match "|" s)
22379 (setq s (replace-match "\\vert" t t s)))
22382 (defun org-uuidgen-p (s)
22383 "Is S an ID created by UUIDGEN?"
22384 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22386 (defun org-in-src-block-p (&optional inside)
22387 "Whether point is in a code source block.
22388 When INSIDE is non-nil, don't consider we are within a src block
22389 when point is at #+BEGIN_SRC or #+END_SRC."
22390 (let ((case-fold-search t))
22391 (or (and (eq (get-char-property (point) 'src-block) t))
22392 (and (not inside)
22393 (save-match-data
22394 (save-excursion
22395 (beginning-of-line)
22396 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22398 (defun org-context ()
22399 "Return a list of contexts of the current cursor position.
22400 If several contexts apply, all are returned.
22401 Each context entry is a list with a symbol naming the context, and
22402 two positions indicating start and end of the context. Possible
22403 contexts are:
22405 :headline anywhere in a headline
22406 :headline-stars on the leading stars in a headline
22407 :todo-keyword on a TODO keyword (including DONE) in a headline
22408 :tags on the TAGS in a headline
22409 :priority on the priority cookie in a headline
22410 :item on the first line of a plain list item
22411 :item-bullet on the bullet/number of a plain list item
22412 :checkbox on the checkbox in a plain list item
22413 :table in an org-mode table
22414 :table-special on a special filed in a table
22415 :table-table in a table.el table
22416 :clocktable in a clocktable
22417 :src-block in a source block
22418 :link on a hyperlink
22419 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22420 :target on a <<target>>
22421 :radio-target on a <<<radio-target>>>
22422 :latex-fragment on a LaTeX fragment
22423 :latex-preview on a LaTeX fragment with overlaid preview image
22425 This function expects the position to be visible because it uses font-lock
22426 faces as a help to recognize the following contexts: :table-special, :link,
22427 and :keyword."
22428 (let* ((f (get-text-property (point) 'face))
22429 (faces (if (listp f) f (list f)))
22430 (case-fold-search t)
22431 (p (point)) clist o)
22432 ;; First the large context
22433 (cond
22434 ((org-at-heading-p t)
22435 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22436 (when (progn
22437 (beginning-of-line 1)
22438 (looking-at org-todo-line-tags-regexp))
22439 (push (org-point-in-group p 1 :headline-stars) clist)
22440 (push (org-point-in-group p 2 :todo-keyword) clist)
22441 (push (org-point-in-group p 4 :tags) clist))
22442 (goto-char p)
22443 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22444 (when (looking-at "\\[#[A-Z0-9]\\]")
22445 (push (org-point-in-group p 0 :priority) clist)))
22447 ((org-at-item-p)
22448 (push (org-point-in-group p 2 :item-bullet) clist)
22449 (push (list :item (point-at-bol)
22450 (save-excursion (org-end-of-item) (point)))
22451 clist)
22452 (and (org-at-item-checkbox-p)
22453 (push (org-point-in-group p 0 :checkbox) clist)))
22455 ((org-at-table-p)
22456 (push (list :table (org-table-begin) (org-table-end)) clist)
22457 (when (memq 'org-formula faces)
22458 (push (list :table-special
22459 (previous-single-property-change p 'face)
22460 (next-single-property-change p 'face)) clist)))
22461 ((org-at-table-p 'any)
22462 (push (list :table-table) clist)))
22463 (goto-char p)
22465 (let ((case-fold-search t))
22466 ;; New the "medium" contexts: clocktables, source blocks
22467 (cond ((org-in-clocktable-p)
22468 (push (list :clocktable
22469 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22470 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22471 (match-beginning 1))
22472 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22473 (match-end 0))) clist))
22474 ((org-in-src-block-p)
22475 (push (list :src-block
22476 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22477 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22478 (match-beginning 1))
22479 (and (search-forward "#+END_SRC" nil t)
22480 (match-beginning 0))) clist))))
22481 (goto-char p)
22483 ;; Now the small context
22484 (cond
22485 ((org-at-timestamp-p)
22486 (push (org-point-in-group p 0 :timestamp) clist))
22487 ((memq 'org-link faces)
22488 (push (list :link
22489 (previous-single-property-change p 'face)
22490 (next-single-property-change p 'face)) clist))
22491 ((memq 'org-special-keyword faces)
22492 (push (list :keyword
22493 (previous-single-property-change p 'face)
22494 (next-single-property-change p 'face)) clist))
22495 ((org-at-target-p)
22496 (push (org-point-in-group p 0 :target) clist)
22497 (goto-char (1- (match-beginning 0)))
22498 (when (looking-at org-radio-target-regexp)
22499 (push (org-point-in-group p 0 :radio-target) clist))
22500 (goto-char p))
22501 ((setq o (cl-some
22502 (lambda (o)
22503 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22505 (overlays-at (point))))
22506 (push (list :latex-fragment
22507 (overlay-start o) (overlay-end o)) clist)
22508 (push (list :latex-preview
22509 (overlay-start o) (overlay-end o)) clist))
22510 ((org-inside-LaTeX-fragment-p)
22511 ;; FIXME: positions wrong.
22512 (push (list :latex-fragment (point) (point)) clist)))
22514 (setq clist (nreverse (delq nil clist)))
22515 clist))
22517 (defun org-in-regexp (regexp &optional nlines visually)
22518 "Check if point is inside a match of REGEXP.
22520 Normally only the current line is checked, but you can include
22521 NLINES extra lines around point into the search. If VISUALLY is
22522 set, require that the cursor is not after the match but really
22523 on, so that the block visually is on the match.
22525 Return nil or a cons cell (BEG . END) where BEG and END are,
22526 respectively, the positions at the beginning and the end of the
22527 match."
22528 (catch :exit
22529 (let ((pos (point))
22530 (eol (line-end-position (if nlines (1+ nlines) 1))))
22531 (save-excursion
22532 (beginning-of-line (- 1 (or nlines 0)))
22533 (while (and (re-search-forward regexp eol t)
22534 (<= (match-beginning 0) pos))
22535 (let ((end (match-end 0)))
22536 (when (or (> end pos) (and (= end pos) (not visually)))
22537 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22538 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22539 "Org mode 8.3")
22541 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22542 "Non-nil when point is between matches of START-RE and END-RE.
22544 Also return a non-nil value when point is on one of the matches.
22546 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22547 buffer positions. Default values are the positions of headlines
22548 surrounding the point.
22550 The functions returns a cons cell whose car (resp. cdr) is the
22551 position before START-RE (resp. after END-RE)."
22552 (save-match-data
22553 (let ((pos (point))
22554 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22555 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22556 beg end)
22557 (save-excursion
22558 ;; Point is on a block when on START-RE or if START-RE can be
22559 ;; found before it...
22560 (and (or (org-in-regexp start-re)
22561 (re-search-backward start-re limit-up t))
22562 (setq beg (match-beginning 0))
22563 ;; ... and END-RE after it...
22564 (goto-char (match-end 0))
22565 (re-search-forward end-re limit-down t)
22566 (> (setq end (match-end 0)) pos)
22567 ;; ... without another START-RE in-between.
22568 (goto-char (match-beginning 0))
22569 (not (re-search-backward start-re (1+ beg) t))
22570 ;; Return value.
22571 (cons beg end))))))
22573 (defun org-in-block-p (names)
22574 "Non-nil when point belongs to a block whose name belongs to NAMES.
22576 NAMES is a list of strings containing names of blocks.
22578 Return first block name matched, or nil. Beware that in case of
22579 nested blocks, the returned name may not belong to the closest
22580 block from point."
22581 (save-match-data
22582 (catch 'exit
22583 (let ((case-fold-search t)
22584 (lim-up (save-excursion (outline-previous-heading)))
22585 (lim-down (save-excursion (outline-next-heading))))
22586 (dolist (name names)
22587 (let ((n (regexp-quote name)))
22588 (when (org-between-regexps-p
22589 (concat "^[ \t]*#\\+begin_" n)
22590 (concat "^[ \t]*#\\+end_" n)
22591 lim-up lim-down)
22592 (throw 'exit n)))))
22593 nil)))
22595 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22596 "Call `multi-occur' with buffers for all agenda files."
22597 (interactive "sOrg-files matching: ")
22598 (let* ((files (org-agenda-files))
22599 (tnames (mapcar #'file-truename files))
22600 (extra org-agenda-text-search-extra-files))
22601 (when (eq (car extra) 'agenda-archives)
22602 (setq extra (cdr extra))
22603 (setq files (org-add-archive-files files)))
22604 (dolist (f extra)
22605 (unless (member (file-truename f) tnames)
22606 (unless (member f files) (setq files (append files (list f))))
22607 (setq tnames (append tnames (list (file-truename f))))))
22608 (multi-occur
22609 (mapcar (lambda (x)
22610 (with-current-buffer
22611 ;; FIXME: Why not just (find-file-noselect x)?
22612 ;; Is it to avoid the "revert buffer" prompt?
22613 (or (get-file-buffer x) (find-file-noselect x))
22614 (widen)
22615 (current-buffer)))
22616 files)
22617 regexp)))
22619 (if (boundp 'occur-mode-find-occurrence-hook)
22620 ;; Emacs 23
22621 (add-hook 'occur-mode-find-occurrence-hook
22622 (lambda ()
22623 (when (derived-mode-p 'org-mode)
22624 (org-reveal))))
22625 ;; Emacs 22
22626 (defadvice occur-mode-goto-occurrence
22627 (after org-occur-reveal activate)
22628 (and (derived-mode-p 'org-mode) (org-reveal)))
22629 (defadvice occur-mode-goto-occurrence-other-window
22630 (after org-occur-reveal activate)
22631 (and (derived-mode-p 'org-mode) (org-reveal)))
22632 (defadvice occur-mode-display-occurrence
22633 (after org-occur-reveal activate)
22634 (when (derived-mode-p 'org-mode)
22635 (let ((pos (occur-mode-find-occurrence)))
22636 (with-current-buffer (marker-buffer pos)
22637 (save-excursion
22638 (goto-char pos)
22639 (org-reveal)))))))
22641 (defun org-occur-link-in-agenda-files ()
22642 "Create a link and search for it in the agendas.
22643 The link is not stored in `org-stored-links', it is just created
22644 for the search purpose."
22645 (interactive)
22646 (let ((link (condition-case nil
22647 (org-store-link nil)
22648 (error "Unable to create a link to here"))))
22649 (org-occur-in-agenda-files (regexp-quote link))))
22651 (defun org-reverse-string (string)
22652 "Return the reverse of STRING."
22653 (apply 'string (reverse (string-to-list string))))
22655 ;; defsubst org-uniquify must be defined before first use
22657 (defun org-uniquify-alist (alist)
22658 "Merge elements of ALIST with the same key.
22660 For example, in this alist:
22662 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22663 => \\='((a 1 3) (b 2))
22665 merge (a 1) and (a 3) into (a 1 3).
22667 The function returns the new ALIST."
22668 (let (rtn)
22669 (dolist (e alist rtn)
22670 (let (n)
22671 (if (not (assoc (car e) rtn))
22672 (push e rtn)
22673 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22674 (setq rtn (assq-delete-all (car e) rtn))
22675 (push n rtn))))))
22677 (defun org-delete-all (elts list)
22678 "Remove all elements in ELTS from LIST."
22679 (while elts
22680 (setq list (delete (pop elts) list)))
22681 list)
22683 (defun org-back-over-empty-lines ()
22684 "Move backwards over whitespace, to the beginning of the first empty line.
22685 Returns the number of empty lines passed."
22686 (let ((pos (point)))
22687 (if (cdr (assoc 'heading org-blank-before-new-entry))
22688 (skip-chars-backward " \t\n\r")
22689 (unless (eobp)
22690 (forward-line -1)))
22691 (beginning-of-line 2)
22692 (goto-char (min (point) pos))
22693 (count-lines (point) pos)))
22695 (defun org-skip-whitespace ()
22696 (skip-chars-forward " \t\n\r"))
22698 (defun org-point-in-group (point group &optional context)
22699 "Check if POINT is in match-group GROUP.
22700 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22701 match. If the match group does not exist or point is not inside it,
22702 return nil."
22703 (and (match-beginning group)
22704 (>= point (match-beginning group))
22705 (<= point (match-end group))
22706 (if context
22707 (list context (match-beginning group) (match-end group))
22708 t)))
22710 (defun org-switch-to-buffer-other-window (&rest args)
22711 "Switch to buffer in a second window on the current frame.
22712 In particular, do not allow pop-up frames.
22713 Returns the newly created buffer."
22714 (org-no-popups
22715 (apply 'switch-to-buffer-other-window args)))
22717 (defun org-combine-plists (&rest plists)
22718 "Create a single property list from all plists in PLISTS.
22719 The process starts by copying the first list, and then setting properties
22720 from the other lists. Settings in the last list are the most significant
22721 ones and overrule settings in the other lists."
22722 (let ((rtn (copy-sequence (pop plists)))
22723 p v ls)
22724 (while plists
22725 (setq ls (pop plists))
22726 (while ls
22727 (setq p (pop ls) v (pop ls))
22728 (setq rtn (plist-put rtn p v))))
22729 rtn))
22731 (defun org-replace-escapes (string table)
22732 "Replace %-escapes in STRING with values in TABLE.
22733 TABLE is an association list with keys like \"%a\" and string values.
22734 The sequences in STRING may contain normal field width and padding information,
22735 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22736 so values can contain further %-escapes if they are define later in TABLE."
22737 (let ((tbl (copy-alist table))
22738 (case-fold-search nil)
22739 (pchg 0)
22740 re rpl)
22741 (dolist (e tbl)
22742 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22743 (when (and (cdr e) (string-match re (cdr e)))
22744 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22745 (safe "SREF"))
22746 (add-text-properties 0 3 (list 'sref sref) safe)
22747 (setcdr e (replace-match safe t t (cdr e)))))
22748 (while (string-match re string)
22749 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22750 (cdr e)))
22751 (setq string (replace-match rpl t t string))))
22752 (while (setq pchg (next-property-change pchg string))
22753 (let ((sref (get-text-property pchg 'sref string)))
22754 (when (and sref (string-match "SREF" string pchg))
22755 (setq string (replace-match sref t t string)))))
22756 string))
22758 (defun org-sublist (list start end)
22759 "Return a section of LIST, from START to END.
22761 Counting starts at 1."
22762 (cl-subseq list (1- start) end))
22763 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22765 (defun org-find-base-buffer-visiting (file)
22766 "Like `find-buffer-visiting' but always return the base buffer and
22767 not an indirect buffer."
22768 (let ((buf (or (get-file-buffer file)
22769 (find-buffer-visiting file))))
22770 (if buf
22771 (or (buffer-base-buffer buf) buf)
22772 nil)))
22774 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22775 "Org 9.0")
22777 ;;; TODO: Only called once, from ox-odt which should probably use
22778 ;;; org-export-inline-image-p or something.
22779 (defun org-file-image-p (file)
22780 "Return non-nil if FILE is an image."
22781 (save-match-data
22782 (string-match (image-file-name-regexp) file)))
22784 (defun org-get-cursor-date (&optional with-time)
22785 "Return the date at cursor in as a time.
22786 This works in the calendar and in the agenda, anywhere else it just
22787 returns the current time.
22788 If WITH-TIME is non-nil, returns the time of the event at point (in
22789 the agenda) or the current time of the day."
22790 (let (date day defd tp hod mod)
22791 (when with-time
22792 (setq tp (get-text-property (point) 'time))
22793 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22794 (setq hod (string-to-number (match-string 1 tp))
22795 mod (string-to-number (match-string 2 tp))))
22796 (or tp (let ((now (decode-time)))
22797 (setq hod (nth 2 now)
22798 mod (nth 1 now)))))
22799 (cond
22800 ((eq major-mode 'calendar-mode)
22801 (setq date (calendar-cursor-to-date)
22802 defd (encode-time 0 (or mod 0) (or hod 0)
22803 (nth 1 date) (nth 0 date) (nth 2 date))))
22804 ((eq major-mode 'org-agenda-mode)
22805 (setq day (get-text-property (point) 'day))
22806 (when day
22807 (setq date (calendar-gregorian-from-absolute day)
22808 defd (encode-time 0 (or mod 0) (or hod 0)
22809 (nth 1 date) (nth 0 date) (nth 2 date))))))
22810 (or defd (current-time))))
22812 (defun org-mark-subtree (&optional up)
22813 "Mark the current subtree.
22814 This puts point at the start of the current subtree, and mark at
22815 the end. If a numeric prefix UP is given, move up into the
22816 hierarchy of headlines by UP levels before marking the subtree."
22817 (interactive "P")
22818 (org-with-limited-levels
22819 (cond ((org-at-heading-p) (beginning-of-line))
22820 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22821 (t (outline-previous-visible-heading 1))))
22822 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22823 (if (org-called-interactively-p 'any)
22824 (call-interactively 'org-mark-element)
22825 (org-mark-element)))
22828 ;;; Indentation
22830 (defun org--get-expected-indentation (element contentsp)
22831 "Expected indentation column for current line, according to ELEMENT.
22832 ELEMENT is an element containing point. CONTENTSP is non-nil
22833 when indentation is to be computed according to contents of
22834 ELEMENT."
22835 (let ((type (org-element-type element))
22836 (start (org-element-property :begin element))
22837 (post-affiliated (org-element-property :post-affiliated element)))
22838 (org-with-wide-buffer
22839 (cond
22840 (contentsp
22841 (cl-case type
22842 ((diary-sexp footnote-definition) 0)
22843 ((headline inlinetask nil)
22844 (if (not org-adapt-indentation) 0
22845 (let ((level (org-current-level)))
22846 (if level (1+ level) 0))))
22847 ((item plain-list) (org-list-item-body-column post-affiliated))
22849 (goto-char start)
22850 (org-get-indentation))))
22851 ((memq type '(headline inlinetask nil))
22852 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22853 (org--get-expected-indentation element t)
22855 ((memq type '(diary-sexp footnote-definition)) 0)
22856 ;; First paragraph of a footnote definition or an item.
22857 ;; Indent like parent.
22858 ((< (line-beginning-position) start)
22859 (org--get-expected-indentation
22860 (org-element-property :parent element) t))
22861 ;; At first line: indent according to previous sibling, if any,
22862 ;; ignoring footnote definitions and inline tasks, or parent's
22863 ;; contents.
22864 ((= (line-beginning-position) start)
22865 (catch 'exit
22866 (while t
22867 (if (= (point-min) start) (throw 'exit 0)
22868 (goto-char (1- start))
22869 (let* ((previous (org-element-at-point))
22870 (parent previous))
22871 (while (and parent (<= (org-element-property :end parent) start))
22872 (setq previous parent
22873 parent (org-element-property :parent parent)))
22874 (cond
22875 ((not previous) (throw 'exit 0))
22876 ((> (org-element-property :end previous) start)
22877 (throw 'exit (org--get-expected-indentation previous t)))
22878 ((memq (org-element-type previous)
22879 '(footnote-definition inlinetask))
22880 (setq start (org-element-property :begin previous)))
22881 (t (goto-char (org-element-property :begin previous))
22882 (throw 'exit
22883 (if (bolp) (org-get-indentation)
22884 ;; At first paragraph in an item or
22885 ;; a footnote definition.
22886 (org--get-expected-indentation
22887 (org-element-property :parent previous) t))))))))))
22888 ;; Otherwise, move to the first non-blank line above.
22890 (beginning-of-line)
22891 (let ((pos (point)))
22892 (skip-chars-backward " \r\t\n")
22893 (cond
22894 ;; Two blank lines end a footnote definition or a plain
22895 ;; list. When we indent an empty line after them, the
22896 ;; containing list or footnote definition is over, so it
22897 ;; qualifies as a previous sibling. Therefore, we indent
22898 ;; like its first line.
22899 ((and (memq type '(footnote-definition plain-list))
22900 (> (count-lines (point) pos) 2))
22901 (goto-char start)
22902 (org-get-indentation))
22903 ;; Line above is the first one of a paragraph at the
22904 ;; beginning of an item or a footnote definition. Indent
22905 ;; like parent.
22906 ((< (line-beginning-position) start)
22907 (org--get-expected-indentation
22908 (org-element-property :parent element) t))
22909 ;; Line above is the beginning of an element, i.e., point
22910 ;; was originally on the blank lines between element's start
22911 ;; and contents.
22912 ((= (line-beginning-position) post-affiliated)
22913 (org--get-expected-indentation element t))
22914 ;; POS is after contents in a greater element. Indent like
22915 ;; the beginning of the element.
22917 ;; As a special case, if point is at the end of a footnote
22918 ;; definition or an item, indent like the very last element
22919 ;; within. If that last element is an item, indent like its
22920 ;; contents.
22921 ((and (not (eq type 'paragraph))
22922 (let ((cend (org-element-property :contents-end element)))
22923 (and cend (<= cend pos))))
22924 (if (memq type '(footnote-definition item plain-list))
22925 (let ((last (org-element-at-point)))
22926 (org--get-expected-indentation
22927 last (eq (org-element-type last) 'item)))
22928 (goto-char start)
22929 (org-get-indentation)))
22930 ;; In any other case, indent like the current line.
22931 (t (org-get-indentation)))))))))
22933 (defun org--align-node-property ()
22934 "Align node property at point.
22935 Alignment is done according to `org-property-format', which see."
22936 (when (save-excursion
22937 (beginning-of-line)
22938 (looking-at org-property-re))
22939 (replace-match
22940 (concat (match-string 4)
22941 (org-trim
22942 (format org-property-format (match-string 1) (match-string 3))))
22943 t t)))
22945 (defun org-indent-line ()
22946 "Indent line depending on context.
22948 Indentation is done according to the following rules:
22950 - Footnote definitions, diary sexps, headlines and inline tasks
22951 have to start at column 0.
22953 - On the very first line of an element, consider, in order, the
22954 next rules until one matches:
22956 1. If there's a sibling element before, ignoring footnote
22957 definitions and inline tasks, indent like its first line.
22959 2. If element has a parent, indent like its contents. More
22960 precisely, if parent is an item, indent after the
22961 description part, if any, or the bullet (see
22962 `org-list-description-max-indent'). Else, indent like
22963 parent's first line.
22965 3. Otherwise, indent relatively to current level, if
22966 `org-adapt-indentation' is non-nil, or to left margin.
22968 - On a blank line at the end of an element, indent according to
22969 the type of the element. More precisely
22971 1. If element is a plain list, an item, or a footnote
22972 definition, indent like the very last element within.
22974 2. If element is a paragraph, indent like its last non blank
22975 line.
22977 3. Otherwise, indent like its very first line.
22979 - In the code part of a source block, use language major mode
22980 to indent current line if `org-src-tab-acts-natively' is
22981 non-nil. If it is nil, do nothing.
22983 - Otherwise, indent like the first non-blank line above.
22985 The function doesn't indent an item as it could break the whole
22986 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
22987 \\[org-shiftmetaright].
22989 Also align node properties according to `org-property-format'."
22990 (interactive)
22991 (cond
22992 (orgstruct-is-++
22993 (let ((indent-line-function
22994 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
22995 (indent-according-to-mode)))
22996 ((org-at-heading-p) 'noindent)
22998 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
22999 (type (org-element-type element)))
23000 (cond ((and (memq type '(plain-list item))
23001 (= (line-beginning-position)
23002 (org-element-property :post-affiliated element)))
23003 'noindent)
23004 ((and (eq type 'src-block)
23005 org-src-tab-acts-natively
23006 (> (line-beginning-position)
23007 (org-element-property :post-affiliated element))
23008 (< (line-beginning-position)
23009 (org-with-wide-buffer
23010 (goto-char (org-element-property :end element))
23011 (skip-chars-backward " \r\t\n")
23012 (line-beginning-position))))
23013 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23015 (let ((column (org--get-expected-indentation element nil)))
23016 ;; Preserve current column.
23017 (if (<= (current-column) (current-indentation))
23018 (org-indent-line-to column)
23019 (save-excursion (org-indent-line-to column))))
23020 ;; Align node property. Also preserve current column.
23021 (when (eq type 'node-property)
23022 (let ((column (current-column)))
23023 (org--align-node-property)
23024 (org-move-to-column column)))))))))
23026 (defun org-indent-region (start end)
23027 "Indent each non-blank line in the region.
23028 Called from a program, START and END specify the region to
23029 indent. The function will not indent contents of example blocks,
23030 verse blocks and export blocks as leading white spaces are
23031 assumed to be significant there."
23032 (interactive "r")
23033 (save-excursion
23034 (goto-char start)
23035 (skip-chars-forward " \r\t\n")
23036 (unless (eobp) (beginning-of-line))
23037 (let ((indent-to
23038 (lambda (ind pos)
23039 ;; Set IND as indentation for all lines between point and
23040 ;; POS. Blank lines are ignored. Leave point after POS
23041 ;; once done.
23042 (let ((limit (copy-marker pos)))
23043 (while (< (point) limit)
23044 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23045 (forward-line))
23046 (set-marker limit nil))))
23047 (end (copy-marker end)))
23048 (while (< (point) end)
23049 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23050 (let* ((element (org-element-at-point))
23051 (type (org-element-type element))
23052 (element-end (copy-marker (org-element-property :end element)))
23053 (ind (org--get-expected-indentation element nil)))
23054 (cond
23055 ((or (memq type '(paragraph table table-row))
23056 (not (or (org-element-property :contents-begin element)
23057 (memq type
23058 '(example-block export-block src-block)))))
23059 ;; Elements here are indented as a single block. Also
23060 ;; align node properties.
23061 (when (eq type 'node-property)
23062 (org--align-node-property)
23063 (beginning-of-line))
23064 (funcall indent-to ind (min element-end end)))
23066 ;; Elements in this category consist of three parts:
23067 ;; before the contents, the contents, and after the
23068 ;; contents. The contents are treated specially,
23069 ;; according to the element type, or not indented at
23070 ;; all. Other parts are indented as a single block.
23071 (let* ((post (copy-marker
23072 (org-element-property :post-affiliated element)))
23073 (cbeg
23074 (copy-marker
23075 (cond
23076 ((not (org-element-property :contents-begin element))
23077 ;; Fake contents for source blocks.
23078 (org-with-wide-buffer
23079 (goto-char post)
23080 (forward-line)
23081 (point)))
23082 ((memq type '(footnote-definition item plain-list))
23083 ;; Contents in these elements could start on
23084 ;; the same line as the beginning of the
23085 ;; element. Make sure we start indenting
23086 ;; from the second line.
23087 (org-with-wide-buffer
23088 (goto-char post)
23089 (end-of-line)
23090 (skip-chars-forward " \r\t\n")
23091 (if (eobp) (point) (line-beginning-position))))
23092 (t (org-element-property :contents-begin element)))))
23093 (cend (copy-marker
23094 (or (org-element-property :contents-end element)
23095 ;; Fake contents for source blocks.
23096 (org-with-wide-buffer
23097 (goto-char element-end)
23098 (skip-chars-backward " \r\t\n")
23099 (line-beginning-position)))
23100 t)))
23101 ;; Do not change items indentation individually as it
23102 ;; might break the list as a whole. On the other
23103 ;; hand, when at a plain list, indent it as a whole.
23104 (cond ((eq type 'plain-list)
23105 (let ((offset (- ind (org-get-indentation))))
23106 (unless (zerop offset)
23107 (indent-rigidly (org-element-property :begin element)
23108 (org-element-property :end element)
23109 offset))
23110 (goto-char cbeg)))
23111 ((eq type 'item) (goto-char cbeg))
23112 (t (funcall indent-to ind (min cbeg end))))
23113 (when (< (point) end)
23114 (cl-case type
23115 ((example-block export-block verse-block))
23116 (src-block
23117 ;; In a source block, indent source code
23118 ;; according to language major mode, but only if
23119 ;; `org-src-tab-acts-natively' is non-nil.
23120 (when (and (< (point) end) org-src-tab-acts-natively)
23121 (ignore-errors
23122 (org-babel-do-in-edit-buffer
23123 (indent-region (point-min) (point-max))))))
23124 (t (org-indent-region (point) (min cend end))))
23125 (goto-char (min cend end))
23126 (when (< (point) end)
23127 (funcall indent-to ind (min element-end end))))
23128 (set-marker post nil)
23129 (set-marker cbeg nil)
23130 (set-marker cend nil))))
23131 (set-marker element-end nil))))
23132 (set-marker end nil))))
23134 (defun org-indent-drawer ()
23135 "Indent the drawer at point."
23136 (interactive)
23137 (unless (save-excursion
23138 (beginning-of-line)
23139 (org-looking-at-p org-drawer-regexp))
23140 (user-error "Not at a drawer"))
23141 (let ((element (org-element-at-point)))
23142 (unless (memq (org-element-type element) '(drawer property-drawer))
23143 (user-error "Not at a drawer"))
23144 (org-with-wide-buffer
23145 (org-indent-region (org-element-property :begin element)
23146 (org-element-property :end element))))
23147 (message "Drawer at point indented"))
23149 (defun org-indent-block ()
23150 "Indent the block at point."
23151 (interactive)
23152 (unless (save-excursion
23153 (beginning-of-line)
23154 (let ((case-fold-search t))
23155 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23156 (user-error "Not at a block"))
23157 (let ((element (org-element-at-point)))
23158 (unless (memq (org-element-type element)
23159 '(comment-block center-block dynamic-block example-block
23160 export-block quote-block special-block
23161 src-block verse-block))
23162 (user-error "Not at a block"))
23163 (org-with-wide-buffer
23164 (org-indent-region (org-element-property :begin element)
23165 (org-element-property :end element))))
23166 (message "Block at point indented"))
23169 ;;; Filling
23171 ;; We use our own fill-paragraph and auto-fill functions.
23173 ;; `org-fill-paragraph' relies on adaptive filling and context
23174 ;; checking. Appropriate `fill-prefix' is computed with
23175 ;; `org-adaptive-fill-function'.
23177 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23178 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23179 ;; `org-adaptive-fill-function' value. Internally,
23180 ;; `org-comment-line-break-function' breaks the line.
23182 ;; `org-setup-filling' installs filling and auto-filling related
23183 ;; variables during `org-mode' initialization.
23185 (defvar org-element-paragraph-separate) ; org-element.el
23186 (defun org-setup-filling ()
23187 (require 'org-element)
23188 ;; Prevent auto-fill from inserting unwanted new items.
23189 (when (boundp 'fill-nobreak-predicate)
23190 (setq-local
23191 fill-nobreak-predicate
23192 (org-uniquify
23193 (append fill-nobreak-predicate
23194 '(org-fill-line-break-nobreak-p
23195 org-fill-paragraph-with-timestamp-nobreak-p)))))
23196 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23197 (setq-local paragraph-start paragraph-ending)
23198 (setq-local paragraph-separate paragraph-ending))
23199 (setq-local fill-paragraph-function 'org-fill-paragraph)
23200 (setq-local auto-fill-inhibit-regexp nil)
23201 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23202 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23203 (setq-local comment-line-break-function 'org-comment-line-break-function))
23205 (defun org-fill-line-break-nobreak-p ()
23206 "Non-nil when a new line at point would create an Org line break."
23207 (save-excursion
23208 (skip-chars-backward "[ \t]")
23209 (skip-chars-backward "\\\\")
23210 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23212 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23213 "Non-nil when a new line at point would split a timestamp."
23214 (and (org-at-timestamp-p t)
23215 (not (looking-at org-ts-regexp-both))))
23217 (declare-function message-in-body-p "message" ())
23218 (defvar orgtbl-line-start-regexp) ; From org-table.el
23219 (defun org-adaptive-fill-function ()
23220 "Compute a fill prefix for the current line.
23221 Return fill prefix, as a string, or nil if current line isn't
23222 meant to be filled. For convenience, if `adaptive-fill-regexp'
23223 matches in paragraphs or comments, use it."
23224 (catch 'exit
23225 (when (derived-mode-p 'message-mode)
23226 (save-excursion
23227 (beginning-of-line)
23228 (cond ((not (message-in-body-p)) (throw 'exit nil))
23229 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23230 ((looking-at message-cite-prefix-regexp)
23231 (throw 'exit (match-string-no-properties 0)))
23232 ((looking-at org-outline-regexp)
23233 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23234 (org-with-wide-buffer
23235 (unless (org-at-heading-p)
23236 (let* ((p (line-beginning-position))
23237 (element (save-excursion
23238 (beginning-of-line)
23239 (org-element-at-point)))
23240 (type (org-element-type element))
23241 (post-affiliated (org-element-property :post-affiliated element)))
23242 (unless (< p post-affiliated)
23243 (cl-case type
23244 (comment
23245 (save-excursion
23246 (beginning-of-line)
23247 (looking-at "[ \t]*")
23248 (concat (match-string 0) "# ")))
23249 (footnote-definition "")
23250 ((item plain-list)
23251 (make-string (org-list-item-body-column post-affiliated) ?\s))
23252 (paragraph
23253 ;; Fill prefix is usually the same as the current line,
23254 ;; unless the paragraph is at the beginning of an item.
23255 (let ((parent (org-element-property :parent element)))
23256 (save-excursion
23257 (beginning-of-line)
23258 (cond ((eq (org-element-type parent) 'item)
23259 (make-string (org-list-item-body-column
23260 (org-element-property :begin parent))
23261 ?\s))
23262 ((and adaptive-fill-regexp
23263 ;; Locally disable
23264 ;; `adaptive-fill-function' to let
23265 ;; `fill-context-prefix' handle
23266 ;; `adaptive-fill-regexp' variable.
23267 (let (adaptive-fill-function)
23268 (fill-context-prefix
23269 post-affiliated
23270 (org-element-property :end element)))))
23271 ((looking-at "[ \t]+") (match-string 0))
23272 (t "")))))
23273 (comment-block
23274 ;; Only fill contents if P is within block boundaries.
23275 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23276 (forward-line)
23277 (point)))
23278 (cend (save-excursion
23279 (goto-char (org-element-property :end element))
23280 (skip-chars-backward " \r\t\n")
23281 (line-beginning-position))))
23282 (when (and (>= p cbeg) (< p cend))
23283 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23284 (match-string 0)
23285 "")))))))))))
23287 (declare-function message-goto-body "message" ())
23288 (defvar message-cite-prefix-regexp) ; From message.el
23289 (defun org-fill-paragraph (&optional justify)
23290 "Fill element at point, when applicable.
23292 This function only applies to comment blocks, comments, example
23293 blocks and paragraphs. Also, as a special case, re-align table
23294 when point is at one.
23296 If JUSTIFY is non-nil (interactively, with prefix argument),
23297 justify as well. If `sentence-end-double-space' is non-nil, then
23298 period followed by one space does not end a sentence, so don't
23299 break a line there. The variable `fill-column' controls the
23300 width for filling.
23302 For convenience, when point is at a plain list, an item or
23303 a footnote definition, try to fill the first paragraph within."
23304 (interactive)
23305 (if (and (derived-mode-p 'message-mode)
23306 (or (not (message-in-body-p))
23307 (save-excursion (move-beginning-of-line 1)
23308 (looking-at message-cite-prefix-regexp))))
23309 ;; First ensure filling is correct in message-mode.
23310 (let ((fill-paragraph-function
23311 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23312 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23313 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23314 (paragraph-separate
23315 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23316 (fill-paragraph nil))
23317 (with-syntax-table org-mode-transpose-word-syntax-table
23318 ;; Move to end of line in order to get the first paragraph
23319 ;; within a plain list or a footnote definition.
23320 (let ((element (save-excursion
23321 (end-of-line)
23322 (or (ignore-errors (org-element-at-point))
23323 (user-error "An element cannot be parsed line %d"
23324 (line-number-at-pos (point)))))))
23325 ;; First check if point is in a blank line at the beginning of
23326 ;; the buffer. In that case, ignore filling.
23327 (cl-case (org-element-type element)
23328 ;; Use major mode filling function is src blocks.
23329 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23330 ;; Align Org tables, leave table.el tables as-is.
23331 (table-row (org-table-align) t)
23332 (table
23333 (when (eq (org-element-property :type element) 'org)
23334 (save-excursion
23335 (goto-char (org-element-property :post-affiliated element))
23336 (org-table-align)))
23338 (paragraph
23339 ;; Paragraphs may contain `line-break' type objects.
23340 (let ((beg (max (point-min)
23341 (org-element-property :contents-begin element)))
23342 (end (min (point-max)
23343 (org-element-property :contents-end element))))
23344 ;; Do nothing if point is at an affiliated keyword.
23345 (if (< (line-end-position) beg) t
23346 (when (derived-mode-p 'message-mode)
23347 ;; In `message-mode', do not fill following citation
23348 ;; in current paragraph nor text before message body.
23349 (let ((body-start (save-excursion (message-goto-body))))
23350 (when body-start (setq beg (max body-start beg))))
23351 (when (save-excursion
23352 (re-search-forward
23353 (concat "^" message-cite-prefix-regexp) end t))
23354 (setq end (match-beginning 0))))
23355 ;; Fill paragraph, taking line breaks into account.
23356 (save-excursion
23357 (goto-char beg)
23358 (let ((cuts (list beg)))
23359 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23360 (when (eq 'line-break
23361 (org-element-type
23362 (save-excursion (backward-char)
23363 (org-element-context))))
23364 (push (point) cuts)))
23365 (dolist (c (delq end cuts))
23366 (fill-region-as-paragraph c end justify)
23367 (setq end c))))
23368 t)))
23369 ;; Contents of `comment-block' type elements should be
23370 ;; filled as plain text, but only if point is within block
23371 ;; markers.
23372 (comment-block
23373 (let* ((case-fold-search t)
23374 (beg (save-excursion
23375 (goto-char (org-element-property :begin element))
23376 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23377 (forward-line)
23378 (point)))
23379 (end (save-excursion
23380 (goto-char (org-element-property :end element))
23381 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23382 (line-beginning-position))))
23383 (if (or (< (point) beg) (> (point) end)) t
23384 (fill-region-as-paragraph
23385 (save-excursion (end-of-line)
23386 (re-search-backward "^[ \t]*$" beg 'move)
23387 (line-beginning-position))
23388 (save-excursion (beginning-of-line)
23389 (re-search-forward "^[ \t]*$" end 'move)
23390 (line-beginning-position))
23391 justify))))
23392 ;; Fill comments.
23393 (comment
23394 (let ((begin (org-element-property :post-affiliated element))
23395 (end (org-element-property :end element)))
23396 (when (and (>= (point) begin) (<= (point) end))
23397 (let ((begin (save-excursion
23398 (end-of-line)
23399 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23400 (progn (forward-line) (point))
23401 begin)))
23402 (end (save-excursion
23403 (end-of-line)
23404 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23405 (1- (line-beginning-position))
23406 (skip-chars-backward " \r\t\n")
23407 (line-end-position)))))
23408 ;; Do not fill comments when at a blank line.
23409 (when (> end begin)
23410 (let ((fill-prefix
23411 (save-excursion
23412 (beginning-of-line)
23413 (looking-at "[ \t]*#")
23414 (let ((comment-prefix (match-string 0)))
23415 (goto-char (match-end 0))
23416 (if (looking-at adaptive-fill-regexp)
23417 (concat comment-prefix (match-string 0))
23418 (concat comment-prefix " "))))))
23419 (save-excursion
23420 (fill-region-as-paragraph begin end justify))))))
23422 ;; Ignore every other element.
23423 (otherwise t))))))
23425 (defun org-auto-fill-function ()
23426 "Auto-fill function."
23427 ;; Check if auto-filling is meaningful.
23428 (let ((fc (current-fill-column)))
23429 (when (and fc (> (current-column) fc))
23430 (let* ((fill-prefix (org-adaptive-fill-function))
23431 ;; Enforce empty fill prefix, if required. Otherwise, it
23432 ;; will be computed again.
23433 (adaptive-fill-mode (not (equal fill-prefix ""))))
23434 (when fill-prefix (do-auto-fill))))))
23436 (defun org-comment-line-break-function (&optional soft)
23437 "Break line at point and indent, continuing comment if within one.
23438 The inserted newline is marked hard if variable
23439 `use-hard-newlines' is true, unless optional argument SOFT is
23440 non-nil."
23441 (if soft (insert-and-inherit ?\n) (newline 1))
23442 (save-excursion (forward-char -1) (delete-horizontal-space))
23443 (delete-horizontal-space)
23444 (indent-to-left-margin)
23445 (insert-before-markers-and-inherit fill-prefix))
23448 ;;; Fixed Width Areas
23450 (defun org-toggle-fixed-width ()
23451 "Toggle fixed-width markup.
23453 Add or remove fixed-width markup on current line, whenever it
23454 makes sense. Return an error otherwise.
23456 If a region is active and if it contains only fixed-width areas
23457 or blank lines, remove all fixed-width markup in it. If the
23458 region contains anything else, convert all non-fixed-width lines
23459 to fixed-width ones.
23461 Blank lines at the end of the region are ignored unless the
23462 region only contains such lines."
23463 (interactive)
23464 (if (not (org-region-active-p))
23465 ;; No region:
23467 ;; Remove fixed width marker only in a fixed-with element.
23469 ;; Add fixed width maker in paragraphs, in blank lines after
23470 ;; elements or at the beginning of a headline or an inlinetask,
23471 ;; and before any one-line elements (e.g., a clock).
23472 (progn
23473 (beginning-of-line)
23474 (let* ((element (org-element-at-point))
23475 (type (org-element-type element)))
23476 (cond
23477 ((and (eq type 'fixed-width)
23478 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23479 (replace-match
23480 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23481 ((and (memq type '(babel-call clock comment diary-sexp headline
23482 horizontal-rule keyword paragraph
23483 planning))
23484 (<= (org-element-property :post-affiliated element) (point)))
23485 (skip-chars-forward " \t")
23486 (insert ": "))
23487 ((and (org-looking-at-p "[ \t]*$")
23488 (or (eq type 'inlinetask)
23489 (save-excursion
23490 (skip-chars-forward " \r\t\n")
23491 (<= (org-element-property :end element) (point)))))
23492 (delete-region (point) (line-end-position))
23493 (org-indent-line)
23494 (insert ": "))
23495 (t (user-error "Cannot insert a fixed-width line here")))))
23496 ;; Region active.
23497 (let* ((begin (save-excursion
23498 (goto-char (region-beginning))
23499 (line-beginning-position)))
23500 (end (copy-marker
23501 (save-excursion
23502 (goto-char (region-end))
23503 (unless (eolp) (beginning-of-line))
23504 (if (save-excursion (re-search-backward "\\S-" begin t))
23505 (progn (skip-chars-backward " \r\t\n") (point))
23506 (point)))))
23507 (all-fixed-width-p
23508 (catch 'not-all-p
23509 (save-excursion
23510 (goto-char begin)
23511 (skip-chars-forward " \r\t\n")
23512 (when (eobp) (throw 'not-all-p nil))
23513 (while (< (point) end)
23514 (let ((element (org-element-at-point)))
23515 (if (eq (org-element-type element) 'fixed-width)
23516 (goto-char (org-element-property :end element))
23517 (throw 'not-all-p nil))))
23518 t))))
23519 (if all-fixed-width-p
23520 (save-excursion
23521 (goto-char begin)
23522 (while (< (point) end)
23523 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23524 (replace-match
23525 "" nil nil nil
23526 (if (= (line-end-position) (match-end 0)) 0 1)))
23527 (forward-line)))
23528 (let ((min-ind (point-max)))
23529 ;; Find minimum indentation across all lines.
23530 (save-excursion
23531 (goto-char begin)
23532 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23533 (setq min-ind 0)
23534 (catch 'zerop
23535 (while (< (point) end)
23536 (unless (org-looking-at-p "[ \t]*$")
23537 (let ((ind (org-get-indentation)))
23538 (setq min-ind (min min-ind ind))
23539 (when (zerop ind) (throw 'zerop t))))
23540 (forward-line)))))
23541 ;; Loop over all lines and add fixed-width markup everywhere
23542 ;; but in fixed-width lines.
23543 (save-excursion
23544 (goto-char begin)
23545 (while (< (point) end)
23546 (cond
23547 ((org-at-heading-p)
23548 (insert ": ")
23549 (forward-line)
23550 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23551 (insert ":")
23552 (forward-line)))
23553 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23554 (let* ((element (org-element-at-point))
23555 (element-end (org-element-property :end element)))
23556 (if (eq (org-element-type element) 'fixed-width)
23557 (progn (goto-char element-end)
23558 (skip-chars-backward " \r\t\n")
23559 (forward-line))
23560 (let ((limit (min end element-end)))
23561 (while (< (point) limit)
23562 (org-move-to-column min-ind t)
23563 (insert ": ")
23564 (forward-line))))))
23566 (org-move-to-column min-ind t)
23567 (insert ": ")
23568 (forward-line)))))))
23569 (set-marker end nil))))
23572 ;;; Comments
23574 ;; Org comments syntax is quite complex. It requires the entire line
23575 ;; to be just a comment. Also, even with the right syntax at the
23576 ;; beginning of line, some some elements (i.e. verse-block or
23577 ;; example-block) don't accept comments. Usual Emacs comment commands
23578 ;; cannot cope with those requirements. Therefore, Org replaces them.
23580 ;; Org still relies on `comment-dwim', but cannot trust
23581 ;; `comment-only-p'. So, `comment-region-function' and
23582 ;; `uncomment-region-function' both point
23583 ;; to`org-comment-or-uncomment-region'. Eventually,
23584 ;; `org-insert-comment' takes care of insertion of comments at the
23585 ;; beginning of line.
23587 ;; `org-setup-comments-handling' install comments related variables
23588 ;; during `org-mode' initialization.
23590 (defun org-setup-comments-handling ()
23591 (interactive)
23592 (setq-local comment-use-syntax nil)
23593 (setq-local comment-start "# ")
23594 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23595 (setq-local comment-insert-comment-function 'org-insert-comment)
23596 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23597 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23599 (defun org-insert-comment ()
23600 "Insert an empty comment above current line.
23601 If the line is empty, insert comment at its beginning. When
23602 point is within a source block, comment according to the related
23603 major mode."
23604 (if (let ((element (org-element-at-point)))
23605 (and (eq (org-element-type element) 'src-block)
23606 (< (save-excursion
23607 (goto-char (org-element-property :post-affiliated element))
23608 (line-end-position))
23609 (point))
23610 (> (save-excursion
23611 (goto-char (org-element-property :end element))
23612 (skip-chars-backward " \r\t\n")
23613 (line-beginning-position))
23614 (point))))
23615 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23616 (beginning-of-line)
23617 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23618 (open-line 1))
23619 (org-indent-line)
23620 (insert "# ")))
23622 (defvar comment-empty-lines) ; From newcomment.el.
23623 (defun org-comment-or-uncomment-region (beg end &rest _)
23624 "Comment or uncomment each non-blank line in the region.
23625 Uncomment each non-blank line between BEG and END if it only
23626 contains commented lines. Otherwise, comment them. If region is
23627 strictly within a source block, use appropriate comment syntax."
23628 (if (let ((element (org-element-at-point)))
23629 (and (eq (org-element-type element) 'src-block)
23630 (< (save-excursion
23631 (goto-char (org-element-property :post-affiliated element))
23632 (line-end-position))
23633 beg)
23634 (>= (save-excursion
23635 (goto-char (org-element-property :end element))
23636 (skip-chars-backward " \r\t\n")
23637 (line-beginning-position))
23638 end)))
23639 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23640 (save-restriction
23641 ;; Restrict region
23642 (narrow-to-region (save-excursion (goto-char beg)
23643 (skip-chars-forward " \r\t\n" end)
23644 (line-beginning-position))
23645 (save-excursion (goto-char end)
23646 (skip-chars-backward " \r\t\n" beg)
23647 (line-end-position)))
23648 (let ((uncommentp
23649 ;; UNCOMMENTP is non-nil when every non blank line between
23650 ;; BEG and END is a comment.
23651 (save-excursion
23652 (goto-char (point-min))
23653 (while (and (not (eobp))
23654 (let ((element (org-element-at-point)))
23655 (and (eq (org-element-type element) 'comment)
23656 (goto-char (min (point-max)
23657 (org-element-property
23658 :end element)))))))
23659 (eobp))))
23660 (if uncommentp
23661 ;; Only blank lines and comments in region: uncomment it.
23662 (save-excursion
23663 (goto-char (point-min))
23664 (while (not (eobp))
23665 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23666 (replace-match "" nil nil nil 1))
23667 (forward-line)))
23668 ;; Comment each line in region.
23669 (let ((min-indent (point-max)))
23670 ;; First find the minimum indentation across all lines.
23671 (save-excursion
23672 (goto-char (point-min))
23673 (while (and (not (eobp)) (not (zerop min-indent)))
23674 (unless (looking-at "[ \t]*$")
23675 (setq min-indent (min min-indent (current-indentation))))
23676 (forward-line)))
23677 ;; Then loop over all lines.
23678 (save-excursion
23679 (goto-char (point-min))
23680 (while (not (eobp))
23681 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23682 ;; Don't get fooled by invisible text (e.g. link path)
23683 ;; when moving to column MIN-INDENT.
23684 (let ((buffer-invisibility-spec nil))
23685 (org-move-to-column min-indent t))
23686 (insert comment-start))
23687 (forward-line)))))))))
23689 (defun org-comment-dwim (_arg)
23690 "Call `comment-dwim' within a source edit buffer if needed."
23691 (interactive "*P")
23692 (if (org-in-src-block-p)
23693 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23694 (call-interactively 'comment-dwim)))
23697 ;;; Timestamps API
23699 ;; This section contains tools to operate on timestamp objects, as
23700 ;; returned by, e.g. `org-element-context'.
23702 (defun org-timestamp--to-internal-time (timestamp &optional end)
23703 "Encode TIMESTAMP object into Emacs internal time.
23704 Use end of date range or time range when END is non-nil."
23705 (apply #'encode-time
23706 (cons 0
23707 (mapcar
23708 (lambda (prop) (or (org-element-property prop timestamp) 0))
23709 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23710 '(:minute-start :hour-start :day-start :month-start
23711 :year-start))))))
23713 (defun org-timestamp-has-time-p (timestamp)
23714 "Non-nil when TIMESTAMP has a time specified."
23715 (org-element-property :hour-start timestamp))
23717 (defun org-timestamp-format (timestamp format &optional end utc)
23718 "Format a TIMESTAMP object into a string.
23720 FORMAT is a format specifier to be passed to
23721 `format-time-string'.
23723 When optional argument END is non-nil, use end of date-range or
23724 time-range, if possible.
23726 When optional argument UTC is non-nil, time will be expressed as
23727 Universal Time."
23728 (format-time-string
23729 format (org-timestamp--to-internal-time timestamp end)
23730 (and utc t)))
23732 (defun org-timestamp-split-range (timestamp &optional end)
23733 "Extract a TIMESTAMP object from a date or time range.
23735 END, when non-nil, means extract the end of the range.
23736 Otherwise, extract its start.
23738 Return a new timestamp object."
23739 (let ((type (org-element-property :type timestamp)))
23740 (if (memq type '(active inactive diary)) timestamp
23741 (let ((split-ts (org-element-copy timestamp)))
23742 ;; Set new type.
23743 (org-element-put-property
23744 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23745 ;; Copy start properties over end properties if END is
23746 ;; non-nil. Otherwise, copy end properties over `start' ones.
23747 (let ((p-alist '((:minute-start . :minute-end)
23748 (:hour-start . :hour-end)
23749 (:day-start . :day-end)
23750 (:month-start . :month-end)
23751 (:year-start . :year-end))))
23752 (dolist (p-cell p-alist)
23753 (org-element-put-property
23754 split-ts
23755 (funcall (if end #'car #'cdr) p-cell)
23756 (org-element-property
23757 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23758 ;; Eventually refresh `:raw-value'.
23759 (org-element-put-property split-ts :raw-value nil)
23760 (org-element-put-property
23761 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23763 (defun org-timestamp-translate (timestamp &optional boundary)
23764 "Translate TIMESTAMP object to custom format.
23766 Format string is defined in `org-time-stamp-custom-formats',
23767 which see.
23769 When optional argument BOUNDARY is non-nil, it is either the
23770 symbol `start' or `end'. In this case, only translate the
23771 starting or ending part of TIMESTAMP if it is a date or time
23772 range. Otherwise, translate both parts.
23774 Return timestamp as-is if `org-display-custom-times' is nil or if
23775 it has a `diary' type."
23776 (let ((type (org-element-property :type timestamp)))
23777 (if (or (not org-display-custom-times) (eq type 'diary))
23778 (org-element-interpret-data timestamp)
23779 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23780 org-time-stamp-custom-formats)))
23781 (if (and (not boundary) (memq type '(active-range inactive-range)))
23782 (concat (org-timestamp-format timestamp fmt)
23783 "--"
23784 (org-timestamp-format timestamp fmt t))
23785 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23789 ;;; Other stuff.
23791 (defvar reftex-docstruct-symbol)
23792 (defvar reftex-cite-format)
23793 (defvar org--rds)
23795 (defun org-reftex-citation ()
23796 "Use reftex-citation to insert a citation into the buffer.
23797 This looks for a line like
23799 #+BIBLIOGRAPHY: foo plain option:-d
23801 and derives from it that foo.bib is the bibliography file relevant
23802 for this document. It then installs the necessary environment for RefTeX
23803 to work in this buffer and calls `reftex-citation' to insert a citation
23804 into the buffer.
23806 Export of such citations to both LaTeX and HTML is handled by the contributed
23807 package ox-bibtex by Taru Karttunen."
23808 (interactive)
23809 (let ((reftex-docstruct-symbol 'org--rds)
23810 (reftex-cite-format "\\cite{%l}")
23811 org--rds bib)
23812 (save-excursion
23813 (save-restriction
23814 (widen)
23815 (let ((case-fold-search t)
23816 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23817 (if (not (save-excursion
23818 (or (re-search-forward re nil t)
23819 (re-search-backward re nil t))))
23820 (user-error "No bibliography defined in file")
23821 (setq bib (concat (match-string 1) ".bib")
23822 org--rds (list (list 'bib bib)))))))
23823 (call-interactively 'reftex-citation)))
23825 ;;;; Functions extending outline functionality
23827 (defun org-beginning-of-line (&optional arg)
23828 "Go to the beginning of the current line. If that is invisible, continue
23829 to a visible line beginning. This makes the function of C-a more intuitive.
23830 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23831 first attempt, and only move to after the tags when the cursor is already
23832 beyond the end of the headline."
23833 (interactive "P")
23834 (let ((pos (point))
23835 (special (if (consp org-special-ctrl-a/e)
23836 (car org-special-ctrl-a/e)
23837 org-special-ctrl-a/e))
23838 deactivate-mark refpos)
23839 (if (org-bound-and-true-p visual-line-mode)
23840 (beginning-of-visual-line 1)
23841 (beginning-of-line 1))
23842 (if (and arg (fboundp 'move-beginning-of-line))
23843 (call-interactively 'move-beginning-of-line)
23844 (unless (bobp)
23845 (backward-char 1)
23846 (if (org-truely-invisible-p)
23847 (while (and (not (bobp)) (org-truely-invisible-p))
23848 (backward-char 1)
23849 (beginning-of-line 1))
23850 (forward-char 1))))
23851 (when special
23852 (cond
23853 ((and (looking-at org-complex-heading-regexp)
23854 (eq (char-after (match-end 1)) ?\s))
23855 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23856 (point-at-eol)))
23857 (goto-char
23858 (if (eq special t)
23859 (cond ((> pos refpos) refpos)
23860 ((= pos (point)) refpos)
23861 (t (point)))
23862 (cond ((> pos (point)) (point))
23863 ((not (eq last-command this-command)) (point))
23864 (t refpos)))))
23865 ((org-at-item-p)
23866 ;; Being at an item and not looking at an the item means point
23867 ;; was previously moved to beginning of a visual line, which
23868 ;; doesn't contain the item. Therefore, do nothing special,
23869 ;; just stay here.
23870 (when (looking-at org-list-full-item-re)
23871 ;; Set special position at first white space character after
23872 ;; bullet, and check-box, if any.
23873 (let ((after-bullet
23874 (let ((box (match-end 3)))
23875 (if (not box) (match-end 1)
23876 (let ((after (char-after box)))
23877 (if (and after (= after ? )) (1+ box) box))))))
23878 ;; Special case: Move point to special position when
23879 ;; currently after it or at beginning of line.
23880 (if (eq special t)
23881 (when (or (> pos after-bullet) (= (point) pos))
23882 (goto-char after-bullet))
23883 ;; Reversed case: Move point to special position when
23884 ;; point was already at beginning of line and command is
23885 ;; repeated.
23886 (when (and (= (point) pos) (eq last-command this-command))
23887 (goto-char after-bullet))))))))
23888 (org-no-warnings
23889 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23890 (setq disable-point-adjustment
23891 (or (not (invisible-p (point)))
23892 (not (invisible-p (max (point-min) (1- (point))))))))
23894 (defun org-end-of-line (&optional arg)
23895 "Go to the end of the line.
23896 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23897 tags on the first attempt, and only move to after the tags when
23898 the cursor is already beyond the end of the headline."
23899 (interactive "P")
23900 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23901 org-special-ctrl-a/e))
23902 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23903 'end-of-visual-line)
23904 ((fboundp 'move-end-of-line) 'move-end-of-line)
23905 (t 'end-of-line)))
23906 deactivate-mark)
23907 (if (or (not special) arg) (call-interactively move-fun)
23908 (let* ((element (save-excursion (beginning-of-line)
23909 (org-element-at-point)))
23910 (type (org-element-type element)))
23911 (cond
23912 ((memq type '(headline inlinetask))
23913 (let ((pos (point)))
23914 (beginning-of-line 1)
23915 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23916 (if (eq special t)
23917 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23918 (goto-char (match-beginning 1))
23919 (goto-char (match-end 0)))
23920 (if (or (< pos (match-end 0))
23921 (not (eq this-command last-command)))
23922 (goto-char (match-end 0))
23923 (goto-char (match-beginning 1))))
23924 (call-interactively move-fun))))
23925 ((outline-invisible-p (line-end-position))
23926 ;; If element is hidden, `move-end-of-line' would put point
23927 ;; after it. Use `end-of-line' to stay on current line.
23928 (call-interactively 'end-of-line))
23929 (t (call-interactively move-fun)))))
23930 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23931 (setq disable-point-adjustment
23932 (or (not (invisible-p (point)))
23933 (not (invisible-p (max (point-min) (1- (point))))))))
23935 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23936 (define-key org-mode-map "\C-e" 'org-end-of-line)
23938 (defun org-backward-sentence (&optional _arg)
23939 "Go to beginning of sentence, or beginning of table field.
23940 This will call `backward-sentence' or `org-table-beginning-of-field',
23941 depending on context."
23942 (interactive)
23943 (let* ((element (org-element-at-point))
23944 (contents-begin (org-element-property :contents-begin element))
23945 (table (org-element-lineage element '(table) t)))
23946 (if (and table
23947 (> (point) contents-begin)
23948 (<= (point) (org-element-property :contents-end table)))
23949 (call-interactively #'org-table-beginning-of-field)
23950 (save-restriction
23951 (when (and contents-begin
23952 (< (point-min) contents-begin)
23953 (> (point) contents-begin))
23954 (narrow-to-region contents-begin
23955 (org-element-property :contents-end element)))
23956 (call-interactively #'backward-sentence)))))
23958 (defun org-forward-sentence (&optional _arg)
23959 "Go to end of sentence, or end of table field.
23960 This will call `forward-sentence' or `org-table-end-of-field',
23961 depending on context."
23962 (interactive)
23963 (let* ((element (org-element-at-point))
23964 (contents-end (org-element-property :contents-end element))
23965 (table (org-element-lineage element '(table) t)))
23966 (if (and table
23967 (>= (point) (org-element-property :contents-begin table))
23968 (< (point) contents-end))
23969 (call-interactively #'org-table-end-of-field)
23970 (save-restriction
23971 (when (and contents-end
23972 (> (point-max) contents-end)
23973 ;; Skip blank lines between elements.
23974 (< (org-element-property :end element)
23975 (save-excursion (goto-char contents-end)
23976 (skip-chars-forward " \r\t\n"))))
23977 (narrow-to-region (org-element-property :contents-begin element)
23978 contents-end))
23979 (call-interactively #'forward-sentence)))))
23981 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23982 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23984 (defun org-kill-line (&optional _arg)
23985 "Kill line, to tags or end of line."
23986 (interactive)
23987 (cond
23988 ((or (not org-special-ctrl-k)
23989 (bolp)
23990 (not (org-at-heading-p)))
23991 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23992 org-ctrl-k-protect-subtree
23993 (or (eq org-ctrl-k-protect-subtree 'error)
23994 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23995 (user-error "C-k aborted as it would kill a hidden subtree"))
23996 (call-interactively
23997 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
23998 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
23999 (kill-region (point) (match-beginning 1))
24000 (org-set-tags nil t))
24001 (t (kill-region (point) (point-at-eol)))))
24003 (define-key org-mode-map "\C-k" 'org-kill-line)
24005 (defun org-yank (&optional arg)
24006 "Yank. If the kill is a subtree, treat it specially.
24007 This command will look at the current kill and check if is a single
24008 subtree, or a series of subtrees[1]. If it passes the test, and if the
24009 cursor is at the beginning of a line or after the stars of a currently
24010 empty headline, then the yank is handled specially. How exactly depends
24011 on the value of the following variables, both set by default.
24013 `org-yank-folded-subtrees'
24014 When set, the subtree(s) will be folded after insertion, but only
24015 if doing so would now swallow text after the yanked text.
24017 `org-yank-adjusted-subtrees'
24018 When set, the subtree will be promoted or demoted in order to
24019 fit into the local outline tree structure, which means that the
24020 level will be adjusted so that it becomes the smaller one of the
24021 two *visible* surrounding headings.
24023 Any prefix to this command will cause `yank' to be called directly with
24024 no special treatment. In particular, a simple \\[universal-argument] prefix \
24025 will just
24026 plainly yank the text as it is.
24028 \[1] The test checks if the first non-white line is a heading
24029 and if there are no other headings with fewer stars."
24030 (interactive "P")
24031 (org-yank-generic 'yank arg))
24033 (defun org-yank-generic (command arg)
24034 "Perform some yank-like command.
24036 This function implements the behavior described in the `org-yank'
24037 documentation. However, it has been generalized to work for any
24038 interactive command with similar behavior."
24040 ;; pretend to be command COMMAND
24041 (setq this-command command)
24043 (if arg
24044 (call-interactively command)
24046 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24047 (and (org-kill-is-subtree-p)
24048 (or (bolp)
24049 (and (looking-at "[ \t]*$")
24050 (string-match
24051 "\\`\\*+\\'"
24052 (buffer-substring (point-at-bol) (point)))))))
24053 swallowp)
24054 (cond
24055 ((and subtreep org-yank-folded-subtrees)
24056 (let ((beg (point))
24057 end)
24058 (if (and subtreep org-yank-adjusted-subtrees)
24059 (org-paste-subtree nil nil 'for-yank)
24060 (call-interactively command))
24062 (setq end (point))
24063 (goto-char beg)
24064 (when (and (bolp) subtreep
24065 (not (setq swallowp
24066 (org-yank-folding-would-swallow-text beg end))))
24067 (org-with-limited-levels
24068 (or (looking-at org-outline-regexp)
24069 (re-search-forward org-outline-regexp-bol end t))
24070 (while (and (< (point) end) (looking-at org-outline-regexp))
24071 (outline-hide-subtree)
24072 (org-cycle-show-empty-lines 'folded)
24073 (condition-case nil
24074 (outline-forward-same-level 1)
24075 (error (goto-char end))))))
24076 (when swallowp
24077 (message
24078 "Inserted text not folded because that would swallow text"))
24080 (goto-char end)
24081 (skip-chars-forward " \t\n\r")
24082 (beginning-of-line 1)
24083 (push-mark beg 'nomsg)))
24084 ((and subtreep org-yank-adjusted-subtrees)
24085 (let ((beg (point-at-bol)))
24086 (org-paste-subtree nil nil 'for-yank)
24087 (push-mark beg 'nomsg)))
24089 (call-interactively command))))))
24091 (defun org-yank-folding-would-swallow-text (beg end)
24092 "Would hide-subtree at BEG swallow any text after END?"
24093 (let (level)
24094 (org-with-limited-levels
24095 (save-excursion
24096 (goto-char beg)
24097 (when (or (looking-at org-outline-regexp)
24098 (re-search-forward org-outline-regexp-bol end t))
24099 (setq level (org-outline-level)))
24100 (goto-char end)
24101 (skip-chars-forward " \t\r\n\v\f")
24102 (not (or (eobp)
24103 (and (bolp) (looking-at-p org-outline-regexp)
24104 (<= (org-outline-level) level))))))))
24106 (define-key org-mode-map "\C-y" 'org-yank)
24108 (defun org-truely-invisible-p ()
24109 "Check if point is at a character currently not visible.
24110 This version does not only check the character property, but also
24111 `visible-mode'."
24112 ;; Early versions of noutline don't have `outline-invisible-p'.
24113 (unless (org-bound-and-true-p visible-mode)
24114 (outline-invisible-p)))
24116 (defun org-invisible-p2 ()
24117 "Check if point is at a character currently not visible."
24118 (save-excursion
24119 (when (and (eolp) (not (bobp))) (backward-char 1))
24120 ;; Early versions of noutline don't have `outline-invisible-p'.
24121 (outline-invisible-p)))
24123 (defun org-back-to-heading (&optional invisible-ok)
24124 "Call `outline-back-to-heading', but provide a better error message."
24125 (condition-case nil
24126 (outline-back-to-heading invisible-ok)
24127 (error (error "Before first headline at position %d in buffer %s"
24128 (point) (current-buffer)))))
24130 (defun org-before-first-heading-p ()
24131 "Before first heading?"
24132 (save-excursion
24133 (end-of-line)
24134 (null (re-search-backward org-outline-regexp-bol nil t))))
24136 (defun org-at-heading-p (&optional ignored)
24137 (outline-on-heading-p t))
24138 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24139 ;;; warning was only added in Org 9.0, which should be taken into
24140 ;;; account when deciding when to remove the alias.
24141 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24143 (defun org-in-commented-heading-p (&optional no-inheritance)
24144 "Non-nil if point is under a commented heading.
24145 This function also checks ancestors of the current headline,
24146 unless optional argument NO-INHERITANCE is non-nil."
24147 (cond
24148 ((org-before-first-heading-p) nil)
24149 ((let ((headline (nth 4 (org-heading-components))))
24150 (and headline
24151 (let ((case-fold-search nil))
24152 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24153 headline)))))
24154 (no-inheritance nil)
24156 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24158 (defun org-at-comment-p nil
24159 "Is cursor in a commented line?"
24160 (save-excursion
24161 (save-match-data
24162 (beginning-of-line)
24163 (looking-at "^[ \t]*# "))))
24165 (defun org-at-drawer-p nil
24166 "Is cursor at a drawer keyword?"
24167 (save-excursion
24168 (move-beginning-of-line 1)
24169 (looking-at org-drawer-regexp)))
24171 (defun org-at-block-p nil
24172 "Is cursor at a block keyword?"
24173 (save-excursion
24174 (move-beginning-of-line 1)
24175 (looking-at org-block-regexp)))
24177 (defun org-point-at-end-of-empty-headline ()
24178 "If point is at the end of an empty headline, return t, else nil.
24179 If the heading only contains a TODO keyword, it is still still considered
24180 empty."
24181 (and (looking-at "[ \t]*$")
24182 (when org-todo-line-regexp
24183 (save-excursion
24184 (beginning-of-line 1)
24185 (let ((case-fold-search nil))
24186 (looking-at org-todo-line-regexp)
24187 (string= (match-string 3) ""))))))
24189 (defun org-at-heading-or-item-p ()
24190 (or (org-at-heading-p) (org-at-item-p)))
24192 (defun org-at-target-p ()
24193 (or (org-in-regexp org-radio-target-regexp)
24194 (org-in-regexp org-target-regexp)))
24195 ;; Compatibility alias with Org versions < 7.8.03
24196 (defalias 'org-on-target-p 'org-at-target-p)
24198 (defun org-up-heading-all (arg)
24199 "Move to the heading line of which the present line is a subheading.
24200 This function considers both visible and invisible heading lines.
24201 With argument, move up ARG levels."
24202 (if (fboundp 'outline-up-heading-all)
24203 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24204 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24206 (defun org-up-heading-safe ()
24207 "Move to the heading line of which the present line is a subheading.
24208 This version will not throw an error. It will return the level of the
24209 headline found, or nil if no higher level is found.
24211 Also, this function will be a lot faster than `outline-up-heading',
24212 because it relies on stars being the outline starters. This can really
24213 make a significant difference in outlines with very many siblings."
24214 (when (ignore-errors (org-back-to-heading t))
24215 (let ((level-up (1- (funcall outline-level))))
24216 (and (> level-up 0)
24217 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24218 (funcall outline-level)))))
24220 (defun org-first-sibling-p ()
24221 "Is this heading the first child of its parents?"
24222 (interactive)
24223 (let ((re org-outline-regexp-bol)
24224 level l)
24225 (unless (org-at-heading-p t)
24226 (user-error "Not at a heading"))
24227 (setq level (funcall outline-level))
24228 (save-excursion
24229 (if (not (re-search-backward re nil t))
24231 (setq l (funcall outline-level))
24232 (< l level)))))
24234 (defun org-goto-sibling (&optional previous)
24235 "Goto the next sibling, even if it is invisible.
24236 When PREVIOUS is set, go to the previous sibling instead. Returns t
24237 when a sibling was found. When none is found, return nil and don't
24238 move point."
24239 (let ((fun (if previous 're-search-backward 're-search-forward))
24240 (pos (point))
24241 (re org-outline-regexp-bol)
24242 level l)
24243 (when (ignore-errors (org-back-to-heading t))
24244 (setq level (funcall outline-level))
24245 (catch 'exit
24246 (or previous (forward-char 1))
24247 (while (funcall fun re nil t)
24248 (setq l (funcall outline-level))
24249 (when (< l level) (goto-char pos) (throw 'exit nil))
24250 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24251 (goto-char pos)
24252 nil))))
24254 (defun org-show-siblings ()
24255 "Show all siblings of the current headline."
24256 (save-excursion
24257 (while (org-goto-sibling) (org-flag-heading nil)))
24258 (save-excursion
24259 (while (org-goto-sibling 'previous)
24260 (org-flag-heading nil))))
24262 (defun org-goto-first-child ()
24263 "Goto the first child, even if it is invisible.
24264 Return t when a child was found. Otherwise don't move point and
24265 return nil."
24266 (let (level (pos (point)) (re org-outline-regexp-bol))
24267 (when (ignore-errors (org-back-to-heading t))
24268 (setq level (outline-level))
24269 (forward-char 1)
24270 (if (and (re-search-forward re nil t) (> (outline-level) level))
24271 (progn (goto-char (match-beginning 0)) t)
24272 (goto-char pos) nil))))
24274 (defun org-show-hidden-entry ()
24275 "Show an entry where even the heading is hidden."
24276 (save-excursion
24277 (org-show-entry)))
24279 (defun org-flag-heading (flag &optional entry)
24280 "Flag the current heading. FLAG non-nil means make invisible.
24281 When ENTRY is non-nil, show the entire entry."
24282 (save-excursion
24283 (org-back-to-heading t)
24284 ;; Check if we should show the entire entry
24285 (if entry
24286 (progn
24287 (org-show-entry)
24288 (save-excursion
24289 (and (outline-next-heading)
24290 (org-flag-heading nil))))
24291 (outline-flag-region (max (point-min) (1- (point)))
24292 (save-excursion (outline-end-of-heading) (point))
24293 flag))))
24295 (defun org-get-next-sibling ()
24296 "Move to next heading of the same level, and return point.
24297 If there is no such heading, return nil.
24298 This is like outline-next-sibling, but invisible headings are ok."
24299 (let ((level (funcall outline-level)))
24300 (outline-next-heading)
24301 (while (and (not (eobp)) (> (funcall outline-level) level))
24302 (outline-next-heading))
24303 (unless (or (eobp) (< (funcall outline-level) level))
24304 (point))))
24306 (defun org-get-last-sibling ()
24307 "Move to previous heading of the same level, and return point.
24308 If there is no such heading, return nil."
24309 (let ((opoint (point))
24310 (level (funcall outline-level)))
24311 (outline-previous-heading)
24312 (when (and (/= (point) opoint) (outline-on-heading-p t))
24313 (while (and (> (funcall outline-level) level)
24314 (not (bobp)))
24315 (outline-previous-heading))
24316 (unless (< (funcall outline-level) level)
24317 (point)))))
24319 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24320 "Goto to the end of a subtree."
24321 ;; This contains an exact copy of the original function, but it uses
24322 ;; `org-back-to-heading', to make it work also in invisible
24323 ;; trees. And is uses an invisible-ok argument.
24324 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24325 ;; Furthermore, when used inside Org, finding the end of a large subtree
24326 ;; with many children and grandchildren etc, this can be much faster
24327 ;; than the outline version.
24328 (org-back-to-heading invisible-ok)
24329 (let ((first t)
24330 (level (funcall outline-level)))
24331 (if (and (derived-mode-p 'org-mode) (< level 1000))
24332 ;; A true heading (not a plain list item), in Org-mode
24333 ;; This means we can easily find the end by looking
24334 ;; only for the right number of stars. Using a regexp to do
24335 ;; this is so much faster than using a Lisp loop.
24336 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24337 (forward-char 1)
24338 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24339 ;; something else, do it the slow way
24340 (while (and (not (eobp))
24341 (or first (> (funcall outline-level) level)))
24342 (setq first nil)
24343 (outline-next-heading)))
24344 (unless to-heading
24345 (when (memq (preceding-char) '(?\n ?\^M))
24346 ;; Go to end of line before heading
24347 (forward-char -1)
24348 (when (memq (preceding-char) '(?\n ?\^M))
24349 ;; leave blank line before heading
24350 (forward-char -1)))))
24351 (point))
24353 (defun org-end-of-meta-data (&optional full)
24354 "Skip planning line and properties drawer in current entry.
24355 When optional argument FULL is non-nil, also skip empty lines,
24356 clocking lines and regular drawers at the beginning of the
24357 entry."
24358 (org-back-to-heading t)
24359 (forward-line)
24360 (when (org-looking-at-p org-planning-line-re) (forward-line))
24361 (when (looking-at org-property-drawer-re)
24362 (goto-char (match-end 0))
24363 (forward-line))
24364 (when (and full (not (org-at-heading-p)))
24365 (catch 'exit
24366 (let ((end (save-excursion (outline-next-heading) (point)))
24367 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24368 (while (not (eobp))
24369 (cond ((org-looking-at-p org-drawer-regexp)
24370 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24371 (forward-line)
24372 (throw 'exit t)))
24373 ((org-looking-at-p re) (forward-line))
24374 (t (throw 'exit t))))))))
24376 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24377 "Move forward to the ARG'th subheading at same level as this one.
24378 Stop at the first and last subheadings of a superior heading.
24379 Normally this only looks at visible headings, but when INVISIBLE-OK is
24380 non-nil it will also look at invisible ones."
24381 (interactive "p")
24382 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24383 (if (and arg (< arg 0))
24384 (goto-char (point-min))
24385 (outline-next-heading))
24386 (org-at-heading-p)
24387 (let ((level (- (match-end 0) (match-beginning 0) 1))
24388 (f (if (and arg (< arg 0))
24389 're-search-backward
24390 're-search-forward))
24391 (count (if arg (abs arg) 1))
24392 (result (point)))
24393 (while (and (prog1 (> count 0)
24394 (forward-char (if (and arg (< arg 0)) -1 1)))
24395 (funcall f org-outline-regexp-bol nil 'move))
24396 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24397 (cond ((< l level) (setq count 0))
24398 ((and (= l level)
24399 (or invisible-ok
24400 (progn
24401 (goto-char (line-beginning-position))
24402 (not (outline-invisible-p)))))
24403 (setq count (1- count))
24404 (when (eq l level)
24405 (setq result (point)))))))
24406 (goto-char result))
24407 (beginning-of-line 1)))
24409 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24410 "Move backward to the ARG'th subheading at same level as this one.
24411 Stop at the first and last subheadings of a superior heading."
24412 (interactive "p")
24413 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24415 (defun org-next-visible-heading (arg)
24416 "Move to the next visible heading.
24418 This function wraps `outline-next-visible-heading' with
24419 `org-with-limited-levels' in order to skip over inline tasks and
24420 respect customization of `org-odd-levels-only'."
24421 (interactive "p")
24422 (org-with-limited-levels
24423 (outline-next-visible-heading arg)))
24425 (defun org-previous-visible-heading (arg)
24426 "Move to the previous visible heading.
24428 This function wraps `outline-previous-visible-heading' with
24429 `org-with-limited-levels' in order to skip over inline tasks and
24430 respect customization of `org-odd-levels-only'."
24431 (interactive "p")
24432 (org-with-limited-levels
24433 (outline-previous-visible-heading arg)))
24435 (defun org-next-block (arg &optional backward block-regexp)
24436 "Jump to the next block.
24438 With a prefix argument ARG, jump forward ARG many blocks.
24440 When BACKWARD is non-nil, jump to the previous block.
24442 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24443 Match data is set according to this regexp when the function
24444 returns.
24446 Return point at beginning of the opening line of found block.
24447 Throw an error if no block is found."
24448 (interactive "p")
24449 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24450 (case-fold-search t)
24451 (search-fn (if backward #'re-search-backward #'re-search-forward))
24452 (count (or arg 1))
24453 (origin (point))
24454 last-element)
24455 (if backward (beginning-of-line) (end-of-line))
24456 (while (and (> count 0) (funcall search-fn re nil t))
24457 (let ((element (save-excursion
24458 (goto-char (match-beginning 0))
24459 (save-match-data (org-element-at-point)))))
24460 (when (and (memq (org-element-type element)
24461 '(center-block comment-block dynamic-block
24462 example-block export-block quote-block
24463 special-block src-block verse-block))
24464 (<= (match-beginning 0)
24465 (org-element-property :post-affiliated element)))
24466 (setq last-element element)
24467 (cl-decf count))))
24468 (if (= count 0)
24469 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24470 (save-match-data (org-show-context)))
24471 (goto-char origin)
24472 (user-error "No %s code blocks" (if backward "previous" "further")))))
24474 (defun org-previous-block (arg &optional block-regexp)
24475 "Jump to the previous block.
24476 With a prefix argument ARG, jump backward ARG many source blocks.
24477 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24478 (interactive "p")
24479 (org-next-block arg t block-regexp))
24481 (defun org-forward-paragraph ()
24482 "Move forward to beginning of next paragraph or equivalent.
24484 The function moves point to the beginning of the next visible
24485 structural element, which can be a paragraph, a table, a list
24486 item, etc. It also provides some special moves for convenience:
24488 - On an affiliated keyword, jump to the beginning of the
24489 relative element.
24490 - On an item or a footnote definition, move to the second
24491 element inside, if any.
24492 - On a table or a property drawer, jump after it.
24493 - On a verse or source block, stop after blank lines."
24494 (interactive)
24495 (when (eobp) (user-error "Cannot move further down"))
24496 (let* ((deactivate-mark nil)
24497 (element (org-element-at-point))
24498 (type (org-element-type element))
24499 (post-affiliated (org-element-property :post-affiliated element))
24500 (contents-begin (org-element-property :contents-begin element))
24501 (contents-end (org-element-property :contents-end element))
24502 (end (let ((end (org-element-property :end element)) (parent element))
24503 (while (and (setq parent (org-element-property :parent parent))
24504 (= (org-element-property :contents-end parent) end))
24505 (setq end (org-element-property :end parent)))
24506 end)))
24507 (cond ((not element)
24508 (skip-chars-forward " \r\t\n")
24509 (or (eobp) (beginning-of-line)))
24510 ;; On affiliated keywords, move to element's beginning.
24511 ((< (point) post-affiliated)
24512 (goto-char post-affiliated))
24513 ;; At a table row, move to the end of the table. Similarly,
24514 ;; at a node property, move to the end of the property
24515 ;; drawer.
24516 ((memq type '(node-property table-row))
24517 (goto-char (org-element-property
24518 :end (org-element-property :parent element))))
24519 ((memq type '(property-drawer table)) (goto-char end))
24520 ;; Consider blank lines as separators in verse and source
24521 ;; blocks to ease editing.
24522 ((memq type '(src-block verse-block))
24523 (when (eq type 'src-block)
24524 (setq contents-end
24525 (save-excursion (goto-char end)
24526 (skip-chars-backward " \r\t\n")
24527 (line-beginning-position))))
24528 (beginning-of-line)
24529 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24530 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24531 (goto-char end)
24532 (skip-chars-forward " \r\t\n")
24533 (if (= (point) contents-end) (goto-char end)
24534 (beginning-of-line))))
24535 ;; With no contents, just skip element.
24536 ((not contents-begin) (goto-char end))
24537 ;; If contents are invisible, skip the element altogether.
24538 ((outline-invisible-p (line-end-position))
24539 (cl-case type
24540 (headline
24541 (org-with-limited-levels (outline-next-visible-heading 1)))
24542 ;; At a plain list, make sure we move to the next item
24543 ;; instead of skipping the whole list.
24544 (plain-list (forward-char)
24545 (org-forward-paragraph))
24546 (otherwise (goto-char end))))
24547 ((>= (point) contents-end) (goto-char end))
24548 ((>= (point) contents-begin)
24549 ;; This can only happen on paragraphs and plain lists.
24550 (cl-case type
24551 (paragraph (goto-char end))
24552 ;; At a plain list, try to move to second element in
24553 ;; first item, if possible.
24554 (plain-list (end-of-line)
24555 (org-forward-paragraph))))
24556 ;; When contents start on the middle of a line (e.g. in
24557 ;; items and footnote definitions), try to reach first
24558 ;; element starting after current line.
24559 ((> (line-end-position) contents-begin)
24560 (end-of-line)
24561 (org-forward-paragraph))
24562 (t (goto-char contents-begin)))))
24564 (defun org-backward-paragraph ()
24565 "Move backward to start of previous paragraph or equivalent.
24567 The function moves point to the beginning of the current
24568 structural element, which can be a paragraph, a table, a list
24569 item, etc., or to the beginning of the previous visible one if
24570 point is already there. It also provides some special moves for
24571 convenience:
24573 - On an affiliated keyword, jump to the first one.
24574 - On a table or a property drawer, move to its beginning.
24575 - On a verse or source block, stop before blank lines."
24576 (interactive)
24577 (when (bobp) (user-error "Cannot move further up"))
24578 (let* ((deactivate-mark nil)
24579 (element (org-element-at-point))
24580 (type (org-element-type element))
24581 (contents-begin (org-element-property :contents-begin element))
24582 (contents-end (org-element-property :contents-end element))
24583 (post-affiliated (org-element-property :post-affiliated element))
24584 (begin (org-element-property :begin element)))
24585 (cond
24586 ((not element) (goto-char (point-min)))
24587 ((= (point) begin)
24588 (backward-char)
24589 (org-backward-paragraph))
24590 ((<= (point) post-affiliated) (goto-char begin))
24591 ((memq type '(node-property table-row))
24592 (goto-char (org-element-property
24593 :post-affiliated (org-element-property :parent element))))
24594 ((memq type '(property-drawer table)) (goto-char begin))
24595 ((memq type '(src-block verse-block))
24596 (when (eq type 'src-block)
24597 (setq contents-begin
24598 (save-excursion (goto-char begin) (forward-line) (point))))
24599 (if (= (point) contents-begin) (goto-char post-affiliated)
24600 ;; Inside a verse block, see blank lines as paragraph
24601 ;; separators.
24602 (let ((origin (point)))
24603 (skip-chars-backward " \r\t\n" contents-begin)
24604 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24605 (skip-chars-forward " \r\t\n" origin)
24606 (if (= (point) origin) (goto-char contents-begin)
24607 (beginning-of-line))))))
24608 ((not contents-begin) (goto-char (or post-affiliated begin)))
24609 ((eq type 'paragraph)
24610 (goto-char contents-begin)
24611 ;; When at first paragraph in an item or a footnote definition,
24612 ;; move directly to beginning of line.
24613 (let ((parent-contents
24614 (org-element-property
24615 :contents-begin (org-element-property :parent element))))
24616 (when (and parent-contents (= parent-contents contents-begin))
24617 (beginning-of-line))))
24618 ;; At the end of a greater element, move to the beginning of the
24619 ;; last element within.
24620 ((>= (point) contents-end)
24621 (goto-char (1- contents-end))
24622 (org-backward-paragraph))
24623 (t (goto-char (or post-affiliated begin))))
24624 ;; Ensure we never leave point invisible.
24625 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24627 (defun org-forward-element ()
24628 "Move forward by one element.
24629 Move to the next element at the same level, when possible."
24630 (interactive)
24631 (cond ((eobp) (user-error "Cannot move further down"))
24632 ((org-with-limited-levels (org-at-heading-p))
24633 (let ((origin (point)))
24634 (goto-char (org-end-of-subtree nil t))
24635 (unless (org-with-limited-levels (org-at-heading-p))
24636 (goto-char origin)
24637 (user-error "Cannot move further down"))))
24639 (let* ((elem (org-element-at-point))
24640 (end (org-element-property :end elem))
24641 (parent (org-element-property :parent elem)))
24642 (cond ((and parent (= (org-element-property :contents-end parent) end))
24643 (goto-char (org-element-property :end parent)))
24644 ((integer-or-marker-p end) (goto-char end))
24645 (t (message "No element at point")))))))
24647 (defun org-backward-element ()
24648 "Move backward by one element.
24649 Move to the previous element at the same level, when possible."
24650 (interactive)
24651 (cond ((bobp) (user-error "Cannot move further up"))
24652 ((org-with-limited-levels (org-at-heading-p))
24653 ;; At a headline, move to the previous one, if any, or stay
24654 ;; here.
24655 (let ((origin (point)))
24656 (org-with-limited-levels (org-backward-heading-same-level 1))
24657 ;; When current headline has no sibling above, move to its
24658 ;; parent.
24659 (when (= (point) origin)
24660 (or (org-with-limited-levels (org-up-heading-safe))
24661 (progn (goto-char origin)
24662 (user-error "Cannot move further up"))))))
24664 (let* ((elem (org-element-at-point))
24665 (beg (org-element-property :begin elem)))
24666 (cond
24667 ;; Move to beginning of current element if point isn't
24668 ;; there already.
24669 ((null beg) (message "No element at point"))
24670 ((/= (point) beg) (goto-char beg))
24671 (t (goto-char beg)
24672 (skip-chars-backward " \r\t\n")
24673 (unless (bobp)
24674 (let ((prev (org-element-at-point)))
24675 (goto-char (org-element-property :begin prev))
24676 (while (and (setq prev (org-element-property :parent prev))
24677 (<= (org-element-property :end prev) beg))
24678 (goto-char (org-element-property :begin prev)))))))))))
24680 (defun org-up-element ()
24681 "Move to upper element."
24682 (interactive)
24683 (if (org-with-limited-levels (org-at-heading-p))
24684 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24685 (let* ((elem (org-element-at-point))
24686 (parent (org-element-property :parent elem)))
24687 (if parent (goto-char (org-element-property :begin parent))
24688 (if (org-with-limited-levels (org-before-first-heading-p))
24689 (user-error "No surrounding element")
24690 (org-with-limited-levels (org-back-to-heading)))))))
24692 (defvar org-element-greater-elements)
24693 (defun org-down-element ()
24694 "Move to inner element."
24695 (interactive)
24696 (let ((element (org-element-at-point)))
24697 (cond
24698 ((memq (org-element-type element) '(plain-list table))
24699 (goto-char (org-element-property :contents-begin element))
24700 (forward-char))
24701 ((memq (org-element-type element) org-element-greater-elements)
24702 ;; If contents are hidden, first disclose them.
24703 (when (outline-invisible-p (line-end-position)) (org-cycle))
24704 (goto-char (or (org-element-property :contents-begin element)
24705 (user-error "No content for this element"))))
24706 (t (user-error "No inner element")))))
24708 (defun org-drag-element-backward ()
24709 "Move backward element at point."
24710 (interactive)
24711 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24712 (let* ((elem (org-element-at-point))
24713 (prev-elem
24714 (save-excursion
24715 (goto-char (org-element-property :begin elem))
24716 (skip-chars-backward " \r\t\n")
24717 (unless (bobp)
24718 (let* ((beg (org-element-property :begin elem))
24719 (prev (org-element-at-point))
24720 (up prev))
24721 (while (and (setq up (org-element-property :parent up))
24722 (<= (org-element-property :end up) beg))
24723 (setq prev up))
24724 prev)))))
24725 ;; Error out if no previous element or previous element is
24726 ;; a parent of the current one.
24727 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24728 (user-error "Cannot drag element backward")
24729 (let ((pos (point)))
24730 (org-element-swap-A-B prev-elem elem)
24731 (goto-char (+ (org-element-property :begin prev-elem)
24732 (- pos (org-element-property :begin elem)))))))))
24734 (defun org-drag-element-forward ()
24735 "Move forward element at point."
24736 (interactive)
24737 (let* ((pos (point))
24738 (elem (org-element-at-point)))
24739 (when (= (point-max) (org-element-property :end elem))
24740 (user-error "Cannot drag element forward"))
24741 (goto-char (org-element-property :end elem))
24742 (let ((next-elem (org-element-at-point)))
24743 (when (or (org-element-nested-p elem next-elem)
24744 (and (eq (org-element-type next-elem) 'headline)
24745 (not (eq (org-element-type elem) 'headline))))
24746 (goto-char pos)
24747 (user-error "Cannot drag element forward"))
24748 ;; Compute new position of point: it's shifted by NEXT-ELEM
24749 ;; body's length (without final blanks) and by the length of
24750 ;; blanks between ELEM and NEXT-ELEM.
24751 (let ((size-next (- (save-excursion
24752 (goto-char (org-element-property :end next-elem))
24753 (skip-chars-backward " \r\t\n")
24754 (forward-line)
24755 ;; Small correction if buffer doesn't end
24756 ;; with a newline character.
24757 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24758 (org-element-property :begin next-elem)))
24759 (size-blank (- (org-element-property :end elem)
24760 (save-excursion
24761 (goto-char (org-element-property :end elem))
24762 (skip-chars-backward " \r\t\n")
24763 (forward-line)
24764 (point)))))
24765 (org-element-swap-A-B elem next-elem)
24766 (goto-char (+ pos size-next size-blank))))))
24768 (defun org-drag-line-forward (arg)
24769 "Drag the line at point ARG lines forward."
24770 (interactive "p")
24771 (dotimes (_ (abs arg))
24772 (let ((c (current-column)))
24773 (if (< 0 arg)
24774 (progn
24775 (beginning-of-line 2)
24776 (transpose-lines 1)
24777 (beginning-of-line 0))
24778 (transpose-lines 1)
24779 (beginning-of-line -1))
24780 (org-move-to-column c))))
24782 (defun org-drag-line-backward (arg)
24783 "Drag the line at point ARG lines backward."
24784 (interactive "p")
24785 (org-drag-line-forward (- arg)))
24787 (defun org-mark-element ()
24788 "Put point at beginning of this element, mark at end.
24790 Interactively, if this command is repeated or (in Transient Mark
24791 mode) if the mark is active, it marks the next element after the
24792 ones already marked."
24793 (interactive)
24794 (let (deactivate-mark)
24795 (if (and (org-called-interactively-p 'any)
24796 (or (and (eq last-command this-command) (mark t))
24797 (and transient-mark-mode mark-active)))
24798 (set-mark
24799 (save-excursion
24800 (goto-char (mark))
24801 (goto-char (org-element-property :end (org-element-at-point)))))
24802 (let ((element (org-element-at-point)))
24803 (end-of-line)
24804 (push-mark (org-element-property :end element) t t)
24805 (goto-char (org-element-property :begin element))))))
24807 (defun org-narrow-to-element ()
24808 "Narrow buffer to current element."
24809 (interactive)
24810 (let ((elem (org-element-at-point)))
24811 (cond
24812 ((eq (car elem) 'headline)
24813 (narrow-to-region
24814 (org-element-property :begin elem)
24815 (org-element-property :end elem)))
24816 ((memq (car elem) org-element-greater-elements)
24817 (narrow-to-region
24818 (org-element-property :contents-begin elem)
24819 (org-element-property :contents-end elem)))
24821 (narrow-to-region
24822 (org-element-property :begin elem)
24823 (org-element-property :end elem))))))
24825 (defun org-transpose-element ()
24826 "Transpose current and previous elements, keeping blank lines between.
24827 Point is moved after both elements."
24828 (interactive)
24829 (org-skip-whitespace)
24830 (let ((end (org-element-property :end (org-element-at-point))))
24831 (org-drag-element-backward)
24832 (goto-char end)))
24834 (defun org-unindent-buffer ()
24835 "Un-indent the visible part of the buffer.
24836 Relative indentation (between items, inside blocks, etc.) isn't
24837 modified."
24838 (interactive)
24839 (unless (eq major-mode 'org-mode)
24840 (user-error "Cannot un-indent a buffer not in Org mode"))
24841 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24842 (unindent-tree
24843 (lambda (contents)
24844 (dolist (element (reverse contents))
24845 (if (memq (org-element-type element) '(headline section))
24846 (funcall unindent-tree (org-element-contents element))
24847 (save-excursion
24848 (save-restriction
24849 (narrow-to-region
24850 (org-element-property :begin element)
24851 (org-element-property :end element))
24852 (org-do-remove-indentation))))))))
24853 (funcall unindent-tree (org-element-contents parse-tree))))
24855 (defun org-show-children (&optional level)
24856 "Show all direct subheadings of this heading.
24857 Prefix arg LEVEL is how many levels below the current level
24858 should be shown. Default is enough to cause the following
24859 heading to appear."
24860 (interactive "p")
24861 ;; If `orgstruct-mode' is active, use the slower version.
24862 (if orgstruct-mode (call-interactively #'outline-show-children)
24863 (save-excursion
24864 (org-back-to-heading t)
24865 (let* ((current-level (funcall outline-level))
24866 (max-level (org-get-valid-level
24867 current-level
24868 (if level (prefix-numeric-value level) 1)))
24869 (end (save-excursion (org-end-of-subtree t t)))
24870 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24871 (past-first-child nil)
24872 ;; Make sure to skip inlinetasks.
24873 (re (format regexp-fmt
24874 current-level
24875 (cond
24876 ((not (featurep 'org-inlinetask)) "")
24877 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24879 (t (1- org-inlinetask-min-level))))))
24880 ;; Display parent heading.
24881 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24882 (forward-line)
24883 ;; Display children. First child may be deeper than expected
24884 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24885 ;; MAX-LEVEL accordingly.
24886 (while (re-search-forward re end t)
24887 (unless past-first-child
24888 (setq re (format regexp-fmt
24889 current-level
24890 (max (funcall outline-level) max-level)))
24891 (setq past-first-child t))
24892 (outline-flag-region
24893 (line-end-position 0) (line-end-position) nil))))))
24895 (defun org-show-subtree ()
24896 "Show everything after this heading at deeper levels."
24897 (interactive)
24898 (outline-flag-region
24899 (point)
24900 (save-excursion
24901 (org-end-of-subtree t t))
24902 nil))
24904 (defun org-show-entry ()
24905 "Show the body directly following this heading.
24906 Show the heading too, if it is currently invisible."
24907 (interactive)
24908 (save-excursion
24909 (ignore-errors
24910 (org-back-to-heading t)
24911 (outline-flag-region
24912 (max (point-min) (1- (point)))
24913 (save-excursion
24914 (if (re-search-forward
24915 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24916 (match-beginning 1)
24917 (point-max)))
24918 nil)
24919 (org-cycle-hide-drawers 'children))))
24921 (defun org-make-options-regexp (kwds &optional extra)
24922 "Make a regular expression for keyword lines.
24923 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24924 when non-nil, is a regexp matching keywords names."
24925 (concat "^[ \t]*#\\+\\("
24926 (regexp-opt kwds)
24927 (and extra (concat (and kwds "\\|") extra))
24928 "\\):[ \t]*\\(.*\\)"))
24930 ;;;; Integration with and fixes for other packages
24932 ;;; Imenu support
24934 (defvar-local org-imenu-markers nil
24935 "All markers currently used by Imenu.")
24937 (defun org-imenu-new-marker (&optional pos)
24938 "Return a new marker for use by Imenu, and remember the marker."
24939 (let ((m (make-marker)))
24940 (move-marker m (or pos (point)))
24941 (push m org-imenu-markers)
24944 (defun org-imenu-get-tree ()
24945 "Produce the index for Imenu."
24946 (dolist (x org-imenu-markers) (move-marker x nil))
24947 (setq org-imenu-markers nil)
24948 (let* ((n org-imenu-depth)
24949 (re (concat "^" (org-get-limited-outline-regexp)))
24950 (subs (make-vector (1+ n) nil))
24951 (last-level 0)
24952 m level head0 head)
24953 (save-excursion
24954 (save-restriction
24955 (widen)
24956 (goto-char (point-max))
24957 (while (re-search-backward re nil t)
24958 (setq level (org-reduced-level (funcall outline-level)))
24959 (when (and (<= level n)
24960 (looking-at org-complex-heading-regexp)
24961 (setq head0 (org-match-string-no-properties 4)))
24962 (setq head (org-link-display-format head0)
24963 m (org-imenu-new-marker))
24964 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24965 (if (>= level last-level)
24966 (push (cons head m) (aref subs level))
24967 (push (cons head (aref subs (1+ level))) (aref subs level))
24968 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24969 (setq last-level level)))))
24970 (aref subs 1)))
24972 (eval-after-load "imenu"
24973 '(progn
24974 (add-hook 'imenu-after-jump-hook
24975 (lambda ()
24976 (when (derived-mode-p 'org-mode)
24977 (org-show-context 'org-goto))))))
24979 (defun org-link-display-format (s)
24980 "Replace links in string S with their description.
24981 If there is no description, use the link target."
24982 (save-match-data
24983 (replace-regexp-in-string
24984 org-bracket-link-analytic-regexp
24985 (lambda (m)
24986 (if (match-end 5) (match-string 5 m)
24987 (concat (match-string 1 m) (match-string 3 m))))
24988 s nil t)))
24990 (defun org-toggle-link-display ()
24991 "Toggle the literal or descriptive display of links."
24992 (interactive)
24993 (if org-descriptive-links
24994 (progn (org-remove-from-invisibility-spec '(org-link))
24995 (org-restart-font-lock)
24996 (setq org-descriptive-links nil))
24997 (progn (add-to-invisibility-spec '(org-link))
24998 (org-restart-font-lock)
24999 (setq org-descriptive-links t))))
25001 ;; Speedbar support
25003 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25004 "Overlay marking the agenda restriction line in speedbar.")
25005 (overlay-put org-speedbar-restriction-lock-overlay
25006 'face 'org-agenda-restriction-lock)
25007 (overlay-put org-speedbar-restriction-lock-overlay
25008 'help-echo "Agendas are currently limited to this item.")
25009 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25011 (defun org-speedbar-set-agenda-restriction ()
25012 "Restrict future agenda commands to the location at point in speedbar.
25013 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25014 (interactive)
25015 (require 'org-agenda)
25016 (let (p m tp np dir txt)
25017 (cond
25018 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25019 'org-imenu t))
25020 (setq m (get-text-property p 'org-imenu-marker))
25021 (with-current-buffer (marker-buffer m)
25022 (goto-char m)
25023 (org-agenda-set-restriction-lock 'subtree)))
25024 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25025 'speedbar-function 'speedbar-find-file))
25026 (setq tp (previous-single-property-change
25027 (1+ p) 'speedbar-function)
25028 np (next-single-property-change
25029 tp 'speedbar-function)
25030 dir (speedbar-line-directory)
25031 txt (buffer-substring-no-properties (or tp (point-min))
25032 (or np (point-max))))
25033 (with-current-buffer (find-file-noselect
25034 (let ((default-directory dir))
25035 (expand-file-name txt)))
25036 (unless (derived-mode-p 'org-mode)
25037 (user-error "Cannot restrict to non-Org-mode file"))
25038 (org-agenda-set-restriction-lock 'file)))
25039 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25040 (move-overlay org-speedbar-restriction-lock-overlay
25041 (point-at-bol) (point-at-eol))
25042 (setq current-prefix-arg nil)
25043 (org-agenda-maybe-redo)))
25045 (defvar speedbar-file-key-map)
25046 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25047 (eval-after-load "speedbar"
25048 '(progn
25049 (speedbar-add-supported-extension ".org")
25050 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25051 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25052 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25053 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25054 (add-hook 'speedbar-visiting-tag-hook
25055 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25057 ;;; Fixes and Hacks for problems with other packages
25059 (defun org--flyspell-object-check-p (element)
25060 "Non-nil when Flyspell can check object at point.
25061 ELEMENT is the element at point."
25062 (let ((object (save-excursion
25063 (when (org-looking-at-p "\\>") (backward-char))
25064 (org-element-context element))))
25065 (cl-case (org-element-type object)
25066 ;; Prevent checks in links due to keybinding conflict with
25067 ;; Flyspell.
25068 ((code entity export-snippet inline-babel-call
25069 inline-src-block line-break latex-fragment link macro
25070 statistics-cookie target timestamp verbatim)
25071 nil)
25072 (footnote-reference
25073 ;; Only in inline footnotes, within the definition.
25074 (and (eq (org-element-property :type object) 'inline)
25075 (< (save-excursion
25076 (goto-char (org-element-property :begin object))
25077 (search-forward ":" nil t 2))
25078 (point))))
25079 (otherwise t))))
25081 (defun org-mode-flyspell-verify ()
25082 "Function used for `flyspell-generic-check-word-predicate'."
25083 (if (org-at-heading-p)
25084 ;; At a headline or an inlinetask, check title only. This is
25085 ;; faster than relying on `org-element-at-point'.
25086 (and (save-excursion (beginning-of-line)
25087 (and (let ((case-fold-search t))
25088 (not (looking-at "\\*+ END[ \t]*$")))
25089 (looking-at org-complex-heading-regexp)))
25090 (match-beginning 4)
25091 (>= (point) (match-beginning 4))
25092 (or (not (match-beginning 5))
25093 (< (point) (match-beginning 5))))
25094 (let* ((element (org-element-at-point))
25095 (post-affiliated (org-element-property :post-affiliated element)))
25096 (cond
25097 ;; Ignore checks in all affiliated keywords but captions.
25098 ((< (point) post-affiliated)
25099 (and (save-excursion
25100 (beginning-of-line)
25101 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25102 (> (point) (match-end 0))
25103 (org--flyspell-object-check-p element)))
25104 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25105 ((let ((log (org-log-into-drawer)))
25106 (and log
25107 (let ((drawer (org-element-lineage element '(drawer))))
25108 (and drawer
25109 (eq (compare-strings
25110 log nil nil
25111 (org-element-property :drawer-name drawer) nil nil t)
25112 t)))))
25113 nil)
25115 (cl-case (org-element-type element)
25116 ((comment quote-section) t)
25117 (comment-block
25118 ;; Allow checks between block markers, not on them.
25119 (and (> (line-beginning-position) post-affiliated)
25120 (save-excursion
25121 (end-of-line)
25122 (skip-chars-forward " \r\t\n")
25123 (< (point) (org-element-property :end element)))))
25124 ;; Arbitrary list of keywords where checks are meaningful.
25125 ;; Make sure point is on the value part of the element.
25126 (keyword
25127 (and (member (org-element-property :key element)
25128 '("DESCRIPTION" "TITLE"))
25129 (save-excursion
25130 (search-backward ":" (line-beginning-position) t))))
25131 ;; Check is globally allowed in paragraphs verse blocks and
25132 ;; table rows (after affiliated keywords) but some objects
25133 ;; must not be affected.
25134 ((paragraph table-row verse-block)
25135 (let ((cbeg (org-element-property :contents-begin element))
25136 (cend (org-element-property :contents-end element)))
25137 (and cbeg (>= (point) cbeg) (< (point) cend)
25138 (org--flyspell-object-check-p element))))))))))
25139 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25141 (defun org-remove-flyspell-overlays-in (beg end)
25142 "Remove flyspell overlays in region."
25143 (and (org-bound-and-true-p flyspell-mode)
25144 (fboundp 'flyspell-delete-region-overlays)
25145 (flyspell-delete-region-overlays beg end)))
25147 (defvar flyspell-delayed-commands)
25148 (eval-after-load "flyspell"
25149 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25151 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25152 (eval-after-load "bookmark"
25153 '(if (boundp 'bookmark-after-jump-hook)
25154 ;; We can use the hook
25155 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25156 ;; Hook not available, use advice
25157 (defadvice bookmark-jump (after org-make-visible activate)
25158 "Make the position visible."
25159 (org-bookmark-jump-unhide))))
25161 ;; Make sure saveplace shows the location if it was hidden
25162 (eval-after-load "saveplace"
25163 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25164 "Make the position visible."
25165 (org-bookmark-jump-unhide)))
25167 ;; Make sure ecb shows the location if it was hidden
25168 (eval-after-load "ecb"
25169 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25170 "Make hierarchy visible when jumping into location from ECB tree buffer."
25171 (when (derived-mode-p 'org-mode)
25172 (org-show-context))))
25174 (defun org-bookmark-jump-unhide ()
25175 "Unhide the current position, to show the bookmark location."
25176 (and (derived-mode-p 'org-mode)
25177 (or (outline-invisible-p)
25178 (save-excursion (goto-char (max (point-min) (1- (point))))
25179 (outline-invisible-p)))
25180 (org-show-context 'bookmark-jump)))
25182 (defun org-mark-jump-unhide ()
25183 "Make the point visible with `org-show-context' after jumping to the mark."
25184 (when (and (derived-mode-p 'org-mode)
25185 (outline-invisible-p))
25186 (org-show-context 'mark-goto)))
25188 (eval-after-load "simple"
25189 '(defadvice pop-to-mark-command (after org-make-visible activate)
25190 "Make the point visible with `org-show-context'."
25191 (org-mark-jump-unhide)))
25193 (eval-after-load "simple"
25194 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25195 "Make the point visible with `org-show-context'."
25196 (org-mark-jump-unhide)))
25198 (eval-after-load "simple"
25199 '(defadvice pop-global-mark (after org-make-visible activate)
25200 "Make the point visible with `org-show-context'."
25201 (org-mark-jump-unhide)))
25203 ;; Make session.el ignore our circular variable
25204 (defvar session-globals-exclude)
25205 (eval-after-load "session"
25206 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25208 ;;;; Finish up
25210 (provide 'org)
25212 (run-hooks 'org-load-hook)
25214 ;;; org.el ends here