Merge branch 'maint'
[org-mode.git] / lisp / org.el
blobfeb71966159002c069a1cb43266787db78785304
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 '((agenda . local)
1155 (bookmark-jump . lineage)
1156 (isearch . lineage)
1157 (default . ancestors))
1158 "Alist between context and visibility span when revealing a location.
1160 \\<org-mode-map>Some actions may move point into invisible
1161 locations. As a consequence, Org always expose a neighborhood
1162 around point. How much is shown depends on the initial action,
1163 or context. Valid contexts are
1165 agenda when exposing an entry from the agenda
1166 org-goto when using the command `org-goto' (\\[org-goto])
1167 occur-tree when using the command `org-occur' (\\[org-sparse-tree] /)
1168 tags-tree when constructing a sparse tree based on tags matches
1169 link-search when exposing search matches associated with a link
1170 mark-goto when exposing the jump goal of a mark
1171 bookmark-jump when exposing a bookmark location
1172 isearch when exiting from an incremental search
1173 default default for all contexts not set explicitly
1175 Allowed visibility spans are
1177 minimal show current headline; if point is not on headline,
1178 also show entry
1180 local show current headline, entry and next headline
1182 ancestors show current headline and its direct ancestors; if
1183 point is not on headline, also show entry
1185 lineage show current headline, its direct ancestors and all
1186 their children; if point is not on headline, also show
1187 entry and first child
1189 tree show current headline, its direct ancestors and all
1190 their children; if point is not on headline, also show
1191 entry and all children
1193 canonical show current headline, its direct ancestors along with
1194 their entries and children; if point is not located on
1195 the headline, also show current entry and all children
1197 As special cases, a nil or t value means show all contexts in
1198 `minimal' or `canonical' view, respectively.
1200 Some views can make displayed information very compact, but also
1201 make it harder to edit the location of the match. In such
1202 a case, use the command `org-reveal' (\\[org-reveal]) to show
1203 more context."
1204 :group 'org-reveal-location
1205 :version "25.1"
1206 :package-version '(Org . "8.3")
1207 :type '(choice
1208 (const :tag "Canonical" t)
1209 (const :tag "Minimal" nil)
1210 (repeat :greedy t :tag "Individual contexts"
1211 (cons
1212 (choice :tag "Context"
1213 (const agenda)
1214 (const org-goto)
1215 (const occur-tree)
1216 (const tags-tree)
1217 (const link-search)
1218 (const mark-goto)
1219 (const bookmark-jump)
1220 (const isearch)
1221 (const default))
1222 (choice :tag "Detail level"
1223 (const minimal)
1224 (const local)
1225 (const ancestors)
1226 (const lineage)
1227 (const tree)
1228 (const canonical))))))
1230 (defcustom org-indirect-buffer-display 'other-window
1231 "How should indirect tree buffers be displayed?
1232 This applies to indirect buffers created with the commands
1233 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
1234 Valid values are:
1235 current-window Display in the current window
1236 other-window Just display in another window.
1237 dedicated-frame Create one new frame, and re-use it each time.
1238 new-frame Make a new frame each time. Note that in this case
1239 previously-made indirect buffers are kept, and you need to
1240 kill these buffers yourself."
1241 :group 'org-structure
1242 :group 'org-agenda-windows
1243 :type '(choice
1244 (const :tag "In current window" current-window)
1245 (const :tag "In current frame, other window" other-window)
1246 (const :tag "Each time a new frame" new-frame)
1247 (const :tag "One dedicated frame" dedicated-frame)))
1249 (defcustom org-use-speed-commands nil
1250 "Non-nil means activate single letter commands at beginning of a headline.
1251 This may also be a function to test for appropriate locations where speed
1252 commands should be active.
1254 For example, to activate speed commands when the point is on any
1255 star at the beginning of the headline, you can do this:
1257 (setq org-use-speed-commands
1258 (lambda () (and (looking-at org-outline-regexp) (looking-back \"^\\**\"))))"
1259 :group 'org-structure
1260 :type '(choice
1261 (const :tag "Never" nil)
1262 (const :tag "At beginning of headline stars" t)
1263 (function)))
1265 (defcustom org-speed-commands-user nil
1266 "Alist of additional speed commands.
1267 This list will be checked before `org-speed-commands-default'
1268 when the variable `org-use-speed-commands' is non-nil
1269 and when the cursor is at the beginning of a headline.
1270 The car if each entry is a string with a single letter, which must
1271 be assigned to `self-insert-command' in the global map.
1272 The cdr is either a command to be called interactively, a function
1273 to be called, or a form to be evaluated.
1274 An entry that is just a list with a single string will be interpreted
1275 as a descriptive headline that will be added when listing the speed
1276 commands in the Help buffer using the `?' speed command."
1277 :group 'org-structure
1278 :type '(repeat :value ("k" . ignore)
1279 (choice :value ("k" . ignore)
1280 (list :tag "Descriptive Headline" (string :tag "Headline"))
1281 (cons :tag "Letter and Command"
1282 (string :tag "Command letter")
1283 (choice
1284 (function)
1285 (sexp))))))
1287 (defcustom org-bookmark-names-plist
1288 '(:last-capture "org-capture-last-stored"
1289 :last-refile "org-refile-last-stored"
1290 :last-capture-marker "org-capture-last-stored-marker")
1291 "Names for bookmarks automatically set by some Org commands.
1292 This can provide strings as names for a number of bookmarks Org sets
1293 automatically. The following keys are currently implemented:
1294 :last-capture
1295 :last-capture-marker
1296 :last-refile
1297 When a key does not show up in the property list, the corresponding bookmark
1298 is not set."
1299 :group 'org-structure
1300 :type 'plist)
1302 (defgroup org-cycle nil
1303 "Options concerning visibility cycling in Org-mode."
1304 :tag "Org Cycle"
1305 :group 'org-structure)
1307 (defcustom org-cycle-skip-children-state-if-no-children t
1308 "Non-nil means skip CHILDREN state in entries that don't have any."
1309 :group 'org-cycle
1310 :type 'boolean)
1312 (defcustom org-cycle-max-level nil
1313 "Maximum level which should still be subject to visibility cycling.
1314 Levels higher than this will, for cycling, be treated as text, not a headline.
1315 When `org-odd-levels-only' is set, a value of N in this variable actually
1316 means 2N-1 stars as the limiting headline.
1317 When nil, cycle all levels.
1318 Note that the limiting level of cycling is also influenced by
1319 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
1320 `org-inlinetask-min-level' is, cycling will be limited to levels one less
1321 than its value."
1322 :group 'org-cycle
1323 :type '(choice
1324 (const :tag "No limit" nil)
1325 (integer :tag "Maximum level")))
1327 (defcustom org-hide-block-startup nil
1328 "Non-nil means entering Org-mode will fold all blocks.
1329 This can also be set in on a per-file basis with
1331 #+STARTUP: hideblocks
1332 #+STARTUP: showblocks"
1333 :group 'org-startup
1334 :group 'org-cycle
1335 :type 'boolean)
1337 (defcustom org-cycle-global-at-bob nil
1338 "Cycle globally if cursor is at beginning of buffer and not at a headline.
1339 This makes it possible to do global cycling without having to use S-TAB or
1340 \\[universal-argument] TAB. For this special case to work, the first line
1341 of the buffer must not be a headline -- it may be empty or some other text.
1342 When used in this way, `org-cycle-hook' is disabled temporarily to make
1343 sure the cursor stays at the beginning of the buffer. When this option is
1344 nil, don't do anything special at the beginning of the buffer."
1345 :group 'org-cycle
1346 :type 'boolean)
1348 (defcustom org-cycle-level-after-item/entry-creation t
1349 "Non-nil means cycle entry level or item indentation in new empty entries.
1351 When the cursor is at the end of an empty headline, i.e., with only stars
1352 and maybe a TODO keyword, TAB will then switch the entry to become a child,
1353 and then all possible ancestor states, before returning to the original state.
1354 This makes data entry extremely fast: M-RET to create a new headline,
1355 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
1357 When the cursor is at the end of an empty plain list item, one TAB will
1358 make it a subitem, two or more tabs will back up to make this an item
1359 higher up in the item hierarchy."
1360 :group 'org-cycle
1361 :type 'boolean)
1363 (defcustom org-cycle-emulate-tab t
1364 "Where should `org-cycle' emulate TAB.
1365 nil Never
1366 white Only in completely white lines
1367 whitestart Only at the beginning of lines, before the first non-white char
1368 t Everywhere except in headlines
1369 exc-hl-bol Everywhere except at the start of a headline
1370 If TAB is used in a place where it does not emulate TAB, the current subtree
1371 visibility is cycled."
1372 :group 'org-cycle
1373 :type '(choice (const :tag "Never" nil)
1374 (const :tag "Only in completely white lines" white)
1375 (const :tag "Before first char in a line" whitestart)
1376 (const :tag "Everywhere except in headlines" t)
1377 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)))
1379 (defcustom org-cycle-separator-lines 2
1380 "Number of empty lines needed to keep an empty line between collapsed trees.
1381 If you leave an empty line between the end of a subtree and the following
1382 headline, this empty line is hidden when the subtree is folded.
1383 Org-mode will leave (exactly) one empty line visible if the number of
1384 empty lines is equal or larger to the number given in this variable.
1385 So the default 2 means at least 2 empty lines after the end of a subtree
1386 are needed to produce free space between a collapsed subtree and the
1387 following headline.
1389 If the number is negative, and the number of empty lines is at least -N,
1390 all empty lines are shown.
1392 Special case: when 0, never leave empty lines in collapsed view."
1393 :group 'org-cycle
1394 :type 'integer)
1395 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
1397 (defcustom org-pre-cycle-hook nil
1398 "Hook that is run before visibility cycling is happening.
1399 The function(s) in this hook must accept a single argument which indicates
1400 the new state that will be set right after running this hook. The
1401 argument is a symbol. Before a global state change, it can have the values
1402 `overview', `content', or `all'. Before a local state change, it can have
1403 the values `folded', `children', or `subtree'."
1404 :group 'org-cycle
1405 :type 'hook)
1407 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
1408 org-cycle-hide-drawers
1409 org-cycle-show-empty-lines
1410 org-optimize-window-after-visibility-change)
1411 "Hook that is run after `org-cycle' has changed the buffer visibility.
1412 The function(s) in this hook must accept a single argument which indicates
1413 the new state that was set by the most recent `org-cycle' command. The
1414 argument is a symbol. After a global state change, it can have the values
1415 `overview', `contents', or `all'. After a local state change, it can have
1416 the values `folded', `children', or `subtree'."
1417 :group 'org-cycle
1418 :type 'hook
1419 :version "25.1"
1420 :package-version '(Org . "8.3"))
1422 (defgroup org-edit-structure nil
1423 "Options concerning structure editing in Org-mode."
1424 :tag "Org Edit Structure"
1425 :group 'org-structure)
1427 (defcustom org-odd-levels-only nil
1428 "Non-nil means skip even levels and only use odd levels for the outline.
1429 This has the effect that two stars are being added/taken away in
1430 promotion/demotion commands. It also influences how levels are
1431 handled by the exporters.
1432 Changing it requires restart of `font-lock-mode' to become effective
1433 for fontification also in regions already fontified.
1434 You may also set this on a per-file basis by adding one of the following
1435 lines to the buffer:
1437 #+STARTUP: odd
1438 #+STARTUP: oddeven"
1439 :group 'org-edit-structure
1440 :group 'org-appearance
1441 :type 'boolean)
1443 (defcustom org-adapt-indentation t
1444 "Non-nil means adapt indentation to outline node level.
1446 When this variable is set, Org assumes that you write outlines by
1447 indenting text in each node to align with the headline (after the
1448 stars). The following issues are influenced by this variable:
1450 - The indentation is increased by one space in a demotion
1451 command, and decreased by one in a promotion command. However,
1452 in the latter case, if shifting some line in the entry body
1453 would alter document structure (e.g., insert a new headline),
1454 indentation is not changed at all.
1456 - Property drawers and planning information is inserted indented
1457 when this variable is set. When nil, they will not be indented.
1459 - TAB indents a line relative to current level. The lines below
1460 a headline will be indented when this variable is set.
1462 Note that this is all about true indentation, by adding and
1463 removing space characters. See also `org-indent.el' which does
1464 level-dependent indentation in a virtual way, i.e. at display
1465 time in Emacs."
1466 :group 'org-edit-structure
1467 :type 'boolean)
1469 (defcustom org-special-ctrl-a/e nil
1470 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
1472 When t, `C-a' will bring back the cursor to the beginning of the
1473 headline text, i.e. after the stars and after a possible TODO
1474 keyword. In an item, this will be the position after bullet and
1475 check-box, if any. When the cursor is already at that position,
1476 another `C-a' will bring it to the beginning of the line.
1478 `C-e' will jump to the end of the headline, ignoring the presence
1479 of tags in the headline. A second `C-e' will then jump to the
1480 true end of the line, after any tags. This also means that, when
1481 this variable is non-nil, `C-e' also will never jump beyond the
1482 end of the heading of a folded section, i.e. not after the
1483 ellipses.
1485 When set to the symbol `reversed', the first `C-a' or `C-e' works
1486 normally, going to the true line boundary first. Only a directly
1487 following, identical keypress will bring the cursor to the
1488 special positions.
1490 This may also be a cons cell where the behavior for `C-a' and
1491 `C-e' is set separately."
1492 :group 'org-edit-structure
1493 :type '(choice
1494 (const :tag "off" nil)
1495 (const :tag "on: after stars/bullet and before tags first" t)
1496 (const :tag "reversed: true line boundary first" reversed)
1497 (cons :tag "Set C-a and C-e separately"
1498 (choice :tag "Special C-a"
1499 (const :tag "off" nil)
1500 (const :tag "on: after stars/bullet first" t)
1501 (const :tag "reversed: before stars/bullet first" reversed))
1502 (choice :tag "Special C-e"
1503 (const :tag "off" nil)
1504 (const :tag "on: before tags first" t)
1505 (const :tag "reversed: after tags first" reversed)))))
1506 (org-defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e)
1508 (defcustom org-special-ctrl-k nil
1509 "Non-nil means `C-k' will behave specially in headlines.
1510 When nil, `C-k' will call the default `kill-line' command.
1511 When t, the following will happen while the cursor is in the headline:
1513 - When the cursor is at the beginning of a headline, kill the entire
1514 line and possible the folded subtree below the line.
1515 - When in the middle of the headline text, kill the headline up to the tags.
1516 - When after the headline text, kill the tags."
1517 :group 'org-edit-structure
1518 :type 'boolean)
1520 (defcustom org-ctrl-k-protect-subtree nil
1521 "Non-nil means, do not delete a hidden subtree with C-k.
1522 When set to the symbol `error', simply throw an error when C-k is
1523 used to kill (part-of) a headline that has hidden text behind it.
1524 Any other non-nil value will result in a query to the user, if it is
1525 OK to kill that hidden subtree. When nil, kill without remorse."
1526 :group 'org-edit-structure
1527 :version "24.1"
1528 :type '(choice
1529 (const :tag "Do not protect hidden subtrees" nil)
1530 (const :tag "Protect hidden subtrees with a security query" t)
1531 (const :tag "Never kill a hidden subtree with C-k" error)))
1533 (defcustom org-special-ctrl-o t
1534 "Non-nil means, make `C-o' insert a row in tables."
1535 :group 'org-edit-structure
1536 :type 'boolean)
1538 (defcustom org-catch-invisible-edits nil
1539 "Check if in invisible region before inserting or deleting a character.
1540 Valid values are:
1542 nil Do not check, so just do invisible edits.
1543 error Throw an error and do nothing.
1544 show Make point visible, and do the requested edit.
1545 show-and-error Make point visible, then throw an error and abort the edit.
1546 smart Make point visible, and do insertion/deletion if it is
1547 adjacent to visible text and the change feels predictable.
1548 Never delete a previously invisible character or add in the
1549 middle or right after an invisible region. Basically, this
1550 allows insertion and backward-delete right before ellipses.
1551 FIXME: maybe in this case we should not even show?"
1552 :group 'org-edit-structure
1553 :version "24.1"
1554 :type '(choice
1555 (const :tag "Do not check" nil)
1556 (const :tag "Throw error when trying to edit" error)
1557 (const :tag "Unhide, but do not do the edit" show-and-error)
1558 (const :tag "Show invisible part and do the edit" show)
1559 (const :tag "Be smart and do the right thing" smart)))
1561 (defcustom org-yank-folded-subtrees t
1562 "Non-nil means when yanking subtrees, fold them.
1563 If the kill is a single subtree, or a sequence of subtrees, i.e. if
1564 it starts with a heading and all other headings in it are either children
1565 or siblings, then fold all the subtrees. However, do this only if no
1566 text after the yank would be swallowed into a folded tree by this action."
1567 :group 'org-edit-structure
1568 :type 'boolean)
1570 (defcustom org-yank-adjusted-subtrees nil
1571 "Non-nil means when yanking subtrees, adjust the level.
1572 With this setting, `org-paste-subtree' is used to insert the subtree, see
1573 this function for details."
1574 :group 'org-edit-structure
1575 :type 'boolean)
1577 (defcustom org-M-RET-may-split-line '((default . t))
1578 "Non-nil means M-RET will split the line at the cursor position.
1579 When nil, it will go to the end of the line before making a
1580 new line.
1581 You may also set this option in a different way for different
1582 contexts. Valid contexts are:
1584 headline when creating a new headline
1585 item when creating a new item
1586 table in a table field
1587 default the value to be used for all contexts not explicitly
1588 customized"
1589 :group 'org-structure
1590 :group 'org-table
1591 :type '(choice
1592 (const :tag "Always" t)
1593 (const :tag "Never" nil)
1594 (repeat :greedy t :tag "Individual contexts"
1595 (cons
1596 (choice :tag "Context"
1597 (const headline)
1598 (const item)
1599 (const table)
1600 (const default))
1601 (boolean)))))
1604 (defcustom org-insert-heading-respect-content nil
1605 "Non-nil means insert new headings after the current subtree.
1606 When nil, the new heading is created directly after the current line.
1607 The commands \\[org-insert-heading-respect-content] and \\[org-insert-todo-heading-respect-content] turn
1608 this variable on for the duration of the command."
1609 :group 'org-structure
1610 :type 'boolean)
1612 (defcustom org-blank-before-new-entry '((heading . auto)
1613 (plain-list-item . auto))
1614 "Should `org-insert-heading' leave a blank line before new heading/item?
1615 The value is an alist, with `heading' and `plain-list-item' as CAR,
1616 and a boolean flag as CDR. The cdr may also be the symbol `auto', in
1617 which case Org will look at the surrounding headings/items and try to
1618 make an intelligent decision whether to insert a blank line or not."
1619 :group 'org-edit-structure
1620 :type '(list
1621 (cons (const heading)
1622 (choice (const :tag "Never" nil)
1623 (const :tag "Always" t)
1624 (const :tag "Auto" auto)))
1625 (cons (const plain-list-item)
1626 (choice (const :tag "Never" nil)
1627 (const :tag "Always" t)
1628 (const :tag "Auto" auto)))))
1630 (defcustom org-insert-heading-hook nil
1631 "Hook being run after inserting a new heading."
1632 :group 'org-edit-structure
1633 :type 'hook)
1635 (defcustom org-enable-fixed-width-editor t
1636 "Non-nil means lines starting with \":\" are treated as fixed-width.
1637 This currently only means they are never auto-wrapped.
1638 When nil, such lines will be treated like ordinary lines."
1639 :group 'org-edit-structure
1640 :type 'boolean)
1642 (defcustom org-goto-auto-isearch t
1643 "Non-nil means typing characters in `org-goto' starts incremental search.
1644 When nil, you can use these keybindings to navigate the buffer:
1646 q Quit the org-goto interface
1647 n Go to the next visible heading
1648 p Go to the previous visible heading
1649 f Go one heading forward on same level
1650 b Go one heading backward on same level
1651 u Go one heading up"
1652 :group 'org-edit-structure
1653 :type 'boolean)
1655 (defgroup org-sparse-trees nil
1656 "Options concerning sparse trees in Org-mode."
1657 :tag "Org Sparse Trees"
1658 :group 'org-structure)
1660 (defcustom org-highlight-sparse-tree-matches t
1661 "Non-nil means highlight all matches that define a sparse tree.
1662 The highlights will automatically disappear the next time the buffer is
1663 changed by an edit command."
1664 :group 'org-sparse-trees
1665 :type 'boolean)
1667 (defcustom org-remove-highlights-with-change t
1668 "Non-nil means any change to the buffer will remove temporary highlights.
1669 \\<org-mode-map>\
1670 Such highlights are created by `org-occur' and `org-clock-display'.
1671 When nil, `\\[org-ctrl-c-ctrl-c]' needs to be used \
1672 to get rid of the highlights.
1673 The highlights created by `org-toggle-latex-fragment' always need
1674 `\\[org-toggle-latex-fragment]' to be removed."
1675 :group 'org-sparse-trees
1676 :group 'org-time
1677 :type 'boolean)
1680 (defcustom org-occur-hook '(org-first-headline-recenter)
1681 "Hook that is run after `org-occur' has constructed a sparse tree.
1682 This can be used to recenter the window to show as much of the structure
1683 as possible."
1684 :group 'org-sparse-trees
1685 :type 'hook)
1687 (defgroup org-imenu-and-speedbar nil
1688 "Options concerning imenu and speedbar in Org-mode."
1689 :tag "Org Imenu and Speedbar"
1690 :group 'org-structure)
1692 (defcustom org-imenu-depth 2
1693 "The maximum level for Imenu access to Org-mode headlines.
1694 This also applied for speedbar access."
1695 :group 'org-imenu-and-speedbar
1696 :type 'integer)
1698 (defgroup org-table nil
1699 "Options concerning tables in Org-mode."
1700 :tag "Org Table"
1701 :group 'org)
1703 (defcustom org-enable-table-editor 'optimized
1704 "Non-nil means lines starting with \"|\" are handled by the table editor.
1705 When nil, such lines will be treated like ordinary lines.
1707 When equal to the symbol `optimized', the table editor will be optimized to
1708 do the following:
1709 - Automatic overwrite mode in front of whitespace in table fields.
1710 This makes the structure of the table stay in tact as long as the edited
1711 field does not exceed the column width.
1712 - Minimize the number of realigns. Normally, the table is aligned each time
1713 TAB or RET are pressed to move to another field. With optimization this
1714 happens only if changes to a field might have changed the column width.
1715 Optimization requires replacing the functions `self-insert-command',
1716 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1717 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1718 very good at guessing when a re-align will be necessary, but you can always
1719 force one with \\[org-ctrl-c-ctrl-c].
1721 If you would like to use the optimized version in Org-mode, but the
1722 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1724 This variable can be used to turn on and off the table editor during a session,
1725 but in order to toggle optimization, a restart is required.
1727 See also the variable `org-table-auto-blank-field'."
1728 :group 'org-table
1729 :type '(choice
1730 (const :tag "off" nil)
1731 (const :tag "on" t)
1732 (const :tag "on, optimized" optimized)))
1734 (defcustom org-self-insert-cluster-for-undo (or (featurep 'xemacs)
1735 (version<= emacs-version "24.1"))
1736 "Non-nil means cluster self-insert commands for undo when possible.
1737 If this is set, then, like in the Emacs command loop, 20 consecutive
1738 characters will be undone together.
1739 This is configurable, because there is some impact on typing performance."
1740 :group 'org-table
1741 :type 'boolean)
1743 (defcustom org-table-tab-recognizes-table.el t
1744 "Non-nil means TAB will automatically notice a table.el table.
1745 When it sees such a table, it moves point into it and - if necessary -
1746 calls `table-recognize-table'."
1747 :group 'org-table-editing
1748 :type 'boolean)
1750 (defgroup org-link nil
1751 "Options concerning links in Org-mode."
1752 :tag "Org Link"
1753 :group 'org)
1755 (defvar-local org-link-abbrev-alist-local nil
1756 "Buffer-local version of `org-link-abbrev-alist', which see.
1757 The value of this is taken from the #+LINK lines.")
1759 (defcustom org-link-abbrev-alist nil
1760 "Alist of link abbreviations.
1761 The car of each element is a string, to be replaced at the start of a link.
1762 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1763 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1765 [[linkkey:tag][description]]
1767 The `linkkey' must be a word word, starting with a letter, followed
1768 by letters, numbers, `-' or `_'.
1770 If REPLACE is a string, the tag will simply be appended to create the link.
1771 If the string contains \"%s\", the tag will be inserted there. If the string
1772 contains \"%h\", it will cause a url-encoded version of the tag to be inserted
1773 at that point (see the function `url-hexify-string'). If the string contains
1774 the specifier \"%(my-function)\", then the custom function `my-function' will
1775 be invoked: this function takes the tag as its only argument and must return
1776 a string.
1778 REPLACE may also be a function that will be called with the tag as the
1779 only argument to create the link, which should be returned as a string.
1781 See the manual for examples."
1782 :group 'org-link
1783 :type '(repeat
1784 (cons
1785 (string :tag "Protocol")
1786 (choice
1787 (string :tag "Format")
1788 (function)))))
1790 (defcustom org-descriptive-links t
1791 "Non-nil means Org will display descriptive links.
1792 E.g. [[http://orgmode.org][Org website]] will be displayed as
1793 \"Org Website\", hiding the link itself and just displaying its
1794 description. When set to nil, Org will display the full links
1795 literally.
1797 You can interactively set the value of this variable by calling
1798 `org-toggle-link-display' or from the menu Org>Hyperlinks menu."
1799 :group 'org-link
1800 :type 'boolean)
1802 (defcustom org-link-file-path-type 'adaptive
1803 "How the path name in file links should be stored.
1804 Valid values are:
1806 relative Relative to the current directory, i.e. the directory of the file
1807 into which the link is being inserted.
1808 absolute Absolute path, if possible with ~ for home directory.
1809 noabbrev Absolute path, no abbreviation of home directory.
1810 adaptive Use relative path for files in the current directory and sub-
1811 directories of it. For other files, use an absolute path."
1812 :group 'org-link
1813 :type '(choice
1814 (const relative)
1815 (const absolute)
1816 (const noabbrev)
1817 (const adaptive)))
1819 (defvaralias 'org-activate-links 'org-highlight-links)
1820 (defcustom org-highlight-links '(bracket angle plain radio tag date footnote)
1821 "Types of links that should be highlighted in Org-mode files.
1823 This is a list of symbols, each one of them leading to the
1824 highlighting of a certain link type.
1826 You can still open links that are not highlighted.
1828 In principle, it does not hurt to turn on highlighting for all
1829 link types. There may be a small gain when turning off unused
1830 link types. The types are:
1832 bracket The recommended [[link][description]] or [[link]] links with hiding.
1833 angle Links in angular brackets that may contain whitespace like
1834 <bbdb:Carsten Dominik>.
1835 plain Plain links in normal text, no whitespace, like http://google.com.
1836 radio Text that is matched by a radio target, see manual for details.
1837 tag Tag settings in a headline (link to tag search).
1838 date Time stamps (link to calendar).
1839 footnote Footnote labels.
1841 If you set this variable during an Emacs session, use `org-mode-restart'
1842 in the Org buffer so that the change takes effect."
1843 :group 'org-link
1844 :group 'org-appearance
1845 :type '(set :greedy t
1846 (const :tag "Double bracket links" bracket)
1847 (const :tag "Angular bracket links" angle)
1848 (const :tag "Plain text links" plain)
1849 (const :tag "Radio target matches" radio)
1850 (const :tag "Tags" tag)
1851 (const :tag "Timestamps" date)
1852 (const :tag "Footnotes" footnote)))
1854 (defcustom org-make-link-description-function nil
1855 "Function to use for generating link descriptions from links.
1856 When nil, the link location will be used. This function must take
1857 two parameters: the first one is the link, the second one is the
1858 description generated by `org-insert-link'. The function should
1859 return the description to use."
1860 :group 'org-link
1861 :type '(choice (const nil) (function)))
1863 (defgroup org-link-store nil
1864 "Options concerning storing links in Org-mode."
1865 :tag "Org Store Link"
1866 :group 'org-link)
1868 (defcustom org-url-hexify-p t
1869 "When non-nil, hexify URL when creating a link."
1870 :type 'boolean
1871 :version "24.3"
1872 :group 'org-link-store)
1874 (defcustom org-email-link-description-format "Email %c: %.30s"
1875 "Format of the description part of a link to an email or usenet message.
1876 The following %-escapes will be replaced by corresponding information:
1878 %F full \"From\" field
1879 %f name, taken from \"From\" field, address if no name
1880 %T full \"To\" field
1881 %t first name in \"To\" field, address if no name
1882 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1883 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1884 %s subject
1885 %d date
1886 %m message-id.
1888 You may use normal field width specification between the % and the letter.
1889 This is for example useful to limit the length of the subject.
1891 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1892 :group 'org-link-store
1893 :type 'string)
1895 (defcustom org-from-is-user-regexp
1896 (let (r1 r2)
1897 (when (and user-mail-address (not (string= user-mail-address "")))
1898 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1899 (when (and user-full-name (not (string= user-full-name "")))
1900 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1901 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1902 "Regexp matched against the \"From:\" header of an email or usenet message.
1903 It should match if the message is from the user him/herself."
1904 :group 'org-link-store
1905 :type 'regexp)
1907 (defcustom org-context-in-file-links t
1908 "Non-nil means file links from `org-store-link' contain context.
1909 A search string will be added to the file name with :: as separator and
1910 used to find the context when the link is activated by the command
1911 `org-open-at-point'. When this option is t, the entire active region
1912 will be placed in the search string of the file link. If set to a
1913 positive integer, only the first n lines of context will be stored.
1915 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1916 negates this setting for the duration of the command."
1917 :group 'org-link-store
1918 :type '(choice boolean integer))
1920 (defcustom org-keep-stored-link-after-insertion nil
1921 "Non-nil means keep link in list for entire session.
1923 The command `org-store-link' adds a link pointing to the current
1924 location to an internal list. These links accumulate during a session.
1925 The command `org-insert-link' can be used to insert links into any
1926 Org-mode file (offering completion for all stored links). When this
1927 option is nil, every link which has been inserted once using \\[org-insert-link]
1928 will be removed from the list, to make completing the unused links
1929 more efficient."
1930 :group 'org-link-store
1931 :type 'boolean)
1933 (defgroup org-link-follow nil
1934 "Options concerning following links in Org-mode."
1935 :tag "Org Follow Link"
1936 :group 'org-link)
1938 (defcustom org-link-translation-function nil
1939 "Function to translate links with different syntax to Org syntax.
1940 This can be used to translate links created for example by the Planner
1941 or emacs-wiki packages to Org syntax.
1942 The function must accept two parameters, a TYPE containing the link
1943 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1944 which is everything after the link protocol. It should return a cons
1945 with possibly modified values of type and path.
1946 Org contains a function for this, so if you set this variable to
1947 `org-translate-link-from-planner', you should be able follow many
1948 links created by planner."
1949 :group 'org-link-follow
1950 :type '(choice (const nil) (function)))
1952 (defcustom org-follow-link-hook nil
1953 "Hook that is run after a link has been followed."
1954 :group 'org-link-follow
1955 :type 'hook)
1957 (defcustom org-tab-follows-link nil
1958 "Non-nil means on links TAB will follow the link.
1959 Needs to be set before org.el is loaded.
1960 This really should not be used, it does not make sense, and the
1961 implementation is bad."
1962 :group 'org-link-follow
1963 :type 'boolean)
1965 (defcustom org-return-follows-link nil
1966 "Non-nil means on links RET will follow the link.
1967 In tables, the special behavior of RET has precedence."
1968 :group 'org-link-follow
1969 :type 'boolean)
1971 (defcustom org-mouse-1-follows-link
1972 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1973 "Non-nil means mouse-1 on a link will follow the link.
1974 A longer mouse click will still set point. Does not work on XEmacs.
1975 Needs to be set before org.el is loaded."
1976 :group 'org-link-follow
1977 :version "24.4"
1978 :package-version '(Org . "8.3")
1979 :type '(choice
1980 (const :tag "A double click follows the link" double)
1981 (const :tag "Unconditionally follow the link with mouse-1" t)
1982 (integer :tag "mouse-1 click does not follow the link if longer than N ms" 450)))
1984 (defcustom org-mark-ring-length 4
1985 "Number of different positions to be recorded in the ring.
1986 Changing this requires a restart of Emacs to work correctly."
1987 :group 'org-link-follow
1988 :type 'integer)
1990 (defcustom org-link-search-must-match-exact-headline 'query-to-create
1991 "Non-nil means internal links in Org files must exactly match a headline.
1992 When nil, the link search tries to match a phrase with all words
1993 in the search text."
1994 :group 'org-link-follow
1995 :version "24.1"
1996 :type '(choice
1997 (const :tag "Use fuzzy text search" nil)
1998 (const :tag "Match only exact headline" t)
1999 (const :tag "Match exact headline or query to create it"
2000 query-to-create)))
2002 (defcustom org-link-frame-setup
2003 '((vm . vm-visit-folder-other-frame)
2004 (vm-imap . vm-visit-imap-folder-other-frame)
2005 (gnus . org-gnus-no-new-news)
2006 (file . find-file-other-window)
2007 (wl . wl-other-frame))
2008 "Setup the frame configuration for following links.
2009 When following a link with Emacs, it may often be useful to display
2010 this link in another window or frame. This variable can be used to
2011 set this up for the different types of links.
2012 For VM, use any of
2013 `vm-visit-folder'
2014 `vm-visit-folder-other-window'
2015 `vm-visit-folder-other-frame'
2016 For Gnus, use any of
2017 `gnus'
2018 `gnus-other-frame'
2019 `org-gnus-no-new-news'
2020 For FILE, use any of
2021 `find-file'
2022 `find-file-other-window'
2023 `find-file-other-frame'
2024 For Wanderlust use any of
2025 `wl'
2026 `wl-other-frame'
2027 For the calendar, use the variable `calendar-setup'.
2028 For BBDB, it is currently only possible to display the matches in
2029 another window."
2030 :group 'org-link-follow
2031 :type '(list
2032 (cons (const vm)
2033 (choice
2034 (const vm-visit-folder)
2035 (const vm-visit-folder-other-window)
2036 (const vm-visit-folder-other-frame)))
2037 (cons (const vm-imap)
2038 (choice
2039 (const vm-visit-imap-folder)
2040 (const vm-visit-imap-folder-other-window)
2041 (const vm-visit-imap-folder-other-frame)))
2042 (cons (const gnus)
2043 (choice
2044 (const gnus)
2045 (const gnus-other-frame)
2046 (const org-gnus-no-new-news)))
2047 (cons (const file)
2048 (choice
2049 (const find-file)
2050 (const find-file-other-window)
2051 (const find-file-other-frame)))
2052 (cons (const wl)
2053 (choice
2054 (const wl)
2055 (const wl-other-frame)))))
2057 (defcustom org-display-internal-link-with-indirect-buffer nil
2058 "Non-nil means use indirect buffer to display infile links.
2059 Activating internal links (from one location in a file to another location
2060 in the same file) normally just jumps to the location. When the link is
2061 activated with a \\[universal-argument] prefix (or with mouse-3), the link \
2062 is displayed in
2063 another window. When this option is set, the other window actually displays
2064 an indirect buffer clone of the current buffer, to avoid any visibility
2065 changes to the current buffer."
2066 :group 'org-link-follow
2067 :type 'boolean)
2069 (defcustom org-open-non-existing-files nil
2070 "Non-nil means `org-open-file' will open non-existing files.
2071 When nil, an error will be generated.
2072 This variable applies only to external applications because they
2073 might choke on non-existing files. If the link is to a file that
2074 will be opened in Emacs, the variable is ignored."
2075 :group 'org-link-follow
2076 :type 'boolean)
2078 (defcustom org-open-directory-means-index-dot-org nil
2079 "Non-nil means a link to a directory really means to index.org.
2080 When nil, following a directory link will run dired or open a finder/explorer
2081 window on that directory."
2082 :group 'org-link-follow
2083 :type 'boolean)
2085 (defcustom org-confirm-shell-link-function 'yes-or-no-p
2086 "Non-nil means ask for confirmation before executing shell links.
2087 Shell links can be dangerous: just think about a link
2089 [[shell:rm -rf ~/*][Google Search]]
2091 This link would show up in your Org-mode document as \"Google Search\",
2092 but really it would remove your entire home directory.
2093 Therefore we advise against setting this variable to nil.
2094 Just change it to `y-or-n-p' if you want to confirm with a
2095 single keystroke rather than having to type \"yes\"."
2096 :group 'org-link-follow
2097 :type '(choice
2098 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2099 (const :tag "with y-or-n (faster)" y-or-n-p)
2100 (const :tag "no confirmation (dangerous)" nil)))
2101 (put 'org-confirm-shell-link-function
2102 'safe-local-variable
2103 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2105 (defcustom org-confirm-shell-link-not-regexp ""
2106 "A regexp to skip confirmation for shell links."
2107 :group 'org-link-follow
2108 :version "24.1"
2109 :type 'regexp)
2111 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
2112 "Non-nil means ask for confirmation before executing Emacs Lisp links.
2113 Elisp links can be dangerous: just think about a link
2115 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
2117 This link would show up in your Org-mode document as \"Google Search\",
2118 but really it would remove your entire home directory.
2119 Therefore we advise against setting this variable to nil.
2120 Just change it to `y-or-n-p' if you want to confirm with a
2121 single keystroke rather than having to type \"yes\"."
2122 :group 'org-link-follow
2123 :type '(choice
2124 (const :tag "with yes-or-no (safer)" yes-or-no-p)
2125 (const :tag "with y-or-n (faster)" y-or-n-p)
2126 (const :tag "no confirmation (dangerous)" nil)))
2127 (put 'org-confirm-shell-link-function
2128 'safe-local-variable
2129 (lambda (x) (member x '(yes-or-no-p y-or-n-p))))
2131 (defcustom org-confirm-elisp-link-not-regexp ""
2132 "A regexp to skip confirmation for Elisp links."
2133 :group 'org-link-follow
2134 :version "24.1"
2135 :type 'regexp)
2137 (defconst org-file-apps-defaults-gnu
2138 '((remote . emacs)
2139 (system . mailcap)
2140 (t . mailcap))
2141 "Default file applications on a UNIX or GNU/Linux system.
2142 See `org-file-apps'.")
2144 (defconst org-file-apps-defaults-macosx
2145 '((remote . emacs)
2146 (system . "open %s")
2147 ("ps.gz" . "gv %s")
2148 ("eps.gz" . "gv %s")
2149 ("dvi" . "xdvi %s")
2150 ("fig" . "xfig %s")
2151 (t . "open %s"))
2152 "Default file applications on a MacOS X system.
2153 The system \"open\" is known as a default, but we use X11 applications
2154 for some files for which the OS does not have a good default.
2155 See `org-file-apps'.")
2157 (defconst org-file-apps-defaults-windowsnt
2158 (list '(remote . emacs)
2159 (cons 'system (lambda (file _path)
2160 (with-no-warnings (w32-shell-execute "open" file))))
2161 (cons t (lambda (file _path)
2162 (with-no-warnings (w32-shell-execute "open" file)))))
2163 "Default file applications on a Windows NT system.
2164 The system \"open\" is used for most files.
2165 See `org-file-apps'.")
2167 (defcustom org-file-apps
2168 '((auto-mode . emacs)
2169 ("\\.mm\\'" . default)
2170 ("\\.x?html?\\'" . default)
2171 ("\\.pdf\\'" . default))
2172 "External applications for opening `file:path' items in a document.
2173 \\<org-mode-map>\
2174 Org mode uses system defaults for different file types, but
2175 you can use this variable to set the application for a given file
2176 extension. The entries in this list are cons cells where the car identifies
2177 files and the cdr the corresponding command. Possible values for the
2178 file identifier are
2179 \"string\" A string as a file identifier can be interpreted in different
2180 ways, depending on its contents:
2182 - Alphanumeric characters only:
2183 Match links with this file extension.
2184 Example: (\"pdf\" . \"evince %s\")
2185 to open PDFs with evince.
2187 - Regular expression: Match links where the
2188 filename matches the regexp. If you want to
2189 use groups here, use shy groups.
2191 Example: (\"\\.x?html\\\\='\" . \"firefox %s\")
2192 \(\"\\(?:xhtml\\|html\\)\" . \"firefox %s\")
2193 to open *.html and *.xhtml with firefox.
2195 - Regular expression which contains (non-shy) groups:
2196 Match links where the whole link, including \"::\", and
2197 anything after that, matches the regexp.
2198 In a custom command string, %1, %2, etc. are replaced with
2199 the parts of the link that were matched by the groups.
2200 For backwards compatibility, if a command string is given
2201 that does not use any of the group matches, this case is
2202 handled identically to the second one (i.e. match against
2203 file name only).
2204 In a custom function, you can access the group matches with
2205 \(match-string n link).
2207 Example: (\"\\.pdf::\\(\\d+\\)\\\\='\" . \"evince -p %1 %s\")
2208 to open [[file:document.pdf::5]] with evince at page 5.
2210 `directory' Matches a directory
2211 `remote' Matches a remote file, accessible through tramp or efs.
2212 Remote files most likely should be visited through Emacs
2213 because external applications cannot handle such paths.
2214 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
2215 so all files Emacs knows how to handle. Using this with
2216 command `emacs' will open most files in Emacs. Beware that this
2217 will also open html files inside Emacs, unless you add
2218 \(\"html\" . default) to the list as well.
2219 `system' The system command to open files, like `open' on Windows
2220 and Mac OS X, and mailcap under GNU/Linux. This is the command
2221 that will be selected if you call \\[org-open-at-point] with a double
2222 \\[universal-argument] \\[universal-argument] prefix.
2223 t Default for files not matched by any of the other options.
2225 Possible values for the command are:
2226 `emacs' The file will be visited by the current Emacs process.
2227 `default' Use the default application for this file type, which is the
2228 association for t in the list, most likely in the system-specific
2229 part. This can be used to overrule an unwanted setting in the
2230 system-specific variable.
2231 `system' Use the system command for opening files, like \"open\".
2232 This command is specified by the entry whose car is `system'.
2233 Most likely, the system-specific version of this variable
2234 does define this command, but you can overrule/replace it
2235 here.
2236 `mailcap' Use command specified in the mailcaps.
2237 string A command to be executed by a shell; %s will be replaced
2238 by the path to the file.
2240 function A Lisp function, which will be called with two arguments:
2241 the file path and the original link string, without the
2242 \"file:\" prefix.
2244 For more examples, see the system specific constants
2245 `org-file-apps-defaults-macosx'
2246 `org-file-apps-defaults-windowsnt'
2247 `org-file-apps-defaults-gnu'."
2248 :group 'org-link-follow
2249 :type '(repeat
2250 (cons (choice :value ""
2251 (string :tag "Extension")
2252 (const :tag "System command to open files" system)
2253 (const :tag "Default for unrecognized files" t)
2254 (const :tag "Remote file" remote)
2255 (const :tag "Links to a directory" directory)
2256 (const :tag "Any files that have Emacs modes"
2257 auto-mode))
2258 (choice :value ""
2259 (const :tag "Visit with Emacs" emacs)
2260 (const :tag "Use default" default)
2261 (const :tag "Use the system command" system)
2262 (string :tag "Command")
2263 (function :tag "Function")))))
2265 (defcustom org-doi-server-url "http://dx.doi.org/"
2266 "The URL of the DOI server."
2267 :type 'string
2268 :version "24.3"
2269 :group 'org-link-follow)
2271 (defgroup org-refile nil
2272 "Options concerning refiling entries in Org-mode."
2273 :tag "Org Refile"
2274 :group 'org)
2276 (defcustom org-directory "~/org"
2277 "Directory with Org files.
2278 This is just a default location to look for Org files. There is no need
2279 at all to put your files into this directory. It is used in the
2280 following situations:
2282 1. When a capture template specifies a target file that is not an
2283 absolute path. The path will then be interpreted relative to
2284 `org-directory'
2285 2. When the value of variable `org-agenda-files' is a single file, any
2286 relative paths in this file will be taken as relative to
2287 `org-directory'."
2288 :group 'org-refile
2289 :group 'org-capture
2290 :type 'directory)
2292 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
2293 "Default target for storing notes.
2294 Used as a fall back file for org-capture.el, for templates that
2295 do not specify a target file."
2296 :group 'org-refile
2297 :group 'org-capture
2298 :type 'file)
2300 (defcustom org-goto-interface 'outline
2301 "The default interface to be used for `org-goto'.
2302 Allowed values are:
2303 outline The interface shows an outline of the relevant file
2304 and the correct heading is found by moving through
2305 the outline or by searching with incremental search.
2306 outline-path-completion Headlines in the current buffer are offered via
2307 completion. This is the interface also used by
2308 the refile command."
2309 :group 'org-refile
2310 :type '(choice
2311 (const :tag "Outline" outline)
2312 (const :tag "Outline-path-completion" outline-path-completion)))
2314 (defcustom org-goto-max-level 5
2315 "Maximum target level when running `org-goto' with refile interface."
2316 :group 'org-refile
2317 :type 'integer)
2319 (defcustom org-reverse-note-order nil
2320 "Non-nil means store new notes at the beginning of a file or entry.
2321 When nil, new notes will be filed to the end of a file or entry.
2322 This can also be a list with cons cells of regular expressions that
2323 are matched against file names, and values."
2324 :group 'org-capture
2325 :group 'org-refile
2326 :type '(choice
2327 (const :tag "Reverse always" t)
2328 (const :tag "Reverse never" nil)
2329 (repeat :tag "By file name regexp"
2330 (cons regexp boolean))))
2332 (defcustom org-log-refile nil
2333 "Information to record when a task is refiled.
2335 Possible values are:
2337 nil Don't add anything
2338 time Add a time stamp to the task
2339 note Prompt for a note and add it with template `org-log-note-headings'
2341 This option can also be set with on a per-file-basis with
2343 #+STARTUP: nologrefile
2344 #+STARTUP: logrefile
2345 #+STARTUP: lognoterefile
2347 You can have local logging settings for a subtree by setting the LOGGING
2348 property to one or more of these keywords.
2350 When bulk-refiling from the agenda, the value `note' is forbidden and
2351 will temporarily be changed to `time'."
2352 :group 'org-refile
2353 :group 'org-progress
2354 :version "24.1"
2355 :type '(choice
2356 (const :tag "No logging" nil)
2357 (const :tag "Record timestamp" time)
2358 (const :tag "Record timestamp with note." note)))
2360 (defcustom org-refile-targets nil
2361 "Targets for refiling entries with \\[org-refile].
2362 This is a list of cons cells. Each cell contains:
2363 - a specification of the files to be considered, either a list of files,
2364 or a symbol whose function or variable value will be used to retrieve
2365 a file name or a list of file names. If you use `org-agenda-files' for
2366 that, all agenda files will be scanned for targets. Nil means consider
2367 headings in the current buffer.
2368 - A specification of how to find candidate refile targets. This may be
2369 any of:
2370 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
2371 This tag has to be present in all target headlines, inheritance will
2372 not be considered.
2373 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
2374 todo keyword.
2375 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
2376 headlines that are refiling targets.
2377 - a cons cell (:level . N). Any headline of level N is considered a target.
2378 Note that, when `org-odd-levels-only' is set, level corresponds to
2379 order in hierarchy, not to the number of stars.
2380 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
2381 Note that, when `org-odd-levels-only' is set, level corresponds to
2382 order in hierarchy, not to the number of stars.
2384 Each element of this list generates a set of possible targets.
2385 The union of these sets is presented (with completion) to
2386 the user by `org-refile'.
2388 You can set the variable `org-refile-target-verify-function' to a function
2389 to verify each headline found by the simple criteria above.
2391 When this variable is nil, all top-level headlines in the current buffer
2392 are used, equivalent to the value `((nil . (:level . 1))'."
2393 :group 'org-refile
2394 :type '(repeat
2395 (cons
2396 (choice :value org-agenda-files
2397 (const :tag "All agenda files" org-agenda-files)
2398 (const :tag "Current buffer" nil)
2399 (function) (variable) (file))
2400 (choice :tag "Identify target headline by"
2401 (cons :tag "Specific tag" (const :value :tag) (string))
2402 (cons :tag "TODO keyword" (const :value :todo) (string))
2403 (cons :tag "Regular expression" (const :value :regexp) (regexp))
2404 (cons :tag "Level number" (const :value :level) (integer))
2405 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
2407 (defcustom org-refile-target-verify-function nil
2408 "Function to verify if the headline at point should be a refile target.
2409 The function will be called without arguments, with point at the
2410 beginning of the headline. It should return t and leave point
2411 where it is if the headline is a valid target for refiling.
2413 If the target should not be selected, the function must return nil.
2414 In addition to this, it may move point to a place from where the search
2415 should be continued. For example, the function may decide that the entire
2416 subtree of the current entry should be excluded and move point to the end
2417 of the subtree."
2418 :group 'org-refile
2419 :type '(choice
2420 (const nil)
2421 (function)))
2423 (defcustom org-refile-use-cache nil
2424 "Non-nil means cache refile targets to speed up the process.
2425 \\<org-mode-map>\
2426 The cache for a particular file will be updated automatically when
2427 the buffer has been killed, or when any of the marker used for flagging
2428 refile targets no longer points at a live buffer.
2429 If you have added new entries to a buffer that might themselves be targets,
2430 you need to clear the cache manually by pressing `C-0 \\[org-refile]' or,
2431 if you find that easier, \
2432 `\\[universal-argument] \\[universal-argument] \\[universal-argument] \
2433 \\[org-refile]'."
2434 :group 'org-refile
2435 :version "24.1"
2436 :type 'boolean)
2438 (defcustom org-refile-use-outline-path nil
2439 "Non-nil means provide refile targets as paths.
2440 So a level 3 headline will be available as level1/level2/level3.
2442 When the value is `file', also include the file name (without directory)
2443 into the path. In this case, you can also stop the completion after
2444 the file name, to get entries inserted as top level in the file.
2446 When `full-file-path', include the full file path."
2447 :group 'org-refile
2448 :type '(choice
2449 (const :tag "Not" nil)
2450 (const :tag "Yes" t)
2451 (const :tag "Start with file name" file)
2452 (const :tag "Start with full file path" full-file-path)))
2454 (defcustom org-outline-path-complete-in-steps t
2455 "Non-nil means complete the outline path in hierarchical steps.
2456 When Org-mode uses the refile interface to select an outline path
2457 \(see variable `org-refile-use-outline-path'), the completion of
2458 the path can be done in a single go, or it can be done in steps down
2459 the headline hierarchy. Going in steps is probably the best if you
2460 do not use a special completion package like `ido' or `icicles'.
2461 However, when using these packages, going in one step can be very
2462 fast, while still showing the whole path to the entry."
2463 :group 'org-refile
2464 :type 'boolean)
2466 (defcustom org-refile-allow-creating-parent-nodes nil
2467 "Non-nil means allow the creation of new nodes as refile targets.
2468 New nodes are then created by adding \"/new node name\" to the completion
2469 of an existing node. When the value of this variable is `confirm',
2470 new node creation must be confirmed by the user (recommended).
2471 When nil, the completion must match an existing entry.
2473 Note that, if the new heading is not seen by the criteria
2474 listed in `org-refile-targets', multiple instances of the same
2475 heading would be created by trying again to file under the new
2476 heading."
2477 :group 'org-refile
2478 :type '(choice
2479 (const :tag "Never" nil)
2480 (const :tag "Always" t)
2481 (const :tag "Prompt for confirmation" confirm)))
2483 (defcustom org-refile-active-region-within-subtree nil
2484 "Non-nil means also refile active region within a subtree.
2486 By default `org-refile' doesn't allow refiling regions if they
2487 don't contain a set of subtrees, but it might be convenient to
2488 do so sometimes: in that case, the first line of the region is
2489 converted to a headline before refiling."
2490 :group 'org-refile
2491 :version "24.1"
2492 :type 'boolean)
2494 (defgroup org-todo nil
2495 "Options concerning TODO items in Org-mode."
2496 :tag "Org TODO"
2497 :group 'org)
2499 (defgroup org-progress nil
2500 "Options concerning Progress logging in Org-mode."
2501 :tag "Org Progress"
2502 :group 'org-time)
2504 (defvar org-todo-interpretation-widgets
2505 '((:tag "Sequence (cycling hits every state)" sequence)
2506 (:tag "Type (cycling directly to DONE)" type))
2507 "The available interpretation symbols for customizing `org-todo-keywords'.
2508 Interested libraries should add to this list.")
2510 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
2511 "List of TODO entry keyword sequences and their interpretation.
2512 \\<org-mode-map>This is a list of sequences.
2514 Each sequence starts with a symbol, either `sequence' or `type',
2515 indicating if the keywords should be interpreted as a sequence of
2516 action steps, or as different types of TODO items. The first
2517 keywords are states requiring action - these states will select a headline
2518 for inclusion into the global TODO list Org-mode produces. If one of
2519 the \"keywords\" is the vertical bar, \"|\", the remaining keywords
2520 signify that no further action is necessary. If \"|\" is not found,
2521 the last keyword is treated as the only DONE state of the sequence.
2523 The command \\[org-todo] cycles an entry through these states, and one
2524 additional state where no keyword is present. For details about this
2525 cycling, see the manual.
2527 TODO keywords and interpretation can also be set on a per-file basis with
2528 the special #+SEQ_TODO and #+TYP_TODO lines.
2530 Each keyword can optionally specify a character for fast state selection
2531 \(in combination with the variable `org-use-fast-todo-selection')
2532 and specifiers for state change logging, using the same syntax that
2533 is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says that
2534 the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
2535 indicates to record a time stamp each time this state is selected.
2537 Each keyword may also specify if a timestamp or a note should be
2538 recorded when entering or leaving the state, by adding additional
2539 characters in the parenthesis after the keyword. This looks like this:
2540 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
2541 record only the time of the state change. With X and Y being either
2542 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
2543 Y when leaving the state if and only if the *target* state does not
2544 define X. You may omit any of the fast-selection key or X or /Y,
2545 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
2547 For backward compatibility, this variable may also be just a list
2548 of keywords. In this case the interpretation (sequence or type) will be
2549 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
2550 :group 'org-todo
2551 :group 'org-keywords
2552 :type '(choice
2553 (repeat :tag "Old syntax, just keywords"
2554 (string :tag "Keyword"))
2555 (repeat :tag "New syntax"
2556 (cons
2557 (choice
2558 :tag "Interpretation"
2559 ;;Quick and dirty way to see
2560 ;;`org-todo-interpretations'. This takes the
2561 ;;place of item arguments
2562 :convert-widget
2563 (lambda (widget)
2564 (widget-put widget
2565 :args (mapcar
2566 (lambda (x)
2567 (widget-convert
2568 (cons 'const x)))
2569 org-todo-interpretation-widgets))
2570 widget))
2571 (repeat
2572 (string :tag "Keyword"))))))
2574 (defvar-local org-todo-keywords-1 nil
2575 "All TODO and DONE keywords active in a buffer.")
2576 (defvar org-todo-keywords-for-agenda nil)
2577 (defvar org-done-keywords-for-agenda nil)
2578 (defvar org-todo-keyword-alist-for-agenda nil)
2579 (defvar org-tag-alist-for-agenda nil
2580 "Alist of all tags from all agenda files.")
2581 (defvar org-tag-groups-alist-for-agenda nil
2582 "Alist of all groups tags from all current agenda files.")
2583 (defvar-local org-tag-groups-alist nil)
2584 (defvar org-agenda-contributing-files nil)
2585 (defvar-local org-current-tag-alist nil
2586 "Alist of all tag groups in current buffer.
2587 This variable takes into consideration `org-tag-alist',
2588 `org-tag-persistent-alist' and TAGS keywords in the buffer.")
2589 (defvar-local org-not-done-keywords nil)
2590 (defvar-local org-done-keywords nil)
2591 (defvar-local org-todo-heads nil)
2592 (defvar-local org-todo-sets nil)
2593 (defvar-local org-todo-log-states nil)
2594 (defvar-local org-todo-kwd-alist nil)
2595 (defvar-local org-todo-key-alist nil)
2596 (defvar-local org-todo-key-trigger nil)
2598 (defcustom org-todo-interpretation 'sequence
2599 "Controls how TODO keywords are interpreted.
2600 This variable is in principle obsolete and is only used for
2601 backward compatibility, if the interpretation of todo keywords is
2602 not given already in `org-todo-keywords'. See that variable for
2603 more information."
2604 :group 'org-todo
2605 :group 'org-keywords
2606 :type '(choice (const sequence)
2607 (const type)))
2609 (defcustom org-use-fast-todo-selection t
2610 "\\<org-mode-map>\
2611 Non-nil means use the fast todo selection scheme with \\[org-todo].
2612 This variable describes if and under what circumstances the cycling
2613 mechanism for TODO keywords will be replaced by a single-key, direct
2614 selection scheme.
2616 When nil, fast selection is never used.
2618 When the symbol `prefix', it will be used when `org-todo' is called
2619 with a prefix argument, i.e. `\\[universal-argument] \\[org-todo]' \
2620 in an Org-mode buffer, and
2621 `\\[universal-argument] t' in an agenda buffer.
2623 When t, fast selection is used by default. In this case, the prefix
2624 argument forces cycling instead.
2626 In all cases, the special interface is only used if access keys have
2627 actually been assigned by the user, i.e. if keywords in the configuration
2628 are followed by a letter in parenthesis, like TODO(t)."
2629 :group 'org-todo
2630 :type '(choice
2631 (const :tag "Never" nil)
2632 (const :tag "By default" t)
2633 (const :tag "Only with C-u C-c C-t" prefix)))
2635 (defcustom org-provide-todo-statistics t
2636 "Non-nil means update todo statistics after insert and toggle.
2637 ALL-HEADLINES means update todo statistics by including headlines
2638 with no TODO keyword as well, counting them as not done.
2639 A list of TODO keywords means the same, but skip keywords that are
2640 not in this list.
2641 When set to a list of two lists, the first list contains keywords
2642 to consider as TODO keywords, the second list contains keywords
2643 to consider as DONE keywords.
2645 When this is set, todo statistics is updated in the parent of the
2646 current entry each time a todo state is changed."
2647 :group 'org-todo
2648 :type '(choice
2649 (const :tag "Yes, only for TODO entries" t)
2650 (const :tag "Yes, including all entries" all-headlines)
2651 (repeat :tag "Yes, for TODOs in this list"
2652 (string :tag "TODO keyword"))
2653 (list :tag "Yes, for TODOs and DONEs in these lists"
2654 (repeat (string :tag "TODO keyword"))
2655 (repeat (string :tag "DONE keyword")))
2656 (other :tag "No TODO statistics" nil)))
2658 (defcustom org-hierarchical-todo-statistics t
2659 "Non-nil means TODO statistics covers just direct children.
2660 When nil, all entries in the subtree are considered.
2661 This has only an effect if `org-provide-todo-statistics' is set.
2662 To set this to nil for only a single subtree, use a COOKIE_DATA
2663 property and include the word \"recursive\" into the value."
2664 :group 'org-todo
2665 :type 'boolean)
2667 (defcustom org-after-todo-state-change-hook nil
2668 "Hook which is run after the state of a TODO item was changed.
2669 The new state (a string with a TODO keyword, or nil) is available in the
2670 Lisp variable `org-state'."
2671 :group 'org-todo
2672 :type 'hook)
2674 (defvar org-blocker-hook nil
2675 "Hook for functions that are allowed to block a state change.
2677 Functions in this hook should not modify the buffer.
2678 Each function gets as its single argument a property list,
2679 see `org-trigger-hook' for more information about this list.
2681 If any of the functions in this hook returns nil, the state change
2682 is blocked.")
2684 (defvar org-trigger-hook nil
2685 "Hook for functions that are triggered by a state change.
2687 Each function gets as its single argument a property list with at
2688 least the following elements:
2690 (:type type-of-change :position pos-at-entry-start
2691 :from old-state :to new-state)
2693 Depending on the type, more properties may be present.
2695 This mechanism is currently implemented for:
2697 TODO state changes
2698 ------------------
2699 :type todo-state-change
2700 :from previous state (keyword as a string), or nil, or a symbol
2701 `todo' or `done', to indicate the general type of state.
2702 :to new state, like in :from")
2704 (defcustom org-enforce-todo-dependencies nil
2705 "Non-nil means undone TODO entries will block switching the parent to DONE.
2706 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
2707 be blocked if any prior sibling is not yet done.
2708 Finally, if the parent is blocked because of ordered siblings of its own,
2709 the child will also be blocked."
2710 :set (lambda (var val)
2711 (set var val)
2712 (if val
2713 (add-hook 'org-blocker-hook
2714 'org-block-todo-from-children-or-siblings-or-parent)
2715 (remove-hook 'org-blocker-hook
2716 'org-block-todo-from-children-or-siblings-or-parent)))
2717 :group 'org-todo
2718 :type 'boolean)
2720 (defcustom org-enforce-todo-checkbox-dependencies nil
2721 "Non-nil means unchecked boxes will block switching the parent to DONE.
2722 When this is nil, checkboxes have no influence on switching TODO states.
2723 When non-nil, you first need to check off all check boxes before the TODO
2724 entry can be switched to DONE.
2725 This variable needs to be set before org.el is loaded, and you need to
2726 restart Emacs after a change to make the change effective. The only way
2727 to change is while Emacs is running is through the customize interface."
2728 :set (lambda (var val)
2729 (set var val)
2730 (if val
2731 (add-hook 'org-blocker-hook
2732 'org-block-todo-from-checkboxes)
2733 (remove-hook 'org-blocker-hook
2734 'org-block-todo-from-checkboxes)))
2735 :group 'org-todo
2736 :type 'boolean)
2738 (defcustom org-treat-insert-todo-heading-as-state-change nil
2739 "Non-nil means inserting a TODO heading is treated as state change.
2740 So when the command \\[org-insert-todo-heading] is used, state change
2741 logging will apply if appropriate. When nil, the new TODO item will
2742 be inserted directly, and no logging will take place."
2743 :group 'org-todo
2744 :type 'boolean)
2746 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
2747 "Non-nil means switching TODO states with S-cursor counts as state change.
2748 This is the default behavior. However, setting this to nil allows a
2749 convenient way to select a TODO state and bypass any logging associated
2750 with that."
2751 :group 'org-todo
2752 :type 'boolean)
2754 (defcustom org-todo-state-tags-triggers nil
2755 "Tag changes that should be triggered by TODO state changes.
2756 This is a list. Each entry is
2758 (state-change (tag . flag) .......)
2760 State-change can be a string with a state, and empty string to indicate the
2761 state that has no TODO keyword, or it can be one of the symbols `todo'
2762 or `done', meaning any not-done or done state, respectively."
2763 :group 'org-todo
2764 :group 'org-tags
2765 :type '(repeat
2766 (cons (choice :tag "When changing to"
2767 (const :tag "Not-done state" todo)
2768 (const :tag "Done state" done)
2769 (string :tag "State"))
2770 (repeat
2771 (cons :tag "Tag action"
2772 (string :tag "Tag")
2773 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
2775 (defcustom org-log-done nil
2776 "Information to record when a task moves to the DONE state.
2778 Possible values are:
2780 nil Don't add anything, just change the keyword
2781 time Add a time stamp to the task
2782 note Prompt for a note and add it with template `org-log-note-headings'
2784 This option can also be set with on a per-file-basis with
2786 #+STARTUP: nologdone
2787 #+STARTUP: logdone
2788 #+STARTUP: lognotedone
2790 You can have local logging settings for a subtree by setting the LOGGING
2791 property to one or more of these keywords."
2792 :group 'org-todo
2793 :group 'org-progress
2794 :type '(choice
2795 (const :tag "No logging" nil)
2796 (const :tag "Record CLOSED timestamp" time)
2797 (const :tag "Record CLOSED timestamp with note." note)))
2799 ;; Normalize old uses of org-log-done.
2800 (cond
2801 ((eq org-log-done t) (setq org-log-done 'time))
2802 ((and (listp org-log-done) (memq 'done org-log-done))
2803 (setq org-log-done 'note)))
2805 (defcustom org-log-reschedule nil
2806 "Information to record when the scheduling date of a tasks is modified.
2808 Possible values are:
2810 nil Don't add anything, just change the date
2811 time Add a time stamp to the task
2812 note Prompt for a note and add it with template `org-log-note-headings'
2814 This option can also be set with on a per-file-basis with
2816 #+STARTUP: nologreschedule
2817 #+STARTUP: logreschedule
2818 #+STARTUP: lognotereschedule"
2819 :group 'org-todo
2820 :group 'org-progress
2821 :type '(choice
2822 (const :tag "No logging" nil)
2823 (const :tag "Record timestamp" time)
2824 (const :tag "Record timestamp with note." note)))
2826 (defcustom org-log-redeadline nil
2827 "Information to record when the deadline date of a tasks is modified.
2829 Possible values are:
2831 nil Don't add anything, just change the date
2832 time Add a time stamp to the task
2833 note Prompt for a note and add it with template `org-log-note-headings'
2835 This option can also be set with on a per-file-basis with
2837 #+STARTUP: nologredeadline
2838 #+STARTUP: logredeadline
2839 #+STARTUP: lognoteredeadline
2841 You can have local logging settings for a subtree by setting the LOGGING
2842 property to one or more of these keywords."
2843 :group 'org-todo
2844 :group 'org-progress
2845 :type '(choice
2846 (const :tag "No logging" nil)
2847 (const :tag "Record timestamp" time)
2848 (const :tag "Record timestamp with note." note)))
2850 (defcustom org-log-note-clock-out nil
2851 "Non-nil means record a note when clocking out of an item.
2852 This can also be configured on a per-file basis by adding one of
2853 the following lines anywhere in the buffer:
2855 #+STARTUP: lognoteclock-out
2856 #+STARTUP: nolognoteclock-out"
2857 :group 'org-todo
2858 :group 'org-progress
2859 :type 'boolean)
2861 (defcustom org-log-done-with-time t
2862 "Non-nil means the CLOSED time stamp will contain date and time.
2863 When nil, only the date will be recorded."
2864 :group 'org-progress
2865 :type 'boolean)
2867 (defcustom org-log-note-headings
2868 '((done . "CLOSING NOTE %t")
2869 (state . "State %-12s from %-12S %t")
2870 (note . "Note taken on %t")
2871 (reschedule . "Rescheduled from %S on %t")
2872 (delschedule . "Not scheduled, was %S on %t")
2873 (redeadline . "New deadline from %S on %t")
2874 (deldeadline . "Removed deadline, was %S on %t")
2875 (refile . "Refiled on %t")
2876 (clock-out . ""))
2877 "Headings for notes added to entries.
2879 The value is an alist, with the car being a symbol indicating the
2880 note context, and the cdr is the heading to be used. The heading
2881 may also be the empty string. The following placeholders can be
2882 used:
2884 %t a time stamp.
2885 %T an active time stamp instead the default inactive one
2886 %d a short-format time stamp.
2887 %D an active short-format time stamp.
2888 %s the new TODO state or time stamp (inactive), in double quotes.
2889 %S the old TODO state or time stamp (inactive), in double quotes.
2890 %u the user name.
2891 %U full user name.
2893 In fact, it is not a good idea to change the `state' entry,
2894 because Agenda Log mode depends on the format of these entries."
2895 :group 'org-todo
2896 :group 'org-progress
2897 :type '(list :greedy t
2898 (cons (const :tag "Heading when closing an item" done) string)
2899 (cons (const :tag
2900 "Heading when changing todo state (todo sequence only)"
2901 state) string)
2902 (cons (const :tag "Heading when just taking a note" note) string)
2903 (cons (const :tag "Heading when rescheduling" reschedule) string)
2904 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2905 (cons (const :tag "Heading when changing deadline" redeadline) string)
2906 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2907 (cons (const :tag "Heading when refiling" refile) string)
2908 (cons (const :tag "Heading when clocking out" clock-out) string)))
2910 (unless (assq 'note org-log-note-headings)
2911 (push '(note . "%t") org-log-note-headings))
2913 (defcustom org-log-into-drawer nil
2914 "Non-nil means insert state change notes and time stamps into a drawer.
2915 When nil, state changes notes will be inserted after the headline and
2916 any scheduling and clock lines, but not inside a drawer.
2918 The value of this variable should be the name of the drawer to use.
2919 LOGBOOK is proposed as the default drawer for this purpose, you can
2920 also set this to a string to define the drawer of your choice.
2922 A value of t is also allowed, representing \"LOGBOOK\".
2924 A value of t or nil can also be set with on a per-file-basis with
2926 #+STARTUP: logdrawer
2927 #+STARTUP: nologdrawer
2929 If this variable is set, `org-log-state-notes-insert-after-drawers'
2930 will be ignored.
2932 You can set the property LOG_INTO_DRAWER to overrule this setting for
2933 a subtree.
2935 Do not check directly this variable in a Lisp program. Call
2936 function `org-log-into-drawer' instead."
2937 :group 'org-todo
2938 :group 'org-progress
2939 :type '(choice
2940 (const :tag "Not into a drawer" nil)
2941 (const :tag "LOGBOOK" t)
2942 (string :tag "Other")))
2944 (org-defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer)
2946 (defun org-log-into-drawer ()
2947 "Name of the log drawer, as a string, or nil.
2948 This is the value of `org-log-into-drawer'. However, if the
2949 current entry has or inherits a LOG_INTO_DRAWER property, it will
2950 be used instead of the default value."
2951 (let ((p (org-entry-get nil "LOG_INTO_DRAWER" 'inherit t)))
2952 (cond ((equal p "nil") nil)
2953 ((equal p "t") "LOGBOOK")
2954 ((stringp p) p)
2955 (p "LOGBOOK")
2956 ((stringp org-log-into-drawer) org-log-into-drawer)
2957 (org-log-into-drawer "LOGBOOK"))))
2959 (defcustom org-log-state-notes-insert-after-drawers nil
2960 "Non-nil means insert state change notes after any drawers in entry.
2961 Only the drawers that *immediately* follow the headline and the
2962 deadline/scheduled line are skipped.
2963 When nil, insert notes right after the heading and perhaps the line
2964 with deadline/scheduling if present.
2966 This variable will have no effect if `org-log-into-drawer' is
2967 set."
2968 :group 'org-todo
2969 :group 'org-progress
2970 :type 'boolean)
2972 (defcustom org-log-states-order-reversed t
2973 "Non-nil means the latest state note will be directly after heading.
2974 When nil, the state change notes will be ordered according to time.
2976 This option can also be set with on a per-file-basis with
2978 #+STARTUP: logstatesreversed
2979 #+STARTUP: nologstatesreversed"
2980 :group 'org-todo
2981 :group 'org-progress
2982 :type 'boolean)
2984 (defcustom org-todo-repeat-to-state nil
2985 "The TODO state to which a repeater should return the repeating task.
2986 By default this is the first task in a TODO sequence, or the previous state
2987 in a TODO_TYP set. But you can specify another task here.
2988 alternatively, set the :REPEAT_TO_STATE: property of the entry."
2989 :group 'org-todo
2990 :version "24.1"
2991 :type '(choice (const :tag "Head of sequence" nil)
2992 (string :tag "Specific state")))
2994 (defcustom org-log-repeat 'time
2995 "Non-nil means record moving through the DONE state when triggering repeat.
2996 An auto-repeating task is immediately switched back to TODO when
2997 marked DONE. If you are not logging state changes (by adding \"@\"
2998 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2999 record a closing note, there will be no record of the task moving
3000 through DONE. This variable forces taking a note anyway.
3002 nil Don't force a record
3003 time Record a time stamp
3004 note Prompt for a note and add it with template `org-log-note-headings'
3006 This option can also be set with on a per-file-basis with
3008 #+STARTUP: nologrepeat
3009 #+STARTUP: logrepeat
3010 #+STARTUP: lognoterepeat
3012 You can have local logging settings for a subtree by setting the LOGGING
3013 property to one or more of these keywords."
3014 :group 'org-todo
3015 :group 'org-progress
3016 :type '(choice
3017 (const :tag "Don't force a record" nil)
3018 (const :tag "Force recording the DONE state" time)
3019 (const :tag "Force recording a note with the DONE state" note)))
3022 (defgroup org-priorities nil
3023 "Priorities in Org-mode."
3024 :tag "Org Priorities"
3025 :group 'org-todo)
3027 (defcustom org-enable-priority-commands t
3028 "Non-nil means priority commands are active.
3029 When nil, these commands will be disabled, so that you never accidentally
3030 set a priority."
3031 :group 'org-priorities
3032 :type 'boolean)
3034 (defcustom org-highest-priority ?A
3035 "The highest priority of TODO items. A character like ?A, ?B etc.
3036 Must have a smaller ASCII number than `org-lowest-priority'."
3037 :group 'org-priorities
3038 :type 'character)
3040 (defcustom org-lowest-priority ?C
3041 "The lowest priority of TODO items. A character like ?A, ?B etc.
3042 Must have a larger ASCII number than `org-highest-priority'."
3043 :group 'org-priorities
3044 :type 'character)
3046 (defcustom org-default-priority ?B
3047 "The default priority of TODO items.
3048 This is the priority an item gets if no explicit priority is given.
3049 When starting to cycle on an empty priority the first step in the cycle
3050 depends on `org-priority-start-cycle-with-default'. The resulting first
3051 step priority must not exceed the range from `org-highest-priority' to
3052 `org-lowest-priority' which means that `org-default-priority' has to be
3053 in this range exclusive or inclusive the range boundaries. Else the
3054 first step refuses to set the default and the second will fall back
3055 to (depending on the command used) the highest or lowest priority."
3056 :group 'org-priorities
3057 :type 'character)
3059 (defcustom org-priority-start-cycle-with-default t
3060 "Non-nil means start with default priority when starting to cycle.
3061 When this is nil, the first step in the cycle will be (depending on the
3062 command used) one higher or lower than the default priority.
3063 See also `org-default-priority'."
3064 :group 'org-priorities
3065 :type 'boolean)
3067 (defcustom org-get-priority-function nil
3068 "Function to extract the priority from a string.
3069 The string is normally the headline. If this is nil Org computes the
3070 priority from the priority cookie like [#A] in the headline. It returns
3071 an integer, increasing by 1000 for each priority level.
3072 The user can set a different function here, which should take a string
3073 as an argument and return the numeric priority."
3074 :group 'org-priorities
3075 :version "24.1"
3076 :type '(choice
3077 (const nil)
3078 (function)))
3080 (defgroup org-time nil
3081 "Options concerning time stamps and deadlines in Org-mode."
3082 :tag "Org Time"
3083 :group 'org)
3085 (defcustom org-time-stamp-rounding-minutes '(0 5)
3086 "Number of minutes to round time stamps to.
3087 \\<org-mode-map>\
3088 These are two values, the first applies when first creating a time stamp.
3089 The second applies when changing it with the commands `S-up' and `S-down'.
3090 When changing the time stamp, this means that it will change in steps
3091 of N minutes, as given by the second value.
3093 When a setting is 0 or 1, insert the time unmodified. Useful rounding
3094 numbers should be factors of 60, so for example 5, 10, 15.
3096 When this is larger than 1, you can still force an exact time stamp by using
3097 a double prefix argument to a time stamp command like \
3098 `\\[org-time-stamp]' or `\\[org-time-stamp-inactive],
3099 and by using a prefix arg to `S-up/down' to specify the exact number
3100 of minutes to shift."
3101 :group 'org-time
3102 :get (lambda (var) ; Make sure both elements are there
3103 (if (integerp (default-value var))
3104 (list (default-value var) 5)
3105 (default-value var)))
3106 :type '(list
3107 (integer :tag "when inserting times")
3108 (integer :tag "when modifying times")))
3110 ;; Normalize old customizations of this variable.
3111 (when (integerp org-time-stamp-rounding-minutes)
3112 (setq org-time-stamp-rounding-minutes
3113 (list org-time-stamp-rounding-minutes
3114 org-time-stamp-rounding-minutes)))
3116 (defcustom org-display-custom-times nil
3117 "Non-nil means overlay custom formats over all time stamps.
3118 The formats are defined through the variable `org-time-stamp-custom-formats'.
3119 To turn this on on a per-file basis, insert anywhere in the file:
3120 #+STARTUP: customtime"
3121 :group 'org-time
3122 :set 'set-default
3123 :type 'sexp)
3124 (make-variable-buffer-local 'org-display-custom-times)
3126 (defcustom org-time-stamp-custom-formats
3127 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
3128 "Custom formats for time stamps. See `format-time-string' for the syntax.
3129 These are overlaid over the default ISO format if the variable
3130 `org-display-custom-times' is set. Time like %H:%M should be at the
3131 end of the second format. The custom formats are also honored by export
3132 commands, if custom time display is turned on at the time of export."
3133 :group 'org-time
3134 :type 'sexp)
3136 (defun org-time-stamp-format (&optional long inactive)
3137 "Get the right format for a time string."
3138 (let ((f (if long (cdr org-time-stamp-formats)
3139 (car org-time-stamp-formats))))
3140 (if inactive
3141 (concat "[" (substring f 1 -1) "]")
3142 f)))
3144 (defcustom org-time-clocksum-format
3145 '(:days "%dd " :hours "%d" :require-hours t :minutes ":%02d" :require-minutes t)
3146 "The format string used when creating CLOCKSUM lines.
3147 This is also used when Org mode generates a time duration.
3149 The value can be a single format string containing two
3150 %-sequences, which will be filled with the number of hours and
3151 minutes in that order.
3153 Alternatively, the value can be a plist associating any of the
3154 keys :years, :months, :weeks, :days, :hours or :minutes with
3155 format strings. The time duration is formatted using only the
3156 time components that are needed and concatenating the results.
3157 If a time unit in absent, it falls back to the next smallest
3158 unit.
3160 The keys :require-years, :require-months, :require-days,
3161 :require-weeks, :require-hours, :require-minutes are also
3162 meaningful. A non-nil value for these keys indicates that the
3163 corresponding time component should always be included, even if
3164 its value is 0.
3167 For example,
3169 (:days \"%dd\" :hours \"%d\" :require-hours t :minutes \":%02d\"
3170 :require-minutes t)
3172 means durations longer than a day will be expressed in days,
3173 hours and minutes, and durations less than a day will always be
3174 expressed in hours and minutes (even for durations less than an
3175 hour).
3177 The value
3179 (:days \"%dd\" :minutes \"%dm\")
3181 means durations longer than a day will be expressed in days and
3182 minutes, and durations less than a day will be expressed entirely
3183 in minutes (even for durations longer than an hour)."
3184 :group 'org-time
3185 :group 'org-clock
3186 :version "24.4"
3187 :package-version '(Org . "8.0")
3188 :type '(choice (string :tag "Format string")
3189 (set :tag "Plist"
3190 (group :inline t (const :tag "Years" :years)
3191 (string :tag "Format string"))
3192 (group :inline t
3193 (const :tag "Always show years" :require-years)
3194 (const t))
3195 (group :inline t (const :tag "Months" :months)
3196 (string :tag "Format string"))
3197 (group :inline t
3198 (const :tag "Always show months" :require-months)
3199 (const t))
3200 (group :inline t (const :tag "Weeks" :weeks)
3201 (string :tag "Format string"))
3202 (group :inline t
3203 (const :tag "Always show weeks" :require-weeks)
3204 (const t))
3205 (group :inline t (const :tag "Days" :days)
3206 (string :tag "Format string"))
3207 (group :inline t
3208 (const :tag "Always show days" :require-days)
3209 (const t))
3210 (group :inline t (const :tag "Hours" :hours)
3211 (string :tag "Format string"))
3212 (group :inline t
3213 (const :tag "Always show hours" :require-hours)
3214 (const t))
3215 (group :inline t (const :tag "Minutes" :minutes)
3216 (string :tag "Format string"))
3217 (group :inline t
3218 (const :tag "Always show minutes" :require-minutes)
3219 (const t)))))
3221 (defcustom org-time-clocksum-use-fractional nil
3222 "When non-nil, \\[org-clock-display] uses fractional times.
3223 See `org-time-clocksum-format' for more on time clock formats."
3224 :group 'org-time
3225 :group 'org-clock
3226 :version "24.3"
3227 :type 'boolean)
3229 (defcustom org-time-clocksum-use-effort-durations nil
3230 "When non-nil, \\[org-clock-display] uses effort durations.
3231 E.g. by default, one day is considered to be a 8 hours effort,
3232 so a task that has been clocked for 16 hours will be displayed
3233 as during 2 days in the clock display or in the clocktable.
3235 See `org-effort-durations' on how to set effort durations
3236 and `org-time-clocksum-format' for more on time clock formats."
3237 :group 'org-time
3238 :group 'org-clock
3239 :version "24.4"
3240 :package-version '(Org . "8.0")
3241 :type 'boolean)
3243 (defcustom org-time-clocksum-fractional-format "%.2f"
3244 "The format string used when creating CLOCKSUM lines,
3245 or when Org mode generates a time duration, if
3246 `org-time-clocksum-use-fractional' is enabled.
3248 The value can be a single format string containing one
3249 %-sequence, which will be filled with the number of hours as
3250 a float.
3252 Alternatively, the value can be a plist associating any of the
3253 keys :years, :months, :weeks, :days, :hours or :minutes with
3254 a format string. The time duration is formatted using the
3255 largest time unit which gives a non-zero integer part. If all
3256 specified formats have zero integer part, the smallest time unit
3257 is used."
3258 :group 'org-time
3259 :type '(choice (string :tag "Format string")
3260 (set (group :inline t (const :tag "Years" :years)
3261 (string :tag "Format string"))
3262 (group :inline t (const :tag "Months" :months)
3263 (string :tag "Format string"))
3264 (group :inline t (const :tag "Weeks" :weeks)
3265 (string :tag "Format string"))
3266 (group :inline t (const :tag "Days" :days)
3267 (string :tag "Format string"))
3268 (group :inline t (const :tag "Hours" :hours)
3269 (string :tag "Format string"))
3270 (group :inline t (const :tag "Minutes" :minutes)
3271 (string :tag "Format string")))))
3273 (defcustom org-deadline-warning-days 14
3274 "Number of days before expiration during which a deadline becomes active.
3275 This variable governs the display in sparse trees and in the agenda.
3276 When 0 or negative, it means use this number (the absolute value of it)
3277 even if a deadline has a different individual lead time specified.
3279 Custom commands can set this variable in the options section."
3280 :group 'org-time
3281 :group 'org-agenda-daily/weekly
3282 :type 'integer)
3284 (defcustom org-scheduled-delay-days 0
3285 "Number of days before a scheduled item becomes active.
3286 This variable governs the display in sparse trees and in the agenda.
3287 The default value (i.e. 0) means: don't delay scheduled item.
3288 When negative, it means use this number (the absolute value of it)
3289 even if a scheduled item has a different individual delay time
3290 specified.
3292 Custom commands can set this variable in the options section."
3293 :group 'org-time
3294 :group 'org-agenda-daily/weekly
3295 :version "24.4"
3296 :package-version '(Org . "8.0")
3297 :type 'integer)
3299 (defcustom org-read-date-prefer-future t
3300 "Non-nil means assume future for incomplete date input from user.
3301 This affects the following situations:
3302 1. The user gives a month but not a year.
3303 For example, if it is April and you enter \"feb 2\", this will be read
3304 as Feb 2, *next* year. \"May 5\", however, will be this year.
3305 2. The user gives a day, but no month.
3306 For example, if today is the 15th, and you enter \"3\", Org-mode will
3307 read this as the third of *next* month. However, if you enter \"17\",
3308 it will be considered as *this* month.
3310 If you set this variable to the symbol `time', then also the following
3311 will work:
3313 3. If the user gives a time.
3314 If the time is before now, it will be interpreted as tomorrow.
3316 Currently none of this works for ISO week specifications.
3318 When this option is nil, the current day, month and year will always be
3319 used as defaults.
3321 See also `org-agenda-jump-prefer-future'."
3322 :group 'org-time
3323 :type '(choice
3324 (const :tag "Never" nil)
3325 (const :tag "Check month and day" t)
3326 (const :tag "Check month, day, and time" time)))
3328 (defcustom org-agenda-jump-prefer-future 'org-read-date-prefer-future
3329 "Should the agenda jump command prefer the future for incomplete dates?
3330 The default is to do the same as configured in `org-read-date-prefer-future'.
3331 But you can also set a deviating value here.
3332 This may t or nil, or the symbol `org-read-date-prefer-future'."
3333 :group 'org-agenda
3334 :group 'org-time
3335 :version "24.1"
3336 :type '(choice
3337 (const :tag "Use org-read-date-prefer-future"
3338 org-read-date-prefer-future)
3339 (const :tag "Never" nil)
3340 (const :tag "Always" t)))
3342 (defcustom org-read-date-force-compatible-dates t
3343 "Should date/time prompt force dates that are guaranteed to work in Emacs?
3345 Depending on the system Emacs is running on, certain dates cannot
3346 be represented with the type used internally to represent time.
3347 Dates between 1970-1-1 and 2038-1-1 can always be represented
3348 correctly. Some systems allow for earlier dates, some for later,
3349 some for both. One way to find out it to insert any date into an
3350 Org buffer, putting the cursor on the year and hitting S-up and
3351 S-down to test the range.
3353 When this variable is set to t, the date/time prompt will not let
3354 you specify dates outside the 1970-2037 range, so it is certain that
3355 these dates will work in whatever version of Emacs you are
3356 running, and also that you can move a file from one Emacs implementation
3357 to another. WHenever Org is forcing the year for you, it will display
3358 a message and beep.
3360 When this variable is nil, Org will check if the date is
3361 representable in the specific Emacs implementation you are using.
3362 If not, it will force a year, usually the current year, and beep
3363 to remind you. Currently this setting is not recommended because
3364 the likelihood that you will open your Org files in an Emacs that
3365 has limited date range is not negligible.
3367 A workaround for this problem is to use diary sexp dates for time
3368 stamps outside of this range."
3369 :group 'org-time
3370 :version "24.1"
3371 :type 'boolean)
3373 (defcustom org-read-date-display-live t
3374 "Non-nil means display current interpretation of date prompt live.
3375 This display will be in an overlay, in the minibuffer."
3376 :group 'org-time
3377 :type 'boolean)
3379 (defcustom org-read-date-popup-calendar t
3380 "Non-nil means pop up a calendar when prompting for a date.
3381 In the calendar, the date can be selected with mouse-1. However, the
3382 minibuffer will also be active, and you can simply enter the date as well.
3383 When nil, only the minibuffer will be available."
3384 :group 'org-time
3385 :type 'boolean)
3386 (org-defvaralias 'org-popup-calendar-for-date-prompt
3387 'org-read-date-popup-calendar)
3389 (make-obsolete-variable
3390 'org-read-date-minibuffer-setup-hook
3391 "Set `org-read-date-minibuffer-local-map' instead." "24.4")
3392 (defcustom org-read-date-minibuffer-setup-hook nil
3393 "Hook to be used to set up keys for the date/time interface.
3394 Add key definitions to `minibuffer-local-map', which will be a
3395 temporary copy.
3397 WARNING: This option is obsolete, you should use
3398 `org-read-date-minibuffer-local-map' to set up keys."
3399 :group 'org-time
3400 :type 'hook)
3402 (defcustom org-extend-today-until 0
3403 "The hour when your day really ends. Must be an integer.
3404 This has influence for the following applications:
3405 - When switching the agenda to \"today\". It it is still earlier than
3406 the time given here, the day recognized as TODAY is actually yesterday.
3407 - When a date is read from the user and it is still before the time given
3408 here, the current date and time will be assumed to be yesterday, 23:59.
3409 Also, timestamps inserted in capture templates follow this rule.
3411 IMPORTANT: This is a feature whose implementation is and likely will
3412 remain incomplete. Really, it is only here because past midnight seems to
3413 be the favorite working time of John Wiegley :-)"
3414 :group 'org-time
3415 :type 'integer)
3417 (defcustom org-use-effective-time nil
3418 "If non-nil, consider `org-extend-today-until' when creating timestamps.
3419 For example, if `org-extend-today-until' is 8, and it's 4am, then the
3420 \"effective time\" of any timestamps between midnight and 8am will be
3421 23:59 of the previous day."
3422 :group 'org-time
3423 :version "24.1"
3424 :type 'boolean)
3426 (defcustom org-use-last-clock-out-time-as-effective-time nil
3427 "When non-nil, use the last clock out time for `org-todo'.
3428 Note that this option has precedence over the combined use of
3429 `org-use-effective-time' and `org-extend-today-until'."
3430 :group 'org-time
3431 :version "24.4"
3432 :package-version '(Org . "8.0")
3433 :type 'boolean)
3435 (defcustom org-edit-timestamp-down-means-later nil
3436 "Non-nil means S-down will increase the time in a time stamp.
3437 When nil, S-up will increase."
3438 :group 'org-time
3439 :type 'boolean)
3441 (defcustom org-calendar-follow-timestamp-change t
3442 "Non-nil means make the calendar window follow timestamp changes.
3443 When a timestamp is modified and the calendar window is visible, it will be
3444 moved to the new date."
3445 :group 'org-time
3446 :type 'boolean)
3448 (defgroup org-tags nil
3449 "Options concerning tags in Org-mode."
3450 :tag "Org Tags"
3451 :group 'org)
3453 (defcustom org-tag-alist nil
3454 "Default tags available in Org files.
3456 The value of this variable is an alist. Associations either:
3458 (TAG)
3459 (TAG . SELECT)
3460 (SPECIAL)
3462 where TAG is a tag as a string, SELECT is a character, used to
3463 select that tag through the fast tag selection interface, and
3464 SPECIAL is one of the following keywords: `:startgroup',
3465 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3466 `:newline'. These keywords are used to define a hierarchy of
3467 tags. See manual for details.
3469 When this variable is nil, Org mode bases tag input on what is
3470 already in the buffer. The value can be overridden locally by
3471 using a TAGS keyword, e.g.,
3473 #+TAGS: tag1 tag2
3475 See also `org-tag-persistent-alist' to sidestep this behavior."
3476 :group 'org-tags
3477 :type '(repeat
3478 (choice
3479 (cons (string :tag "Tag name")
3480 (character :tag "Access char"))
3481 (const :tag "Start radio group" (:startgroup))
3482 (const :tag "Start tag group, non distinct" (:startgrouptag))
3483 (const :tag "Group tags delimiter" (:grouptags))
3484 (const :tag "End radio group" (:endgroup))
3485 (const :tag "End tag group, non distinct" (:endgrouptag))
3486 (const :tag "New line" (:newline)))))
3488 (defcustom org-tag-persistent-alist nil
3489 "Tags always available in Org files.
3491 The value of this variable is an alist. Associations either:
3493 (TAG)
3494 (TAG . SELECT)
3495 (SPECIAL)
3497 where TAG is a tag as a string, SELECT is a character, used to
3498 select that tag through the fast tag selection interface, and
3499 SPECIAL is one of the following keywords: `:startgroup',
3500 `:startgrouptag', `:grouptags', `:engroup', `:endgrouptag' or
3501 `:newline'. These keywords are used to define a hierarchy of
3502 tags. See manual for details.
3504 Unlike to `org-tag-alist', tags defined in this variable do not
3505 depend on a local TAGS keyword. Instead, to disable these tags
3506 on a per-file basis, insert anywhere in the file:
3508 #+STARTUP: noptag"
3509 :group 'org-tags
3510 :type '(repeat
3511 (choice
3512 (cons (string :tag "Tag name")
3513 (character :tag "Access char"))
3514 (const :tag "Start radio group" (:startgroup))
3515 (const :tag "Start tag group, non distinct" (:startgrouptag))
3516 (const :tag "Group tags delimiter" (:grouptags))
3517 (const :tag "End radio group" (:endgroup))
3518 (const :tag "End tag group, non distinct" (:endgrouptag))
3519 (const :tag "New line" (:newline)))))
3521 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
3522 "If non-nil, always offer completion for all tags of all agenda files.
3523 Instead of customizing this variable directly, you might want to
3524 set it locally for capture buffers, because there no list of
3525 tags in that file can be created dynamically (there are none).
3527 (add-hook \\='org-capture-mode-hook
3528 (lambda ()
3529 (setq-local org-complete-tags-always-offer-all-agenda-tags t)))"
3530 :group 'org-tags
3531 :version "24.1"
3532 :type 'boolean)
3534 (defvar org-file-tags nil
3535 "List of tags that can be inherited by all entries in the file.
3536 The tags will be inherited if the variable `org-use-tag-inheritance'
3537 says they should be.
3538 This variable is populated from #+FILETAGS lines.")
3540 (defcustom org-use-fast-tag-selection 'auto
3541 "Non-nil means use fast tag selection scheme.
3542 This is a special interface to select and deselect tags with single keys.
3543 When nil, fast selection is never used.
3544 When the symbol `auto', fast selection is used if and only if selection
3545 characters for tags have been configured, either through the variable
3546 `org-tag-alist' or through a #+TAGS line in the buffer.
3547 When t, fast selection is always used and selection keys are assigned
3548 automatically if necessary."
3549 :group 'org-tags
3550 :type '(choice
3551 (const :tag "Always" t)
3552 (const :tag "Never" nil)
3553 (const :tag "When selection characters are configured" auto)))
3555 (defcustom org-fast-tag-selection-single-key nil
3556 "Non-nil means fast tag selection exits after first change.
3557 When nil, you have to press RET to exit it.
3558 During fast tag selection, you can toggle this flag with `C-c'.
3559 This variable can also have the value `expert'. In this case, the window
3560 displaying the tags menu is not even shown, until you press C-c again."
3561 :group 'org-tags
3562 :type '(choice
3563 (const :tag "No" nil)
3564 (const :tag "Yes" t)
3565 (const :tag "Expert" expert)))
3567 (defvar org-fast-tag-selection-include-todo nil
3568 "Non-nil means fast tags selection interface will also offer TODO states.
3569 This is an undocumented feature, you should not rely on it.")
3571 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
3572 "The column to which tags should be indented in a headline.
3573 If this number is positive, it specifies the column. If it is negative,
3574 it means that the tags should be flushright to that column. For example,
3575 -80 works well for a normal 80 character screen.
3576 When 0, place tags directly after headline text, with only one space in
3577 between."
3578 :group 'org-tags
3579 :type 'integer)
3581 (defcustom org-auto-align-tags t
3582 "Non-nil keeps tags aligned when modifying headlines.
3583 Some operations (i.e. demoting) change the length of a headline and
3584 therefore shift the tags around. With this option turned on, after
3585 each such operation the tags are again aligned to `org-tags-column'."
3586 :group 'org-tags
3587 :type 'boolean)
3589 (defcustom org-use-tag-inheritance t
3590 "Non-nil means tags in levels apply also for sublevels.
3591 When nil, only the tags directly given in a specific line apply there.
3592 This may also be a list of tags that should be inherited, or a regexp that
3593 matches tags that should be inherited. Additional control is possible
3594 with the variable `org-tags-exclude-from-inheritance' which gives an
3595 explicit list of tags to be excluded from inheritance, even if the value of
3596 `org-use-tag-inheritance' would select it for inheritance.
3598 If this option is t, a match early-on in a tree can lead to a large
3599 number of matches in the subtree when constructing the agenda or creating
3600 a sparse tree. If you only want to see the first match in a tree during
3601 a search, check out the variable `org-tags-match-list-sublevels'."
3602 :group 'org-tags
3603 :type '(choice
3604 (const :tag "Not" nil)
3605 (const :tag "Always" t)
3606 (repeat :tag "Specific tags" (string :tag "Tag"))
3607 (regexp :tag "Tags matched by regexp")))
3609 (defcustom org-tags-exclude-from-inheritance nil
3610 "List of tags that should never be inherited.
3611 This is a way to exclude a few tags from inheritance. For way to do
3612 the opposite, to actively allow inheritance for selected tags,
3613 see the variable `org-use-tag-inheritance'."
3614 :group 'org-tags
3615 :type '(repeat (string :tag "Tag")))
3617 (defun org-tag-inherit-p (tag)
3618 "Check if TAG is one that should be inherited."
3619 (cond
3620 ((member tag org-tags-exclude-from-inheritance) nil)
3621 ((eq org-use-tag-inheritance t) t)
3622 ((not org-use-tag-inheritance) nil)
3623 ((stringp org-use-tag-inheritance)
3624 (string-match org-use-tag-inheritance tag))
3625 ((listp org-use-tag-inheritance)
3626 (member tag org-use-tag-inheritance))
3627 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
3629 (defcustom org-tags-match-list-sublevels t
3630 "Non-nil means list also sublevels of headlines matching a search.
3631 This variable applies to tags/property searches, and also to stuck
3632 projects because this search is based on a tags match as well.
3634 When set to the symbol `indented', sublevels are indented with
3635 leading dots.
3637 Because of tag inheritance (see variable `org-use-tag-inheritance'),
3638 the sublevels of a headline matching a tag search often also match
3639 the same search. Listing all of them can create very long lists.
3640 Setting this variable to nil causes subtrees of a match to be skipped.
3642 This variable is semi-obsolete and probably should always be true. It
3643 is better to limit inheritance to certain tags using the variables
3644 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
3645 :group 'org-tags
3646 :type '(choice
3647 (const :tag "No, don't list them" nil)
3648 (const :tag "Yes, do list them" t)
3649 (const :tag "List them, indented with leading dots" indented)))
3651 (defcustom org-tags-sort-function nil
3652 "When set, tags are sorted using this function as a comparator."
3653 :group 'org-tags
3654 :type '(choice
3655 (const :tag "No sorting" nil)
3656 (const :tag "Alphabetical" string<)
3657 (const :tag "Reverse alphabetical" string>)
3658 (function :tag "Custom function" nil)))
3660 (defvar org-tags-history nil
3661 "History of minibuffer reads for tags.")
3662 (defvar org-last-tags-completion-table nil
3663 "The last used completion table for tags.")
3664 (defvar org-after-tags-change-hook nil
3665 "Hook that is run after the tags in a line have changed.")
3667 (defgroup org-properties nil
3668 "Options concerning properties in Org-mode."
3669 :tag "Org Properties"
3670 :group 'org)
3672 (defcustom org-property-format "%-10s %s"
3673 "How property key/value pairs should be formatted by `indent-line'.
3674 When `indent-line' hits a property definition, it will format the line
3675 according to this format, mainly to make sure that the values are
3676 lined-up with respect to each other."
3677 :group 'org-properties
3678 :type 'string)
3680 (defcustom org-properties-postprocess-alist nil
3681 "Alist of properties and functions to adjust inserted values.
3682 Elements of this alist must be of the form
3684 ([string] [function])
3686 where [string] must be a property name and [function] must be a
3687 lambda expression: this lambda expression must take one argument,
3688 the value to adjust, and return the new value as a string.
3690 For example, this element will allow the property \"Remaining\"
3691 to be updated wrt the relation between the \"Effort\" property
3692 and the clock summary:
3694 ((\"Remaining\" (lambda(value)
3695 (let ((clocksum (org-clock-sum-current-item))
3696 (effort (org-duration-string-to-minutes
3697 (org-entry-get (point) \"Effort\"))))
3698 (org-minutes-to-clocksum-string (- effort clocksum))))))"
3699 :group 'org-properties
3700 :version "24.1"
3701 :type '(alist :key-type (string :tag "Property")
3702 :value-type (function :tag "Function")))
3704 (defcustom org-use-property-inheritance nil
3705 "Non-nil means properties apply also for sublevels.
3707 This setting is chiefly used during property searches. Turning it on can
3708 cause significant overhead when doing a search, which is why it is not
3709 on by default.
3711 When nil, only the properties directly given in the current entry count.
3712 When t, every property is inherited. The value may also be a list of
3713 properties that should have inheritance, or a regular expression matching
3714 properties that should be inherited.
3716 However, note that some special properties use inheritance under special
3717 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
3718 and the properties ending in \"_ALL\" when they are used as descriptor
3719 for valid values of a property.
3721 Note for programmers:
3722 When querying an entry with `org-entry-get', you can control if inheritance
3723 should be used. By default, `org-entry-get' looks only at the local
3724 properties. You can request inheritance by setting the inherit argument
3725 to t (to force inheritance) or to `selective' (to respect the setting
3726 in this variable)."
3727 :group 'org-properties
3728 :type '(choice
3729 (const :tag "Not" nil)
3730 (const :tag "Always" t)
3731 (repeat :tag "Specific properties" (string :tag "Property"))
3732 (regexp :tag "Properties matched by regexp")))
3734 (defun org-property-inherit-p (property)
3735 "Check if PROPERTY is one that should be inherited."
3736 (cond
3737 ((eq org-use-property-inheritance t) t)
3738 ((not org-use-property-inheritance) nil)
3739 ((stringp org-use-property-inheritance)
3740 (string-match org-use-property-inheritance property))
3741 ((listp org-use-property-inheritance)
3742 (member property org-use-property-inheritance))
3743 (t (error "Invalid setting of `org-use-property-inheritance'"))))
3745 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
3746 "The default column format, if no other format has been defined.
3747 This variable can be set on the per-file basis by inserting a line
3749 #+COLUMNS: %25ITEM ....."
3750 :group 'org-properties
3751 :type 'string)
3753 (defcustom org-columns-ellipses ".."
3754 "The ellipses to be used when a field in column view is truncated.
3755 When this is the empty string, as many characters as possible are shown,
3756 but then there will be no visual indication that the field has been truncated.
3757 When this is a string of length N, the last N characters of a truncated
3758 field are replaced by this string. If the column is narrower than the
3759 ellipses string, only part of the ellipses string will be shown."
3760 :group 'org-properties
3761 :type 'string)
3763 (defconst org-global-properties-fixed
3764 '(("VISIBILITY_ALL" . "folded children content all")
3765 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
3766 "List of property/value pairs that can be inherited by any entry.
3768 These are fixed values, for the preset properties. The user variable
3769 that can be used to add to this list is `org-global-properties'.
3771 The entries in this list are cons cells where the car is a property
3772 name and cdr is a string with the value. If the value represents
3773 multiple items like an \"_ALL\" property, separate the items by
3774 spaces.")
3776 (defcustom org-global-properties nil
3777 "List of property/value pairs that can be inherited by any entry.
3779 This list will be combined with the constant `org-global-properties-fixed'.
3781 The entries in this list are cons cells where the car is a property
3782 name and cdr is a string with the value.
3784 You can set buffer-local values for the same purpose in the variable
3785 `org-file-properties' this by adding lines like
3787 #+PROPERTY: NAME VALUE"
3788 :group 'org-properties
3789 :type '(repeat
3790 (cons (string :tag "Property")
3791 (string :tag "Value"))))
3793 (defvar-local org-file-properties nil
3794 "List of property/value pairs that can be inherited by any entry.
3795 Valid for the current buffer.
3796 This variable is populated from #+PROPERTY lines.")
3798 (defgroup org-agenda nil
3799 "Options concerning agenda views in Org-mode."
3800 :tag "Org Agenda"
3801 :group 'org)
3803 (defvar-local org-category nil
3804 "Variable used by org files to set a category for agenda display.
3805 Such files should use a file variable to set it, for example
3807 # -*- mode: org; org-category: \"ELisp\"
3809 or contain a special line
3811 #+CATEGORY: ELisp
3813 If the file does not specify a category, then file's base name
3814 is used instead.")
3815 (put 'org-category 'safe-local-variable (lambda (x) (or (symbolp x) (stringp x))))
3817 (defcustom org-agenda-files nil
3818 "The files to be used for agenda display.
3819 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
3820 \\[org-remove-file]. You can also use customize to edit the list.
3822 If an entry is a directory, all files in that directory that are matched by
3823 `org-agenda-file-regexp' will be part of the file list.
3825 If the value of the variable is not a list but a single file name, then
3826 the list of agenda files is actually stored and maintained in that file, one
3827 agenda file per line. In this file paths can be given relative to
3828 `org-directory'. Tilde expansion and environment variable substitution
3829 are also made."
3830 :group 'org-agenda
3831 :type '(choice
3832 (repeat :tag "List of files and directories" file)
3833 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
3835 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
3836 "Regular expression to match files for `org-agenda-files'.
3837 If any element in the list in that variable contains a directory instead
3838 of a normal file, all files in that directory that are matched by this
3839 regular expression will be included."
3840 :group 'org-agenda
3841 :type 'regexp)
3843 (defcustom org-agenda-text-search-extra-files nil
3844 "List of extra files to be searched by text search commands.
3845 These files will be searched in addition to the agenda files by the
3846 commands `org-search-view' (`\\[org-agenda] s') \
3847 and `org-occur-in-agenda-files'.
3848 Note that these files will only be searched for text search commands,
3849 not for the other agenda views like todo lists, tag searches or the weekly
3850 agenda. This variable is intended to list notes and possibly archive files
3851 that should also be searched by these two commands.
3852 In fact, if the first element in the list is the symbol `agenda-archives',
3853 then all archive files of all agenda files will be added to the search
3854 scope."
3855 :group 'org-agenda
3856 :type '(set :greedy t
3857 (const :tag "Agenda Archives" agenda-archives)
3858 (repeat :inline t (file))))
3860 (org-defvaralias 'org-agenda-multi-occur-extra-files
3861 'org-agenda-text-search-extra-files)
3863 (defcustom org-agenda-skip-unavailable-files nil
3864 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
3865 A nil value means to remove them, after a query, from the list."
3866 :group 'org-agenda
3867 :type 'boolean)
3869 (defcustom org-calendar-to-agenda-key [?c]
3870 "The key to be installed in `calendar-mode-map' for switching to the agenda.
3871 The command `org-calendar-goto-agenda' will be bound to this key. The
3872 default is the character `c' because then `c' can be used to switch back and
3873 forth between agenda and calendar."
3874 :group 'org-agenda
3875 :type 'sexp)
3877 (defcustom org-calendar-insert-diary-entry-key [?i]
3878 "The key to be installed in `calendar-mode-map' for adding diary entries.
3879 This option is irrelevant until `org-agenda-diary-file' has been configured
3880 to point to an Org-mode file. When that is the case, the command
3881 `org-agenda-diary-entry' will be bound to the key given here, by default
3882 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
3883 if you want to continue doing this, you need to change this to a different
3884 key."
3885 :group 'org-agenda
3886 :type 'sexp)
3888 (defcustom org-agenda-diary-file 'diary-file
3889 "File to which to add new entries with the `i' key in agenda and calendar.
3890 When this is the symbol `diary-file', the functionality in the Emacs
3891 calendar will be used to add entries to the `diary-file'. But when this
3892 points to a file, `org-agenda-diary-entry' will be used instead."
3893 :group 'org-agenda
3894 :type '(choice
3895 (const :tag "The standard Emacs diary file" diary-file)
3896 (file :tag "Special Org file diary entries")))
3898 (eval-after-load "calendar"
3899 '(progn
3900 (org-defkey calendar-mode-map org-calendar-to-agenda-key
3901 'org-calendar-goto-agenda)
3902 (add-hook 'calendar-mode-hook
3903 (lambda ()
3904 (unless (eq org-agenda-diary-file 'diary-file)
3905 (define-key calendar-mode-map
3906 org-calendar-insert-diary-entry-key
3907 'org-agenda-diary-entry))))))
3909 (defgroup org-latex nil
3910 "Options for embedding LaTeX code into Org-mode."
3911 :tag "Org LaTeX"
3912 :group 'org)
3914 (defcustom org-format-latex-options
3915 '(:foreground default :background default :scale 1.0
3916 :html-foreground "Black" :html-background "Transparent"
3917 :html-scale 1.0 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
3918 "Options for creating images from LaTeX fragments.
3919 This is a property list with the following properties:
3920 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
3921 `default' means use the foreground of the default face.
3922 `auto' means use the foreground from the text face.
3923 :background the background color, or \"Transparent\".
3924 `default' means use the background of the default face.
3925 `auto' means use the background from the text face.
3926 :scale a scaling factor for the size of the images, to get more pixels
3927 :html-foreground, :html-background, :html-scale
3928 the same numbers for HTML export.
3929 :matchers a list indicating which matchers should be used to
3930 find LaTeX fragments. Valid members of this list are:
3931 \"begin\" find environments
3932 \"$1\" find single characters surrounded by $.$
3933 \"$\" find math expressions surrounded by $...$
3934 \"$$\" find math expressions surrounded by $$....$$
3935 \"\\(\" find math expressions surrounded by \\(...\\)
3936 \"\\=\\[\" find math expressions surrounded by \\=\\[...\\]"
3937 :group 'org-latex
3938 :type 'plist)
3940 (defcustom org-format-latex-signal-error t
3941 "Non-nil means signal an error when image creation of LaTeX snippets fails.
3942 When nil, just push out a message."
3943 :group 'org-latex
3944 :version "24.1"
3945 :type 'boolean)
3947 (defcustom org-latex-to-mathml-jar-file nil
3948 "Value of\"%j\" in `org-latex-to-mathml-convert-command'.
3949 Use this to specify additional executable file say a jar file.
3951 When using MathToWeb as the converter, specify the full-path to
3952 your mathtoweb.jar file."
3953 :group 'org-latex
3954 :version "24.1"
3955 :type '(choice
3956 (const :tag "None" nil)
3957 (file :tag "JAR file" :must-match t)))
3959 (defcustom org-latex-to-mathml-convert-command nil
3960 "Command to convert LaTeX fragments to MathML.
3961 Replace format-specifiers in the command as noted below and use
3962 `shell-command' to convert LaTeX to MathML.
3963 %j: Executable file in fully expanded form as specified by
3964 `org-latex-to-mathml-jar-file'.
3965 %I: Input LaTeX file in fully expanded form.
3966 %i: The latex fragment to be converted.
3967 %o: Output MathML file.
3969 This command is used by `org-create-math-formula'.
3971 When using MathToWeb as the converter, set this option to
3972 \"java -jar %j -unicode -force -df %o %I\".
3974 When using LaTeXML set this option to
3975 \"latexmlmath \"%i\" --presentationmathml=%o\"."
3976 :group 'org-latex
3977 :version "24.1"
3978 :type '(choice
3979 (const :tag "None" nil)
3980 (string :tag "\nShell command")))
3982 (defcustom org-latex-create-formula-image-program 'dvipng
3983 "Program to convert LaTeX fragments with.
3985 dvipng Process the LaTeX fragments to dvi file, then convert
3986 dvi files to png files using dvipng.
3987 This will also include processing of non-math environments.
3988 imagemagick Convert the LaTeX fragments to pdf files and use imagemagick
3989 to convert pdf files to png files"
3990 :group 'org-latex
3991 :version "24.1"
3992 :type '(choice
3993 (const :tag "dvipng" dvipng)
3994 (const :tag "imagemagick" imagemagick)))
3996 (defcustom org-latex-preview-ltxpng-directory "ltxpng/"
3997 "Path to store latex preview images.
3998 A relative path here creates many directories relative to the
3999 processed org files paths. An absolute path puts all preview
4000 images at the same place."
4001 :group 'org-latex
4002 :version "24.3"
4003 :type 'string)
4005 (defun org-format-latex-mathml-available-p ()
4006 "Return t if `org-latex-to-mathml-convert-command' is usable."
4007 (save-match-data
4008 (when (and (boundp 'org-latex-to-mathml-convert-command)
4009 org-latex-to-mathml-convert-command)
4010 (let ((executable (car (split-string
4011 org-latex-to-mathml-convert-command))))
4012 (when (executable-find executable)
4013 (if (string-match
4014 "%j" org-latex-to-mathml-convert-command)
4015 (file-readable-p org-latex-to-mathml-jar-file)
4016 t))))))
4018 (defcustom org-format-latex-header "\\documentclass{article}
4019 \\usepackage[usenames]{color}
4020 \[PACKAGES]
4021 \[DEFAULT-PACKAGES]
4022 \\pagestyle{empty} % do not remove
4023 % The settings below are copied from fullpage.sty
4024 \\setlength{\\textwidth}{\\paperwidth}
4025 \\addtolength{\\textwidth}{-3cm}
4026 \\setlength{\\oddsidemargin}{1.5cm}
4027 \\addtolength{\\oddsidemargin}{-2.54cm}
4028 \\setlength{\\evensidemargin}{\\oddsidemargin}
4029 \\setlength{\\textheight}{\\paperheight}
4030 \\addtolength{\\textheight}{-\\headheight}
4031 \\addtolength{\\textheight}{-\\headsep}
4032 \\addtolength{\\textheight}{-\\footskip}
4033 \\addtolength{\\textheight}{-3cm}
4034 \\setlength{\\topmargin}{1.5cm}
4035 \\addtolength{\\topmargin}{-2.54cm}"
4036 "The document header used for processing LaTeX fragments.
4037 It is imperative that this header make sure that no page number
4038 appears on the page. The package defined in the variables
4039 `org-latex-default-packages-alist' and `org-latex-packages-alist'
4040 will either replace the placeholder \"[PACKAGES]\" in this
4041 header, or they will be appended."
4042 :group 'org-latex
4043 :type 'string)
4045 (defun org-set-packages-alist (var val)
4046 "Set the packages alist and make sure it has 3 elements per entry."
4047 (set var (mapcar (lambda (x)
4048 (if (and (consp x) (= (length x) 2))
4049 (list (car x) (nth 1 x) t)
4051 val)))
4053 (defun org-get-packages-alist (var)
4054 "Get the packages alist and make sure it has 3 elements per entry."
4055 (mapcar (lambda (x)
4056 (if (and (consp x) (= (length x) 2))
4057 (list (car x) (nth 1 x) t)
4059 (default-value var)))
4061 (defcustom org-latex-default-packages-alist
4062 '(("AUTO" "inputenc" t ("pdflatex"))
4063 ("T1" "fontenc" t ("pdflatex"))
4064 ("" "graphicx" t)
4065 ("" "grffile" t)
4066 ("" "longtable" nil)
4067 ("" "wrapfig" nil)
4068 ("" "rotating" nil)
4069 ("normalem" "ulem" t)
4070 ("" "amsmath" t)
4071 ("" "textcomp" t)
4072 ("" "amssymb" t)
4073 ("" "capt-of" nil)
4074 ("" "hyperref" nil))
4075 "Alist of default packages to be inserted in the header.
4077 Change this only if one of the packages here causes an
4078 incompatibility with another package you are using.
4080 The packages in this list are needed by one part or another of
4081 Org mode to function properly:
4083 - inputenc, fontenc: for basic font and character selection
4084 - graphicx: for including images
4085 - grffile: allow periods and spaces in graphics file names
4086 - longtable: For multipage tables
4087 - wrapfig: for figure placement
4088 - rotating: for sideways figures and tables
4089 - ulem: for underline and strike-through
4090 - amsmath: for subscript and superscript and math environments
4091 - textcomp, amssymb: for various symbols used
4092 for interpreting the entities in `org-entities'. You can skip
4093 some of these packages if you don't use any of their symbols.
4094 - capt-of: for captions outside of floats
4095 - hyperref: for cross references
4097 Therefore you should not modify this variable unless you know
4098 what you are doing. The one reason to change it anyway is that
4099 you might be loading some other package that conflicts with one
4100 of the default packages. Each element is either a cell or
4101 a string.
4103 A cell is of the format
4105 (\"options\" \"package\" SNIPPET-FLAG COMPILERS)
4107 If SNIPPET-FLAG is non-nil, the package also needs to be included
4108 when compiling LaTeX snippets into images for inclusion into
4109 non-LaTeX output. COMPILERS is a list of compilers that should
4110 include the package, see `org-latex-compiler'. If the document
4111 compiler is not in the list, and the list is non-nil, the package
4112 will not be inserted in the final document.
4114 A string will be inserted as-is in the header of the document."
4115 :group 'org-latex
4116 :group 'org-export-latex
4117 :set 'org-set-packages-alist
4118 :get 'org-get-packages-alist
4119 :version "25.1"
4120 :package-version '(Org . "8.3")
4121 :type '(repeat
4122 (choice
4123 (list :tag "options/package pair"
4124 (string :tag "options")
4125 (string :tag "package")
4126 (boolean :tag "Snippet"))
4127 (string :tag "A line of LaTeX"))))
4129 (defcustom org-latex-packages-alist nil
4130 "Alist of packages to be inserted in every LaTeX header.
4132 These will be inserted after `org-latex-default-packages-alist'.
4133 Each element is either a cell or a string.
4135 A cell is of the format:
4137 (\"options\" \"package\" SNIPPET-FLAG)
4139 SNIPPET-FLAG, when non-nil, indicates that this package is also
4140 needed when turning LaTeX snippets into images for inclusion into
4141 non-LaTeX output.
4143 A string will be inserted as-is in the header of the document.
4145 Make sure that you only list packages here which:
4147 - you want in every file;
4148 - do not conflict with the setup in `org-format-latex-header';
4149 - do not conflict with the default packages in
4150 `org-latex-default-packages-alist'."
4151 :group 'org-latex
4152 :group 'org-export-latex
4153 :set 'org-set-packages-alist
4154 :get 'org-get-packages-alist
4155 :type '(repeat
4156 (choice
4157 (list :tag "options/package pair"
4158 (string :tag "options")
4159 (string :tag "package")
4160 (boolean :tag "Snippet"))
4161 (string :tag "A line of LaTeX"))))
4163 (defgroup org-appearance nil
4164 "Settings for Org-mode appearance."
4165 :tag "Org Appearance"
4166 :group 'org)
4168 (defcustom org-level-color-stars-only nil
4169 "Non-nil means fontify only the stars in each headline.
4170 When nil, the entire headline is fontified.
4171 Changing it requires restart of `font-lock-mode' to become effective
4172 also in regions already fontified."
4173 :group 'org-appearance
4174 :type 'boolean)
4176 (defcustom org-hide-leading-stars nil
4177 "Non-nil means hide the first N-1 stars in a headline.
4178 This works by using the face `org-hide' for these stars. This
4179 face is white for a light background, and black for a dark
4180 background. You may have to customize the face `org-hide' to
4181 make this work.
4182 Changing it requires restart of `font-lock-mode' to become effective
4183 also in regions already fontified.
4184 You may also set this on a per-file basis by adding one of the following
4185 lines to the buffer:
4187 #+STARTUP: hidestars
4188 #+STARTUP: showstars"
4189 :group 'org-appearance
4190 :type 'boolean)
4192 (defcustom org-hidden-keywords nil
4193 "List of symbols corresponding to keywords to be hidden the org buffer.
4194 For example, a value \\='(title) for this list will make the document's title
4195 appear in the buffer without the initial #+TITLE: keyword."
4196 :group 'org-appearance
4197 :version "24.1"
4198 :type '(set (const :tag "#+AUTHOR" author)
4199 (const :tag "#+DATE" date)
4200 (const :tag "#+EMAIL" email)
4201 (const :tag "#+TITLE" title)))
4203 (defcustom org-custom-properties nil
4204 "List of properties (as strings) with a special meaning.
4205 The default use of these custom properties is to let the user
4206 hide them with `org-toggle-custom-properties-visibility'."
4207 :group 'org-properties
4208 :group 'org-appearance
4209 :version "24.3"
4210 :type '(repeat (string :tag "Property Name")))
4212 (defcustom org-fontify-done-headline nil
4213 "Non-nil means change the face of a headline if it is marked DONE.
4214 Normally, only the TODO/DONE keyword indicates the state of a headline.
4215 When this is non-nil, the headline after the keyword is set to the
4216 `org-headline-done' as an additional indication."
4217 :group 'org-appearance
4218 :type 'boolean)
4220 (defcustom org-fontify-emphasized-text t
4221 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
4222 Changing this variable requires a restart of Emacs to take effect."
4223 :group 'org-appearance
4224 :type 'boolean)
4226 (defcustom org-fontify-whole-heading-line nil
4227 "Non-nil means fontify the whole line for headings.
4228 This is useful when setting a background color for the
4229 org-level-* faces."
4230 :group 'org-appearance
4231 :type 'boolean)
4233 (defcustom org-highlight-latex-and-related nil
4234 "Non-nil means highlight LaTeX related syntax in the buffer.
4235 When non nil, the value should be a list containing any of the
4236 following symbols:
4237 `latex' Highlight LaTeX snippets and environments.
4238 `script' Highlight subscript and superscript.
4239 `entities' Highlight entities."
4240 :group 'org-appearance
4241 :version "24.4"
4242 :package-version '(Org . "8.0")
4243 :type '(choice
4244 (const :tag "No highlighting" nil)
4245 (set :greedy t :tag "Highlight"
4246 (const :tag "LaTeX snippets and environments" latex)
4247 (const :tag "Subscript and superscript" script)
4248 (const :tag "Entities" entities))))
4250 (defcustom org-hide-emphasis-markers nil
4251 "Non-nil mean font-lock should hide the emphasis marker characters."
4252 :group 'org-appearance
4253 :type 'boolean)
4255 (defcustom org-hide-macro-markers nil
4256 "Non-nil mean font-lock should hide the brackets marking macro calls."
4257 :group 'org-appearance
4258 :type 'boolean)
4260 (defcustom org-pretty-entities nil
4261 "Non-nil means show entities as UTF8 characters.
4262 When nil, the \\name form remains in the buffer."
4263 :group 'org-appearance
4264 :version "24.1"
4265 :type 'boolean)
4267 (defcustom org-pretty-entities-include-sub-superscripts t
4268 "Non-nil means, pretty entity display includes formatting sub/superscripts."
4269 :group 'org-appearance
4270 :version "24.1"
4271 :type 'boolean)
4273 (defvar org-emph-re nil
4274 "Regular expression for matching emphasis.
4275 After a match, the match groups contain these elements:
4276 0 The match of the full regular expression, including the characters
4277 before and after the proper match
4278 1 The character before the proper match, or empty at beginning of line
4279 2 The proper match, including the leading and trailing markers
4280 3 The leading marker like * or /, indicating the type of highlighting
4281 4 The text between the emphasis markers, not including the markers
4282 5 The character after the match, empty at the end of a line")
4283 (defvar org-verbatim-re nil
4284 "Regular expression for matching verbatim text.")
4285 (defvar org-emphasis-regexp-components) ; defined just below
4286 (defvar org-emphasis-alist) ; defined just below
4287 (defun org-set-emph-re (var val)
4288 "Set variable and compute the emphasis regular expression."
4289 (set var val)
4290 (when (and (boundp 'org-emphasis-alist)
4291 (boundp 'org-emphasis-regexp-components)
4292 org-emphasis-alist org-emphasis-regexp-components)
4293 (let* ((e org-emphasis-regexp-components)
4294 (pre (car e))
4295 (post (nth 1 e))
4296 (border (nth 2 e))
4297 (body (nth 3 e))
4298 (nl (nth 4 e))
4299 (body1 (concat body "*?"))
4300 (markers (mapconcat 'car org-emphasis-alist ""))
4301 (vmarkers (mapconcat
4302 (lambda (x) (if (eq (nth 2 x) 'verbatim) (car x) ""))
4303 org-emphasis-alist "")))
4304 ;; make sure special characters appear at the right position in the class
4305 (if (string-match "\\^" markers)
4306 (setq markers (concat (replace-match "" t t markers) "^")))
4307 (if (string-match "-" markers)
4308 (setq markers (concat (replace-match "" t t markers) "-")))
4309 (if (string-match "\\^" vmarkers)
4310 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
4311 (if (string-match "-" vmarkers)
4312 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
4313 (if (> nl 0)
4314 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
4315 (int-to-string nl) "\\}")))
4316 ;; Make the regexp
4317 (setq org-emph-re
4318 (concat "\\([" pre "]\\|^\\)"
4319 "\\("
4320 "\\([" markers "]\\)"
4321 "\\("
4322 "[^" border "]\\|"
4323 "[^" border "]"
4324 body1
4325 "[^" border "]"
4326 "\\)"
4327 "\\3\\)"
4328 "\\([" post "]\\|$\\)"))
4329 (setq org-verbatim-re
4330 (concat "\\([" pre "]\\|^\\)"
4331 "\\("
4332 "\\([" vmarkers "]\\)"
4333 "\\("
4334 "[^" border "]\\|"
4335 "[^" border "]"
4336 body1
4337 "[^" border "]"
4338 "\\)"
4339 "\\3\\)"
4340 "\\([" post "]\\|$\\)")))))
4342 ;; This used to be a defcustom (Org <8.0) but allowing the users to
4343 ;; set this option proved cumbersome. See this message/thread:
4344 ;; http://article.gmane.org/gmane.emacs.orgmode/68681
4345 (defvar org-emphasis-regexp-components
4346 '(" \t('\"{" "- \t.,:!?;'\")}\\[" " \t\r\n" "." 1)
4347 "Components used to build the regular expression for emphasis.
4348 This is a list with five entries. Terminology: In an emphasis string
4349 like \" *strong word* \", we call the initial space PREMATCH, the final
4350 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
4351 and \"trong wor\" is the body. The different components in this variable
4352 specify what is allowed/forbidden in each part:
4354 pre Chars allowed as prematch. Beginning of line will be allowed too.
4355 post Chars allowed as postmatch. End of line will be allowed too.
4356 border The chars *forbidden* as border characters.
4357 body-regexp A regexp like \".\" to match a body character. Don't use
4358 non-shy groups here, and don't allow newline here.
4359 newline The maximum number of newlines allowed in an emphasis exp.
4361 You need to reload Org or to restart Emacs after customizing this.")
4363 (defcustom org-emphasis-alist
4364 `(("*" bold)
4365 ("/" italic)
4366 ("_" underline)
4367 ("=" org-verbatim verbatim)
4368 ("~" org-code verbatim)
4369 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))))
4370 "Alist of characters and faces to emphasize text.
4371 Text starting and ending with a special character will be emphasized,
4372 for example *bold*, _underlined_ and /italic/. This variable sets the
4373 marker characters and the face to be used by font-lock for highlighting
4374 in Org-mode Emacs buffers.
4376 You need to reload Org or to restart Emacs after customizing this."
4377 :group 'org-appearance
4378 :set 'org-set-emph-re
4379 :version "24.4"
4380 :package-version '(Org . "8.0")
4381 :type '(repeat
4382 (list
4383 (string :tag "Marker character")
4384 (choice
4385 (face :tag "Font-lock-face")
4386 (plist :tag "Face property list"))
4387 (option (const verbatim)))))
4389 (defvar org-protecting-blocks '("src" "example" "export")
4390 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
4391 This is needed for font-lock setup.")
4393 ;;; Functions and variables from their packages
4394 ;; Declared here to avoid compiler warnings
4396 ;; XEmacs only
4397 (defvar outline-mode-menu-heading)
4398 (defvar outline-mode-menu-show)
4399 (defvar outline-mode-menu-hide)
4400 (defvar zmacs-regions) ; XEmacs regions
4402 ;; Emacs only
4403 (defvar mark-active)
4405 ;; Various packages
4406 (declare-function calc-eval "calc" (str &optional separator &rest args))
4407 (declare-function calendar-forward-day "cal-move" (arg))
4408 (declare-function calendar-goto-date "cal-move" (date))
4409 (declare-function calendar-goto-today "cal-move" ())
4410 (declare-function calendar-iso-from-absolute "cal-iso" (date))
4411 (declare-function calendar-iso-to-absolute "cal-iso" (date))
4412 (declare-function cdlatex-compute-tables "ext:cdlatex" ())
4413 (declare-function cdlatex-tab "ext:cdlatex" ())
4414 (declare-function dired-get-filename
4415 "dired"
4416 (&optional localp no-error-if-not-filep))
4417 (declare-function iswitchb-read-buffer
4418 "iswitchb"
4419 (prompt &optional default require-match start matches-set))
4420 (declare-function org-agenda-change-all-lines
4421 "org-agenda"
4422 (newhead hdmarker &optional fixface just-this))
4423 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
4424 "org-agenda"
4425 (&optional end))
4426 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
4427 (declare-function org-agenda-format-item
4428 "org-agenda"
4429 (extra txt &optional level category tags dotime noprefix
4430 remove-re habitp))
4431 (declare-function org-agenda-maybe-redo "org-agenda" ())
4432 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
4433 (declare-function org-agenda-save-markers-for-cut-and-paste
4434 "org-agenda"
4435 (beg end))
4436 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
4437 (declare-function org-agenda-skip "org-agenda" ())
4438 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
4439 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
4440 (declare-function org-indent-mode "org-indent" (&optional arg))
4441 (declare-function org-inlinetask-goto-beginning "org-inlinetask" ())
4442 (declare-function org-inlinetask-goto-end "org-inlinetask" ())
4443 (declare-function org-inlinetask-in-task-p "org-inlinetask" ())
4444 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
4445 (declare-function orgtbl-send-table "org-table" (&optional maybe))
4446 (declare-function parse-time-string "parse-time" (string))
4447 (declare-function speedbar-line-directory "speedbar" (&optional depth))
4448 (declare-function table--at-cell-p
4449 "table"
4450 (position &optional object at-column))
4452 (defvar align-mode-rules-list)
4453 (defvar calc-embedded-close-formula)
4454 (defvar calc-embedded-open-formula)
4455 (defvar calc-embedded-open-mode)
4456 (defvar font-lock-unfontify-region-function)
4457 (defvar iswitchb-temp-buflist)
4458 (defvar org-agenda-tags-todo-honor-ignore-options)
4459 (defvar remember-data-file)
4460 (defvar texmathp-why)
4462 ;;;###autoload
4463 (defun turn-on-orgtbl ()
4464 "Unconditionally turn on `orgtbl-mode'."
4465 (require 'org-table)
4466 (orgtbl-mode 1))
4468 (defun org-at-table-p (&optional table-type)
4469 "Non-nil if the cursor is inside an Org table.
4470 If TABLE-TYPE is non-nil, also check for table.el-type tables.
4471 If `org-enable-table-editor' is nil, return nil unconditionally."
4472 (and
4473 org-enable-table-editor
4474 (save-excursion
4475 (beginning-of-line)
4476 (org-looking-at-p (if table-type "[ \t]*[|+]" "[ \t]*|")))
4477 (or (not (derived-mode-p 'org-mode))
4478 (let ((e (org-element-lineage (org-element-at-point) '(table) t)))
4479 (and e (or table-type (eq (org-element-property :type e) 'org)))))))
4480 (define-obsolete-function-alias 'org-table-p 'org-at-table-p "Org 9.0")
4482 (defun org-at-table.el-p ()
4483 "Non-nil when point is at a table.el table."
4484 (and (save-excursion (beginning-of-line) (looking-at "[ \t]*[|+]"))
4485 (let ((element (org-element-at-point)))
4486 (and (eq (org-element-type element) 'table)
4487 (eq (org-element-property :type element) 'table.el)))))
4489 (defun org-table-recognize-table.el ()
4490 "If there is a table.el table nearby, recognize it and move into it."
4491 (when (and org-table-tab-recognizes-table.el (org-at-table.el-p))
4492 (beginning-of-line)
4493 (unless (or (looking-at org-table-dataline-regexp)
4494 (not (looking-at org-table1-hline-regexp)))
4495 (forward-line)
4496 (when (looking-at org-table-any-border-regexp)
4497 (forward-line -2)))
4498 (if (re-search-forward "|" (org-table-end t) t)
4499 (progn
4500 (require 'table)
4501 (if (table--at-cell-p (point)) t
4502 (message "recognizing table.el table...")
4503 (table-recognize-table)
4504 (message "recognizing table.el table...done")))
4505 (error "This should not happen"))))
4506 ;;; This function is not used by org core since commit 6d1e3082, Feb 2010
4507 (make-obsolete 'org-table-recognize-table.el
4508 "please notify the org mailing list if you use this function."
4509 "Org 9.0")
4511 (defun org-at-table-hline-p ()
4512 "Non-nil when point is inside a hline in a table.
4513 Assume point is already in a table. If `org-enable-table-editor'
4514 is nil, return nil unconditionally."
4515 (and org-enable-table-editor
4516 (save-excursion
4517 (beginning-of-line)
4518 (looking-at org-table-hline-regexp))))
4520 (defun org-table-map-tables (function &optional quietly)
4521 "Apply FUNCTION to the start of all tables in the buffer."
4522 (save-excursion
4523 (save-restriction
4524 (widen)
4525 (goto-char (point-min))
4526 (while (re-search-forward org-table-any-line-regexp nil t)
4527 (unless quietly
4528 (message "Mapping tables: %d%%"
4529 (floor (* 100.0 (point)) (buffer-size))))
4530 (beginning-of-line 1)
4531 (when (and (looking-at org-table-line-regexp)
4532 ;; Exclude tables in src/example/verbatim/clocktable blocks
4533 (not (org-in-block-p '("src" "example" "verbatim" "clocktable"))))
4534 (save-excursion (funcall function))
4535 (or (looking-at org-table-line-regexp)
4536 (forward-char 1)))
4537 (re-search-forward org-table-any-border-regexp nil 1))))
4538 (unless quietly (message "Mapping tables: done")))
4540 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock" (beg end))
4541 (declare-function org-clock-update-mode-line "org-clock" ())
4542 (declare-function org-resolve-clocks "org-clock"
4543 (&optional also-non-dangling-p prompt last-valid))
4545 (defun org-at-TBLFM-p (&optional pos)
4546 "Non-nil when point (or POS) is in #+TBLFM line."
4547 (save-excursion
4548 (goto-char (or pos (point)))
4549 (beginning-of-line)
4550 (and (let ((case-fold-search t)) (looking-at org-TBLFM-regexp))
4551 (eq (org-element-type (org-element-at-point)) 'table))))
4553 (defvar org-clock-start-time)
4554 (defvar org-clock-marker (make-marker)
4555 "Marker recording the last clock-in.")
4556 (defvar org-clock-hd-marker (make-marker)
4557 "Marker recording the last clock-in, but the headline position.")
4558 (defvar org-clock-heading ""
4559 "The heading of the current clock entry.")
4560 (defun org-clock-is-active ()
4561 "Return the buffer where the clock is currently running.
4562 Return nil if no clock is running."
4563 (marker-buffer org-clock-marker))
4565 (defun org-check-running-clock ()
4566 "Check if the current buffer contains the running clock.
4567 If yes, offer to stop it and to save the buffer with the changes."
4568 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
4569 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
4570 (buffer-name))))
4571 (org-clock-out)
4572 (when (y-or-n-p "Save changed buffer?")
4573 (save-buffer))))
4575 (defun org-clocktable-try-shift (dir n)
4576 "Check if this line starts a clock table, if yes, shift the time block."
4577 (when (org-match-line "^[ \t]*#\\+BEGIN:[ \t]+clocktable\\>")
4578 (org-clocktable-shift dir n)))
4580 ;;;###autoload
4581 (defun org-clock-persistence-insinuate ()
4582 "Set up hooks for clock persistence."
4583 (require 'org-clock)
4584 (add-hook 'org-mode-hook 'org-clock-load)
4585 (add-hook 'kill-emacs-hook 'org-clock-save))
4587 (defgroup org-archive nil
4588 "Options concerning archiving in Org-mode."
4589 :tag "Org Archive"
4590 :group 'org-structure)
4592 (defcustom org-archive-location "%s_archive::"
4593 "The location where subtrees should be archived.
4595 The value of this variable is a string, consisting of two parts,
4596 separated by a double-colon. The first part is a filename and
4597 the second part is a headline.
4599 When the filename is omitted, archiving happens in the same file.
4600 %s in the filename will be replaced by the current file
4601 name (without the directory part). Archiving to a different file
4602 is useful to keep archived entries from contributing to the
4603 Org-mode Agenda.
4605 The archived entries will be filed as subtrees of the specified
4606 headline. When the headline is omitted, the subtrees are simply
4607 filed away at the end of the file, as top-level entries. Also in
4608 the heading you can use %s to represent the file name, this can be
4609 useful when using the same archive for a number of different files.
4611 Here are a few examples:
4612 \"%s_archive::\"
4613 If the current file is Projects.org, archive in file
4614 Projects.org_archive, as top-level trees. This is the default.
4616 \"::* Archived Tasks\"
4617 Archive in the current file, under the top-level headline
4618 \"* Archived Tasks\".
4620 \"~/org/archive.org::\"
4621 Archive in file ~/org/archive.org (absolute path), as top-level trees.
4623 \"~/org/archive.org::* From %s\"
4624 Archive in file ~/org/archive.org (absolute path), under headlines
4625 \"From FILENAME\" where file name is the current file name.
4627 \"~/org/datetree.org::datetree/* Finished Tasks\"
4628 The \"datetree/\" string is special, signifying to archive
4629 items to the datetree. Items are placed in either the CLOSED
4630 date of the item, or the current date if there is no CLOSED date.
4631 The heading will be a subentry to the current date. There doesn't
4632 need to be a heading, but there always needs to be a slash after
4633 datetree. For example, to store archived items directly in the
4634 datetree, use \"~/org/datetree.org::datetree/\".
4636 \"basement::** Finished Tasks\"
4637 Archive in file ./basement (relative path), as level 3 trees
4638 below the level 2 heading \"** Finished Tasks\".
4640 You may set this option on a per-file basis by adding to the buffer a
4641 line like
4643 #+ARCHIVE: basement::** Finished Tasks
4645 You may also define it locally for a subtree by setting an ARCHIVE property
4646 in the entry. If such a property is found in an entry, or anywhere up
4647 the hierarchy, it will be used."
4648 :group 'org-archive
4649 :type 'string)
4651 (defcustom org-agenda-skip-archived-trees t
4652 "Non-nil means the agenda will skip any items located in archived trees.
4653 An archived tree is a tree marked with the tag ARCHIVE. The use of this
4654 variable is no longer recommended, you should leave it at the value t.
4655 Instead, use the key `v' to cycle the archives-mode in the agenda."
4656 :group 'org-archive
4657 :group 'org-agenda-skip
4658 :type 'boolean)
4660 (defcustom org-columns-skip-archived-trees t
4661 "Non-nil means ignore archived trees when creating column view."
4662 :group 'org-archive
4663 :group 'org-properties
4664 :type 'boolean)
4666 (defcustom org-cycle-open-archived-trees nil
4667 "Non-nil means `org-cycle' will open archived trees.
4668 An archived tree is a tree marked with the tag ARCHIVE.
4669 When nil, archived trees will stay folded. You can still open them with
4670 normal outline commands like `show-all', but not with the cycling commands."
4671 :group 'org-archive
4672 :group 'org-cycle
4673 :type 'boolean)
4675 (defcustom org-sparse-tree-open-archived-trees nil
4676 "Non-nil means sparse tree construction shows matches in archived trees.
4677 When nil, matches in these trees are highlighted, but the trees are kept in
4678 collapsed state."
4679 :group 'org-archive
4680 :group 'org-sparse-trees
4681 :type 'boolean)
4683 (defcustom org-sparse-tree-default-date-type nil
4684 "The default date type when building a sparse tree.
4685 When this is nil, a date is a scheduled or a deadline timestamp.
4686 Otherwise, these types are allowed:
4688 all: all timestamps
4689 active: only active timestamps (<...>)
4690 inactive: only inactive timestamps ([...])
4691 scheduled: only scheduled timestamps
4692 deadline: only deadline timestamps"
4693 :type '(choice (const :tag "Scheduled or deadline" nil)
4694 (const :tag "All timestamps" all)
4695 (const :tag "Only active timestamps" active)
4696 (const :tag "Only inactive timestamps" inactive)
4697 (const :tag "Only scheduled timestamps" scheduled)
4698 (const :tag "Only deadline timestamps" deadline)
4699 (const :tag "Only closed timestamps" closed))
4700 :version "25.1"
4701 :package-version '(Org . "8.3")
4702 :group 'org-sparse-trees)
4704 (defun org-cycle-hide-archived-subtrees (state)
4705 "Re-hide all archived subtrees after a visibility state change."
4706 (when (and (not org-cycle-open-archived-trees)
4707 (not (memq state '(overview folded))))
4708 (save-excursion
4709 (let* ((globalp (memq state '(contents all)))
4710 (beg (if globalp (point-min) (point)))
4711 (end (if globalp (point-max) (org-end-of-subtree t))))
4712 (org-hide-archived-subtrees beg end)
4713 (goto-char beg)
4714 (when (looking-at-p (concat ".*:" org-archive-tag ":"))
4715 (message "%s" (substitute-command-keys
4716 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4718 (defun org-force-cycle-archived ()
4719 "Cycle subtree even if it is archived."
4720 (interactive)
4721 (setq this-command 'org-cycle)
4722 (let ((org-cycle-open-archived-trees t))
4723 (call-interactively 'org-cycle)))
4725 (defun org-hide-archived-subtrees (beg end)
4726 "Re-hide all archived subtrees after a visibility state change."
4727 (org-with-wide-buffer
4728 (let ((case-fold-search nil)
4729 (re (concat org-outline-regexp-bol ".*:" org-archive-tag ":")))
4730 (goto-char beg)
4731 ;; Include headline point is currently on.
4732 (beginning-of-line)
4733 (while (and (< (point) end) (re-search-forward re end t))
4734 (when (member org-archive-tag (org-get-tags))
4735 (org-flag-subtree t)
4736 (org-end-of-subtree t))))))
4738 (declare-function outline-end-of-heading "outline" ())
4739 (declare-function outline-flag-region "outline" (from to flag))
4740 (defun org-flag-subtree (flag)
4741 (save-excursion
4742 (org-back-to-heading t)
4743 (outline-end-of-heading)
4744 (outline-flag-region (point)
4745 (progn (org-end-of-subtree t) (point))
4746 flag)))
4748 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
4750 ;; Declare Column View Code
4752 (declare-function org-columns-get-format-and-top-level "org-colview" ())
4753 (declare-function org-columns-compute "org-colview" (property))
4755 ;; Declare ID code
4757 (declare-function org-id-store-link "org-id")
4758 (declare-function org-id-locations-load "org-id")
4759 (declare-function org-id-locations-save "org-id")
4760 (defvar org-id-track-globally)
4762 ;;; Variables for pre-computed regular expressions, all buffer local
4764 (defvar-local org-todo-regexp nil
4765 "Matches any of the TODO state keywords.")
4766 (defvar-local org-not-done-regexp nil
4767 "Matches any of the TODO state keywords except the last one.")
4768 (defvar-local org-not-done-heading-regexp nil
4769 "Matches a TODO headline that is not done.")
4770 (defvar-local org-todo-line-regexp nil
4771 "Matches a headline and puts TODO state into group 2 if present.")
4772 (defvar-local org-complex-heading-regexp nil
4773 "Matches a headline and puts everything into groups:
4774 group 1: the stars
4775 group 2: The todo keyword, maybe
4776 group 3: Priority cookie
4777 group 4: True headline
4778 group 5: Tags")
4779 (defvar-local org-complex-heading-regexp-format nil
4780 "Printf format to make regexp to match an exact headline.
4781 This regexp will match the headline of any node which has the
4782 exact headline text that is put into the format, but may have any
4783 TODO state, priority and tags.")
4784 (defvar-local org-todo-line-tags-regexp nil
4785 "Matches a headline and puts TODO state into group 2 if present.
4786 Also put tags into group 4 if tags are present.")
4788 (defconst org-plain-time-of-day-regexp
4789 (concat
4790 "\\(\\<[012]?[0-9]"
4791 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4792 "\\(--?"
4793 "\\(\\<[012]?[0-9]"
4794 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4795 "\\)?")
4796 "Regular expression to match a plain time or time range.
4797 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4798 groups carry important information:
4799 0 the full match
4800 1 the first time, range or not
4801 8 the second time, if it is a range.")
4803 (defconst org-plain-time-extension-regexp
4804 (concat
4805 "\\(\\<[012]?[0-9]"
4806 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4807 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
4808 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
4809 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4810 groups carry important information:
4811 0 the full match
4812 7 hours of duration
4813 9 minutes of duration")
4815 (defconst org-stamp-time-of-day-regexp
4816 (concat
4817 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
4818 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
4819 "\\(--?"
4820 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4821 "Regular expression to match a timestamp time or time range.
4822 After a match, the following groups carry important information:
4823 0 the full match
4824 1 date plus weekday, for back referencing to make sure both times are on the same day
4825 2 the first time, range or not
4826 4 the second time, if it is a range.")
4828 (defconst org-startup-options
4829 '(("fold" org-startup-folded t)
4830 ("overview" org-startup-folded t)
4831 ("nofold" org-startup-folded nil)
4832 ("showall" org-startup-folded nil)
4833 ("showeverything" org-startup-folded showeverything)
4834 ("content" org-startup-folded content)
4835 ("indent" org-startup-indented t)
4836 ("noindent" org-startup-indented nil)
4837 ("hidestars" org-hide-leading-stars t)
4838 ("showstars" org-hide-leading-stars nil)
4839 ("odd" org-odd-levels-only t)
4840 ("oddeven" org-odd-levels-only nil)
4841 ("align" org-startup-align-all-tables t)
4842 ("noalign" org-startup-align-all-tables nil)
4843 ("inlineimages" org-startup-with-inline-images t)
4844 ("noinlineimages" org-startup-with-inline-images nil)
4845 ("latexpreview" org-startup-with-latex-preview t)
4846 ("nolatexpreview" org-startup-with-latex-preview nil)
4847 ("customtime" org-display-custom-times t)
4848 ("logdone" org-log-done time)
4849 ("lognotedone" org-log-done note)
4850 ("nologdone" org-log-done nil)
4851 ("lognoteclock-out" org-log-note-clock-out t)
4852 ("nolognoteclock-out" org-log-note-clock-out nil)
4853 ("logrepeat" org-log-repeat state)
4854 ("lognoterepeat" org-log-repeat note)
4855 ("logdrawer" org-log-into-drawer t)
4856 ("nologdrawer" org-log-into-drawer nil)
4857 ("logstatesreversed" org-log-states-order-reversed t)
4858 ("nologstatesreversed" org-log-states-order-reversed nil)
4859 ("nologrepeat" org-log-repeat nil)
4860 ("logreschedule" org-log-reschedule time)
4861 ("lognotereschedule" org-log-reschedule note)
4862 ("nologreschedule" org-log-reschedule nil)
4863 ("logredeadline" org-log-redeadline time)
4864 ("lognoteredeadline" org-log-redeadline note)
4865 ("nologredeadline" org-log-redeadline nil)
4866 ("logrefile" org-log-refile time)
4867 ("lognoterefile" org-log-refile note)
4868 ("nologrefile" org-log-refile nil)
4869 ("fninline" org-footnote-define-inline t)
4870 ("nofninline" org-footnote-define-inline nil)
4871 ("fnlocal" org-footnote-section nil)
4872 ("fnauto" org-footnote-auto-label t)
4873 ("fnprompt" org-footnote-auto-label nil)
4874 ("fnconfirm" org-footnote-auto-label confirm)
4875 ("fnplain" org-footnote-auto-label plain)
4876 ("fnadjust" org-footnote-auto-adjust t)
4877 ("nofnadjust" org-footnote-auto-adjust nil)
4878 ("constcgs" constants-unit-system cgs)
4879 ("constSI" constants-unit-system SI)
4880 ("noptag" org-tag-persistent-alist nil)
4881 ("hideblocks" org-hide-block-startup t)
4882 ("nohideblocks" org-hide-block-startup nil)
4883 ("beamer" org-startup-with-beamer-mode t)
4884 ("entitiespretty" org-pretty-entities t)
4885 ("entitiesplain" org-pretty-entities nil))
4886 "Variable associated with STARTUP options for org-mode.
4887 Each element is a list of three items: the startup options (as written
4888 in the #+STARTUP line), the corresponding variable, and the value to set
4889 this variable to if the option is found. An optional forth element PUSH
4890 means to push this value onto the list in the variable.")
4892 (defcustom org-group-tags t
4893 "When non-nil (the default), use group tags.
4894 This can be turned on/off through `org-toggle-tags-groups'."
4895 :group 'org-tags
4896 :group 'org-startup
4897 :type 'boolean)
4899 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4901 (defun org-toggle-tags-groups ()
4902 "Toggle support for group tags.
4903 Support for group tags is controlled by the option
4904 `org-group-tags', which is non-nil by default."
4905 (interactive)
4906 (setq org-group-tags (not org-group-tags))
4907 (cond ((and (derived-mode-p 'org-agenda-mode)
4908 org-group-tags)
4909 (org-agenda-redo))
4910 ((derived-mode-p 'org-mode)
4911 (let ((org-inhibit-startup t)) (org-mode))))
4912 (message "Groups tags support has been turned %s"
4913 (if org-group-tags "on" "off")))
4915 (defun org-set-regexps-and-options (&optional tags-only)
4916 "Precompute regular expressions used in the current buffer.
4917 When optional argument TAGS-ONLY is non-nil, only compute tags
4918 related expressions."
4919 (when (derived-mode-p 'org-mode)
4920 (let ((alist (org--setup-collect-keywords
4921 (org-make-options-regexp
4922 (append '("FILETAGS" "TAGS" "SETUPFILE")
4923 (and (not tags-only)
4924 '("ARCHIVE" "CATEGORY" "COLUMNS" "CONSTANTS"
4925 "LINK" "OPTIONS" "PRIORITIES" "PROPERTY"
4926 "SEQ_TODO" "STARTUP" "TODO" "TYP_TODO")))))))
4927 ;; Startup options. Get this early since it does change
4928 ;; behavior for other options (e.g., tags).
4929 (let ((startup (cdr (assq 'startup alist))))
4930 (dolist (option startup)
4931 (let ((entry (assoc-string option org-startup-options t)))
4932 (when entry
4933 (let ((var (nth 1 entry))
4934 (val (nth 2 entry)))
4935 (if (not (nth 3 entry)) (set (make-local-variable var) val)
4936 (unless (listp (symbol-value var))
4937 (set (make-local-variable var) nil))
4938 (add-to-list var val)))))))
4939 (setq-local org-file-tags
4940 (mapcar #'org-add-prop-inherited
4941 (cdr (assq 'filetags alist))))
4942 (setq org-current-tag-alist
4943 (append org-tag-persistent-alist
4944 (let ((tags (cdr (assq 'tags alist))))
4945 (if tags (org-tag-string-to-alist tags)
4946 org-tag-alist))))
4947 (setq org-tag-groups-alist
4948 (org-tag-alist-to-groups org-current-tag-alist))
4949 (unless tags-only
4950 ;; File properties.
4951 (setq-local org-file-properties (cdr (assq 'property alist)))
4952 ;; Archive location.
4953 (let ((archive (cdr (assq 'archive alist))))
4954 (when archive (setq-local org-archive-location archive)))
4955 ;; Category.
4956 (let ((cat (org-string-nw-p (cdr (assq 'category alist)))))
4957 (when cat
4958 (setq-local org-category (intern cat))
4959 (setq-local org-file-properties
4960 (org--update-property-plist
4961 "CATEGORY" cat org-file-properties))))
4962 ;; Columns.
4963 (let ((column (cdr (assq 'columns alist))))
4964 (when column (setq-local org-columns-default-format column)))
4965 ;; Constants.
4966 (setq org-table-formula-constants-local (cdr (assq 'constants alist)))
4967 ;; Link abbreviations.
4968 (let ((links (cdr (assq 'link alist))))
4969 (when links (setq org-link-abbrev-alist-local (nreverse links))))
4970 ;; Priorities.
4971 (let ((priorities (cdr (assq 'priorities alist))))
4972 (when priorities
4973 (setq-local org-highest-priority (nth 0 priorities))
4974 (setq-local org-lowest-priority (nth 1 priorities))
4975 (setq-local org-default-priority (nth 2 priorities))))
4976 ;; Scripts.
4977 (let ((scripts (assq 'scripts alist)))
4978 (when scripts
4979 (setq-local org-use-sub-superscripts (cdr scripts))))
4980 ;; TODO keywords.
4981 (setq-local org-todo-kwd-alist nil)
4982 (setq-local org-todo-key-alist nil)
4983 (setq-local org-todo-key-trigger nil)
4984 (setq-local org-todo-keywords-1 nil)
4985 (setq-local org-done-keywords nil)
4986 (setq-local org-todo-heads nil)
4987 (setq-local org-todo-sets nil)
4988 (setq-local org-todo-log-states nil)
4989 (let ((todo-sequences
4990 (or (nreverse (cdr (assq 'todo alist)))
4991 (let ((d (default-value 'org-todo-keywords)))
4992 (if (not (stringp (car d))) d
4993 ;; XXX: Backward compatibility code.
4994 (list (cons org-todo-interpretation d)))))))
4995 (dolist (sequence todo-sequences)
4996 (let* ((sequence (or (run-hook-with-args-until-success
4997 'org-todo-setup-filter-hook sequence)
4998 sequence))
4999 (sequence-type (car sequence))
5000 (keywords (cdr sequence))
5001 (sep (member "|" keywords))
5002 names alist)
5003 (dolist (k (remove "|" keywords))
5004 (unless (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$"
5006 (error "Invalid TODO keyword %s" k))
5007 (let ((name (match-string 1 k))
5008 (key (match-string 2 k))
5009 (log (org-extract-log-state-settings k)))
5010 (push name names)
5011 (push (cons name (and key (string-to-char key))) alist)
5012 (when log (push log org-todo-log-states))))
5013 (let* ((names (nreverse names))
5014 (done (if sep (org-remove-keyword-keys (cdr sep))
5015 (last names)))
5016 (head (car names))
5017 (tail (list sequence-type head (car done) (org-last done))))
5018 (add-to-list 'org-todo-heads head 'append)
5019 (push names org-todo-sets)
5020 (setq org-done-keywords (append org-done-keywords done nil))
5021 (setq org-todo-keywords-1 (append org-todo-keywords-1 names nil))
5022 (setq org-todo-key-alist
5023 (append org-todo-key-alist
5024 (and alist
5025 (append '((:startgroup))
5026 (nreverse alist)
5027 '((:endgroup))))))
5028 (dolist (k names) (push (cons k tail) org-todo-kwd-alist))))))
5029 (setq org-todo-sets (nreverse org-todo-sets)
5030 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
5031 org-todo-key-trigger (delq nil (mapcar #'cdr org-todo-key-alist))
5032 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist))
5033 ;; Compute the regular expressions and other local variables.
5034 ;; Using `org-outline-regexp-bol' would complicate them much,
5035 ;; because of the fixed white space at the end of that string.
5036 (unless org-done-keywords
5037 (setq org-done-keywords
5038 (and org-todo-keywords-1 (last org-todo-keywords-1))))
5039 (setq org-not-done-keywords
5040 (org-delete-all org-done-keywords
5041 (copy-sequence org-todo-keywords-1))
5042 org-todo-regexp (regexp-opt org-todo-keywords-1 t)
5043 org-not-done-regexp (regexp-opt org-not-done-keywords t)
5044 org-not-done-heading-regexp
5045 (format org-heading-keyword-regexp-format org-not-done-regexp)
5046 org-todo-line-regexp
5047 (format org-heading-keyword-maybe-regexp-format org-todo-regexp)
5048 org-complex-heading-regexp
5049 (concat "^\\(\\*+\\)"
5050 "\\(?: +" org-todo-regexp "\\)?"
5051 "\\(?: +\\(\\[#.\\]\\)\\)?"
5052 "\\(?: +\\(.*?\\)\\)??"
5053 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)?")
5054 "[ \t]*$")
5055 org-complex-heading-regexp-format
5056 (concat "^\\(\\*+\\)"
5057 "\\(?: +" org-todo-regexp "\\)?"
5058 "\\(?: +\\(\\[#.\\]\\)\\)?"
5059 "\\(?: +"
5060 ;; Stats cookies can be stuck to body.
5061 "\\(?:\\[[0-9%%/]+\\] *\\)*"
5062 "\\(%s\\)"
5063 "\\(?: *\\[[0-9%%/]+\\]\\)*"
5064 "\\)"
5065 (org-re "\\(?:[ \t]+\\(:[[:alnum:]_@#%%:]+:\\)\\)?")
5066 "[ \t]*$")
5067 org-todo-line-tags-regexp
5068 (concat "^\\(\\*+\\)"
5069 "\\(?: +" org-todo-regexp "\\)?"
5070 "\\(?: +\\(.*?\\)\\)??"
5071 (org-re "\\(?:[ \t]+\\(:[[:alnum:]:_@#%]+:\\)\\)?")
5072 "[ \t]*$"))
5073 (org-compute-latex-and-related-regexp)))))
5075 (defun org--setup-collect-keywords (regexp &optional files alist)
5076 "Return setup keywords values as an alist.
5078 REGEXP matches a subset of setup keywords. FILES is a list of
5079 file names already visited. It is used to avoid circular setup
5080 files. ALIST, when non-nil, is the alist computed so far.
5082 Return value contains the following keys: `archive', `category',
5083 `columns', `constants', `filetags', `link', `priorities',
5084 `property', `scripts', `startup', `tags' and `todo'."
5085 (org-with-wide-buffer
5086 (goto-char (point-min))
5087 (let ((case-fold-search t))
5088 (while (re-search-forward regexp nil t)
5089 (let ((element (org-element-at-point)))
5090 (when (eq (org-element-type element) 'keyword)
5091 (let ((key (org-element-property :key element))
5092 (value (org-element-property :value element)))
5093 (cond
5094 ((equal key "ARCHIVE")
5095 (when (org-string-nw-p value)
5096 (push (cons 'archive value) alist)))
5097 ((equal key "CATEGORY") (push (cons 'category value) alist))
5098 ((equal key "COLUMNS") (push (cons 'columns value) alist))
5099 ((equal key "CONSTANTS")
5100 (let* ((constants (assq 'constants alist))
5101 (store (cdr constants)))
5102 (dolist (pair (org-split-string value))
5103 (when (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)"
5104 pair)
5105 (let* ((name (match-string 1 pair))
5106 (value (match-string 2 pair))
5107 (old (assoc name store)))
5108 (if old (setcdr old value)
5109 (push (cons name value) store)))))
5110 (if constants (setcdr constants store)
5111 (push (cons 'constants store) alist))))
5112 ((equal key "FILETAGS")
5113 (when (org-string-nw-p value)
5114 (let ((old (assq 'filetags alist))
5115 (new (apply #'nconc
5116 (mapcar (lambda (x) (org-split-string x ":"))
5117 (org-split-string value)))))
5118 (if old (setcdr old (append new (cdr old)))
5119 (push (cons 'filetags new) alist)))))
5120 ((equal key "LINK")
5121 (when (string-match "\\`\\(\\S-+\\)[ \t]+\\(.+\\)" value)
5122 (let ((links (assq 'link alist))
5123 (pair (cons (org-match-string-no-properties 1 value)
5124 (org-match-string-no-properties 2 value))))
5125 (if links (push pair (cdr links))
5126 (push (list 'link pair) alist)))))
5127 ((equal key "OPTIONS")
5128 (when (and (org-string-nw-p value)
5129 (string-match "\\^:\\(t\\|nil\\|{}\\)" value))
5130 (push (cons 'scripts (read (match-string 1 value))) alist)))
5131 ((equal key "PRIORITIES")
5132 (push (cons 'priorities
5133 (let ((prio (org-split-string value)))
5134 (if (< (length prio) 3) '(?A ?C ?B)
5135 (mapcar #'string-to-char prio))))
5136 alist))
5137 ((equal key "PROPERTY")
5138 (when (string-match "\\(\\S-+\\)[ \t]+\\(.*\\)" value)
5139 (let* ((property (assq 'property alist))
5140 (value (org--update-property-plist
5141 (org-match-string-no-properties 1 value)
5142 (org-match-string-no-properties 2 value)
5143 (cdr property))))
5144 (if property (setcdr property value)
5145 (push (cons 'property value) alist)))))
5146 ((equal key "STARTUP")
5147 (let ((startup (assq 'startup alist)))
5148 (if startup
5149 (setcdr startup
5150 (append (cdr startup) (org-split-string value)))
5151 (push (cons 'startup (org-split-string value)) alist))))
5152 ((equal key "TAGS")
5153 (let ((tag-cell (assq 'tags alist)))
5154 (if tag-cell
5155 (setcdr tag-cell (concat (cdr tag-cell) "\n" value))
5156 (push (cons 'tags value) alist))))
5157 ((member key '("TODO" "SEQ_TODO" "TYP_TODO"))
5158 (let ((todo (assq 'todo alist))
5159 (value (cons (if (equal key "TYP_TODO") 'type 'sequence)
5160 (org-split-string value))))
5161 (if todo (push value (cdr todo))
5162 (push (list 'todo value) alist))))
5163 ((equal key "SETUPFILE")
5164 (unless buffer-read-only ; Do not check in Gnus messages.
5165 (let ((f (and (org-string-nw-p value)
5166 (expand-file-name
5167 (org-remove-double-quotes value)))))
5168 (when (and f (file-readable-p f) (not (member f files)))
5169 (with-temp-buffer
5170 (setq default-directory (file-name-directory f))
5171 (insert-file-contents f)
5172 (setq alist
5173 ;; Fake Org mode to benefit from cache
5174 ;; without recurring needlessly.
5175 (let ((major-mode 'org-mode))
5176 (org--setup-collect-keywords
5177 regexp (cons f files) alist)))))))))))))))
5178 alist)
5180 (defun org-tag-string-to-alist (s)
5181 "Return tag alist associated to string S.
5182 S is a value for TAGS keyword or produced with
5183 `org-tag-alist-to-string'. Return value is an alist suitable for
5184 `org-tag-alist' or `org-tag-persistent-alist'."
5185 (let ((lines (mapcar #'split-string (split-string s "\n" t)))
5186 (tag-re (concat "\\`\\([[:alnum:]_@#%]+"
5187 "\\|{.+?}\\)" ; regular expression
5188 "\\(?:(\\(.\\))\\)?\\'"))
5189 alist group-flag)
5190 (dolist (tokens lines (cdr (nreverse alist)))
5191 (push '(:newline) alist)
5192 (while tokens
5193 (let ((token (pop tokens)))
5194 (pcase token
5195 ("{"
5196 (push '(:startgroup) alist)
5197 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5198 ("}"
5199 (push '(:endgroup) alist)
5200 (setq group-flag nil))
5201 ("["
5202 (push '(:startgrouptag) alist)
5203 (when (equal (nth 1 tokens) ":") (setq group-flag t)))
5204 ("]"
5205 (push '(:endgrouptag) alist)
5206 (setq group-flag nil))
5207 (":"
5208 (push '(:grouptags) alist))
5209 ((guard (string-match tag-re token))
5210 (let ((tag (match-string 1 token))
5211 (key (and (match-beginning 2)
5212 (string-to-char (match-string 2 token)))))
5213 ;; Push all tags in groups, no matter if they already
5214 ;; appear somewhere else in the list.
5215 (when (or group-flag (not (assoc tag alist)))
5216 (push (cons tag key) alist))))))))))
5218 (defun org-tag-alist-to-string (alist &optional skip-key)
5219 "Return tag string associated to ALIST.
5221 ALIST is an alist, as defined in `org-tag-alist' or
5222 `org-tag-persistent-alist', or produced with
5223 `org-tag-string-to-alist'.
5225 Return value is a string suitable as a value for \"TAGS\"
5226 keyword.
5228 When optional argument SKIP-KEY is non-nil, skip selection keys
5229 next to tags."
5230 (mapconcat (lambda (token)
5231 (pcase token
5232 (`(:startgroup) "{")
5233 (`(:endgroup) "}")
5234 (`(:startgrouptag) "[")
5235 (`(:endgrouptag) "]")
5236 (`(:grouptags) ":")
5237 (`(:newline) "\\n")
5238 ((and
5239 (guard (not skip-key))
5240 `(,(and tag (pred stringp)) . ,(and key (pred characterp))))
5241 (format "%s(%c)" tag key))
5242 (`(,(and tag (pred stringp)) . ,_) tag)
5243 (_ (user-error "Invalid tag token: %S" token))))
5244 alist
5245 " "))
5247 (defun org-tag-alist-to-groups (alist)
5248 "Return group alist from tag ALIST.
5249 ALIST is an alist, as defined in `org-tag-alist' or
5250 `org-tag-persistent-alist', or produced with
5251 `org-tag-string-to-alist'. Return value is an alist following
5252 the pattern (GROUP-TAG TAGS) where GROUP-TAG is the tag, as
5253 a string, summarizing TAGS, as a list of strings."
5254 (let (groups group-status current-group)
5255 (dolist (token alist (nreverse groups))
5256 (pcase token
5257 (`(,(or :startgroup :startgrouptag)) (setq group-status t))
5258 (`(,(or :endgroup :endgrouptag))
5259 (when (eq group-status 'append)
5260 (push (nreverse current-group) groups))
5261 (setq group-status nil))
5262 (`(:grouptags) (setq group-status 'append))
5263 ((and `(,tag . ,_) (guard group-status))
5264 (if (eq group-status 'append) (push tag current-group)
5265 (setq current-group (list tag))))
5266 (_ nil)))))
5268 (defun org-file-contents (file &optional noerror)
5269 "Return the contents of FILE, as a string."
5270 (if (and file (file-readable-p file))
5271 (with-temp-buffer
5272 (insert-file-contents file)
5273 (buffer-string))
5274 (funcall (if noerror 'message 'error)
5275 "Cannot read file \"%s\"%s"
5276 file
5277 (let ((from (buffer-file-name (buffer-base-buffer))))
5278 (if from (concat " (referenced in file \"" from "\")") "")))))
5280 (defun org-extract-log-state-settings (x)
5281 "Extract the log state setting from a TODO keyword string.
5282 This will extract info from a string like \"WAIT(w@/!)\"."
5283 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
5284 (let ((kw (match-string 1 x))
5285 (log1 (and (match-end 3) (match-string 3 x)))
5286 (log2 (and (match-end 4) (match-string 4 x))))
5287 (and (or log1 log2)
5288 (list kw
5289 (and log1 (if (equal log1 "!") 'time 'note))
5290 (and log2 (if (equal log2 "!") 'time 'note)))))))
5292 (defun org-remove-keyword-keys (list)
5293 "Remove a pair of parenthesis at the end of each string in LIST."
5294 (mapcar (lambda (x)
5295 (if (string-match "(.*)$" x)
5296 (substring x 0 (match-beginning 0))
5298 list))
5300 (defun org-assign-fast-keys (alist)
5301 "Assign fast keys to a keyword-key alist.
5302 Respect keys that are already there."
5303 (let (new e (alt ?0))
5304 (while (setq e (pop alist))
5305 (if (or (memq (car e) '(:newline :grouptags :endgroup :startgroup))
5306 (cdr e)) ;; Key already assigned.
5307 (push e new)
5308 (let ((clist (string-to-list (downcase (car e))))
5309 (used (append new alist)))
5310 (when (= (car clist) ?@)
5311 (pop clist))
5312 (while (and clist (rassoc (car clist) used))
5313 (pop clist))
5314 (unless clist
5315 (while (rassoc alt used)
5316 (cl-incf alt)))
5317 (push (cons (car e) (or (car clist) alt)) new))))
5318 (nreverse new)))
5320 ;;; Some variables used in various places
5322 (defvar org-window-configuration nil
5323 "Used in various places to store a window configuration.")
5324 (defvar org-selected-window nil
5325 "Used in various places to store a window configuration.")
5326 (defvar org-finish-function nil
5327 "Function to be called when `C-c C-c' is used.
5328 This is for getting out of special buffers like capture.")
5329 (defvar org-last-state)
5331 ;; Defined somewhere in this file, but used before definition.
5332 (defvar org-entities) ;; defined in org-entities.el
5333 (defvar org-struct-menu)
5334 (defvar org-org-menu)
5335 (defvar org-tbl-menu)
5337 ;;;; Define the Org-mode
5339 ;; We use a before-change function to check if a table might need
5340 ;; an update.
5341 (defvar org-table-may-need-update t
5342 "Indicates that a table might need an update.
5343 This variable is set by `org-before-change-function'.
5344 `org-table-align' sets it back to nil.")
5345 (defun org-before-change-function (_beg _end)
5346 "Every change indicates that a table might need an update."
5347 (setq org-table-may-need-update t))
5348 (defvar org-mode-map)
5349 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
5350 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
5351 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
5352 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
5353 (defvar org-table-buffer-is-an nil)
5355 (defvar bidi-paragraph-direction)
5356 (defvar buffer-face-mode-face)
5358 (require 'outline)
5359 (when (and (not (keymapp outline-mode-map)) (featurep 'allout))
5360 (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"))
5361 (require 'noutline "noutline" 'noerror) ;; stock XEmacs does not have it
5363 ;; Other stuff we need.
5364 (require 'time-date)
5365 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
5366 (require 'easymenu)
5367 (autoload 'easy-menu-add "easymenu")
5368 (require 'overlay)
5370 ;; (require 'org-macs) moved higher up in the file before it is first used
5371 (require 'org-entities)
5372 ;; (require 'org-compat) moved higher up in the file before it is first used
5373 (require 'org-faces)
5374 (require 'org-list)
5375 (require 'org-pcomplete)
5376 (require 'org-src)
5377 (require 'org-footnote)
5378 (require 'org-macro)
5380 ;; babel
5381 (require 'ob)
5383 ;;;###autoload
5384 (define-derived-mode org-mode outline-mode "Org"
5385 "Outline-based notes management and organizer, alias
5386 \"Carsten's outline-mode for keeping track of everything.\"
5388 Org-mode develops organizational tasks around a NOTES file which
5389 contains information about projects as plain text. Org-mode is
5390 implemented on top of outline-mode, which is ideal to keep the content
5391 of large files well structured. It supports ToDo items, deadlines and
5392 time stamps, which magically appear in the diary listing of the Emacs
5393 calendar. Tables are easily created with a built-in table editor.
5394 Plain text URL-like links connect to websites, emails (VM), Usenet
5395 messages (Gnus), BBDB entries, and any files related to the project.
5396 For printing and sharing of notes, an Org-mode file (or a part of it)
5397 can be exported as a structured ASCII or HTML file.
5399 The following commands are available:
5401 \\{org-mode-map}"
5403 ;; Get rid of Outline menus, they are not needed
5404 ;; Need to do this here because define-derived-mode sets up
5405 ;; the keymap so late. Still, it is a waste to call this each time
5406 ;; we switch another buffer into org-mode.
5407 (if (featurep 'xemacs)
5408 (when (boundp 'outline-mode-menu-heading)
5409 ;; Assume this is Greg's port, it uses easymenu
5410 (easy-menu-remove outline-mode-menu-heading)
5411 (easy-menu-remove outline-mode-menu-show)
5412 (easy-menu-remove outline-mode-menu-hide))
5413 (define-key org-mode-map [menu-bar headings] 'undefined)
5414 (define-key org-mode-map [menu-bar hide] 'undefined)
5415 (define-key org-mode-map [menu-bar show] 'undefined))
5417 (org-load-modules-maybe)
5418 (when (featurep 'xemacs)
5419 (easy-menu-add org-org-menu)
5420 (easy-menu-add org-tbl-menu))
5421 (org-install-agenda-files-menu)
5422 (when org-descriptive-links (add-to-invisibility-spec '(org-link)))
5423 (add-to-invisibility-spec '(org-cwidth))
5424 (add-to-invisibility-spec '(org-hide-block . t))
5425 (when (featurep 'xemacs)
5426 (setq-local line-move-ignore-invisible t))
5427 (setq-local outline-regexp org-outline-regexp)
5428 (setq-local outline-level 'org-outline-level)
5429 (setq bidi-paragraph-direction 'left-to-right)
5430 (when (and org-ellipsis
5431 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
5432 (fboundp 'make-glyph-code))
5433 (unless org-display-table
5434 (setq org-display-table (make-display-table)))
5435 (set-display-table-slot
5436 org-display-table 4
5437 (vconcat (mapcar
5438 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
5439 org-ellipsis)))
5440 (if (stringp org-ellipsis) org-ellipsis "..."))))
5441 (setq buffer-display-table org-display-table))
5442 (org-set-regexps-and-options)
5443 (org-set-font-lock-defaults)
5444 (when (and org-tag-faces (not org-tags-special-faces-re))
5445 ;; tag faces set outside customize.... force initialization.
5446 (org-set-tag-faces 'org-tag-faces org-tag-faces))
5447 ;; Calc embedded
5448 (setq-local calc-embedded-open-mode "# ")
5449 ;; Modify a few syntax entries
5450 (modify-syntax-entry ?@ "w")
5451 (modify-syntax-entry ?\" "\"")
5452 (modify-syntax-entry ?\\ "_")
5453 (modify-syntax-entry ?~ "_")
5454 (setq-local font-lock-unfontify-region-function 'org-unfontify-region)
5455 ;; Activate before-change-function
5456 (setq-local org-table-may-need-update t)
5457 (org-add-hook 'before-change-functions 'org-before-change-function nil 'local)
5458 ;; Check for running clock before killing a buffer
5459 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
5460 ;; Initialize macros templates.
5461 (org-macro-initialize-templates)
5462 ;; Initialize radio targets.
5463 (org-update-radio-target-regexp)
5464 ;; Indentation.
5465 (setq-local indent-line-function 'org-indent-line)
5466 (setq-local indent-region-function 'org-indent-region)
5467 ;; Filling and auto-filling.
5468 (org-setup-filling)
5469 ;; Comments.
5470 (org-setup-comments-handling)
5471 ;; Initialize cache.
5472 (org-element-cache-reset)
5473 ;; Beginning/end of defun
5474 (setq-local beginning-of-defun-function 'org-backward-element)
5475 (setq-local end-of-defun-function
5476 (lambda ()
5477 (if (not (org-at-heading-p))
5478 (org-forward-element)
5479 (org-forward-element)
5480 (forward-char -1))))
5481 ;; Next error for sparse trees
5482 (setq-local next-error-function 'org-occur-next-match)
5483 ;; Make sure dependence stuff works reliably, even for users who set it
5484 ;; too late :-(
5485 (if org-enforce-todo-dependencies
5486 (add-hook 'org-blocker-hook
5487 'org-block-todo-from-children-or-siblings-or-parent)
5488 (remove-hook 'org-blocker-hook
5489 'org-block-todo-from-children-or-siblings-or-parent))
5490 (if org-enforce-todo-checkbox-dependencies
5491 (add-hook 'org-blocker-hook
5492 'org-block-todo-from-checkboxes)
5493 (remove-hook 'org-blocker-hook
5494 'org-block-todo-from-checkboxes))
5496 ;; Align options lines
5497 (setq-local
5498 align-mode-rules-list
5499 '((org-in-buffer-settings
5500 (regexp . "^[ \t]*#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
5501 (modes . '(org-mode)))))
5503 ;; Imenu
5504 (setq-local imenu-create-index-function 'org-imenu-get-tree)
5506 ;; Make isearch reveal context
5507 (setq-local outline-isearch-open-invisible-function
5508 (lambda (&rest _) (org-show-context 'isearch)))
5510 ;; Setup the pcomplete hooks
5511 (setq-local pcomplete-command-completion-function 'org-pcomplete-initial)
5512 (setq-local pcomplete-command-name-function 'org-command-at-point)
5513 (setq-local pcomplete-default-completion-function 'ignore)
5514 (setq-local pcomplete-parse-arguments-function 'org-parse-arguments)
5515 (setq-local pcomplete-termination-string "")
5516 (setq-local buffer-face-mode-face 'org-default)
5518 ;; If empty file that did not turn on Org mode automatically, make
5519 ;; it to.
5520 (when (and org-insert-mode-line-in-empty-file
5521 (org-called-interactively-p 'any)
5522 (= (point-min) (point-max)))
5523 (insert "# -*- mode: org -*-\n\n"))
5524 (unless org-inhibit-startup
5525 (org-unmodified
5526 (when org-startup-with-beamer-mode (org-beamer-mode))
5527 (when org-startup-align-all-tables
5528 (org-table-map-tables #'org-table-align t))
5529 (when org-startup-with-inline-images (org-display-inline-images))
5530 (when org-startup-with-latex-preview (org-toggle-latex-fragment))
5531 (unless org-inhibit-startup-visibility-stuff (org-set-startup-visibility))
5532 (when org-startup-truncated (setq truncate-lines t))
5533 (when org-startup-indented (require 'org-indent) (org-indent-mode 1))
5534 (org-refresh-effort-properties)))
5535 ;; Try to set `org-hide' face correctly.
5536 (let ((foreground (org-find-invisible-foreground)))
5537 (when foreground
5538 (set-face-foreground 'org-hide foreground))))
5540 ;; Update `customize-package-emacs-version-alist'
5541 (add-to-list 'customize-package-emacs-version-alist
5542 '(Org ("6.21b" . "23.1") ("6.33x" . "23.2")
5543 ("7.8.11" . "24.1") ("7.9.4" . "24.3")
5544 ("8.2.6" . "24.4") ("8.3" . "25.1")))
5546 (defvar org-mode-transpose-word-syntax-table
5547 (let ((st (make-syntax-table text-mode-syntax-table)))
5548 (dolist (c org-emphasis-alist st)
5549 (modify-syntax-entry (string-to-char (car c)) "w p" st))))
5551 (when (fboundp 'abbrev-table-put)
5552 (abbrev-table-put org-mode-abbrev-table
5553 :parents (list text-mode-abbrev-table)))
5555 (defun org-find-invisible-foreground ()
5556 (let ((candidates (remove
5557 "unspecified-bg"
5558 (nconc
5559 (list (face-background 'default)
5560 (face-background 'org-default))
5561 (mapcar
5562 (lambda (alist)
5563 (when (boundp alist)
5564 (cdr (assoc 'background-color (symbol-value alist)))))
5565 '(default-frame-alist initial-frame-alist window-system-default-frame-alist))
5566 (list (face-foreground 'org-hide))))))
5567 (car (remove nil candidates))))
5569 (defun org-current-time (&optional rounding-minutes past)
5570 "Current time, possibly rounded to ROUNDING-MINUTES.
5571 When ROUNDING-MINUTES is not an integer, fall back on the car of
5572 `org-time-stamp-rounding-minutes'. When PAST is non-nil, ensure
5573 the rounding returns a past time."
5574 (let ((r (or (and (integerp rounding-minutes) rounding-minutes)
5575 (car org-time-stamp-rounding-minutes)))
5576 (time (decode-time)) res)
5577 (if (< r 1)
5578 (current-time)
5579 (setq res
5580 (apply 'encode-time
5581 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
5582 (nthcdr 2 time))))
5583 (if (and past (< (org-float-time (time-subtract (current-time) res)) 0))
5584 (seconds-to-time (- (org-float-time res) (* r 60)))
5585 res))))
5587 (defun org-today ()
5588 "Return today date, considering `org-extend-today-until'."
5589 (time-to-days
5590 (time-subtract (current-time)
5591 (list 0 (* 3600 org-extend-today-until) 0))))
5593 ;;;; Font-Lock stuff, including the activators
5595 (defvar org-mouse-map (make-sparse-keymap))
5596 (org-defkey org-mouse-map [mouse-2] 'org-open-at-mouse)
5597 (org-defkey org-mouse-map [mouse-3] 'org-find-file-at-mouse)
5598 (when org-mouse-1-follows-link
5599 (org-defkey org-mouse-map [follow-link] 'mouse-face))
5600 (when org-tab-follows-link
5601 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
5602 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
5604 (require 'font-lock)
5606 (defconst org-non-link-chars "]\t\n\r<>")
5607 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "file+emacs"
5608 "file+sys" "news" "shell" "elisp" "doi" "message"
5609 "help"))
5610 (defvar org-link-types-re nil
5611 "Matches a link that has a url-like prefix like \"http:\"")
5612 (defvar org-link-re-with-space nil
5613 "Matches a link with spaces, optional angular brackets around it.")
5614 (defvar org-link-re-with-space2 nil
5615 "Matches a link with spaces, optional angular brackets around it.")
5616 (defvar org-link-re-with-space3 nil
5617 "Matches a link with spaces, only for internal part in bracket links.")
5618 (defvar org-angle-link-re nil
5619 "Matches link with angular brackets, spaces are allowed.")
5620 (defvar org-plain-link-re nil
5621 "Matches plain link, without spaces.")
5622 (defvar org-bracket-link-regexp nil
5623 "Matches a link in double brackets.")
5624 (defvar org-bracket-link-analytic-regexp nil
5625 "Regular expression used to analyze links.
5626 Here is what the match groups contain after a match:
5627 1: http:
5628 2: http
5629 3: path
5630 4: [desc]
5631 5: desc")
5632 (defvar org-bracket-link-analytic-regexp++ nil
5633 "Like `org-bracket-link-analytic-regexp', but include coderef internal type.")
5634 (defvar org-any-link-re nil
5635 "Regular expression matching any link.")
5637 (defconst org-match-sexp-depth 3
5638 "Number of stacked braces for sub/superscript matching.")
5640 (defun org-create-multibrace-regexp (left right n)
5641 "Create a regular expression which will match a balanced sexp.
5642 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
5643 as single character strings.
5644 The regexp returned will match the entire expression including the
5645 delimiters. It will also define a single group which contains the
5646 match except for the outermost delimiters. The maximum depth of
5647 stacked delimiters is N. Escaping delimiters is not possible."
5648 (let* ((nothing (concat "[^" left right "]*?"))
5649 (or "\\|")
5650 (re nothing)
5651 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
5652 (while (> n 1)
5653 (setq n (1- n)
5654 re (concat re or next)
5655 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
5656 (concat left "\\(" re "\\)" right)))
5658 (defconst org-match-substring-regexp
5659 (concat
5660 "\\(\\S-\\)\\([_^]\\)\\("
5661 "\\(?:" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
5662 "\\|"
5663 "\\(?:" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
5664 "\\|"
5665 "\\(?:\\*\\|[+-]?[[:alnum:].,\\]*[[:alnum:]]\\)\\)")
5666 "The regular expression matching a sub- or superscript.")
5668 (defconst org-match-substring-with-braces-regexp
5669 (concat
5670 "\\(\\S-\\)\\([_^]\\)"
5671 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)")
5672 "The regular expression matching a sub- or superscript, forcing braces.")
5674 (defun org-make-link-regexps ()
5675 "Update the link regular expressions.
5676 This should be called after the variable `org-link-types' has changed."
5677 (let ((types-re (regexp-opt org-link-types t)))
5678 (setq org-link-types-re
5679 (concat "\\`" types-re ":")
5680 org-link-re-with-space
5681 (concat "<?" types-re ":"
5682 "\\([^" org-non-link-chars " ]"
5683 "[^" org-non-link-chars "]*"
5684 "[^" org-non-link-chars " ]\\)>?")
5685 org-link-re-with-space2
5686 (concat "<?" types-re ":"
5687 "\\([^" org-non-link-chars " ]"
5688 "[^\t\n\r]*"
5689 "[^" org-non-link-chars " ]\\)>?")
5690 org-link-re-with-space3
5691 (concat "<?" types-re ":"
5692 "\\([^" org-non-link-chars " ]"
5693 "[^\t\n\r]*\\)")
5694 org-angle-link-re
5695 (format "<%s:\\([^>\n]*\\(?:\n[ \t]*[^> \t\n][^>\n]*\\)*\\)>"
5696 types-re)
5697 org-plain-link-re
5698 (concat
5699 "\\<" types-re ":"
5700 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9_]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
5701 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
5702 org-bracket-link-regexp
5703 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
5704 org-bracket-link-analytic-regexp
5705 (concat
5706 "\\[\\["
5707 "\\(" types-re ":\\)?"
5708 "\\([^]]+\\)"
5709 "\\]"
5710 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5711 "\\]")
5712 org-bracket-link-analytic-regexp++
5713 (concat
5714 "\\[\\["
5715 "\\(" (regexp-opt (cons "coderef" org-link-types) t) ":\\)?"
5716 "\\([^]]+\\)"
5717 "\\]"
5718 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
5719 "\\]")
5720 org-any-link-re
5721 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
5722 org-angle-link-re "\\)\\|\\("
5723 org-plain-link-re "\\)"))))
5725 (org-make-link-regexps)
5727 (defvar org-emph-face nil)
5729 (defun org-do-emphasis-faces (limit)
5730 "Run through the buffer and emphasize strings."
5731 (let (rtn a)
5732 (while (and (not rtn) (re-search-forward org-emph-re limit t))
5733 (let* ((border (char-after (match-beginning 3)))
5734 (bre (regexp-quote (char-to-string border))))
5735 (when (and (not (= border (char-after (match-beginning 4))))
5736 (not (string-match-p (concat bre ".*" bre)
5737 (replace-regexp-in-string
5738 "\n" " "
5739 (substring (match-string 2) 1 -1)))))
5740 (setq rtn t)
5741 (setq a (assoc (match-string 3) org-emphasis-alist))
5742 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
5743 'face
5744 (nth 1 a))
5745 (and (nth 2 a)
5746 (org-remove-flyspell-overlays-in
5747 (match-beginning 0) (match-end 0)))
5748 (add-text-properties (match-beginning 2) (match-end 2)
5749 '(font-lock-multiline t org-emphasis t))
5750 (when org-hide-emphasis-markers
5751 (add-text-properties (match-end 4) (match-beginning 5)
5752 '(invisible org-link))
5753 (add-text-properties (match-beginning 3) (match-end 3)
5754 '(invisible org-link)))))
5755 (goto-char (1+ (match-beginning 0))))
5756 rtn))
5758 (defun org-emphasize (&optional char)
5759 "Insert or change an emphasis, i.e. a font like bold or italic.
5760 If there is an active region, change that region to a new emphasis.
5761 If there is no region, just insert the marker characters and position
5762 the cursor between them.
5763 CHAR should be the marker character. If it is a space, it means to
5764 remove the emphasis of the selected region.
5765 If CHAR is not given (for example in an interactive call) it will be
5766 prompted for."
5767 (interactive)
5768 (let ((erc org-emphasis-regexp-components)
5769 (string "") beg end move s)
5770 (if (org-region-active-p)
5771 (setq beg (region-beginning)
5772 end (region-end)
5773 string (buffer-substring beg end))
5774 (setq move t))
5776 (unless char
5777 (message "Emphasis marker or tag: [%s]"
5778 (mapconcat #'car org-emphasis-alist ""))
5779 (setq char (read-char-exclusive)))
5780 (if (equal char ?\s)
5781 (setq s ""
5782 move nil)
5783 (unless (assoc (char-to-string char) org-emphasis-alist)
5784 (user-error "No such emphasis marker: \"%c\"" char))
5785 (setq s (char-to-string char)))
5786 (while (and (> (length string) 1)
5787 (equal (substring string 0 1) (substring string -1))
5788 (assoc (substring string 0 1) org-emphasis-alist))
5789 (setq string (substring string 1 -1)))
5790 (setq string (concat s string s))
5791 (when beg (delete-region beg end))
5792 (unless (or (bolp)
5793 (string-match (concat "[" (nth 0 erc) "\n]")
5794 (char-to-string (char-before (point)))))
5795 (insert " "))
5796 (unless (or (eobp)
5797 (string-match (concat "[" (nth 1 erc) "\n]")
5798 (char-to-string (char-after (point)))))
5799 (insert " ") (backward-char 1))
5800 (insert string)
5801 (and move (backward-char 1))))
5803 (defconst org-nonsticky-props
5804 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text htmlize-link))
5806 (defsubst org-rear-nonsticky-at (pos)
5807 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
5809 (defun org-activate-plain-links (limit)
5810 "Add link properties for plain links."
5811 (when (and (re-search-forward org-plain-link-re limit t)
5812 (not (org-in-src-block-p)))
5813 (let ((face (get-text-property (max (1- (match-beginning 0)) (point-min))
5814 'face))
5815 (link (org-match-string-no-properties 0)))
5816 (unless (if (consp face) (memq 'org-tag face) (eq 'org-tag face))
5817 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5818 (add-text-properties (match-beginning 0) (match-end 0)
5819 (list 'mouse-face 'highlight
5820 'face 'org-link
5821 'htmlize-link `(:uri ,link)
5822 'keymap org-mouse-map))
5823 (org-rear-nonsticky-at (match-end 0))
5824 t))))
5826 (defun org-activate-code (limit)
5827 (when (re-search-forward "^[ \t]*\\(:\\(?: .*\\|$\\)\n?\\)" limit t)
5828 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5829 (remove-text-properties (match-beginning 0) (match-end 0)
5830 '(display t invisible t intangible t))
5833 (defcustom org-src-fontify-natively t
5834 "When non-nil, fontify code in code blocks."
5835 :type 'boolean
5836 :version "24.4"
5837 :package-version '(Org . "8.3")
5838 :group 'org-appearance
5839 :group 'org-babel)
5841 (defcustom org-allow-promoting-top-level-subtree nil
5842 "When non-nil, allow promoting a top level subtree.
5843 The leading star of the top level headline will be replaced
5844 by a #."
5845 :type 'boolean
5846 :version "24.1"
5847 :group 'org-appearance)
5849 (defun org-fontify-meta-lines-and-blocks (limit)
5850 (condition-case nil
5851 (org-fontify-meta-lines-and-blocks-1 limit)
5852 (error (message "org-mode fontification error in %S at %d"
5853 (current-buffer)
5854 (line-number-at-pos)))))
5856 (defun org-fontify-meta-lines-and-blocks-1 (limit)
5857 "Fontify #+ lines and blocks."
5858 (let ((case-fold-search t))
5859 (when (re-search-forward
5860 "^\\([ \t]*#\\(\\(\\+[a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)[ \t]*\\(\\([^ \t\n]*\\)[ \t]*\\(.*\\)\\)\\)"
5861 limit t)
5862 (let ((beg (match-beginning 0))
5863 (block-start (match-end 0))
5864 (block-end nil)
5865 (lang (match-string 7))
5866 (beg1 (line-beginning-position 2))
5867 (dc1 (downcase (match-string 2)))
5868 (dc3 (downcase (match-string 3)))
5869 end end1 quoting block-type)
5870 (cond
5871 ((and (match-end 4) (equal dc3 "+begin"))
5872 ;; Truly a block
5873 (setq block-type (downcase (match-string 5))
5874 quoting (member block-type org-protecting-blocks))
5875 (when (re-search-forward
5876 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
5877 nil t) ;; on purpose, we look further than LIMIT
5878 (setq end (min (point-max) (match-end 0))
5879 end1 (min (point-max) (1- (match-beginning 0))))
5880 (setq block-end (match-beginning 0))
5881 (when quoting
5882 (org-remove-flyspell-overlays-in beg1 end1)
5883 (remove-text-properties beg end
5884 '(display t invisible t intangible t)))
5885 (add-text-properties
5886 beg end '(font-lock-fontified t font-lock-multiline t))
5887 (add-text-properties beg beg1 '(face org-meta-line))
5888 (org-remove-flyspell-overlays-in beg beg1)
5889 (add-text-properties ; For end_src
5890 end1 (min (point-max) (1+ end)) '(face org-meta-line))
5891 (org-remove-flyspell-overlays-in end1 end)
5892 (cond
5893 ((and lang (not (string= lang "")) org-src-fontify-natively)
5894 (org-src-font-lock-fontify-block lang block-start block-end)
5895 (add-text-properties beg1 block-end '(src-block t)))
5896 (quoting
5897 (add-text-properties beg1 (min (point-max) (1+ end1))
5898 '(face org-block))) ; end of source block
5899 ((not org-fontify-quote-and-verse-blocks))
5900 ((string= block-type "quote")
5901 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-quote)))
5902 ((string= block-type "verse")
5903 (add-text-properties beg1 (min (point-max) (1+ end1)) '(face org-verse))))
5904 (add-text-properties beg beg1 '(face org-block-begin-line))
5905 (add-text-properties (min (point-max) (1+ end)) (min (point-max) (1+ end1))
5906 '(face org-block-end-line))
5908 ((member dc1 '("+title:" "+author:" "+email:" "+date:"))
5909 (org-remove-flyspell-overlays-in
5910 (match-beginning 0)
5911 (if (equal "+title:" dc1) (match-end 2) (match-end 0)))
5912 (add-text-properties
5913 beg (match-end 3)
5914 (if (member (intern (substring dc1 1 -1)) org-hidden-keywords)
5915 '(font-lock-fontified t invisible t)
5916 '(font-lock-fontified t face org-document-info-keyword)))
5917 (add-text-properties
5918 (match-beginning 6) (min (point-max) (1+ (match-end 6)))
5919 (if (string-equal dc1 "+title:")
5920 '(font-lock-fontified t face org-document-title)
5921 '(font-lock-fontified t face org-document-info))))
5922 ((equal dc1 "+caption:")
5923 (org-remove-flyspell-overlays-in (match-end 2) (match-end 0))
5924 (remove-text-properties (match-beginning 0) (match-end 0)
5925 '(display t invisible t intangible t))
5926 (add-text-properties (match-beginning 1) (match-end 3)
5927 '(font-lock-fontified t face org-meta-line))
5928 (add-text-properties (match-beginning 6) (+ (match-end 6) 1)
5929 '(font-lock-fontified t face org-block))
5931 ((member dc3 '(" " ""))
5932 (org-remove-flyspell-overlays-in beg (match-end 0))
5933 (add-text-properties
5934 beg (match-end 0)
5935 '(font-lock-fontified t face font-lock-comment-face)))
5936 (t ;; just any other in-buffer setting, but not indented
5937 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5938 (remove-text-properties (match-beginning 0) (match-end 0)
5939 '(display t invisible t intangible t))
5940 (add-text-properties beg (match-end 0)
5941 '(font-lock-fontified t face org-meta-line))
5942 t))))))
5944 (defun org-fontify-drawers (limit)
5945 "Fontify drawers."
5946 (when (re-search-forward org-drawer-regexp limit t)
5947 (add-text-properties
5948 (match-beginning 0) (match-end 0)
5949 '(font-lock-fontified t face org-special-keyword))
5950 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5953 (defun org-fontify-macros (limit)
5954 "Fontify macros."
5955 (when (re-search-forward "\\({{{\\).+?\\(}}}\\)" limit t)
5956 (add-text-properties
5957 (match-beginning 0) (match-end 0)
5958 '(font-lock-fontified t face org-macro))
5959 (when org-hide-macro-markers
5960 (add-text-properties (match-end 2) (match-beginning 2)
5961 '(invisible t))
5962 (add-text-properties (match-beginning 1) (match-end 1)
5963 '(invisible t)))
5964 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5967 (defun org-activate-angle-links (limit)
5968 "Add text properties for angle links."
5969 (when (and (re-search-forward org-angle-link-re limit t)
5970 (not (org-in-src-block-p)))
5971 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
5972 (add-text-properties (match-beginning 0) (match-end 0)
5973 (list 'mouse-face 'highlight
5974 'keymap org-mouse-map
5975 'font-lock-multiline t))
5976 (org-rear-nonsticky-at (match-end 0))
5979 (defun org-activate-footnote-links (limit)
5980 "Add text properties for footnotes."
5981 (let ((fn (org-footnote-next-reference-or-definition limit)))
5982 (when fn
5983 (let* ((beg (nth 1 fn))
5984 (end (nth 2 fn))
5985 (label (car fn))
5986 (referencep (/= (line-beginning-position) beg)))
5987 (when (and referencep (nth 3 fn))
5988 (save-excursion
5989 (goto-char beg)
5990 (search-forward (or label "fn:"))
5991 (org-remove-flyspell-overlays-in beg (match-end 0))))
5992 (add-text-properties beg end
5993 (list 'mouse-face 'highlight
5994 'keymap org-mouse-map
5995 'help-echo
5996 (if referencep "Footnote reference"
5997 "Footnote definition")
5998 'font-lock-fontified t
5999 'font-lock-multiline t
6000 'face 'org-footnote))))))
6002 (defun org-activate-bracket-links (limit)
6003 "Add text properties for bracketed links."
6004 (when (and (re-search-forward org-bracket-link-regexp limit t)
6005 (not (org-in-src-block-p)))
6006 (let* ((hl (org-match-string-no-properties 1))
6007 (help (concat "LINK: " (save-match-data (org-link-unescape hl))))
6008 (ip (org-maybe-intangible
6009 (list 'invisible 'org-link
6010 'keymap org-mouse-map 'mouse-face 'highlight
6011 'font-lock-multiline t 'help-echo help
6012 'htmlize-link `(:uri ,hl))))
6013 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
6014 'font-lock-multiline t 'help-echo help
6015 'htmlize-link `(:uri ,hl))))
6016 ;; We need to remove the invisible property here. Table narrowing
6017 ;; may have made some of this invisible.
6018 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6019 (remove-text-properties (match-beginning 0) (match-end 0)
6020 '(invisible nil))
6021 (if (match-end 3)
6022 (progn
6023 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
6024 (org-rear-nonsticky-at (match-beginning 3))
6025 (add-text-properties (match-beginning 3) (match-end 3) vp)
6026 (org-rear-nonsticky-at (match-end 3))
6027 (add-text-properties (match-end 3) (match-end 0) ip)
6028 (org-rear-nonsticky-at (match-end 0)))
6029 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
6030 (org-rear-nonsticky-at (match-beginning 1))
6031 (add-text-properties (match-beginning 1) (match-end 1) vp)
6032 (org-rear-nonsticky-at (match-end 1))
6033 (add-text-properties (match-end 1) (match-end 0) ip)
6034 (org-rear-nonsticky-at (match-end 0)))
6035 t)))
6037 (defun org-activate-dates (limit)
6038 "Add text properties for dates."
6039 (when (and (re-search-forward org-tsr-regexp-both limit t)
6040 (not (equal (char-before (match-beginning 0)) 91)))
6041 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
6042 (add-text-properties (match-beginning 0) (match-end 0)
6043 (list 'mouse-face 'highlight
6044 'keymap org-mouse-map))
6045 (org-rear-nonsticky-at (match-end 0))
6046 (when org-display-custom-times
6047 (if (match-end 3)
6048 (org-display-custom-time (match-beginning 3) (match-end 3))
6049 (org-display-custom-time (match-beginning 1) (match-end 1))))
6052 (defvar-local org-target-link-regexp nil
6053 "Regular expression matching radio targets in plain text.")
6055 (defconst org-target-regexp (let ((border "[^<>\n\r \t]"))
6056 (format "<<\\(%s\\|%s[^<>\n\r]*%s\\)>>"
6057 border border border))
6058 "Regular expression matching a link target.")
6060 (defconst org-radio-target-regexp (format "<%s>" org-target-regexp)
6061 "Regular expression matching a radio target.")
6063 (defconst org-any-target-regexp
6064 (format "%s\\|%s" org-radio-target-regexp org-target-regexp)
6065 "Regular expression matching any target.")
6067 (defun org-activate-target-links (limit)
6068 "Add text properties for target matches."
6069 (when org-target-link-regexp
6070 (let ((case-fold-search t))
6071 (when (re-search-forward org-target-link-regexp limit t)
6072 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6073 (add-text-properties (match-beginning 1) (match-end 1)
6074 (list 'mouse-face 'highlight
6075 'keymap org-mouse-map
6076 'help-echo "Radio target link"
6077 'org-linked-text t))
6078 (org-rear-nonsticky-at (match-end 1))
6079 t))))
6081 (defun org-update-radio-target-regexp ()
6082 "Find all radio targets in this file and update the regular expression.
6083 Also refresh fontification if needed."
6084 (interactive)
6085 (let ((old-regexp org-target-link-regexp)
6086 (before-re "\\(?:^\\|[^[:alnum:]]\\)\\(")
6087 (after-re "\\)\\(?:$\\|[^[:alnum:]]\\)")
6088 (targets
6089 (org-with-wide-buffer
6090 (goto-char (point-min))
6091 (let (rtn)
6092 (while (re-search-forward org-radio-target-regexp nil t)
6093 ;; Make sure point is really within the object.
6094 (backward-char)
6095 (let ((obj (org-element-context)))
6096 (when (eq (org-element-type obj) 'radio-target)
6097 (cl-pushnew (org-element-property :value obj) rtn
6098 :test #'equal))))
6099 rtn))))
6100 (setq org-target-link-regexp
6101 (and targets
6102 (concat before-re
6103 (mapconcat
6104 (lambda (x)
6105 (replace-regexp-in-string
6106 " +" "\\s-+" (regexp-quote x) t t))
6107 targets
6108 "\\|")
6109 after-re)))
6110 (unless (equal old-regexp org-target-link-regexp)
6111 ;; Clean-up cache.
6112 (let ((regexp (cond ((not old-regexp) org-target-link-regexp)
6113 ((not org-target-link-regexp) old-regexp)
6115 (concat before-re
6116 (mapconcat
6117 (lambda (re)
6118 (substring re (length before-re)
6119 (- (length after-re))))
6120 (list old-regexp org-target-link-regexp)
6121 "\\|")
6122 after-re)))))
6123 (org-with-wide-buffer
6124 (goto-char (point-min))
6125 (while (re-search-forward regexp nil t)
6126 (org-element-cache-refresh (match-beginning 1)))))
6127 ;; Re fontify buffer.
6128 (when (memq 'radio org-highlight-links)
6129 (org-restart-font-lock)))))
6131 (defun org-hide-wide-columns (limit)
6132 (let (s e)
6133 (setq s (text-property-any (point) (or limit (point-max))
6134 'org-cwidth t))
6135 (when s
6136 (setq e (next-single-property-change s 'org-cwidth))
6137 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
6138 (goto-char e)
6139 t)))
6141 (defvar org-latex-and-related-regexp nil
6142 "Regular expression for highlighting LaTeX, entities and sub/superscript.")
6144 (defun org-compute-latex-and-related-regexp ()
6145 "Compute regular expression for LaTeX, entities and sub/superscript.
6146 Result depends on variable `org-highlight-latex-and-related'."
6147 (setq-local
6148 org-latex-and-related-regexp
6149 (let* ((re-sub
6150 (cond ((not (memq 'script org-highlight-latex-and-related)) nil)
6151 ((eq org-use-sub-superscripts '{})
6152 (list org-match-substring-with-braces-regexp))
6153 (org-use-sub-superscripts (list org-match-substring-regexp))))
6154 (re-latex
6155 (when (memq 'latex org-highlight-latex-and-related)
6156 (let ((matchers (plist-get org-format-latex-options :matchers)))
6157 (delq nil
6158 (mapcar (lambda (x)
6159 (and (member (car x) matchers) (nth 1 x)))
6160 org-latex-regexps)))))
6161 (re-entities
6162 (when (memq 'entities org-highlight-latex-and-related)
6163 (list "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]]\\)"))))
6164 (mapconcat 'identity (append re-latex re-entities re-sub) "\\|"))))
6166 (defun org-do-latex-and-related (limit)
6167 "Highlight LaTeX snippets and environments, entities and sub/superscript.
6168 LIMIT bounds the search for syntax to highlight. Stop at first
6169 highlighted object, if any. Return t if some highlighting was
6170 done, nil otherwise."
6171 (when (org-string-nw-p org-latex-and-related-regexp)
6172 (catch 'found
6173 (while (re-search-forward org-latex-and-related-regexp limit t)
6174 (unless
6175 (cl-some
6176 (lambda (f)
6177 (memq f '(org-code org-verbatim underline org-special-keyword)))
6178 (save-excursion
6179 (goto-char (1+ (match-beginning 0)))
6180 (face-at-point nil t)))
6181 (let ((offset (if (memq (char-after (1+ (match-beginning 0)))
6182 '(?_ ?^))
6184 0)))
6185 (font-lock-prepend-text-property
6186 (+ offset (match-beginning 0)) (match-end 0)
6187 'face 'org-latex-and-related)
6188 (add-text-properties (+ offset (match-beginning 0)) (match-end 0)
6189 '(font-lock-multiline t)))
6190 (throw 'found t)))
6191 nil)))
6193 (defun org-restart-font-lock ()
6194 "Restart `font-lock-mode', to force refontification."
6195 (when (and (boundp 'font-lock-mode) font-lock-mode)
6196 (font-lock-mode -1)
6197 (font-lock-mode 1)))
6199 (defun org-activate-tags (limit)
6200 (when (re-search-forward
6201 (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$") limit t)
6202 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
6203 (add-text-properties (match-beginning 1) (match-end 1)
6204 (list 'mouse-face 'highlight
6205 'keymap org-mouse-map))
6206 (org-rear-nonsticky-at (match-end 1))
6209 (defun org-outline-level ()
6210 "Compute the outline level of the heading at point.
6212 If this is called at a normal headline, the level is the number
6213 of stars. Use `org-reduced-level' to remove the effect of
6214 `org-odd-levels'. Unlike to `org-current-level', this function
6215 takes into consideration inlinetasks."
6216 (org-with-wide-buffer
6217 (end-of-line)
6218 (if (re-search-backward org-outline-regexp-bol nil t)
6219 (1- (- (match-end 0) (match-beginning 0)))
6220 0)))
6222 (defvar org-font-lock-keywords nil)
6224 (defsubst org-re-property (property &optional literal allow-null value)
6225 "Return a regexp matching a PROPERTY line.
6227 When optional argument LITERAL is non-nil, do not quote PROPERTY.
6228 This is useful when PROPERTY is a regexp. When ALLOW-NULL is
6229 non-nil, match properties even without a value.
6231 Match group 3 is set to the value when it exists. If there is no
6232 value and ALLOW-NULL is non-nil, it is set to the empty string.
6234 With optional argument VALUE, match only property lines with
6235 that value; in this case, ALLOW-NULL is ignored. VALUE is quoted
6236 unless LITERAL is non-nil."
6237 (concat
6238 "^\\(?4:[ \t]*\\)"
6239 (format "\\(?1::\\(?2:%s\\):\\)"
6240 (if literal property (regexp-quote property)))
6241 (cond (value
6242 (format "[ \t]+\\(?3:%s\\)\\(?5:[ \t]*\\)$"
6243 (if literal value (regexp-quote value))))
6244 (allow-null
6245 "\\(?:\\(?3:$\\)\\|[ \t]+\\(?3:.*?\\)\\)\\(?5:[ \t]*\\)$")
6247 "[ \t]+\\(?3:[^ \r\t\n]+.*?\\)\\(?5:[ \t]*\\)$"))))
6249 (defconst org-property-re
6250 (org-re-property "\\S-+" 'literal t)
6251 "Regular expression matching a property line.
6252 There are four matching groups:
6253 1: :PROPKEY: including the leading and trailing colon,
6254 2: PROPKEY without the leading and trailing colon,
6255 3: PROPVAL without leading or trailing spaces,
6256 4: the indentation of the current line,
6257 5: trailing whitespace.")
6259 (defvar org-font-lock-hook nil
6260 "Functions to be called for special font lock stuff.")
6262 (defvar org-font-lock-extra-keywords nil) ;Dynamically scoped.
6264 (defvar org-font-lock-set-keywords-hook nil
6265 "Functions that can manipulate `org-font-lock-extra-keywords'.
6266 This is called after `org-font-lock-extra-keywords' is defined, but before
6267 it is installed to be used by font lock. This can be useful if something
6268 needs to be inserted at a specific position in the font-lock sequence.")
6270 (defun org-font-lock-hook (limit)
6271 "Run `org-font-lock-hook' within LIMIT."
6272 (run-hook-with-args 'org-font-lock-hook limit))
6274 (defun org-set-font-lock-defaults ()
6275 "Set font lock defaults for the current buffer."
6276 (let* ((em org-fontify-emphasized-text)
6277 (lk org-highlight-links)
6278 (org-font-lock-extra-keywords
6279 (list
6280 ;; Call the hook
6281 '(org-font-lock-hook)
6282 ;; Headlines
6283 `(,(if org-fontify-whole-heading-line
6284 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
6285 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
6286 (1 (org-get-level-face 1))
6287 (2 (org-get-level-face 2))
6288 (3 (org-get-level-face 3)))
6289 ;; Table lines
6290 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
6291 (1 'org-table t))
6292 ;; Table internals
6293 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
6294 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
6295 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
6296 '("| *\\(<[lrc]?[0-9]*>\\)" (1 'org-formula t))
6297 ;; Drawers
6298 '(org-fontify-drawers)
6299 ;; Properties
6300 (list org-property-re
6301 '(1 'org-special-keyword t)
6302 '(3 'org-property-value t))
6303 ;; Links
6304 (when (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
6305 (when (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
6306 (when (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
6307 (when (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
6308 (when (memq 'radio lk) '(org-activate-target-links (1 'org-link t)))
6309 (when (memq 'date lk) '(org-activate-dates (0 'org-date t)))
6310 (when (memq 'footnote lk) '(org-activate-footnote-links))
6311 ;; Targets.
6312 (list org-any-target-regexp '(0 'org-target t))
6313 ;; Diary sexps.
6314 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
6315 ;; Macro
6316 '(org-fontify-macros)
6317 '(org-hide-wide-columns (0 nil append))
6318 ;; TODO keyword
6319 (list (format org-heading-keyword-regexp-format
6320 org-todo-regexp)
6321 '(2 (org-get-todo-face 2) t))
6322 ;; DONE
6323 (if org-fontify-done-headline
6324 (list (format org-heading-keyword-regexp-format
6325 (concat
6326 "\\(?:"
6327 (mapconcat 'regexp-quote org-done-keywords "\\|")
6328 "\\)"))
6329 '(2 'org-headline-done t))
6330 nil)
6331 ;; Priorities
6332 '(org-font-lock-add-priority-faces)
6333 ;; Tags
6334 '(org-font-lock-add-tag-faces)
6335 ;; Tags groups
6336 (when (and org-group-tags org-tag-groups-alist)
6337 (list (concat org-outline-regexp-bol ".+\\(:"
6338 (regexp-opt (mapcar 'car org-tag-groups-alist))
6339 ":\\).*$")
6340 '(1 'org-tag-group prepend)))
6341 ;; Special keywords
6342 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
6343 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
6344 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
6345 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
6346 ;; Emphasis
6347 (when em
6348 (if (featurep 'xemacs)
6349 '(org-do-emphasis-faces (0 nil append))
6350 '(org-do-emphasis-faces)))
6351 ;; Checkboxes
6352 '("^[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\)[ \t]+\\(?:\\[@\\(?:start:\\)?[0-9]+\\][ \t]*\\)?\\(\\[[- X]\\]\\)"
6353 1 'org-checkbox prepend)
6354 (when (cdr (assq 'checkbox org-list-automatic-rules))
6355 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
6356 (0 (org-get-checkbox-statistics-face) t)))
6357 ;; Description list items
6358 '("^[ \t]*[-+*][ \t]+\\(.*?[ \t]+::\\)\\([ \t]+\\|$\\)"
6359 1 'org-list-dt prepend)
6360 ;; ARCHIVEd headings
6361 (list (concat
6362 org-outline-regexp-bol
6363 "\\(.*:" org-archive-tag ":.*\\)")
6364 '(1 'org-archived prepend))
6365 ;; Specials
6366 '(org-do-latex-and-related)
6367 '(org-fontify-entities)
6368 '(org-raise-scripts)
6369 ;; Code
6370 '(org-activate-code (1 'org-code t))
6371 ;; COMMENT
6372 (list (format
6373 "^\\*+\\(?: +%s\\)?\\(?: +\\[#[A-Z0-9]\\]\\)? +\\(?9:%s\\)\\(?: \\|$\\)"
6374 org-todo-regexp
6375 org-comment-string)
6376 '(9 'org-special-keyword t))
6377 ;; Blocks and meta lines
6378 '(org-fontify-meta-lines-and-blocks))))
6379 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
6380 (run-hooks 'org-font-lock-set-keywords-hook)
6381 ;; Now set the full font-lock-keywords
6382 (setq-local org-font-lock-keywords org-font-lock-extra-keywords)
6383 (setq-local font-lock-defaults
6384 '(org-font-lock-keywords t nil nil backward-paragraph))
6385 (kill-local-variable 'font-lock-keywords) nil))
6387 (defun org-toggle-pretty-entities ()
6388 "Toggle the composition display of entities as UTF8 characters."
6389 (interactive)
6390 (setq-local org-pretty-entities (not org-pretty-entities))
6391 (org-restart-font-lock)
6392 (if org-pretty-entities
6393 (message "Entities are now displayed as UTF8 characters")
6394 (save-restriction
6395 (widen)
6396 (org-decompose-region (point-min) (point-max))
6397 (message "Entities are now displayed as plain text"))))
6399 (defvar-local org-custom-properties-overlays nil
6400 "List of overlays used for custom properties.")
6402 (defun org-toggle-custom-properties-visibility ()
6403 "Display or hide properties in `org-custom-properties'."
6404 (interactive)
6405 (if org-custom-properties-overlays
6406 (progn (mapc #'delete-overlay org-custom-properties-overlays)
6407 (setq org-custom-properties-overlays nil))
6408 (when org-custom-properties
6409 (org-with-wide-buffer
6410 (goto-char (point-min))
6411 (let ((regexp (org-re-property (regexp-opt org-custom-properties) t t)))
6412 (while (re-search-forward regexp nil t)
6413 (let ((end (cdr (save-match-data (org-get-property-block)))))
6414 (when (and end (< (point) end))
6415 ;; Hide first custom property in current drawer.
6416 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6417 (overlay-put o 'invisible t)
6418 (overlay-put o 'org-custom-property t)
6419 (push o org-custom-properties-overlays))
6420 ;; Hide additional custom properties in the same drawer.
6421 (while (re-search-forward regexp end t)
6422 (let ((o (make-overlay (match-beginning 0) (1+ (match-end 0)))))
6423 (overlay-put o 'invisible t)
6424 (overlay-put o 'org-custom-property t)
6425 (push o org-custom-properties-overlays)))))
6426 ;; Each entry is limited to a single property drawer.
6427 (outline-next-heading)))))))
6429 (defun org-fontify-entities (limit)
6430 "Find an entity to fontify."
6431 (let (ee)
6432 (when org-pretty-entities
6433 (catch 'match
6434 ;; "\_ "-family is left out on purpose. Only the first one,
6435 ;; i.e., "\_ ", could be fontified anyway, and it would be
6436 ;; confusing when adding a second white space character.
6437 (while (re-search-forward
6438 "\\\\\\(there4\\|sup[123]\\|frac[13][24]\\|[a-zA-Z]+\\)\\($\\|{}\\|[^[:alpha:]\n]\\)"
6439 limit t)
6440 (when (and (not (org-at-comment-p))
6441 (setq ee (org-entity-get (match-string 1)))
6442 (= (length (nth 6 ee)) 1))
6443 (let* ((end (if (equal (match-string 2) "{}")
6444 (match-end 2)
6445 (match-end 1))))
6446 (add-text-properties
6447 (match-beginning 0) end
6448 (list 'font-lock-fontified t))
6449 (compose-region (match-beginning 0) end
6450 (nth 6 ee) nil)
6451 (backward-char 1)
6452 (throw 'match t))))
6453 nil))))
6455 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
6456 "Fontify string S like in Org-mode."
6457 (with-temp-buffer
6458 (insert s)
6459 (let ((org-odd-levels-only odd-levels))
6460 (org-mode)
6461 (org-font-lock-ensure)
6462 (buffer-string))))
6464 (defvar org-m nil)
6465 (defvar org-l nil)
6466 (defvar org-f nil)
6467 (defun org-get-level-face (n)
6468 "Get the right face for match N in font-lock matching of headlines."
6469 (setq org-l (- (match-end 2) (match-beginning 1) 1))
6470 (when org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
6471 (if org-cycle-level-faces
6472 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
6473 (setq org-f (nth (1- (min org-l org-n-level-faces)) org-level-faces)))
6474 (cond
6475 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
6476 ((eq n 2) org-f)
6477 (t (unless org-level-color-stars-only org-f))))
6479 (defun org-face-from-face-or-color (context inherit face-or-color)
6480 "Create a face list that inherits INHERIT, but sets the foreground color.
6481 When FACE-OR-COLOR is not a string, just return it."
6482 (if (stringp face-or-color)
6483 (list :inherit inherit
6484 (cdr (assoc context org-faces-easy-properties))
6485 face-or-color)
6486 face-or-color))
6488 (defun org-get-todo-face (kwd)
6489 "Get the right face for a TODO keyword KWD.
6490 If KWD is a number, get the corresponding match group."
6491 (when (numberp kwd) (setq kwd (match-string kwd)))
6492 (or (org-face-from-face-or-color
6493 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
6494 (and (member kwd org-done-keywords) 'org-done)
6495 'org-todo))
6497 (defun org-get-priority-face (priority)
6498 "Get the right face for PRIORITY.
6499 PRIORITY is a character."
6500 (or (org-face-from-face-or-color
6501 'priority 'org-priority (cdr (assq priority org-priority-faces)))
6502 'org-priority))
6504 (defun org-get-tag-face (tag)
6505 "Get the right face for TAG.
6506 If TAG is a number, get the corresponding match group."
6507 (let ((tag (if (wholenump tag) (match-string tag) tag)))
6508 (or (org-face-from-face-or-color
6509 'tag 'org-tag (cdr (assoc tag org-tag-faces)))
6510 'org-tag)))
6512 (defun org-font-lock-add-priority-faces (limit)
6513 "Add the special priority faces."
6514 (while (re-search-forward "^\\*+ .*?\\(\\[#\\(.\\)\\]\\)" limit t)
6515 (add-text-properties
6516 (match-beginning 1) (match-end 1)
6517 (list 'face (org-get-priority-face (string-to-char (match-string 2)))
6518 'font-lock-fontified t))))
6520 (defun org-font-lock-add-tag-faces (limit)
6521 "Add the special tag faces."
6522 (when (and org-tag-faces org-tags-special-faces-re)
6523 (while (re-search-forward org-tags-special-faces-re limit t)
6524 (add-text-properties (match-beginning 1) (match-end 1)
6525 (list 'face (org-get-tag-face 1)
6526 'font-lock-fontified t))
6527 (backward-char 1))))
6529 (defun org-unfontify-region (beg end &optional _maybe_loudly)
6530 "Remove fontification and activation overlays from links."
6531 (font-lock-default-unfontify-region beg end)
6532 (let* ((buffer-undo-list t)
6533 (inhibit-read-only t) (inhibit-point-motion-hooks t)
6534 (inhibit-modification-hooks t)
6535 deactivate-mark buffer-file-name buffer-file-truename)
6536 (org-decompose-region beg end)
6537 (remove-text-properties beg end
6538 '(mouse-face t keymap t org-linked-text t
6539 invisible t intangible t
6540 org-emphasis t))
6541 (org-remove-font-lock-display-properties beg end)))
6543 (defconst org-script-display '(((raise -0.3) (height 0.7))
6544 ((raise 0.3) (height 0.7))
6545 ((raise -0.5))
6546 ((raise 0.5)))
6547 "Display properties for showing superscripts and subscripts.")
6549 (defun org-remove-font-lock-display-properties (beg end)
6550 "Remove specific display properties that have been added by font lock.
6551 The will remove the raise properties that are used to show superscripts
6552 and subscripts."
6553 (let (next prop)
6554 (while (< beg end)
6555 (setq next (next-single-property-change beg 'display nil end)
6556 prop (get-text-property beg 'display))
6557 (when (member prop org-script-display)
6558 (put-text-property beg next 'display nil))
6559 (setq beg next))))
6561 (defun org-raise-scripts (limit)
6562 "Add raise properties to sub/superscripts."
6563 (when (and org-pretty-entities org-pretty-entities-include-sub-superscripts
6564 (re-search-forward
6565 (if (eq org-use-sub-superscripts t)
6566 org-match-substring-regexp
6567 org-match-substring-with-braces-regexp)
6568 limit t))
6569 (let* ((pos (point)) table-p comment-p
6570 (mpos (match-beginning 3))
6571 (emph-p (get-text-property mpos 'org-emphasis))
6572 (link-p (get-text-property mpos 'mouse-face))
6573 (keyw-p (eq 'org-special-keyword (get-text-property mpos 'face))))
6574 (goto-char (point-at-bol))
6575 (setq table-p (org-looking-at-p org-table-dataline-regexp)
6576 comment-p (org-looking-at-p "^[ \t]*#[ +]"))
6577 (goto-char pos)
6578 ;; Handle a_b^c
6579 (when (member (char-after) '(?_ ?^)) (goto-char (1- pos)))
6580 (unless (or comment-p emph-p link-p keyw-p)
6581 (put-text-property (match-beginning 3) (match-end 0)
6582 'display
6583 (if (equal (char-after (match-beginning 2)) ?^)
6584 (nth (if table-p 3 1) org-script-display)
6585 (nth (if table-p 2 0) org-script-display)))
6586 (add-text-properties (match-beginning 2) (match-end 2)
6587 (list 'invisible t
6588 'org-dwidth t 'org-dwidth-n 1))
6589 (if (and (eq (char-after (match-beginning 3)) ?{)
6590 (eq (char-before (match-end 3)) ?}))
6591 (progn
6592 (add-text-properties
6593 (match-beginning 3) (1+ (match-beginning 3))
6594 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1))
6595 (add-text-properties
6596 (1- (match-end 3)) (match-end 3)
6597 (list 'invisible t 'org-dwidth t 'org-dwidth-n 1)))))
6598 t)))
6600 ;;;; Visibility cycling, including org-goto and indirect buffer
6602 ;;; Cycling
6604 (defvar-local org-cycle-global-status nil)
6605 (put 'org-cycle-global-status 'org-state t)
6606 (defvar-local org-cycle-subtree-status nil)
6607 (put 'org-cycle-subtree-status 'org-state t)
6609 (defvar org-inlinetask-min-level)
6611 (defun org-unlogged-message (&rest args)
6612 "Display a message, but avoid logging it in the *Messages* buffer."
6613 (let ((message-log-max nil))
6614 (apply 'message args)))
6616 ;;;###autoload
6617 (defun org-cycle (&optional arg)
6618 "TAB-action and visibility cycling for Org-mode.
6620 This is the command invoked in Org-mode by the TAB key. Its main purpose
6621 is outline visibility cycling, but it also invokes other actions
6622 in special contexts.
6624 - When this function is called with a prefix argument, rotate the entire
6625 buffer through 3 states (global cycling)
6626 1. OVERVIEW: Show only top-level headlines.
6627 2. CONTENTS: Show all headlines of all levels, but no body text.
6628 3. SHOW ALL: Show everything.
6629 With a double \\[universal-argument] prefix argument, \
6630 switch to the startup visibility,
6631 determined by the variable `org-startup-folded', and by any VISIBILITY
6632 properties in the buffer.
6633 With a triple \\[universal-argument] prefix argument, \
6634 show the entire buffer, including any drawers.
6636 - When inside a table, re-align the table and move to the next field.
6638 - When point is at the beginning of a headline, rotate the subtree started
6639 by this line through 3 different states (local cycling)
6640 1. FOLDED: Only the main headline is shown.
6641 2. CHILDREN: The main headline and the direct children are shown.
6642 From this state, you can move to one of the children
6643 and zoom in further.
6644 3. SUBTREE: Show the entire subtree, including body text.
6645 If there is no subtree, switch directly from CHILDREN to FOLDED.
6647 - When point is at the beginning of an empty headline and the variable
6648 `org-cycle-level-after-item/entry-creation' is set, cycle the level
6649 of the headline by demoting and promoting it to likely levels. This
6650 speeds up creation document structure by pressing TAB once or several
6651 times right after creating a new headline.
6653 - When there is a numeric prefix, go up to a heading with level ARG, do
6654 a `show-subtree' and return to the previous cursor position. If ARG
6655 is negative, go up that many levels.
6657 - When point is not at the beginning of a headline, execute the global
6658 binding for TAB, which is re-indenting the line. See the option
6659 `org-cycle-emulate-tab' for details.
6661 - Special case: if point is at the beginning of the buffer and there is
6662 no headline in line 1, this function will act as if called with prefix arg
6663 (\\[universal-argument] TAB, same as S-TAB) also when called without prefix arg.
6664 But only if also the variable `org-cycle-global-at-bob' is t."
6665 (interactive "P")
6666 (org-load-modules-maybe)
6667 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
6668 (and org-cycle-level-after-item/entry-creation
6669 (or (org-cycle-level)
6670 (org-cycle-item-indentation))))
6671 (let* ((limit-level
6672 (or org-cycle-max-level
6673 (and (boundp 'org-inlinetask-min-level)
6674 org-inlinetask-min-level
6675 (1- org-inlinetask-min-level))))
6676 (nstars (and limit-level
6677 (if org-odd-levels-only
6678 (and limit-level (1- (* limit-level 2)))
6679 limit-level)))
6680 (org-outline-regexp
6681 (if (not (derived-mode-p 'org-mode))
6682 outline-regexp
6683 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ "))))
6684 (bob-special (and org-cycle-global-at-bob (not arg) (bobp)
6685 (not (looking-at org-outline-regexp))))
6686 (org-cycle-hook
6687 (if bob-special
6688 (delq 'org-optimize-window-after-visibility-change
6689 (copy-sequence org-cycle-hook))
6690 org-cycle-hook))
6691 (pos (point)))
6693 (when (or bob-special (equal arg '(4)))
6694 ;; special case: use global cycling
6695 (setq arg t))
6697 (cond
6699 ((equal arg '(16))
6700 (setq last-command 'dummy)
6701 (org-set-startup-visibility)
6702 (org-unlogged-message "Startup visibility, plus VISIBILITY properties"))
6704 ((equal arg '(64))
6705 (outline-show-all)
6706 (org-unlogged-message "Entire buffer visible, including drawers"))
6708 ;; Try cdlatex TAB completion
6709 ((org-try-cdlatex-tab))
6711 ;; Table: enter it or move to the next field.
6712 ((org-at-table-p 'any)
6713 (if (org-at-table.el-p)
6714 (message "%s" (substitute-command-keys "\\<org-mode-map>\
6715 Use \\[org-edit-special] to edit table.el tables"))
6716 (if arg (org-table-edit-field t)
6717 (org-table-justify-field-maybe)
6718 (call-interactively 'org-table-next-field))))
6720 ((run-hook-with-args-until-success
6721 'org-tab-after-check-for-table-hook))
6723 ;; Global cycling: delegate to `org-cycle-internal-global'.
6724 ((eq arg t) (org-cycle-internal-global))
6726 ;; Drawers: delegate to `org-flag-drawer'.
6727 ((save-excursion
6728 (beginning-of-line 1)
6729 (looking-at org-drawer-regexp))
6730 (org-flag-drawer ; toggle block visibility
6731 (not (get-char-property (match-end 0) 'invisible))))
6733 ;; Show-subtree, ARG levels up from here.
6734 ((integerp arg)
6735 (save-excursion
6736 (org-back-to-heading)
6737 (outline-up-heading (if (< arg 0) (- arg)
6738 (- (funcall outline-level) arg)))
6739 (org-show-subtree)))
6741 ;; Inline task: delegate to `org-inlinetask-toggle-visibility'.
6742 ((and (featurep 'org-inlinetask)
6743 (org-inlinetask-at-task-p)
6744 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6745 (org-inlinetask-toggle-visibility))
6747 ;; At an item/headline: delegate to `org-cycle-internal-local'.
6748 ((and (or (and org-cycle-include-plain-lists (org-at-item-p))
6749 (save-excursion (move-beginning-of-line 1)
6750 (looking-at org-outline-regexp)))
6751 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
6752 (org-cycle-internal-local))
6754 ;; From there: TAB emulation and template completion.
6755 (buffer-read-only (org-back-to-heading))
6757 ((run-hook-with-args-until-success
6758 'org-tab-after-check-for-cycling-hook))
6760 ((org-try-structure-completion))
6762 ((run-hook-with-args-until-success
6763 'org-tab-before-tab-emulation-hook))
6765 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
6766 (or (not (bolp))
6767 (not (looking-at org-outline-regexp))))
6768 (call-interactively (global-key-binding "\t")))
6770 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
6771 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
6772 (or (and (eq org-cycle-emulate-tab 'white)
6773 (= (match-end 0) (point-at-eol)))
6774 (and (eq org-cycle-emulate-tab 'whitestart)
6775 (>= (match-end 0) pos))))
6777 (eq org-cycle-emulate-tab t))
6778 (call-interactively (global-key-binding "\t")))
6780 (t (save-excursion
6781 (org-back-to-heading)
6782 (org-cycle)))))))
6784 (defun org-cycle-internal-global ()
6785 "Do the global cycling action."
6786 ;; Hack to avoid display of messages for .org attachments in Gnus
6787 (let ((ga (string-match "\\*fontification" (buffer-name))))
6788 (cond
6789 ((and (eq last-command this-command)
6790 (eq org-cycle-global-status 'overview))
6791 ;; We just created the overview - now do table of contents
6792 ;; This can be slow in very large buffers, so indicate action
6793 (run-hook-with-args 'org-pre-cycle-hook 'contents)
6794 (unless ga (org-unlogged-message "CONTENTS..."))
6795 (org-content)
6796 (unless ga (org-unlogged-message "CONTENTS...done"))
6797 (setq org-cycle-global-status 'contents)
6798 (run-hook-with-args 'org-cycle-hook 'contents))
6800 ((and (eq last-command this-command)
6801 (eq org-cycle-global-status 'contents))
6802 ;; We just showed the table of contents - now show everything
6803 (run-hook-with-args 'org-pre-cycle-hook 'all)
6804 (outline-show-all)
6805 (unless ga (org-unlogged-message "SHOW ALL"))
6806 (setq org-cycle-global-status 'all)
6807 (run-hook-with-args 'org-cycle-hook 'all))
6810 ;; Default action: go to overview
6811 (run-hook-with-args 'org-pre-cycle-hook 'overview)
6812 (org-overview)
6813 (unless ga (org-unlogged-message "OVERVIEW"))
6814 (setq org-cycle-global-status 'overview)
6815 (run-hook-with-args 'org-cycle-hook 'overview)))))
6817 (defvar org-called-with-limited-levels nil
6818 "Non-nil when `org-with-limited-levels' is currently active.")
6820 (defun org-cycle-internal-local ()
6821 "Do the local cycling action."
6822 (let ((goal-column 0) eoh eol eos has-children children-skipped struct)
6823 ;; First, determine end of headline (EOH), end of subtree or item
6824 ;; (EOS), and if item or heading has children (HAS-CHILDREN).
6825 (save-excursion
6826 (if (org-at-item-p)
6827 (progn
6828 (beginning-of-line)
6829 (setq struct (org-list-struct))
6830 (setq eoh (point-at-eol))
6831 (setq eos (org-list-get-item-end-before-blank (point) struct))
6832 (setq has-children (org-list-has-child-p (point) struct)))
6833 (org-back-to-heading)
6834 (setq eoh (save-excursion (outline-end-of-heading) (point)))
6835 (setq eos (save-excursion (org-end-of-subtree t t)
6836 (when (bolp) (backward-char)) (point)))
6837 (setq has-children
6838 (or (save-excursion
6839 (let ((level (funcall outline-level)))
6840 (outline-next-heading)
6841 (and (org-at-heading-p t)
6842 (> (funcall outline-level) level))))
6843 (save-excursion
6844 (org-list-search-forward (org-item-beginning-re) eos t)))))
6845 ;; Determine end invisible part of buffer (EOL)
6846 (beginning-of-line 2)
6847 ;; XEmacs doesn't have `next-single-char-property-change'
6848 (if (featurep 'xemacs)
6849 (while (and (not (eobp)) ;; this is like `next-line'
6850 (get-char-property (1- (point)) 'invisible))
6851 (beginning-of-line 2))
6852 (while (and (not (eobp)) ;; this is like `next-line'
6853 (get-char-property (1- (point)) 'invisible))
6854 (goto-char (next-single-char-property-change (point) 'invisible))
6855 (and (eolp) (beginning-of-line 2))))
6856 (setq eol (point)))
6857 ;; Find out what to do next and set `this-command'
6858 (cond
6859 ((= eos eoh)
6860 ;; Nothing is hidden behind this heading
6861 (unless (org-before-first-heading-p)
6862 (run-hook-with-args 'org-pre-cycle-hook 'empty))
6863 (org-unlogged-message "EMPTY ENTRY")
6864 (setq org-cycle-subtree-status nil)
6865 (save-excursion
6866 (goto-char eos)
6867 (outline-next-heading)
6868 (when (outline-invisible-p) (org-flag-heading nil))))
6869 ((and (or (>= eol eos)
6870 (not (string-match "\\S-" (buffer-substring eol eos))))
6871 (or has-children
6872 (not (setq children-skipped
6873 org-cycle-skip-children-state-if-no-children))))
6874 ;; Entire subtree is hidden in one line: children view
6875 (unless (org-before-first-heading-p)
6876 (run-hook-with-args 'org-pre-cycle-hook 'children))
6877 (if (org-at-item-p)
6878 (org-list-set-item-visibility (point-at-bol) struct 'children)
6879 (org-show-entry)
6880 (org-with-limited-levels (org-show-children))
6881 ;; FIXME: This slows down the func way too much.
6882 ;; How keep drawers hidden in subtree anyway?
6883 ;; (when (memq 'org-cycle-hide-drawers org-cycle-hook)
6884 ;; (org-cycle-hide-drawers 'subtree))
6886 ;; Fold every list in subtree to top-level items.
6887 (when (eq org-cycle-include-plain-lists 'integrate)
6888 (save-excursion
6889 (org-back-to-heading)
6890 (while (org-list-search-forward (org-item-beginning-re) eos t)
6891 (beginning-of-line 1)
6892 (let* ((struct (org-list-struct))
6893 (prevs (org-list-prevs-alist struct))
6894 (end (org-list-get-bottom-point struct)))
6895 (dolist (e (org-list-get-all-items (point) struct prevs))
6896 (org-list-set-item-visibility e struct 'folded))
6897 (goto-char (if (< end eos) end eos)))))))
6898 (org-unlogged-message "CHILDREN")
6899 (save-excursion
6900 (goto-char eos)
6901 (outline-next-heading)
6902 (when (outline-invisible-p) (org-flag-heading nil)))
6903 (setq org-cycle-subtree-status 'children)
6904 (unless (org-before-first-heading-p)
6905 (run-hook-with-args 'org-cycle-hook 'children)))
6906 ((or children-skipped
6907 (and (eq last-command this-command)
6908 (eq org-cycle-subtree-status 'children)))
6909 ;; We just showed the children, or no children are there,
6910 ;; now show everything.
6911 (unless (org-before-first-heading-p)
6912 (run-hook-with-args 'org-pre-cycle-hook 'subtree))
6913 (outline-flag-region eoh eos nil)
6914 (org-unlogged-message
6915 (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
6916 (setq org-cycle-subtree-status 'subtree)
6917 (unless (org-before-first-heading-p)
6918 (run-hook-with-args 'org-cycle-hook 'subtree)))
6920 ;; Default action: hide the subtree.
6921 (run-hook-with-args 'org-pre-cycle-hook 'folded)
6922 (outline-flag-region eoh eos t)
6923 (org-unlogged-message "FOLDED")
6924 (setq org-cycle-subtree-status 'folded)
6925 (unless (org-before-first-heading-p)
6926 (run-hook-with-args 'org-cycle-hook 'folded))))))
6928 ;;;###autoload
6929 (defun org-global-cycle (&optional arg)
6930 "Cycle the global visibility. For details see `org-cycle'.
6931 With \\[universal-argument] prefix arg, switch to startup visibility.
6932 With a numeric prefix, show all headlines up to that level."
6933 (interactive "P")
6934 (let ((org-cycle-include-plain-lists
6935 (if (derived-mode-p 'org-mode) org-cycle-include-plain-lists nil)))
6936 (cond
6937 ((integerp arg)
6938 (outline-show-all)
6939 (outline-hide-sublevels arg)
6940 (setq org-cycle-global-status 'contents))
6941 ((equal arg '(4))
6942 (org-set-startup-visibility)
6943 (org-unlogged-message "Startup visibility, plus VISIBILITY properties."))
6945 (org-cycle '(4))))))
6947 (defun org-set-startup-visibility ()
6948 "Set the visibility required by startup options and properties."
6949 (cond
6950 ((eq org-startup-folded t)
6951 (org-overview))
6952 ((eq org-startup-folded 'content)
6953 (org-content))
6954 ((or (eq org-startup-folded 'showeverything)
6955 (eq org-startup-folded nil))
6956 (outline-show-all)))
6957 (unless (eq org-startup-folded 'showeverything)
6958 (when org-hide-block-startup (org-hide-block-all))
6959 (org-set-visibility-according-to-property 'no-cleanup)
6960 (org-cycle-hide-archived-subtrees 'all)
6961 (org-cycle-hide-drawers 'all)
6962 (org-cycle-show-empty-lines t)))
6964 (defun org-set-visibility-according-to-property (&optional no-cleanup)
6965 "Switch subtree visibilities according to :VISIBILITY: property."
6966 (interactive)
6967 (org-with-wide-buffer
6968 (goto-char (point-min))
6969 (while (re-search-forward "^[ \t]*:VISIBILITY:" nil t)
6970 (if (not (org-at-property-p)) (outline-next-heading)
6971 (let ((state (match-string 3)))
6972 (save-excursion
6973 (org-back-to-heading t)
6974 (outline-hide-subtree)
6975 (org-reveal)
6976 (cond
6977 ((equal state "folded")
6978 (outline-hide-subtree))
6979 ((equal state "children")
6980 (org-show-hidden-entry)
6981 (org-show-children))
6982 ((equal state "content")
6983 (save-excursion
6984 (save-restriction
6985 (org-narrow-to-subtree)
6986 (org-content))))
6987 ((member state '("all" "showall"))
6988 (outline-show-subtree)))))))
6989 (unless no-cleanup
6990 (org-cycle-hide-archived-subtrees 'all)
6991 (org-cycle-hide-drawers 'all)
6992 (org-cycle-show-empty-lines 'all))))
6994 ;; This function uses outline-regexp instead of the more fundamental
6995 ;; org-outline-regexp so that org-cycle-global works outside of Org
6996 ;; buffers, where outline-regexp is needed.
6997 (defun org-overview ()
6998 "Switch to overview mode, showing only top-level headlines.
6999 This shows all headlines with a level equal or greater than the level
7000 of the first headline in the buffer. This is important, because if the
7001 first headline is not level one, then (hide-sublevels 1) gives confusing
7002 results."
7003 (interactive)
7004 (save-excursion
7005 (let ((level
7006 (save-excursion
7007 (goto-char (point-min))
7008 (when (re-search-forward (concat "^" outline-regexp) nil t)
7009 (goto-char (match-beginning 0))
7010 (funcall outline-level)))))
7011 (and level (outline-hide-sublevels level)))))
7013 (defun org-content (&optional arg)
7014 "Show all headlines in the buffer, like a table of contents.
7015 With numerical argument N, show content up to level N."
7016 (interactive "P")
7017 (org-overview)
7018 (save-excursion
7019 ;; Visit all headings and show their offspring
7020 (and (integerp arg) (org-overview))
7021 (goto-char (point-max))
7022 (catch 'exit
7023 (while (and (progn (condition-case nil
7024 (outline-previous-visible-heading 1)
7025 (error (goto-char (point-min))))
7027 (looking-at org-outline-regexp))
7028 (if (integerp arg)
7029 (org-show-children (1- arg))
7030 (outline-show-branches))
7031 (when (bobp) (throw 'exit nil))))))
7033 (defun org-optimize-window-after-visibility-change (state)
7034 "Adjust the window after a change in outline visibility.
7035 This function is the default value of the hook `org-cycle-hook'."
7036 (when (get-buffer-window (current-buffer))
7037 (cond
7038 ((eq state 'content) nil)
7039 ((eq state 'all) nil)
7040 ((eq state 'folded) nil)
7041 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
7042 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
7044 (defun org-remove-empty-overlays-at (pos)
7045 "Remove outline overlays that do not contain non-white stuff."
7046 (dolist (o (overlays-at pos))
7047 (and (eq 'outline (overlay-get o 'invisible))
7048 (not (string-match "\\S-" (buffer-substring (overlay-start o)
7049 (overlay-end o))))
7050 (delete-overlay o))))
7052 (defun org-clean-visibility-after-subtree-move ()
7053 "Fix visibility issues after moving a subtree."
7054 ;; First, find a reasonable region to look at:
7055 ;; Start two siblings above, end three below
7056 (let* ((beg (save-excursion
7057 (and (org-get-last-sibling)
7058 (org-get-last-sibling))
7059 (point)))
7060 (end (save-excursion
7061 (and (org-get-next-sibling)
7062 (org-get-next-sibling)
7063 (org-get-next-sibling))
7064 (if (org-at-heading-p)
7065 (point-at-eol)
7066 (point))))
7067 (level (looking-at "\\*+"))
7068 (re (when level (concat "^" (regexp-quote (match-string 0)) " "))))
7069 (save-excursion
7070 (save-restriction
7071 (narrow-to-region beg end)
7072 (when re
7073 ;; Properly fold already folded siblings
7074 (goto-char (point-min))
7075 (while (re-search-forward re nil t)
7076 (when (and (not (outline-invisible-p))
7077 (save-excursion
7078 (goto-char (point-at-eol)) (outline-invisible-p)))
7079 (outline-hide-entry))))
7080 (org-cycle-show-empty-lines 'overview)
7081 (org-cycle-hide-drawers 'overview)))))
7083 (defun org-cycle-show-empty-lines (state)
7084 "Show empty lines above all visible headlines.
7085 The region to be covered depends on STATE when called through
7086 `org-cycle-hook'. Lisp program can use t for STATE to get the
7087 entire buffer covered. Note that an empty line is only shown if there
7088 are at least `org-cycle-separator-lines' empty lines before the headline."
7089 (when (/= org-cycle-separator-lines 0)
7090 (save-excursion
7091 (let* ((n (abs org-cycle-separator-lines))
7092 (re (cond
7093 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
7094 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
7095 (t (let ((ns (number-to-string (- n 2))))
7096 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
7097 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
7098 beg end)
7099 (cond
7100 ((memq state '(overview contents t))
7101 (setq beg (point-min) end (point-max)))
7102 ((memq state '(children folded))
7103 (setq beg (point)
7104 end (progn (org-end-of-subtree t t)
7105 (line-beginning-position 2)))))
7106 (when beg
7107 (goto-char beg)
7108 (while (re-search-forward re end t)
7109 (unless (get-char-property (match-end 1) 'invisible)
7110 (let ((e (match-end 1))
7111 (b (if (>= org-cycle-separator-lines 0)
7112 (match-beginning 1)
7113 (save-excursion
7114 (goto-char (match-beginning 0))
7115 (skip-chars-backward " \t\n")
7116 (line-end-position)))))
7117 (outline-flag-region b e nil))))))))
7118 ;; Never hide empty lines at the end of the file.
7119 (save-excursion
7120 (goto-char (point-max))
7121 (outline-previous-heading)
7122 (outline-end-of-heading)
7123 (when (and (looking-at "[ \t\n]+")
7124 (= (match-end 0) (point-max)))
7125 (outline-flag-region (point) (match-end 0) nil))))
7127 (defun org-show-empty-lines-in-parent ()
7128 "Move to the parent and re-show empty lines before visible headlines."
7129 (save-excursion
7130 (let ((context (if (org-up-heading-safe) 'children 'overview)))
7131 (org-cycle-show-empty-lines context))))
7133 (defun org-files-list ()
7134 "Return `org-agenda-files' list, plus all open org-mode files.
7135 This is useful for operations that need to scan all of a user's
7136 open and agenda-wise Org files."
7137 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
7138 (dolist (buf (buffer-list))
7139 (with-current-buffer buf
7140 (when (and (derived-mode-p 'org-mode) (buffer-file-name))
7141 (cl-pushnew (expand-file-name (buffer-file-name)) files))))
7142 files))
7144 (defsubst org-entry-beginning-position ()
7145 "Return the beginning position of the current entry."
7146 (save-excursion (org-back-to-heading t) (point)))
7148 (defsubst org-entry-end-position ()
7149 "Return the end position of the current entry."
7150 (save-excursion (outline-next-heading) (point)))
7152 (defun org-cycle-hide-drawers (state &optional exceptions)
7153 "Re-hide all drawers after a visibility state change.
7154 When non-nil, optional argument EXCEPTIONS is a list of strings
7155 specifying which drawers should not be hidden."
7156 (when (and (derived-mode-p 'org-mode)
7157 (not (memq state '(overview folded contents))))
7158 (save-excursion
7159 (let* ((globalp (memq state '(contents all)))
7160 (beg (if globalp (point-min) (point)))
7161 (end (if globalp (point-max)
7162 (if (eq state 'children)
7163 (save-excursion (outline-next-heading) (point))
7164 (org-end-of-subtree t)))))
7165 (goto-char beg)
7166 (while (re-search-forward org-drawer-regexp (max end (point)) t)
7167 (unless (member-ignore-case (match-string 1) exceptions)
7168 (let ((drawer (org-element-at-point)))
7169 (when (memq (org-element-type drawer) '(drawer property-drawer))
7170 (org-flag-drawer t drawer)
7171 ;; Make sure to skip drawer entirely or we might flag
7172 ;; it another time when matching its ending line with
7173 ;; `org-drawer-regexp'.
7174 (goto-char (org-element-property :end drawer))))))))))
7176 (defun org-flag-drawer (flag &optional element)
7177 "When FLAG is non-nil, hide the drawer we are at.
7178 Otherwise make it visible. When optional argument ELEMENT is
7179 a parsed drawer, as returned by `org-element-at-point', hide or
7180 show that drawer instead."
7181 (let ((drawer (or element
7182 (and (save-excursion
7183 (beginning-of-line)
7184 (org-looking-at-p org-drawer-regexp))
7185 (org-element-at-point)))))
7186 (when (memq (org-element-type drawer) '(drawer property-drawer))
7187 (let ((post (org-element-property :post-affiliated drawer)))
7188 (save-excursion
7189 (outline-flag-region
7190 (progn (goto-char post) (line-end-position))
7191 (progn (goto-char (org-element-property :end drawer))
7192 (skip-chars-backward " \r\t\n")
7193 (line-end-position))
7194 flag))
7195 ;; When the drawer is hidden away, make sure point lies in
7196 ;; a visible part of the buffer.
7197 (when (and flag (> (line-beginning-position) post))
7198 (goto-char post))))))
7200 (defun org-subtree-end-visible-p ()
7201 "Is the end of the current subtree visible?"
7202 (pos-visible-in-window-p
7203 (save-excursion (org-end-of-subtree t) (point))))
7205 (defun org-first-headline-recenter ()
7206 "Move cursor to the first headline and recenter the headline."
7207 (goto-char (point-min))
7208 (when (re-search-forward (concat "^\\(" org-outline-regexp "\\)") nil t)
7209 (set-window-start (selected-window) (point-at-bol))))
7211 ;;; Saving and restoring visibility
7213 (defun org-outline-overlay-data (&optional use-markers)
7214 "Return a list of the locations of all outline overlays.
7215 These are overlays with the `invisible' property value `outline'.
7216 The return value is a list of cons cells, with start and stop
7217 positions for each overlay.
7218 If USE-MARKERS is set, return the positions as markers."
7219 (let (beg end)
7220 (save-excursion
7221 (save-restriction
7222 (widen)
7223 (delq nil
7224 (mapcar (lambda (o)
7225 (when (eq (overlay-get o 'invisible) 'outline)
7226 (setq beg (overlay-start o)
7227 end (overlay-end o))
7228 (and beg end (> end beg)
7229 (if use-markers
7230 (cons (copy-marker beg)
7231 (copy-marker end t))
7232 (cons beg end)))))
7233 (overlays-in (point-min) (point-max))))))))
7235 (defun org-set-outline-overlay-data (data)
7236 "Create visibility overlays for all positions in DATA.
7237 DATA should have been made by `org-outline-overlay-data'."
7238 (org-with-wide-buffer
7239 (outline-show-all)
7240 (dolist (c data) (outline-flag-region (car c) (cdr c) t))))
7242 ;;; Folding of blocks
7244 (defvar-local org-hide-block-overlays nil
7245 "Overlays hiding blocks.")
7247 (defun org-block-map (function &optional start end)
7248 "Call FUNCTION at the head of all source blocks in the current buffer.
7249 Optional arguments START and END can be used to limit the range."
7250 (let ((start (or start (point-min)))
7251 (end (or end (point-max))))
7252 (save-excursion
7253 (goto-char start)
7254 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
7255 (save-excursion
7256 (save-match-data
7257 (goto-char (match-beginning 0))
7258 (funcall function)))))))
7260 (defun org-hide-block-toggle-all ()
7261 "Toggle the visibility of all blocks in the current buffer."
7262 (org-block-map 'org-hide-block-toggle))
7264 (defun org-hide-block-all ()
7265 "Fold all blocks in the current buffer."
7266 (interactive)
7267 (org-show-block-all)
7268 (org-block-map 'org-hide-block-toggle-maybe))
7270 (defun org-show-block-all ()
7271 "Unfold all blocks in the current buffer."
7272 (interactive)
7273 (mapc #'delete-overlay org-hide-block-overlays)
7274 (setq org-hide-block-overlays nil))
7276 (defun org-hide-block-toggle-maybe ()
7277 "Toggle visibility of block at point.
7278 Unlike to `org-hide-block-toggle', this function does not throw
7279 an error. Return a non-nil value when toggling is successful."
7280 (interactive)
7281 (ignore-errors (org-hide-block-toggle)))
7283 (defun org-hide-block-toggle (&optional force)
7284 "Toggle the visibility of the current block.
7285 When optional argument FORCE is `off', make block visible. If it
7286 is non-nil, hide it unconditionally. Throw an error when not at
7287 a block. Return a non-nil value when toggling is successful."
7288 (interactive)
7289 (let ((element (org-element-at-point)))
7290 (unless (memq (org-element-type element)
7291 '(center-block comment-block dynamic-block example-block
7292 export-block quote-block special-block
7293 src-block verse-block))
7294 (user-error "Not at a block"))
7295 (let* ((start (save-excursion
7296 (goto-char (org-element-property :post-affiliated element))
7297 (line-end-position)))
7298 (end (save-excursion
7299 (goto-char (org-element-property :end element))
7300 (skip-chars-backward " \r\t\n")
7301 (line-end-position)))
7302 (overlays (overlays-at start)))
7303 (cond
7304 ;; Do nothing when not before or at the block opening line or
7305 ;; at the block closing line.
7306 ((let ((eol (line-end-position))) (and (> eol start) (/= eol end))) nil)
7307 ((and (not (eq force 'off))
7308 (not (memq t (mapcar
7309 (lambda (o)
7310 (eq (overlay-get o 'invisible) 'org-hide-block))
7311 overlays))))
7312 (let ((ov (make-overlay start end)))
7313 (overlay-put ov 'invisible 'org-hide-block)
7314 ;; Make the block accessible to `isearch'.
7315 (overlay-put
7316 ov 'isearch-open-invisible
7317 (lambda (ov)
7318 (when (memq ov org-hide-block-overlays)
7319 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7320 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7321 (delete-overlay ov))))
7322 (push ov org-hide-block-overlays)
7323 ;; When the block is hidden away, make sure point is left in
7324 ;; a visible part of the buffer.
7325 (when (> (line-beginning-position) start)
7326 (goto-char start)
7327 (beginning-of-line))
7328 ;; Signal successful toggling.
7330 ((or (not force) (eq force 'off))
7331 (dolist (ov overlays t)
7332 (when (memq ov org-hide-block-overlays)
7333 (setq org-hide-block-overlays (delq ov org-hide-block-overlays)))
7334 (when (eq (overlay-get ov 'invisible) 'org-hide-block)
7335 (delete-overlay ov))))))))
7337 ;; org-tab-after-check-for-cycling-hook
7338 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
7339 ;; Remove overlays when changing major mode
7340 (add-hook 'org-mode-hook
7341 (lambda () (org-add-hook 'change-major-mode-hook
7342 'org-show-block-all 'append 'local)))
7344 ;;; Org-goto
7346 (defvar org-goto-window-configuration nil)
7347 (defvar org-goto-marker nil)
7348 (defvar org-goto-map)
7349 (defun org-goto-map ()
7350 "Set the keymap `org-goto'."
7351 (setq org-goto-map
7352 (let ((map (make-sparse-keymap)))
7353 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command
7354 mouse-drag-region universal-argument org-occur)))
7355 (dolist (cmd cmds)
7356 (substitute-key-definition cmd cmd map global-map)))
7357 (suppress-keymap map)
7358 (org-defkey map "\C-m" 'org-goto-ret)
7359 (org-defkey map [(return)] 'org-goto-ret)
7360 (org-defkey map [(left)] 'org-goto-left)
7361 (org-defkey map [(right)] 'org-goto-right)
7362 (org-defkey map [(control ?g)] 'org-goto-quit)
7363 (org-defkey map "\C-i" 'org-cycle)
7364 (org-defkey map [(tab)] 'org-cycle)
7365 (org-defkey map [(down)] 'outline-next-visible-heading)
7366 (org-defkey map [(up)] 'outline-previous-visible-heading)
7367 (if org-goto-auto-isearch
7368 (if (fboundp 'define-key-after)
7369 (define-key-after map [t] 'org-goto-local-auto-isearch)
7370 nil)
7371 (org-defkey map "q" 'org-goto-quit)
7372 (org-defkey map "n" 'outline-next-visible-heading)
7373 (org-defkey map "p" 'outline-previous-visible-heading)
7374 (org-defkey map "f" 'outline-forward-same-level)
7375 (org-defkey map "b" 'outline-backward-same-level)
7376 (org-defkey map "u" 'outline-up-heading))
7377 (org-defkey map "/" 'org-occur)
7378 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
7379 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
7380 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
7381 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
7382 (org-defkey map "\C-c\C-u" 'outline-up-heading)
7383 map)))
7385 (defconst org-goto-help
7386 "Browse buffer copy, to find location or copy text.%s
7387 RET=jump to location C-g=quit and return to previous location
7388 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
7390 (defvar org-goto-start-pos) ; dynamically scoped parameter
7392 (defun org-goto (&optional alternative-interface)
7393 "Look up a different location in the current file, keeping current visibility.
7395 When you want look-up or go to a different location in a
7396 document, the fastest way is often to fold the entire buffer and
7397 then dive into the tree. This method has the disadvantage, that
7398 the previous location will be folded, which may not be what you
7399 want.
7401 This command works around this by showing a copy of the current
7402 buffer in an indirect buffer, in overview mode. You can dive
7403 into the tree in that copy, use org-occur and incremental search
7404 to find a location. When pressing RET or `Q', the command
7405 returns to the original buffer in which the visibility is still
7406 unchanged. After RET it will also jump to the location selected
7407 in the indirect buffer and expose the headline hierarchy above.
7409 With a prefix argument, use the alternative interface: e.g., if
7410 `org-goto-interface' is `outline' use `outline-path-completion'."
7411 (interactive "P")
7412 (org-goto-map)
7413 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
7414 (org-refile-use-outline-path t)
7415 (org-refile-target-verify-function nil)
7416 (interface
7417 (if (not alternative-interface)
7418 org-goto-interface
7419 (if (eq org-goto-interface 'outline)
7420 'outline-path-completion
7421 'outline)))
7422 (org-goto-start-pos (point))
7423 (selected-point
7424 (if (eq interface 'outline)
7425 (car (org-get-location (current-buffer) org-goto-help))
7426 (let ((pa (org-refile-get-location "Goto")))
7427 (org-refile-check-position pa)
7428 (nth 3 pa)))))
7429 (if selected-point
7430 (progn
7431 (org-mark-ring-push org-goto-start-pos)
7432 (goto-char selected-point)
7433 (when (or (outline-invisible-p) (org-invisible-p2))
7434 (org-show-context 'org-goto)))
7435 (message "Quit"))))
7437 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
7438 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
7439 (defvar org-goto-local-auto-isearch-map) ; defined below
7441 (defun org-get-location (_buf help)
7442 "Let the user select a location in current buffer.
7443 This function uses a recursive edit. It returns the selected position
7444 or nil."
7445 (org-no-popups
7446 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
7447 (isearch-hide-immediately nil)
7448 (isearch-search-fun-function
7449 (lambda () 'org-goto-local-search-headings))
7450 (org-goto-selected-point org-goto-exit-command))
7451 (save-excursion
7452 (save-window-excursion
7453 (delete-other-windows)
7454 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
7455 (org-pop-to-buffer-same-window
7456 (condition-case nil
7457 (make-indirect-buffer (current-buffer) "*org-goto*")
7458 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
7459 (with-output-to-temp-buffer "*Org Help*"
7460 (princ (format help (if org-goto-auto-isearch
7461 " Just type for auto-isearch."
7462 " n/p/f/b/u to navigate, q to quit."))))
7463 (org-fit-window-to-buffer (get-buffer-window "*Org Help*"))
7464 (setq buffer-read-only nil)
7465 (let ((org-startup-truncated t)
7466 (org-startup-folded nil)
7467 (org-startup-align-all-tables nil))
7468 (org-mode)
7469 (org-overview))
7470 (setq buffer-read-only t)
7471 (if (and (boundp 'org-goto-start-pos)
7472 (integer-or-marker-p org-goto-start-pos))
7473 (progn (goto-char org-goto-start-pos)
7474 (when (outline-invisible-p)
7475 (org-show-set-visibility 'lineage)))
7476 (goto-char (point-min)))
7477 (let (org-special-ctrl-a/e) (org-beginning-of-line))
7478 (message "Select location and press RET")
7479 (use-local-map org-goto-map)
7480 (recursive-edit)))
7481 (kill-buffer "*org-goto*")
7482 (cons org-goto-selected-point org-goto-exit-command))))
7484 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
7485 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
7486 ;; `isearch-other-control-char' was removed in Emacs 24.4.
7487 (if (fboundp 'isearch-other-control-char)
7488 (progn
7489 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
7490 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char))
7491 (define-key org-goto-local-auto-isearch-map "\C-i" nil)
7492 (define-key org-goto-local-auto-isearch-map "\C-m" nil)
7493 (define-key org-goto-local-auto-isearch-map [return] nil))
7495 (defun org-goto-local-search-headings (string bound noerror)
7496 "Search and make sure that any matches are in headlines."
7497 (catch 'return
7498 (while (if isearch-forward
7499 (search-forward string bound noerror)
7500 (search-backward string bound noerror))
7501 (when (save-match-data
7502 (and (save-excursion
7503 (beginning-of-line)
7504 (looking-at org-complex-heading-regexp))
7505 (or (not (match-beginning 5))
7506 (< (point) (match-beginning 5)))))
7507 (throw 'return (point))))))
7509 (defun org-goto-local-auto-isearch ()
7510 "Start isearch."
7511 (interactive)
7512 (goto-char (point-min))
7513 (let ((keys (this-command-keys)))
7514 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
7515 (isearch-mode t)
7516 (isearch-process-search-char (string-to-char keys)))))
7518 (defun org-goto-ret (&optional _arg)
7519 "Finish `org-goto' by going to the new location."
7520 (interactive "P")
7521 (setq org-goto-selected-point (point))
7522 (setq org-goto-exit-command 'return)
7523 (throw 'exit nil))
7525 (defun org-goto-left ()
7526 "Finish `org-goto' by going to the new location."
7527 (interactive)
7528 (if (org-at-heading-p)
7529 (progn
7530 (beginning-of-line 1)
7531 (setq org-goto-selected-point (point)
7532 org-goto-exit-command 'left)
7533 (throw 'exit nil))
7534 (user-error "Not on a heading")))
7536 (defun org-goto-right ()
7537 "Finish `org-goto' by going to the new location."
7538 (interactive)
7539 (if (org-at-heading-p)
7540 (progn
7541 (setq org-goto-selected-point (point)
7542 org-goto-exit-command 'right)
7543 (throw 'exit nil))
7544 (user-error "Not on a heading")))
7546 (defun org-goto-quit ()
7547 "Finish `org-goto' without cursor motion."
7548 (interactive)
7549 (setq org-goto-selected-point nil)
7550 (setq org-goto-exit-command 'quit)
7551 (throw 'exit nil))
7553 ;;; Indirect buffer display of subtrees
7555 (defvar org-indirect-dedicated-frame nil
7556 "This is the frame being used for indirect tree display.")
7557 (defvar org-last-indirect-buffer nil)
7559 (defun org-tree-to-indirect-buffer (&optional arg)
7560 "Create indirect buffer and narrow it to current subtree.
7561 With a numerical prefix ARG, go up to this level and then take that tree.
7562 If ARG is negative, go up that many levels.
7564 If `org-indirect-buffer-display' is not `new-frame', the command removes the
7565 indirect buffer previously made with this command, to avoid proliferation of
7566 indirect buffers. However, when you call the command with a \
7567 \\[universal-argument] prefix, or
7568 when `org-indirect-buffer-display' is `new-frame', the last buffer
7569 is kept so that you can work with several indirect buffers at the same time.
7570 If `org-indirect-buffer-display' is `dedicated-frame', the \
7571 \\[universal-argument] prefix also
7572 requests that a new frame be made for the new buffer, so that the dedicated
7573 frame is not changed."
7574 (interactive "P")
7575 (let ((cbuf (current-buffer))
7576 (cwin (selected-window))
7577 (pos (point))
7578 beg end level heading ibuf)
7579 (save-excursion
7580 (org-back-to-heading t)
7581 (when (numberp arg)
7582 (setq level (org-outline-level))
7583 (when (< arg 0) (setq arg (+ level arg)))
7584 (while (> (setq level (org-outline-level)) arg)
7585 (org-up-heading-safe)))
7586 (setq beg (point)
7587 heading (org-get-heading 'no-tags))
7588 (org-end-of-subtree t t)
7589 (when (org-at-heading-p) (backward-char 1))
7590 (setq end (point)))
7591 (when (and (buffer-live-p org-last-indirect-buffer)
7592 (not (eq org-indirect-buffer-display 'new-frame))
7593 (not arg))
7594 (kill-buffer org-last-indirect-buffer))
7595 (setq ibuf (org-get-indirect-buffer cbuf heading)
7596 org-last-indirect-buffer ibuf)
7597 (cond
7598 ((or (eq org-indirect-buffer-display 'new-frame)
7599 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
7600 (select-frame (make-frame))
7601 (delete-other-windows)
7602 (org-pop-to-buffer-same-window ibuf)
7603 (org-set-frame-title heading))
7604 ((eq org-indirect-buffer-display 'dedicated-frame)
7605 (raise-frame
7606 (select-frame (or (and org-indirect-dedicated-frame
7607 (frame-live-p org-indirect-dedicated-frame)
7608 org-indirect-dedicated-frame)
7609 (setq org-indirect-dedicated-frame (make-frame)))))
7610 (delete-other-windows)
7611 (org-pop-to-buffer-same-window ibuf)
7612 (org-set-frame-title (concat "Indirect: " heading)))
7613 ((eq org-indirect-buffer-display 'current-window)
7614 (org-pop-to-buffer-same-window ibuf))
7615 ((eq org-indirect-buffer-display 'other-window)
7616 (pop-to-buffer ibuf))
7617 (t (error "Invalid value")))
7618 (when (featurep 'xemacs)
7619 (save-excursion (org-mode) (turn-on-font-lock)))
7620 (narrow-to-region beg end)
7621 (outline-show-all)
7622 (goto-char pos)
7623 (run-hook-with-args 'org-cycle-hook 'all)
7624 (and (window-live-p cwin) (select-window cwin))))
7626 (defun org-get-indirect-buffer (&optional buffer heading)
7627 (setq buffer (or buffer (current-buffer)))
7628 (let ((n 1) (base (buffer-name buffer)) bname)
7629 (while (buffer-live-p
7630 (get-buffer
7631 (setq bname
7632 (concat base "-"
7633 (if heading (concat heading "-" (number-to-string n))
7634 (number-to-string n))))))
7635 (setq n (1+ n)))
7636 (condition-case nil
7637 (make-indirect-buffer buffer bname 'clone)
7638 (error (make-indirect-buffer buffer bname)))))
7640 (defun org-set-frame-title (title)
7641 "Set the title of the current frame to the string TITLE."
7642 ;; FIXME: how to name a single frame in XEmacs???
7643 (unless (featurep 'xemacs)
7644 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
7646 ;;;; Structure editing
7648 ;;; Inserting headlines
7650 (defun org--line-empty-p (n)
7651 "Is the Nth next line empty?
7653 Counts the current line as N = 1 and the previous line as N = 0;
7654 see `beginning-of-line'."
7655 (save-excursion
7656 (and (not (bobp))
7657 (or (beginning-of-line n) t)
7658 (save-match-data
7659 (looking-at "[ \t]*$")))))
7661 (defun org-previous-line-empty-p ()
7662 "Is the previous line a blank line?
7663 When NEXT is non-nil, check the next line instead."
7664 (org--line-empty-p 0))
7666 (defun org-next-line-empty-p ()
7667 "Is the previous line a blank line?
7668 When NEXT is non-nil, check the next line instead."
7669 (org--line-empty-p 2))
7671 (defun org-insert-heading (&optional arg invisible-ok top)
7672 "Insert a new heading or an item with the same depth at point.
7674 If point is at the beginning of a heading or a list item, insert
7675 a new heading or a new item above the current one. If point is
7676 at the beginning of a normal line, turn the line into a heading.
7678 If point is in the middle of a headline or a list item, split the
7679 headline or the item and create a new headline/item with the text
7680 in the current line after point \(see `org-M-RET-may-split-line'
7681 on how to modify this behavior).
7683 With one universal prefix argument, set the user option
7684 `org-insert-heading-respect-content' to t for the duration of
7685 the command. This modifies the behavior described above in this
7686 ways: on list items and at the beginning of normal lines, force
7687 the insertion of a heading after the current subtree.
7689 With two universal prefix arguments, insert the heading at the
7690 end of the grandparent subtree. For example, if point is within
7691 a 2nd-level heading, then it will insert a 2nd-level heading at
7692 the end of the 1st-level parent heading.
7694 If point is at the beginning of a headline, insert a sibling
7695 before the current headline. If point is not at the beginning,
7696 split the line and create a new headline with the text in the
7697 current line after point \(see `org-M-RET-may-split-line' on how
7698 to modify this behavior).
7700 If point is at the beginning of a normal line, turn this line
7701 into a heading.
7703 When INVISIBLE-OK is set, stop at invisible headlines when going
7704 back. This is important for non-interactive uses of the
7705 command.
7707 When optional argument TOP is non-nil, insert a level 1 heading,
7708 unconditionally."
7709 (interactive "P")
7710 (when (org-called-interactively-p 'any) (org-reveal))
7711 (let ((itemp (and (not top) (org-in-item-p)))
7712 (may-split (org-get-alist-option org-M-RET-may-split-line 'headline))
7713 (respect-content (or org-insert-heading-respect-content
7714 (equal arg '(4))))
7715 (initial-content ""))
7717 (cond
7719 ((or (= (buffer-size) 0)
7720 (and (not (save-excursion
7721 (and (ignore-errors (org-back-to-heading invisible-ok))
7722 (org-at-heading-p))))
7723 (or arg (not itemp))))
7724 ;; At beginning of buffer or so high up that only a heading
7725 ;; makes sense.
7726 (cond ((and (bolp) (not respect-content)) (insert "* "))
7727 ((not respect-content)
7728 (unless may-split (end-of-line))
7729 (insert "\n* "))
7730 ((re-search-forward org-outline-regexp-bol nil t)
7731 (beginning-of-line)
7732 (insert "* \n")
7733 (backward-char))
7734 (t (goto-char (point-max))
7735 (insert "\n* ")))
7736 (run-hooks 'org-insert-heading-hook))
7738 ((and itemp (not (member arg '((4) (16)))) (org-insert-item)))
7741 ;; Maybe move at the end of the subtree
7742 (when (equal arg '(16))
7743 (org-up-heading-safe)
7744 (org-end-of-subtree t))
7745 ;; Insert a heading
7746 (save-restriction
7747 (widen)
7748 (let* ((level nil)
7749 (on-heading (org-at-heading-p))
7750 (empty-line-p (if on-heading
7751 (org-previous-line-empty-p)
7752 ;; We will decide later
7753 nil))
7754 ;; Get a level string to fall back on.
7755 (fix-level
7756 (if (org-before-first-heading-p) "*"
7757 (save-excursion
7758 (org-back-to-heading t)
7759 (when (org-previous-line-empty-p) (setq empty-line-p t))
7760 (looking-at org-outline-regexp)
7761 (make-string (1- (length (match-string 0))) ?*))))
7762 (stars
7763 (save-excursion
7764 (condition-case nil
7765 (if top "* "
7766 (org-back-to-heading invisible-ok)
7767 (when (and (not on-heading)
7768 (featurep 'org-inlinetask)
7769 (integerp org-inlinetask-min-level)
7770 (>= (length (match-string 0))
7771 org-inlinetask-min-level))
7772 ;; Find a heading level before the inline
7773 ;; task.
7774 (while (and (setq level (org-up-heading-safe))
7775 (>= level org-inlinetask-min-level)))
7776 (if (org-at-heading-p)
7777 (org-back-to-heading invisible-ok)
7778 (error "This should not happen")))
7779 (unless (and (save-excursion
7780 (save-match-data
7781 (org-backward-heading-same-level
7782 1 invisible-ok))
7783 (= (point) (match-beginning 0)))
7784 (not (org-next-line-empty-p)))
7785 (setq empty-line-p (or empty-line-p
7786 (org-previous-line-empty-p))))
7787 (match-string 0))
7788 (error (or fix-level "* ")))))
7789 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
7790 (blank (if (eq blank-a 'auto) empty-line-p blank-a)))
7792 ;; If we insert after content, move there and clean up
7793 ;; whitespace.
7794 (when (and respect-content
7795 (not (org-looking-at-p org-outline-regexp-bol)))
7796 (if (not (org-before-first-heading-p))
7797 (org-end-of-subtree nil t)
7798 (re-search-forward org-outline-regexp-bol)
7799 (beginning-of-line 0))
7800 (skip-chars-backward " \r\t\n")
7801 (and (not (org-looking-back "^\\*+" (line-beginning-position)))
7802 (looking-at "[ \t]+") (replace-match ""))
7803 (unless (eobp) (forward-char 1))
7804 (when (looking-at "^\\*")
7805 (unless (bobp) (backward-char 1))
7806 (insert "\n")))
7808 ;; If we are splitting, grab the text that should be moved
7809 ;; to the new headline.
7810 (when may-split
7811 (if (org-at-heading-p)
7812 ;; This is a heading: split intelligently (keeping
7813 ;; tags).
7814 (let ((pos (point)))
7815 (beginning-of-line)
7816 (unless (looking-at org-complex-heading-regexp)
7817 (error "This should not happen"))
7818 (when (and (match-beginning 4)
7819 (> pos (match-beginning 4))
7820 (< pos (match-end 4)))
7821 (setq initial-content (buffer-substring pos (match-end 4)))
7822 (goto-char pos)
7823 (delete-region (point) (match-end 4))
7824 (if (looking-at "[ \t]*$")
7825 (replace-match "")
7826 (insert (make-string (length initial-content) ?\s)))
7827 (setq initial-content (org-trim initial-content)))
7828 (goto-char pos))
7829 ;; A normal line.
7830 (setq initial-content
7831 (org-trim
7832 (delete-and-extract-region (point) (line-end-position))))))
7834 ;; If we are at the beginning of the line, insert before it.
7835 ;; Otherwise, after it.
7836 (cond
7837 ((and (bolp) (looking-at "[ \t]*$")))
7838 ((bolp) (save-excursion (insert "\n")))
7839 (t (end-of-line)
7840 (insert "\n")))
7842 ;; Insert the new heading
7843 (insert stars)
7844 (just-one-space)
7845 (insert initial-content)
7846 (unless (and blank (org-previous-line-empty-p))
7847 (org-N-empty-lines-before-current (if blank 1 0)))
7848 ;; Adjust visibility, which may be messed up if we removed
7849 ;; blank lines while previous entry was hidden.
7850 (let ((bol (line-beginning-position)))
7851 (dolist (o (overlays-at (1- bol)))
7852 (when (and (eq (overlay-get o 'invisible) 'outline)
7853 (eq (overlay-end o) bol))
7854 (move-overlay o (overlay-start o) (1- bol)))))
7855 (run-hooks 'org-insert-heading-hook)))))))
7857 (defun org-N-empty-lines-before-current (N)
7858 "Make the number of empty lines before current exactly N.
7859 So this will delete or add empty lines."
7860 (save-excursion
7861 (beginning-of-line)
7862 (let ((p (point)))
7863 (skip-chars-backward " \r\t\n")
7864 (unless (bolp) (forward-line))
7865 (delete-region (point) p))
7866 (when (> N 0) (insert (make-string N ?\n)))))
7868 (defun org-get-heading (&optional no-tags no-todo)
7869 "Return the heading of the current entry, without the stars.
7870 When NO-TAGS is non-nil, don't include tags.
7871 When NO-TODO is non-nil, don't include TODO keywords."
7872 (save-excursion
7873 (org-back-to-heading t)
7874 (cond
7875 ((and no-tags no-todo)
7876 (looking-at org-complex-heading-regexp)
7877 (match-string 4))
7878 (no-tags
7879 (looking-at (concat org-outline-regexp
7880 "\\(.*?\\)"
7881 "\\(?:[ \t]+:[[:alnum:]:_@#%]+:\\)?[ \t]*$"))
7882 (match-string 1))
7883 (no-todo
7884 (looking-at org-todo-line-regexp)
7885 (match-string 3))
7886 (t (looking-at org-heading-regexp)
7887 (match-string 2)))))
7889 (defvar orgstruct-mode) ; defined below
7891 (defun org-heading-components ()
7892 "Return the components of the current heading.
7893 This is a list with the following elements:
7894 - the level as an integer
7895 - the reduced level, different if `org-odd-levels-only' is set.
7896 - the TODO keyword, or nil
7897 - the priority character, like ?A, or nil if no priority is given
7898 - the headline text itself, or the tags string if no headline text
7899 - the tags string, or nil."
7900 (save-excursion
7901 (org-back-to-heading t)
7902 (when (let (case-fold-search)
7903 (looking-at
7904 (if orgstruct-mode
7905 org-heading-regexp
7906 org-complex-heading-regexp)))
7907 (if orgstruct-mode
7908 (list (length (match-string 1))
7909 (org-reduced-level (length (match-string 1)))
7912 (match-string 2)
7913 nil)
7914 (list (length (match-string 1))
7915 (org-reduced-level (length (match-string 1)))
7916 (org-match-string-no-properties 2)
7917 (and (match-end 3) (aref (match-string 3) 2))
7918 (org-match-string-no-properties 4)
7919 (org-match-string-no-properties 5))))))
7921 (defun org-get-entry ()
7922 "Get the entry text, after heading, entire subtree."
7923 (save-excursion
7924 (org-back-to-heading t)
7925 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
7927 (defun org-edit-headline (&optional heading)
7928 "Edit the current headline.
7929 Set it to HEADING when provided."
7930 (interactive)
7931 (org-with-wide-buffer
7932 (org-back-to-heading t)
7933 (when (looking-at org-complex-heading-regexp)
7934 (let* ((old (match-string-no-properties 4))
7935 (new (org-trim (or heading (read-string "Edit: " old)))))
7936 (unless (equal old new)
7937 (if old (replace-match new t t nil 4)
7938 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
7939 (insert " " new))
7940 (org-set-tags nil t)
7941 (when (looking-at "[ \t]*$") (replace-match "")))))))
7943 (defun org-insert-heading-after-current ()
7944 "Insert a new heading with same level as current, after current subtree."
7945 (interactive)
7946 (org-back-to-heading)
7947 (org-insert-heading)
7948 (org-move-subtree-down)
7949 (end-of-line 1))
7951 (defun org-insert-heading-respect-content (&optional invisible-ok)
7952 "Insert heading with `org-insert-heading-respect-content' set to t."
7953 (interactive)
7954 (org-insert-heading '(4) invisible-ok))
7956 (defun org-insert-todo-heading-respect-content (&optional force-state)
7957 "Insert TODO heading with `org-insert-heading-respect-content' set to t."
7958 (interactive)
7959 (org-insert-todo-heading force-state '(4)))
7961 (defun org-insert-todo-heading (arg &optional force-heading)
7962 "Insert a new heading with the same level and TODO state as current heading.
7963 If the heading has no TODO state, or if the state is DONE, use the first
7964 state (TODO by default). Also with one prefix arg, force first state. With
7965 two prefix args, force inserting at the end of the parent subtree."
7966 (interactive "P")
7967 (when (or force-heading (not (org-insert-item 'checkbox)))
7968 (org-insert-heading (or (and (equal arg '(16)) '(16))
7969 force-heading))
7970 (save-excursion
7971 (org-back-to-heading)
7972 (outline-previous-heading)
7973 (looking-at org-todo-line-regexp))
7974 (let*
7975 ((new-mark-x
7976 (if (or (equal arg '(4))
7977 (not (match-beginning 2))
7978 (member (match-string 2) org-done-keywords))
7979 (car org-todo-keywords-1)
7980 (match-string 2)))
7981 (new-mark
7983 (run-hook-with-args-until-success
7984 'org-todo-get-default-hook new-mark-x nil)
7985 new-mark-x)))
7986 (beginning-of-line 1)
7987 (and (looking-at org-outline-regexp) (goto-char (match-end 0))
7988 (if org-treat-insert-todo-heading-as-state-change
7989 (org-todo new-mark)
7990 (insert new-mark " "))))
7991 (when org-provide-todo-statistics
7992 (org-update-parent-todo-statistics))))
7994 (defun org-insert-subheading (arg)
7995 "Insert a new subheading and demote it.
7996 Works for outline headings and for plain lists alike."
7997 (interactive "P")
7998 (org-insert-heading arg)
7999 (cond
8000 ((org-at-heading-p) (org-do-demote))
8001 ((org-at-item-p) (org-indent-item))))
8003 (defun org-insert-todo-subheading (arg)
8004 "Insert a new subheading with TODO keyword or checkbox and demote it.
8005 Works for outline headings and for plain lists alike."
8006 (interactive "P")
8007 (org-insert-todo-heading arg)
8008 (cond
8009 ((org-at-heading-p) (org-do-demote))
8010 ((org-at-item-p) (org-indent-item))))
8012 ;;; Promotion and Demotion
8014 (defvar org-after-demote-entry-hook nil
8015 "Hook run after an entry has been demoted.
8016 The cursor will be at the beginning of the entry.
8017 When a subtree is being demoted, the hook will be called for each node.")
8019 (defvar org-after-promote-entry-hook nil
8020 "Hook run after an entry has been promoted.
8021 The cursor will be at the beginning of the entry.
8022 When a subtree is being promoted, the hook will be called for each node.")
8024 (defun org-promote-subtree ()
8025 "Promote the entire subtree.
8026 See also `org-promote'."
8027 (interactive)
8028 (save-excursion
8029 (org-with-limited-levels (org-map-tree 'org-promote)))
8030 (org-fix-position-after-promote))
8032 (defun org-demote-subtree ()
8033 "Demote the entire subtree.
8034 See `org-demote' and `org-promote'."
8035 (interactive)
8036 (save-excursion
8037 (org-with-limited-levels (org-map-tree 'org-demote)))
8038 (org-fix-position-after-promote))
8040 (defun org-do-promote ()
8041 "Promote the current heading higher up the tree.
8042 If the region is active in `transient-mark-mode', promote all
8043 headings in the region."
8044 (interactive)
8045 (save-excursion
8046 (if (org-region-active-p)
8047 (org-map-region 'org-promote (region-beginning) (region-end))
8048 (org-promote)))
8049 (org-fix-position-after-promote))
8051 (defun org-do-demote ()
8052 "Demote the current heading lower down the tree.
8053 If the region is active in `transient-mark-mode', demote all
8054 headings in the region."
8055 (interactive)
8056 (save-excursion
8057 (if (org-region-active-p)
8058 (org-map-region 'org-demote (region-beginning) (region-end))
8059 (org-demote)))
8060 (org-fix-position-after-promote))
8062 (defun org-fix-position-after-promote ()
8063 "Fix cursor position and indentation after demoting/promoting."
8064 (let ((pos (point)))
8065 (when (save-excursion
8066 (beginning-of-line 1)
8067 (looking-at org-todo-line-regexp)
8068 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
8069 (cond ((eobp) (insert " "))
8070 ((eolp) (insert " "))
8071 ((equal (char-after) ?\ ) (forward-char 1))))))
8073 (defun org-current-level ()
8074 "Return the level of the current entry, or nil if before the first headline.
8075 The level is the number of stars at the beginning of the
8076 headline. Use `org-reduced-level' to remove the effect of
8077 `org-odd-levels'. Unlike to `org-outline-level', this function
8078 ignores inlinetasks."
8079 (let ((level (org-with-limited-levels (org-outline-level))))
8080 (and (> level 0) level)))
8082 (defun org-get-previous-line-level ()
8083 "Return the outline depth of the last headline before the current line.
8084 Returns 0 for the first headline in the buffer, and nil if before the
8085 first headline."
8086 (and (org-current-level)
8087 (or (and (/= (line-beginning-position) (point-min))
8088 (save-excursion (beginning-of-line 0) (org-current-level)))
8089 0)))
8091 (defun org-reduced-level (l)
8092 "Compute the effective level of a heading.
8093 This takes into account the setting of `org-odd-levels-only'."
8094 (cond
8095 ((zerop l) 0)
8096 (org-odd-levels-only (1+ (floor (/ l 2))))
8097 (t l)))
8099 (defun org-level-increment ()
8100 "Return the number of stars that will be added or removed at a
8101 time to headlines when structure editing, based on the value of
8102 `org-odd-levels-only'."
8103 (if org-odd-levels-only 2 1))
8105 (defun org-get-valid-level (level &optional change)
8106 "Rectify a level change under the influence of `org-odd-levels-only'
8107 LEVEL is a current level, CHANGE is by how much the level should be
8108 modified. Even if CHANGE is nil, LEVEL may be returned modified because
8109 even level numbers will become the next higher odd number."
8110 (if org-odd-levels-only
8111 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
8112 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
8113 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
8114 (max 1 (+ level (or change 0)))))
8115 (define-obsolete-function-alias 'org-get-legal-level 'org-get-valid-level "23.1")
8117 (defun org-promote ()
8118 "Promote the current heading higher up the tree."
8119 (org-with-wide-buffer
8120 (org-back-to-heading t)
8121 (let* ((after-change-functions (remq 'flyspell-after-change-function
8122 after-change-functions))
8123 (level (save-match-data (funcall outline-level)))
8124 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
8125 (diff (abs (- level (length up-head) -1))))
8126 (cond
8127 ((and (= level 1) org-allow-promoting-top-level-subtree)
8128 (replace-match "# " nil t))
8129 ((= level 1)
8130 (user-error "Cannot promote to level 0. UNDO to recover if necessary"))
8131 (t (replace-match up-head nil t)))
8132 (unless (= level 1)
8133 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8134 (when org-adapt-indentation (org-fixup-indentation (- diff))))
8135 (run-hooks 'org-after-promote-entry-hook))))
8137 (defun org-demote ()
8138 "Demote the current heading lower down the tree."
8139 (org-with-wide-buffer
8140 (org-back-to-heading t)
8141 (let* ((after-change-functions (remq 'flyspell-after-change-function
8142 after-change-functions))
8143 (level (save-match-data (funcall outline-level)))
8144 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
8145 (diff (abs (- level (length down-head) -1))))
8146 (replace-match down-head nil t)
8147 (when org-auto-align-tags (org-set-tags nil 'ignore-column))
8148 (when org-adapt-indentation (org-fixup-indentation diff))
8149 (run-hooks 'org-after-demote-entry-hook))))
8151 (defun org-cycle-level ()
8152 "Cycle the level of an empty headline through possible states.
8153 This goes first to child, then to parent, level, then up the hierarchy.
8154 After top level, it switches back to sibling level."
8155 (interactive)
8156 (let ((org-adapt-indentation nil))
8157 (when (org-point-at-end-of-empty-headline)
8158 (setq this-command 'org-cycle-level) ; Only needed for caching
8159 (let ((cur-level (org-current-level))
8160 (prev-level (org-get-previous-line-level)))
8161 (cond
8162 ;; If first headline in file, promote to top-level.
8163 ((= prev-level 0)
8164 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8165 do (org-do-promote)))
8166 ;; If same level as prev, demote one.
8167 ((= prev-level cur-level)
8168 (org-do-demote))
8169 ;; If parent is top-level, promote to top level if not already.
8170 ((= prev-level 1)
8171 (cl-loop repeat (/ (- cur-level 1) (org-level-increment))
8172 do (org-do-promote)))
8173 ;; If top-level, return to prev-level.
8174 ((= cur-level 1)
8175 (cl-loop repeat (/ (- prev-level 1) (org-level-increment))
8176 do (org-do-demote)))
8177 ;; If less than prev-level, promote one.
8178 ((< cur-level prev-level)
8179 (org-do-promote))
8180 ;; If deeper than prev-level, promote until higher than
8181 ;; prev-level.
8182 ((> cur-level prev-level)
8183 (cl-loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
8184 do (org-do-promote))))
8185 t))))
8187 (defun org-map-tree (fun)
8188 "Call FUN for every heading underneath the current one."
8189 (org-back-to-heading)
8190 (let ((level (funcall outline-level)))
8191 (save-excursion
8192 (funcall fun)
8193 (while (and (progn
8194 (outline-next-heading)
8195 (> (funcall outline-level) level))
8196 (not (eobp)))
8197 (funcall fun)))))
8199 (defun org-map-region (fun beg end)
8200 "Call FUN for every heading between BEG and END."
8201 (let ((org-ignore-region t))
8202 (save-excursion
8203 (setq end (copy-marker end))
8204 (goto-char beg)
8205 (when (and (re-search-forward org-outline-regexp-bol nil t)
8206 (< (point) end))
8207 (funcall fun))
8208 (while (and (progn
8209 (outline-next-heading)
8210 (< (point) end))
8211 (not (eobp)))
8212 (funcall fun)))))
8214 (defun org-fixup-indentation (diff)
8215 "Change the indentation in the current entry by DIFF.
8217 DIFF is an integer. Indentation is done according to the
8218 following rules:
8220 - Planning information and property drawers are always indented
8221 according to the new level of the headline;
8223 - Footnote definitions and their contents are ignored;
8225 - Inlinetasks' boundaries are not shifted;
8227 - Empty lines are ignored;
8229 - Other lines' indentation are shifted by DIFF columns, unless
8230 it would introduce a structural change in the document, in
8231 which case no shifting is done at all.
8233 Assume point is at a heading or an inlinetask beginning."
8234 (org-with-wide-buffer
8235 (narrow-to-region (line-beginning-position)
8236 (save-excursion
8237 (if (org-with-limited-levels (org-at-heading-p))
8238 (org-with-limited-levels (outline-next-heading))
8239 (org-inlinetask-goto-end))
8240 (point)))
8241 (forward-line)
8242 ;; Indent properly planning info and property drawer.
8243 (when (org-looking-at-p org-planning-line-re)
8244 (org-indent-line)
8245 (forward-line))
8246 (when (looking-at org-property-drawer-re)
8247 (goto-char (match-end 0))
8248 (forward-line)
8249 (save-excursion (org-indent-region (match-beginning 0) (match-end 0))))
8250 (catch 'no-shift
8251 (when (zerop diff) (throw 'no-shift nil))
8252 ;; If DIFF is negative, first check if a shift is possible at all
8253 ;; (e.g., it doesn't break structure). This can only happen if
8254 ;; some contents are not properly indented.
8255 (let ((case-fold-search t))
8256 (when (< diff 0)
8257 (let ((diff (- diff))
8258 (forbidden-re (concat org-outline-regexp
8259 "\\|"
8260 (substring org-footnote-definition-re 1))))
8261 (save-excursion
8262 (while (not (eobp))
8263 (cond
8264 ((org-looking-at-p "[ \t]*$") (forward-line))
8265 ((and (org-looking-at-p org-footnote-definition-re)
8266 (let ((e (org-element-at-point)))
8267 (and (eq (org-element-type e) 'footnote-definition)
8268 (goto-char (org-element-property :end e))))))
8269 ((org-looking-at-p org-outline-regexp) (forward-line))
8270 ;; Give up if shifting would move before column 0 or
8271 ;; if it would introduce a headline or a footnote
8272 ;; definition.
8274 (skip-chars-forward " \t")
8275 (let ((ind (current-column)))
8276 (when (or (< ind diff)
8277 (and (= ind diff) (org-looking-at-p forbidden-re)))
8278 (throw 'no-shift nil)))
8279 ;; Ignore contents of example blocks and source
8280 ;; blocks if their indentation is meant to be
8281 ;; preserved. Jump to block's closing line.
8282 (beginning-of-line)
8283 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8284 (let ((e (org-element-at-point)))
8285 (and (memq (org-element-type e)
8286 '(example-block src-block))
8287 (or org-src-preserve-indentation
8288 (org-element-property :preserve-indent e))
8289 (goto-char (org-element-property :end e))
8290 (progn (skip-chars-backward " \r\t\n")
8291 (beginning-of-line)
8292 t))))
8293 (forward-line))))))))
8294 ;; Shift lines but footnote definitions, inlinetasks boundaries
8295 ;; by DIFF. Also skip contents of source or example blocks
8296 ;; when indentation is meant to be preserved.
8297 (while (not (eobp))
8298 (cond
8299 ((and (org-looking-at-p org-footnote-definition-re)
8300 (let ((e (org-element-at-point)))
8301 (and (eq (org-element-type e) 'footnote-definition)
8302 (goto-char (org-element-property :end e))))))
8303 ((org-looking-at-p org-outline-regexp) (forward-line))
8304 ((org-looking-at-p "[ \t]*$") (forward-line))
8306 (org-indent-line-to (+ (org-get-indentation) diff))
8307 (beginning-of-line)
8308 (or (and (org-looking-at-p "[ \t]*#\\+BEGIN_\\(EXAMPLE\\|SRC\\)")
8309 (let ((e (org-element-at-point)))
8310 (and (memq (org-element-type e)
8311 '(example-block src-block))
8312 (or org-src-preserve-indentation
8313 (org-element-property :preserve-indent e))
8314 (goto-char (org-element-property :end e))
8315 (progn (skip-chars-backward " \r\t\n")
8316 (beginning-of-line)
8317 t))))
8318 (forward-line)))))))))
8320 (defun org-convert-to-odd-levels ()
8321 "Convert an org-mode file with all levels allowed to one with odd levels.
8322 This will leave level 1 alone, convert level 2 to level 3, level 3 to
8323 level 5 etc."
8324 (interactive)
8325 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
8326 (let ((outline-level 'org-outline-level)
8327 (org-odd-levels-only nil) n)
8328 (save-excursion
8329 (goto-char (point-min))
8330 (while (re-search-forward "^\\*\\*+ " nil t)
8331 (setq n (- (length (match-string 0)) 2))
8332 (while (>= (setq n (1- n)) 0)
8333 (org-demote))
8334 (end-of-line 1))))))
8336 (defun org-convert-to-oddeven-levels ()
8337 "Convert an org-mode file with only odd levels to one with odd/even levels.
8338 This promotes level 3 to level 2, level 5 to level 3 etc. If the
8339 file contains a section with an even level, conversion would
8340 destroy the structure of the file. An error is signaled in this
8341 case."
8342 (interactive)
8343 (goto-char (point-min))
8344 ;; First check if there are no even levels
8345 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
8346 (org-show-set-visibility 'canonical)
8347 (error "Not all levels are odd in this file. Conversion not possible"))
8348 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
8349 (let ((outline-regexp org-outline-regexp)
8350 (outline-level 'org-outline-level)
8351 (org-odd-levels-only nil) n)
8352 (save-excursion
8353 (goto-char (point-min))
8354 (while (re-search-forward "^\\*\\*+ " nil t)
8355 (setq n (/ (1- (length (match-string 0))) 2))
8356 (while (>= (setq n (1- n)) 0)
8357 (org-promote))
8358 (end-of-line 1))))))
8360 (defun org-tr-level (n)
8361 "Make N odd if required."
8362 (if org-odd-levels-only (1+ (/ n 2)) n))
8364 ;;; Vertical tree motion, cutting and pasting of subtrees
8366 (defun org-move-subtree-up (&optional arg)
8367 "Move the current subtree up past ARG headlines of the same level."
8368 (interactive "p")
8369 (org-move-subtree-down (- (prefix-numeric-value arg))))
8371 (defun org-move-subtree-down (&optional arg)
8372 "Move the current subtree down past ARG headlines of the same level."
8373 (interactive "p")
8374 (setq arg (prefix-numeric-value arg))
8375 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
8376 'org-get-last-sibling))
8377 (ins-point (make-marker))
8378 (cnt (abs arg))
8379 (col (current-column))
8380 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
8381 ;; Select the tree
8382 (org-back-to-heading)
8383 (setq beg0 (point))
8384 (save-excursion
8385 (setq ne-beg (org-back-over-empty-lines))
8386 (setq beg (point)))
8387 (save-match-data
8388 (save-excursion (outline-end-of-heading)
8389 (setq folded (outline-invisible-p)))
8390 (progn (org-end-of-subtree nil t)
8391 (unless (eobp) (backward-char))))
8392 (outline-next-heading)
8393 (setq ne-end (org-back-over-empty-lines))
8394 (setq end (point))
8395 (goto-char beg0)
8396 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
8397 ;; include less whitespace
8398 (save-excursion
8399 (goto-char beg)
8400 (forward-line (- ne-beg ne-end))
8401 (setq beg (point))))
8402 ;; Find insertion point, with error handling
8403 (while (> cnt 0)
8404 (or (and (funcall movfunc) (looking-at org-outline-regexp))
8405 (progn (goto-char beg0)
8406 (user-error "Cannot move past superior level or buffer limit")))
8407 (setq cnt (1- cnt)))
8408 (when (> arg 0)
8409 ;; Moving forward - still need to move over subtree
8410 (org-end-of-subtree t t)
8411 (save-excursion
8412 (org-back-over-empty-lines)
8413 (or (bolp) (newline))))
8414 (setq ne-ins (org-back-over-empty-lines))
8415 (move-marker ins-point (point))
8416 (setq txt (buffer-substring beg end))
8417 (org-save-markers-in-region beg end)
8418 (delete-region beg end)
8419 (org-remove-empty-overlays-at beg)
8420 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
8421 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
8422 (and (not (bolp)) (looking-at "\n") (forward-char 1))
8423 (let ((bbb (point)))
8424 (insert-before-markers txt)
8425 (org-reinstall-markers-in-region bbb)
8426 (move-marker ins-point bbb))
8427 (or (bolp) (insert "\n"))
8428 (setq ins-end (point))
8429 (goto-char ins-point)
8430 (org-skip-whitespace)
8431 (when (and (< arg 0)
8432 (org-first-sibling-p)
8433 (> ne-ins ne-beg))
8434 ;; Move whitespace back to beginning
8435 (save-excursion
8436 (goto-char ins-end)
8437 (let ((kill-whole-line t))
8438 (kill-line (- ne-ins ne-beg)) (point)))
8439 (insert (make-string (- ne-ins ne-beg) ?\n)))
8440 (move-marker ins-point nil)
8441 (if folded
8442 (outline-hide-subtree)
8443 (org-show-entry)
8444 (org-show-children)
8445 (org-cycle-hide-drawers 'children))
8446 (org-clean-visibility-after-subtree-move)
8447 ;; move back to the initial column we were at
8448 (move-to-column col)))
8450 (defvar org-subtree-clip ""
8451 "Clipboard for cut and paste of subtrees.
8452 This is actually only a copy of the kill, because we use the normal kill
8453 ring. We need it to check if the kill was created by `org-copy-subtree'.")
8455 (defvar org-subtree-clip-folded nil
8456 "Was the last copied subtree folded?
8457 This is used to fold the tree back after pasting.")
8459 (defun org-cut-subtree (&optional n)
8460 "Cut the current subtree into the clipboard.
8461 With prefix arg N, cut this many sequential subtrees.
8462 This is a short-hand for marking the subtree and then cutting it."
8463 (interactive "p")
8464 (org-copy-subtree n 'cut))
8466 (defun org-copy-subtree (&optional n cut force-store-markers nosubtrees)
8467 "Copy the current subtree it in the clipboard.
8468 With prefix arg N, copy this many sequential subtrees.
8469 This is a short-hand for marking the subtree and then copying it.
8470 If CUT is non-nil, actually cut the subtree.
8471 If FORCE-STORE-MARKERS is non-nil, store the relative locations
8472 of some markers in the region, even if CUT is non-nil. This is
8473 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
8474 (interactive "p")
8475 (let (beg end folded (beg0 (point)))
8476 (if (org-called-interactively-p 'any)
8477 (org-back-to-heading nil) ; take what looks like a subtree
8478 (org-back-to-heading t)) ; take what is really there
8479 (setq beg (point))
8480 (skip-chars-forward " \t\r\n")
8481 (save-match-data
8482 (if nosubtrees
8483 (outline-next-heading)
8484 (save-excursion (outline-end-of-heading)
8485 (setq folded (outline-invisible-p)))
8486 (ignore-errors (org-forward-heading-same-level (1- n) t))
8487 (org-end-of-subtree t t)))
8488 ;; Include the end of an inlinetask
8489 (when (and (featurep 'org-inlinetask)
8490 (looking-at-p (concat (org-inlinetask-outline-regexp)
8491 "END[ \t]*$")))
8492 (end-of-line))
8493 (setq end (point))
8494 (goto-char beg0)
8495 (when (> end beg)
8496 (setq org-subtree-clip-folded folded)
8497 (when (or cut force-store-markers)
8498 (org-save-markers-in-region beg end))
8499 (if cut (kill-region beg end) (copy-region-as-kill beg end))
8500 (setq org-subtree-clip (current-kill 0))
8501 (message "%s: Subtree(s) with %d characters"
8502 (if cut "Cut" "Copied")
8503 (length org-subtree-clip)))))
8505 (defun org-paste-subtree (&optional level tree for-yank remove)
8506 "Paste the clipboard as a subtree, with modification of headline level.
8507 The entire subtree is promoted or demoted in order to match a new headline
8508 level.
8510 If the cursor is at the beginning of a headline, the same level as
8511 that headline is used to paste the tree.
8513 If not, the new level is derived from the *visible* headings
8514 before and after the insertion point, and taken to be the inferior headline
8515 level of the two. So if the previous visible heading is level 3 and the
8516 next is level 4 (or vice versa), level 4 will be used for insertion.
8517 This makes sure that the subtree remains an independent subtree and does
8518 not swallow low level entries.
8520 You can also force a different level, either by using a numeric prefix
8521 argument, or by inserting the heading marker by hand. For example, if the
8522 cursor is after \"*****\", then the tree will be shifted to level 5.
8524 If optional TREE is given, use this text instead of the kill ring.
8526 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
8527 move back over whitespace before inserting, and move point to the end of
8528 the inserted text when done.
8530 When REMOVE is non-nil, remove the subtree from the clipboard."
8531 (interactive "P")
8532 (setq tree (or tree (and kill-ring (current-kill 0))))
8533 (unless (org-kill-is-subtree-p tree)
8534 (user-error "%s"
8535 (substitute-command-keys
8536 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
8537 (org-with-limited-levels
8538 (let* ((visp (not (outline-invisible-p)))
8539 (txt tree)
8540 (^re_ "\\(\\*+\\)[ \t]*")
8541 (old-level (if (string-match org-outline-regexp-bol txt)
8542 (- (match-end 0) (match-beginning 0) 1)
8543 -1))
8544 (force-level (cond (level (prefix-numeric-value level))
8545 ((and (looking-at "[ \t]*$")
8546 (string-match
8547 "^\\*+$" (buffer-substring
8548 (point-at-bol) (point))))
8549 (- (match-end 0) (match-beginning 0)))
8550 ((and (bolp)
8551 (looking-at org-outline-regexp))
8552 (- (match-end 0) (point) 1))))
8553 (previous-level (save-excursion
8554 (condition-case nil
8555 (progn
8556 (outline-previous-visible-heading 1)
8557 (if (looking-at ^re_)
8558 (- (match-end 0) (match-beginning 0) 1)
8560 (error 1))))
8561 (next-level (save-excursion
8562 (condition-case nil
8563 (progn
8564 (or (looking-at org-outline-regexp)
8565 (outline-next-visible-heading 1))
8566 (if (looking-at ^re_)
8567 (- (match-end 0) (match-beginning 0) 1)
8569 (error 1))))
8570 (new-level (or force-level (max previous-level next-level)))
8571 (shift (if (or (= old-level -1)
8572 (= new-level -1)
8573 (= old-level new-level))
8575 (- new-level old-level)))
8576 (delta (if (> shift 0) -1 1))
8577 (func (if (> shift 0) 'org-demote 'org-promote))
8578 (org-odd-levels-only nil)
8579 beg end newend)
8580 ;; Remove the forced level indicator
8581 (when force-level
8582 (delete-region (point-at-bol) (point)))
8583 ;; Paste
8584 (beginning-of-line (if (bolp) 1 2))
8585 (setq beg (point))
8586 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
8587 (insert-before-markers txt)
8588 (unless (string-match "\n\\'" txt) (insert "\n"))
8589 (setq newend (point))
8590 (org-reinstall-markers-in-region beg)
8591 (setq end (point))
8592 (goto-char beg)
8593 (skip-chars-forward " \t\n\r")
8594 (setq beg (point))
8595 (when (and (outline-invisible-p) visp)
8596 (save-excursion (outline-show-heading)))
8597 ;; Shift if necessary
8598 (unless (= shift 0)
8599 (save-restriction
8600 (narrow-to-region beg end)
8601 (while (not (= shift 0))
8602 (org-map-region func (point-min) (point-max))
8603 (setq shift (+ delta shift)))
8604 (goto-char (point-min))
8605 (setq newend (point-max))))
8606 (when (or (org-called-interactively-p 'interactive) for-yank)
8607 (message "Clipboard pasted as level %d subtree" new-level))
8608 (when (and (not for-yank) ; in this case, org-yank will decide about folding
8609 kill-ring
8610 (eq org-subtree-clip (current-kill 0))
8611 org-subtree-clip-folded)
8612 ;; The tree was folded before it was killed/copied
8613 (outline-hide-subtree))
8614 (and for-yank (goto-char newend))
8615 (and remove (setq kill-ring (cdr kill-ring))))))
8617 (defun org-kill-is-subtree-p (&optional txt)
8618 "Check if the current kill is an outline subtree, or a set of trees.
8619 Returns nil if kill does not start with a headline, or if the first
8620 headline level is not the largest headline level in the tree.
8621 So this will actually accept several entries of equal levels as well,
8622 which is OK for `org-paste-subtree'.
8623 If optional TXT is given, check this string instead of the current kill."
8624 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
8625 (re (org-get-limited-outline-regexp))
8626 (^re (concat "^" re))
8627 (start-level (and kill
8628 (string-match
8629 (concat "\\`\\([ \t\n\r]*?\n\\)?\\(" re "\\)")
8630 kill)
8631 (- (match-end 2) (match-beginning 2) 1)))
8632 (start (1+ (or (match-beginning 2) -1))))
8633 (if (not start-level)
8634 (progn
8635 nil) ;; does not even start with a heading
8636 (catch 'exit
8637 (while (setq start (string-match ^re kill (1+ start)))
8638 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
8639 (throw 'exit nil)))
8640 t))))
8642 (defvar org-markers-to-move nil
8643 "Markers that should be moved with a cut-and-paste operation.
8644 Those markers are stored together with their positions relative to
8645 the start of the region.")
8647 (defun org-save-markers-in-region (beg end)
8648 "Check markers in region.
8649 If these markers are between BEG and END, record their position relative
8650 to BEG, so that after moving the block of text, we can put the markers back
8651 into place.
8652 This function gets called just before an entry or tree gets cut from the
8653 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
8654 called immediately, to move the markers with the entries."
8655 (setq org-markers-to-move nil)
8656 (when (featurep 'org-clock)
8657 (org-clock-save-markers-for-cut-and-paste beg end))
8658 (when (featurep 'org-agenda)
8659 (org-agenda-save-markers-for-cut-and-paste beg end)))
8661 (defun org-check-and-save-marker (marker beg end)
8662 "Check if MARKER is between BEG and END.
8663 If yes, remember the marker and the distance to BEG."
8664 (when (and (marker-buffer marker)
8665 (equal (marker-buffer marker) (current-buffer))
8666 (>= marker beg) (< marker end))
8667 (push (cons marker (- marker beg)) org-markers-to-move)))
8669 (defun org-reinstall-markers-in-region (beg)
8670 "Move all remembered markers to their position relative to BEG."
8671 (dolist (x org-markers-to-move)
8672 (move-marker (car x) (+ beg (cdr x))))
8673 (setq org-markers-to-move nil))
8675 (defun org-narrow-to-subtree ()
8676 "Narrow buffer to the current subtree."
8677 (interactive)
8678 (save-excursion
8679 (save-match-data
8680 (org-with-limited-levels
8681 (narrow-to-region
8682 (progn (org-back-to-heading t) (point))
8683 (progn (org-end-of-subtree t t)
8684 (when (and (org-at-heading-p) (not (eobp))) (backward-char 1))
8685 (point)))))))
8687 (defun org-narrow-to-block ()
8688 "Narrow buffer to the current block."
8689 (interactive)
8690 (let* ((case-fold-search t)
8691 (blockp (org-between-regexps-p "^[ \t]*#\\+begin_.*"
8692 "^[ \t]*#\\+end_.*")))
8693 (if blockp
8694 (narrow-to-region (car blockp) (cdr blockp))
8695 (user-error "Not in a block"))))
8697 (defun org-clone-subtree-with-time-shift (n &optional shift)
8698 "Clone the task (subtree) at point N times.
8699 The clones will be inserted as siblings.
8701 In interactive use, the user will be prompted for the number of
8702 clones to be produced. If the entry has a timestamp, the user
8703 will also be prompted for a time shift, which may be a repeater
8704 as used in time stamps, for example `+3d'. To disable this,
8705 you can call the function with a universal prefix argument.
8707 When a valid repeater is given and the entry contains any time
8708 stamps, the clones will become a sequence in time, with time
8709 stamps in the subtree shifted for each clone produced. If SHIFT
8710 is nil or the empty string, time stamps will be left alone. The
8711 ID property of the original subtree is removed.
8713 If the original subtree did contain time stamps with a repeater,
8714 the following will happen:
8715 - the repeater will be removed in each clone
8716 - an additional clone will be produced, with the current, unshifted
8717 date(s) in the entry.
8718 - the original entry will be placed *after* all the clones, with
8719 repeater intact.
8720 - the start days in the repeater in the original entry will be shifted
8721 to past the last clone.
8722 In this way you can spell out a number of instances of a repeating task,
8723 and still retain the repeater to cover future instances of the task.
8725 As described above, N+1 clones are produced when the original
8726 subtree has a repeater. Setting N to 0, then, can be used to
8727 remove the repeater from a subtree and create a shifted clone
8728 with the original repeater."
8729 (interactive "nNumber of clones to produce: ")
8730 (let ((shift
8731 (or shift
8732 (if (and (not (equal current-prefix-arg '(4)))
8733 (save-excursion
8734 (re-search-forward org-ts-regexp-both
8735 (save-excursion
8736 (org-end-of-subtree t)
8737 (point)) t)))
8738 (read-from-minibuffer
8739 "Date shift per clone (e.g. +1w, empty to copy unchanged): ")
8740 ""))) ;; No time shift
8741 (n-no-remove -1)
8742 (drawer-re org-drawer-regexp)
8743 (org-clock-re (format "^[ \t]*%s.*$" org-clock-string))
8744 beg end template task idprop
8745 shift-n shift-what doshift nmin nmax)
8746 (unless (wholenump n)
8747 (user-error "Invalid number of replications %s" n))
8748 (when (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
8749 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([hdwmy]\\)[ \t]*\\'"
8750 shift)))
8751 (user-error "Invalid shift specification %s" shift))
8752 (when doshift
8753 (setq shift-n (string-to-number (match-string 1 shift))
8754 shift-what (cdr (assoc (match-string 2 shift)
8755 '(("d" . day) ("w" . week)
8756 ("m" . month) ("y" . year))))))
8757 (when (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
8758 (setq nmin 1 nmax n)
8759 (org-back-to-heading t)
8760 (setq beg (point))
8761 (setq idprop (org-entry-get nil "ID"))
8762 (org-end-of-subtree t t)
8763 (or (bolp) (insert "\n"))
8764 (setq end (point))
8765 (setq template (buffer-substring beg end))
8766 (when (and doshift
8767 (string-match "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template))
8768 (delete-region beg end)
8769 (setq end beg)
8770 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
8771 (goto-char end)
8772 (cl-loop for n from nmin to nmax do
8773 ;; prepare clone
8774 (with-temp-buffer
8775 (insert template)
8776 (org-mode)
8777 (goto-char (point-min))
8778 (org-show-subtree)
8779 (and idprop (if org-clone-delete-id
8780 (org-entry-delete nil "ID")
8781 (org-id-get-create t)))
8782 (unless (= n 0)
8783 (while (re-search-forward org-clock-re nil t)
8784 (kill-whole-line))
8785 (goto-char (point-min))
8786 (while (re-search-forward drawer-re nil t)
8787 (org-remove-empty-drawer-at (point))))
8788 (goto-char (point-min))
8789 (when doshift
8790 (while (re-search-forward org-ts-regexp-both nil t)
8791 (org-timestamp-change (* n shift-n) shift-what))
8792 (unless (= n n-no-remove)
8793 (goto-char (point-min))
8794 (while (re-search-forward org-ts-regexp nil t)
8795 (save-excursion
8796 (goto-char (match-beginning 0))
8797 (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)")
8798 (delete-region (match-beginning 1) (match-end 1)))))))
8799 (setq task (buffer-string)))
8800 (insert task))
8801 (goto-char beg)))
8803 ;;; Outline Sorting
8805 (defun org-sort (with-case)
8806 "Call `org-sort-entries', `org-table-sort-lines' or `org-sort-list'.
8807 Optional argument WITH-CASE means sort case-sensitively."
8808 (interactive "P")
8809 (cond
8810 ((org-at-table-p) (org-call-with-arg 'org-table-sort-lines with-case))
8811 ((org-at-item-p) (org-call-with-arg 'org-sort-list with-case))
8813 (org-call-with-arg 'org-sort-entries with-case))))
8815 (defun org-sort-remove-invisible (s)
8816 "Remove invisible links from string S."
8817 (remove-text-properties 0 (length s) org-rm-props s)
8818 (while (string-match org-bracket-link-regexp s)
8819 (setq s (replace-match (if (match-end 2)
8820 (match-string 3 s)
8821 (match-string 1 s))
8822 t t s)))
8823 (let ((st (format " %s " s)))
8824 (while (string-match org-emph-re st)
8825 (setq st (replace-match (format " %s " (match-string 4 st)) t t st)))
8826 (setq s (substring st 1 -1)))
8829 (defvar org-priority-regexp) ; defined later in the file
8831 (defvar org-after-sorting-entries-or-items-hook nil
8832 "Hook that is run after a bunch of entries or items have been sorted.
8833 When children are sorted, the cursor is in the parent line when this
8834 hook gets called. When a region or a plain list is sorted, the cursor
8835 will be in the first entry of the sorted region/list.")
8837 (defun org-sort-entries
8838 (&optional with-case sorting-type getkey-func compare-func property)
8839 "Sort entries on a certain level of an outline tree.
8840 If there is an active region, the entries in the region are sorted.
8841 Else, if the cursor is before the first entry, sort the top-level items.
8842 Else, the children of the entry at point are sorted.
8844 Sorting can be alphabetically, numerically, by date/time as given by
8845 a time stamp, by a property, by priority order, or by a custom function.
8847 The command prompts for the sorting type unless it has been given to the
8848 function through the SORTING-TYPE argument, which needs to be a character,
8849 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?o ?O ?r ?R ?f ?F ?k ?K). Here is
8850 the precise meaning of each character:
8852 a Alphabetically, ignoring the TODO keyword and the priority, if any.
8853 c By creation time, which is assumed to be the first inactive time stamp
8854 at the beginning of a line.
8855 d By deadline date/time.
8856 k By clocking time.
8857 n Numerically, by converting the beginning of the entry/item to a number.
8858 o By order of TODO keywords.
8859 p By priority according to the cookie.
8860 r By the value of a property.
8861 s By scheduled date/time.
8862 t By date/time, either the first active time stamp in the entry, or, if
8863 none exist, by the first inactive one.
8865 Capital letters will reverse the sort order.
8867 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
8868 called with point at the beginning of the record. It must return either
8869 a string or a number that should serve as the sorting key for that record.
8871 Comparing entries ignores case by default. However, with an optional argument
8872 WITH-CASE, the sorting considers case as well.
8874 Sorting is done against the visible part of the headlines, it ignores hidden
8875 links.
8877 When sorting is done, call `org-after-sorting-entries-or-items-hook'."
8878 (interactive "P")
8879 (let ((case-func (if with-case 'identity 'downcase))
8880 (cmstr
8881 ;; The clock marker is lost when using `sort-subr', let's
8882 ;; store the clocking string.
8883 (when (equal (marker-buffer org-clock-marker) (current-buffer))
8884 (save-excursion
8885 (goto-char org-clock-marker)
8886 (buffer-substring-no-properties (line-beginning-position)
8887 (point)))))
8888 start beg end stars re re2
8889 txt what tmp)
8890 ;; Find beginning and end of region to sort
8891 (cond
8892 ((org-region-active-p)
8893 ;; we will sort the region
8894 (setq end (region-end)
8895 what "region")
8896 (goto-char (region-beginning))
8897 (unless (org-at-heading-p) (outline-next-heading))
8898 (setq start (point)))
8899 ((or (org-at-heading-p)
8900 (ignore-errors (progn (org-back-to-heading) t)))
8901 ;; we will sort the children of the current headline
8902 (org-back-to-heading)
8903 (setq start (point)
8904 end (progn (org-end-of-subtree t t)
8905 (or (bolp) (insert "\n"))
8906 (when (>= (org-back-over-empty-lines) 1)
8907 (forward-line 1))
8908 (point))
8909 what "children")
8910 (goto-char start)
8911 (outline-show-subtree)
8912 (outline-next-heading))
8914 ;; we will sort the top-level entries in this file
8915 (goto-char (point-min))
8916 (or (org-at-heading-p) (outline-next-heading))
8917 (setq start (point))
8918 (goto-char (point-max))
8919 (beginning-of-line 1)
8920 (when (looking-at ".*?\\S-")
8921 ;; File ends in a non-white line
8922 (end-of-line 1)
8923 (insert "\n"))
8924 (setq end (point-max))
8925 (setq what "top-level")
8926 (goto-char start)
8927 (outline-show-all)))
8929 (setq beg (point))
8930 (when (>= beg end) (goto-char start) (user-error "Nothing to sort"))
8932 (looking-at "\\(\\*+\\)")
8933 (setq stars (match-string 1)
8934 re (concat "^" (regexp-quote stars) " +")
8935 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[ \t\n]")
8936 txt (buffer-substring beg end))
8937 (unless (equal (substring txt -1) "\n") (setq txt (concat txt "\n")))
8938 (when (and (not (equal stars "*")) (string-match re2 txt))
8939 (user-error "Region to sort contains a level above the first entry"))
8941 (unless sorting-type
8942 (message
8943 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
8944 [t]ime [s]cheduled [d]eadline [c]reated cloc[k]ing
8945 A/N/P/R/O/F/T/S/D/C/K means reversed:"
8946 what)
8947 (setq sorting-type (read-char-exclusive))
8949 (unless getkey-func
8950 (and (= (downcase sorting-type) ?f)
8951 (setq getkey-func
8952 (completing-read "Sort using function: "
8953 obarray 'fboundp t nil nil))
8954 (setq getkey-func (intern getkey-func))))
8956 (and (= (downcase sorting-type) ?r)
8957 (not property)
8958 (setq property
8959 (completing-read "Property: "
8960 (mapcar #'list (org-buffer-property-keys t))
8961 nil t))))
8963 (when (member sorting-type '(?k ?K)) (org-clock-sum))
8964 (message "Sorting entries...")
8966 (save-restriction
8967 (narrow-to-region start end)
8968 (let ((dcst (downcase sorting-type))
8969 (case-fold-search nil)
8970 (now (current-time)))
8971 (sort-subr
8972 (/= dcst sorting-type)
8973 ;; This function moves to the beginning character of the "record" to
8974 ;; be sorted.
8975 (lambda nil
8976 (if (re-search-forward re nil t)
8977 (goto-char (match-beginning 0))
8978 (goto-char (point-max))))
8979 ;; This function moves to the last character of the "record" being
8980 ;; sorted.
8981 (lambda nil
8982 (save-match-data
8983 (condition-case nil
8984 (outline-forward-same-level 1)
8985 (error
8986 (goto-char (point-max))))))
8987 ;; This function returns the value that gets sorted against.
8988 (lambda nil
8989 (cond
8990 ((= dcst ?n)
8991 (if (looking-at org-complex-heading-regexp)
8992 (string-to-number (org-sort-remove-invisible (match-string 4)))
8993 nil))
8994 ((= dcst ?a)
8995 (if (looking-at org-complex-heading-regexp)
8996 (funcall case-func (org-sort-remove-invisible (match-string 4)))
8997 nil))
8998 ((= dcst ?k)
8999 (or (get-text-property (point) :org-clock-minutes) 0))
9000 ((= dcst ?t)
9001 (let ((end (save-excursion (outline-next-heading) (point))))
9002 (if (or (re-search-forward org-ts-regexp end t)
9003 (re-search-forward org-ts-regexp-both end t))
9004 (org-time-string-to-seconds (match-string 0))
9005 (org-float-time now))))
9006 ((= dcst ?c)
9007 (let ((end (save-excursion (outline-next-heading) (point))))
9008 (if (re-search-forward
9009 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
9010 end t)
9011 (org-time-string-to-seconds (match-string 0))
9012 (org-float-time now))))
9013 ((= dcst ?s)
9014 (let ((end (save-excursion (outline-next-heading) (point))))
9015 (if (re-search-forward org-scheduled-time-regexp end t)
9016 (org-time-string-to-seconds (match-string 1))
9017 (org-float-time now))))
9018 ((= dcst ?d)
9019 (let ((end (save-excursion (outline-next-heading) (point))))
9020 (if (re-search-forward org-deadline-time-regexp end t)
9021 (org-time-string-to-seconds (match-string 1))
9022 (org-float-time now))))
9023 ((= dcst ?p)
9024 (if (re-search-forward org-priority-regexp (point-at-eol) t)
9025 (string-to-char (match-string 2))
9026 org-default-priority))
9027 ((= dcst ?r)
9028 (or (org-entry-get nil property) ""))
9029 ((= dcst ?o)
9030 (when (looking-at org-complex-heading-regexp)
9031 (let* ((m (match-string 2))
9032 (s (if (member m org-done-keywords) '- '+)))
9033 (- 99 (funcall s (length (member m org-todo-keywords-1)))))))
9034 ((= dcst ?f)
9035 (if getkey-func
9036 (progn
9037 (setq tmp (funcall getkey-func))
9038 (when (stringp tmp) (setq tmp (funcall case-func tmp)))
9039 tmp)
9040 (error "Invalid key function `%s'" getkey-func)))
9041 (t (error "Invalid sorting type `%c'" sorting-type))))
9043 (cond
9044 ((= dcst ?a) 'string<)
9045 ((= dcst ?f) compare-func)
9046 ((member dcst '(?p ?t ?s ?d ?c ?k)) '<)))))
9047 (run-hooks 'org-after-sorting-entries-or-items-hook)
9048 ;; Reset the clock marker if needed
9049 (when cmstr
9050 (save-excursion
9051 (goto-char start)
9052 (search-forward cmstr nil t)
9053 (move-marker org-clock-marker (point))))
9054 (message "Sorting entries...done")))
9056 ;;; The orgstruct minor mode
9058 ;; Define a minor mode which can be used in other modes in order to
9059 ;; integrate the org-mode structure editing commands.
9061 ;; This is really a hack, because the org-mode structure commands use
9062 ;; keys which normally belong to the major mode. Here is how it
9063 ;; works: The minor mode defines all the keys necessary to operate the
9064 ;; structure commands, but wraps the commands into a function which
9065 ;; tests if the cursor is currently at a headline or a plain list
9066 ;; item. If that is the case, the structure command is used,
9067 ;; temporarily setting many Org-mode variables like regular
9068 ;; expressions for filling etc. However, when any of those keys is
9069 ;; used at a different location, function uses `key-binding' to look
9070 ;; up if the key has an associated command in another currently active
9071 ;; keymap (minor modes, major mode, global), and executes that
9072 ;; command. There might be problems if any of the keys is otherwise
9073 ;; used as a prefix key.
9075 (defcustom orgstruct-heading-prefix-regexp ""
9076 "Regexp that matches the custom prefix of Org headlines in
9077 orgstruct(++)-mode."
9078 :group 'org
9079 :version "24.4"
9080 :package-version '(Org . "8.3")
9081 :type 'regexp)
9082 ;;;###autoload(put 'orgstruct-heading-prefix-regexp 'safe-local-variable 'stringp)
9084 (defcustom orgstruct-setup-hook nil
9085 "Hook run after orgstruct-mode-map is filled."
9086 :group 'org
9087 :version "24.4"
9088 :package-version '(Org . "8.0")
9089 :type 'hook)
9091 (defvar orgstruct-initialized nil)
9093 (defvar org-local-vars nil
9094 "List of local variables, for use by `orgstruct-mode'.")
9096 ;;;###autoload
9097 (define-minor-mode orgstruct-mode
9098 "Toggle the minor mode `orgstruct-mode'.
9099 This mode is for using Org-mode structure commands in other
9100 modes. The following keys behave as if Org-mode were active, if
9101 the cursor is on a headline, or on a plain list item (both as
9102 defined by Org-mode)."
9103 nil " OrgStruct" (make-sparse-keymap)
9104 (funcall (if orgstruct-mode
9105 'add-to-invisibility-spec
9106 'remove-from-invisibility-spec)
9107 '(outline . t))
9108 (when orgstruct-mode
9109 (org-load-modules-maybe)
9110 (unless orgstruct-initialized
9111 (orgstruct-setup)
9112 (setq orgstruct-initialized t))))
9114 ;;;###autoload
9115 (defun turn-on-orgstruct ()
9116 "Unconditionally turn on `orgstruct-mode'."
9117 (orgstruct-mode 1))
9119 (defvar-local orgstruct-is-++ nil
9120 "Is `orgstruct-mode' in ++ version in the current-buffer?")
9121 (defvar-local org-fb-vars nil)
9122 (defun orgstruct++-mode (&optional arg)
9123 "Toggle `orgstruct-mode', the enhanced version of it.
9124 In addition to setting orgstruct-mode, this also exports all
9125 indentation and autofilling variables from org-mode into the
9126 buffer. It will also recognize item context in multiline items."
9127 (interactive "P")
9128 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
9129 (if (< arg 1)
9130 (progn (orgstruct-mode -1)
9131 (dolist (v org-fb-vars)
9132 (set (make-local-variable (car v))
9133 (if (eq (car-safe (cadr v)) 'quote)
9134 (cl-cadadr v)
9135 (nth 1 v)))))
9136 (orgstruct-mode 1)
9137 (setq org-fb-vars nil)
9138 (unless org-local-vars
9139 (setq org-local-vars (org-get-local-variables)))
9140 (let (var val)
9141 (dolist (x org-local-vars)
9142 (when (string-match
9143 "^\\(paragraph-\\|auto-fill\\|normal-auto-fill\\|fill-paragraph\
9144 \\|fill-prefix\\|indent-\\)"
9145 (symbol-name (car x)))
9146 (setq var (car x) val (nth 1 x))
9147 (push (list var `(quote ,(eval var))) org-fb-vars)
9148 (set (make-local-variable var)
9149 (if (eq (car-safe val) 'quote) (nth 1 val) val))))
9150 (setq-local orgstruct-is-++ t))))
9152 ;;;###autoload
9153 (defun turn-on-orgstruct++ ()
9154 "Unconditionally turn on `orgstruct++-mode'."
9155 (orgstruct++-mode 1))
9157 (defun orgstruct-error ()
9158 "Error when there is no default binding for a structure key."
9159 (interactive)
9160 (funcall (if (fboundp 'user-error)
9161 'user-error
9162 'error)
9163 "This key has no function outside structure elements"))
9165 (defun orgstruct-setup ()
9166 "Setup orgstruct keymap."
9167 (dolist (cell '((org-demote . t)
9168 (org-metaleft . t)
9169 (org-metaright . t)
9170 (org-promote . t)
9171 (org-shiftmetaleft . t)
9172 (org-shiftmetaright . t)
9173 org-backward-element
9174 org-backward-heading-same-level
9175 org-ctrl-c-ret
9176 org-ctrl-c-minus
9177 org-ctrl-c-star
9178 org-cycle
9179 org-force-cycle-archived
9180 org-forward-heading-same-level
9181 org-insert-heading
9182 org-insert-heading-respect-content
9183 org-kill-note-or-show-branches
9184 org-mark-subtree
9185 org-meta-return
9186 org-metadown
9187 org-metaup
9188 org-narrow-to-subtree
9189 org-promote-subtree
9190 org-reveal
9191 org-shiftdown
9192 org-shiftleft
9193 org-shiftmetadown
9194 org-shiftmetaup
9195 org-shiftright
9196 org-shifttab
9197 org-shifttab
9198 org-shiftup
9199 org-show-children
9200 org-show-subtree
9201 org-sort
9202 org-up-element
9203 outline-demote
9204 outline-next-visible-heading
9205 outline-previous-visible-heading
9206 outline-promote
9207 outline-up-heading))
9208 (let ((f (or (car-safe cell) cell))
9209 (disable-when-heading-prefix (cdr-safe cell)))
9210 (when (fboundp f)
9211 (let ((new-bindings))
9212 (dolist (binding (nconc (where-is-internal f org-mode-map)
9213 (where-is-internal f outline-mode-map)))
9214 (push binding new-bindings)
9215 ;; TODO use local-function-key-map
9216 (dolist (rep '(("<tab>" . "TAB")
9217 ("<return>" . "RET")
9218 ("<escape>" . "ESC")
9219 ("<delete>" . "DEL")))
9220 (setq binding (read-kbd-macro
9221 (let ((case-fold-search))
9222 (replace-regexp-in-string
9223 (regexp-quote (cdr rep))
9224 (car rep)
9225 (key-description binding)))))
9226 (cl-pushnew binding new-bindings :test 'equal)))
9227 (dolist (binding new-bindings)
9228 (let ((key (lookup-key orgstruct-mode-map binding)))
9229 (when (or (not key) (numberp key))
9230 (ignore-errors
9231 (org-defkey orgstruct-mode-map
9232 binding
9233 (orgstruct-make-binding
9234 f binding disable-when-heading-prefix))))))))))
9235 (run-hooks 'orgstruct-setup-hook))
9237 (defun orgstruct-make-binding (fun key disable-when-heading-prefix)
9238 "Create a function for binding in the structure minor mode.
9239 FUN is the command to call inside a table. KEY is the key that
9240 should be checked in for a command to execute outside of tables.
9241 Non-nil `disable-when-heading-prefix' means to disable the command
9242 if `orgstruct-heading-prefix-regexp' is not empty."
9243 (let ((name (concat "orgstruct-hijacker-" (symbol-name fun))))
9244 (let ((nname name)
9245 (i 0))
9246 (while (fboundp (intern nname))
9247 (setq nname (format "%s-%d" name (setq i (1+ i)))))
9248 (setq name (intern nname)))
9249 (eval
9250 (let ((bindings '((org-heading-regexp
9251 (concat "^"
9252 orgstruct-heading-prefix-regexp
9253 "\\(\\*+\\)\\(?: +\\(.*?\\)\\)?[ ]*$"))
9254 (org-outline-regexp
9255 (concat orgstruct-heading-prefix-regexp "\\*+ "))
9256 (org-outline-regexp-bol
9257 (concat "^" org-outline-regexp))
9258 (outline-regexp org-outline-regexp)
9259 (outline-heading-end-regexp "\n")
9260 (outline-level 'org-outline-level)
9261 (outline-heading-alist))))
9262 `(defun ,name (arg)
9263 ,(concat "In Structure, run `" (symbol-name fun) "'.\n"
9264 "Outside of structure, run the binding of `"
9265 (key-description key) "'."
9266 (when disable-when-heading-prefix
9267 (concat
9268 "\nIf `orgstruct-heading-prefix-regexp' is not empty, this command will always fall\n"
9269 "back to the default binding due to limitations of Org's implementation of\n"
9270 "`" (symbol-name fun) "'.")))
9271 (interactive "p")
9272 (let* ((disable
9273 ,(and disable-when-heading-prefix
9274 '(not (string= orgstruct-heading-prefix-regexp ""))))
9275 (fallback
9276 (or disable
9277 (not
9278 (let* ,bindings
9279 (org-context-p 'headline 'item
9280 ,(when (memq fun
9281 '(org-insert-heading
9282 org-insert-heading-respect-content
9283 org-meta-return))
9284 '(when orgstruct-is-++
9285 'item-body))))))))
9286 (if fallback
9287 (let* ((orgstruct-mode)
9288 (binding
9289 (let ((key ,key))
9290 (catch 'exit
9291 (dolist
9292 (rep
9293 '(nil
9294 ("<\\([^>]*\\)tab>" . "\\1TAB")
9295 ("<\\([^>]*\\)return>" . "\\1RET")
9296 ("<\\([^>]*\\)escape>" . "\\1ESC")
9297 ("<\\([^>]*\\)delete>" . "\\1DEL"))
9298 nil)
9299 (when rep
9300 (setq key (read-kbd-macro
9301 (let ((case-fold-search))
9302 (replace-regexp-in-string
9303 (car rep)
9304 (cdr rep)
9305 (key-description key))))))
9306 (when (key-binding key)
9307 (throw 'exit (key-binding key))))))))
9308 (if (keymapp binding)
9309 (org-set-transient-map binding)
9310 (let ((func (or binding
9311 (unless disable
9312 'orgstruct-error))))
9313 (when func
9314 (call-interactively func)))))
9315 (org-run-like-in-org-mode
9316 (lambda ()
9317 (interactive)
9318 (let* ,bindings
9319 (call-interactively ',fun)))))))))
9320 name))
9322 (defun org-contextualize-keys (alist contexts)
9323 "Return valid elements in ALIST depending on CONTEXTS.
9325 `org-agenda-custom-commands' or `org-capture-templates' are the
9326 values used for ALIST, and `org-agenda-custom-commands-contexts'
9327 or `org-capture-templates-contexts' are the associated contexts
9328 definitions."
9329 (let ((contexts
9330 ;; normalize contexts
9331 (mapcar
9332 (lambda(c) (cond ((listp (cadr c))
9333 (list (car c) (car c) (nth 1 c)))
9334 ((string= "" (cadr c))
9335 (list (car c) (car c) (nth 2 c)))
9336 (t c)))
9337 contexts))
9338 (a alist) r s)
9339 ;; loop over all commands or templates
9340 (dolist (c a)
9341 (let (vrules repl)
9342 (cond
9343 ((not (assoc (car c) contexts))
9344 (push c r))
9345 ((and (assoc (car c) contexts)
9346 (setq vrules (org-contextualize-validate-key
9347 (car c) contexts)))
9348 (mapc (lambda (vr)
9349 (unless (equal (car vr) (cadr vr))
9350 (setq repl vr)))
9351 vrules)
9352 (if (not repl) (push c r)
9353 (push (cadr repl) s)
9354 (push
9355 (cons (car c)
9356 (cdr (or (assoc (cadr repl) alist)
9357 (error "Undefined key `%s' as contextual replacement for `%s'"
9358 (cadr repl) (car c)))))
9359 r))))))
9360 ;; Return limited ALIST, possibly with keys modified, and deduplicated
9361 (delq
9363 (delete-dups
9364 (mapcar (lambda (x)
9365 (let ((tpl (car x)))
9366 (unless (delq
9368 (mapcar (lambda (y)
9369 (equal y tpl))
9371 x)))
9372 (reverse r))))))
9374 (defun org-contextualize-validate-key (key contexts)
9375 "Check CONTEXTS for agenda or capture KEY."
9376 (let (res)
9377 (dolist (r contexts)
9378 (dolist (rr (car (last r)))
9379 (when
9380 (and (equal key (car r))
9381 (if (functionp rr) (funcall rr)
9382 (or (and (eq (car rr) 'in-file)
9383 (buffer-file-name)
9384 (string-match (cdr rr) (buffer-file-name)))
9385 (and (eq (car rr) 'in-mode)
9386 (string-match (cdr rr) (symbol-name major-mode)))
9387 (and (eq (car rr) 'in-buffer)
9388 (string-match (cdr rr) (buffer-name)))
9389 (when (and (eq (car rr) 'not-in-file)
9390 (buffer-file-name))
9391 (not (string-match (cdr rr) (buffer-file-name))))
9392 (when (eq (car rr) 'not-in-mode)
9393 (not (string-match (cdr rr) (symbol-name major-mode))))
9394 (when (eq (car rr) 'not-in-buffer)
9395 (not (string-match (cdr rr) (buffer-name)))))))
9396 (push r res))))
9397 (delete-dups (delq nil res))))
9399 (defun org-context-p (&rest contexts)
9400 "Check if local context is any of CONTEXTS.
9401 Possible values in the list of contexts are `table', `headline', and `item'."
9402 (let ((pos (point)))
9403 (goto-char (point-at-bol))
9404 (prog1 (or (and (memq 'table contexts)
9405 (looking-at "[ \t]*|"))
9406 (and (memq 'headline contexts)
9407 (looking-at org-outline-regexp))
9408 (and (memq 'item contexts)
9409 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
9410 (and (memq 'item-body contexts)
9411 (org-in-item-p)))
9412 (goto-char pos))))
9414 (defconst org-unique-local-variables
9415 '(org-element--cache
9416 org-element--cache-objects
9417 org-element--cache-sync-keys
9418 org-element--cache-sync-requests
9419 org-element--cache-sync-timer)
9420 "List of local variables that cannot be transferred to another buffer.")
9422 (defun org-get-local-variables ()
9423 "Return a list of all local variables in an Org mode buffer."
9424 (delq nil
9425 (mapcar
9426 (lambda (x)
9427 (let* ((binding (if (symbolp x) (list x) (list (car x) (cdr x))))
9428 (name (car binding)))
9429 (and (not (get name 'org-state))
9430 (not (memq name org-unique-local-variables))
9431 (string-match-p
9432 "\\`\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|\
9433 auto-fill\\|normal-auto-fill\\|fill-paragraph\\|indent-\\)"
9434 (symbol-name name))
9435 binding)))
9436 (with-temp-buffer
9437 (org-mode)
9438 (buffer-local-variables)))))
9440 (defun org-clone-local-variables (from-buffer &optional regexp)
9441 "Clone local variables from FROM-BUFFER.
9442 Optional argument REGEXP selects variables to clone."
9443 (dolist (pair (buffer-local-variables from-buffer))
9444 (let ((name (car pair)))
9445 (when (and (symbolp name)
9446 (not (memq name org-unique-local-variables))
9447 (or (null regexp) (string-match regexp (symbol-name name))))
9448 (set (make-local-variable name) (cdr pair))))))
9450 ;;;###autoload
9451 (defun org-run-like-in-org-mode (cmd)
9452 "Run a command, pretending that the current buffer is in Org-mode.
9453 This will temporarily bind local variables that are typically bound in
9454 Org-mode to the values they have in Org-mode, and then interactively
9455 call CMD."
9456 (org-load-modules-maybe)
9457 (unless org-local-vars
9458 (setq org-local-vars (org-get-local-variables)))
9459 (let (binds)
9460 (dolist (var org-local-vars)
9461 (when (or (not (boundp (car var)))
9462 (eq (symbol-value (car var))
9463 (default-value (car var))))
9464 (push (list (car var) `(quote ,(cadr var))) binds)))
9465 (eval `(let ,binds
9466 (call-interactively (quote ,cmd))))))
9468 (defun org-get-category (&optional pos force-refresh)
9469 "Get the category applying to position POS."
9470 (save-match-data
9471 (when force-refresh (org-refresh-category-properties))
9472 (let ((pos (or pos (point))))
9473 (or (get-text-property pos 'org-category)
9474 (progn (org-refresh-category-properties)
9475 (get-text-property pos 'org-category))))))
9477 ;;; Refresh properties
9479 (defun org-refresh-properties (dprop tprop)
9480 "Refresh buffer text properties.
9481 DPROP is the drawer property and TPROP is either the
9482 corresponding text property to set, or an alist with each element
9483 being a text property (as a symbol) and a function to apply to
9484 the value of the drawer property."
9485 (let ((case-fold-search t)
9486 (inhibit-read-only t))
9487 (org-with-silent-modifications
9488 (save-excursion
9489 (save-restriction
9490 (widen)
9491 (goto-char (point-min))
9492 (while (re-search-forward (concat "^[ \t]*:" dprop ": +\\(.*\\)[ \t]*$") nil t)
9493 (org-refresh-property tprop (org-match-string-no-properties 1))))))))
9495 (defun org-refresh-property (tprop p)
9496 "Refresh the buffer text property TPROP from the drawer property P.
9497 The refresh happens only for the current tree (not subtree)."
9498 (unless (org-before-first-heading-p)
9499 (save-excursion
9500 (org-back-to-heading t)
9501 (if (symbolp tprop)
9502 ;; TPROP is a text property symbol
9503 (put-text-property
9504 (point) (or (outline-next-heading) (point-max)) tprop p)
9505 ;; TPROP is an alist with (properties . function) elements
9506 (dolist (al tprop)
9507 (save-excursion
9508 (put-text-property
9509 (line-beginning-position) (or (outline-next-heading) (point-max))
9510 (car al)
9511 (funcall (cdr al) p))))))))
9513 (defun org-refresh-category-properties ()
9514 "Refresh category text properties in the buffer."
9515 (let ((case-fold-search t)
9516 (inhibit-read-only t)
9517 (default-category
9518 (cond ((null org-category)
9519 (if buffer-file-name
9520 (file-name-sans-extension
9521 (file-name-nondirectory buffer-file-name))
9522 "???"))
9523 ((symbolp org-category) (symbol-name org-category))
9524 (t org-category))))
9525 (org-with-silent-modifications
9526 (org-with-wide-buffer
9527 ;; Set buffer-wide category. Search last #+CATEGORY keyword.
9528 ;; This is the default category for the buffer. If none is
9529 ;; found, fall-back to `org-category' or buffer file name.
9530 (put-text-property
9531 (point-min) (point-max)
9532 'org-category
9533 (catch 'buffer-category
9534 (goto-char (point-max))
9535 (while (re-search-backward "^[ \t]*#\\+CATEGORY:" (point-min) t)
9536 (let ((element (org-element-at-point)))
9537 (when (eq (org-element-type element) 'keyword)
9538 (throw 'buffer-category
9539 (org-element-property :value element)))))
9540 default-category))
9541 ;; Set sub-tree specific categories.
9542 (goto-char (point-min))
9543 (let ((regexp (org-re-property "CATEGORY")))
9544 (while (re-search-forward regexp nil t)
9545 (let ((value (org-match-string-no-properties 3)))
9546 (when (org-at-property-p)
9547 (put-text-property
9548 (save-excursion (org-back-to-heading t) (point))
9549 (save-excursion (org-end-of-subtree t t) (point))
9550 'org-category
9551 value)))))))))
9553 (defun org-refresh-stats-properties ()
9554 "Refresh stats text properties in the buffer."
9555 (let (stats)
9556 (org-with-silent-modifications
9557 (save-excursion
9558 (save-restriction
9559 (widen)
9560 (goto-char (point-min))
9561 (while (re-search-forward
9562 (concat org-outline-regexp-bol ".*"
9563 "\\(?:\\[\\([0-9]+\\)%\\|\\([0-9]+\\)/\\([0-9]+\\)\\]\\)")
9564 nil t)
9565 (setq stats (cond ((equal (match-string 3) "0") 0)
9566 ((match-string 2)
9567 (/ (* (string-to-number (match-string 2)) 100)
9568 (string-to-number (match-string 3))))
9569 (t (string-to-number (match-string 1)))))
9570 (org-back-to-heading t)
9571 (put-text-property (point) (progn (org-end-of-subtree t t) (point))
9572 'org-stats stats)))))))
9574 (defun org-refresh-effort-properties ()
9575 "Refresh effort properties"
9576 (org-refresh-properties
9577 org-effort-property
9578 '((effort . identity)
9579 (effort-minutes . org-duration-string-to-minutes))))
9581 ;;;; Link Stuff
9583 ;;; Link abbreviations
9585 (defun org-link-expand-abbrev (link)
9586 "Apply replacements as defined in `org-link-abbrev-alist'."
9587 (if (string-match "^\\([^:]*\\)\\(::?\\(.*\\)\\)?$" link)
9588 (let* ((key (match-string 1 link))
9589 (as (or (assoc key org-link-abbrev-alist-local)
9590 (assoc key org-link-abbrev-alist)))
9591 (tag (and (match-end 2) (match-string 3 link)))
9592 rpl)
9593 (if (not as)
9594 link
9595 (setq rpl (cdr as))
9596 (cond
9597 ((symbolp rpl) (funcall rpl tag))
9598 ((string-match "%(\\([^)]+\\))" rpl)
9599 (replace-match
9600 (save-match-data
9601 (funcall (intern-soft (match-string 1 rpl)) tag)) t t rpl))
9602 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
9603 ((string-match "%h" rpl)
9604 (replace-match (url-hexify-string (or tag "")) t t rpl))
9605 (t (concat rpl tag)))))
9606 link))
9608 ;;; Storing and inserting links
9610 (defvar org-insert-link-history nil
9611 "Minibuffer history for links inserted with `org-insert-link'.")
9613 (defvar org-stored-links nil
9614 "Contains the links stored with `org-store-link'.")
9616 (defvar org-store-link-plist nil
9617 "Plist with info about the most recently link created with `org-store-link'.")
9619 (defvar org-link-protocols nil
9620 "Link protocols added to Org-mode using `org-add-link-type'.")
9622 (defvar org-store-link-functions nil
9623 "List of functions that are called to create and store a link.
9624 Each function will be called in turn until one returns a non-nil
9625 value. Each function should check if it is responsible for creating
9626 this link (for example by looking at the major mode).
9627 If not, it must exit and return nil.
9628 If yes, it should return a non-nil value after a calling
9629 `org-store-link-props' with a list of properties and values.
9630 Special properties are:
9632 :type The link prefix, like \"http\". This must be given.
9633 :link The link, like \"http://www.astro.uva.nl/~dominik\".
9634 This is obligatory as well.
9635 :description Optional default description for the second pair
9636 of brackets in an Org-mode link. The user can still change
9637 this when inserting this link into an Org-mode buffer.
9639 In addition to these, any additional properties can be specified
9640 and then used in capture templates.")
9642 (defun org-add-link-type (type &optional follow export)
9643 "Add TYPE to the list of `org-link-types'.
9644 Re-compute all regular expressions depending on `org-link-types'
9646 FOLLOW and EXPORT are two functions.
9648 FOLLOW should take the link path as the single argument and do whatever
9649 is necessary to follow the link, for example find a file or display
9650 a mail message.
9652 EXPORT should format the link path for export to one of the export formats.
9653 It should be a function accepting three arguments:
9655 path the path of the link, the text after the prefix (like \"http:\")
9656 desc the description of the link, if any
9657 format the export format, a symbol like `html' or `latex' or `ascii'.
9659 The function may use the FORMAT information to return different values
9660 depending on the format. The return value will be put literally into
9661 the exported file. If the return value is nil, this means Org should
9662 do what it normally does with links which do not have EXPORT defined.
9664 Org mode has a built-in default for exporting links. If you are happy with
9665 this default, there is no need to define an export function for the link
9666 type. For a simple example of an export function, see `org-bbdb.el'."
9667 (add-to-list 'org-link-types type t)
9668 (org-make-link-regexps)
9669 (org-element-update-syntax)
9670 (if (assoc type org-link-protocols)
9671 (setcdr (assoc type org-link-protocols) (list follow export))
9672 (push (list type follow export) org-link-protocols)))
9674 (defvar org-agenda-buffer-name) ; Defined in org-agenda.el
9675 (defvar org-id-link-to-org-use-id) ; Defined in org-id.el
9677 ;;;###autoload
9678 (defun org-store-link (arg)
9679 "\\<org-mode-map>Store an org-link to the current location.
9680 This link is added to `org-stored-links' and can later be inserted
9681 into an Org buffer with \\[org-insert-link].
9683 For some link types, a prefix ARG is interpreted.
9684 For links to Usenet articles, ARG negates `org-gnus-prefer-web-links'.
9685 For file links, ARG negates `org-context-in-file-links'.
9687 A double prefix ARG force skipping storing functions that are not
9688 part of Org's core.
9690 A triple prefix ARG force storing a link for each line in the
9691 active region."
9692 (interactive "P")
9693 (org-load-modules-maybe)
9694 (if (and (equal arg '(64)) (org-region-active-p))
9695 (save-excursion
9696 (let ((end (region-end)))
9697 (goto-char (region-beginning))
9698 (set-mark (point))
9699 (while (< (point-at-eol) end)
9700 (move-end-of-line 1) (activate-mark)
9701 (let (current-prefix-arg)
9702 (call-interactively 'org-store-link))
9703 (move-beginning-of-line 2)
9704 (set-mark (point)))))
9705 (org-with-limited-levels
9706 (setq org-store-link-plist nil)
9707 (let (link cpltxt desc description search
9708 txt custom-id agenda-link sfuns sfunsn)
9709 (cond
9711 ;; Store a link using an external link type
9712 ((and (not (equal arg '(16)))
9713 (setq sfuns
9714 (delq
9715 nil (mapcar (lambda (f)
9716 (let (fs) (if (funcall f) (push f fs))))
9717 org-store-link-functions))
9718 sfunsn (mapcar (lambda (fu) (symbol-name (car fu))) sfuns))
9719 (or (and (cdr sfuns)
9720 (funcall (intern
9721 (completing-read
9722 "Which function for creating the link? "
9723 sfunsn nil t (car sfunsn)))))
9724 (funcall (caar sfuns)))
9725 (setq link (plist-get org-store-link-plist :link)
9726 desc (or (plist-get org-store-link-plist
9727 :description)
9728 link))))
9730 ;; Store a link from a source code buffer.
9731 ((org-src-edit-buffer-p)
9732 (cond
9733 ((save-excursion
9734 (beginning-of-line)
9735 (looking-at (concat (format org-coderef-label-format "\\(.*?\\)")
9736 "[ \t]*$")))
9737 (setq link (format "(%s)" (org-match-string-no-properties 1))))
9738 ((org-called-interactively-p 'any)
9739 (let (label)
9740 (while (or (not label)
9741 (org-with-wide-buffer
9742 (goto-char (point-min))
9743 (re-search-forward
9744 (regexp-quote (format org-coderef-label-format label))
9745 nil t)))
9746 (when label (message "Label exists already") (sit-for 2))
9747 (setq label (read-string "Code line label: " label)))
9748 (end-of-line)
9749 (setq link (format org-coderef-label-format label))
9750 (let ((gc (- 79 (length link))))
9751 (if (< (current-column) gc) (org-move-to-column gc t)
9752 (insert " ")))
9753 (insert link)
9754 (setq link (concat "(" label ")") desc nil)))
9755 (t (setq link nil))))
9757 ;; We are in the agenda, link to referenced location
9758 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
9759 (let ((m (or (get-text-property (point) 'org-hd-marker)
9760 (get-text-property (point) 'org-marker))))
9761 (when m
9762 (org-with-point-at m
9763 (setq agenda-link
9764 (if (org-called-interactively-p 'any)
9765 (call-interactively 'org-store-link)
9766 (org-store-link nil)))))))
9768 ((eq major-mode 'calendar-mode)
9769 (let ((cd (calendar-cursor-to-date)))
9770 (setq link
9771 (format-time-string
9772 (car org-time-stamp-formats)
9773 (apply 'encode-time
9774 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9775 nil nil nil))))
9776 (org-store-link-props :type "calendar" :date cd)))
9778 ((eq major-mode 'help-mode)
9779 (setq link (concat "help:" (save-excursion
9780 (goto-char (point-min))
9781 (looking-at "^[^ ]+")
9782 (match-string 0))))
9783 (org-store-link-props :type "help"))
9785 ((eq major-mode 'w3-mode)
9786 (setq cpltxt (if (and (buffer-name)
9787 (not (string-match "Untitled" (buffer-name))))
9788 (buffer-name)
9789 (url-view-url t))
9790 link (url-view-url t))
9791 (org-store-link-props :type "w3" :url (url-view-url t)))
9793 ((eq major-mode 'image-mode)
9794 (setq cpltxt (concat "file:"
9795 (abbreviate-file-name buffer-file-name))
9796 link cpltxt)
9797 (org-store-link-props :type "image" :file buffer-file-name))
9799 ;; In dired, store a link to the file of the current line
9800 ((derived-mode-p 'dired-mode)
9801 (let ((file (dired-get-filename nil t)))
9802 (setq file (if file
9803 (abbreviate-file-name
9804 (expand-file-name (dired-get-filename nil t)))
9805 ;; otherwise, no file so use current directory.
9806 default-directory))
9807 (setq cpltxt (concat "file:" file)
9808 link cpltxt)))
9810 ((setq search (run-hook-with-args-until-success
9811 'org-create-file-search-functions))
9812 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9813 "::" search))
9814 (setq cpltxt (or description link)))
9816 ((and (buffer-file-name (buffer-base-buffer)) (derived-mode-p 'org-mode))
9817 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
9818 (cond
9819 ;; Store a link using the target at point
9820 ((org-in-regexp "[^<]<<\\([^<>]+\\)>>[^>]" 1)
9821 (setq cpltxt
9822 (concat "file:"
9823 (abbreviate-file-name
9824 (buffer-file-name (buffer-base-buffer)))
9825 "::" (match-string 1))
9826 link cpltxt))
9827 ((and (featurep 'org-id)
9828 (or (eq org-id-link-to-org-use-id t)
9829 (and (org-called-interactively-p 'any)
9830 (or (eq org-id-link-to-org-use-id 'create-if-interactive)
9831 (and (eq org-id-link-to-org-use-id
9832 'create-if-interactive-and-no-custom-id)
9833 (not custom-id))))
9834 (and org-id-link-to-org-use-id (org-entry-get nil "ID"))))
9835 ;; Store a link using the ID at point
9836 (setq link (condition-case nil
9837 (prog1 (org-id-store-link)
9838 (setq desc (or (plist-get org-store-link-plist
9839 :description)
9840 "")))
9841 (error
9842 ;; Probably before first headline, link only to file
9843 (concat "file:"
9844 (abbreviate-file-name
9845 (buffer-file-name (buffer-base-buffer))))))))
9847 ;; Just link to current headline
9848 (setq cpltxt (concat "file:"
9849 (abbreviate-file-name
9850 (buffer-file-name (buffer-base-buffer)))))
9851 ;; Add a context search string
9852 (when (org-xor org-context-in-file-links arg)
9853 (let* ((element (org-element-at-point))
9854 (name (org-element-property :name element)))
9855 (setq txt (cond
9856 ((org-at-heading-p) nil)
9857 (name)
9858 ((org-region-active-p)
9859 (buffer-substring (region-beginning) (region-end)))))
9860 (when (or (null txt) (string-match "\\S-" txt))
9861 (setq cpltxt
9862 (concat cpltxt "::"
9863 (condition-case nil
9864 (org-make-org-heading-search-string txt)
9865 (error "")))
9866 desc (or name
9867 (nth 4 (ignore-errors (org-heading-components)))
9868 "NONE")))))
9869 (when (string-match "::\\'" cpltxt)
9870 (setq cpltxt (substring cpltxt 0 -2)))
9871 (setq link cpltxt))))
9873 ((buffer-file-name (buffer-base-buffer))
9874 ;; Just link to this file here.
9875 (setq cpltxt (concat "file:"
9876 (abbreviate-file-name
9877 (buffer-file-name (buffer-base-buffer)))))
9878 ;; Add a context string.
9879 (when (org-xor org-context-in-file-links arg)
9880 (setq txt (if (org-region-active-p)
9881 (buffer-substring (region-beginning) (region-end))
9882 (buffer-substring (point-at-bol) (point-at-eol))))
9883 ;; Only use search option if there is some text.
9884 (when (string-match "\\S-" txt)
9885 (setq cpltxt
9886 (concat cpltxt "::" (org-make-org-heading-search-string txt))
9887 desc "NONE")))
9888 (setq link cpltxt))
9890 ((org-called-interactively-p 'interactive)
9891 (user-error "No method for storing a link from this buffer"))
9893 (t (setq link nil)))
9895 ;; We're done setting link and desc, clean up
9896 (when (consp link) (setq cpltxt (car link) link (cdr link)))
9897 (setq link (or link cpltxt)
9898 desc (or desc cpltxt))
9899 (cond ((not desc))
9900 ((equal desc "NONE") (setq desc nil))
9901 (t (setq desc
9902 (replace-regexp-in-string
9903 org-bracket-link-analytic-regexp
9904 (lambda (m) (or (match-string 5 m) (match-string 3 m)))
9905 desc))))
9906 ;; Return the link
9907 (if (not (and (or (org-called-interactively-p 'any)
9908 executing-kbd-macro)
9909 link))
9910 (or agenda-link (and link (org-make-link-string link desc)))
9911 (push (list link desc) org-stored-links)
9912 (message "Stored: %s" (or desc link))
9913 (when custom-id
9914 (setq link (concat "file:" (abbreviate-file-name
9915 (buffer-file-name)) "::#" custom-id))
9916 (push (list link desc) org-stored-links))
9917 (car org-stored-links))))))
9919 (defun org-store-link-props (&rest plist)
9920 "Store link properties, extract names, addresses and dates."
9921 (let ((x (plist-get plist :from)))
9922 (when x
9923 (let ((adr (mail-extract-address-components x)))
9924 (setq plist (plist-put plist :fromname (car adr)))
9925 (setq plist (plist-put plist :fromaddress (nth 1 adr))))))
9926 (let ((x (plist-get plist :to)))
9927 (when x
9928 (let ((adr (mail-extract-address-components x)))
9929 (setq plist (plist-put plist :toname (car adr)))
9930 (setq plist (plist-put plist :toaddress (nth 1 adr))))))
9931 (let ((x (ignore-errors (date-to-time (plist-get plist :date)))))
9932 (when x
9933 (setq plist (plist-put plist :date-timestamp
9934 (format-time-string
9935 (org-time-stamp-format t) x)))
9936 (setq plist (plist-put plist :date-timestamp-inactive
9937 (format-time-string
9938 (org-time-stamp-format t t) x)))))
9939 (let ((from (plist-get plist :from))
9940 (to (plist-get plist :to)))
9941 (when (and from to org-from-is-user-regexp)
9942 (setq plist
9943 (plist-put plist :fromto
9944 (if (string-match org-from-is-user-regexp from)
9945 (concat "to %t")
9946 (concat "from %f"))))))
9947 (setq org-store-link-plist plist))
9949 (defun org-add-link-props (&rest plist)
9950 "Add these properties to the link property list."
9951 (let (key value)
9952 (while plist
9953 (setq key (pop plist) value (pop plist))
9954 (setq org-store-link-plist
9955 (plist-put org-store-link-plist key value)))))
9957 (defun org-email-link-description (&optional fmt)
9958 "Return the description part of an email link.
9959 This takes information from `org-store-link-plist' and formats it
9960 according to FMT (default from `org-email-link-description-format')."
9961 (setq fmt (or fmt org-email-link-description-format))
9962 (let* ((p org-store-link-plist)
9963 (to (plist-get p :toaddress))
9964 (from (plist-get p :fromaddress))
9965 (table
9966 (list
9967 (cons "%c" (plist-get p :fromto))
9968 (cons "%F" (plist-get p :from))
9969 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
9970 (cons "%T" (plist-get p :to))
9971 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
9972 (cons "%s" (plist-get p :subject))
9973 (cons "%d" (plist-get p :date))
9974 (cons "%m" (plist-get p :message-id)))))
9975 (when (string-match "%c" fmt)
9976 ;; Check if the user wrote this message
9977 (if (and org-from-is-user-regexp from to
9978 (save-match-data (string-match org-from-is-user-regexp from)))
9979 (setq fmt (replace-match "to %t" t t fmt))
9980 (setq fmt (replace-match "from %f" t t fmt))))
9981 (org-replace-escapes fmt table)))
9983 (defun org-make-org-heading-search-string (&optional string)
9984 "Make search string for the current headline or STRING."
9985 (let ((s (or string
9986 (and (derived-mode-p 'org-mode)
9987 (save-excursion
9988 (org-back-to-heading t)
9989 (org-element-property :raw-value (org-element-at-point))))))
9990 (lines org-context-in-file-links))
9991 (or string (setq s (concat "*" s))) ; Add * for headlines
9992 (setq s (replace-regexp-in-string "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" "" s))
9993 (when (and string (integerp lines) (> lines 0))
9994 (let ((slines (org-split-string s "\n")))
9995 (when (< lines (length slines))
9996 (setq s (mapconcat
9997 'identity
9998 (reverse (nthcdr (- (length slines) lines)
9999 (reverse slines))) "\n")))))
10000 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10002 (defun org-make-link-string (link &optional description)
10003 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10004 (unless (org-string-nw-p link) (error "Empty link"))
10005 (let ((uri (cond ((string-match org-link-types-re link)
10006 (concat (match-string 1 link)
10007 (org-link-escape (substring link (match-end 1)))))
10008 ;; For readability, url-encode internal links only
10009 ;; when absolutely needed (i.e, when they contain
10010 ;; square brackets). File links however, are
10011 ;; encoded since, e.g., spaces are significant.
10012 ((or (file-name-absolute-p link)
10013 (org-string-match-p "\\`\\.\\.?/\\|[][]" link))
10014 (org-link-escape link))
10015 (t link)))
10016 (description
10017 (and (org-string-nw-p description)
10018 ;; Remove brackets from description, as they are fatal.
10019 (replace-regexp-in-string
10020 "[][]" (lambda (m) (if (equal "[" m) "{" "}"))
10021 (org-trim description)))))
10022 (format "[[%s]%s]"
10024 (if description (format "[%s]" description) ""))))
10026 (defconst org-link-escape-chars
10027 ;;%20 %5B %5D %25
10028 '(?\s ?\[ ?\] ?%)
10029 "List of characters that should be escaped in a link when stored to Org.
10030 This is the list that is used for internal purposes.")
10032 (defconst org-link-escape-chars-browser
10033 ;;%20 %22
10034 '(?\s ?\")
10035 "List of characters to be escaped before handing over to the browser.
10036 If you consider using this constant then you probably want to use
10037 the function `org-link-escape-browser' instead. See there why
10038 this constant is a candidate to be removed once Org drops support
10039 for Emacs 24.1 and 24.2.")
10041 (defun org-link-escape (text &optional table merge)
10042 "Return percent escaped representation of TEXT.
10043 TEXT is a string with the text to escape.
10044 Optional argument TABLE is a list with characters that should be
10045 escaped. When nil, `org-link-escape-chars' is used.
10046 If optional argument MERGE is set, merge TABLE into
10047 `org-link-escape-chars'."
10048 (let ((characters-to-encode
10049 (cond ((null table) org-link-escape-chars)
10050 (merge (append org-link-escape-chars table))
10051 (t table))))
10052 (mapconcat
10053 (lambda (c)
10054 (if (or (memq c characters-to-encode)
10055 (and org-url-hexify-p (or (< c 32) (> c 126))))
10056 (mapconcat (lambda (e) (format "%%%.2X" e))
10057 (or (encode-coding-char c 'utf-8)
10058 (error "Unable to percent escape character: %c" c))
10060 (char-to-string c)))
10061 text "")))
10063 (defun org-link-escape-browser (text)
10064 "Escape some characters before handing over to the browser.
10065 This function is a candidate to be removed together with the
10066 constant `org-link-escape-chars-browser' once Org drops support
10067 for Emacs 24.1 and 24.2. All calls to this function will have to
10068 be replaced with `url-encode-url' which is available since Emacs
10069 24.3.1."
10070 ;; Example with the Org link
10071 ;; [[http://lists.gnu.org/archive/cgi-bin/namazu.cgi?idxname=emacs-orgmode&query=%252Bsubject:"Release+8.2"]]
10072 ;; to open the browser with +subject:"Release 8.2" filled into the
10073 ;; query field: In this case the variable TEXT contains the
10074 ;; unescaped [...]=%2Bsubject:"Release+8.2". Then `url-encode-url'
10075 ;; converts correctly to [...]=%2Bsubject:%22Release+8.2%22 or
10076 ;; `org-link-escape' with `org-link-escape-chars-browser' converts
10077 ;; wrongly to [...]=%252Bsubject:%22Release+8.2%22.
10078 (if (fboundp 'url-encode-url)
10079 (url-encode-url text)
10080 (if (org-string-match-p
10081 (concat "[[:nonascii:]" org-link-escape-chars-browser "]")
10082 text)
10083 (org-link-escape text org-link-escape-chars-browser)
10084 text)))
10086 (defun org-link-unescape (str)
10087 "Unhex hexified Unicode parts in string STR.
10088 E.g. `%C3%B6' becomes the german o-Umlaut. This is the
10089 reciprocal of `org-link-escape', which see."
10090 (if (org-string-nw-p str)
10091 (replace-regexp-in-string
10092 "\\(%[0-9A-Za-z]\\{2\\}\\)+" #'org-link-unescape-compound str t t)
10093 str))
10095 (defun org-link-unescape-compound (hex)
10096 "Unhexify Unicode hex-chars. E.g. `%C3%B6' is the German o-Umlaut.
10097 Note: this function also decodes single byte encodings like
10098 `%E1' (a-acute) if not followed by another `%[A-F0-9]{2}' group."
10099 (save-match-data
10100 (let* ((bytes (cdr (split-string hex "%")))
10101 (ret "")
10102 (eat 0)
10103 (sum 0))
10104 (while bytes
10105 (let* ((val (string-to-number (pop bytes) 16))
10106 (shift-xor
10107 (if (= 0 eat)
10108 (cond
10109 ((>= val 252) (cons 6 252))
10110 ((>= val 248) (cons 5 248))
10111 ((>= val 240) (cons 4 240))
10112 ((>= val 224) (cons 3 224))
10113 ((>= val 192) (cons 2 192))
10114 (t (cons 0 0)))
10115 (cons 6 128))))
10116 (when (>= val 192) (setq eat (car shift-xor)))
10117 (setq val (logxor val (cdr shift-xor)))
10118 (setq sum (+ (lsh sum (car shift-xor)) val))
10119 (when (> eat 0) (setq eat (- eat 1)))
10120 (cond
10121 ((= 0 eat) ;multi byte
10122 (setq ret (concat ret (org-char-to-string sum)))
10123 (setq sum 0))
10124 ((not bytes) ; single byte(s)
10125 (setq ret (org-link-unescape-single-byte-sequence hex))))))
10126 ret)))
10128 (defun org-link-unescape-single-byte-sequence (hex)
10129 "Unhexify hex-encoded single byte character sequences."
10130 (mapconcat (lambda (byte)
10131 (char-to-string (string-to-number byte 16)))
10132 (cdr (split-string hex "%")) ""))
10134 (defun org-xor (a b)
10135 "Exclusive or."
10136 (if a (not b) b))
10138 (defun org-fixup-message-id-for-http (s)
10139 "Replace special characters in a message id, so it can be used in an http query."
10140 (when (string-match "%" s)
10141 (setq s (mapconcat (lambda (c)
10142 (if (eq c ?%)
10143 "%25"
10144 (char-to-string c)))
10145 s "")))
10146 (while (string-match "<" s)
10147 (setq s (replace-match "%3C" t t s)))
10148 (while (string-match ">" s)
10149 (setq s (replace-match "%3E" t t s)))
10150 (while (string-match "@" s)
10151 (setq s (replace-match "%40" t t s)))
10154 (defun org-link-prettify (link)
10155 "Return a human-readable representation of LINK.
10156 The car of LINK must be a raw link.
10157 The cdr of LINK must be either a link description or nil."
10158 (let ((desc (or (cadr link) "<no description>")))
10159 (concat (format "%-45s" (substring desc 0 (min (length desc) 40)))
10160 "<" (car link) ">")))
10162 ;;;###autoload
10163 (defun org-insert-link-global ()
10164 "Insert a link like Org-mode does.
10165 This command can be called in any mode to insert a link in Org-mode syntax."
10166 (interactive)
10167 (org-load-modules-maybe)
10168 (org-run-like-in-org-mode 'org-insert-link))
10170 (defun org-insert-all-links (arg &optional pre post)
10171 "Insert all links in `org-stored-links'.
10172 When a universal prefix, do not delete the links from `org-stored-links'.
10173 When `ARG' is a number, insert the last N link(s).
10174 `PRE' and `POST' are optional arguments to define a string to
10175 prepend or to append."
10176 (interactive "P")
10177 (let ((org-keep-stored-link-after-insertion (equal arg '(4)))
10178 (links (copy-sequence org-stored-links))
10179 (pr (or pre "- "))
10180 (po (or post "\n"))
10181 (cnt 1) l)
10182 (if (null org-stored-links)
10183 (message "No link to insert")
10184 (while (and (or (listp arg) (>= arg cnt))
10185 (setq l (if (listp arg)
10186 (pop links)
10187 (pop org-stored-links))))
10188 (setq cnt (1+ cnt))
10189 (insert pr)
10190 (org-insert-link nil (car l) (or (cadr l) "<no description>"))
10191 (insert po)))))
10193 (defun org-insert-last-stored-link (arg)
10194 "Insert the last link stored in `org-stored-links'."
10195 (interactive "p")
10196 (org-insert-all-links arg "" "\n"))
10198 (defun org-link-fontify-links-to-this-file ()
10199 "Fontify links to the current file in `org-stored-links'."
10200 (let ((f (buffer-file-name)) a b)
10201 (setq a (mapcar (lambda(l)
10202 (let ((ll (car l)))
10203 (when (and (string-match "^file:\\(.+\\)::" ll)
10204 (equal f (expand-file-name (match-string 1 ll))))
10205 ll)))
10206 org-stored-links))
10207 (when (featurep 'org-id)
10208 (setq b (mapcar (lambda(l)
10209 (let ((ll (car l)))
10210 (when (and (string-match "^id:\\(.+\\)$" ll)
10211 (equal f (expand-file-name
10212 (or (org-id-find-id-file
10213 (match-string 1 ll)) ""))))
10214 ll)))
10215 org-stored-links)))
10216 (mapcar (lambda(l)
10217 (put-text-property 0 (length l) 'face 'font-lock-comment-face l))
10218 (delq nil (append a b)))))
10220 (defvar org--links-history nil)
10221 (defun org-insert-link (&optional complete-file link-location default-description)
10222 "Insert a link. At the prompt, enter the link.
10224 Completion can be used to insert any of the link protocol prefixes like
10225 http or ftp in use.
10227 The history can be used to select a link previously stored with
10228 `org-store-link'. When the empty string is entered (i.e. if you just
10229 press RET at the prompt), the link defaults to the most recently
10230 stored link. As SPC triggers completion in the minibuffer, you need to
10231 use M-SPC or C-q SPC to force the insertion of a space character.
10233 You will also be prompted for a description, and if one is given, it will
10234 be displayed in the buffer instead of the link.
10236 If there is already a link at point, this command will allow you to edit link
10237 and description parts.
10239 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
10240 be selected using completion. The path to the file will be relative to the
10241 current directory if the file is in the current directory or a subdirectory.
10242 Otherwise, the link will be the absolute path as completed in the minibuffer
10243 \(i.e. normally ~/path/to/file). You can configure this behavior using the
10244 option `org-link-file-path-type'.
10246 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
10247 the current directory or below.
10249 With three \\[universal-argument] prefixes, negate the meaning of
10250 `org-keep-stored-link-after-insertion'.
10252 If `org-make-link-description-function' is non-nil, this function will be
10253 called with the link target, and the result will be the default
10254 link description.
10256 If the LINK-LOCATION parameter is non-nil, this value will be
10257 used as the link location instead of reading one interactively.
10259 If the DEFAULT-DESCRIPTION parameter is non-nil, this value will
10260 be used as the default description."
10261 (interactive "P")
10262 (let* ((wcf (current-window-configuration))
10263 (origbuf (current-buffer))
10264 (region (when (org-region-active-p)
10265 (buffer-substring (region-beginning) (region-end))))
10266 (remove (and region (list (region-beginning) (region-end))))
10267 (desc region)
10268 (link link-location)
10269 (abbrevs org-link-abbrev-alist-local)
10270 entry all-prefixes auto-desc)
10271 (cond
10272 (link-location) ; specified by arg, just use it.
10273 ((org-in-regexp org-bracket-link-regexp 1)
10274 ;; We do have a link at point, and we are going to edit it.
10275 (setq remove (list (match-beginning 0) (match-end 0)))
10276 (setq desc (when (match-end 3) (org-match-string-no-properties 3)))
10277 (setq link (read-string "Link: "
10278 (org-link-unescape
10279 (org-match-string-no-properties 1)))))
10280 ((or (org-in-regexp org-angle-link-re)
10281 (org-in-regexp org-plain-link-re))
10282 ;; Convert to bracket link
10283 (setq remove (list (match-beginning 0) (match-end 0))
10284 link (read-string "Link: "
10285 (org-remove-angle-brackets (match-string 0)))))
10286 ((member complete-file '((4) (16)))
10287 ;; Completing read for file names.
10288 (setq link (org-file-complete-link complete-file)))
10290 ;; Read link, with completion for stored links.
10291 (org-link-fontify-links-to-this-file)
10292 (org-switch-to-buffer-other-window "*Org Links*")
10293 (with-current-buffer "*Org Links*"
10294 (erase-buffer)
10295 (insert "Insert a link.
10296 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
10297 (when org-stored-links
10298 (insert "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
10299 (insert (mapconcat 'org-link-prettify
10300 (reverse org-stored-links) "\n")))
10301 (goto-char (point-min)))
10302 (let ((cw (selected-window)))
10303 (select-window (get-buffer-window "*Org Links*" 'visible))
10304 (with-current-buffer "*Org Links*" (setq truncate-lines t))
10305 (unless (pos-visible-in-window-p (point-max))
10306 (org-fit-window-to-buffer))
10307 (and (window-live-p cw) (select-window cw)))
10308 (setq all-prefixes (append (mapcar 'car abbrevs)
10309 (mapcar 'car org-link-abbrev-alist)
10310 org-link-types))
10311 (unwind-protect
10312 ;; Fake a link history, containing the stored links.
10313 (let ((org--links-history
10314 (append (mapcar #'car org-stored-links)
10315 org-insert-link-history)))
10316 (setq link
10317 (org-completing-read
10318 "Link: "
10319 (append
10320 (mapcar (lambda (x) (concat x ":")) all-prefixes)
10321 (mapcar #'car org-stored-links))
10322 nil nil nil
10323 'org--links-history
10324 (caar org-stored-links)))
10325 (unless (org-string-nw-p link) (user-error "No link selected"))
10326 (dolist (l org-stored-links)
10327 (when (equal link (cadr l))
10328 (setq link (car l))
10329 (setq auto-desc t)))
10330 (when (or (member link all-prefixes)
10331 (and (equal ":" (substring link -1))
10332 (member (substring link 0 -1) all-prefixes)
10333 (setq link (substring link 0 -1))))
10334 (setq link (with-current-buffer origbuf
10335 (org-link-try-special-completion link)))))
10336 (set-window-configuration wcf)
10337 (kill-buffer "*Org Links*"))
10338 (setq entry (assoc link org-stored-links))
10339 (or entry (push link org-insert-link-history))
10340 (setq desc (or desc (nth 1 entry)))))
10342 (when (funcall (if (equal complete-file '(64)) 'not 'identity)
10343 (not org-keep-stored-link-after-insertion))
10344 (setq org-stored-links (delq (assoc link org-stored-links)
10345 org-stored-links)))
10347 (when (and (string-match org-plain-link-re link)
10348 (not (string-match org-ts-regexp link)))
10349 ;; URL-like link, normalize the use of angular brackets.
10350 (setq link (org-remove-angle-brackets link)))
10352 ;; Check if we are linking to the current file with a search
10353 ;; option If yes, simplify the link by using only the search
10354 ;; option.
10355 (when (and buffer-file-name
10356 (string-match "^file:\\(.+?\\)::\\(.+\\)" link))
10357 (let* ((path (match-string 1 link))
10358 (case-fold-search nil)
10359 (search (match-string 2 link)))
10360 (save-match-data
10361 (when (equal (file-truename buffer-file-name) (file-truename path))
10362 ;; We are linking to this same file, with a search option
10363 (setq link search)))))
10365 ;; Check if we can/should use a relative path. If yes, simplify the link
10366 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
10367 (let* ((type (match-string 1 link))
10368 (path (match-string 2 link))
10369 (origpath path)
10370 (case-fold-search nil))
10371 (cond
10372 ((or (eq org-link-file-path-type 'absolute)
10373 (equal complete-file '(16)))
10374 (setq path (abbreviate-file-name (expand-file-name path))))
10375 ((eq org-link-file-path-type 'noabbrev)
10376 (setq path (expand-file-name path)))
10377 ((eq org-link-file-path-type 'relative)
10378 (setq path (file-relative-name path)))
10380 (save-match-data
10381 (if (string-match (concat "^" (regexp-quote
10382 (expand-file-name
10383 (file-name-as-directory
10384 default-directory))))
10385 (expand-file-name path))
10386 ;; We are linking a file with relative path name.
10387 (setq path (substring (expand-file-name path)
10388 (match-end 0)))
10389 (setq path (abbreviate-file-name (expand-file-name path)))))))
10390 (setq link (concat type path))
10391 (when (equal desc origpath)
10392 (setq desc path))))
10394 (if org-make-link-description-function
10395 (setq desc
10396 (or (condition-case nil
10397 (funcall org-make-link-description-function link desc)
10398 (error (progn (message "Can't get link description from `%s'"
10399 (symbol-name org-make-link-description-function))
10400 (sit-for 2) nil)))
10401 (read-string "Description: " default-description)))
10402 (if default-description (setq desc default-description)
10403 (setq desc (or (and auto-desc desc)
10404 (read-string "Description: " desc)))))
10406 (unless (string-match "\\S-" desc) (setq desc nil))
10407 (when remove (apply 'delete-region remove))
10408 (insert (org-make-link-string link desc))
10409 ;; Redisplay so as the new link has proper invisible characters.
10410 (sit-for 0)))
10412 (defun org-link-try-special-completion (type)
10413 "If there is completion support for link type TYPE, offer it."
10414 (let ((fun (intern (concat "org-" type "-complete-link"))))
10415 (if (functionp fun)
10416 (funcall fun)
10417 (read-string "Link (no completion support): " (concat type ":")))))
10419 (defun org-file-complete-link (&optional arg)
10420 "Create a file link using completion."
10421 (let ((file (read-file-name "File: "))
10422 (pwd (file-name-as-directory (expand-file-name ".")))
10423 (pwd1 (file-name-as-directory (abbreviate-file-name
10424 (expand-file-name ".")))))
10425 (cond ((equal arg '(16))
10426 (concat "file:"
10427 (abbreviate-file-name (expand-file-name file))))
10428 ((string-match
10429 (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10430 (concat "file:" (match-string 1 file)))
10431 ((string-match
10432 (concat "^" (regexp-quote pwd) "\\(.+\\)")
10433 (expand-file-name file))
10434 (concat "file:"
10435 (match-string 1 (expand-file-name file))))
10436 (t (concat "file:" file)))))
10438 (defun org-completing-read (&rest args)
10439 "Completing-read with SPACE being a normal character."
10440 (let ((enable-recursive-minibuffers t)
10441 (minibuffer-local-completion-map
10442 (copy-keymap minibuffer-local-completion-map)))
10443 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
10444 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
10445 (org-defkey minibuffer-local-completion-map (kbd "C-c !")
10446 'org-time-stamp-inactive)
10447 (apply #'completing-read args)))
10449 (define-obsolete-function-alias
10450 'org-completing-read-no-i 'completing-read "Org 9.0")
10451 (define-obsolete-function-alias
10452 'org-icompleting-read 'completing-read "Org 9.0")
10453 (define-obsolete-function-alias
10454 'org-iread-file-name 'read-file-name "Org 9.0")
10456 ;;; Opening/following a link
10458 (defvar org-link-search-failed nil)
10460 (defvar org-open-link-functions nil
10461 "Hook for functions finding a plain text link.
10462 These functions must take a single argument, the link content.
10463 They will be called for links that look like [[link text][description]]
10464 when LINK TEXT does not have a protocol like \"http:\" and does not look
10465 like a filename (e.g. \"./blue.png\").
10467 These functions will be called *before* Org attempts to resolve the
10468 link by doing text searches in the current buffer - so if you want a
10469 link \"[[target]]\" to still find \"<<target>>\", your function should
10470 handle this as a special case.
10472 When the function does handle the link, it must return a non-nil value.
10473 If it decides that it is not responsible for this link, it must return
10474 nil to indicate that that Org-mode can continue with other options
10475 like exact and fuzzy text search.")
10477 (defun org-next-link (&optional search-backward)
10478 "Move forward to the next link.
10479 If the link is in hidden text, expose it."
10480 (interactive "P")
10481 (when (and org-link-search-failed (eq this-command last-command))
10482 (goto-char (point-min))
10483 (message "Link search wrapped back to beginning of buffer"))
10484 (setq org-link-search-failed nil)
10485 (let* ((pos (point))
10486 (ct (org-context))
10487 (a (assoc :link ct))
10488 (srch-fun (if search-backward 're-search-backward 're-search-forward)))
10489 (cond (a (goto-char (nth (if search-backward 1 2) a)))
10490 ((looking-at org-any-link-re)
10491 ;; Don't stay stuck at link without an org-link face
10492 (forward-char (if search-backward -1 1))))
10493 (if (funcall srch-fun org-any-link-re nil t)
10494 (progn
10495 (goto-char (match-beginning 0))
10496 (when (outline-invisible-p) (org-show-context)))
10497 (goto-char pos)
10498 (setq org-link-search-failed t)
10499 (message "No further link found"))))
10501 (defun org-previous-link ()
10502 "Move backward to the previous link.
10503 If the link is in hidden text, expose it."
10504 (interactive)
10505 (funcall 'org-next-link t))
10507 (defun org-translate-link (s)
10508 "Translate a link string if a translation function has been defined."
10509 (with-temp-buffer
10510 (insert (org-trim s))
10511 (org-trim (org-element-interpret-data (org-element-context)))))
10513 (defun org-translate-link-from-planner (type path)
10514 "Translate a link from Emacs Planner syntax so that Org can follow it.
10515 This is still an experimental function, your mileage may vary."
10516 (cond
10517 ((member type '("http" "https" "news" "ftp"))
10518 ;; standard Internet links are the same.
10519 nil)
10520 ((and (equal type "irc") (string-match "^//" path))
10521 ;; Planner has two / at the beginning of an irc link, we have 1.
10522 ;; We should have zero, actually....
10523 (setq path (substring path 1)))
10524 ((and (equal type "lisp") (string-match "^/" path))
10525 ;; Planner has a slash, we do not.
10526 (setq type "elisp" path (substring path 1)))
10527 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
10528 ;; A typical message link. Planner has the id after the final slash,
10529 ;; we separate it with a hash mark
10530 (setq path (concat (match-string 1 path) "#"
10531 (org-remove-angle-brackets (match-string 2 path))))))
10532 (cons type path))
10534 (defun org-find-file-at-mouse (ev)
10535 "Open file link or URL at mouse."
10536 (interactive "e")
10537 (mouse-set-point ev)
10538 (org-open-at-point 'in-emacs))
10540 (defun org-open-at-mouse (ev)
10541 "Open file link or URL at mouse.
10542 See the docstring of `org-open-file' for details."
10543 (interactive "e")
10544 (mouse-set-point ev)
10545 (when (eq major-mode 'org-agenda-mode)
10546 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
10547 (org-open-at-point))
10549 (defvar org-window-config-before-follow-link nil
10550 "The window configuration before following a link.
10551 This is saved in case the need arises to restore it.")
10553 ;;;###autoload
10554 (defun org-open-at-point-global ()
10555 "Follow a link like Org-mode does.
10556 This command can be called in any mode to follow a link that has
10557 Org-mode syntax."
10558 (interactive)
10559 (org-run-like-in-org-mode 'org-open-at-point))
10561 ;;;###autoload
10562 (defun org-open-link-from-string (s &optional arg reference-buffer)
10563 "Open a link in the string S, as if it was in Org-mode."
10564 (interactive "sLink: \nP")
10565 (let ((reference-buffer (or reference-buffer (current-buffer))))
10566 (with-temp-buffer
10567 (let ((org-inhibit-startup (not reference-buffer)))
10568 (org-mode)
10569 (insert s)
10570 (goto-char (point-min))
10571 (when reference-buffer
10572 (setq org-link-abbrev-alist-local
10573 (with-current-buffer reference-buffer
10574 org-link-abbrev-alist-local)))
10575 (org-open-at-point arg reference-buffer)))))
10577 (defvar org-open-at-point-functions nil
10578 "Hook that is run when following a link at point.
10580 Functions in this hook must return t if they identify and follow
10581 a link at point. If they don't find anything interesting at point,
10582 they must return nil.")
10584 (defvar org-link-search-inhibit-query nil) ;; dynamically scoped
10585 (defvar clean-buffer-list-kill-buffer-names) ; Defined in midnight.el
10586 (defun org-open-at-point (&optional arg reference-buffer)
10587 "Open link, timestamp, footnote or tags at point.
10589 When point is on a link, follow it. Normally, files will be
10590 opened by an appropriate application. If the optional prefix
10591 argument ARG is non-nil, Emacs will visit the file. With
10592 a double prefix argument, try to open outside of Emacs, in the
10593 application the system uses for this file type.
10595 When point is on a timestamp, open the agenda at the day
10596 specified.
10598 When point is a footnote definition, move to the first reference
10599 found. If it is on a reference, move to the associated
10600 definition.
10602 When point is on a headline, display a list of every link in the
10603 entry, so it is possible to pick one, or all, of them. If point
10604 is on a tag, call `org-tags-view' instead.
10606 When optional argument REFERENCE-BUFFER is non-nil, it should
10607 specify a buffer from where the link search should happen. This
10608 is used internally by `org-open-link-from-string'.
10610 On top of syntactically correct links, this function will open
10611 the link at point in comments or comment blocks and the first
10612 link in a property drawer line."
10613 (interactive "P")
10614 ;; On a code block, open block's results.
10615 (unless (call-interactively 'org-babel-open-src-block-result)
10616 (org-load-modules-maybe)
10617 (setq org-window-config-before-follow-link (current-window-configuration))
10618 (org-remove-occur-highlights nil nil t)
10619 (unless (run-hook-with-args-until-success 'org-open-at-point-functions)
10620 (let* ((context
10621 ;; Only consider supported types, even if they are not
10622 ;; the closest one.
10623 (org-element-lineage
10624 (org-element-context)
10625 '(clock comment comment-block footnote-definition
10626 footnote-reference headline inlinetask keyword link
10627 node-property timestamp)
10629 (type (org-element-type context))
10630 (value (org-element-property :value context)))
10631 (cond
10632 ((not context) (user-error "No link found"))
10633 ;; Exception: open timestamps and links in properties
10634 ;; drawers, keywords and comments.
10635 ((memq type '(comment comment-block keyword node-property))
10636 (cond ((org-in-regexp org-any-link-re)
10637 (org-open-link-from-string (match-string-no-properties 0)))
10638 ((or (org-in-regexp org-ts-regexp-both nil t)
10639 (org-in-regexp org-tsr-regexp-both nil t))
10640 (org-follow-timestamp-link))
10641 (t (user-error "No link found"))))
10642 ;; On a headline or an inlinetask, but not on a timestamp,
10643 ;; a link, a footnote reference or on tags.
10644 ((and (memq type '(headline inlinetask))
10645 ;; Not on tags.
10646 (progn (save-excursion (beginning-of-line)
10647 (looking-at org-complex-heading-regexp))
10648 (or (not (match-beginning 5))
10649 (< (point) (match-beginning 5)))))
10650 (let* ((data (org-offer-links-in-entry (current-buffer) (point) arg))
10651 (links (car data))
10652 (links-end (cdr data)))
10653 (if links
10654 (dolist (link (if (stringp links) (list links) links))
10655 (search-forward link nil links-end)
10656 (goto-char (match-beginning 0))
10657 (org-open-at-point))
10658 (require 'org-attach)
10659 (org-attach-reveal 'if-exists))))
10660 ;; On a clock line, make sure point is on the timestamp
10661 ;; before opening it.
10662 ((and (eq type 'clock)
10663 value
10664 (>= (point) (org-element-property :begin value))
10665 (<= (point) (org-element-property :end value)))
10666 (org-follow-timestamp-link))
10667 ;; Do nothing on white spaces after an object.
10668 ((>= (point)
10669 (save-excursion
10670 (goto-char (org-element-property :end context))
10671 (skip-chars-backward " \t")
10672 (point)))
10673 (user-error "No link found"))
10674 ((eq type 'timestamp) (org-follow-timestamp-link))
10675 ;; On tags within a headline or an inlinetask.
10676 ((and (memq type '(headline inlinetask))
10677 (progn (save-excursion (beginning-of-line)
10678 (looking-at org-complex-heading-regexp))
10679 (and (match-beginning 5)
10680 (>= (point) (match-beginning 5)))))
10681 (org-tags-view arg (substring (match-string 5) 0 -1)))
10682 ((eq type 'link)
10683 ;; When link is located within the description of another
10684 ;; link (e.g., an inline image), always open the parent
10685 ;; link.
10686 (let*((link (let ((up (org-element-property :parent context)))
10687 (if (eq (org-element-type up) 'link) up context)))
10688 (type (org-element-property :type link))
10689 (path (org-link-unescape (org-element-property :path link))))
10690 ;; Switch back to REFERENCE-BUFFER needed when called in
10691 ;; a temporary buffer through `org-open-link-from-string'.
10692 (with-current-buffer (or reference-buffer (current-buffer))
10693 (cond
10694 ((equal type "file")
10695 (if (string-match "[*?{]" (file-name-nondirectory path))
10696 (dired path)
10697 ;; Look into `org-link-protocols' in order to find
10698 ;; a DEDICATED-FUNCTION to open file. The function
10699 ;; will be applied on raw link instead of parsed
10700 ;; link due to the limitation in `org-add-link-type'
10701 ;; ("open" function called with a single argument).
10702 ;; If no such function is found, fallback to
10703 ;; `org-open-file'.
10705 ;; Note : "file+emacs" and "file+sys" types are
10706 ;; hard-coded in order to escape the previous
10707 ;; limitation.
10708 (let* ((option (org-element-property :search-option link))
10709 (app (org-element-property :application link))
10710 (dedicated-function
10711 (nth 1 (assoc app org-link-protocols))))
10712 (if dedicated-function
10713 (funcall dedicated-function
10714 (concat path
10715 (and option (concat "::" option))))
10716 (apply #'org-open-file
10717 path
10718 (cond (arg)
10719 ((equal app "emacs") 'emacs)
10720 ((equal app "sys") 'system))
10721 (cond ((not option) nil)
10722 ((org-string-match-p "\\`[0-9]+\\'" option)
10723 (list (string-to-number option)))
10724 (t (list nil
10725 (org-link-unescape option)))))))))
10726 ((assoc type org-link-protocols)
10727 (funcall (nth 1 (assoc type org-link-protocols)) path))
10728 ((equal type "help")
10729 (let ((f-or-v (intern path)))
10730 (cond ((fboundp f-or-v) (describe-function f-or-v))
10731 ((boundp f-or-v) (describe-variable f-or-v))
10732 (t (error "Not a known function or variable")))))
10733 ((member type '("http" "https" "ftp" "mailto" "news"))
10734 (browse-url (org-link-escape-browser (concat type ":" path))))
10735 ((equal type "doi")
10736 (browse-url
10737 (org-link-escape-browser (concat org-doi-server-url path))))
10738 ((equal type "message") (browse-url (concat type ":" path)))
10739 ((equal type "shell")
10740 (let ((buf (generate-new-buffer "*Org Shell Output*"))
10741 (cmd path))
10742 (if (or (and (org-string-nw-p
10743 org-confirm-shell-link-not-regexp)
10744 (string-match
10745 org-confirm-shell-link-not-regexp cmd))
10746 (not org-confirm-shell-link-function)
10747 (funcall org-confirm-shell-link-function
10748 (format "Execute \"%s\" in shell? "
10749 (org-add-props cmd nil
10750 'face 'org-warning))))
10751 (progn
10752 (message "Executing %s" cmd)
10753 (shell-command cmd buf)
10754 (when (featurep 'midnight)
10755 (setq clean-buffer-list-kill-buffer-names
10756 (cons (buffer-name buf)
10757 clean-buffer-list-kill-buffer-names))))
10758 (user-error "Abort"))))
10759 ((equal type "elisp")
10760 (let ((cmd path))
10761 (if (or (and (org-string-nw-p
10762 org-confirm-elisp-link-not-regexp)
10763 (org-string-match-p
10764 org-confirm-elisp-link-not-regexp cmd))
10765 (not org-confirm-elisp-link-function)
10766 (funcall org-confirm-elisp-link-function
10767 (format "Execute \"%s\" as elisp? "
10768 (org-add-props cmd nil
10769 'face 'org-warning))))
10770 (message "%s => %s" cmd
10771 (if (eq (string-to-char cmd) ?\()
10772 (eval (read cmd))
10773 (call-interactively (read cmd))))
10774 (user-error "Abort"))))
10775 ((equal type "id")
10776 (require 'org-id)
10777 (funcall (nth 1 (assoc "id" org-link-protocols)) path))
10778 ((member type '("coderef" "custom-id" "fuzzy" "radio"))
10779 (unless (run-hook-with-args-until-success
10780 'org-open-link-functions path)
10781 (if (not arg) (org-mark-ring-push)
10782 (switch-to-buffer-other-window
10783 (org-get-buffer-for-internal-link (current-buffer))))
10784 (let ((destination
10785 (org-with-wide-buffer
10786 (if (equal type "radio")
10787 (org-search-radio-target
10788 (org-element-property :path link))
10789 (org-link-search
10790 (if (member type '("custom-id" "coderef"))
10791 (org-element-property :raw-link link)
10792 path)
10793 ;; Prevent fuzzy links from matching
10794 ;; themselves.
10795 (and (equal type "fuzzy")
10796 (+ 2 (org-element-property :begin link)))))
10797 (point))))
10798 (unless (and (<= (point-min) destination)
10799 (>= (point-max) destination))
10800 (widen))
10801 (goto-char destination))))
10802 (t (browse-url-at-point))))))
10803 ;; On a footnote reference or at a footnote definition's label.
10804 ((or (eq type 'footnote-reference)
10805 (and (eq type 'footnote-definition)
10806 (save-excursion
10807 ;; Do not validate action when point is on the
10808 ;; spaces right after the footnote label, in
10809 ;; order to be on par with behaviour on links.
10810 (skip-chars-forward " \t")
10811 (let ((begin
10812 (org-element-property :contents-begin context)))
10813 (if begin (< (point) begin)
10814 (= (org-element-property :post-affiliated context)
10815 (line-beginning-position)))))))
10816 (org-footnote-action))
10817 (t (user-error "No link found")))))
10818 (run-hook-with-args 'org-follow-link-hook)))
10820 (defun org-offer-links-in-entry (buffer marker &optional nth zero)
10821 "Offer links in the current entry and return the selected link.
10822 If there is only one link, return it.
10823 If NTH is an integer, return the NTH link found.
10824 If ZERO is a string, check also this string for a link, and if
10825 there is one, return it."
10826 (with-current-buffer buffer
10827 (save-excursion
10828 (save-restriction
10829 (widen)
10830 (goto-char marker)
10831 (let ((cnt ?0)
10832 have-zero end links link c)
10833 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
10834 (push (match-string 0 zero) links)
10835 (setq cnt (1- cnt) have-zero t))
10836 (save-excursion
10837 (org-back-to-heading t)
10838 (setq end (save-excursion (outline-next-heading) (point)))
10839 (while (re-search-forward org-any-link-re end t)
10840 (push (match-string 0) links))
10841 (setq links (org-uniquify (reverse links))))
10842 (cond
10843 ((null links)
10844 (message "No links"))
10845 ((equal (length links) 1)
10846 (setq link (car links)))
10847 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
10848 (setq link (nth (if have-zero nth (1- nth)) links)))
10849 (t ; we have to select a link
10850 (save-excursion
10851 (save-window-excursion
10852 (delete-other-windows)
10853 (with-output-to-temp-buffer "*Select Link*"
10854 (dolist (l links)
10855 (cond
10856 ((not (string-match org-bracket-link-regexp l))
10857 (princ (format "[%c] %s\n" (cl-incf cnt)
10858 (org-remove-angle-brackets l))))
10859 ((match-end 3)
10860 (princ (format "[%c] %s (%s)\n" (cl-incf cnt)
10861 (match-string 3 l) (match-string 1 l))))
10862 (t (princ (format "[%c] %s\n" (cl-incf cnt)
10863 (match-string 1 l)))))))
10864 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
10865 (message "Select link to open, RET to open all:")
10866 (setq c (read-char-exclusive))
10867 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
10868 (when (equal c ?q) (user-error "Abort"))
10869 (if (equal c ?\C-m)
10870 (setq link links)
10871 (setq nth (- c ?0))
10872 (when have-zero (setq nth (1+ nth)))
10873 (unless (and (integerp nth) (>= (length links) nth))
10874 (user-error "Invalid link selection"))
10875 (setq link (nth (1- nth) links)))))
10876 (cons link end))))))
10878 ;; TODO: These functions are deprecated since `org-open-at-point'
10879 ;; hard-codes behaviour for "file+emacs" and "file+sys" types.
10880 (defun org-open-file-with-system (path)
10881 "Open file at PATH using the system way of opening it."
10882 (org-open-file path 'system))
10883 (defun org-open-file-with-emacs (path)
10884 "Open file at PATH in Emacs."
10885 (org-open-file path 'emacs))
10888 ;;; File search
10890 (defvar org-create-file-search-functions nil
10891 "List of functions to construct the right search string for a file link.
10892 These functions are called in turn with point at the location to
10893 which the link should point.
10895 A function in the hook should first test if it would like to
10896 handle this file type, for example by checking the `major-mode'
10897 or the file extension. If it decides not to handle this file, it
10898 should just return nil to give other functions a chance. If it
10899 does handle the file, it must return the search string to be used
10900 when following the link. The search string will be part of the
10901 file link, given after a double colon, and `org-open-at-point'
10902 will automatically search for it. If special measures must be
10903 taken to make the search successful, another function should be
10904 added to the companion hook `org-execute-file-search-functions',
10905 which see.
10907 A function in this hook may also use `setq' to set the variable
10908 `description' to provide a suggestion for the descriptive text to
10909 be used for this link when it gets inserted into an Org-mode
10910 buffer with \\[org-insert-link].")
10912 (defvar org-execute-file-search-functions nil
10913 "List of functions to execute a file search triggered by a link.
10915 Functions added to this hook must accept a single argument, the
10916 search string that was part of the file link, the part after the
10917 double colon. The function must first check if it would like to
10918 handle this search, for example by checking the `major-mode' or
10919 the file extension. If it decides not to handle this search, it
10920 should just return nil to give other functions a chance. If it
10921 does handle the search, it must return a non-nil value to keep
10922 other functions from trying.
10924 Each function can access the current prefix argument through the
10925 variable `current-prefix-arg'. Note that a single prefix is used
10926 to force opening a link in Emacs, so it may be good to only use a
10927 numeric or double prefix to guide the search function.
10929 In case this is needed, a function in this hook can also restore
10930 the window configuration before `org-open-at-point' was called using:
10932 \(set-window-configuration org-window-config-before-follow-link)")
10934 (defun org-search-radio-target (target)
10935 "Search a radio target matching TARGET in current buffer.
10936 White spaces are not significant."
10937 (let ((re (format "<<<%s>>>"
10938 (mapconcat #'regexp-quote
10939 (org-split-string target "[ \t\n]+")
10940 "[ \t]+\\(?:\n[ \t]*\\)?")))
10941 (origin (point)))
10942 (goto-char (point-min))
10943 (catch :radio-match
10944 (while (re-search-forward re nil t)
10945 (backward-char)
10946 (let ((object (org-element-context)))
10947 (when (eq (org-element-type object) 'radio-target)
10948 (goto-char (org-element-property :begin object))
10949 (org-show-context 'link-search)
10950 (throw :radio-match nil))))
10951 (goto-char origin)
10952 (user-error "No match for radio target: %s" target))))
10954 (defun org-link-search (s &optional avoid-pos stealth)
10955 "Search for a search string S.
10957 If S starts with \"#\", it triggers a custom ID search.
10959 If S is enclosed within parenthesis, it initiates a coderef
10960 search.
10962 If S is surrounded by forward slashes, it is interpreted as
10963 a regular expression. In Org mode files, this will create an
10964 `org-occur' sparse tree. In ordinary files, `occur' will be used
10965 to list matches. If the current buffer is in `dired-mode', grep
10966 will be used to search in all files.
10968 When AVOID-POS is given, ignore matches near that position.
10970 When optional argument STEALTH is non-nil, do not modify
10971 visibility around point, thus ignoring `org-show-context-detail'
10972 variable.
10974 Search is case-insensitive and ignores white spaces. Return type
10975 of matched result, with is either `dedicated' or `fuzzy'."
10976 (unless (org-string-nw-p s) (error "Invalid search string \"%s\"" s))
10977 (let* ((case-fold-search t)
10978 (origin (point))
10979 (normalized (replace-regexp-in-string "\n[ \t]*" " " s))
10980 (words (org-split-string s "[ \t\n]+"))
10981 (s-multi-re (mapconcat #'regexp-quote words "[ \t]+\\(?:\n[ \t]*\\)?"))
10982 (s-single-re (mapconcat #'regexp-quote words "[ \t]+"))
10983 type)
10984 (cond
10985 ;; Check if there are any special search functions.
10986 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
10987 ((eq (string-to-char s) ?#)
10988 ;; Look for a custom ID S if S starts with "#".
10989 (let* ((id (substring normalized 1))
10990 (match (org-find-property "CUSTOM_ID" id)))
10991 (if match (progn (goto-char match) (setf type 'dedicated))
10992 (error "No match for custom ID: %s" id))))
10993 ((string-match "\\`(\\(.*\\))\\'" normalized)
10994 ;; Look for coderef targets if S is enclosed within parenthesis.
10995 (let ((coderef (match-string-no-properties 1 normalized))
10996 (re (substring s-single-re 1 -1)))
10997 (goto-char (point-min))
10998 (catch :coderef-match
10999 (while (re-search-forward re nil t)
11000 (let ((element (org-element-at-point)))
11001 (when (and (memq (org-element-type element)
11002 '(example-block src-block))
11003 ;; Build proper regexp according to current
11004 ;; block's label format.
11005 (let ((label-fmt
11006 (regexp-quote
11007 (or (org-element-property :label-fmt element)
11008 org-coderef-label-format))))
11009 (save-excursion
11010 (beginning-of-line)
11011 (looking-at (format ".*?\\(%s\\)[ \t]*$"
11012 (format label-fmt coderef))))))
11013 (setq type 'dedicated)
11014 (goto-char (match-beginning 1))
11015 (throw :coderef-match nil))))
11016 (goto-char origin)
11017 (error "No match for coderef: %s" coderef))))
11018 ((string-match "\\`/\\(.*\\)/\\'" normalized)
11019 ;; Look for a regular expression.
11020 (funcall (if (derived-mode-p 'org-mode) #'org-occur #'org-do-occur)
11021 (match-string 1 s)))
11022 ;; Fuzzy links.
11024 (let ((starred (eq (string-to-char normalized) ?*)))
11025 (cond
11026 ;; Look for targets, only if not in a headline search.
11027 ((and (not starred)
11028 (let ((target (format "<<%s>>" s-multi-re)))
11029 (catch :target-match
11030 (goto-char (point-min))
11031 (while (re-search-forward target nil t)
11032 (backward-char)
11033 (let ((context (org-element-context)))
11034 (when (eq (org-element-type context) 'target)
11035 (setq type 'dedicated)
11036 (goto-char (org-element-property :begin context))
11037 (throw :target-match t))))
11038 nil))))
11039 ;; Look for elements named after S, only if not in a headline
11040 ;; search.
11041 ((and (not starred)
11042 (let ((name (format "^[ \t]*#\\+NAME: +%s[ \t]*$" s-single-re)))
11043 (catch :name-match
11044 (goto-char (point-min))
11045 (while (re-search-forward name nil t)
11046 (let ((element (org-element-at-point)))
11047 (when (equal (org-split-string
11048 (org-element-property :name element)
11049 "[ \t]+")
11050 words)
11051 (setq type 'dedicated)
11052 (beginning-of-line)
11053 (throw :name-match t))))
11054 nil))))
11055 ;; Regular text search. Prefer headlines in Org mode
11056 ;; buffers.
11057 ((and (derived-mode-p 'org-mode)
11058 (let* ((wspace "[ \t]")
11059 (wspaceopt (concat wspace "*"))
11060 (cookie (concat "\\(?:"
11061 wspaceopt
11062 "\\[[0-9]*\\(?:%\\|/[0-9]*\\)\\]"
11063 wspaceopt
11064 "\\)"))
11065 (sep (concat "\\(?:\\(?:" wspace "\\|" cookie "\\)+\\)"))
11066 (re (concat
11067 org-outline-regexp-bol
11068 "\\(?:" org-todo-regexp "[ \t]+\\)?"
11069 "\\(?:\\[#.\\][ \t]+\\)?"
11070 "\\(?:" org-comment-string "[ \t]+\\)?"
11071 sep "?"
11072 (let ((title (mapconcat #'regexp-quote
11073 words
11074 sep)))
11075 (if starred (substring title 1) title))
11076 sep "?"
11077 (org-re "\\(?:[ \t]+:[[:alnum:]_@#%%:]+:\\)?")
11078 "[ \t]*$")))
11079 (goto-char (point-min))
11080 (re-search-forward re nil t)))
11081 (goto-char (match-beginning 0))
11082 (setq type 'dedicated))
11083 ;; Offer to create non-existent headline depending on
11084 ;; `org-link-search-must-match-exact-headline'.
11085 ((and (derived-mode-p 'org-mode)
11086 (not org-link-search-inhibit-query)
11087 (eq org-link-search-must-match-exact-headline 'query-to-create)
11088 (yes-or-no-p "No match - create this as a new heading? "))
11089 (goto-char (point-max))
11090 (unless (bolp) (newline))
11091 (org-insert-heading nil t t)
11092 (insert s "\n")
11093 (beginning-of-line 0))
11094 ;; Only headlines are looked after. No need to process
11095 ;; further: throw an error.
11096 ((and (derived-mode-p 'org-mode)
11097 (or starred org-link-search-must-match-exact-headline))
11098 (goto-char origin)
11099 (error "No match for fuzzy expression: %s" normalized))
11100 ;; Regular text search.
11101 ((catch :fuzzy-match
11102 (goto-char (point-min))
11103 (while (re-search-forward s-multi-re nil t)
11104 ;; Skip match if it contains AVOID-POS or it is included
11105 ;; in a link with a description but outside the
11106 ;; description.
11107 (unless (or (and avoid-pos
11108 (<= (match-beginning 0) avoid-pos)
11109 (> (match-end 0) avoid-pos))
11110 (and (save-match-data
11111 (org-in-regexp org-bracket-link-regexp))
11112 (match-beginning 3)
11113 (or (> (match-beginning 3) (point))
11114 (<= (match-end 3) (point)))
11115 (org-element-lineage
11116 (save-match-data (org-element-context))
11117 '(link) t)))
11118 (goto-char (match-beginning 0))
11119 (setq type 'fuzzy)
11120 (throw :fuzzy-match t)))
11121 nil))
11122 ;; All failed. Throw an error.
11123 (t (goto-char origin)
11124 (error "No match for fuzzy expression: %s" normalized))))))
11125 ;; Disclose surroundings of match, if appropriate.
11126 (when (and (derived-mode-p 'org-mode) (not stealth))
11127 (org-show-context 'link-search))
11128 type))
11130 (defun org-get-buffer-for-internal-link (buffer)
11131 "Return a buffer to be used for displaying the link target of internal links."
11132 (cond
11133 ((not org-display-internal-link-with-indirect-buffer)
11134 buffer)
11135 ((string-match "(Clone)$" (buffer-name buffer))
11136 (message "Buffer is already a clone, not making another one")
11137 ;; we also do not modify visibility in this case
11138 buffer)
11139 (t ; make a new indirect buffer for displaying the link
11140 (let* ((bn (buffer-name buffer))
11141 (ibn (concat bn "(Clone)"))
11142 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
11143 (with-current-buffer ib (org-overview))
11144 ib))))
11146 (defun org-do-occur (regexp &optional cleanup)
11147 "Call the Emacs command `occur'.
11148 If CLEANUP is non-nil, remove the printout of the regular expression
11149 in the *Occur* buffer. This is useful if the regex is long and not useful
11150 to read."
11151 (occur regexp)
11152 (when cleanup
11153 (let ((cwin (selected-window)) win beg end)
11154 (when (setq win (get-buffer-window "*Occur*"))
11155 (select-window win))
11156 (goto-char (point-min))
11157 (when (re-search-forward "match[a-z]+" nil t)
11158 (setq beg (match-end 0))
11159 (when (re-search-forward "^[ \t]*[0-9]+" nil t)
11160 (setq end (1- (match-beginning 0)))))
11161 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
11162 (goto-char (point-min))
11163 (select-window cwin))))
11165 ;;; The mark ring for links jumps
11167 (defvar org-mark-ring nil
11168 "Mark ring for positions before jumps in Org-mode.")
11169 (defvar org-mark-ring-last-goto nil
11170 "Last position in the mark ring used to go back.")
11171 ;; Fill and close the ring
11172 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
11173 (dotimes (_ org-mark-ring-length)
11174 (push (make-marker) org-mark-ring))
11175 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
11176 org-mark-ring)
11178 (defun org-mark-ring-push (&optional pos buffer)
11179 "Put the current position or POS into the mark ring and rotate it."
11180 (interactive)
11181 (setq pos (or pos (point)))
11182 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
11183 (move-marker (car org-mark-ring)
11184 (or pos (point))
11185 (or buffer (current-buffer)))
11186 (message "%s"
11187 (substitute-command-keys
11188 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
11190 (defun org-mark-ring-goto (&optional n)
11191 "Jump to the previous position in the mark ring.
11192 With prefix arg N, jump back that many stored positions. When
11193 called several times in succession, walk through the entire ring.
11194 Org-mode commands jumping to a different position in the current file,
11195 or to another Org-mode file, automatically push the old position
11196 onto the ring."
11197 (interactive "p")
11198 (let (p m)
11199 (if (eq last-command this-command)
11200 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
11201 (setq p org-mark-ring))
11202 (setq org-mark-ring-last-goto p)
11203 (setq m (car p))
11204 (org-pop-to-buffer-same-window (marker-buffer m))
11205 (goto-char m)
11206 (when (or (outline-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
11208 ;;; TODO: Use string-remove-prefix and -suffix once we only support
11209 ;;; Emacs 24.4+
11210 (defun org-remove-angle-brackets (s)
11211 (when (equal (substring s 0 1) "<") (setq s (substring s 1)))
11212 (when (equal (substring s -1) ">") (setq s (substring s 0 -1)))
11214 (defun org-add-angle-brackets (s)
11215 (unless (equal (substring s 0 1) "<") (setq s (concat "<" s)))
11216 (unless (equal (substring s -1) ">") (setq s (concat s ">")))
11218 (defun org-remove-double-quotes (s)
11219 (when (equal (substring s 0 1) "\"") (setq s (substring s 1)))
11220 (when (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
11223 ;;; Following specific links
11225 (defvar org-agenda-buffer-tmp-name)
11226 (defvar org-agenda-start-on-weekday)
11227 (defun org-follow-timestamp-link ()
11228 "Open an agenda view for the time-stamp date/range at point."
11229 (cond
11230 ((org-at-date-range-p t)
11231 (let ((org-agenda-start-on-weekday)
11232 (t1 (match-string 1))
11233 (t2 (match-string 2)) tt1 tt2)
11234 (setq tt1 (time-to-days (org-time-string-to-time t1))
11235 tt2 (time-to-days (org-time-string-to-time t2)))
11236 (let ((org-agenda-buffer-tmp-name
11237 (format "*Org Agenda(a:%s)"
11238 (concat (substring t1 0 10) "--" (substring t2 0 10)))))
11239 (org-agenda-list nil tt1 (1+ (- tt2 tt1))))))
11240 ((org-at-timestamp-p t)
11241 (let ((org-agenda-buffer-tmp-name
11242 (format "*Org Agenda(a:%s)" (substring (match-string 1) 0 10))))
11243 (org-agenda-list nil (time-to-days (org-time-string-to-time
11244 (substring (match-string 1) 0 10)))
11245 1)))
11246 (t (error "This should not happen"))))
11249 ;;; Following file links
11250 (declare-function mailcap-parse-mailcaps "mailcap" (&optional path force))
11251 (declare-function mailcap-extension-to-mime "mailcap" (extn))
11252 (declare-function mailcap-mime-info
11253 "mailcap" (string &optional request no-decode))
11254 (defvar org-wait nil)
11255 (defun org-open-file (path &optional in-emacs line search)
11256 "Open the file at PATH.
11257 First, this expands any special file name abbreviations. Then the
11258 configuration variable `org-file-apps' is checked if it contains an
11259 entry for this file type, and if yes, the corresponding command is launched.
11261 If no application is found, Emacs simply visits the file.
11263 With optional prefix argument IN-EMACS, Emacs will visit the file.
11264 With a double \\[universal-argument] \\[universal-argument] \
11265 prefix arg, Org tries to avoid opening in Emacs
11266 and to use an external application to visit the file.
11268 Optional LINE specifies a line to go to, optional SEARCH a string
11269 to search for. If LINE or SEARCH is given, the file will be
11270 opened in Emacs, unless an entry from org-file-apps that makes
11271 use of groups in a regexp matches.
11273 If you want to change the way frames are used when following a
11274 link, please customize `org-link-frame-setup'.
11276 If the file does not exist, an error is thrown."
11277 (let* ((file (if (equal path "")
11278 buffer-file-name
11279 (substitute-in-file-name (expand-file-name path))))
11280 (file-apps (append org-file-apps (org-default-apps)))
11281 (apps (cl-remove-if
11282 'org-file-apps-entry-match-against-dlink-p file-apps))
11283 (apps-dlink (cl-remove-if-not
11284 'org-file-apps-entry-match-against-dlink-p file-apps))
11285 (remp (and (assq 'remote apps) (org-file-remote-p file)))
11286 (dirp (unless remp (file-directory-p file)))
11287 (file (if (and dirp org-open-directory-means-index-dot-org)
11288 (concat (file-name-as-directory file) "index.org")
11289 file))
11290 (a-m-a-p (assq 'auto-mode apps))
11291 (dfile (downcase file))
11292 ;; Reconstruct the original link from the PATH, LINE and
11293 ;; SEARCH args.
11294 (link (cond (line (concat file "::" (number-to-string line)))
11295 (search (concat file "::" search))
11296 (t file)))
11297 (dlink (downcase link))
11298 (old-buffer (current-buffer))
11299 (old-pos (point))
11300 (old-mode major-mode)
11301 (ext
11302 (and (string-match "\\`.*?\\.\\([a-zA-Z0-9]+\\(\\.gz\\)?\\)\\'" dfile)
11303 (match-string 1 dfile)))
11304 cmd link-match-data)
11305 (cond
11306 ((member in-emacs '((16) system))
11307 (setq cmd (cdr (assq 'system apps))))
11308 (in-emacs (setq cmd 'emacs))
11310 (setq cmd (or (and remp (cdr (assq 'remote apps)))
11311 (and dirp (cdr (assq 'directory apps)))
11312 ;; First, try matching against apps-dlink if we
11313 ;; get a match here, store the match data for
11314 ;; later.
11315 (let ((match (assoc-default dlink apps-dlink
11316 'string-match)))
11317 (if match
11318 (progn (setq link-match-data (match-data))
11319 match)
11320 (progn (setq in-emacs (or in-emacs line search))
11321 nil))) ; if we have no match in apps-dlink,
11322 ; always open the file in emacs if line or search
11323 ; is given (for backwards compatibility)
11324 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
11325 'string-match)
11326 (cdr (assoc ext apps))
11327 (cdr (assq t apps))))))
11328 (when (eq cmd 'system)
11329 (setq cmd (cdr (assoc 'system apps))))
11330 (when (eq cmd 'default)
11331 (setq cmd (cdr (assoc t apps))))
11332 (when (eq cmd 'mailcap)
11333 (require 'mailcap)
11334 (mailcap-parse-mailcaps)
11335 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
11336 (command (mailcap-mime-info mime-type)))
11337 (if (stringp command)
11338 (setq cmd command)
11339 (setq cmd 'emacs))))
11340 (when (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
11341 (not (file-exists-p file))
11342 (not org-open-non-existing-files))
11343 (user-error "No such file: %s" file))
11344 (cond
11345 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
11346 ;; Remove quotes around the file name - we'll use shell-quote-argument.
11347 (while (string-match "['\"]%s['\"]" cmd)
11348 (setq cmd (replace-match "%s" t t cmd)))
11349 (while (string-match "%s" cmd)
11350 (setq cmd (replace-match
11351 (save-match-data
11352 (shell-quote-argument
11353 (convert-standard-filename file)))
11354 t t cmd)))
11356 ;; Replace "%1", "%2" etc. in command with group matches from regex
11357 (save-match-data
11358 (let ((match-index 1)
11359 (number-of-groups (- (/ (length link-match-data) 2) 1)))
11360 (set-match-data link-match-data)
11361 (while (<= match-index number-of-groups)
11362 (let ((regex (concat "%" (number-to-string match-index)))
11363 (replace-with (match-string match-index dlink)))
11364 (while (string-match regex cmd)
11365 (setq cmd (replace-match replace-with t t cmd))))
11366 (setq match-index (+ match-index 1)))))
11368 (save-window-excursion
11369 (message "Running %s...done" cmd)
11370 (start-process-shell-command cmd nil cmd)
11371 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))))
11372 ((or (stringp cmd)
11373 (eq cmd 'emacs))
11374 (funcall (cdr (assq 'file org-link-frame-setup)) file)
11375 (widen)
11376 (cond (line (org-goto-line line)
11377 (when (derived-mode-p 'org-mode) (org-reveal)))
11378 (search (org-link-search search))))
11379 ((functionp cmd)
11380 (save-match-data
11381 (set-match-data link-match-data)
11382 (condition-case nil
11383 (funcall cmd file link)
11384 ;; FIXME: Remove this check when most default installations
11385 ;; of Emacs have at least Org 9.0.
11386 ((debug wrong-number-of-arguments wrong-type-argument
11387 invalid-function)
11388 (user-error "Please see Org News for version 9.0 about \
11389 `org-file-apps'--Lisp error: %S" cmd)))))
11390 ((consp cmd)
11391 ;; FIXME: Remove this check when most default installations of
11392 ;; Emacs have at least Org 9.0.
11393 ;; Heads-up instead of silently fall back to
11394 ;; `org-link-frame-setup' for an old usage of `org-file-apps'
11395 ;; with sexp instead of a function for `cmd'.
11396 (user-error "Please see Org News for version 9.0 about \
11397 `org-file-apps'--Error: Deprecated usage of %S" cmd))
11398 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
11399 (and (derived-mode-p 'org-mode)
11400 (eq old-mode 'org-mode)
11401 (or (not (eq old-buffer (current-buffer)))
11402 (not (eq old-pos (point))))
11403 (org-mark-ring-push old-pos old-buffer))))
11405 (defun org-file-apps-entry-match-against-dlink-p (entry)
11406 "This function returns non-nil if `entry' uses a regular
11407 expression which should be matched against the whole link by
11408 org-open-file.
11410 It assumes that is the case when the entry uses a regular
11411 expression which has at least one grouping construct and the
11412 action is either a lisp form or a command string containing
11413 `%1', i.e. using at least one subexpression match as a
11414 parameter."
11415 (let ((selector (car entry))
11416 (action (cdr entry)))
11417 (if (stringp selector)
11418 (and (> (regexp-opt-depth selector) 0)
11419 (or (and (stringp action)
11420 (string-match "%[0-9]" action))
11421 (consp action)))
11422 nil)))
11424 (defun org-default-apps ()
11425 "Return the default applications for this operating system."
11426 (cond
11427 ((eq system-type 'darwin)
11428 org-file-apps-defaults-macosx)
11429 ((eq system-type 'windows-nt)
11430 org-file-apps-defaults-windowsnt)
11431 (t org-file-apps-defaults-gnu)))
11433 (defun org-apps-regexp-alist (list &optional add-auto-mode)
11434 "Convert extensions to regular expressions in the cars of LIST.
11435 Also, weed out any non-string entries, because the return value is used
11436 only for regexp matching.
11437 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
11438 point to the symbol `emacs', indicating that the file should
11439 be opened in Emacs."
11440 (append
11441 (delq nil
11442 (mapcar (lambda (x)
11443 (unless (not (stringp (car x)))
11444 (if (string-match "\\W" (car x))
11446 (cons (concat "\\." (car x) "\\'") (cdr x)))))
11447 list))
11448 (when add-auto-mode
11449 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
11451 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
11452 (defun org-file-remote-p (file)
11453 "Test whether FILE specifies a location on a remote system.
11454 Return non-nil if the location is indeed remote.
11456 For example, the filename \"/user@host:/foo\" specifies a location
11457 on the system \"/user@host:\"."
11458 (cond ((fboundp 'file-remote-p)
11459 (file-remote-p file))
11460 ((fboundp 'tramp-handle-file-remote-p)
11461 (tramp-handle-file-remote-p file))
11462 ((and (boundp 'ange-ftp-name-format)
11463 (string-match (car ange-ftp-name-format) file))
11464 t)))
11467 ;;;; Refiling
11469 (defun org-get-org-file ()
11470 "Read a filename, with default directory `org-directory'."
11471 (let ((default (or org-default-notes-file remember-data-file)))
11472 (read-file-name (format "File name [%s]: " default)
11473 (file-name-as-directory org-directory)
11474 default)))
11476 (defun org-notes-order-reversed-p ()
11477 "Check if the current file should receive notes in reversed order."
11478 (cond
11479 ((not org-reverse-note-order) nil)
11480 ((eq t org-reverse-note-order) t)
11481 ((not (listp org-reverse-note-order)) nil)
11482 (t (catch 'exit
11483 (dolist (entry org-reverse-note-order)
11484 (when (string-match (car entry) buffer-file-name)
11485 (throw 'exit (cdr entry))))))))
11487 (defvar org-refile-target-table nil
11488 "The list of refile targets, created by `org-refile'.")
11490 (defvar org-agenda-new-buffers nil
11491 "Buffers created to visit agenda files.")
11493 (defvar org-refile-cache nil
11494 "Cache for refile targets.")
11496 (defvar org-refile-markers nil
11497 "All the markers used for caching refile locations.")
11499 (defun org-refile-marker (pos)
11500 "Get a new refile marker, but only if caching is in use."
11501 (if (not org-refile-use-cache)
11503 (let ((m (make-marker)))
11504 (move-marker m pos)
11505 (push m org-refile-markers)
11506 m)))
11508 (defun org-refile-cache-clear ()
11509 "Clear the refile cache and disable all the markers."
11510 (dolist (m org-refile-markers) (move-marker m nil))
11511 (setq org-refile-markers nil)
11512 (setq org-refile-cache nil)
11513 (message "Refile cache has been cleared"))
11515 (defun org-refile-cache-check-set (set)
11516 "Check if all the markers in the cache still have live buffers."
11517 (let (marker)
11518 (catch 'exit
11519 (while (and set (setq marker (nth 3 (pop set))))
11520 ;; If `org-refile-use-outline-path' is 'file, marker may be nil
11521 (when (and marker (null (marker-buffer marker)))
11522 (message "Please regenerate the refile cache with `C-0 C-c C-w'")
11523 (sit-for 3)
11524 (throw 'exit nil)))
11525 t)))
11527 (defun org-refile-cache-put (set &rest identifiers)
11528 "Push the refile targets SET into the cache, under IDENTIFIERS."
11529 (let* ((key (sha1 (prin1-to-string identifiers)))
11530 (entry (assoc key org-refile-cache)))
11531 (if entry
11532 (setcdr entry set)
11533 (push (cons key set) org-refile-cache))))
11535 (defun org-refile-cache-get (&rest identifiers)
11536 "Retrieve the cached value for refile targets given by IDENTIFIERS."
11537 (cond
11538 ((not org-refile-cache) nil)
11539 ((not org-refile-use-cache) (org-refile-cache-clear) nil)
11541 (let ((set (cdr (assoc (sha1 (prin1-to-string identifiers))
11542 org-refile-cache))))
11543 (and set (org-refile-cache-check-set set) set)))))
11545 (defvar org-outline-path-cache nil
11546 "Alist between buffer positions and outline paths.
11547 It value is an alist (POSITION . PATH) where POSITION is the
11548 buffer position at the beginning of an entry and PATH is a list
11549 of strings describing the outline path for that entry, in reverse
11550 order.")
11552 (defun org-refile-get-targets (&optional default-buffer)
11553 "Produce a table with refile targets."
11554 (let ((case-fold-search nil)
11555 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
11556 (entries (or org-refile-targets '((nil . (:level . 1)))))
11557 targets tgs files desc descre)
11558 (message "Getting targets...")
11559 (with-current-buffer (or default-buffer (current-buffer))
11560 (dolist (entry entries)
11561 (setq files (car entry) desc (cdr entry))
11562 (cond
11563 ((null files) (setq files (list (current-buffer))))
11564 ((eq files 'org-agenda-files)
11565 (setq files (org-agenda-files 'unrestricted)))
11566 ((and (symbolp files) (fboundp files))
11567 (setq files (funcall files)))
11568 ((and (symbolp files) (boundp files))
11569 (setq files (symbol-value files))))
11570 (when (stringp files) (setq files (list files)))
11571 (cond
11572 ((eq (car desc) :tag)
11573 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
11574 ((eq (car desc) :todo)
11575 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
11576 ((eq (car desc) :regexp)
11577 (setq descre (cdr desc)))
11578 ((eq (car desc) :level)
11579 (setq descre (concat "^\\*\\{" (number-to-string
11580 (if org-odd-levels-only
11581 (1- (* 2 (cdr desc)))
11582 (cdr desc)))
11583 "\\}[ \t]")))
11584 ((eq (car desc) :maxlevel)
11585 (setq descre (concat "^\\*\\{1," (number-to-string
11586 (if org-odd-levels-only
11587 (1- (* 2 (cdr desc)))
11588 (cdr desc)))
11589 "\\}[ \t]")))
11590 (t (error "Bad refiling target description %s" desc)))
11591 (dolist (f files)
11592 (with-current-buffer (if (bufferp f) f (org-get-agenda-file-buffer f))
11594 (setq tgs (org-refile-cache-get (buffer-file-name) descre))
11595 (progn
11596 (when (bufferp f)
11597 (setq f (buffer-file-name (buffer-base-buffer f))))
11598 (setq f (and f (expand-file-name f)))
11599 (when (eq org-refile-use-outline-path 'file)
11600 (push (list (file-name-nondirectory f) f nil nil) tgs))
11601 (org-with-wide-buffer
11602 (goto-char (point-min))
11603 (setq org-outline-path-cache nil)
11604 (while (re-search-forward descre nil t)
11605 (beginning-of-line)
11606 (looking-at org-complex-heading-regexp)
11607 (let ((begin (point))
11608 (heading (org-match-string-no-properties 4)))
11609 (unless (or (and
11610 org-refile-target-verify-function
11611 (not
11612 (funcall org-refile-target-verify-function)))
11613 (not heading))
11614 (let ((re (format org-complex-heading-regexp-format
11615 (regexp-quote heading)))
11616 (target
11617 (if (not org-refile-use-outline-path) heading
11618 (mapconcat
11619 #'org-protect-slash
11620 (append
11621 (pcase org-refile-use-outline-path
11622 (`file (list (file-name-nondirectory
11623 (buffer-file-name
11624 (buffer-base-buffer)))))
11625 (`full-file-path
11626 (list (buffer-file-name
11627 (buffer-base-buffer))))
11628 (_ nil))
11629 (org-get-outline-path t t))
11630 "/"))))
11631 (push (list target f re (org-refile-marker (point)))
11632 tgs)))
11633 (when (= (point) begin)
11634 ;; Verification function has not moved point.
11635 (end-of-line)))))))
11636 (when org-refile-use-cache
11637 (org-refile-cache-put tgs (buffer-file-name) descre))
11638 (setq targets (append tgs targets))))))
11639 (message "Getting targets...done")
11640 (nreverse targets)))
11642 (defun org-protect-slash (s)
11643 (while (string-match "/" s)
11644 (setq s (replace-match "\\" t t s)))
11647 (defun org--get-outline-path-1 (&optional use-cache)
11648 "Return outline path to current headline.
11650 Outline path is a list of strings, in reverse order. When
11651 optional argument USE-CACHE is non-nil, make use of a cache. See
11652 `org-get-outline-path' for details.
11654 Assume buffer is widened and point is on a headline."
11655 (or (and use-cache (cdr (assq (point) org-outline-path-cache)))
11656 (let ((p (point))
11657 (heading (progn
11658 (looking-at org-complex-heading-regexp)
11659 (if (not (match-end 4)) ""
11660 ;; Remove statistics cookies.
11661 (org-trim
11662 (org-link-display-format
11663 (replace-regexp-in-string
11664 "\\[[0-9]+%\\]\\|\\[[0-9]+/[0-9]+\\]" ""
11665 (org-match-string-no-properties 4))))))))
11666 (if (org-up-heading-safe)
11667 (let ((path (cons heading (org--get-outline-path-1 use-cache))))
11668 (when use-cache
11669 (push (cons p path) org-outline-path-cache))
11670 path)
11671 ;; This is a new root node. Since we assume we are moving
11672 ;; forward, we can drop previous cache so as to limit number
11673 ;; of associations there.
11674 (let ((path (list heading)))
11675 (when use-cache (setq org-outline-path-cache (list (cons p path))))
11676 path)))))
11678 (defun org-get-outline-path (&optional with-self use-cache)
11679 "Return the outline path to the current entry.
11681 An outline path is a list of ancestors for current headline, as
11682 a list of strings. Statistics cookies are removed and links are
11683 replaced with their description, if any, or their path otherwise.
11685 When optional argument WITH-SELF is non-nil, the path also
11686 includes the current headline.
11688 When optional argument USE-CACHE is non-nil, cache outline paths
11689 between calls to this function so as to avoid backtracking. This
11690 argument is useful when planning to find more than one outline
11691 path in the same document. In that case, there are two
11692 conditions to satisfy:
11693 - `org-outline-path-cache' is set to nil before starting the
11694 process;
11695 - outline paths are computed by increasing buffer positions."
11696 (org-with-wide-buffer
11697 (and (or (and with-self (org-back-to-heading t))
11698 (org-up-heading-safe))
11699 (reverse (org--get-outline-path-1 use-cache)))))
11701 (defun org-format-outline-path (path &optional width prefix separator)
11702 "Format the outline path PATH for display.
11703 WIDTH is the maximum number of characters that is available.
11704 PREFIX is a prefix to be included in the returned string,
11705 such as the file name.
11706 SEPARATOR is inserted between the different parts of the path,
11707 the default is \"/\"."
11708 (setq width (or width 79))
11709 (setq path (delq nil path))
11710 (unless (> width 0)
11711 (user-error "Argument `width' must be positive"))
11712 (setq separator (or separator "/"))
11713 (let* ((org-odd-levels-only nil)
11714 (fpath (concat
11715 prefix (and prefix path separator)
11716 (mapconcat
11717 (lambda (s) (replace-regexp-in-string "[ \t]+\\'" "" s))
11718 (cl-loop for head in path
11719 for n from 0
11720 collect (org-add-props
11721 head nil 'face
11722 (nth (% n org-n-level-faces) org-level-faces)))
11723 separator))))
11724 (when (> (length fpath) width)
11725 (if (< width 7)
11726 ;; It's unlikely that `width' will be this small, but don't
11727 ;; waste characters by adding ".." if it is.
11728 (setq fpath (substring fpath 0 width))
11729 (setf (substring fpath (- width 2)) "..")))
11730 fpath))
11732 (defun org-display-outline-path (&optional file current separator just-return-string)
11733 "Display the current outline path in the echo area.
11735 If FILE is non-nil, prepend the output with the file name.
11736 If CURRENT is non-nil, append the current heading to the output.
11737 SEPARATOR is passed through to `org-format-outline-path'. It separates
11738 the different parts of the path and defaults to \"/\".
11739 If JUST-RETURN-STRING is non-nil, return a string, don't display a message."
11740 (interactive "P")
11741 (let* (case-fold-search
11742 (bfn (buffer-file-name (buffer-base-buffer)))
11743 (path (and (derived-mode-p 'org-mode) (org-get-outline-path)))
11744 res)
11745 (when current (setq path (append path
11746 (save-excursion
11747 (org-back-to-heading t)
11748 (when (looking-at org-complex-heading-regexp)
11749 (list (match-string 4)))))))
11750 (setq res
11751 (org-format-outline-path
11752 path
11753 (1- (frame-width))
11754 (and file bfn (concat (file-name-nondirectory bfn) separator))
11755 separator))
11756 (if just-return-string
11757 (org-no-properties res)
11758 (org-unlogged-message "%s" res))))
11760 (defvar org-refile-history nil
11761 "History for refiling operations.")
11763 (defvar org-after-refile-insert-hook nil
11764 "Hook run after `org-refile' has inserted its stuff at the new location.
11765 Note that this is still *before* the stuff will be removed from
11766 the *old* location.")
11768 (defvar org-capture-last-stored-marker)
11769 (defvar org-refile-keep nil
11770 "Non-nil means `org-refile' will copy instead of refile.")
11772 (defun org-copy ()
11773 "Like `org-refile', but copy."
11774 (interactive)
11775 (let ((org-refile-keep t))
11776 (funcall 'org-refile nil nil nil "Copy")))
11778 (defun org-refile (&optional arg default-buffer rfloc msg)
11779 "Move the entry or entries at point to another heading.
11780 The list of target headings is compiled using the information in
11781 `org-refile-targets', which see.
11783 At the target location, the entry is filed as a subitem of the
11784 target heading. Depending on `org-reverse-note-order', the new
11785 subitem will either be the first or the last subitem.
11787 If there is an active region, all entries in that region will be
11788 refiled. However, the region must fulfill the requirement that
11789 the first heading sets the top-level of the moved text.
11791 With prefix arg ARG, the command will only visit the target
11792 location and not actually move anything.
11794 With a double prefix arg \\[universal-argument] \\[universal-argument], go to the location where the last
11795 refiling operation has put the subtree.
11797 With a numeric prefix argument of `2', refile to the running clock.
11799 With a numeric prefix argument of `3', emulate `org-refile-keep'
11800 being set to t and copy to the target location, don't move it.
11801 Beware that keeping refiled entries may result in duplicated ID
11802 properties.
11804 RFLOC can be a refile location obtained in a different way.
11806 MSG is a string to replace \"Refile\" in the default prompt with
11807 another verb. E.g. `org-copy' sets this parameter to \"Copy\".
11809 See also `org-refile-use-outline-path'.
11811 If you are using target caching (see `org-refile-use-cache'), you
11812 have to clear the target cache in order to find new targets.
11813 This can be done with a 0 prefix (`C-0 C-c C-w') or a triple
11814 prefix argument (`C-u C-u C-u C-c C-w')."
11815 (interactive "P")
11816 (if (member arg '(0 (64)))
11817 (org-refile-cache-clear)
11818 (let* ((actionmsg (cond (msg msg)
11819 ((equal arg 3) "Refile (and keep)")
11820 (t "Refile")))
11821 (regionp (org-region-active-p))
11822 (region-start (and regionp (region-beginning)))
11823 (region-end (and regionp (region-end)))
11824 (org-refile-keep (if (equal arg 3) t org-refile-keep))
11825 pos it nbuf file level reversed)
11826 (setq last-command nil)
11827 (when regionp
11828 (goto-char region-start)
11829 (or (bolp) (goto-char (point-at-bol)))
11830 (setq region-start (point))
11831 (unless (or (org-kill-is-subtree-p
11832 (buffer-substring region-start region-end))
11833 (prog1 org-refile-active-region-within-subtree
11834 (let ((s (point-at-eol)))
11835 (org-toggle-heading)
11836 (setq region-end (+ (- (point-at-eol) s) region-end)))))
11837 (user-error "The region is not a (sequence of) subtree(s)")))
11838 (if (equal arg '(16))
11839 (org-refile-goto-last-stored)
11840 (when (or
11841 (and (equal arg 2)
11842 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
11843 (prog1
11844 (setq it (list (or org-clock-heading "running clock")
11845 (buffer-file-name
11846 (marker-buffer org-clock-hd-marker))
11848 (marker-position org-clock-hd-marker)))
11849 (setq arg nil)))
11850 (setq it
11851 (or rfloc
11852 (let (heading-text)
11853 (save-excursion
11854 (unless (and arg (listp arg))
11855 (org-back-to-heading t)
11856 (setq heading-text
11857 (replace-regexp-in-string
11858 org-bracket-link-regexp
11859 "\\3"
11860 (nth 4 (org-heading-components)))))
11861 (org-refile-get-location
11862 (cond ((and arg (listp arg)) "Goto")
11863 (regionp (concat actionmsg " region to"))
11864 (t (concat actionmsg " subtree \""
11865 heading-text "\" to")))
11866 default-buffer
11867 (and (not (equal '(4) arg))
11868 org-refile-allow-creating-parent-nodes)))))))
11869 (setq file (nth 1 it)
11870 pos (nth 3 it))
11871 (when (and (not arg)
11873 (equal (buffer-file-name) file)
11874 (if regionp
11875 (and (>= pos region-start)
11876 (<= pos region-end))
11877 (and (>= pos (point))
11878 (< pos (save-excursion
11879 (org-end-of-subtree t t))))))
11880 (error "Cannot refile to position inside the tree or region"))
11881 (setq nbuf (or (find-buffer-visiting file)
11882 (find-file-noselect file)))
11883 (if (and arg (not (equal arg 3)))
11884 (progn
11885 (org-pop-to-buffer-same-window nbuf)
11886 (goto-char pos)
11887 (org-show-context 'org-goto))
11888 (if regionp
11889 (progn
11890 (org-kill-new (buffer-substring region-start region-end))
11891 (org-save-markers-in-region region-start region-end))
11892 (org-copy-subtree 1 nil t))
11893 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
11894 (find-file-noselect file)))
11895 (setq reversed (org-notes-order-reversed-p))
11896 (save-excursion
11897 (save-restriction
11898 (widen)
11899 (if pos
11900 (progn
11901 (goto-char pos)
11902 (looking-at org-outline-regexp)
11903 (setq level (org-get-valid-level (funcall outline-level) 1))
11904 (goto-char
11905 (if reversed
11906 (or (outline-next-heading) (point-max))
11907 (or (save-excursion (org-get-next-sibling))
11908 (org-end-of-subtree t t)
11909 (point-max)))))
11910 (setq level 1)
11911 (if (not reversed)
11912 (goto-char (point-max))
11913 (goto-char (point-min))
11914 (or (outline-next-heading) (goto-char (point-max)))))
11915 (unless (bolp) (newline))
11916 (org-paste-subtree level nil nil t)
11917 (when org-log-refile
11918 (org-add-log-setup 'refile nil nil org-log-refile)
11919 (unless (eq org-log-refile 'note)
11920 (save-excursion (org-add-log-note))))
11921 (and org-auto-align-tags
11922 (let ((org-loop-over-headlines-in-active-region nil))
11923 (org-set-tags nil t)))
11924 (let ((bookmark-name (plist-get org-bookmark-names-plist
11925 :last-refile)))
11926 (when bookmark-name
11927 (with-demoted-errors
11928 (bookmark-set bookmark-name))))
11929 ;; If we are refiling for capture, make sure that the
11930 ;; last-capture pointers point here
11931 (when (org-bound-and-true-p org-capture-is-refiling)
11932 (let ((bookmark-name (plist-get org-bookmark-names-plist
11933 :last-capture-marker)))
11934 (when bookmark-name
11935 (with-demoted-errors
11936 (bookmark-set bookmark-name))))
11937 (move-marker org-capture-last-stored-marker (point)))
11938 (when (fboundp 'deactivate-mark) (deactivate-mark))
11939 (run-hooks 'org-after-refile-insert-hook))))
11940 (unless org-refile-keep
11941 (if regionp
11942 (delete-region (point) (+ (point) (- region-end region-start)))
11943 (delete-region
11944 (and (org-back-to-heading t) (point))
11945 (min (1+ (buffer-size)) (org-end-of-subtree t t) (point)))))
11946 (when (featurep 'org-inlinetask)
11947 (org-inlinetask-remove-END-maybe))
11948 (setq org-markers-to-move nil)
11949 (message (concat actionmsg " to \"%s\" in file %s: done") (car it) file)))))))
11951 (defun org-refile-goto-last-stored ()
11952 "Go to the location where the last refile was stored."
11953 (interactive)
11954 (bookmark-jump (plist-get org-bookmark-names-plist :last-refile))
11955 (message "This is the location of the last refile"))
11957 (defun org-refile--get-location (refloc tbl)
11958 "When user refile to REFLOC, find the associated target in TBL.
11959 Also check `org-refile-target-table'."
11960 (car (delq
11962 (mapcar
11963 (lambda (r) (or (assoc r tbl)
11964 (assoc r org-refile-target-table)))
11965 (list (replace-regexp-in-string "/$" "" refloc)
11966 (replace-regexp-in-string "\\([^/]\\)$" "\\1/" refloc))))))
11968 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
11969 "Prompt the user for a refile location, using PROMPT.
11970 PROMPT should not be suffixed with a colon and a space, because
11971 this function appends the default value from
11972 `org-refile-history' automatically, if that is not empty."
11973 (let ((org-refile-targets org-refile-targets)
11974 (org-refile-use-outline-path org-refile-use-outline-path))
11975 (setq org-refile-target-table (org-refile-get-targets default-buffer)))
11976 (unless org-refile-target-table
11977 (user-error "No refile targets"))
11978 (let* ((cbuf (current-buffer))
11979 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
11980 (cfunc (if (and org-refile-use-outline-path
11981 org-outline-path-complete-in-steps)
11982 #'org-olpath-completing-read
11983 #'completing-read))
11984 (extra (if org-refile-use-outline-path "/" ""))
11985 (cbnex (concat (buffer-name) extra))
11986 (filename (and cfn (expand-file-name cfn)))
11987 (tbl (mapcar
11988 (lambda (x)
11989 (if (and (not (member org-refile-use-outline-path
11990 '(file full-file-path)))
11991 (not (equal filename (nth 1 x))))
11992 (cons (concat (car x) extra " ("
11993 (file-name-nondirectory (nth 1 x)) ")")
11994 (cdr x))
11995 (cons (concat (car x) extra) (cdr x))))
11996 org-refile-target-table))
11997 (completion-ignore-case t)
11998 cdef
11999 (prompt (concat prompt
12000 (or (and (car org-refile-history)
12001 (concat " (default " (car org-refile-history) ")"))
12002 (and (assoc cbnex tbl) (setq cdef cbnex)
12003 (concat " (default " cbnex ")"))) ": "))
12004 pa answ parent-target child parent old-hist)
12005 (setq old-hist org-refile-history)
12006 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
12007 nil 'org-refile-history (or cdef (car org-refile-history))))
12008 (if (setq pa (org-refile--get-location answ tbl))
12009 (progn
12010 (org-refile-check-position pa)
12011 (when (or (not org-refile-history)
12012 (not (eq old-hist org-refile-history))
12013 (not (equal (car pa) (car org-refile-history))))
12014 (setq org-refile-history
12015 (cons (car pa) (if (assoc (car org-refile-history) tbl)
12016 org-refile-history
12017 (cdr org-refile-history))))
12018 (when (equal (car org-refile-history) (nth 1 org-refile-history))
12019 (pop org-refile-history)))
12021 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
12022 (progn
12023 (setq parent (match-string 1 answ)
12024 child (match-string 2 answ))
12025 (setq parent-target (org-refile--get-location parent tbl))
12026 (when (and parent-target
12027 (or (eq new-nodes t)
12028 (and (eq new-nodes 'confirm)
12029 (y-or-n-p (format "Create new node \"%s\"? "
12030 child)))))
12031 (org-refile-new-child parent-target child)))
12032 (user-error "Invalid target location")))))
12034 (declare-function org-string-nw-p "org-macs" (s))
12035 (defun org-refile-check-position (refile-pointer)
12036 "Check if the refile pointer matches the headline to which it points."
12037 (let* ((file (nth 1 refile-pointer))
12038 (re (nth 2 refile-pointer))
12039 (pos (nth 3 refile-pointer))
12040 buffer)
12041 (if (and (not (markerp pos)) (not file))
12042 (user-error "Please indicate a target file in the refile path")
12043 (when (org-string-nw-p re)
12044 (setq buffer (if (markerp pos)
12045 (marker-buffer pos)
12046 (or (find-buffer-visiting file)
12047 (find-file-noselect file))))
12048 (with-current-buffer buffer
12049 (save-excursion
12050 (save-restriction
12051 (widen)
12052 (goto-char pos)
12053 (beginning-of-line 1)
12054 (unless (org-looking-at-p re)
12055 (user-error "Invalid refile position, please clear the cache with `C-0 C-c C-w' before refiling")))))))))
12057 (defun org-refile-new-child (parent-target child)
12058 "Use refile target PARENT-TARGET to add new CHILD below it."
12059 (unless parent-target
12060 (error "Cannot find parent for new node"))
12061 (let ((file (nth 1 parent-target))
12062 (pos (nth 3 parent-target))
12063 level)
12064 (with-current-buffer (or (find-buffer-visiting file)
12065 (find-file-noselect file))
12066 (save-excursion
12067 (save-restriction
12068 (widen)
12069 (if pos
12070 (goto-char pos)
12071 (goto-char (point-max))
12072 (unless (bolp) (newline)))
12073 (when (looking-at org-outline-regexp)
12074 (setq level (funcall outline-level))
12075 (org-end-of-subtree t t))
12076 (org-back-over-empty-lines)
12077 (insert "\n" (make-string
12078 (if pos (org-get-valid-level level 1) 1) ?*)
12079 " " child "\n")
12080 (beginning-of-line 0)
12081 (list (concat (car parent-target) "/" child) file "" (point)))))))
12083 (defun org-olpath-completing-read (prompt collection &rest args)
12084 "Read an outline path like a file name."
12085 (let ((thetable collection))
12086 (apply #'completing-read
12087 prompt
12088 (lambda (string predicate &optional flag)
12089 (cond
12090 ((eq flag nil) (try-completion string thetable))
12091 ((eq flag t)
12092 (let ((l (length string)))
12093 (mapcar (lambda (x)
12094 (let ((r (substring x l))
12095 (f (if (string-match " ([^)]*)$" x)
12096 (match-string 0 x)
12097 "")))
12098 (if (string-match "/" r)
12099 (concat string (substring r 0 (match-end 0)) f)
12100 x)))
12101 (all-completions string thetable predicate))))
12102 ;; Exact match?
12103 ((eq flag 'lambda) (assoc string thetable))))
12104 args)))
12106 ;;;; Dynamic blocks
12108 (defun org-find-dblock (name)
12109 "Find the first dynamic block with name NAME in the buffer.
12110 If not found, stay at current position and return nil."
12111 (let ((case-fold-search t) pos)
12112 (save-excursion
12113 (goto-char (point-min))
12114 (setq pos (and (re-search-forward
12115 (concat "^[ \t]*#\\+\\(?:BEGIN\\|begin\\):[ \t]+" name "\\>") nil t)
12116 (match-beginning 0))))
12117 (when pos (goto-char pos))
12118 pos))
12120 (defun org-create-dblock (plist)
12121 "Create a dynamic block section, with parameters taken from PLIST.
12122 PLIST must contain a :name entry which is used as the name of the block."
12123 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
12124 (end-of-line 1)
12125 (newline))
12126 (let ((col (current-column))
12127 (name (plist-get plist :name)))
12128 (insert "#+BEGIN: " name)
12129 (while plist
12130 (if (eq (car plist) :name)
12131 (setq plist (cddr plist))
12132 (insert " " (prin1-to-string (pop plist)))))
12133 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
12134 (beginning-of-line -2)))
12136 (defun org-prepare-dblock ()
12137 "Prepare dynamic block for refresh.
12138 This empties the block, puts the cursor at the insert position and returns
12139 the property list including an extra property :name with the block name."
12140 (unless (looking-at org-dblock-start-re)
12141 (user-error "Not at a dynamic block"))
12142 (let* ((begdel (1+ (match-end 0)))
12143 (name (org-no-properties (match-string 1)))
12144 (params (append (list :name name)
12145 (read (concat "(" (match-string 3) ")")))))
12146 (save-excursion
12147 (beginning-of-line 1)
12148 (skip-chars-forward " \t")
12149 (setq params (plist-put params :indentation-column (current-column))))
12150 (unless (re-search-forward org-dblock-end-re nil t)
12151 (error "Dynamic block not terminated"))
12152 (setq params
12153 (append params
12154 (list :content (buffer-substring
12155 begdel (match-beginning 0)))))
12156 (delete-region begdel (match-beginning 0))
12157 (goto-char begdel)
12158 (open-line 1)
12159 params))
12161 (defun org-map-dblocks (&optional command)
12162 "Apply COMMAND to all dynamic blocks in the current buffer.
12163 If COMMAND is not given, use `org-update-dblock'."
12164 (let ((cmd (or command 'org-update-dblock)))
12165 (save-excursion
12166 (goto-char (point-min))
12167 (while (re-search-forward org-dblock-start-re nil t)
12168 (goto-char (match-beginning 0))
12169 (save-excursion
12170 (condition-case nil
12171 (funcall cmd)
12172 (error (message "Error during update of dynamic block"))))
12173 (unless (re-search-forward org-dblock-end-re nil t)
12174 (error "Dynamic block not terminated"))))))
12176 (defun org-dblock-update (&optional arg)
12177 "User command for updating dynamic blocks.
12178 Update the dynamic block at point. With prefix ARG, update all dynamic
12179 blocks in the buffer."
12180 (interactive "P")
12181 (if arg
12182 (org-update-all-dblocks)
12183 (or (looking-at org-dblock-start-re)
12184 (org-beginning-of-dblock))
12185 (org-update-dblock)))
12187 (defun org-update-dblock ()
12188 "Update the dynamic block at point.
12189 This means to empty the block, parse for parameters and then call
12190 the correct writing function."
12191 (interactive)
12192 (save-excursion
12193 (let* ((win (selected-window))
12194 (pos (point))
12195 (line (org-current-line))
12196 (params (org-prepare-dblock))
12197 (name (plist-get params :name))
12198 (indent (plist-get params :indentation-column))
12199 (cmd (intern (concat "org-dblock-write:" name))))
12200 (message "Updating dynamic block `%s' at line %d..." name line)
12201 (funcall cmd params)
12202 (message "Updating dynamic block `%s' at line %d...done" name line)
12203 (goto-char pos)
12204 (when (and indent (> indent 0))
12205 (setq indent (make-string indent ?\ ))
12206 (save-excursion
12207 (select-window win)
12208 (org-beginning-of-dblock)
12209 (forward-line 1)
12210 (while (not (looking-at org-dblock-end-re))
12211 (insert indent)
12212 (beginning-of-line 2))
12213 (when (looking-at org-dblock-end-re)
12214 (and (looking-at "[ \t]+")
12215 (replace-match ""))
12216 (insert indent)))))))
12218 (defun org-beginning-of-dblock ()
12219 "Find the beginning of the dynamic block at point.
12220 Error if there is no such block at point."
12221 (let ((pos (point))
12222 beg)
12223 (end-of-line 1)
12224 (if (and (re-search-backward org-dblock-start-re nil t)
12225 (setq beg (match-beginning 0))
12226 (re-search-forward org-dblock-end-re nil t)
12227 (> (match-end 0) pos))
12228 (goto-char beg)
12229 (goto-char pos)
12230 (error "Not in a dynamic block"))))
12232 (defun org-update-all-dblocks ()
12233 "Update all dynamic blocks in the buffer.
12234 This function can be used in a hook."
12235 (interactive)
12236 (when (derived-mode-p 'org-mode)
12237 (org-map-dblocks 'org-update-dblock)))
12240 ;;;; Completion
12242 (declare-function org-export-backend-name "org-export" (cl-x))
12243 (declare-function org-export-backend-options "org-export" (cl-x))
12244 (defun org-get-export-keywords ()
12245 "Return a list of all currently understood export keywords.
12246 Export keywords include options, block names, attributes and
12247 keywords relative to each registered export back-end."
12248 (let (keywords)
12249 (dolist (backend
12250 (org-bound-and-true-p org-export-registered-backends)
12251 (delq nil keywords))
12252 ;; Back-end name (for keywords, like #+LATEX:)
12253 (push (upcase (symbol-name (org-export-backend-name backend))) keywords)
12254 (dolist (option-entry (org-export-backend-options backend))
12255 ;; Back-end options.
12256 (push (nth 1 option-entry) keywords)))))
12258 (defconst org-options-keywords
12259 '("ARCHIVE:" "AUTHOR:" "BIND:" "CATEGORY:" "COLUMNS:" "CREATOR:" "DATE:"
12260 "DESCRIPTION:" "DRAWERS:" "EMAIL:" "EXCLUDE_TAGS:" "FILETAGS:" "INCLUDE:"
12261 "INDEX:" "KEYWORDS:" "LANGUAGE:" "MACRO:" "OPTIONS:" "PROPERTY:"
12262 "PRIORITIES:" "SELECT_TAGS:" "SEQ_TODO:" "SETUPFILE:" "STARTUP:" "TAGS:"
12263 "TITLE:" "TODO:" "TYP_TODO:" "SELECT_TAGS:" "EXCLUDE_TAGS:"))
12265 (defcustom org-structure-template-alist
12266 '(("s" "#+BEGIN_SRC ?\n\n#+END_SRC")
12267 ("e" "#+BEGIN_EXAMPLE\n?\n#+END_EXAMPLE")
12268 ("q" "#+BEGIN_QUOTE\n?\n#+END_QUOTE")
12269 ("v" "#+BEGIN_VERSE\n?\n#+END_VERSE")
12270 ("V" "#+BEGIN_VERBATIM\n?\n#+END_VERBATIM")
12271 ("c" "#+BEGIN_CENTER\n?\n#+END_CENTER")
12272 ("l" "#+BEGIN_EXPORT latex\n?\n#+END_EXPORT")
12273 ("L" "#+LaTeX: ")
12274 ("h" "#+BEGIN_EXPORT html\n?\n#+END_EXPORT")
12275 ("H" "#+HTML: ")
12276 ("a" "#+BEGIN_EXPORT ascii\n?\n#+END_EXPORT")
12277 ("A" "#+ASCII: ")
12278 ("i" "#+INDEX: ?")
12279 ("I" "#+INCLUDE: %file ?"))
12280 "Structure completion elements.
12281 This is a list of abbreviation keys and values. The value gets inserted
12282 if you type `<' followed by the key and then press the completion key,
12283 usually `TAB'. %file will be replaced by a file name after prompting
12284 for the file using completion. The cursor will be placed at the position
12285 of the `?' in the template.
12286 There are two templates for each key, the first uses the original Org syntax,
12287 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
12288 the default when the /org-mtags.el/ module has been loaded. See also the
12289 variable `org-mtags-prefer-muse-templates'."
12290 :group 'org-completion
12291 :type '(repeat
12292 (list
12293 (string :tag "Key")
12294 (string :tag "Template")))
12295 :version "25.1"
12296 :package-version '(Org . "8.3"))
12298 (defun org-try-structure-completion ()
12299 "Try to complete a structure template before point.
12300 This looks for strings like \"<e\" on an otherwise empty line and
12301 expands them."
12302 (let ((l (buffer-substring (point-at-bol) (point)))
12304 (when (and (looking-at "[ \t]*$")
12305 (string-match "^[ \t]*<\\([a-zA-Z]+\\)$" l)
12306 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
12307 (org-complete-expand-structure-template (+ -1 (point-at-bol)
12308 (match-beginning 1)) a)
12309 t)))
12311 (defun org-complete-expand-structure-template (start cell)
12312 "Expand a structure template."
12313 (let ((rpl (nth 1 cell))
12314 (ind ""))
12315 (delete-region start (point))
12316 (when (string-match "\\`[ \t]*#\\+" rpl)
12317 (cond
12318 ((bolp))
12319 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
12320 (setq ind (buffer-substring (point-at-bol) (point))))
12321 (t (newline))))
12322 (setq start (point))
12323 (when (string-match "%file" rpl)
12324 (setq rpl (replace-match
12325 (concat
12326 "\""
12327 (save-match-data
12328 (abbreviate-file-name (read-file-name "Include file: ")))
12329 "\"")
12330 t t rpl)))
12331 (setq rpl (mapconcat 'identity (split-string rpl "\n")
12332 (concat "\n" ind)))
12333 (insert rpl)
12334 (when (re-search-backward "\\?" start t) (delete-char 1))))
12336 ;;;; TODO, DEADLINE, Comments
12338 (defun org-toggle-comment ()
12339 "Change the COMMENT state of an entry."
12340 (interactive)
12341 (save-excursion
12342 (org-back-to-heading)
12343 (looking-at org-complex-heading-regexp)
12344 (goto-char (or (match-end 3) (match-end 2) (match-end 1)))
12345 (skip-chars-forward " \t")
12346 (unless (memq (char-before) '(?\s ?\t)) (insert " "))
12347 (if (org-in-commented-heading-p t)
12348 (delete-region (point)
12349 (progn (search-forward " " (line-end-position) 'move)
12350 (skip-chars-forward " \t")
12351 (point)))
12352 (insert org-comment-string)
12353 (unless (eolp) (insert " ")))))
12355 (defvar org-last-todo-state-is-todo nil
12356 "This is non-nil when the last TODO state change led to a TODO state.
12357 If the last change removed the TODO tag or switched to DONE, then
12358 this is nil.")
12360 (defvar org-setting-tags nil) ; dynamically skipped
12362 (defvar org-todo-setup-filter-hook nil
12363 "Hook for functions that pre-filter todo specs.
12364 Each function takes a todo spec and returns either nil or the spec
12365 transformed into canonical form." )
12367 (defvar org-todo-get-default-hook nil
12368 "Hook for functions that get a default item for todo.
12369 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
12370 nil or a string to be used for the todo mark." )
12372 (defvar org-agenda-headline-snapshot-before-repeat)
12374 (defun org-current-effective-time ()
12375 "Return current time adjusted for `org-extend-today-until' variable."
12376 (let* ((ct (org-current-time))
12377 (dct (decode-time ct))
12378 (ct1
12379 (cond
12380 (org-use-last-clock-out-time-as-effective-time
12381 (or (org-clock-get-last-clock-out-time) ct))
12382 ((and org-use-effective-time (< (nth 2 dct) org-extend-today-until))
12383 (encode-time 0 59 23 (1- (nth 3 dct)) (nth 4 dct) (nth 5 dct)))
12384 (t ct))))
12385 ct1))
12387 (defun org-todo-yesterday (&optional arg)
12388 "Like `org-todo' but the time of change will be 23:59 of yesterday."
12389 (interactive "P")
12390 (if (eq major-mode 'org-agenda-mode)
12391 (apply 'org-agenda-todo-yesterday arg)
12392 (let* ((org-use-effective-time t)
12393 (hour (nth 2 (decode-time (org-current-time))))
12394 (org-extend-today-until (1+ hour)))
12395 (org-todo arg))))
12397 (defvar org-block-entry-blocking ""
12398 "First entry preventing the TODO state change.")
12400 (defun org-cancel-repeater ()
12401 "Cancel a repeater by setting its numeric value to zero."
12402 (interactive)
12403 (save-excursion
12404 (org-back-to-heading t)
12405 (let ((bound1 (point))
12406 (bound0 (save-excursion (outline-next-heading) (point))))
12407 (when (and (re-search-forward
12408 (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
12409 org-deadline-time-regexp "\\)\\|\\("
12410 org-ts-regexp "\\)")
12411 bound0 t)
12412 (re-search-backward "[ \t]+\\(?:[.+]\\)?\\+\\([0-9]+\\)[hdwmy]"
12413 bound1 t))
12414 (replace-match "0" t nil nil 1)))))
12416 (defvar org-state) ;; dynamically scoped into this function
12417 (defun org-todo (&optional arg)
12418 "Change the TODO state of an item.
12419 The state of an item is given by a keyword at the start of the heading,
12420 like
12421 *** TODO Write paper
12422 *** DONE Call mom
12424 The different keywords are specified in the variable `org-todo-keywords'.
12425 By default the available states are \"TODO\" and \"DONE\".
12426 So for this example: when the item starts with TODO, it is changed to DONE.
12427 When it starts with DONE, the DONE is removed. And when neither TODO nor
12428 DONE are present, add TODO at the beginning of the heading.
12430 With \\[universal-argument] prefix arg, use completion to determine the new \
12431 state.
12432 With numeric prefix arg, switch to that state.
12433 With a double \\[universal-argument] prefix, switch to the next set of TODO \
12434 keywords (nextset).
12435 With a triple \\[universal-argument] prefix, circumvent any state blocking.
12436 With a numeric prefix arg of 0, inhibit note taking for the change.
12437 With a numeric prefix arg of -1, cancel repeater to allow marking as DONE.
12439 When called through ELisp, arg is also interpreted in the following way:
12440 `none' -> empty state
12441 \"\"(empty string) -> switch to empty state
12442 `done' -> switch to DONE
12443 `nextset' -> switch to the next set of keywords
12444 `previousset' -> switch to the previous set of keywords
12445 \"WAITING\" -> switch to the specified keyword, but only if it
12446 really is a member of `org-todo-keywords'."
12447 (interactive "P")
12448 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
12449 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
12450 'region-start-level 'region))
12451 org-loop-over-headlines-in-active-region)
12452 (org-map-entries
12453 `(org-todo ,arg)
12454 org-loop-over-headlines-in-active-region
12455 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
12456 (when (equal arg '(16)) (setq arg 'nextset))
12457 (when (equal arg -1) (org-cancel-repeater) (setq arg nil))
12458 (let ((org-blocker-hook org-blocker-hook)
12459 commentp
12460 case-fold-search)
12461 (when (equal arg '(64))
12462 (setq arg nil org-blocker-hook nil))
12463 (when (and org-blocker-hook
12464 (or org-inhibit-blocking
12465 (org-entry-get nil "NOBLOCKING")))
12466 (setq org-blocker-hook nil))
12467 (save-excursion
12468 (catch 'exit
12469 (org-back-to-heading t)
12470 (when (org-in-commented-heading-p t)
12471 (org-toggle-comment)
12472 (setq commentp t))
12473 (when (looking-at org-outline-regexp) (goto-char (1- (match-end 0))))
12474 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|[ \t]*$\\)"))
12475 (looking-at "\\(?: *\\|[ \t]*$\\)"))
12476 (let* ((match-data (match-data))
12477 (startpos (point-at-bol))
12478 (logging (save-match-data (org-entry-get nil "LOGGING" t t)))
12479 (org-log-done org-log-done)
12480 (org-log-repeat org-log-repeat)
12481 (org-todo-log-states org-todo-log-states)
12482 (org-inhibit-logging
12483 (if (equal arg 0)
12484 (progn (setq arg nil) 'note) org-inhibit-logging))
12485 (this (match-string 1))
12486 (hl-pos (match-beginning 0))
12487 (head (org-get-todo-sequence-head this))
12488 (ass (assoc head org-todo-kwd-alist))
12489 (interpret (nth 1 ass))
12490 (done-word (nth 3 ass))
12491 (final-done-word (nth 4 ass))
12492 (org-last-state (or this ""))
12493 (completion-ignore-case t)
12494 (member (member this org-todo-keywords-1))
12495 (tail (cdr member))
12496 (org-state (cond
12497 ((and org-todo-key-trigger
12498 (or (and (equal arg '(4))
12499 (eq org-use-fast-todo-selection 'prefix))
12500 (and (not arg) org-use-fast-todo-selection
12501 (not (eq org-use-fast-todo-selection
12502 'prefix)))))
12503 ;; Use fast selection
12504 (org-fast-todo-selection))
12505 ((and (equal arg '(4))
12506 (or (not org-use-fast-todo-selection)
12507 (not org-todo-key-trigger)))
12508 ;; Read a state with completion
12509 (completing-read
12510 "State: " (mapcar #'list org-todo-keywords-1)
12511 nil t))
12512 ((eq arg 'right)
12513 (if this
12514 (if tail (car tail) nil)
12515 (car org-todo-keywords-1)))
12516 ((eq arg 'left)
12517 (unless (equal member org-todo-keywords-1)
12518 (if this
12519 (nth (- (length org-todo-keywords-1)
12520 (length tail) 2)
12521 org-todo-keywords-1)
12522 (org-last org-todo-keywords-1))))
12523 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
12524 (setq arg nil))) ; hack to fall back to cycling
12525 (arg
12526 ;; user or caller requests a specific state
12527 (cond
12528 ((equal arg "") nil)
12529 ((eq arg 'none) nil)
12530 ((eq arg 'done) (or done-word (car org-done-keywords)))
12531 ((eq arg 'nextset)
12532 (or (car (cdr (member head org-todo-heads)))
12533 (car org-todo-heads)))
12534 ((eq arg 'previousset)
12535 (let ((org-todo-heads (reverse org-todo-heads)))
12536 (or (car (cdr (member head org-todo-heads)))
12537 (car org-todo-heads))))
12538 ((car (member arg org-todo-keywords-1)))
12539 ((stringp arg)
12540 (user-error "State `%s' not valid in this file" arg))
12541 ((nth (1- (prefix-numeric-value arg))
12542 org-todo-keywords-1))))
12543 ((null member) (or head (car org-todo-keywords-1)))
12544 ((equal this final-done-word) nil) ;; -> make empty
12545 ((null tail) nil) ;; -> first entry
12546 ((memq interpret '(type priority))
12547 (if (eq this-command last-command)
12548 (car tail)
12549 (if (> (length tail) 0)
12550 (or done-word (car org-done-keywords))
12551 nil)))
12553 (car tail))))
12554 (org-state (or
12555 (run-hook-with-args-until-success
12556 'org-todo-get-default-hook org-state org-last-state)
12557 org-state))
12558 (next (if org-state (concat " " org-state " ") " "))
12559 (change-plist (list :type 'todo-state-change :from this :to org-state
12560 :position startpos))
12561 dolog now-done-p)
12562 (when org-blocker-hook
12563 (setq org-last-todo-state-is-todo
12564 (not (member this org-done-keywords)))
12565 (unless (save-excursion
12566 (save-match-data
12567 (org-with-wide-buffer
12568 (run-hook-with-args-until-failure
12569 'org-blocker-hook change-plist))))
12570 (if (org-called-interactively-p 'interactive)
12571 (user-error "TODO state change from %s to %s blocked (by \"%s\")"
12572 this org-state org-block-entry-blocking)
12573 ;; fail silently
12574 (message "TODO state change from %s to %s blocked (by \"%s\")"
12575 this org-state org-block-entry-blocking)
12576 (throw 'exit nil))))
12577 (store-match-data match-data)
12578 (replace-match next t t)
12579 (cond ((equal this org-state)
12580 (message "TODO state was already %s" (org-trim next)))
12581 ((pos-visible-in-window-p hl-pos)
12582 (message "TODO state changed to %s" (org-trim next))))
12583 (unless head
12584 (setq head (org-get-todo-sequence-head org-state)
12585 ass (assoc head org-todo-kwd-alist)
12586 interpret (nth 1 ass)
12587 done-word (nth 3 ass)
12588 final-done-word (nth 4 ass)))
12589 (when (memq arg '(nextset previousset))
12590 (message "Keyword-Set %d/%d: %s"
12591 (- (length org-todo-sets) -1
12592 (length (memq (assoc org-state org-todo-sets) org-todo-sets)))
12593 (length org-todo-sets)
12594 (mapconcat 'identity (assoc org-state org-todo-sets) " ")))
12595 (setq org-last-todo-state-is-todo
12596 (not (member org-state org-done-keywords)))
12597 (setq now-done-p (and (member org-state org-done-keywords)
12598 (not (member this org-done-keywords))))
12599 (and logging (org-local-logging logging))
12600 (when (and (or org-todo-log-states org-log-done)
12601 (not (eq org-inhibit-logging t))
12602 (not (memq arg '(nextset previousset))))
12603 ;; we need to look at recording a time and note
12604 (setq dolog (or (nth 1 (assoc org-state org-todo-log-states))
12605 (nth 2 (assoc this org-todo-log-states))))
12606 (when (and (eq dolog 'note) (eq org-inhibit-logging 'note))
12607 (setq dolog 'time))
12608 (when (or (and (not org-state) (not org-closed-keep-when-no-todo))
12609 (and org-state
12610 (member org-state org-not-done-keywords)
12611 (not (member this org-not-done-keywords))))
12612 ;; This is now a todo state and was not one before
12613 ;; If there was a CLOSED time stamp, get rid of it.
12614 (org-add-planning-info nil nil 'closed))
12615 (when (and now-done-p org-log-done)
12616 ;; It is now done, and it was not done before
12617 (org-add-planning-info 'closed (org-current-effective-time))
12618 (when (and (not dolog) (eq 'note org-log-done))
12619 (org-add-log-setup 'done org-state this 'note)))
12620 (when (and org-state dolog)
12621 ;; This is a non-nil state, and we need to log it
12622 (org-add-log-setup 'state org-state this dolog)))
12623 ;; Fixup tag positioning
12624 (org-todo-trigger-tag-changes org-state)
12625 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
12626 (when org-provide-todo-statistics
12627 (org-update-parent-todo-statistics))
12628 (run-hooks 'org-after-todo-state-change-hook)
12629 (when (and arg (not (member org-state org-done-keywords)))
12630 (setq head (org-get-todo-sequence-head org-state)))
12631 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
12632 ;; Do we need to trigger a repeat?
12633 (when now-done-p
12634 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
12635 ;; This is for the agenda, take a snapshot of the headline.
12636 (save-match-data
12637 (setq org-agenda-headline-snapshot-before-repeat
12638 (org-get-heading))))
12639 (org-auto-repeat-maybe org-state))
12640 ;; Fixup cursor location if close to the keyword
12641 (when (and (outline-on-heading-p)
12642 (not (bolp))
12643 (save-excursion (beginning-of-line 1)
12644 (looking-at org-todo-line-regexp))
12645 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
12646 (goto-char (or (match-end 2) (match-end 1)))
12647 (and (looking-at " ") (just-one-space)))
12648 (when org-trigger-hook
12649 (save-excursion
12650 (run-hook-with-args 'org-trigger-hook change-plist)))
12651 (when commentp (org-toggle-comment))))))))
12653 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
12654 "Block turning an entry into a TODO, using the hierarchy.
12655 This checks whether the current task should be blocked from state
12656 changes. Such blocking occurs when:
12658 1. The task has children which are not all in a completed state.
12660 2. A task has a parent with the property :ORDERED:, and there
12661 are siblings prior to the current task with incomplete
12662 status.
12664 3. The parent of the task is blocked because it has siblings that should
12665 be done first, or is child of a block grandparent TODO entry."
12667 (if (not org-enforce-todo-dependencies)
12668 t ; if locally turned off don't block
12669 (catch 'dont-block
12670 ;; If this is not a todo state change, or if this entry is already DONE,
12671 ;; do not block
12672 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12673 (member (plist-get change-plist :from)
12674 (cons 'done org-done-keywords))
12675 (member (plist-get change-plist :to)
12676 (cons 'todo org-not-done-keywords))
12677 (not (plist-get change-plist :to)))
12678 (throw 'dont-block t))
12679 ;; If this task has children, and any are undone, it's blocked
12680 (save-excursion
12681 (org-back-to-heading t)
12682 (let ((this-level (funcall outline-level)))
12683 (outline-next-heading)
12684 (let ((child-level (funcall outline-level)))
12685 (while (and (not (eobp))
12686 (> child-level this-level))
12687 ;; this todo has children, check whether they are all
12688 ;; completed
12689 (when (and (not (org-entry-is-done-p))
12690 (org-entry-is-todo-p))
12691 (setq org-block-entry-blocking (org-get-heading))
12692 (throw 'dont-block nil))
12693 (outline-next-heading)
12694 (setq child-level (funcall outline-level))))))
12695 ;; Otherwise, if the task's parent has the :ORDERED: property, and
12696 ;; any previous siblings are undone, it's blocked
12697 (save-excursion
12698 (org-back-to-heading t)
12699 (let* ((pos (point))
12700 (parent-pos (and (org-up-heading-safe) (point))))
12701 (unless parent-pos (throw 'dont-block t)) ; no parent
12702 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12703 (forward-line 1)
12704 (re-search-forward org-not-done-heading-regexp pos t))
12705 (setq org-block-entry-blocking (match-string 0))
12706 (throw 'dont-block nil)) ; block, there is an older sibling not done.
12707 ;; Search further up the hierarchy, to see if an ancestor is blocked
12708 (while t
12709 (goto-char parent-pos)
12710 (unless (looking-at org-not-done-heading-regexp)
12711 (throw 'dont-block t)) ; do not block, parent is not a TODO
12712 (setq pos (point))
12713 (setq parent-pos (and (org-up-heading-safe) (point)))
12714 (unless parent-pos (throw 'dont-block t)) ; no parent
12715 (when (and (org-not-nil (org-entry-get (point) "ORDERED"))
12716 (forward-line 1)
12717 (re-search-forward org-not-done-heading-regexp pos t)
12718 (setq org-block-entry-blocking (org-get-heading)))
12719 (throw 'dont-block nil)))))))) ; block, older sibling not done.
12721 (defcustom org-track-ordered-property-with-tag nil
12722 "Should the ORDERED property also be shown as a tag?
12723 The ORDERED property decides if an entry should require subtasks to be
12724 completed in sequence. Since a property is not very visible, setting
12725 this option means that toggling the ORDERED property with the command
12726 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
12727 not relevant for the behavior, but it makes things more visible.
12729 Note that toggling the tag with tags commands will not change the property
12730 and therefore not influence behavior!
12732 This can be t, meaning the tag ORDERED should be used, It can also be a
12733 string to select a different tag for this task."
12734 :group 'org-todo
12735 :type '(choice
12736 (const :tag "No tracking" nil)
12737 (const :tag "Track with ORDERED tag" t)
12738 (string :tag "Use other tag")))
12740 (defun org-toggle-ordered-property ()
12741 "Toggle the ORDERED property of the current entry.
12742 For better visibility, you can track the value of this property with a tag.
12743 See variable `org-track-ordered-property-with-tag'."
12744 (interactive)
12745 (let* ((t1 org-track-ordered-property-with-tag)
12746 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
12747 (save-excursion
12748 (org-back-to-heading)
12749 (if (org-entry-get nil "ORDERED")
12750 (progn
12751 (org-delete-property "ORDERED")
12752 (and tag (org-toggle-tag tag 'off))
12753 (message "Subtasks can be completed in arbitrary order"))
12754 (org-entry-put nil "ORDERED" "t")
12755 (and tag (org-toggle-tag tag 'on))
12756 (message "Subtasks must be completed in sequence")))))
12758 (defvar org-blocked-by-checkboxes) ; dynamically scoped
12759 (defun org-block-todo-from-checkboxes (change-plist)
12760 "Block turning an entry into a TODO, using checkboxes.
12761 This checks whether the current task should be blocked from state
12762 changes because there are unchecked boxes in this entry."
12763 (if (not org-enforce-todo-checkbox-dependencies)
12764 t ; if locally turned off don't block
12765 (catch 'dont-block
12766 ;; If this is not a todo state change, or if this entry is already DONE,
12767 ;; do not block
12768 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
12769 (member (plist-get change-plist :from)
12770 (cons 'done org-done-keywords))
12771 (member (plist-get change-plist :to)
12772 (cons 'todo org-not-done-keywords))
12773 (not (plist-get change-plist :to)))
12774 (throw 'dont-block t))
12775 ;; If this task has checkboxes that are not checked, it's blocked
12776 (save-excursion
12777 (org-back-to-heading t)
12778 (let ((beg (point)) end)
12779 (outline-next-heading)
12780 (setq end (point))
12781 (goto-char beg)
12782 (when (org-list-search-forward
12783 (concat (org-item-beginning-re)
12784 "\\(?:\\[@\\(?:start:\\)?\\([0-9]+\\|[A-Za-z]\\)\\][ \t]*\\)?"
12785 "\\[[- ]\\]")
12786 end t)
12787 (when (boundp 'org-blocked-by-checkboxes)
12788 (setq org-blocked-by-checkboxes t))
12789 (throw 'dont-block nil))))
12790 t))) ; do not block
12792 (defun org-entry-blocked-p ()
12793 "Non-nil if entry at point is blocked."
12794 (and (not (org-entry-get nil "NOBLOCKING"))
12795 (member (org-entry-get nil "TODO") org-not-done-keywords)
12796 (not (run-hook-with-args-until-failure
12797 'org-blocker-hook
12798 (list :type 'todo-state-change
12799 :position (point)
12800 :from 'todo
12801 :to 'done)))))
12803 (defun org-update-statistics-cookies (all)
12804 "Update the statistics cookie, either from TODO or from checkboxes.
12805 This should be called with the cursor in a line with a statistics cookie."
12806 (interactive "P")
12807 (if all
12808 (progn
12809 (org-update-checkbox-count 'all)
12810 (org-map-entries 'org-update-parent-todo-statistics))
12811 (if (not (org-at-heading-p))
12812 (org-update-checkbox-count)
12813 (let ((pos (point-marker))
12814 end l1 l2)
12815 (ignore-errors (org-back-to-heading t))
12816 (if (not (org-at-heading-p))
12817 (org-update-checkbox-count)
12818 (setq l1 (org-outline-level))
12819 (setq end (save-excursion
12820 (outline-next-heading)
12821 (when (org-at-heading-p) (setq l2 (org-outline-level)))
12822 (point)))
12823 (if (and (save-excursion
12824 (re-search-forward
12825 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
12826 (not (save-excursion (re-search-forward
12827 ":COOKIE_DATA:.*\\<todo\\>" end t))))
12828 (org-update-checkbox-count)
12829 (if (and l2 (> l2 l1))
12830 (progn
12831 (goto-char end)
12832 (org-update-parent-todo-statistics))
12833 (goto-char pos)
12834 (beginning-of-line 1)
12835 (while (re-search-forward
12836 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
12837 (point-at-eol) t)
12838 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
12839 (goto-char pos)
12840 (move-marker pos nil)))))
12842 (defvar org-entry-property-inherited-from) ;; defined below
12843 (defun org-update-parent-todo-statistics ()
12844 "Update any statistics cookie in the parent of the current headline.
12845 When `org-hierarchical-todo-statistics' is nil, statistics will cover
12846 the entire subtree and this will travel up the hierarchy and update
12847 statistics everywhere."
12848 (let* ((prop (save-excursion (org-up-heading-safe)
12849 (org-entry-get nil "COOKIE_DATA" 'inherit)))
12850 (recursive (or (not org-hierarchical-todo-statistics)
12851 (and prop (string-match "\\<recursive\\>" prop))))
12852 (lim (or (and prop (marker-position org-entry-property-inherited-from))
12854 (first t)
12855 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
12856 level ltoggle l1 new ndel
12857 (cnt-all 0) (cnt-done 0) is-percent kwd
12858 checkbox-beg ov ovs ove cookie-present)
12859 (catch 'exit
12860 (save-excursion
12861 (beginning-of-line 1)
12862 (setq ltoggle (funcall outline-level))
12863 ;; Three situations are to consider:
12865 ;; 1. if `org-hierarchical-todo-statistics' is nil, repeat up
12866 ;; to the top-level ancestor on the headline;
12868 ;; 2. If parent has "recursive" property, repeat up to the
12869 ;; headline setting that property, taking inheritance into
12870 ;; account;
12872 ;; 3. Else, move up to direct parent and proceed only once.
12873 (while (and (setq level (org-up-heading-safe))
12874 (or recursive first)
12875 (>= (point) lim))
12876 (setq first nil cookie-present nil)
12877 (unless (and level
12878 (not (string-match
12879 "\\<checkbox\\>"
12880 (downcase (or (org-entry-get nil "COOKIE_DATA")
12881 "")))))
12882 (throw 'exit nil))
12883 (while (re-search-forward box-re (point-at-eol) t)
12884 (setq cnt-all 0 cnt-done 0 cookie-present t)
12885 (setq is-percent (match-end 2) checkbox-beg (match-beginning 0))
12886 (save-match-data
12887 (unless (outline-next-heading) (throw 'exit nil))
12888 (while (and (looking-at org-complex-heading-regexp)
12889 (> (setq l1 (length (match-string 1))) level))
12890 (setq kwd (and (or recursive (= l1 ltoggle))
12891 (match-string 2)))
12892 (if (or (eq org-provide-todo-statistics 'all-headlines)
12893 (and (eq org-provide-todo-statistics t)
12894 (or (member kwd org-done-keywords)))
12895 (and (listp org-provide-todo-statistics)
12896 (stringp (car org-provide-todo-statistics))
12897 (or (member kwd org-provide-todo-statistics)
12898 (member kwd org-done-keywords)))
12899 (and (listp org-provide-todo-statistics)
12900 (listp (car org-provide-todo-statistics))
12901 (or (member kwd (car org-provide-todo-statistics))
12902 (and (member kwd org-done-keywords)
12903 (member kwd (cadr org-provide-todo-statistics))))))
12904 (setq cnt-all (1+ cnt-all))
12905 (and (eq org-provide-todo-statistics t)
12907 (setq cnt-all (1+ cnt-all))))
12908 (when (or (and (member org-provide-todo-statistics '(t all-headlines))
12909 (member kwd org-done-keywords))
12910 (and (listp org-provide-todo-statistics)
12911 (listp (car org-provide-todo-statistics))
12912 (member kwd org-done-keywords)
12913 (member kwd (cadr org-provide-todo-statistics)))
12914 (and (listp org-provide-todo-statistics)
12915 (stringp (car org-provide-todo-statistics))
12916 (member kwd org-done-keywords)))
12917 (setq cnt-done (1+ cnt-done)))
12918 (outline-next-heading)))
12919 (setq new
12920 (if is-percent
12921 (format "[%d%%]" (floor (* 100.0 cnt-done)
12922 (max 1 cnt-all)))
12923 (format "[%d/%d]" cnt-done cnt-all))
12924 ndel (- (match-end 0) checkbox-beg))
12925 ;; handle overlays when updating cookie from column view
12926 (when (setq ov (car (overlays-at checkbox-beg)))
12927 (setq ovs (overlay-start ov) ove (overlay-end ov))
12928 (delete-overlay ov))
12929 (goto-char checkbox-beg)
12930 (insert new)
12931 (delete-region (point) (+ (point) ndel))
12932 (when org-auto-align-tags (org-fix-tags-on-the-fly))
12933 (when ov (move-overlay ov ovs ove)))
12934 (when cookie-present
12935 (run-hook-with-args 'org-after-todo-statistics-hook
12936 cnt-done (- cnt-all cnt-done))))))
12937 (run-hooks 'org-todo-statistics-hook)))
12939 (defvar org-after-todo-statistics-hook nil
12940 "Hook that is called after a TODO statistics cookie has been updated.
12941 Each function is called with two arguments: the number of not-done entries
12942 and the number of done entries.
12944 For example, the following function, when added to this hook, will switch
12945 an entry to DONE when all children are done, and back to TODO when new
12946 entries are set to a TODO status. Note that this hook is only called
12947 when there is a statistics cookie in the headline!
12949 \(defun org-summary-todo (n-done n-not-done)
12950 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
12951 \(let (org-log-done org-log-states) ; turn off logging
12952 \(org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
12955 (defvar org-todo-statistics-hook nil
12956 "Hook that is run whenever Org thinks TODO statistics should be updated.
12957 This hook runs even if there is no statistics cookie present, in which case
12958 `org-after-todo-statistics-hook' would not run.")
12960 (defun org-todo-trigger-tag-changes (state)
12961 "Apply the changes defined in `org-todo-state-tags-triggers'."
12962 (let ((l org-todo-state-tags-triggers)
12963 changes)
12964 (when (or (not state) (equal state ""))
12965 (setq changes (append changes (cdr (assoc "" l)))))
12966 (when (and (stringp state) (> (length state) 0))
12967 (setq changes (append changes (cdr (assoc state l)))))
12968 (when (member state org-not-done-keywords)
12969 (setq changes (append changes (cdr (assoc 'todo l)))))
12970 (when (member state org-done-keywords)
12971 (setq changes (append changes (cdr (assoc 'done l)))))
12972 (dolist (c changes)
12973 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
12975 (defun org-local-logging (value)
12976 "Get logging settings from a property VALUE."
12977 ;; Directly set the variables, they are already local.
12978 (setq org-log-done nil
12979 org-log-repeat nil
12980 org-todo-log-states nil)
12981 (dolist (w (org-split-string value))
12982 (let (a)
12983 (cond
12984 ((setq a (assoc w org-startup-options))
12985 (and (member (nth 1 a) '(org-log-done org-log-repeat))
12986 (set (nth 1 a) (nth 2 a))))
12987 ((setq a (org-extract-log-state-settings w))
12988 (and (member (car a) org-todo-keywords-1)
12989 (push a org-todo-log-states)))))))
12991 (defun org-get-todo-sequence-head (kwd)
12992 "Return the head of the TODO sequence to which KWD belongs.
12993 If KWD is not set, check if there is a text property remembering the
12994 right sequence."
12995 (let (p)
12996 (cond
12997 ((not kwd)
12998 (or (get-text-property (point-at-bol) 'org-todo-head)
12999 (progn
13000 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
13001 nil (point-at-eol)))
13002 (get-text-property p 'org-todo-head))))
13003 ((not (member kwd org-todo-keywords-1))
13004 (car org-todo-keywords-1))
13005 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
13007 (defun org-fast-todo-selection ()
13008 "Fast TODO keyword selection with single keys.
13009 Returns the new TODO keyword, or nil if no state change should occur."
13010 (let* ((fulltable org-todo-key-alist)
13011 (done-keywords org-done-keywords) ;; needed for the faces.
13012 (maxlen (apply 'max (mapcar
13013 (lambda (x)
13014 (if (stringp (car x)) (string-width (car x)) 0))
13015 fulltable)))
13016 (expert nil)
13017 (fwidth (+ maxlen 3 1 3))
13018 (ncol (/ (- (window-width) 4) fwidth))
13019 tg cnt e c tbl
13020 groups ingroup)
13021 (save-excursion
13022 (save-window-excursion
13023 (if expert
13024 (set-buffer (get-buffer-create " *Org todo*"))
13025 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
13026 (erase-buffer)
13027 (setq-local org-done-keywords done-keywords)
13028 (setq tbl fulltable cnt 0)
13029 (while (setq e (pop tbl))
13030 (cond
13031 ((equal e '(:startgroup))
13032 (push '() groups) (setq ingroup t)
13033 (unless (= cnt 0)
13034 (setq cnt 0)
13035 (insert "\n"))
13036 (insert "{ "))
13037 ((equal e '(:endgroup))
13038 (setq ingroup nil cnt 0)
13039 (insert "}\n"))
13040 ((equal e '(:newline))
13041 (unless (= cnt 0)
13042 (setq cnt 0)
13043 (insert "\n")
13044 (setq e (car tbl))
13045 (while (equal (car tbl) '(:newline))
13046 (insert "\n")
13047 (setq tbl (cdr tbl)))))
13049 (setq tg (car e) c (cdr e))
13050 (when ingroup (push tg (car groups)))
13051 (setq tg (org-add-props tg nil 'face
13052 (org-get-todo-face tg)))
13053 (when (and (= cnt 0) (not ingroup)) (insert " "))
13054 (insert "[" c "] " tg (make-string
13055 (- fwidth 4 (length tg)) ?\ ))
13056 (when (= (setq cnt (1+ cnt)) ncol)
13057 (insert "\n")
13058 (when ingroup (insert " "))
13059 (setq cnt 0)))))
13060 (insert "\n")
13061 (goto-char (point-min))
13062 (unless expert (org-fit-window-to-buffer))
13063 (message "[a-z..]:Set [SPC]:clear")
13064 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
13065 (cond
13066 ((or (= c ?\C-g)
13067 (and (= c ?q) (not (rassoc c fulltable))))
13068 (setq quit-flag t))
13069 ((= c ?\ ) nil)
13070 ((setq e (rassoc c fulltable) tg (car e))
13072 (t (setq quit-flag t)))))))
13074 (defun org-entry-is-todo-p ()
13075 (member (org-get-todo-state) org-not-done-keywords))
13077 (defun org-entry-is-done-p ()
13078 (member (org-get-todo-state) org-done-keywords))
13080 (defun org-get-todo-state ()
13081 "Return the TODO keyword of the current subtree."
13082 (save-excursion
13083 (org-back-to-heading t)
13084 (and (looking-at org-todo-line-regexp)
13085 (match-end 2)
13086 (match-string 2))))
13088 (defun org-at-date-range-p (&optional inactive-ok)
13089 "Non-nil if point is inside a date range.
13091 When optional argument INACTIVE-OK is non-nil, also consider
13092 inactive time ranges.
13094 When this function returns a non-nil value, match data is set
13095 according to `org-tr-regexp-both' or `org-tr-regexp', depending
13096 on INACTIVE-OK."
13097 (interactive)
13098 (save-excursion
13099 (catch 'exit
13100 (let ((pos (point)))
13101 (skip-chars-backward "^[<\r\n")
13102 (skip-chars-backward "<[")
13103 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13104 (>= (match-end 0) pos)
13105 (throw 'exit t))
13106 (skip-chars-backward "^<[\r\n")
13107 (skip-chars-backward "<[")
13108 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
13109 (>= (match-end 0) pos)
13110 (throw 'exit t)))
13111 nil)))
13113 (defun org-get-repeat (&optional tagline)
13114 "Check if there is a deadline/schedule with repeater in this entry."
13115 (save-match-data
13116 (save-excursion
13117 (org-back-to-heading t)
13118 (and (re-search-forward (if tagline
13119 (concat tagline "\\s-*" org-repeat-re)
13120 org-repeat-re)
13121 (org-entry-end-position) t)
13122 (match-string-no-properties 1)))))
13124 (defvar org-last-changed-timestamp)
13125 (defvar org-last-inserted-timestamp)
13126 (defvar org-log-post-message)
13127 (defvar org-log-note-purpose)
13128 (defvar org-log-note-how nil)
13129 (defvar org-log-note-extra)
13130 (defun org-auto-repeat-maybe (done-word)
13131 "Check if the current headline contains a repeated time-stamp.
13133 If yes, set TODO state back to what it was and change the base date
13134 of repeating deadline/scheduled time stamps to new date.
13136 This function is run automatically after each state change to a DONE state."
13137 (let* ((repeat (org-get-repeat))
13138 (aa (assoc org-last-state org-todo-kwd-alist))
13139 (interpret (nth 1 aa))
13140 (head (nth 2 aa))
13141 (whata '(("h" . hour) ("d" . day) ("m" . month) ("y" . year)))
13142 (msg "Entry repeats: ")
13143 (org-log-done nil)
13144 (org-todo-log-states nil))
13145 (when (and repeat (not (zerop (string-to-number (substring repeat 1)))))
13146 (when (eq org-log-repeat t) (setq org-log-repeat 'state))
13147 (let ((to-state (or (org-entry-get nil "REPEAT_TO_STATE" 'selective)
13148 org-todo-repeat-to-state)))
13149 (unless (and to-state (member to-state org-todo-keywords-1))
13150 (setq to-state (if (eq interpret 'type) org-last-state head)))
13151 (org-todo to-state))
13152 (when (or org-log-repeat (org-entry-get nil "CLOCK"))
13153 (org-entry-put nil "LAST_REPEAT" (format-time-string
13154 (org-time-stamp-format t t))))
13155 (when org-log-repeat
13156 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
13157 (memq 'org-add-log-note post-command-hook))
13158 ;; We are already setup for some record.
13159 (when (eq org-log-repeat 'note)
13160 ;; Make sure we take a note, not only a time stamp.
13161 (setq org-log-note-how 'note))
13162 ;; Set up for taking a record.
13163 (org-add-log-setup 'state
13164 (or done-word (car org-done-keywords))
13165 org-last-state
13166 org-log-repeat)))
13167 (org-back-to-heading t)
13168 (org-add-planning-info nil nil 'closed)
13169 (let ((end (save-excursion (outline-next-heading) (point))))
13170 (while (re-search-forward org-ts-regexp end t)
13171 (when (save-match-data
13172 (or (org-at-planning-p)
13173 (org-at-property-p)
13174 (eq (org-element-type (save-excursion
13175 (backward-char)
13176 (org-element-context)))
13177 'timestamp)))
13178 (let ((type (cond ((match-end 1) org-scheduled-string)
13179 ((match-end 3) org-deadline-string)
13180 (t "Plain:")))
13181 (ts (or (match-string 2) (match-string 4) (match-string 0))))
13182 (cond
13183 ((not
13184 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" ts))
13185 ;; Time-stamps without a repeater are usually skipped.
13186 ;; However, a SCHEDULED time-stamp without one is
13187 ;; removed, as it is considered as no longer relevant.
13188 (when (equal type org-scheduled-string)
13189 (org-remove-timestamp-with-keyword type)))
13191 (let ((n (string-to-number (match-string 2 ts)))
13192 (what (match-string 3 ts)))
13193 (when (equal what "w") (setq n (* n 7) what "d"))
13194 (when (and (equal what "h")
13195 (not (string-match-p "[0-9]\\{1,2\\}:[0-9]\\{2\\}"
13196 ts)))
13197 (user-error
13198 "Cannot repeat in Repeat in %d hour(s) because no hour \
13199 has been set"
13201 ;; Preparation, see if we need to modify the start
13202 ;; date for the change.
13203 (when (match-end 1)
13204 (let ((time (save-match-data (org-time-string-to-time ts))))
13205 (cond
13206 ((equal (match-string 1 ts) ".")
13207 ;; Shift starting date to today
13208 (org-timestamp-change
13209 (- (org-today) (time-to-days time))
13210 'day))
13211 ((equal (match-string 1 ts) "+")
13212 (let ((nshiftmax 10)
13213 (nshift 0))
13214 (while (or (= nshift 0)
13215 (<= (time-to-days time)
13216 (time-to-days (current-time))))
13217 (when (= (cl-incf nshift) nshiftmax)
13218 (or (y-or-n-p
13219 (format "%d repeater intervals were not \
13220 enough to shift date past today. Continue? "
13221 nshift))
13222 (user-error "Abort")))
13223 (org-timestamp-change n (cdr (assoc what whata)))
13224 (org-at-timestamp-p t)
13225 (setq ts (match-string 1))
13226 (setq time
13227 (save-match-data
13228 (org-time-string-to-time ts)))))
13229 (org-timestamp-change (- n) (cdr (assoc what whata)))
13230 ;; Rematch, so that we have everything in
13231 ;; place for the real shift.
13232 (org-at-timestamp-p t)
13233 (setq ts (match-string 1))
13234 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)"
13235 ts)))))
13236 (save-excursion
13237 (org-timestamp-change n (cdr (assoc what whata)) nil t))
13238 (setq msg
13239 (concat
13240 msg type " " org-last-changed-timestamp " ")))))))))
13241 (setq org-log-post-message msg)
13242 (message "%s" msg))))
13244 (defun org-show-todo-tree (arg)
13245 "Make a compact tree which shows all headlines marked with TODO.
13246 The tree will show the lines where the regexp matches, and all higher
13247 headlines above the match.
13248 With a \\[universal-argument] prefix, prompt for a regexp to match.
13249 With a numeric prefix N, construct a sparse tree for the Nth element
13250 of `org-todo-keywords-1'."
13251 (interactive "P")
13252 (let ((case-fold-search nil)
13253 (kwd-re
13254 (cond ((null arg) org-not-done-regexp)
13255 ((equal arg '(4))
13256 (let ((kwd
13257 (completing-read "Keyword (or KWD1|KWD2|...): "
13258 (mapcar #'list org-todo-keywords-1))))
13259 (concat "\\("
13260 (mapconcat 'identity (org-split-string kwd "|") "\\|")
13261 "\\)\\>")))
13262 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
13263 (regexp-quote (nth (1- (prefix-numeric-value arg))
13264 org-todo-keywords-1)))
13265 (t (user-error "Invalid prefix argument: %s" arg)))))
13266 (message "%d TODO entries found"
13267 (org-occur (concat "^" org-outline-regexp " *" kwd-re )))))
13269 (defun org-deadline (arg &optional time)
13270 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
13271 With one universal prefix argument, remove any deadline from the item.
13272 With two universal prefix arguments, prompt for a warning delay.
13273 With argument TIME, set the deadline at the corresponding date. TIME
13274 can either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13275 (interactive "P")
13276 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13277 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13278 'region-start-level 'region))
13279 org-loop-over-headlines-in-active-region)
13280 (org-map-entries
13281 `(org-deadline ',arg ,time)
13282 org-loop-over-headlines-in-active-region
13283 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13284 (let* ((old-date (org-entry-get nil "DEADLINE"))
13285 (old-date-time (when old-date (org-time-string-to-time old-date)))
13286 (repeater (and old-date
13287 (string-match
13288 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13289 old-date)
13290 (match-string 1 old-date))))
13291 (cond
13292 ((equal arg '(4))
13293 (when (and old-date org-log-redeadline)
13294 (org-add-log-setup 'deldeadline nil old-date org-log-redeadline))
13295 (org-remove-timestamp-with-keyword org-deadline-string)
13296 (message "Item no longer has a deadline."))
13297 ((equal arg '(16))
13298 (save-excursion
13299 (org-back-to-heading t)
13300 (if (re-search-forward
13301 org-deadline-time-regexp
13302 (save-excursion (outline-next-heading) (point)) t)
13303 (let* ((rpl0 (match-string 1))
13304 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13305 (replace-match
13306 (concat org-deadline-string
13307 " <" rpl
13308 (format " -%dd"
13309 (abs
13310 (- (time-to-days
13311 (save-match-data
13312 (org-read-date nil t nil "Warn starting from" old-date-time)))
13313 (time-to-days old-date-time))))
13314 ">") t t))
13315 (user-error "No deadline information to update"))))
13317 (org-add-planning-info 'deadline time 'closed)
13318 (when (and old-date
13319 org-log-redeadline
13320 (not (equal old-date org-last-inserted-timestamp)))
13321 (org-add-log-setup
13322 'redeadline org-last-inserted-timestamp old-date org-log-redeadline))
13323 (when repeater
13324 (save-excursion
13325 (org-back-to-heading t)
13326 (when (re-search-forward (concat org-deadline-string " "
13327 org-last-inserted-timestamp)
13328 (save-excursion
13329 (outline-next-heading) (point)) t)
13330 (goto-char (1- (match-end 0)))
13331 (insert " " repeater)
13332 (setq org-last-inserted-timestamp
13333 (concat (substring org-last-inserted-timestamp 0 -1)
13334 " " repeater
13335 (substring org-last-inserted-timestamp -1))))))
13336 (message "Deadline on %s" org-last-inserted-timestamp))))))
13338 (defun org-schedule (arg &optional time)
13339 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
13340 With one universal prefix argument, remove any scheduling date from the item.
13341 With two universal prefix arguments, prompt for a delay cookie.
13342 With argument TIME, scheduled at the corresponding date. TIME can
13343 either be an Org date like \"2011-07-24\" or a delta like \"+2d\"."
13344 (interactive "P")
13345 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
13346 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
13347 'region-start-level 'region))
13348 org-loop-over-headlines-in-active-region)
13349 (org-map-entries
13350 `(org-schedule ',arg ,time)
13351 org-loop-over-headlines-in-active-region
13352 cl (when (outline-invisible-p) (org-end-of-subtree nil t))))
13353 (let* ((old-date (org-entry-get nil "SCHEDULED"))
13354 (old-date-time (when old-date (org-time-string-to-time old-date)))
13355 (repeater (and old-date
13356 (string-match
13357 "\\([.+-]+[0-9]+[hdwmy]\\(?:[/ ][-+]?[0-9]+[hdwmy]\\)?\\) ?"
13358 old-date)
13359 (match-string 1 old-date))))
13360 (cond
13361 ((equal arg '(4))
13362 (progn
13363 (when (and old-date org-log-reschedule)
13364 (org-add-log-setup 'delschedule nil old-date org-log-reschedule))
13365 (org-remove-timestamp-with-keyword org-scheduled-string)
13366 (message "Item is no longer scheduled.")))
13367 ((equal arg '(16))
13368 (save-excursion
13369 (org-back-to-heading t)
13370 (if (re-search-forward
13371 org-scheduled-time-regexp
13372 (save-excursion (outline-next-heading) (point)) t)
13373 (let* ((rpl0 (match-string 1))
13374 (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0)))
13375 (replace-match
13376 (concat org-scheduled-string
13377 " <" rpl
13378 (format " -%dd"
13379 (abs
13380 (- (time-to-days
13381 (save-match-data
13382 (org-read-date nil t nil "Delay until" old-date-time)))
13383 (time-to-days old-date-time))))
13384 ">") t t))
13385 (user-error "No scheduled information to update"))))
13387 (org-add-planning-info 'scheduled time 'closed)
13388 (when (and old-date
13389 org-log-reschedule
13390 (not (equal old-date org-last-inserted-timestamp)))
13391 (org-add-log-setup
13392 'reschedule org-last-inserted-timestamp old-date org-log-reschedule))
13393 (when repeater
13394 (save-excursion
13395 (org-back-to-heading t)
13396 (when (re-search-forward (concat org-scheduled-string " "
13397 org-last-inserted-timestamp)
13398 (save-excursion
13399 (outline-next-heading) (point)) t)
13400 (goto-char (1- (match-end 0)))
13401 (insert " " repeater)
13402 (setq org-last-inserted-timestamp
13403 (concat (substring org-last-inserted-timestamp 0 -1)
13404 " " repeater
13405 (substring org-last-inserted-timestamp -1))))))
13406 (message "Scheduled to %s" org-last-inserted-timestamp))))))
13408 (defun org-get-scheduled-time (pom &optional inherit)
13409 "Get the scheduled time as a time tuple, of a format suitable
13410 for calling org-schedule with, or if there is no scheduling,
13411 returns nil."
13412 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
13413 (when time
13414 (apply 'encode-time (org-parse-time-string time)))))
13416 (defun org-get-deadline-time (pom &optional inherit)
13417 "Get the deadline as a time tuple, of a format suitable for
13418 calling org-deadline with, or if there is no scheduling, returns
13419 nil."
13420 (let ((time (org-entry-get pom "DEADLINE" inherit)))
13421 (when time
13422 (apply 'encode-time (org-parse-time-string time)))))
13424 (defun org-remove-timestamp-with-keyword (keyword)
13425 "Remove all time stamps with KEYWORD in the current entry."
13426 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
13427 beg)
13428 (save-excursion
13429 (org-back-to-heading t)
13430 (setq beg (point))
13431 (outline-next-heading)
13432 (while (re-search-backward re beg t)
13433 (replace-match "")
13434 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
13435 (equal (char-before) ?\ ))
13436 (backward-delete-char 1)
13437 (when (string-match "^[ \t]*$" (buffer-substring
13438 (point-at-bol) (point-at-eol)))
13439 (delete-region (point-at-bol)
13440 (min (point-max) (1+ (point-at-eol))))))))))
13442 (defvar org-time-was-given) ; dynamically scoped parameter
13443 (defvar org-end-time-was-given) ; dynamically scoped parameter
13445 (defun org-at-planning-p ()
13446 "Non-nil when point is on a planning info line."
13447 ;; This is as accurate and faster than `org-element-at-point' since
13448 ;; planning info location is fixed in the section.
13449 (org-with-wide-buffer
13450 (beginning-of-line)
13451 (and (org-looking-at-p org-planning-line-re)
13452 (eq (point)
13453 (ignore-errors
13454 (if (and (featurep 'org-inlinetask) (org-inlinetask-in-task-p))
13455 (org-back-to-heading t)
13456 (org-with-limited-levels (org-back-to-heading t)))
13457 (line-beginning-position 2))))))
13459 (defun org-add-planning-info (what &optional time &rest remove)
13460 "Insert new timestamp with keyword in the planning line.
13461 WHAT indicates what kind of time stamp to add. It is a symbol
13462 among `closed', `deadline', `scheduled' and nil. TIME indicates
13463 the time to use. If none is given, the user is prompted for
13464 a date. REMOVE indicates what kind of entries to remove. An old
13465 WHAT entry will also be removed."
13466 (let (org-time-was-given org-end-time-was-given default-time default-input)
13467 (catch 'exit
13468 (when (and (memq what '(scheduled deadline))
13469 (or (not time)
13470 (and (stringp time)
13471 (string-match "^[-+]+[0-9]" time))))
13472 ;; Try to get a default date/time from existing timestamp
13473 (save-excursion
13474 (org-back-to-heading t)
13475 (let ((end (save-excursion (outline-next-heading) (point))) ts)
13476 (when (re-search-forward (if (eq what 'scheduled)
13477 org-scheduled-time-regexp
13478 org-deadline-time-regexp)
13479 end t)
13480 (setq ts (match-string 1)
13481 default-time (apply 'encode-time (org-parse-time-string ts))
13482 default-input (and ts (org-get-compact-tod ts)))))))
13483 (when what
13484 (setq time
13485 (if (stringp time)
13486 ;; This is a string (relative or absolute), set
13487 ;; proper date.
13488 (apply #'encode-time
13489 (org-read-date-analyze
13490 time default-time (decode-time default-time)))
13491 ;; If necessary, get the time from the user
13492 (or time (org-read-date nil 'to-time nil nil
13493 default-time default-input)))))
13495 (org-with-wide-buffer
13496 (org-back-to-heading t)
13497 (forward-line)
13498 (unless (bolp) (insert "\n"))
13499 (cond ((org-looking-at-p org-planning-line-re)
13500 ;; Move to current indentation.
13501 (skip-chars-forward " \t")
13502 ;; Check if we have to remove something.
13503 (dolist (type (if what (cons what remove) remove))
13504 (save-excursion
13505 (when (re-search-forward
13506 (cl-case type
13507 (closed org-closed-time-regexp)
13508 (deadline org-deadline-time-regexp)
13509 (scheduled org-scheduled-time-regexp)
13510 (otherwise
13511 (error "Invalid planning type: %s" type)))
13512 (line-end-position) t)
13513 ;; Delete until next keyword or end of line.
13514 (delete-region
13515 (match-beginning 0)
13516 (if (re-search-forward org-keyword-time-not-clock-regexp
13517 (line-end-position)
13519 (match-beginning 0)
13520 (line-end-position))))))
13521 ;; If there is nothing more to add and no more keyword
13522 ;; is left, remove the line completely.
13523 (if (and (org-looking-at-p "[ \t]*$") (not what))
13524 (delete-region (line-beginning-position)
13525 (line-beginning-position 2))
13526 ;; If we removed last keyword, do not leave trailing
13527 ;; white space at the end of line.
13528 (let ((p (point)))
13529 (save-excursion
13530 (end-of-line)
13531 (unless (= (skip-chars-backward " \t" p) 0)
13532 (delete-region (point) (line-end-position)))))))
13533 ((not what) (throw 'exit nil)) ; Nothing to do.
13534 (t (insert-before-markers "\n")
13535 (backward-char 1)
13536 (when org-adapt-indentation
13537 (org-indent-to-column (1+ (org-outline-level))))))
13538 (when what
13539 ;; Insert planning keyword.
13540 (insert (cl-case what
13541 (closed org-closed-string)
13542 (deadline org-deadline-string)
13543 (scheduled org-scheduled-string)
13544 (otherwise (error "Invalid planning type: %s" what)))
13545 " ")
13546 ;; Insert associated timestamp.
13547 (let ((ts (org-insert-time-stamp
13548 time
13549 (or org-time-was-given
13550 (and (eq what 'closed) org-log-done-with-time))
13551 (eq what 'closed)
13552 nil nil (list org-end-time-was-given))))
13553 (unless (eolp) (insert " "))
13554 ts))))))
13556 (defvar org-log-note-marker (make-marker)
13557 "Marker pointing at the entry where the note is to be inserted.")
13558 (defvar org-log-note-purpose nil)
13559 (defvar org-log-note-state nil)
13560 (defvar org-log-note-previous-state nil)
13561 (defvar org-log-note-extra nil)
13562 (defvar org-log-note-window-configuration nil)
13563 (defvar org-log-note-return-to (make-marker))
13564 (defvar org-log-note-effective-time nil
13565 "Remembered current time so that dynamically scoped
13566 `org-extend-today-until' affects timestamps in state change log")
13568 (defvar org-log-post-message nil
13569 "Message to be displayed after a log note has been stored.
13570 The auto-repeater uses this.")
13572 (defun org-add-note ()
13573 "Add a note to the current entry.
13574 This is done in the same way as adding a state change note."
13575 (interactive)
13576 (org-add-log-setup 'note))
13578 (defun org-log-beginning (&optional create)
13579 "Return expected start of log notes in current entry.
13580 When optional argument CREATE is non-nil, the function creates
13581 a drawer to store notes, if necessary. Returned position ignores
13582 narrowing."
13583 (org-with-wide-buffer
13584 (let ((drawer (org-log-into-drawer)))
13585 (cond
13586 (drawer
13587 (org-end-of-meta-data)
13588 (let ((regexp (concat "^[ \t]*:" (regexp-quote drawer) ":[ \t]*$"))
13589 (end (if (org-at-heading-p) (point)
13590 (save-excursion (outline-next-heading) (point))))
13591 (case-fold-search t))
13592 (catch 'exit
13593 ;; Try to find existing drawer.
13594 (while (re-search-forward regexp end t)
13595 (let ((element (org-element-at-point)))
13596 (when (eq (org-element-type element) 'drawer)
13597 (let ((cend (org-element-property :contents-end element)))
13598 (when (and (not org-log-states-order-reversed) cend)
13599 (goto-char cend)))
13600 (throw 'exit nil))))
13601 ;; No drawer found. Create one, if permitted.
13602 (when create
13603 (unless (bolp) (insert "\n"))
13604 (let ((beg (point)))
13605 (insert ":" drawer ":\n:END:\n")
13606 (org-indent-region beg (point)))
13607 (end-of-line -1)))))
13609 (org-end-of-meta-data org-log-state-notes-insert-after-drawers)
13610 (skip-chars-forward " \t\n")
13611 (beginning-of-line)
13612 (unless org-log-states-order-reversed
13613 (org-skip-over-state-notes)
13614 (skip-chars-backward " \t\n")
13615 (forward-line)))))
13616 (if (bolp) (point) (line-beginning-position 2))))
13618 (defun org-add-log-setup (&optional purpose state prev-state how extra)
13619 "Set up the post command hook to take a note.
13620 If this is about to TODO state change, the new state is expected in STATE.
13621 HOW is an indicator what kind of note should be created.
13622 EXTRA is additional text that will be inserted into the notes buffer."
13623 (move-marker org-log-note-marker (point))
13624 (setq org-log-note-purpose purpose
13625 org-log-note-state state
13626 org-log-note-previous-state prev-state
13627 org-log-note-how how
13628 org-log-note-extra extra
13629 org-log-note-effective-time (org-current-effective-time))
13630 (add-hook 'post-command-hook 'org-add-log-note 'append))
13632 (defun org-skip-over-state-notes ()
13633 "Skip past the list of State notes in an entry."
13634 (when (ignore-errors (goto-char (org-in-item-p)))
13635 (let* ((struct (org-list-struct))
13636 (prevs (org-list-prevs-alist struct))
13637 (regexp
13638 (concat "[ \t]*- +"
13639 (replace-regexp-in-string
13640 " +" " +"
13641 (org-replace-escapes
13642 (regexp-quote (cdr (assq 'state org-log-note-headings)))
13643 `(("%d" . ,org-ts-regexp-inactive)
13644 ("%D" . ,org-ts-regexp)
13645 ("%s" . "\"\\S-+\"")
13646 ("%S" . "\"\\S-+\"")
13647 ("%t" . ,org-ts-regexp-inactive)
13648 ("%T" . ,org-ts-regexp)
13649 ("%u" . ".*?")
13650 ("%U" . ".*?")))))))
13651 (while (org-looking-at-p regexp)
13652 (goto-char (or (org-list-get-next-item (point) struct prevs)
13653 (org-list-get-item-end (point) struct)))))))
13655 (defun org-add-log-note (&optional _purpose)
13656 "Pop up a window for taking a note, and add this note later."
13657 (remove-hook 'post-command-hook 'org-add-log-note)
13658 (setq org-log-note-window-configuration (current-window-configuration))
13659 (delete-other-windows)
13660 (move-marker org-log-note-return-to (point))
13661 (org-pop-to-buffer-same-window (marker-buffer org-log-note-marker))
13662 (goto-char org-log-note-marker)
13663 (org-switch-to-buffer-other-window "*Org Note*")
13664 (erase-buffer)
13665 (if (memq org-log-note-how '(time state))
13666 (let (current-prefix-arg) (org-store-log-note))
13667 (let ((org-inhibit-startup t)) (org-mode))
13668 (insert (format "# Insert note for %s.
13669 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
13670 (cond
13671 ((eq org-log-note-purpose 'clock-out) "stopped clock")
13672 ((eq org-log-note-purpose 'done) "closed todo item")
13673 ((eq org-log-note-purpose 'state)
13674 (format "state change from \"%s\" to \"%s\""
13675 (or org-log-note-previous-state "")
13676 (or org-log-note-state "")))
13677 ((eq org-log-note-purpose 'reschedule)
13678 "rescheduling")
13679 ((eq org-log-note-purpose 'delschedule)
13680 "no longer scheduled")
13681 ((eq org-log-note-purpose 'redeadline)
13682 "changing deadline")
13683 ((eq org-log-note-purpose 'deldeadline)
13684 "removing deadline")
13685 ((eq org-log-note-purpose 'refile)
13686 "refiling")
13687 ((eq org-log-note-purpose 'note)
13688 "this entry")
13689 (t (error "This should not happen")))))
13690 (when org-log-note-extra (insert org-log-note-extra))
13691 (setq-local org-finish-function 'org-store-log-note)
13692 (run-hooks 'org-log-buffer-setup-hook)))
13694 (defvar org-note-abort nil) ; dynamically scoped
13695 (defun org-store-log-note ()
13696 "Finish taking a log note, and insert it to where it belongs."
13697 (let ((txt (prog1 (buffer-string)
13698 (kill-buffer)))
13699 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
13700 lines)
13701 (while (string-match "\\`# .*\n[ \t\n]*" txt)
13702 (setq txt (replace-match "" t t txt)))
13703 (when (string-match "\\s-+\\'" txt)
13704 (setq txt (replace-match "" t t txt)))
13705 (setq lines (org-split-string txt "\n"))
13706 (when (org-string-nw-p note)
13707 (setq note
13708 (org-replace-escapes
13709 note
13710 (list (cons "%u" (user-login-name))
13711 (cons "%U" user-full-name)
13712 (cons "%t" (format-time-string
13713 (org-time-stamp-format 'long 'inactive)
13714 org-log-note-effective-time))
13715 (cons "%T" (format-time-string
13716 (org-time-stamp-format 'long nil)
13717 org-log-note-effective-time))
13718 (cons "%d" (format-time-string
13719 (org-time-stamp-format nil 'inactive)
13720 org-log-note-effective-time))
13721 (cons "%D" (format-time-string
13722 (org-time-stamp-format nil nil)
13723 org-log-note-effective-time))
13724 (cons "%s" (cond
13725 ((not org-log-note-state) "")
13726 ((org-string-match-p org-ts-regexp
13727 org-log-note-state)
13728 (format "\"[%s]\""
13729 (substring org-log-note-state 1 -1)))
13730 (t (format "\"%s\"" org-log-note-state))))
13731 (cons "%S"
13732 (cond
13733 ((not org-log-note-previous-state) "")
13734 ((org-string-match-p org-ts-regexp
13735 org-log-note-previous-state)
13736 (format "\"[%s]\""
13737 (substring
13738 org-log-note-previous-state 1 -1)))
13739 (t (format "\"%s\""
13740 org-log-note-previous-state)))))))
13741 (when lines (setq note (concat note " \\\\")))
13742 (push note lines))
13743 (when (and lines (not (or current-prefix-arg org-note-abort)))
13744 (with-current-buffer (marker-buffer org-log-note-marker)
13745 (org-with-wide-buffer
13746 ;; Find location for the new note.
13747 (goto-char org-log-note-marker)
13748 (set-marker org-log-note-marker nil)
13749 (goto-char (org-log-beginning t))
13750 ;; Make sure point is at the beginning of an empty line.
13751 (cond ((not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
13752 ((looking-at "[ \t]*\\S-") (save-excursion (insert "\n"))))
13753 ;; In an existing list, add a new item at the top level.
13754 ;; Otherwise, indent line like a regular one.
13755 (let ((itemp (org-in-item-p)))
13756 (if itemp
13757 (org-indent-line-to
13758 (let ((struct (save-excursion
13759 (goto-char itemp) (org-list-struct))))
13760 (org-list-get-ind (org-list-get-top-point struct) struct)))
13761 (org-indent-line)))
13762 (insert (org-list-bullet-string "-") (pop lines))
13763 (let ((ind (org-list-item-body-column (line-beginning-position))))
13764 (dolist (line lines)
13765 (insert "\n")
13766 (org-indent-line-to ind)
13767 (insert line)))
13768 (message "Note stored")
13769 (org-back-to-heading t)
13770 (org-cycle-hide-drawers 'children))
13771 ;; Fix `buffer-undo-list' when `org-store-log-note' is called
13772 ;; from within `org-add-log-note' because `buffer-undo-list'
13773 ;; is then modified outside of `org-with-remote-undo'.
13774 (when (eq this-command 'org-agenda-todo)
13775 (setcdr buffer-undo-list (cddr buffer-undo-list))))))
13776 ;; Don't add undo information when called from `org-agenda-todo'.
13777 (let ((buffer-undo-list (eq this-command 'org-agenda-todo)))
13778 (set-window-configuration org-log-note-window-configuration)
13779 (with-current-buffer (marker-buffer org-log-note-return-to)
13780 (goto-char org-log-note-return-to))
13781 (move-marker org-log-note-return-to nil)
13782 (when org-log-post-message (message "%s" org-log-post-message))))
13784 (defun org-remove-empty-drawer-at (pos)
13785 "Remove an empty drawer at position POS.
13786 POS may also be a marker."
13787 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
13788 (org-with-wide-buffer
13789 (goto-char pos)
13790 (let ((drawer (org-element-at-point)))
13791 (when (and (memq (org-element-type drawer) '(drawer property-drawer))
13792 (not (org-element-property :contents-begin drawer)))
13793 (delete-region (org-element-property :begin drawer)
13794 (progn (goto-char (org-element-property :end drawer))
13795 (skip-chars-backward " \r\t\n")
13796 (forward-line)
13797 (point))))))))
13799 (defvar org-ts-type nil)
13800 (defun org-sparse-tree (&optional arg type)
13801 "Create a sparse tree, prompt for the details.
13802 This command can create sparse trees. You first need to select the type
13803 of match used to create the tree:
13805 t Show all TODO entries.
13806 T Show entries with a specific TODO keyword.
13807 m Show entries selected by a tags/property match.
13808 p Enter a property name and its value (both with completion on existing
13809 names/values) and show entries with that property.
13810 r Show entries matching a regular expression (`/' can be used as well).
13811 b Show deadlines and scheduled items before a date.
13812 a Show deadlines and scheduled items after a date.
13813 d Show deadlines due within `org-deadline-warning-days'.
13814 D Show deadlines and scheduled items between a date range."
13815 (interactive "P")
13816 (setq type (or type org-sparse-tree-default-date-type))
13817 (setq org-ts-type type)
13818 (message "Sparse tree: [/]regexp [t]odo [T]odo-kwd [m]atch [p]roperty
13819 \[d]eadlines [b]efore-date [a]fter-date [D]ates range
13820 \[c]ycle through date types: %s"
13821 (cl-case type
13822 (all "all timestamps")
13823 (scheduled "only scheduled")
13824 (deadline "only deadline")
13825 (active "only active timestamps")
13826 (inactive "only inactive timestamps")
13827 (closed "with a closed time-stamp")
13828 (otherwise "scheduled/deadline")))
13829 (let ((answer (read-char-exclusive)))
13830 (cl-case answer
13832 (org-sparse-tree
13834 (cadr
13835 (memq type '(nil all scheduled deadline active inactive closed)))))
13836 (?d (call-interactively 'org-check-deadlines))
13837 (?b (call-interactively 'org-check-before-date))
13838 (?a (call-interactively 'org-check-after-date))
13839 (?D (call-interactively 'org-check-dates-range))
13840 (?t (call-interactively 'org-show-todo-tree))
13841 (?T (org-show-todo-tree '(4)))
13842 (?m (call-interactively 'org-match-sparse-tree))
13843 ((?p ?P)
13844 (let* ((kwd (completing-read
13845 "Property: " (mapcar #'list (org-buffer-property-keys))))
13846 (value (completing-read
13847 "Value: " (mapcar #'list (org-property-values kwd)))))
13848 (unless (string-match "\\`{.*}\\'" value)
13849 (setq value (concat "\"" value "\"")))
13850 (org-match-sparse-tree arg (concat kwd "=" value))))
13851 ((?r ?R ?/) (call-interactively 'org-occur))
13852 (otherwise (user-error "No such sparse tree command \"%c\"" answer)))))
13854 (defvar-local org-occur-highlights nil
13855 "List of overlays used for occur matches.")
13856 (defvar-local org-occur-parameters nil
13857 "Parameters of the active org-occur calls.
13858 This is a list, each call to org-occur pushes as cons cell,
13859 containing the regular expression and the callback, onto the list.
13860 The list can contain several entries if `org-occur' has been called
13861 several time with the KEEP-PREVIOUS argument. Otherwise, this list
13862 will only contain one set of parameters. When the highlights are
13863 removed (for example with `C-c C-c', or with the next edit (depending
13864 on `org-remove-highlights-with-change'), this variable is emptied
13865 as well.")
13867 (defun org-occur (regexp &optional keep-previous callback)
13868 "Make a compact tree which shows all matches of REGEXP.
13869 The tree will show the lines where the regexp matches, and all higher
13870 headlines above the match. It will also show the heading after the match,
13871 to make sure editing the matching entry is easy.
13872 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
13873 call to `org-occur' will be kept, to allow stacking of calls to this
13874 command.
13875 If CALLBACK is non-nil, it is a function which is called to confirm
13876 that the match should indeed be shown."
13877 (interactive "sRegexp: \nP")
13878 (when (equal regexp "")
13879 (user-error "Regexp cannot be empty"))
13880 (unless keep-previous
13881 (org-remove-occur-highlights nil nil t))
13882 (push (cons regexp callback) org-occur-parameters)
13883 (let ((cnt 0))
13884 (save-excursion
13885 (goto-char (point-min))
13886 (when (or (not keep-previous) ; do not want to keep
13887 (not org-occur-highlights)) ; no previous matches
13888 ;; hide everything
13889 (org-overview))
13890 (while (re-search-forward regexp nil t)
13891 (backward-char) ;; FIXME: Match timestamps at the end of a headline
13892 (when (or (not callback)
13893 (save-match-data (funcall callback)))
13894 (setq cnt (1+ cnt))
13895 (when org-highlight-sparse-tree-matches
13896 (org-highlight-new-match (match-beginning 0) (match-end 0)))
13897 (org-show-context 'occur-tree))))
13898 (when org-remove-highlights-with-change
13899 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
13900 nil 'local))
13901 (unless org-sparse-tree-open-archived-trees
13902 (org-hide-archived-subtrees (point-min) (point-max)))
13903 (run-hooks 'org-occur-hook)
13904 (when (org-called-interactively-p 'interactive)
13905 (message "%d match(es) for regexp %s" cnt regexp))
13906 cnt))
13908 (defun org-occur-next-match (&optional n _reset)
13909 "Function for `next-error-function' to find sparse tree matches.
13910 N is the number of matches to move, when negative move backwards.
13911 This function always goes back to the starting point when no
13912 match is found."
13913 (let* ((limit (if (< n 0) (point-min) (point-max)))
13914 (search-func (if (< n 0)
13915 'previous-single-char-property-change
13916 'next-single-char-property-change))
13917 (n (abs n))
13918 (pos (point))
13920 (catch 'exit
13921 (while (setq p1 (funcall search-func (point) 'org-type))
13922 (when (equal p1 limit)
13923 (goto-char pos)
13924 (user-error "No more matches"))
13925 (when (equal (get-char-property p1 'org-type) 'org-occur)
13926 (setq n (1- n))
13927 (when (= n 0)
13928 (goto-char p1)
13929 (throw 'exit (point))))
13930 (goto-char p1))
13931 (goto-char p1)
13932 (user-error "No more matches"))))
13934 (defun org-show-context (&optional key)
13935 "Make sure point and context are visible.
13936 Optional argument KEY, when non-nil, is a symbol. See
13937 `org-show-context-detail' for allowed values and how much is to
13938 be shown."
13939 (org-show-set-visibility
13940 (cond ((symbolp org-show-context-detail) org-show-context-detail)
13941 ((cdr (assq key org-show-context-detail)))
13942 (t (cdr (assq 'default org-show-context-detail))))))
13944 (defun org-show-set-visibility (detail)
13945 "Set visibility around point according to DETAIL.
13946 DETAIL is either nil, `minimal', `local', `ancestors', `lineage',
13947 `tree', `canonical' or t. See `org-show-context-detail' for more
13948 information."
13949 ;; Show current heading and possibly its entry, following headline
13950 ;; or all children.
13951 (if (and (org-at-heading-p) (not (eq detail 'local)))
13952 (org-flag-heading nil)
13953 (org-show-entry)
13954 ;; If point is hidden within a drawer or a block, make sure to
13955 ;; expose it.
13956 (dolist (o (overlays-at (point)))
13957 (when (memq (overlay-get o 'invisible) '(org-hide-block outline))
13958 (delete-overlay o)))
13959 (unless (org-before-first-heading-p)
13960 (org-with-limited-levels
13961 (cl-case detail
13962 ((tree canonical t) (org-show-children))
13963 ((nil minimal ancestors))
13964 (t (save-excursion
13965 (outline-next-heading)
13966 (org-flag-heading nil)))))))
13967 ;; Show all siblings.
13968 (when (eq detail 'lineage) (org-show-siblings))
13969 ;; Show ancestors, possibly with their children.
13970 (when (memq detail '(ancestors lineage tree canonical t))
13971 (save-excursion
13972 (while (org-up-heading-safe)
13973 (org-flag-heading nil)
13974 (when (memq detail '(canonical t)) (org-show-entry))
13975 (when (memq detail '(tree canonical t)) (org-show-children))))))
13977 (defvar org-reveal-start-hook nil
13978 "Hook run before revealing a location.")
13980 (defun org-reveal (&optional siblings)
13981 "Show current entry, hierarchy above it, and the following headline.
13983 This can be used to show a consistent set of context around
13984 locations exposed with `org-show-context'.
13986 With optional argument SIBLINGS, on each level of the hierarchy all
13987 siblings are shown. This repairs the tree structure to what it would
13988 look like when opened with hierarchical calls to `org-cycle'.
13990 With double optional argument \\[universal-argument] \\[universal-argument], \
13991 go to the parent and show the
13992 entire tree."
13993 (interactive "P")
13994 (run-hooks 'org-reveal-start-hook)
13995 (cond ((equal siblings '(4)) (org-show-set-visibility 'canonical))
13996 ((equal siblings '(16))
13997 (save-excursion
13998 (when (org-up-heading-safe)
13999 (org-show-subtree)
14000 (run-hook-with-args 'org-cycle-hook 'subtree))))
14001 (t (org-show-set-visibility 'lineage))))
14003 (defun org-highlight-new-match (beg end)
14004 "Highlight from BEG to END and mark the highlight is an occur headline."
14005 (let ((ov (make-overlay beg end)))
14006 (overlay-put ov 'face 'secondary-selection)
14007 (overlay-put ov 'org-type 'org-occur)
14008 (push ov org-occur-highlights)))
14010 (defun org-remove-occur-highlights (&optional _beg _end noremove)
14011 "Remove the occur highlights from the buffer.
14012 BEG and END are ignored. If NOREMOVE is nil, remove this function
14013 from the `before-change-functions' in the current buffer."
14014 (interactive)
14015 (unless org-inhibit-highlight-removal
14016 (mapc #'delete-overlay org-occur-highlights)
14017 (setq org-occur-highlights nil)
14018 (setq org-occur-parameters nil)
14019 (unless noremove
14020 (remove-hook 'before-change-functions
14021 'org-remove-occur-highlights 'local))))
14023 ;;;; Priorities
14025 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
14026 "Regular expression matching the priority indicator.")
14028 (defvar org-remove-priority-next-time nil)
14030 (defun org-priority-up ()
14031 "Increase the priority of the current item."
14032 (interactive)
14033 (org-priority 'up))
14035 (defun org-priority-down ()
14036 "Decrease the priority of the current item."
14037 (interactive)
14038 (org-priority 'down))
14040 (defun org-priority (&optional action _show)
14041 "Change the priority of an item.
14042 ACTION can be `set', `up', `down', or a character."
14043 (interactive "P")
14044 (if (equal action '(4))
14045 (org-show-priority)
14046 (unless org-enable-priority-commands
14047 (user-error "Priority commands are disabled"))
14048 (setq action (or action 'set))
14049 (let (current new news have remove)
14050 (save-excursion
14051 (org-back-to-heading t)
14052 (when (looking-at org-priority-regexp)
14053 (setq current (string-to-char (match-string 2))
14054 have t))
14055 (cond
14056 ((eq action 'remove)
14057 (setq remove t new ?\ ))
14058 ((or (eq action 'set)
14059 (if (featurep 'xemacs) (characterp action) (integerp action)))
14060 (if (not (eq action 'set))
14061 (setq new action)
14062 (message "Priority %c-%c, SPC to remove: "
14063 org-highest-priority org-lowest-priority)
14064 (save-match-data
14065 (setq new (read-char-exclusive))))
14066 (when (and (= (upcase org-highest-priority) org-highest-priority)
14067 (= (upcase org-lowest-priority) org-lowest-priority))
14068 (setq new (upcase new)))
14069 (cond ((equal new ?\ ) (setq remove t))
14070 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
14071 (user-error "Priority must be between `%c' and `%c'"
14072 org-highest-priority org-lowest-priority))))
14073 ((eq action 'up)
14074 (setq new (if have
14075 (1- current) ; normal cycling
14076 ;; last priority was empty
14077 (if (eq last-command this-command)
14078 org-lowest-priority ; wrap around empty to lowest
14079 ;; default
14080 (if org-priority-start-cycle-with-default
14081 org-default-priority
14082 (1- org-default-priority))))))
14083 ((eq action 'down)
14084 (setq new (if have
14085 (1+ current) ; normal cycling
14086 ;; last priority was empty
14087 (if (eq last-command this-command)
14088 org-highest-priority ; wrap around empty to highest
14089 ;; default
14090 (if org-priority-start-cycle-with-default
14091 org-default-priority
14092 (1+ org-default-priority))))))
14093 (t (user-error "Invalid action")))
14094 (when (or (< (upcase new) org-highest-priority)
14095 (> (upcase new) org-lowest-priority))
14096 (if (and (memq action '(up down))
14097 (not have) (not (eq last-command this-command)))
14098 ;; `new' is from default priority
14099 (error
14100 "The default can not be set, see `org-default-priority' why")
14101 ;; normal cycling: `new' is beyond highest/lowest priority
14102 ;; and is wrapped around to the empty priority
14103 (setq remove t)))
14104 (setq news (format "%c" new))
14105 (if have
14106 (if remove
14107 (replace-match "" t t nil 1)
14108 (replace-match news t t nil 2))
14109 (if remove
14110 (user-error "No priority cookie found in line")
14111 (let ((case-fold-search nil))
14112 (looking-at org-todo-line-regexp))
14113 (if (match-end 2)
14114 (progn
14115 (goto-char (match-end 2))
14116 (insert " [#" news "]"))
14117 (goto-char (match-beginning 3))
14118 (insert "[#" news "] "))))
14119 (org-set-tags nil 'align))
14120 (if remove
14121 (message "Priority removed")
14122 (message "Priority of current item set to %s" news)))))
14124 (defun org-show-priority ()
14125 "Show the priority of the current item.
14126 This priority is composed of the main priority given with the [#A] cookies,
14127 and by additional input from the age of a schedules or deadline entry."
14128 (interactive)
14129 (let ((pri (if (eq major-mode 'org-agenda-mode)
14130 (org-get-at-bol 'priority)
14131 (save-excursion
14132 (save-match-data
14133 (beginning-of-line)
14134 (and (looking-at org-heading-regexp)
14135 (org-get-priority (match-string 0))))))))
14136 (message "Priority is %d" (if pri pri -1000))))
14138 (defun org-get-priority (s)
14139 "Find priority cookie and return priority."
14140 (save-match-data
14141 (if (functionp org-get-priority-function)
14142 (funcall org-get-priority-function)
14143 (if (not (string-match org-priority-regexp s))
14144 (* 1000 (- org-lowest-priority org-default-priority))
14145 (* 1000 (- org-lowest-priority
14146 (string-to-char (match-string 2 s))))))))
14148 ;;;; Tags
14150 (defvar org-agenda-archives-mode)
14151 (defvar org-map-continue-from nil
14152 "Position from where mapping should continue.
14153 Can be set by the action argument to `org-scan-tags' and `org-map-entries'.")
14155 (defvar org-scanner-tags nil
14156 "The current tag list while the tags scanner is running.")
14158 (defvar org-trust-scanner-tags nil
14159 "Should `org-get-tags-at' use the tags for the scanner.
14160 This is for internal dynamical scoping only.
14161 When this is non-nil, the function `org-get-tags-at' will return the value
14162 of `org-scanner-tags' instead of building the list by itself. This
14163 can lead to large speed-ups when the tags scanner is used in a file with
14164 many entries, and when the list of tags is retrieved, for example to
14165 obtain a list of properties. Building the tags list for each entry in such
14166 a file becomes an N^2 operation - but with this variable set, it scales
14167 as N.")
14169 (defvar org--matcher-tags-todo-only nil)
14171 (defun org-scan-tags (action matcher todo-only &optional start-level)
14172 "Scan headline tags with inheritance and produce output ACTION.
14174 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
14175 or `agenda' to produce an entry list for an agenda view. It can also be
14176 a Lisp form or a function that should be called at each matched headline, in
14177 this case the return value is a list of all return values from these calls.
14179 MATCHER is a function accepting three arguments, returning
14180 a non-nil value whenever a given set of tags qualifies a headline
14181 for inclusion. See `org-make-tags-matcher' for more information.
14182 As a special case, it can also be set to t (respectively nil) in
14183 order to match all (respectively none) headline.
14185 When TODO-ONLY is non-nil, only lines with a not-done TODO
14186 keyword are included in the output.
14188 START-LEVEL can be a string with asterisks, reducing the scope to
14189 headlines matching this string."
14190 (require 'org-agenda)
14191 (let* ((re (concat "^"
14192 (if start-level
14193 ;; Get the correct level to match
14194 (concat "\\*\\{" (number-to-string start-level) "\\} ")
14195 org-outline-regexp)
14196 " *\\(\\<\\("
14197 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
14198 (org-re "\\)\\>\\)? *\\(.*?\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*$")))
14199 (props (list 'face 'default
14200 'done-face 'org-agenda-done
14201 'undone-face 'default
14202 'mouse-face 'highlight
14203 'org-not-done-regexp org-not-done-regexp
14204 'org-todo-regexp org-todo-regexp
14205 'org-complex-heading-regexp org-complex-heading-regexp
14206 'help-echo
14207 (format "mouse-2 or RET jump to org file %s"
14208 (abbreviate-file-name
14209 (or (buffer-file-name (buffer-base-buffer))
14210 (buffer-name (buffer-base-buffer)))))))
14211 (org-map-continue-from nil)
14212 lspos tags tags-list
14213 (tags-alist (list (cons 0 org-file-tags)))
14214 (llast 0) rtn rtn1 level category i txt
14215 todo marker entry priority
14216 ts-date ts-date-type ts-date-pair)
14217 (unless (or (member action '(agenda sparse-tree)) (functionp action))
14218 (setq action (list 'lambda nil action)))
14219 (save-excursion
14220 (goto-char (point-min))
14221 (when (eq action 'sparse-tree)
14222 (org-overview)
14223 (org-remove-occur-highlights))
14224 (while (let (case-fold-search)
14225 (re-search-forward re nil t))
14226 (setq org-map-continue-from nil)
14227 (catch :skip
14228 (setq todo
14229 ;; TODO: is the 1-2 difference a bug?
14230 (when (match-end 1) (org-match-string-no-properties 2))
14231 tags (when (match-end 4) (org-match-string-no-properties 4)))
14232 (goto-char (setq lspos (match-beginning 0)))
14233 (setq level (org-reduced-level (org-outline-level))
14234 category (org-get-category))
14235 (when (eq action 'agenda)
14236 (setq ts-date-pair (org-agenda-entry-get-agenda-timestamp (point))
14237 ts-date (car ts-date-pair)
14238 ts-date-type (cdr ts-date-pair)))
14239 (setq i llast llast level)
14240 ;; remove tag lists from same and sublevels
14241 (while (>= i level)
14242 (when (setq entry (assoc i tags-alist))
14243 (setq tags-alist (delete entry tags-alist)))
14244 (setq i (1- i)))
14245 ;; add the next tags
14246 (when tags
14247 (setq tags (org-split-string tags ":")
14248 tags-alist
14249 (cons (cons level tags) tags-alist)))
14250 ;; compile tags for current headline
14251 (setq tags-list
14252 (if org-use-tag-inheritance
14253 (apply 'append (mapcar 'cdr (reverse tags-alist)))
14254 tags)
14255 org-scanner-tags tags-list)
14256 (when org-use-tag-inheritance
14257 (setcdr (car tags-alist)
14258 (mapcar (lambda (x)
14259 (setq x (copy-sequence x))
14260 (org-add-prop-inherited x))
14261 (cdar tags-alist))))
14262 (when (and tags org-use-tag-inheritance
14263 (or (not (eq t org-use-tag-inheritance))
14264 org-tags-exclude-from-inheritance))
14265 ;; Selective inheritance, remove uninherited ones.
14266 (setcdr (car tags-alist)
14267 (org-remove-uninherited-tags (cdar tags-alist))))
14268 (when (and
14270 ;; eval matcher only when the todo condition is OK
14271 (and (or (not todo-only) (member todo org-not-done-keywords))
14272 (if (functionp matcher)
14273 (let ((case-fold-search t) (org-trust-scanner-tags t))
14274 (funcall matcher todo tags-list level))
14275 matcher))
14277 ;; Call the skipper, but return t if it does not
14278 ;; skip, so that the `and' form continues evaluating.
14279 (progn
14280 (unless (eq action 'sparse-tree) (org-agenda-skip))
14283 ;; Check if timestamps are deselecting this entry
14284 (or (not todo-only)
14285 (and (member todo org-not-done-keywords)
14286 (or (not org-agenda-tags-todo-honor-ignore-options)
14287 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item))))))
14289 ;; select this headline
14290 (cond
14291 ((eq action 'sparse-tree)
14292 (and org-highlight-sparse-tree-matches
14293 (org-get-heading) (match-end 0)
14294 (org-highlight-new-match
14295 (match-beginning 1) (match-end 1)))
14296 (org-show-context 'tags-tree))
14297 ((eq action 'agenda)
14298 (setq txt (org-agenda-format-item
14300 (concat
14301 (if (eq org-tags-match-list-sublevels 'indented)
14302 (make-string (1- level) ?.) "")
14303 (org-get-heading))
14304 (make-string level ?\s)
14305 category
14306 tags-list)
14307 priority (org-get-priority txt))
14308 (goto-char lspos)
14309 (setq marker (org-agenda-new-marker))
14310 (org-add-props txt props
14311 'org-marker marker 'org-hd-marker marker 'org-category category
14312 'todo-state todo
14313 'ts-date ts-date
14314 'priority priority
14315 'type (concat "tagsmatch" ts-date-type))
14316 (push txt rtn))
14317 ((functionp action)
14318 (setq org-map-continue-from nil)
14319 (save-excursion
14320 (setq rtn1 (funcall action))
14321 (push rtn1 rtn)))
14322 (t (user-error "Invalid action")))
14324 ;; if we are to skip sublevels, jump to end of subtree
14325 (unless org-tags-match-list-sublevels
14326 (org-end-of-subtree t)
14327 (backward-char 1))))
14328 ;; Get the correct position from where to continue
14329 (if org-map-continue-from
14330 (goto-char org-map-continue-from)
14331 (and (= (point) lspos) (end-of-line 1)))))
14332 (when (and (eq action 'sparse-tree)
14333 (not org-sparse-tree-open-archived-trees))
14334 (org-hide-archived-subtrees (point-min) (point-max)))
14335 (nreverse rtn)))
14337 (defun org-remove-uninherited-tags (tags)
14338 "Remove all tags that are not inherited from the list TAGS."
14339 (cond
14340 ((eq org-use-tag-inheritance t)
14341 (if org-tags-exclude-from-inheritance
14342 (org-delete-all org-tags-exclude-from-inheritance tags)
14343 tags))
14344 ((not org-use-tag-inheritance) nil)
14345 ((stringp org-use-tag-inheritance)
14346 (delq nil (mapcar
14347 (lambda (x)
14348 (if (and (string-match org-use-tag-inheritance x)
14349 (not (member x org-tags-exclude-from-inheritance)))
14350 x nil))
14351 tags)))
14352 ((listp org-use-tag-inheritance)
14353 (delq nil (mapcar
14354 (lambda (x)
14355 (if (member x org-use-tag-inheritance) x nil))
14356 tags)))))
14358 (defun org-match-sparse-tree (&optional todo-only match)
14359 "Create a sparse tree according to tags string MATCH.
14360 MATCH can contain positive and negative selection of tags, like
14361 \"+WORK+URGENT-WITHBOSS\".
14362 If optional argument TODO-ONLY is non-nil, only select lines that are
14363 also TODO lines."
14364 (interactive "P")
14365 (org-agenda-prepare-buffers (list (current-buffer)))
14366 (let ((org--matcher-tags-todo-only todo-only))
14367 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match))
14368 org--matcher-tags-todo-only)))
14370 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
14372 (defvar org-cached-props nil)
14373 (defun org-cached-entry-get (pom property)
14374 (if (or (eq t org-use-property-inheritance)
14375 (and (stringp org-use-property-inheritance)
14376 (let ((case-fold-search t))
14377 (org-string-match-p org-use-property-inheritance property)))
14378 (and (listp org-use-property-inheritance)
14379 (member-ignore-case property org-use-property-inheritance)))
14380 ;; Caching is not possible, check it directly.
14381 (org-entry-get pom property 'inherit)
14382 ;; Get all properties, so we can do complicated checks easily.
14383 (cdr (assoc-string property
14384 (or org-cached-props
14385 (setq org-cached-props (org-entry-properties pom)))
14386 t))))
14388 (defun org-global-tags-completion-table (&optional files)
14389 "Return the list of all tags in all agenda buffer/files.
14390 Optional FILES argument is a list of files which can be used
14391 instead of the agenda files."
14392 (save-excursion
14393 (org-uniquify
14394 (delq nil
14395 (apply #'append
14396 (mapcar
14397 (lambda (file)
14398 (set-buffer (find-file-noselect file))
14399 (mapcar (lambda (x)
14400 (and (stringp (car-safe x))
14401 (list (car-safe x))))
14402 (or org-current-tag-alist (org-get-buffer-tags))))
14403 (if (car-safe files) files
14404 (org-agenda-files))))))))
14406 (defun org-make-tags-matcher (match)
14407 "Create the TAGS/TODO matcher form for the selection string MATCH.
14409 Returns a cons of the selection string MATCH and a function
14410 implementing the matcher.
14412 The matcher is to be called at an Org entry, with point on the
14413 headline, and returns non-nil if the entry matches the selection
14414 string MATCH. It must be called with three arguments: the TODO
14415 keyword at the entry (or nil if none), the list of all tags at
14416 the entry including inherited ones and the reduced level of the
14417 headline. Additionally, the category of the entry, if any, must
14418 be specified as the text property `org-category' on the headline.
14420 This function sets the variable `org--matcher-tags-todo-only' to
14421 a non-nil value if the matcher restricts matching to TODO
14422 entries, otherwise it is not touched.
14424 See also `org-scan-tags'."
14425 (unless match
14426 ;; Get a new match request, with completion against the global
14427 ;; tags table and the local tags in current buffer.
14428 (let ((org-last-tags-completion-table
14429 (org-uniquify
14430 (delq nil (append (org-get-buffer-tags)
14431 (org-global-tags-completion-table))))))
14432 (setq match
14433 (completing-read
14434 "Match: "
14435 'org-tags-completion-function nil nil nil 'org-tags-history))))
14437 (let ((match0 match)
14438 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\(\\(?:[[:alnum:]_]+\\(?:\\\\-\\)*\\)+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@#%]+\\)"))
14439 (start 0)
14440 tagsmatch todomatch tagsmatcher todomatcher)
14442 ;; Expand group tags.
14443 (setq match (org-tags-expand match))
14445 ;; Check if there is a TODO part of this match, which would be the
14446 ;; part after a "/". To make sure that this slash is not part of
14447 ;; a property value to be matched against, we also check that
14448 ;; there is no / after that slash. First, find the last slash.
14449 (let ((s 0))
14450 (while (string-match "/+" match s)
14451 (setq start (match-beginning 0))
14452 (setq s (match-end 0))))
14453 (if (and (string-match "/+" match start)
14454 (not (string-match-p "\"" match start)))
14455 ;; Match contains also a TODO-matching request.
14456 (progn
14457 (setq tagsmatch (substring match 0 (match-beginning 0)))
14458 (setq todomatch (substring match (match-end 0)))
14459 (when (string-match "\\`!" todomatch)
14460 (setq org--matcher-tags-todo-only t)
14461 (setq todomatch (substring todomatch 1)))
14462 (when (string-match "\\`\\s-*\\'" todomatch)
14463 (setq todomatch nil)))
14464 ;; Only matching tags.
14465 (setq tagsmatch match)
14466 (setq todomatch nil))
14468 ;; Make the tags matcher.
14469 (when (org-string-nw-p tagsmatch)
14470 (let ((orlist nil)
14471 (orterms (org-split-string tagsmatch "|"))
14472 term)
14473 (while (setq term (pop orterms))
14474 (while (and (equal (substring term -1) "\\") orterms)
14475 (setq term (concat term "|" (pop orterms)))) ;repair bad split.
14476 (while (string-match re term)
14477 (let* ((rest (substring term (match-end 0)))
14478 (minus (and (match-end 1)
14479 (equal (match-string 1 term) "-")))
14480 (tag (save-match-data
14481 (replace-regexp-in-string
14482 "\\\\-" "-" (match-string 2 term))))
14483 (regexp (eq (string-to-char tag) ?{))
14484 (levelp (match-end 4))
14485 (propp (match-end 5))
14487 (cond
14488 (regexp `(org-match-any-p ,(substring tag 1 -1) tags-list))
14489 (levelp
14490 `(,(org-op-to-function (match-string 3 term))
14491 level
14492 ,(string-to-number (match-string 4 term))))
14493 (propp
14494 (let* ((gv (pcase (upcase (match-string 5 term))
14495 ("CATEGORY"
14496 '(get-text-property (point) 'org-category))
14497 ("TODO" 'todo)
14498 (p `(org-cached-entry-get nil ,p))))
14499 (pv (match-string 7 term))
14500 (regexp (eq (string-to-char pv) ?{))
14501 (strp (eq (string-to-char pv) ?\"))
14502 (timep (string-match-p "^\"[[<].*[]>]\"$" pv))
14503 (po (org-op-to-function (match-string 6 term)
14504 (if timep 'time strp))))
14505 (setq pv (if (or regexp strp) (substring pv 1 -1) pv))
14506 (when timep (setq pv (org-matcher-time pv)))
14507 (cond ((and regexp (eq po 'org<>))
14508 `(not (string-match ,pv (or ,gv ""))))
14509 (regexp `(string-match ,pv (or ,gv "")))
14510 (strp `(,po (or ,gv "") ,pv))
14512 `(,po
14513 (string-to-number (or ,gv ""))
14514 ,(string-to-number pv))))))
14515 (t `(member ,tag tags-list)))))
14516 (push (if minus `(not ,mm) mm) tagsmatcher)
14517 (setq term rest)))
14518 (push `(and ,@tagsmatcher) orlist)
14519 (setq tagsmatcher nil))
14520 (setq tagsmatcher `(progn (setq org-cached-props nil) (or ,@orlist)))))
14522 ;; Make the TODO matcher.
14523 (when (org-string-nw-p todomatch)
14524 (let ((orlist nil))
14525 (dolist (term (org-split-string todomatch "|"))
14526 (while (string-match re term)
14527 (let* ((minus (and (match-end 1)
14528 (equal (match-string 1 term) "-")))
14529 (kwd (match-string 2 term))
14530 (regexp (eq (string-to-char kwd) ?{))
14531 (mm (if regexp `(string-match ,(substring kwd 1 -1) todo)
14532 `(equal todo ,kwd))))
14533 (push (if minus `(not ,mm) mm) todomatcher))
14534 (setq term (substring term (match-end 0))))
14535 (push (if (> (length todomatcher) 1)
14536 (cons 'and todomatcher)
14537 (car todomatcher))
14538 orlist)
14539 (setq todomatcher nil))
14540 (setq todomatcher (cons 'or orlist))))
14542 ;; Return the string and function of the matcher. If no
14543 ;; tags-specific or todo-specific matcher exists, match
14544 ;; everything.
14545 (let ((matcher (if (and tagsmatcher todomatcher)
14546 `(and ,tagsmatcher ,todomatcher)
14547 (or tagsmatcher todomatcher t))))
14548 (when org--matcher-tags-todo-only
14549 (setq matcher `(and (member todo org-not-done-keywords) ,matcher)))
14550 (cons match0 `(lambda (todo tags-list level) ,matcher)))))
14552 (defun org-tags-expand (match &optional single-as-list downcased tags-already-expanded)
14553 "Expand group tags in MATCH.
14555 This replaces every group tag in MATCH with a regexp tag search.
14556 For example, a group tag \"Work\" defined as { Work : Lab Conf }
14557 will be replaced like this:
14559 Work => {\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14560 +Work => +{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14561 -Work => -{\\<\\(?:Work\\|Lab\\|Conf\\)\\>}
14563 Replacing by a regexp preserves the structure of the match.
14564 E.g., this expansion
14566 Work|Home => {\\(?:Work\\|Lab\\|Conf\\}|Home
14568 will match anything tagged with \"Lab\" and \"Home\", or tagged
14569 with \"Conf\" and \"Home\" or tagged with \"Work\" and \"home\".
14571 A group tag in MATCH can contain regular expressions of its own.
14572 For example, a group tag \"Proj\" defined as { Proj : {P@.+} }
14573 will be replaced like this:
14575 Proj => {\\<\\(?:Proj\\)\\>\\|P@.+}
14577 When the optional argument SINGLE-AS-LIST is non-nil, MATCH is
14578 assumed to be a single group tag, and the function will return
14579 the list of tags in this group.
14581 When DOWNCASE is non-nil, expand downcased TAGS."
14582 (if org-group-tags
14583 (let* ((case-fold-search t)
14584 (stable org-mode-syntax-table)
14585 (taggroups (or org-tag-groups-alist-for-agenda org-tag-groups-alist))
14586 (taggroups (if downcased
14587 (mapcar (lambda (tg) (mapcar #'downcase tg))
14588 taggroups)
14589 taggroups))
14590 (taggroups-keys (mapcar #'car taggroups))
14591 (return-match (if downcased (downcase match) match))
14592 (count 0)
14593 (work-already-expanded tags-already-expanded)
14594 regexps-in-match tags-in-group regexp-in-group regexp-in-group-escaped)
14595 ;; @ and _ are allowed as word-components in tags.
14596 (modify-syntax-entry ?@ "w" stable)
14597 (modify-syntax-entry ?_ "w" stable)
14598 ;; Temporarily replace regexp-expressions in the match-expression.
14599 (while (string-match "{.+?}" return-match)
14600 (cl-incf count)
14601 (push (match-string 0 return-match) regexps-in-match)
14602 (setq return-match (replace-match (format "<%d>" count) t nil return-match)))
14603 (while (and taggroups-keys
14604 (with-syntax-table stable
14605 (string-match
14606 (concat "\\(?1:[+-]?\\)\\(?2:\\<"
14607 (regexp-opt taggroups-keys) "\\>\\)")
14608 return-match)))
14609 (let* ((dir (match-string 1 return-match))
14610 (tag (match-string 2 return-match))
14611 (tag (if downcased (downcase tag) tag)))
14612 (unless (or (get-text-property 0 'grouptag (match-string 2 return-match))
14613 (member tag work-already-expanded))
14614 (setq tags-in-group (assoc tag taggroups))
14615 (push tag work-already-expanded)
14616 ;; Recursively expand each tag in the group, if the tag hasn't
14617 ;; already been expanded. Restore the match-data after all recursive calls.
14618 (save-match-data
14619 (let (tags-expanded)
14620 (dolist (x (cdr tags-in-group))
14621 (if (and (member x taggroups-keys)
14622 (not (member x work-already-expanded)))
14623 (setq tags-expanded
14624 (delete-dups
14625 (append
14626 (org-tags-expand x t downcased
14627 work-already-expanded)
14628 tags-expanded)))
14629 (setq tags-expanded
14630 (append (list x) tags-expanded)))
14631 (setq work-already-expanded
14632 (delete-dups
14633 (append tags-expanded
14634 work-already-expanded))))
14635 (setq tags-in-group
14636 (delete-dups (cons (car tags-in-group)
14637 tags-expanded)))))
14638 ;; Filter tag-regexps from tags.
14639 (setq regexp-in-group-escaped
14640 (delq nil (mapcar (lambda (x)
14641 (if (stringp x)
14642 (and (equal "{" (substring x 0 1))
14643 (equal "}" (substring x -1))
14646 tags-in-group))
14647 regexp-in-group
14648 (mapcar (lambda (x)
14649 (substring x 1 -1))
14650 regexp-in-group-escaped)
14651 tags-in-group
14652 (delq nil (mapcar (lambda (x)
14653 (if (stringp x)
14654 (and (not (equal "{" (substring x 0 1)))
14655 (not (equal "}" (substring x -1)))
14658 tags-in-group)))
14659 ;; If single-as-list, do no more in the while-loop.
14660 (if (not single-as-list)
14661 (progn
14662 (when regexp-in-group
14663 (setq regexp-in-group
14664 (concat "\\|"
14665 (mapconcat 'identity regexp-in-group
14666 "\\|"))))
14667 (setq tags-in-group
14668 (concat dir
14669 "{\\<"
14670 (regexp-opt tags-in-group)
14671 "\\>"
14672 regexp-in-group
14673 "}"))
14674 (when (stringp tags-in-group)
14675 (org-add-props tags-in-group '(grouptag t)))
14676 (setq return-match
14677 (replace-match tags-in-group t t return-match)))
14678 (setq tags-in-group
14679 (append regexp-in-group-escaped tags-in-group))))
14680 (setq taggroups-keys (delete tag taggroups-keys))))
14681 ;; Add the regular expressions back into the match-expression again.
14682 (while regexps-in-match
14683 (setq return-match (replace-regexp-in-string (format "<%d>" count)
14684 (pop regexps-in-match)
14685 return-match t t))
14686 (cl-decf count))
14687 (if single-as-list
14688 (if tags-in-group tags-in-group (list return-match))
14689 return-match))
14690 (if single-as-list
14691 (list (if downcased (downcase match) match))
14692 match)))
14694 (defun org-op-to-function (op &optional stringp)
14695 "Turn an operator into the appropriate function."
14696 (setq op
14697 (cond
14698 ((equal op "<" ) '(< string< org-time<))
14699 ((equal op ">" ) '(> org-string> org-time>))
14700 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
14701 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
14702 ((member op '("=" "==")) '(= string= org-time=))
14703 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
14704 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
14706 (defun org<> (a b) (not (= a b)))
14707 (defun org-string<= (a b) (or (string= a b) (string< a b)))
14708 (defun org-string>= (a b) (not (string< a b)))
14709 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
14710 (defun org-string<> (a b) (not (string= 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) (> a b)))
14715 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
14716 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
14717 (defun org-2ft (s)
14718 "Convert S to a floating point time.
14719 If S is already a number, just return it. If it is a string, parse
14720 it as a time string and apply `float-time' to it. If S is nil, just return 0."
14721 (cond
14722 ((numberp s) s)
14723 ((stringp s)
14724 (condition-case nil
14725 (float-time (apply 'encode-time (org-parse-time-string s)))
14726 (error 0.)))
14727 (t 0.)))
14729 (defun org-time-today ()
14730 "Time in seconds today at 0:00.
14731 Returns the float number of seconds since the beginning of the
14732 epoch to the beginning of today (00:00)."
14733 (float-time (apply 'encode-time
14734 (append '(0 0 0) (nthcdr 3 (decode-time))))))
14736 (defun org-matcher-time (s)
14737 "Interpret a time comparison value."
14738 (save-match-data
14739 (cond
14740 ((string= s "<now>") (float-time))
14741 ((string= s "<today>") (org-time-today))
14742 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
14743 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
14744 ((string-match "^<\\([-+][0-9]+\\)\\([hdwmy]\\)>$" s)
14745 (+ (org-time-today)
14746 (* (string-to-number (match-string 1 s))
14747 (cdr (assoc (match-string 2 s)
14748 '(("d" . 86400.0) ("w" . 604800.0)
14749 ("m" . 2678400.0) ("y" . 31557600.0)))))))
14750 (t (org-2ft s)))))
14752 (defun org-match-any-p (re list)
14753 "Does re match any element of list?"
14754 (setq list (mapcar (lambda (x) (string-match re x)) list))
14755 (delq nil list))
14757 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
14758 (defvar org-tags-overlay (make-overlay 1 1))
14759 (org-detach-overlay org-tags-overlay)
14761 (defun org-get-local-tags-at (&optional pos)
14762 "Get a list of tags defined in the current headline."
14763 (org-get-tags-at pos 'local))
14765 (defun org-get-local-tags ()
14766 "Get a list of tags defined in the current headline."
14767 (org-get-tags-at nil 'local))
14769 (defun org-get-tags-at (&optional pos local)
14770 "Get a list of all headline tags applicable at POS.
14771 POS defaults to point. If tags are inherited, the list contains
14772 the targets in the same sequence as the headlines appear, i.e.
14773 the tags of the current headline come last.
14774 When LOCAL is non-nil, only return tags from the current headline,
14775 ignore inherited ones."
14776 (interactive)
14777 (if (and org-trust-scanner-tags
14778 (or (not pos) (equal pos (point)))
14779 (not local))
14780 org-scanner-tags
14781 (let (tags ltags lastpos parent)
14782 (save-excursion
14783 (save-restriction
14784 (widen)
14785 (goto-char (or pos (point)))
14786 (save-match-data
14787 (catch 'done
14788 (condition-case nil
14789 (progn
14790 (org-back-to-heading t)
14791 (while (not (equal lastpos (point)))
14792 (setq lastpos (point))
14793 (when (looking-at
14794 (org-re "[^\r\n]+?:\\([[:alnum:]_@#%:]+\\):[ \t]*$"))
14795 (setq ltags (org-split-string
14796 (org-match-string-no-properties 1) ":"))
14797 (when parent
14798 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
14799 (setq tags (append
14800 (if parent
14801 (org-remove-uninherited-tags ltags)
14802 ltags)
14803 tags)))
14804 (or org-use-tag-inheritance (throw 'done t))
14805 (when local (throw 'done t))
14806 (or (org-up-heading-safe) (error nil))
14807 (setq parent t)))
14808 (error nil)))))
14809 (if local
14810 tags
14811 (reverse (delete-dups
14812 (reverse (append
14813 (org-remove-uninherited-tags
14814 org-file-tags)
14815 tags)))))))))
14817 (defun org-add-prop-inherited (s)
14818 (add-text-properties 0 (length s) '(inherited t) s)
14821 (defun org-toggle-tag (tag &optional onoff)
14822 "Toggle the tag TAG for the current line.
14823 If ONOFF is `on' or `off', don't toggle but set to this state."
14824 (let (res current)
14825 (save-excursion
14826 (org-back-to-heading t)
14827 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@#%:]+\\):[ \t]*$")
14828 (point-at-eol) t)
14829 (progn
14830 (setq current (match-string 1))
14831 (replace-match ""))
14832 (setq current ""))
14833 (setq current (nreverse (org-split-string current ":")))
14834 (cond
14835 ((eq onoff 'on)
14836 (setq res t)
14837 (or (member tag current) (push tag current)))
14838 ((eq onoff 'off)
14839 (or (not (member tag current)) (setq current (delete tag current))))
14840 (t (if (member tag current)
14841 (setq current (delete tag current))
14842 (setq res t)
14843 (push tag current))))
14844 (end-of-line 1)
14845 (if current
14846 (progn
14847 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
14848 (org-set-tags nil t))
14849 (delete-horizontal-space))
14850 (run-hooks 'org-after-tags-change-hook))
14851 res))
14853 (defun org-align-tags-here (to-col)
14854 ;; Assumes that this is a headline
14855 "Align tags on the current headline to TO-COL."
14856 (let ((pos (point)) (col (current-column)) ncol tags-l p)
14857 (beginning-of-line 1)
14858 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
14859 (< pos (match-beginning 2)))
14860 (progn
14861 (setq tags-l (- (match-end 2) (match-beginning 2)))
14862 (goto-char (match-beginning 1))
14863 (insert " ")
14864 (delete-region (point) (1+ (match-beginning 2)))
14865 (setq ncol (max (current-column)
14866 (1+ col)
14867 (if (> to-col 0)
14868 to-col
14869 (- (abs to-col) tags-l))))
14870 (setq p (point))
14871 (insert (make-string (- ncol (current-column)) ?\ ))
14872 (setq ncol (current-column))
14873 (when indent-tabs-mode (tabify p (point-at-eol)))
14874 (org-move-to-column (min ncol col)))
14875 (goto-char pos))))
14877 (defun org-set-tags-command (&optional arg just-align)
14878 "Call the set-tags command for the current entry."
14879 (interactive "P")
14880 (if (or (org-at-heading-p) (and arg (org-before-first-heading-p)))
14881 (org-set-tags arg just-align)
14882 (save-excursion
14883 (unless (and (org-region-active-p)
14884 org-loop-over-headlines-in-active-region)
14885 (org-back-to-heading t))
14886 (org-set-tags arg just-align))))
14888 (defun org-set-tags-to (data)
14889 "Set the tags of the current entry to DATA, replacing the current tags.
14890 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
14891 If DATA is nil or the empty string, any tags will be removed."
14892 (interactive "sTags: ")
14893 (setq data
14894 (cond
14895 ((eq data nil) "")
14896 ((equal data "") "")
14897 ((stringp data)
14898 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
14899 ":"))
14900 ((listp data)
14901 (concat ":" (mapconcat 'identity data ":") ":"))))
14902 (when data
14903 (save-excursion
14904 (org-back-to-heading t)
14905 (when (looking-at org-complex-heading-regexp)
14906 (if (match-end 5)
14907 (progn
14908 (goto-char (match-beginning 5))
14909 (insert data)
14910 (delete-region (point) (point-at-eol))
14911 (org-set-tags nil 'align))
14912 (goto-char (point-at-eol))
14913 (insert " " data)
14914 (org-set-tags nil 'align)))
14915 (beginning-of-line 1)
14916 (when (looking-at ".*?\\([ \t]+\\)$")
14917 (delete-region (match-beginning 1) (match-end 1))))))
14919 (defun org-align-all-tags ()
14920 "Align the tags in all headings."
14921 (interactive)
14922 (save-excursion
14923 (or (ignore-errors (org-back-to-heading t))
14924 (outline-next-heading))
14925 (if (org-at-heading-p)
14926 (org-set-tags t)
14927 (message "No headings"))))
14929 (defvar org-indent-indentation-per-level)
14930 (defun org-set-tags (&optional arg just-align)
14931 "Set the tags for the current headline.
14932 With prefix ARG, realign all tags in headings in the current buffer.
14933 When JUST-ALIGN is non-nil, only align tags."
14934 (interactive "P")
14935 (if (and (org-region-active-p) org-loop-over-headlines-in-active-region)
14936 (let ((cl (if (eq org-loop-over-headlines-in-active-region 'start-level)
14937 'region-start-level
14938 'region))
14939 org-loop-over-headlines-in-active-region)
14940 (org-map-entries
14941 ;; We don't use ARG and JUST-ALIGN here because these args
14942 ;; are not useful when looping over headlines.
14943 #'org-set-tags
14944 org-loop-over-headlines-in-active-region
14946 '(when (outline-invisible-p) (org-end-of-subtree nil t))))
14947 (let ((org-setting-tags t))
14948 (if arg
14949 (save-excursion
14950 (goto-char (point-min))
14951 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
14952 (while (re-search-forward org-outline-regexp-bol nil t)
14953 (org-set-tags nil t)
14954 (end-of-line)))
14955 (message "All tags realigned to column %d" org-tags-column))
14956 (let* ((current (org-get-tags-string))
14957 (col (current-column))
14958 (tags
14959 (if just-align current
14960 ;; Get a new set of tags from the user.
14961 (save-excursion
14962 (let* ((seen)
14963 (table
14964 (setq
14965 org-last-tags-completion-table
14966 ;; Uniquify tags in alists, yet preserve
14967 ;; structure (i.e., keywords).
14968 (delq nil
14969 (mapcar
14970 (lambda (pair)
14971 (let ((head (car pair)))
14972 (cond ((symbolp head) pair)
14973 ((member head seen) nil)
14974 (t (push head seen)
14975 pair))))
14976 (append
14977 (or org-current-tag-alist
14978 (org-get-buffer-tags))
14979 (and
14980 org-complete-tags-always-offer-all-agenda-tags
14981 (org-global-tags-completion-table
14982 (org-agenda-files))))))))
14983 (current-tags (org-split-string current ":"))
14984 (inherited-tags
14985 (nreverse (nthcdr (length current-tags)
14986 (nreverse (org-get-tags-at))))))
14987 (replace-regexp-in-string
14988 "\\([-+&]+\\|,\\)"
14990 (if (or (eq t org-use-fast-tag-selection)
14991 (and org-use-fast-tag-selection
14992 (delq nil (mapcar #'cdr table))))
14993 (org-fast-tag-selection
14994 current-tags inherited-tags table
14995 (and org-fast-tag-selection-include-todo
14996 org-todo-key-alist))
14997 (let ((org-add-colon-after-tag-completion
14998 (< 1 (length table))))
14999 (org-trim
15000 (completing-read
15001 "Tags: "
15002 #'org-tags-completion-function
15003 nil nil current 'org-tags-history))))))))))
15005 (when org-tags-sort-function
15006 (setq tags
15007 (mapconcat
15008 #'identity
15009 (sort (org-split-string tags (org-re "[^[:alnum:]_@#%]+"))
15010 org-tags-sort-function)
15011 ":")))
15013 (if (not (org-string-nw-p tags)) (setq tags "")
15014 (unless (string-match ":\\'" tags) (setq tags (concat tags ":")))
15015 (unless (string-match "\\`:" tags) (setq tags (concat ":" tags))))
15017 ;; Insert new tags at the correct column
15018 (beginning-of-line)
15019 (let ((level (if (looking-at org-outline-regexp)
15020 (- (match-end 0) (point) 1)
15021 1)))
15022 (cond
15023 ((and (equal current "") (equal tags "")))
15024 ((re-search-forward
15025 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
15026 (line-end-position)
15028 (if (equal tags "") (replace-match "" t t)
15029 (goto-char (match-beginning 0))
15030 (let* ((c0 (current-column))
15031 ;; Compute offset for the case of org-indent-mode
15032 ;; active.
15033 (di (if (org-bound-and-true-p org-indent-mode)
15034 (* (1- org-indent-indentation-per-level)
15035 (1- level))
15037 (p0 (if (eq (char-before) ?*) (1+ (point)) (point)))
15038 (tc (+ org-tags-column
15039 (if (> org-tags-column 0) (- di) di)))
15040 (c1 (max (1+ c0)
15041 (if (> tc 0) tc
15042 (- (- tc) (string-width tags)))))
15043 (rpl (concat (make-string (max 0 (- c1 c0)) ?\s) tags)))
15044 (replace-match rpl t t)
15045 (when (and (not (featurep 'xemacs)) indent-tabs-mode)
15046 (tabify p0 (point))))))
15047 (t (error "Tags alignment failed"))))
15048 (org-move-to-column col))
15049 (unless just-align (run-hooks 'org-after-tags-change-hook))))))
15051 (defun org-change-tag-in-region (beg end tag off)
15052 "Add or remove TAG for each entry in the region.
15053 This works in the agenda, and also in an org-mode buffer."
15054 (interactive
15055 (list (region-beginning) (region-end)
15056 (let ((org-last-tags-completion-table
15057 (if (derived-mode-p 'org-mode)
15058 (org-uniquify
15059 (delq nil (append (org-get-buffer-tags)
15060 (org-global-tags-completion-table))))
15061 (org-global-tags-completion-table))))
15062 (completing-read
15063 "Tag: " 'org-tags-completion-function nil nil nil
15064 'org-tags-history))
15065 (progn
15066 (message "[s]et or [r]emove? ")
15067 (equal (read-char-exclusive) ?r))))
15068 (when (fboundp 'deactivate-mark) (deactivate-mark))
15069 (let ((agendap (equal major-mode 'org-agenda-mode))
15070 l1 l2 m buf pos newhead (cnt 0))
15071 (goto-char end)
15072 (setq l2 (1- (org-current-line)))
15073 (goto-char beg)
15074 (setq l1 (org-current-line))
15075 (cl-loop for l from l1 to l2 do
15076 (org-goto-line l)
15077 (setq m (get-text-property (point) 'org-hd-marker))
15078 (when (or (and (derived-mode-p 'org-mode) (org-at-heading-p))
15079 (and agendap m))
15080 (setq buf (if agendap (marker-buffer m) (current-buffer))
15081 pos (if agendap m (point)))
15082 (with-current-buffer buf
15083 (save-excursion
15084 (save-restriction
15085 (goto-char pos)
15086 (setq cnt (1+ cnt))
15087 (org-toggle-tag tag (if off 'off 'on))
15088 (setq newhead (org-get-heading)))))
15089 (and agendap (org-agenda-change-all-lines newhead m))))
15090 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
15092 (defun org-tags-completion-function (string _predicate &optional flag)
15093 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
15094 (confirm (lambda (x) (stringp (car x)))))
15095 (if (string-match "^\\(.*[-+:&,|]\\)\\([^-+:&,|]*\\)$" string)
15096 (setq s1 (match-string 1 string)
15097 s2 (match-string 2 string))
15098 (setq s1 "" s2 string))
15099 (cond
15100 ((eq flag nil)
15101 ;; try completion
15102 (setq rtn (try-completion s2 ctable confirm))
15103 (when (stringp rtn)
15104 (setq rtn
15105 (concat s1 s2 (substring rtn (length s2))
15106 (if (and org-add-colon-after-tag-completion
15107 (assoc rtn ctable))
15108 ":" ""))))
15109 rtn)
15110 ((eq flag t)
15111 ;; all-completions
15112 (all-completions s2 ctable confirm))
15113 ((eq flag 'lambda)
15114 ;; exact match?
15115 (assoc s2 ctable)))))
15117 (defun org-fast-tag-insert (kwd tags face &optional end)
15118 "Insert KDW, and the TAGS, the latter with face FACE.
15119 Also insert END."
15120 (insert (format "%-12s" (concat kwd ":"))
15121 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
15122 (or end "")))
15124 (defun org-fast-tag-show-exit (flag)
15125 (save-excursion
15126 (org-goto-line 3)
15127 (when (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
15128 (replace-match ""))
15129 (when flag
15130 (end-of-line 1)
15131 (org-move-to-column (- (window-width) 19) t)
15132 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
15134 (defun org-set-current-tags-overlay (current prefix)
15135 "Add an overlay to CURRENT tag with PREFIX."
15136 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
15137 (if (featurep 'xemacs)
15138 (org-overlay-display org-tags-overlay (concat prefix s)
15139 'secondary-selection)
15140 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
15141 (org-overlay-display org-tags-overlay (concat prefix s)))))
15143 (defvar org-last-tag-selection-key nil)
15144 (defun org-fast-tag-selection (current inherited table &optional todo-table)
15145 "Fast tag selection with single keys.
15146 CURRENT is the current list of tags in the headline, INHERITED is the
15147 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
15148 possibly with grouping information. TODO-TABLE is a similar table with
15149 TODO keywords, should these have keys assigned to them.
15150 If the keys are nil, a-z are automatically assigned.
15151 Returns the new tags string, or nil to not change the current settings."
15152 (let* ((fulltable (append table todo-table))
15153 (maxlen (apply 'max (mapcar
15154 (lambda (x)
15155 (if (stringp (car x)) (string-width (car x)) 0))
15156 fulltable)))
15157 (buf (current-buffer))
15158 (expert (eq org-fast-tag-selection-single-key 'expert))
15159 (buffer-tags nil)
15160 (fwidth (+ maxlen 3 1 3))
15161 (ncol (/ (- (window-width) 4) fwidth))
15162 (i-face 'org-done)
15163 (c-face 'org-todo)
15164 tg cnt e c char c1 c2 ntable tbl rtn
15165 ov-start ov-end ov-prefix
15166 (exit-after-next org-fast-tag-selection-single-key)
15167 (done-keywords org-done-keywords)
15168 groups ingroup intaggroup)
15169 (save-excursion
15170 (beginning-of-line 1)
15171 (if (looking-at
15172 (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15173 (setq ov-start (match-beginning 1)
15174 ov-end (match-end 1)
15175 ov-prefix "")
15176 (setq ov-start (1- (point-at-eol))
15177 ov-end (1+ ov-start))
15178 (skip-chars-forward "^\n\r")
15179 (setq ov-prefix
15180 (concat
15181 (buffer-substring (1- (point)) (point))
15182 (if (> (current-column) org-tags-column)
15184 (make-string (- org-tags-column (current-column)) ?\ ))))))
15185 (move-overlay org-tags-overlay ov-start ov-end)
15186 (save-window-excursion
15187 (if expert
15188 (set-buffer (get-buffer-create " *Org tags*"))
15189 (delete-other-windows)
15190 (set-window-buffer (split-window-vertically) (get-buffer-create " *Org tags*"))
15191 (org-switch-to-buffer-other-window " *Org tags*"))
15192 (erase-buffer)
15193 (setq-local org-done-keywords done-keywords)
15194 (org-fast-tag-insert "Inherited" inherited i-face "\n")
15195 (org-fast-tag-insert "Current" current c-face "\n\n")
15196 (org-fast-tag-show-exit exit-after-next)
15197 (org-set-current-tags-overlay current ov-prefix)
15198 (setq tbl fulltable char ?a cnt 0)
15199 (while (setq e (pop tbl))
15200 (cond
15201 ((eq (car e) :startgroup)
15202 (push '() groups) (setq ingroup t)
15203 (unless (zerop cnt)
15204 (setq cnt 0)
15205 (insert "\n"))
15206 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
15207 ((eq (car e) :endgroup)
15208 (setq ingroup nil cnt 0)
15209 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
15210 ((eq (car e) :startgrouptag)
15211 (setq intaggroup t)
15212 (unless (zerop cnt)
15213 (setq cnt 0)
15214 (insert "\n"))
15215 (insert "[ "))
15216 ((eq (car e) :endgrouptag)
15217 (setq intaggroup nil cnt 0)
15218 (insert "]\n"))
15219 ((equal e '(:newline))
15220 (unless (zerop cnt)
15221 (setq cnt 0)
15222 (insert "\n")
15223 (setq e (car tbl))
15224 (while (equal (car tbl) '(:newline))
15225 (insert "\n")
15226 (setq tbl (cdr tbl)))))
15227 ((equal e '(:grouptags)) (insert " : "))
15229 (setq tg (copy-sequence (car e)) c2 nil)
15230 (if (cdr e)
15231 (setq c (cdr e))
15232 ;; automatically assign a character.
15233 (setq c1 (string-to-char
15234 (downcase (substring
15235 tg (if (= (string-to-char tg) ?@) 1 0)))))
15236 (if (or (rassoc c1 ntable) (rassoc c1 table))
15237 (while (or (rassoc char ntable) (rassoc char table))
15238 (setq char (1+ char)))
15239 (setq c2 c1))
15240 (setq c (or c2 char)))
15241 (when ingroup (push tg (car groups)))
15242 (setq tg (org-add-props tg nil 'face
15243 (cond
15244 ((not (assoc tg table))
15245 (org-get-todo-face tg))
15246 ((member tg current) c-face)
15247 ((member tg inherited) i-face))))
15248 (when (equal (caar tbl) :grouptags)
15249 (org-add-props tg nil 'face 'org-tag-group))
15250 (when (and (zerop cnt) (not ingroup) (not intaggroup)) (insert " "))
15251 (insert "[" c "] " tg (make-string
15252 (- fwidth 4 (length tg)) ?\ ))
15253 (push (cons tg c) ntable)
15254 (when (= (cl-incf cnt) ncol)
15255 (insert "\n")
15256 (when (or ingroup intaggroup) (insert " "))
15257 (setq cnt 0)))))
15258 (setq ntable (nreverse ntable))
15259 (insert "\n")
15260 (goto-char (point-min))
15261 (unless expert (org-fit-window-to-buffer))
15262 (setq rtn
15263 (catch 'exit
15264 (while t
15265 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
15266 (if (not groups) "no " "")
15267 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
15268 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
15269 (setq org-last-tag-selection-key c)
15270 (cond
15271 ((= c ?\r) (throw 'exit t))
15272 ((= c ?!)
15273 (setq groups (not groups))
15274 (goto-char (point-min))
15275 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
15276 ((= c ?\C-c)
15277 (if (not expert)
15278 (org-fast-tag-show-exit
15279 (setq exit-after-next (not exit-after-next)))
15280 (setq expert nil)
15281 (delete-other-windows)
15282 (set-window-buffer (split-window-vertically) " *Org tags*")
15283 (org-switch-to-buffer-other-window " *Org tags*")
15284 (org-fit-window-to-buffer)))
15285 ((or (= c ?\C-g)
15286 (and (= c ?q) (not (rassoc c ntable))))
15287 (org-detach-overlay org-tags-overlay)
15288 (setq quit-flag t))
15289 ((= c ?\ )
15290 (setq current nil)
15291 (when exit-after-next (setq exit-after-next 'now)))
15292 ((= c ?\t)
15293 (condition-case nil
15294 (setq tg (completing-read
15295 "Tag: "
15296 (or buffer-tags
15297 (with-current-buffer buf
15298 (setq buffer-tags
15299 (org-get-buffer-tags))))))
15300 (quit (setq tg "")))
15301 (when (string-match "\\S-" tg)
15302 (cl-pushnew (list tg) buffer-tags :test #'equal)
15303 (if (member tg current)
15304 (setq current (delete tg current))
15305 (push tg current)))
15306 (when exit-after-next (setq exit-after-next 'now)))
15307 ((setq e (rassoc c todo-table) tg (car e))
15308 (with-current-buffer buf
15309 (save-excursion (org-todo tg)))
15310 (when exit-after-next (setq exit-after-next 'now)))
15311 ((setq e (rassoc c ntable) tg (car e))
15312 (if (member tg current)
15313 (setq current (delete tg current))
15314 (cl-loop for g in groups do
15315 (when (member tg g)
15316 (dolist (x g) (setq current (delete x current)))))
15317 (push tg current))
15318 (when exit-after-next (setq exit-after-next 'now))))
15320 ;; Create a sorted list
15321 (setq current
15322 (sort current
15323 (lambda (a b)
15324 (assoc b (cdr (memq (assoc a ntable) ntable))))))
15325 (when (eq exit-after-next 'now) (throw 'exit t))
15326 (goto-char (point-min))
15327 (beginning-of-line 2)
15328 (delete-region (point) (point-at-eol))
15329 (org-fast-tag-insert "Current" current c-face)
15330 (org-set-current-tags-overlay current ov-prefix)
15331 (while (re-search-forward
15332 (org-re "\\[.\\] \\([[:alnum:]_@#%]+\\)") nil t)
15333 (setq tg (match-string 1))
15334 (add-text-properties
15335 (match-beginning 1) (match-end 1)
15336 (list 'face
15337 (cond
15338 ((member tg current) c-face)
15339 ((member tg inherited) i-face)
15340 (t (get-text-property (match-beginning 1) 'face))))))
15341 (goto-char (point-min)))))
15342 (org-detach-overlay org-tags-overlay)
15343 (if rtn
15344 (mapconcat 'identity current ":")
15345 nil))))
15347 (defun org-get-tags-string ()
15348 "Get the TAGS string in the current headline."
15349 (unless (org-at-heading-p t)
15350 (user-error "Not on a heading"))
15351 (save-excursion
15352 (beginning-of-line 1)
15353 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@#%:]+:\\)[ \t]*$"))
15354 (org-match-string-no-properties 1)
15355 "")))
15357 (defun org-get-tags ()
15358 "Get the list of tags specified in the current headline."
15359 (org-split-string (org-get-tags-string) ":"))
15361 (defun org-get-buffer-tags ()
15362 "Get a table of all tags used in the buffer, for completion."
15363 (org-with-wide-buffer
15364 (goto-char (point-min))
15365 (let ((tag-re (concat org-outline-regexp-bol
15366 "\\(?:.*?[ \t]\\)?"
15367 (org-re ":\\([[:alnum:]_@#%:]+\\):[ \t]*$")))
15368 tags)
15369 (while (re-search-forward tag-re nil t)
15370 (dolist (tag (org-split-string (org-match-string-no-properties 1) ":"))
15371 (push tag tags)))
15372 (mapcar #'list (append org-file-tags (org-uniquify tags))))))
15374 ;;;; The mapping API
15376 (defvar org-agenda-skip-comment-trees)
15377 (defvar org-agenda-skip-function)
15378 (defun org-map-entries (func &optional match scope &rest skip)
15379 "Call FUNC at each headline selected by MATCH in SCOPE.
15381 FUNC is a function or a lisp form. The function will be called without
15382 arguments, with the cursor positioned at the beginning of the headline.
15383 The return values of all calls to the function will be collected and
15384 returned as a list.
15386 The call to FUNC will be wrapped into a save-excursion form, so FUNC
15387 does not need to preserve point. After evaluation, the cursor will be
15388 moved to the end of the line (presumably of the headline of the
15389 processed entry) and search continues from there. Under some
15390 circumstances, this may not produce the wanted results. For example,
15391 if you have removed (e.g. archived) the current (sub)tree it could
15392 mean that the next entry will be skipped entirely. In such cases, you
15393 can specify the position from where search should continue by making
15394 FUNC set the variable `org-map-continue-from' to the desired buffer
15395 position.
15397 MATCH is a tags/property/todo match as it is used in the agenda tags view.
15398 Only headlines that are matched by this query will be considered during
15399 the iteration. When MATCH is nil or t, all headlines will be
15400 visited by the iteration.
15402 SCOPE determines the scope of this command. It can be any of:
15404 nil The current buffer, respecting the restriction if any
15405 tree The subtree started with the entry at point
15406 region The entries within the active region, if any
15407 region-start-level
15408 The entries within the active region, but only those at
15409 the same level than the first one.
15410 file The current buffer, without restriction
15411 file-with-archives
15412 The current buffer, and any archives associated with it
15413 agenda All agenda files
15414 agenda-with-archives
15415 All agenda files with any archive files associated with them
15416 \(file1 file2 ...)
15417 If this is a list, all files in the list will be scanned
15419 The remaining args are treated as settings for the skipping facilities of
15420 the scanner. The following items can be given here:
15422 archive skip trees with the archive tag
15423 comment skip trees with the COMMENT keyword
15424 function or Emacs Lisp form:
15425 will be used as value for `org-agenda-skip-function', so
15426 whenever the function returns a position, FUNC will not be
15427 called for that entry and search will continue from the
15428 position returned
15430 If your function needs to retrieve the tags including inherited tags
15431 at the *current* entry, you can use the value of the variable
15432 `org-scanner-tags' which will be much faster than getting the value
15433 with `org-get-tags-at'. If your function gets properties with
15434 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
15435 to t around the call to `org-entry-properties' to get the same speedup.
15436 Note that if your function moves around to retrieve tags and properties at
15437 a *different* entry, you cannot use these techniques."
15438 (unless (and (or (eq scope 'region) (eq scope 'region-start-level))
15439 (not (org-region-active-p)))
15440 (let* ((org-agenda-archives-mode nil) ; just to make sure
15441 (org-agenda-skip-archived-trees (memq 'archive skip))
15442 (org-agenda-skip-comment-trees (memq 'comment skip))
15443 (org-agenda-skip-function
15444 (car (org-delete-all '(comment archive) skip)))
15445 (org-tags-match-list-sublevels t)
15446 (start-level (eq scope 'region-start-level))
15447 matcher res
15448 org-todo-keywords-for-agenda
15449 org-done-keywords-for-agenda
15450 org-todo-keyword-alist-for-agenda
15451 org-tag-alist-for-agenda
15452 org--matcher-tags-todo-only)
15454 (cond
15455 ((eq match t) (setq matcher t))
15456 ((eq match nil) (setq matcher t))
15457 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
15459 (save-excursion
15460 (save-restriction
15461 (cond ((eq scope 'tree)
15462 (org-back-to-heading t)
15463 (org-narrow-to-subtree)
15464 (setq scope nil))
15465 ((and (or (eq scope 'region) (eq scope 'region-start-level))
15466 (org-region-active-p))
15467 ;; If needed, set start-level to a string like "2"
15468 (when start-level
15469 (save-excursion
15470 (goto-char (region-beginning))
15471 (unless (org-at-heading-p) (outline-next-heading))
15472 (setq start-level (org-current-level))))
15473 (narrow-to-region (region-beginning)
15474 (save-excursion
15475 (goto-char (region-end))
15476 (unless (and (bolp) (org-at-heading-p))
15477 (outline-next-heading))
15478 (point)))
15479 (setq scope nil)))
15481 (if (not scope)
15482 (progn
15483 (org-agenda-prepare-buffers
15484 (and buffer-file-name (list buffer-file-name)))
15485 (setq res
15486 (org-scan-tags
15487 func matcher org--matcher-tags-todo-only start-level)))
15488 ;; Get the right scope
15489 (cond
15490 ((and scope (listp scope) (symbolp (car scope)))
15491 (setq scope (eval scope)))
15492 ((eq scope 'agenda)
15493 (setq scope (org-agenda-files t)))
15494 ((eq scope 'agenda-with-archives)
15495 (setq scope (org-agenda-files t))
15496 (setq scope (org-add-archive-files scope)))
15497 ((eq scope 'file)
15498 (setq scope (and buffer-file-name (list buffer-file-name))))
15499 ((eq scope 'file-with-archives)
15500 (setq scope (org-add-archive-files (list (buffer-file-name))))))
15501 (org-agenda-prepare-buffers scope)
15502 (dolist (file scope)
15503 (with-current-buffer (org-find-base-buffer-visiting file)
15504 (save-excursion
15505 (save-restriction
15506 (widen)
15507 (goto-char (point-min))
15508 (setq res
15509 (append
15511 (org-scan-tags
15512 func matcher org--matcher-tags-todo-only))))))))))
15513 res)))
15515 ;;; Properties API
15517 (defconst org-special-properties
15518 '("ALLTAGS" "BLOCKED" "CLOCKSUM" "CLOCKSUM_T" "CLOSED" "DEADLINE" "FILE"
15519 "ITEM" "PRIORITY" "SCHEDULED" "TAGS" "TIMESTAMP" "TIMESTAMP_IA" "TODO")
15520 "The special properties valid in Org mode.
15521 These are properties that are not defined in the property drawer,
15522 but in some other way.")
15524 (defconst org-default-properties
15525 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
15526 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
15527 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
15528 "EXPORT_OPTIONS" "EXPORT_TEXT" "EXPORT_FILE_NAME"
15529 "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE" "UNNUMBERED"
15530 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER" "REPEAT_TO_STATE"
15531 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
15532 "Some properties that are used by Org mode for various purposes.
15533 Being in this list makes sure that they are offered for completion.")
15535 (defun org--valid-property-p (property)
15536 "Non nil when string PROPERTY is a valid property name."
15537 (not
15538 (or (equal property "")
15539 (org-string-match-p "\\s-" property))))
15541 (defun org--update-property-plist (key val props)
15542 "Associate KEY to VAL in alist PROPS.
15543 Modifications are made by side-effect. Return new alist."
15544 (let* ((appending (string= (substring key -1) "+"))
15545 (key (if appending (substring key 0 -1) key))
15546 (old (assoc-string key props t)))
15547 (if (not old) (cons (cons key val) props)
15548 (setcdr old (if appending (concat (cdr old) " " val) val))
15549 props)))
15551 (defun org-get-property-block (&optional beg force)
15552 "Return the (beg . end) range of the body of the property drawer.
15553 BEG is the beginning of the current subtree, or of the part
15554 before the first headline. If it is not given, it will be found.
15555 If the drawer does not exist, create it if FORCE is non-nil, or
15556 return nil."
15557 (org-with-wide-buffer
15558 (when beg (goto-char beg))
15559 (unless (org-before-first-heading-p)
15560 (let ((beg (cond (beg)
15561 ((or (not (featurep 'org-inlinetask))
15562 (org-inlinetask-in-task-p))
15563 (org-back-to-heading t))
15564 (t (org-with-limited-levels (org-back-to-heading t))))))
15565 (forward-line)
15566 (when (org-looking-at-p org-planning-line-re) (forward-line))
15567 (cond ((looking-at org-property-drawer-re)
15568 (forward-line)
15569 (cons (point) (progn (goto-char (match-end 0))
15570 (line-beginning-position))))
15571 (force
15572 (goto-char beg)
15573 (org-insert-property-drawer)
15574 (let ((pos (save-excursion (search-forward ":END:")
15575 (line-beginning-position))))
15576 (cons pos pos))))))))
15578 (defun org-at-property-p ()
15579 "Non-nil when point is inside a property drawer.
15580 See `org-property-re' for match data, if applicable."
15581 (save-excursion
15582 (beginning-of-line)
15583 (and (looking-at org-property-re)
15584 (let ((property-drawer (save-match-data (org-get-property-block))))
15585 (and property-drawer
15586 (>= (point) (car property-drawer))
15587 (< (point) (cdr property-drawer)))))))
15589 (defun org-property-action ()
15590 "Do an action on properties."
15591 (interactive)
15592 (unless (org-at-property-p) (user-error "Not at a property"))
15593 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
15594 (let ((c (read-char-exclusive)))
15595 (cl-case c
15596 (?s (call-interactively #'org-set-property))
15597 (?d (call-interactively #'org-delete-property))
15598 (?D (call-interactively #'org-delete-property-globally))
15599 (?c (call-interactively #'org-compute-property-at-point))
15600 (otherwise (user-error "No such property action %c" c)))))
15602 (defun org-inc-effort ()
15603 "Increment the value of the effort property in the current entry."
15604 (interactive)
15605 (org-set-effort nil t))
15607 (defvar org-clock-effort) ; Defined in org-clock.el.
15608 (defvar org-clock-current-task) ; Defined in org-clock.el.
15609 (defun org-set-effort (&optional value increment)
15610 "Set the effort property of the current entry.
15611 With numerical prefix arg, use the nth allowed value, 0 stands for the
15612 10th allowed value.
15614 When INCREMENT is non-nil, set the property to the next allowed value."
15615 (interactive "P")
15616 (when (equal value 0) (setq value 10))
15617 (let* ((completion-ignore-case t)
15618 (prop org-effort-property)
15619 (cur (org-entry-get nil prop))
15620 (allowed (org-property-get-allowed-values nil prop 'table))
15621 (existing (mapcar 'list (org-property-values prop)))
15622 (heading (nth 4 (org-heading-components)))
15624 (val (cond
15625 ((stringp value) value)
15626 ((and allowed (integerp value))
15627 (or (car (nth (1- value) allowed))
15628 (car (org-last allowed))))
15629 ((and allowed increment)
15630 (or (cl-caadr (member (list cur) allowed))
15631 (user-error "Allowed effort values are not set")))
15632 (allowed
15633 (message "Select 1-9,0, [RET%s]: %s"
15634 (if cur (concat "=" cur) "")
15635 (mapconcat 'car allowed " "))
15636 (setq rpl (read-char-exclusive))
15637 (if (equal rpl ?\r)
15639 (setq rpl (- rpl ?0))
15640 (when (equal rpl 0) (setq rpl 10))
15641 (if (and (> rpl 0) (<= rpl (length allowed)))
15642 (car (nth (1- rpl) allowed))
15643 (org-completing-read "Effort: " allowed nil))))
15645 (org-completing-read
15646 (concat "Effort " (if (and cur (string-match "\\S-" cur))
15647 (concat "[" cur "]") "")
15648 ": ")
15649 existing nil nil "" nil cur)))))
15650 (unless (equal (org-entry-get nil prop) val)
15651 (org-entry-put nil prop val))
15652 (org-refresh-property
15653 '((effort . identity)
15654 (effort-minutes . org-duration-string-to-minutes))
15655 val)
15656 (when (string= heading org-clock-current-task)
15657 (setq org-clock-effort (get-text-property (point-at-bol) 'effort))
15658 (org-clock-update-mode-line))
15659 (message "%s is now %s" prop val)))
15661 (defun org-entry-properties (&optional pom which)
15662 "Get all properties of the current entry.
15664 When POM is a buffer position, get all properties from the entry
15665 there instead.
15667 This includes the TODO keyword, the tags, time strings for
15668 deadline, scheduled, and clocking, and any additional properties
15669 defined in the entry.
15671 If WHICH is nil or `all', get all properties. If WHICH is
15672 `special' or `standard', only get that subclass. If WHICH is
15673 a string, only get that property.
15675 Return value is an alist. Keys are properties, as upcased
15676 strings."
15677 (org-with-point-at pom
15678 (when (and (derived-mode-p 'org-mode)
15679 (ignore-errors (org-back-to-heading t)))
15680 (catch 'exit
15681 (let* ((beg (point))
15682 (specific (and (stringp which) (upcase which)))
15683 (which (cond ((not specific) which)
15684 ((member specific org-special-properties) 'special)
15685 (t 'standard)))
15686 props)
15687 ;; Get the special properties, like TODO and TAGS.
15688 (when (memq which '(nil all special))
15689 (when (or (not specific) (string= specific "CLOCKSUM"))
15690 (let ((clocksum (get-text-property (point) :org-clock-minutes)))
15691 (when clocksum
15692 (push (cons "CLOCKSUM"
15693 (org-minutes-to-clocksum-string clocksum))
15694 props)))
15695 (when specific (throw 'exit props)))
15696 (when (or (not specific) (string= specific "CLOCKSUM_T"))
15697 (let ((clocksumt (get-text-property (point)
15698 :org-clock-minutes-today)))
15699 (when clocksumt
15700 (push (cons "CLOCKSUM_T"
15701 (org-minutes-to-clocksum-string clocksumt))
15702 props)))
15703 (when specific (throw 'exit props)))
15704 (when (or (not specific) (string= specific "ITEM"))
15705 (when (looking-at org-complex-heading-regexp)
15706 (push (cons "ITEM"
15707 (let ((title (match-string-no-properties 4)))
15708 (if (org-string-nw-p title)
15709 (org-remove-tabs title)
15710 "")))
15711 props))
15712 (when specific (throw 'exit props)))
15713 (when (or (not specific) (string= specific "TODO"))
15714 (let ((case-fold-search nil))
15715 (when (and (looking-at org-todo-line-regexp) (match-end 2))
15716 (push (cons "TODO" (org-match-string-no-properties 2)) props)))
15717 (when specific (throw 'exit props)))
15718 (when (or (not specific) (string= specific "PRIORITY"))
15719 (push (cons "PRIORITY"
15720 (if (looking-at org-priority-regexp)
15721 (org-match-string-no-properties 2)
15722 (char-to-string org-default-priority)))
15723 props)
15724 (when specific (throw 'exit props)))
15725 (when (or (not specific) (string= specific "FILE"))
15726 (push (cons "FILE" (buffer-file-name (buffer-base-buffer)))
15727 props)
15728 (when specific (throw 'exit props)))
15729 (when (or (not specific) (string= specific "TAGS"))
15730 (let ((value (org-string-nw-p (org-get-tags-string))))
15731 (when value (push (cons "TAGS" value) props)))
15732 (when specific (throw 'exit props)))
15733 (when (or (not specific) (string= specific "ALLTAGS"))
15734 (let ((value (org-get-tags-at)))
15735 (when value
15736 (push (cons "ALLTAGS"
15737 (format ":%s:" (mapconcat #'identity value ":")))
15738 props)))
15739 (when specific (throw 'exit props)))
15740 (when (or (not specific) (string= specific "BLOCKED"))
15741 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props)
15742 (when specific (throw 'exit props)))
15743 (when (or (not specific)
15744 (member specific '("CLOSED" "DEADLINE" "SCHEDULED")))
15745 (forward-line)
15746 (when (org-looking-at-p org-planning-line-re)
15747 (end-of-line)
15748 (let ((bol (line-beginning-position))
15749 ;; Backward compatibility: time keywords used to
15750 ;; be configurable (before 8.3). Make sure we
15751 ;; get the correct keyword.
15752 (key-assoc `(("CLOSED" . ,org-closed-string)
15753 ("DEADLINE" . ,org-deadline-string)
15754 ("SCHEDULED" . ,org-scheduled-string))))
15755 (dolist (pair (if specific (list (assoc specific key-assoc))
15756 key-assoc))
15757 (save-excursion
15758 (when (search-backward (cdr pair) bol t)
15759 (goto-char (match-end 0))
15760 (skip-chars-forward " \t")
15761 (and (looking-at org-ts-regexp-both)
15762 (push (cons (car pair)
15763 (org-match-string-no-properties 0))
15764 props)))))))
15765 (when specific (throw 'exit props)))
15766 (when (or (not specific)
15767 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
15768 (let ((find-ts
15769 (lambda (end ts)
15770 ;; Fix next time-stamp before END. TS is the
15771 ;; list of time-stamps found so far.
15772 (let ((ts ts)
15773 (regexp (cond
15774 ((string= specific "TIMESTAMP")
15775 org-ts-regexp)
15776 ((string= specific "TIMESTAMP_IA")
15777 org-ts-regexp-inactive)
15778 ((assoc "TIMESTAMP_IA" ts)
15779 org-ts-regexp)
15780 ((assoc "TIMESTAMP" ts)
15781 org-ts-regexp-inactive)
15782 (t org-ts-regexp-both))))
15783 (catch 'next
15784 (while (re-search-forward regexp end t)
15785 (backward-char)
15786 (let ((object (org-element-context)))
15787 ;; Accept to match timestamps in node
15788 ;; properties, too.
15789 (when (memq (org-element-type object)
15790 '(node-property timestamp))
15791 (let ((type
15792 (org-element-property :type object)))
15793 (cond
15794 ((and (memq type '(active active-range))
15795 (not (equal specific "TIMESTAMP_IA")))
15796 (unless (assoc "TIMESTAMP" ts)
15797 (push (cons "TIMESTAMP"
15798 (org-element-property
15799 :raw-value object))
15801 (when specific (throw 'exit ts))))
15802 ((and (memq type '(inactive inactive-range))
15803 (not (string= specific "TIMESTAMP")))
15804 (unless (assoc "TIMESTAMP_IA" ts)
15805 (push (cons "TIMESTAMP_IA"
15806 (org-element-property
15807 :raw-value object))
15809 (when specific (throw 'exit ts))))))
15810 ;; Both timestamp types are found,
15811 ;; move to next part.
15812 (when (= (length ts) 2) (throw 'next ts)))))
15813 ts)))))
15814 (goto-char beg)
15815 ;; First look for timestamps within headline.
15816 (let ((ts (funcall find-ts (line-end-position) nil)))
15817 (if (= (length ts) 2) (setq props (nconc ts props))
15818 (forward-line)
15819 ;; Then find timestamps in the section, skipping
15820 ;; planning line.
15821 (when (org-looking-at-p org-planning-line-re)
15822 (forward-line))
15823 (let ((end (save-excursion (outline-next-heading))))
15824 (setq props (nconc (funcall find-ts end ts) props))))))))
15825 ;; Get the standard properties, like :PROP:.
15826 (when (memq which '(nil all standard))
15827 ;; If we are looking after a specific property, delegate
15828 ;; to `org-entry-get', which is faster. However, make an
15829 ;; exception for "CATEGORY", since it can be also set
15830 ;; through keywords (i.e. #+CATEGORY).
15831 (if (and specific (not (equal specific "CATEGORY")))
15832 (let ((value (org-entry-get beg specific nil t)))
15833 (throw 'exit (and value (list (cons specific value)))))
15834 (let ((range (org-get-property-block beg)))
15835 (when range
15836 (let ((end (cdr range)) seen-base)
15837 (goto-char (car range))
15838 ;; Unlike to `org--update-property-plist', we
15839 ;; handle the case where base values is found
15840 ;; after its extension. We also forbid standard
15841 ;; properties to be named as special properties.
15842 (while (re-search-forward org-property-re end t)
15843 (let* ((key (upcase (org-match-string-no-properties 2)))
15844 (extendp (org-string-match-p "\\+\\'" key))
15845 (key-base (if extendp (substring key 0 -1) key))
15846 (value (org-match-string-no-properties 3)))
15847 (cond
15848 ((member-ignore-case key-base org-special-properties))
15849 (extendp
15850 (setq props
15851 (org--update-property-plist key value props)))
15852 ((member key seen-base))
15853 (t (push key seen-base)
15854 (let ((p (assoc-string key props t)))
15855 (if p (setcdr p (concat value " " (cdr p)))
15856 (push (cons key value) props))))))))))))
15857 (unless (assoc "CATEGORY" props)
15858 (push (cons "CATEGORY" (org-get-category beg)) props)
15859 (when (string= specific "CATEGORY") (throw 'exit props)))
15860 ;; Return value.
15861 props)))))
15863 (defun org-property--local-values (property literal-nil)
15864 "Return value for PROPERTY in current entry.
15865 Value is a list whose car is the base value for PROPERTY and cdr
15866 a list of accumulated values. Return nil if neither is found in
15867 the entry. Also return nil when PROPERTY is set to \"nil\",
15868 unless LITERAL-NIL is non-nil."
15869 (let ((range (org-get-property-block)))
15870 (when range
15871 (goto-char (car range))
15872 (let* ((case-fold-search t)
15873 (end (cdr range))
15874 (value
15875 ;; Base value.
15876 (save-excursion
15877 (let ((v (and (re-search-forward
15878 (org-re-property property nil t) end t)
15879 (org-match-string-no-properties 3))))
15880 (list (if literal-nil v (org-not-nil v)))))))
15881 ;; Find additional values.
15882 (let* ((property+ (org-re-property (concat property "+") nil t)))
15883 (while (re-search-forward property+ end t)
15884 (push (org-match-string-no-properties 3) value)))
15885 ;; Return final values.
15886 (and (not (equal value '(nil))) (nreverse value))))))
15888 (defun org-entry-get (pom property &optional inherit literal-nil)
15889 "Get value of PROPERTY for entry or content at point-or-marker POM.
15891 If INHERIT is non-nil and the entry does not have the property,
15892 then also check higher levels of the hierarchy. If INHERIT is
15893 the symbol `selective', use inheritance only if the setting in
15894 `org-use-property-inheritance' selects PROPERTY for inheritance.
15896 If the property is present but empty, the return value is the
15897 empty string. If the property is not present at all, nil is
15898 returned. In any other case, return the value as a string.
15899 Search is case-insensitive.
15901 If LITERAL-NIL is set, return the string value \"nil\" as
15902 a string, do not interpret it as the list atom nil. This is used
15903 for inheritance when a \"nil\" value can supersede a non-nil
15904 value higher up the hierarchy."
15905 (org-with-point-at pom
15906 (cond
15907 ((member-ignore-case property (cons "CATEGORY" org-special-properties))
15908 ;; We need a special property. Use `org-entry-properties' to
15909 ;; retrieve it, but specify the wanted property.
15910 (cdr (assoc-string property (org-entry-properties nil property))))
15911 ((and inherit
15912 (or (not (eq inherit 'selective)) (org-property-inherit-p property)))
15913 (org-entry-get-with-inheritance property literal-nil))
15915 (let* ((local (org-property--local-values property literal-nil))
15916 (value (and local (mapconcat #'identity (delq nil local) " "))))
15917 (if literal-nil value (org-not-nil value)))))))
15919 (defun org-property-or-variable-value (var &optional inherit)
15920 "Check if there is a property fixing the value of VAR.
15921 If yes, return this value. If not, return the current value of the variable."
15922 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
15923 (if (and prop (stringp prop) (string-match "\\S-" prop))
15924 (read prop)
15925 (symbol-value var))))
15927 (defun org-entry-delete (pom property)
15928 "Delete PROPERTY from entry at point-or-marker POM.
15929 Accumulated properties, i.e. PROPERTY+, are also removed. Return
15930 non-nil when a property was removed."
15931 (unless (member property org-special-properties)
15932 (org-with-point-at pom
15933 (let ((range (org-get-property-block)))
15934 (when range
15935 (let* ((begin (car range))
15936 (origin (cdr range))
15937 (end (copy-marker origin))
15938 (re (org-re-property
15939 (concat (regexp-quote property) "\\+?") t t)))
15940 (goto-char begin)
15941 (while (re-search-forward re end t)
15942 (delete-region (match-beginning 0) (line-beginning-position 2)))
15943 ;; If drawer is empty, remove it altogether.
15944 (when (= begin end)
15945 (delete-region (line-beginning-position 0)
15946 (line-beginning-position 2)))
15947 ;; Return non-nil if some property was removed.
15948 (prog1 (/= end origin) (set-marker end nil))))))))
15950 ;; Multi-values properties are properties that contain multiple values
15951 ;; These values are assumed to be single words, separated by whitespace.
15952 (defun org-entry-add-to-multivalued-property (pom property value)
15953 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
15954 (let* ((old (org-entry-get pom property))
15955 (values (and old (org-split-string old "[ \t]"))))
15956 (setq value (org-entry-protect-space value))
15957 (unless (member value values)
15958 (setq values (append values (list value)))
15959 (org-entry-put pom property
15960 (mapconcat 'identity values " ")))))
15962 (defun org-entry-remove-from-multivalued-property (pom property value)
15963 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
15964 (let* ((old (org-entry-get pom property))
15965 (values (and old (org-split-string old "[ \t]"))))
15966 (setq value (org-entry-protect-space value))
15967 (when (member value values)
15968 (setq values (delete value values))
15969 (org-entry-put pom property
15970 (mapconcat 'identity values " ")))))
15972 (defun org-entry-member-in-multivalued-property (pom property value)
15973 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
15974 (let* ((old (org-entry-get pom property))
15975 (values (and old (org-split-string old "[ \t]"))))
15976 (setq value (org-entry-protect-space value))
15977 (member value values)))
15979 (defun org-entry-get-multivalued-property (pom property)
15980 "Return a list of values in a multivalued property."
15981 (let* ((value (org-entry-get pom property))
15982 (values (and value (org-split-string value "[ \t]"))))
15983 (mapcar 'org-entry-restore-space values)))
15985 (defun org-entry-put-multivalued-property (pom property &rest values)
15986 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
15987 VALUES should be a list of strings. Spaces will be protected."
15988 (org-entry-put pom property
15989 (mapconcat 'org-entry-protect-space values " "))
15990 (let* ((value (org-entry-get pom property))
15991 (values (and value (org-split-string value "[ \t]"))))
15992 (mapcar 'org-entry-restore-space values)))
15994 (defun org-entry-protect-space (s)
15995 "Protect spaces and newline in string S."
15996 (while (string-match " " s)
15997 (setq s (replace-match "%20" t t s)))
15998 (while (string-match "\n" s)
15999 (setq s (replace-match "%0A" t t s)))
16002 (defun org-entry-restore-space (s)
16003 "Restore spaces and newline in string S."
16004 (while (string-match "%20" s)
16005 (setq s (replace-match " " t t s)))
16006 (while (string-match "%0A" s)
16007 (setq s (replace-match "\n" t t s)))
16010 (defvar org-entry-property-inherited-from (make-marker)
16011 "Marker pointing to the entry from where a property was inherited.
16012 Each call to `org-entry-get-with-inheritance' will set this marker to the
16013 location of the entry where the inheritance search matched. If there was
16014 no match, the marker will point nowhere.
16015 Note that also `org-entry-get' calls this function, if the INHERIT flag
16016 is set.")
16018 (defun org-entry-get-with-inheritance (property &optional literal-nil)
16019 "Get PROPERTY of entry or content at point, search higher levels if needed.
16020 The search will stop at the first ancestor which has the property defined.
16021 If the value found is \"nil\", return nil to show that the property
16022 should be considered as undefined (this is the meaning of nil here).
16023 However, if LITERAL-NIL is set, return the string value \"nil\" instead."
16024 (move-marker org-entry-property-inherited-from nil)
16025 (org-with-wide-buffer
16026 (let (value)
16027 (catch 'exit
16028 (while t
16029 (let ((v (org-property--local-values property literal-nil)))
16030 (when v
16031 (setq value
16032 (concat (mapconcat #'identity (delq nil v) " ")
16033 (and value " ")
16034 value)))
16035 (cond
16036 ((car v)
16037 (org-back-to-heading t)
16038 (move-marker org-entry-property-inherited-from (point))
16039 (throw 'exit nil))
16040 ((org-up-heading-safe))
16042 (let ((global
16043 (cdr (or (assoc-string property org-file-properties t)
16044 (assoc-string property org-global-properties t)
16045 (assoc-string property org-global-properties-fixed t)))))
16046 (cond ((not global))
16047 (value (setq value (concat global " " value)))
16048 (t (setq value global))))
16049 (throw 'exit nil))))))
16050 (if literal-nil value (org-not-nil value)))))
16052 (defvar org-property-changed-functions nil
16053 "Hook called when the value of a property has changed.
16054 Each hook function should accept two arguments, the name of the property
16055 and the new value.")
16057 (defun org-entry-put (pom property value)
16058 "Set PROPERTY to VALUE for entry at point-or-marker POM.
16060 If the value is nil, it is converted to the empty string. If it
16061 is not a string, an error is raised. Also raise an error on
16062 invalid property names.
16064 PROPERTY can be any regular property (see
16065 `org-special-properties'). It can also be \"TODO\",
16066 \"PRIORITY\", \"SCHEDULED\" and \"DEADLINE\".
16068 For the last two properties, VALUE may have any of the special
16069 values \"earlier\" and \"later\". The function then increases or
16070 decreases scheduled or deadline date by one day."
16071 (cond ((null value) (setq value ""))
16072 ((not (stringp value)) (error "Properties values should be strings"))
16073 ((not (org--valid-property-p property))
16074 (user-error "Invalid property name: \"%s\"" property)))
16075 (org-with-point-at pom
16076 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16077 (org-back-to-heading t)
16078 (org-with-limited-levels (org-back-to-heading t)))
16079 (let ((beg (point)))
16080 (cond
16081 ((equal property "TODO")
16082 (cond ((not (org-string-nw-p value)) (setq value 'none))
16083 ((not (member value org-todo-keywords-1))
16084 (user-error "\"%s\" is not a valid TODO state" value)))
16085 (org-todo value)
16086 (org-set-tags nil 'align))
16087 ((equal property "PRIORITY")
16088 (org-priority (if (org-string-nw-p value) (string-to-char value) ?\s))
16089 (org-set-tags nil 'align))
16090 ((equal property "SCHEDULED")
16091 (forward-line)
16092 (if (and (org-looking-at-p org-planning-line-re)
16093 (re-search-forward
16094 org-scheduled-time-regexp (line-end-position) t))
16095 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16096 ((string= value "later") (org-timestamp-change 1 'day))
16097 ((string= value "") (org-schedule '(4)))
16098 (t (org-schedule nil value)))
16099 (if (member value '("earlier" "later" ""))
16100 (call-interactively #'org-schedule)
16101 (org-schedule nil value))))
16102 ((equal property "DEADLINE")
16103 (forward-line)
16104 (if (and (org-looking-at-p org-planning-line-re)
16105 (re-search-forward
16106 org-deadline-time-regexp (line-end-position) t))
16107 (cond ((string= value "earlier") (org-timestamp-change -1 'day))
16108 ((string= value "later") (org-timestamp-change 1 'day))
16109 ((string= value "") (org-deadline '(4)))
16110 (t (org-deadline nil value)))
16111 (if (member value '("earlier" "later" ""))
16112 (call-interactively #'org-deadline)
16113 (org-deadline nil value))))
16114 ((member property org-special-properties)
16115 (error "The %s property cannot be set with `org-entry-put'" property))
16117 (let* ((range (org-get-property-block beg 'force))
16118 (end (cdr range))
16119 (case-fold-search t))
16120 (goto-char (car range))
16121 (if (re-search-forward (org-re-property property nil t) end t)
16122 (progn (delete-region (match-beginning 0) (match-end 0))
16123 (goto-char (match-beginning 0)))
16124 (goto-char end)
16125 (insert "\n")
16126 (backward-char))
16127 (insert ":" property ":")
16128 (when value (insert " " value))
16129 (org-indent-line)))))
16130 (run-hook-with-args 'org-property-changed-functions property value)))
16132 (defun org-buffer-property-keys
16133 (&optional specials defaults columns ignore-malformed)
16134 "Get all property keys in the current buffer.
16136 When SPECIALS is non-nil, also list the special properties that
16137 reflect things like tags and TODO state.
16139 When DEFAULTS is non-nil, also include properties that has
16140 special meaning internally: ARCHIVE, CATEGORY, SUMMARY,
16141 DESCRIPTION, LOCATION, and LOGGING and others.
16143 When COLUMNS in non-nil, also include property names given in
16144 COLUMN formats in the current buffer.
16146 When IGNORE-MALFORMED is non-nil, malformed drawer repair will not be
16147 automatically performed, such drawers will be silently ignored."
16148 (let ((case-fold-search t)
16149 (props (append
16150 (and specials org-special-properties)
16151 (and defaults (cons org-effort-property org-default-properties))
16152 nil)))
16153 (org-with-wide-buffer
16154 (goto-char (point-min))
16155 (while (re-search-forward org-property-start-re nil t)
16156 (let ((range (org-get-property-block)))
16157 (catch 'skip
16158 (unless range
16159 (when (and (not ignore-malformed)
16160 (not (org-before-first-heading-p))
16161 (y-or-n-p (format "Malformed drawer at %d, repair?"
16162 (line-beginning-position))))
16163 (org-get-property-block nil t))
16164 (throw 'skip nil))
16165 (goto-char (car range))
16166 (let ((begin (car range))
16167 (end (cdr range)))
16168 ;; Make sure that found property block is not located
16169 ;; before current point, as it would generate an infloop.
16170 ;; It can happen, for example, in the following
16171 ;; situation:
16173 ;; * Headline
16174 ;; :PROPERTIES:
16175 ;; ...
16176 ;; :END:
16177 ;; *************** Inlinetask
16178 ;; #+BEGIN_EXAMPLE
16179 ;; :PROPERTIES:
16180 ;; #+END_EXAMPLE
16182 (if (< begin (point)) (throw 'skip nil) (goto-char begin))
16183 (while (< (point) end)
16184 (let ((p (progn (looking-at org-property-re)
16185 (org-match-string-no-properties 2))))
16186 ;; Only add true property name, not extension symbol.
16187 (push (if (not (org-string-match-p "\\+\\'" p)) p
16188 (substring p 0 -1))
16189 props))
16190 (forward-line))))
16191 (outline-next-heading)))
16192 (when columns
16193 (goto-char (point-min))
16194 (while (re-search-forward "^[ \t]*\\(?:#\\+\\|:\\)COLUMNS:" nil t)
16195 (let ((element (org-element-at-point)))
16196 (when (memq (org-element-type element) '(keyword node-property))
16197 (let ((value (org-element-property :value element))
16198 (start 0))
16199 (while (string-match "%[0-9]*\\(\\S-+\\)" value start)
16200 (setq start (match-end 0))
16201 (let ((p (org-match-string-no-properties 1 value)))
16202 (unless (member-ignore-case p org-special-properties)
16203 (push p props))))))))))
16204 (sort (delete-dups props) (lambda (a b) (string< (upcase a) (upcase b))))))
16206 (defun org-property-values (key)
16207 "List all non-nil values of property KEY in current buffer."
16208 (org-with-wide-buffer
16209 (goto-char (point-min))
16210 (let ((case-fold-search t)
16211 (re (org-re-property key))
16212 values)
16213 (while (re-search-forward re nil t)
16214 (push (org-entry-get (point) key) values))
16215 (delete-dups values))))
16217 (defun org-insert-property-drawer ()
16218 "Insert a property drawer into the current entry."
16219 (org-with-wide-buffer
16220 (if (or (not (featurep 'org-inlinetask)) (org-inlinetask-in-task-p))
16221 (org-back-to-heading t)
16222 (org-with-limited-levels (org-back-to-heading t)))
16223 (forward-line)
16224 (when (org-looking-at-p org-planning-line-re) (forward-line))
16225 (unless (org-looking-at-p org-property-drawer-re)
16226 ;; Make sure we start editing a line from current entry, not from
16227 ;; next one. It prevents extending text properties or overlays
16228 ;; belonging to the latter.
16229 (when (bolp) (backward-char))
16230 (let ((begin (1+ (point)))
16231 (inhibit-read-only t))
16232 (insert "\n:PROPERTIES:\n:END:")
16233 (when (eobp) (insert "\n"))
16234 (org-indent-region begin (point))))))
16236 (defun org-insert-drawer (&optional arg drawer)
16237 "Insert a drawer at point.
16239 When optional argument ARG is non-nil, insert a property drawer.
16241 Optional argument DRAWER, when non-nil, is a string representing
16242 drawer's name. Otherwise, the user is prompted for a name.
16244 If a region is active, insert the drawer around that region
16245 instead.
16247 Point is left between drawer's boundaries."
16248 (interactive "P")
16249 (let* ((drawer (if arg "PROPERTIES"
16250 (or drawer (read-from-minibuffer "Drawer: ")))))
16251 (cond
16252 ;; With C-u, fall back on `org-insert-property-drawer'
16253 (arg (org-insert-property-drawer))
16254 ;; Check validity of suggested drawer's name.
16255 ((not (org-string-match-p org-drawer-regexp (format ":%s:" drawer)))
16256 (user-error "Invalid drawer name"))
16257 ;; With an active region, insert a drawer at point.
16258 ((not (org-region-active-p))
16259 (progn
16260 (unless (bolp) (insert "\n"))
16261 (insert (format ":%s:\n\n:END:\n" drawer))
16262 (forward-line -2)))
16263 ;; Otherwise, insert the drawer at point
16265 (let ((rbeg (region-beginning))
16266 (rend (copy-marker (region-end))))
16267 (unwind-protect
16268 (progn
16269 (goto-char rbeg)
16270 (beginning-of-line)
16271 (when (save-excursion
16272 (re-search-forward org-outline-regexp-bol rend t))
16273 (user-error "Drawers cannot contain headlines"))
16274 ;; Position point at the beginning of the first
16275 ;; non-blank line in region. Insert drawer's opening
16276 ;; there, then indent it.
16277 (org-skip-whitespace)
16278 (beginning-of-line)
16279 (insert ":" drawer ":\n")
16280 (forward-line -1)
16281 (indent-for-tab-command)
16282 ;; Move point to the beginning of the first blank line
16283 ;; after the last non-blank line in region. Insert
16284 ;; drawer's closing, then indent it.
16285 (goto-char rend)
16286 (skip-chars-backward " \r\t\n")
16287 (insert "\n:END:")
16288 (deactivate-mark t)
16289 (indent-for-tab-command)
16290 (unless (eolp) (insert "\n")))
16291 ;; Clear marker, whatever the outcome of insertion is.
16292 (set-marker rend nil)))))))
16294 (defvar org-property-set-functions-alist nil
16295 "Property set function alist.
16296 Each entry should have the following format:
16298 (PROPERTY . READ-FUNCTION)
16300 The read function will be called with the same argument as
16301 `org-completing-read'.")
16303 (defun org-set-property-function (property)
16304 "Get the function that should be used to set PROPERTY.
16305 This is computed according to `org-property-set-functions-alist'."
16306 (or (cdr (assoc property org-property-set-functions-alist))
16307 'org-completing-read))
16309 (defun org-read-property-value (property)
16310 "Read PROPERTY value from user."
16311 (let* ((completion-ignore-case t)
16312 (allowed (org-property-get-allowed-values nil property 'table))
16313 (cur (org-entry-get nil property))
16314 (prompt (concat property " value"
16315 (if (and cur (string-match "\\S-" cur))
16316 (concat " [" cur "]") "") ": "))
16317 (set-function (org-set-property-function property))
16318 (val (if allowed
16319 (funcall set-function prompt allowed nil
16320 (not (get-text-property 0 'org-unrestricted
16321 (caar allowed))))
16322 (funcall set-function prompt
16323 (mapcar 'list (org-property-values property))
16324 nil nil "" nil cur))))
16325 (org-trim val)))
16327 (defvar org-last-set-property nil)
16328 (defvar org-last-set-property-value nil)
16329 (defun org-read-property-name ()
16330 "Read a property name."
16331 (let ((completion-ignore-case t)
16332 (default-prop (or (and (org-at-property-p)
16333 (org-match-string-no-properties 2))
16334 org-last-set-property)))
16335 (org-completing-read
16336 (concat "Property"
16337 (if default-prop (concat " [" default-prop "]") "")
16338 ": ")
16339 (mapcar #'list (org-buffer-property-keys nil t t))
16340 nil nil nil nil default-prop)))
16342 (defun org-set-property-and-value (use-last)
16343 "Allow to set [PROPERTY]: [value] direction from prompt.
16344 When use-default, don't even ask, just use the last
16345 \"[PROPERTY]: [value]\" string from the history."
16346 (interactive "P")
16347 (let* ((completion-ignore-case t)
16348 (pv (or (and use-last org-last-set-property-value)
16349 (org-completing-read
16350 "Enter a \"[Property]: [value]\" pair: "
16351 nil nil nil nil nil
16352 org-last-set-property-value)))
16353 prop val)
16354 (when (string-match "^[ \t]*\\([^:]+\\):[ \t]*\\(.*\\)[ \t]*$" pv)
16355 (setq prop (match-string 1 pv)
16356 val (match-string 2 pv))
16357 (org-set-property prop val))))
16359 (defun org-set-property (property value)
16360 "In the current entry, set PROPERTY to VALUE.
16362 When called interactively, this will prompt for a property name, offering
16363 completion on existing and default properties. And then it will prompt
16364 for a value, offering completion either on allowed values (via an inherited
16365 xxx_ALL property) or on existing values in other instances of this property
16366 in the current file.
16368 Throw an error when trying to set a property with an invalid name."
16369 (interactive (list nil nil))
16370 (let ((property (or property (org-read-property-name))))
16371 ;; `org-entry-put' also makes the following check, but this one
16372 ;; avoids polluting `org-last-set-property' and
16373 ;; `org-last-set-property-value' needlessly.
16374 (unless (org--valid-property-p property)
16375 (user-error "Invalid property name: \"%s\"" property))
16376 (let ((value (or value (org-read-property-value property)))
16377 (fn (cdr (assoc-string property org-properties-postprocess-alist t))))
16378 (setq org-last-set-property property)
16379 (setq org-last-set-property-value (concat property ": " value))
16380 ;; Possibly postprocess the inserted value:
16381 (when fn (setq value (funcall fn value)))
16382 (unless (equal (org-entry-get nil property) value)
16383 (org-entry-put nil property value)))))
16385 (defun org-find-property (property &optional value)
16386 "Find first entry in buffer that sets PROPERTY.
16388 When optional argument VALUE is non-nil, only consider an entry
16389 if it contains PROPERTY set to this value. If PROPERTY should be
16390 explicitly set to nil, use string \"nil\" for VALUE.
16392 Return position where the entry begins, or nil if there is no
16393 such entry. If narrowing is in effect, only search the visible
16394 part of the buffer."
16395 (save-excursion
16396 (goto-char (point-min))
16397 (let ((case-fold-search t)
16398 (re (org-re-property property nil (not value) value)))
16399 (catch 'exit
16400 (while (re-search-forward re nil t)
16401 (when (if value (org-at-property-p)
16402 (org-entry-get (point) property nil t))
16403 (throw 'exit (progn (org-back-to-heading t) (point)))))))))
16405 (defun org-delete-property (property)
16406 "In the current entry, delete PROPERTY."
16407 (interactive
16408 (let* ((completion-ignore-case t)
16409 (cat (org-entry-get (point) "CATEGORY"))
16410 (props0 (org-entry-properties nil 'standard))
16411 (props (if cat props0
16412 (delete `("CATEGORY" . ,(org-get-category)) props0)))
16413 (prop (if (< 1 (length props))
16414 (completing-read "Property: " props nil t)
16415 (caar props))))
16416 (list prop)))
16417 (if (not property)
16418 (message "No property to delete in this entry")
16419 (org-entry-delete nil property)
16420 (message "Property \"%s\" deleted" property)))
16422 (defun org-delete-property-globally (property)
16423 "Remove PROPERTY globally, from all entries.
16424 This function ignores narrowing, if any."
16425 (interactive
16426 (let* ((completion-ignore-case t)
16427 (prop (completing-read
16428 "Globally remove property: "
16429 (mapcar #'list (org-buffer-property-keys)))))
16430 (list prop)))
16431 (org-with-wide-buffer
16432 (goto-char (point-min))
16433 (let ((count 0)
16434 (re (org-re-property (concat (regexp-quote property) "\\+?") t t)))
16435 (while (re-search-forward re nil t)
16436 (when (org-entry-delete (point) property) (cl-incf count)))
16437 (message "Property \"%s\" removed from %d entries" property count))))
16439 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
16441 (defun org-compute-property-at-point ()
16442 "Compute the property at point.
16443 This looks for an enclosing column format, extracts the operator and
16444 then applies it to the property in the column format's scope."
16445 (interactive)
16446 (unless (org-at-property-p)
16447 (user-error "Not at a property"))
16448 (let ((prop (org-match-string-no-properties 2)))
16449 (org-columns-get-format-and-top-level)
16450 (unless (nth 3 (assoc-string prop org-columns-current-fmt-compiled t))
16451 (user-error "No operator defined for property %s" prop))
16452 (org-columns-compute prop)))
16454 (defvar org-property-allowed-value-functions nil
16455 "Hook for functions supplying allowed values for a specific property.
16456 The functions must take a single argument, the name of the property, and
16457 return a flat list of allowed values. If \":ETC\" is one of
16458 the values, this means that these values are intended as defaults for
16459 completion, but that other values should be allowed too.
16460 The functions must return nil if they are not responsible for this
16461 property.")
16463 (defun org-property-get-allowed-values (pom property &optional table)
16464 "Get allowed values for the property PROPERTY.
16465 When TABLE is non-nil, return an alist that can directly be used for
16466 completion."
16467 (let (vals)
16468 (cond
16469 ((equal property "TODO")
16470 (setq vals (org-with-point-at pom
16471 (append org-todo-keywords-1 '("")))))
16472 ((equal property "PRIORITY")
16473 (let ((n org-lowest-priority))
16474 (while (>= n org-highest-priority)
16475 (push (char-to-string n) vals)
16476 (setq n (1- n)))))
16477 ((equal property "CATEGORY"))
16478 ((member property org-special-properties))
16479 ((setq vals (run-hook-with-args-until-success
16480 'org-property-allowed-value-functions property)))
16482 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
16483 (when (and vals (string-match "\\S-" vals))
16484 (setq vals (car (read-from-string (concat "(" vals ")"))))
16485 (setq vals (mapcar (lambda (x)
16486 (cond ((stringp x) x)
16487 ((numberp x) (number-to-string x))
16488 ((symbolp x) (symbol-name x))
16489 (t "???")))
16490 vals)))))
16491 (when (member ":ETC" vals)
16492 (setq vals (remove ":ETC" vals))
16493 (org-add-props (car vals) '(org-unrestricted t)))
16494 (if table (mapcar 'list vals) vals)))
16496 (defun org-property-previous-allowed-value (&optional _previous)
16497 "Switch to the next allowed value for this property."
16498 (interactive)
16499 (org-property-next-allowed-value t))
16501 (defun org-property-next-allowed-value (&optional previous)
16502 "Switch to the next allowed value for this property."
16503 (interactive)
16504 (unless (org-at-property-p)
16505 (user-error "Not at a property"))
16506 (let* ((prop (car (save-match-data (org-split-string (match-string 1) ":"))))
16507 (key (match-string 2))
16508 (value (match-string 3))
16509 (allowed (or (org-property-get-allowed-values (point) key)
16510 (and (member value '("[ ]" "[-]" "[X]"))
16511 '("[ ]" "[X]"))))
16512 (heading (save-match-data (nth 4 (org-heading-components))))
16513 nval)
16514 (unless allowed
16515 (user-error "Allowed values for this property have not been defined"))
16516 (when previous (setq allowed (reverse allowed)))
16517 (when (member value allowed)
16518 (setq nval (car (cdr (member value allowed)))))
16519 (setq nval (or nval (car allowed)))
16520 (when (equal nval value)
16521 (user-error "Only one allowed value for this property"))
16522 (org-at-property-p)
16523 (replace-match (concat " :" key ": " nval) t t)
16524 (org-indent-line)
16525 (beginning-of-line 1)
16526 (skip-chars-forward " \t")
16527 (when (equal prop org-effort-property)
16528 (org-refresh-property
16529 '((effort . identity)
16530 (effort-minutes . org-duration-string-to-minutes))
16531 nval)
16532 (when (string= org-clock-current-task heading)
16533 (setq org-clock-effort nval)
16534 (org-clock-update-mode-line)))
16535 (run-hook-with-args 'org-property-changed-functions key nval)))
16537 (defun org-find-olp (path &optional this-buffer)
16538 "Return a marker pointing to the entry at outline path OLP.
16539 If anything goes wrong, throw an error.
16540 You can wrap this call to catch the error like this:
16542 \(condition-case msg
16543 \(org-mobile-locate-entry (match-string 4))
16544 \(error (nth 1 msg)))
16546 The return value will then be either a string with the error message,
16547 or a marker if everything is OK.
16549 If THIS-BUFFER is set, the outline path does not contain a file,
16550 only headings."
16551 (let* ((file (if this-buffer buffer-file-name (pop path)))
16552 (buffer (if this-buffer (current-buffer) (find-file-noselect file)))
16553 (level 1)
16554 (lmin 1)
16555 (lmax 1)
16556 end found flevel)
16557 (unless buffer (error "File not found :%s" file))
16558 (with-current-buffer buffer
16559 (org-with-wide-buffer
16560 (goto-char (point-min))
16561 (dolist (heading path)
16562 (let ((re (format org-complex-heading-regexp-format
16563 (regexp-quote heading)))
16564 (cnt 0))
16565 (while (re-search-forward re end t)
16566 (setq level (- (match-end 1) (match-beginning 1)))
16567 (when (and (>= level lmin) (<= level lmax))
16568 (setq found (match-beginning 0) flevel level cnt (1+ cnt))))
16569 (when (= cnt 0)
16570 (error "Heading not found on level %d: %s" lmax heading))
16571 (when (> cnt 1)
16572 (error "Heading not unique on level %d: %s" lmax heading))
16573 (goto-char found)
16574 (setq lmin (1+ flevel) lmax (+ lmin (if org-odd-levels-only 1 0)))
16575 (setq end (save-excursion (org-end-of-subtree t t)))))
16576 (when (org-at-heading-p)
16577 (point-marker))))))
16579 (defun org-find-exact-headline-in-buffer (heading &optional buffer pos-only)
16580 "Find node HEADING in BUFFER.
16581 Return a marker to the heading if it was found, or nil if not.
16582 If POS-ONLY is set, return just the position instead of a marker.
16584 The heading text must match exact, but it may have a TODO keyword,
16585 a priority cookie and tags in the standard locations."
16586 (with-current-buffer (or buffer (current-buffer))
16587 (save-excursion
16588 (save-restriction
16589 (widen)
16590 (goto-char (point-min))
16591 (let (case-fold-search)
16592 (when (re-search-forward
16593 (format org-complex-heading-regexp-format
16594 (regexp-quote heading)) nil t)
16595 (if pos-only
16596 (match-beginning 0)
16597 (move-marker (make-marker) (match-beginning 0)))))))))
16599 (defun org-find-exact-heading-in-directory (heading &optional dir)
16600 "Find Org node headline HEADING in all .org files in directory DIR.
16601 When the target headline is found, return a marker to this location."
16602 (let ((files (directory-files (or dir default-directory)
16603 t "\\`[^.#].*\\.org\\'"))
16604 visiting m buffer)
16605 (catch 'found
16606 (dolist (file files)
16607 (message "trying %s" file)
16608 (setq visiting (org-find-base-buffer-visiting file))
16609 (setq buffer (or visiting (find-file-noselect file)))
16610 (setq m (org-find-exact-headline-in-buffer
16611 heading buffer))
16612 (when (and (not m) (not visiting)) (kill-buffer buffer))
16613 (and m (throw 'found m))))))
16615 (defun org-find-entry-with-id (ident)
16616 "Locate the entry that contains the ID property with exact value IDENT.
16617 IDENT can be a string, a symbol or a number, this function will search for
16618 the string representation of it.
16619 Return the position where this entry starts, or nil if there is no such entry."
16620 (interactive "sID: ")
16621 (let ((id (cond
16622 ((stringp ident) ident)
16623 ((symbolp ident) (symbol-name ident))
16624 ((numberp ident) (number-to-string ident))
16625 (t (error "IDENT %s must be a string, symbol or number" ident)))))
16626 (org-with-wide-buffer (org-find-property "ID" id))))
16628 ;;;; Timestamps
16630 (defvar org-last-changed-timestamp nil)
16631 (defvar org-last-inserted-timestamp nil
16632 "The last time stamp inserted with `org-insert-time-stamp'.")
16633 (defvar org-ts-what) ; dynamically scoped parameter
16635 (defun org-time-stamp (arg &optional inactive)
16636 "Prompt for a date/time and insert a time stamp.
16638 If the user specifies a time like HH:MM or if this command is
16639 called with at least one prefix argument, the time stamp contains
16640 the date and the time. Otherwise, only the date is included.
16642 All parts of a date not specified by the user are filled in from
16643 the timestamp at point, if any, or the current date/time
16644 otherwise.
16646 If there is already a timestamp at the cursor, it is replaced.
16648 With two universal prefix arguments, insert an active timestamp
16649 with the current time without prompting the user.
16651 When called from lisp, the timestamp is inactive if INACTIVE is
16652 non-nil."
16653 (interactive "P")
16654 (let* ((ts (cond
16655 ((org-at-date-range-p t)
16656 (match-string (if (< (point) (- (match-beginning 2) 2)) 1 2)))
16657 ((org-at-timestamp-p t) (match-string 0))))
16658 ;; Default time is either the timestamp at point or today.
16659 ;; When entering a range, only the range start is considered.
16660 (default-time (if (not ts) (current-time)
16661 (apply #'encode-time (org-parse-time-string ts))))
16662 (default-input (and ts (org-get-compact-tod ts)))
16663 (repeater (and ts
16664 (string-match "\\([.+-]+[0-9]+[hdwmy] ?\\)+" ts)
16665 (match-string 0 ts)))
16666 org-time-was-given
16667 org-end-time-was-given
16668 (time
16669 (and (if (equal arg '(16)) (current-time)
16670 ;; Preserve `this-command' and `last-command'.
16671 (let ((this-command this-command)
16672 (last-command last-command))
16673 (org-read-date
16674 arg 'totime nil nil default-time default-input
16675 inactive))))))
16676 (cond
16677 ((and ts
16678 (memq last-command '(org-time-stamp org-time-stamp-inactive))
16679 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
16680 (insert "--")
16681 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
16683 ;; Make sure we're on a timestamp. When in the middle of a date
16684 ;; range, move arbitrarily to range end.
16685 (unless (org-at-timestamp-p t)
16686 (skip-chars-forward "-")
16687 (org-at-timestamp-p t))
16688 (replace-match "")
16689 (setq org-last-changed-timestamp
16690 (org-insert-time-stamp
16691 time (or org-time-was-given arg)
16692 inactive nil nil (list org-end-time-was-given)))
16693 (when repeater
16694 (backward-char)
16695 (insert " " repeater)
16696 (setq org-last-changed-timestamp
16697 (concat (substring org-last-inserted-timestamp 0 -1)
16698 " " repeater ">")))
16699 (message "Timestamp updated"))
16700 ((equal arg '(16)) (org-insert-time-stamp time t inactive))
16701 (t (org-insert-time-stamp
16702 time (or org-time-was-given arg) inactive nil nil
16703 (list org-end-time-was-given))))))
16705 ;; FIXME: can we use this for something else, like computing time differences?
16706 (defun org-get-compact-tod (s)
16707 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
16708 (let* ((t1 (match-string 1 s))
16709 (h1 (string-to-number (match-string 2 s)))
16710 (m1 (string-to-number (match-string 3 s)))
16711 (t2 (and (match-end 4) (match-string 5 s)))
16712 (h2 (and t2 (string-to-number (match-string 6 s))))
16713 (m2 (and t2 (string-to-number (match-string 7 s))))
16714 dh dm)
16715 (if (not t2)
16717 (setq dh (- h2 h1) dm (- m2 m1))
16718 (when (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
16719 (concat t1 "+" (number-to-string dh)
16720 (and (/= 0 dm) (format ":%02d" dm)))))))
16722 (defun org-time-stamp-inactive (&optional arg)
16723 "Insert an inactive time stamp.
16724 An inactive time stamp is enclosed in square brackets instead of angle
16725 brackets. It is inactive in the sense that it does not trigger agenda entries,
16726 does not link to the calendar and cannot be changed with the S-cursor keys.
16727 So these are more for recording a certain time/date."
16728 (interactive "P")
16729 (org-time-stamp arg 'inactive))
16731 (defvar org-date-ovl (make-overlay 1 1))
16732 (overlay-put org-date-ovl 'face 'org-date-selected)
16733 (org-detach-overlay org-date-ovl)
16735 (defvar org-ans1) ; dynamically scoped parameter
16736 (defvar org-ans2) ; dynamically scoped parameter
16738 (defvar org-plain-time-of-day-regexp) ; defined below
16740 (defvar org-overriding-default-time nil) ; dynamically scoped
16741 (defvar org-read-date-overlay nil)
16742 (defvar org-dcst nil) ; dynamically scoped
16743 (defvar org-read-date-history nil)
16744 (defvar org-read-date-final-answer nil)
16745 (defvar org-read-date-analyze-futurep nil)
16746 (defvar org-read-date-analyze-forced-year nil)
16747 (defvar org-read-date-inactive)
16749 (defvar org-read-date-minibuffer-local-map
16750 (let* ((map (make-sparse-keymap)))
16751 (set-keymap-parent map minibuffer-local-map)
16752 (org-defkey map (kbd ".")
16753 (lambda () (interactive)
16754 ;; Are we at the beginning of the prompt?
16755 (if (org-looking-back "^[^:]+: "
16756 (let ((inhibit-field-text-motion t))
16757 (line-beginning-position)))
16758 (org-eval-in-calendar '(calendar-goto-today))
16759 (insert "."))))
16760 (org-defkey map (kbd "C-.")
16761 (lambda () (interactive)
16762 (org-eval-in-calendar '(calendar-goto-today))))
16763 (org-defkey map [(meta shift left)]
16764 (lambda () (interactive)
16765 (org-eval-in-calendar '(calendar-backward-month 1))))
16766 (org-defkey map [(meta shift right)]
16767 (lambda () (interactive)
16768 (org-eval-in-calendar '(calendar-forward-month 1))))
16769 (org-defkey map [(meta shift up)]
16770 (lambda () (interactive)
16771 (org-eval-in-calendar '(calendar-backward-year 1))))
16772 (org-defkey map [(meta shift down)]
16773 (lambda () (interactive)
16774 (org-eval-in-calendar '(calendar-forward-year 1))))
16775 (org-defkey map [?\e (shift left)]
16776 (lambda () (interactive)
16777 (org-eval-in-calendar '(calendar-backward-month 1))))
16778 (org-defkey map [?\e (shift right)]
16779 (lambda () (interactive)
16780 (org-eval-in-calendar '(calendar-forward-month 1))))
16781 (org-defkey map [?\e (shift up)]
16782 (lambda () (interactive)
16783 (org-eval-in-calendar '(calendar-backward-year 1))))
16784 (org-defkey map [?\e (shift down)]
16785 (lambda () (interactive)
16786 (org-eval-in-calendar '(calendar-forward-year 1))))
16787 (org-defkey map [(shift up)]
16788 (lambda () (interactive)
16789 (org-eval-in-calendar '(calendar-backward-week 1))))
16790 (org-defkey map [(shift down)]
16791 (lambda () (interactive)
16792 (org-eval-in-calendar '(calendar-forward-week 1))))
16793 (org-defkey map [(shift left)]
16794 (lambda () (interactive)
16795 (org-eval-in-calendar '(calendar-backward-day 1))))
16796 (org-defkey map [(shift right)]
16797 (lambda () (interactive)
16798 (org-eval-in-calendar '(calendar-forward-day 1))))
16799 (org-defkey map "!"
16800 (lambda () (interactive)
16801 (org-eval-in-calendar '(diary-view-entries))
16802 (message "")))
16803 (org-defkey map ">"
16804 (lambda () (interactive)
16805 (org-eval-in-calendar '(calendar-scroll-left 1))))
16806 (org-defkey map "<"
16807 (lambda () (interactive)
16808 (org-eval-in-calendar '(calendar-scroll-right 1))))
16809 (org-defkey map "\C-v"
16810 (lambda () (interactive)
16811 (org-eval-in-calendar
16812 '(calendar-scroll-left-three-months 1))))
16813 (org-defkey map "\M-v"
16814 (lambda () (interactive)
16815 (org-eval-in-calendar
16816 '(calendar-scroll-right-three-months 1))))
16817 map)
16818 "Keymap for minibuffer commands when using `org-read-date'.")
16820 (defvar org-def)
16821 (defvar org-defdecode)
16822 (defvar org-with-time)
16824 (defvar calendar-setup) ; Dynamically scoped.
16825 (defun org-read-date (&optional with-time to-time from-string prompt
16826 default-time default-input inactive)
16827 "Read a date, possibly a time, and make things smooth for the user.
16828 The prompt will suggest to enter an ISO date, but you can also enter anything
16829 which will at least partially be understood by `parse-time-string'.
16830 Unrecognized parts of the date will default to the current day, month, year,
16831 hour and minute. If this command is called to replace a timestamp at point,
16832 or to enter the second timestamp of a range, the default time is taken
16833 from the existing stamp. Furthermore, the command prefers the future,
16834 so if you are giving a date where the year is not given, and the day-month
16835 combination is already past in the current year, it will assume you
16836 mean next year. For details, see the manual. A few examples:
16838 3-2-5 --> 2003-02-05
16839 feb 15 --> currentyear-02-15
16840 2/15 --> currentyear-02-15
16841 sep 12 9 --> 2009-09-12
16842 12:45 --> today 12:45
16843 22 sept 0:34 --> currentyear-09-22 0:34
16844 12 --> currentyear-currentmonth-12
16845 Fri --> nearest Friday after today
16846 -Tue --> last Tuesday
16847 etc.
16849 Furthermore you can specify a relative date by giving, as the *first* thing
16850 in the input: a plus/minus sign, a number and a letter [hdwmy] to indicate
16851 change in days weeks, months, years.
16852 With a single plus or minus, the date is relative to today. With a double
16853 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
16854 +4d --> four days from today
16855 +4 --> same as above
16856 +2w --> two weeks from today
16857 ++5 --> five days from default date
16859 The function understands only English month and weekday abbreviations.
16861 While prompting, a calendar is popped up - you can also select the
16862 date with the mouse (button 1). The calendar shows a period of three
16863 months. To scroll it to other months, use the keys `>' and `<'.
16864 If you don't like the calendar, turn it off with
16865 (setq org-read-date-popup-calendar nil)
16867 With optional argument TO-TIME, the date will immediately be converted
16868 to an internal time.
16869 With an optional argument WITH-TIME, the prompt will suggest to
16870 also insert a time. Note that when WITH-TIME is not set, you can
16871 still enter a time, and this function will inform the calling routine
16872 about this change. The calling routine may then choose to change the
16873 format used to insert the time stamp into the buffer to include the time.
16874 With optional argument FROM-STRING, read from this string instead from
16875 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
16876 the time/date that is used for everything that is not specified by the
16877 user."
16878 (require 'parse-time)
16879 (let* ((org-with-time with-time)
16880 (org-time-stamp-rounding-minutes
16881 (if (equal org-with-time '(16))
16882 '(0 0)
16883 org-time-stamp-rounding-minutes))
16884 (org-dcst org-display-custom-times)
16885 (ct (org-current-time))
16886 (org-def (or org-overriding-default-time default-time ct))
16887 (org-defdecode (decode-time org-def))
16888 (cur-frame (selected-frame))
16889 (mouse-autoselect-window nil) ; Don't let the mouse jump
16890 (calendar-setup
16891 (and (eq calendar-setup 'calendar-only) 'calendar-only))
16892 (calendar-move-hook nil)
16893 (calendar-view-diary-initially-flag nil)
16894 (calendar-view-holidays-initially-flag nil)
16895 ans (org-ans0 "") org-ans1 org-ans2 final cal-frame)
16896 ;; Rationalize `org-def' and `org-defdecode', if required.
16897 (when (< (nth 2 org-defdecode) org-extend-today-until)
16898 (setf (nth 2 org-defdecode) -1)
16899 (setf (nth 1 org-defdecode) 59)
16900 (setq org-def (apply #'encode-time org-defdecode))
16901 (setq org-defdecode (decode-time org-def)))
16902 (let* ((timestr (format-time-string
16903 (if org-with-time "%Y-%m-%d %H:%M" "%Y-%m-%d")
16904 org-def))
16905 (prompt (concat (if prompt (concat prompt " ") "")
16906 (format "Date+time [%s]: " timestr))))
16907 (cond
16908 (from-string (setq ans from-string))
16909 (org-read-date-popup-calendar
16910 (save-excursion
16911 (save-window-excursion
16912 (calendar)
16913 (when (eq calendar-setup 'calendar-only)
16914 (setq cal-frame
16915 (window-frame (get-buffer-window "*Calendar*" 'visible)))
16916 (select-frame cal-frame))
16917 (org-eval-in-calendar '(setq cursor-type nil) t)
16918 (unwind-protect
16919 (progn
16920 (calendar-forward-day (- (time-to-days org-def)
16921 (calendar-absolute-from-gregorian
16922 (calendar-current-date))))
16923 (org-eval-in-calendar nil t)
16924 (let* ((old-map (current-local-map))
16925 (map (copy-keymap calendar-mode-map))
16926 (minibuffer-local-map
16927 (copy-keymap org-read-date-minibuffer-local-map)))
16928 (org-defkey map (kbd "RET") 'org-calendar-select)
16929 (org-defkey map [mouse-1] 'org-calendar-select-mouse)
16930 (org-defkey map [mouse-2] 'org-calendar-select-mouse)
16931 (unwind-protect
16932 (progn
16933 (use-local-map map)
16934 (setq org-read-date-inactive inactive)
16935 (add-hook 'post-command-hook 'org-read-date-display)
16936 (setq org-ans0
16937 (read-string prompt
16938 default-input
16939 'org-read-date-history
16940 nil))
16941 ;; org-ans0: from prompt
16942 ;; org-ans1: from mouse click
16943 ;; org-ans2: from calendar motion
16944 (setq ans
16945 (concat org-ans0 " " (or org-ans1 org-ans2))))
16946 (remove-hook 'post-command-hook 'org-read-date-display)
16947 (use-local-map old-map)
16948 (when org-read-date-overlay
16949 (delete-overlay org-read-date-overlay)
16950 (setq org-read-date-overlay nil)))))
16951 (bury-buffer "*Calendar*")
16952 (when cal-frame
16953 (delete-frame cal-frame)
16954 (select-frame-set-input-focus cur-frame))))))
16956 (t ; Naked prompt only
16957 (unwind-protect
16958 (setq ans (read-string prompt default-input
16959 'org-read-date-history timestr))
16960 (when org-read-date-overlay
16961 (delete-overlay org-read-date-overlay)
16962 (setq org-read-date-overlay nil))))))
16964 (setq final (org-read-date-analyze ans org-def org-defdecode))
16966 (when org-read-date-analyze-forced-year
16967 (message "Year was forced into %s"
16968 (if org-read-date-force-compatible-dates
16969 "compatible range (1970-2037)"
16970 "range representable on this machine"))
16971 (ding))
16973 ;; One round trip to get rid of 34th of August and stuff like that....
16974 (setq final (decode-time (apply 'encode-time final)))
16976 (setq org-read-date-final-answer ans)
16978 (if to-time
16979 (apply 'encode-time final)
16980 (if (and (boundp 'org-time-was-given) org-time-was-given)
16981 (format "%04d-%02d-%02d %02d:%02d"
16982 (nth 5 final) (nth 4 final) (nth 3 final)
16983 (nth 2 final) (nth 1 final))
16984 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
16986 (defun org-read-date-display ()
16987 "Display the current date prompt interpretation in the minibuffer."
16988 (when org-read-date-display-live
16989 (when org-read-date-overlay
16990 (delete-overlay org-read-date-overlay))
16991 (when (minibufferp (current-buffer))
16992 (save-excursion
16993 (end-of-line 1)
16994 (while (not (equal (buffer-substring
16995 (max (point-min) (- (point) 4)) (point))
16996 " "))
16997 (insert " ")))
16998 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
16999 " " (or org-ans1 org-ans2)))
17000 (org-end-time-was-given nil)
17001 (f (org-read-date-analyze ans org-def org-defdecode))
17002 (fmts (if org-dcst
17003 org-time-stamp-custom-formats
17004 org-time-stamp-formats))
17005 (fmt (if (or org-with-time
17006 (and (boundp 'org-time-was-given) org-time-was-given))
17007 (cdr fmts)
17008 (car fmts)))
17009 (txt (format-time-string fmt (apply 'encode-time f)))
17010 (txt (if org-read-date-inactive (concat "[" (substring txt 1 -1) "]") txt))
17011 (txt (concat "=> " txt)))
17012 (when (and org-end-time-was-given
17013 (string-match org-plain-time-of-day-regexp txt))
17014 (setq txt (concat (substring txt 0 (match-end 0)) "-"
17015 org-end-time-was-given
17016 (substring txt (match-end 0)))))
17017 (when org-read-date-analyze-futurep
17018 (setq txt (concat txt " (=>F)")))
17019 (setq org-read-date-overlay
17020 (make-overlay (1- (point-at-eol)) (point-at-eol)))
17021 (org-overlay-display org-read-date-overlay txt 'secondary-selection)))))
17023 (defun org-read-date-analyze (ans def defdecode)
17024 "Analyze the combined answer of the date prompt."
17025 ;; FIXME: cleanup and comment
17026 ;; Pass `current-time' result to `decode-time' (instead of calling
17027 ;; without arguments) so that only `current-time' has to be
17028 ;; overriden in tests.
17029 (let ((org-def def)
17030 (org-defdecode defdecode)
17031 (nowdecode (decode-time (current-time)))
17032 delta deltan deltaw deltadef year month day
17033 hour minute second wday pm h2 m2 tl wday1
17034 iso-year iso-weekday iso-week iso-date futurep kill-year)
17035 (setq org-read-date-analyze-futurep nil
17036 org-read-date-analyze-forced-year nil)
17037 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
17038 (setq ans "+0"))
17040 (when (setq delta (org-read-date-get-relative ans (current-time) org-def))
17041 (setq ans (replace-match "" t t ans)
17042 deltan (car delta)
17043 deltaw (nth 1 delta)
17044 deltadef (nth 2 delta)))
17046 ;; Check if there is an iso week date in there. If yes, store the
17047 ;; info and postpone interpreting it until the rest of the parsing
17048 ;; is done.
17049 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
17050 (setq iso-year (when (match-end 1)
17051 (org-small-year-to-year
17052 (string-to-number (match-string 1 ans))))
17053 iso-weekday (when (match-end 3)
17054 (string-to-number (match-string 3 ans)))
17055 iso-week (string-to-number (match-string 2 ans)))
17056 (setq ans (replace-match "" t t ans)))
17058 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
17059 (when (string-match
17060 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
17061 (setq year (if (match-end 2)
17062 (string-to-number (match-string 2 ans))
17063 (progn (setq kill-year t)
17064 (string-to-number (format-time-string "%Y"))))
17065 month (string-to-number (match-string 3 ans))
17066 day (string-to-number (match-string 4 ans)))
17067 (setq year (org-small-year-to-year year))
17068 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17069 t nil ans)))
17071 ;; Help matching dotted european dates
17072 (when (string-match
17073 "^ *\\(3[01]\\|0?[1-9]\\|[12][0-9]\\)\\. ?\\(0?[1-9]\\|1[012]\\)\\.\\( ?[1-9][0-9]\\{3\\}\\)?" ans)
17074 (setq year (if (match-end 3) (string-to-number (match-string 3 ans))
17075 (setq kill-year t)
17076 (string-to-number (format-time-string "%Y")))
17077 day (string-to-number (match-string 1 ans))
17078 month (string-to-number (match-string 2 ans))
17079 ans (replace-match (format "%04d-%02d-%02d" year month day)
17080 t nil ans)))
17082 ;; Help matching american dates, like 5/30 or 5/30/7
17083 (when (string-match
17084 "^ *\\(0?[1-9]\\|1[012]\\)/\\(0?[1-9]\\|[12][0-9]\\|3[01]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
17085 (setq year (if (match-end 4)
17086 (string-to-number (match-string 4 ans))
17087 (progn (setq kill-year t)
17088 (string-to-number (format-time-string "%Y"))))
17089 month (string-to-number (match-string 1 ans))
17090 day (string-to-number (match-string 2 ans)))
17091 (setq year (org-small-year-to-year year))
17092 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
17093 t nil ans)))
17094 ;; Help matching am/pm times, because `parse-time-string' does not do that.
17095 ;; If there is a time with am/pm, and *no* time without it, we convert
17096 ;; so that matching will be successful.
17097 (cl-loop for i from 1 to 2 do ; twice, for end time as well
17098 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
17099 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
17100 (setq hour (string-to-number (match-string 1 ans))
17101 minute (if (match-end 3)
17102 (string-to-number (match-string 3 ans))
17104 pm (equal ?p
17105 (string-to-char (downcase (match-string 4 ans)))))
17106 (if (and (= hour 12) (not pm))
17107 (setq hour 0)
17108 (when (and pm (< hour 12)) (setq hour (+ 12 hour))))
17109 (setq ans (replace-match (format "%02d:%02d" hour minute)
17110 t t ans))))
17112 ;; Check if a time range is given as a duration
17113 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
17114 (setq hour (string-to-number (match-string 1 ans))
17115 h2 (+ hour (string-to-number (match-string 3 ans)))
17116 minute (string-to-number (match-string 2 ans))
17117 m2 (+ minute (if (match-end 5) (string-to-number
17118 (match-string 5 ans))0)))
17119 (when (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
17120 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
17121 t t ans)))
17123 ;; Check if there is a time range
17124 (when (boundp 'org-end-time-was-given)
17125 (setq org-time-was-given nil)
17126 (when (and (string-match org-plain-time-of-day-regexp ans)
17127 (match-end 8))
17128 (setq org-end-time-was-given (match-string 8 ans))
17129 (setq ans (concat (substring ans 0 (match-beginning 7))
17130 (substring ans (match-end 7))))))
17132 (setq tl (parse-time-string ans)
17133 day (or (nth 3 tl) (nth 3 org-defdecode))
17134 month
17135 (cond ((nth 4 tl))
17136 ((not org-read-date-prefer-future) (nth 4 org-defdecode))
17137 ;; Day was specified. Make sure DAY+MONTH
17138 ;; combination happens in the future.
17139 ((nth 3 tl)
17140 (setq futurep t)
17141 (if (< day (nth 3 nowdecode)) (1+ (nth 4 nowdecode))
17142 (nth 4 nowdecode)))
17143 (t (nth 4 org-defdecode)))
17144 year
17145 (cond ((and (not kill-year) (nth 5 tl)))
17146 ((not org-read-date-prefer-future) (nth 5 org-defdecode))
17147 ;; Month was guessed in the future and is at least
17148 ;; equal to NOWDECODE's. Fix year accordingly.
17149 (futurep
17150 (if (or (> month (nth 4 nowdecode))
17151 (>= day (nth 3 nowdecode)))
17152 (nth 5 nowdecode)
17153 (1+ (nth 5 nowdecode))))
17154 ;; Month was specified. Make sure MONTH+YEAR
17155 ;; combination happens in the future.
17156 ((nth 4 tl)
17157 (setq futurep t)
17158 (cond ((> month (nth 4 nowdecode)) (nth 5 nowdecode))
17159 ((< month (nth 4 nowdecode)) (1+ (nth 5 nowdecode)))
17160 ((< day (nth 3 nowdecode)) (1+ (nth 5 nowdecode)))
17161 (t (nth 5 nowdecode))))
17162 (t (nth 5 org-defdecode)))
17163 hour (or (nth 2 tl) (nth 2 org-defdecode))
17164 minute (or (nth 1 tl) (nth 1 org-defdecode))
17165 second (or (nth 0 tl) 0)
17166 wday (nth 6 tl))
17168 (when (and (eq org-read-date-prefer-future 'time)
17169 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
17170 (equal day (nth 3 nowdecode))
17171 (equal month (nth 4 nowdecode))
17172 (equal year (nth 5 nowdecode))
17173 (nth 2 tl)
17174 (or (< (nth 2 tl) (nth 2 nowdecode))
17175 (and (= (nth 2 tl) (nth 2 nowdecode))
17176 (nth 1 tl)
17177 (< (nth 1 tl) (nth 1 nowdecode)))))
17178 (setq day (1+ day)
17179 futurep t))
17181 ;; Special date definitions below
17182 (cond
17183 (iso-week
17184 ;; There was an iso week
17185 (require 'cal-iso)
17186 (setq futurep nil)
17187 (setq year (or iso-year year)
17188 day (or iso-weekday wday 1)
17189 wday nil ; to make sure that the trigger below does not match
17190 iso-date (calendar-gregorian-from-absolute
17191 (calendar-iso-to-absolute
17192 (list iso-week day year))))
17193 ; FIXME: Should we also push ISO weeks into the future?
17194 ; (when (and org-read-date-prefer-future
17195 ; (not iso-year)
17196 ; (< (calendar-absolute-from-gregorian iso-date)
17197 ; (time-to-days (current-time))))
17198 ; (setq year (1+ year)
17199 ; iso-date (calendar-gregorian-from-absolute
17200 ; (calendar-iso-to-absolute
17201 ; (list iso-week day year)))))
17202 (setq month (car iso-date)
17203 year (nth 2 iso-date)
17204 day (nth 1 iso-date)))
17205 (deltan
17206 (setq futurep nil)
17207 (unless deltadef
17208 ;; Pass `current-time' result to `decode-time' (instead of
17209 ;; calling without arguments) so that only `current-time' has
17210 ;; to be overriden in tests.
17211 (let ((now (decode-time (current-time))))
17212 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
17213 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
17214 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
17215 ((equal deltaw "m") (setq month (+ month deltan)))
17216 ((equal deltaw "y") (setq year (+ year deltan)))))
17217 ((and wday (not (nth 3 tl)))
17218 ;; Weekday was given, but no day, so pick that day in the week
17219 ;; on or after the derived date.
17220 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
17221 (unless (equal wday wday1)
17222 (setq day (+ day (% (- wday wday1 -7) 7))))))
17223 (when (and (boundp 'org-time-was-given)
17224 (nth 2 tl))
17225 (setq org-time-was-given t))
17226 (when (< year 100) (setq year (+ 2000 year)))
17227 ;; Check of the date is representable
17228 (if org-read-date-force-compatible-dates
17229 (progn
17230 (when (< year 1970)
17231 (setq year 1970 org-read-date-analyze-forced-year t))
17232 (when (> year 2037)
17233 (setq year 2037 org-read-date-analyze-forced-year t)))
17234 (condition-case nil
17235 (ignore (encode-time second minute hour day month year))
17236 (error
17237 (setq year (nth 5 org-defdecode))
17238 (setq org-read-date-analyze-forced-year t))))
17239 (setq org-read-date-analyze-futurep futurep)
17240 (list second minute hour day month year)))
17242 (defvar parse-time-weekdays)
17243 (defun org-read-date-get-relative (s today default)
17244 "Check string S for special relative date string.
17245 TODAY and DEFAULT are internal times, for today and for a default.
17246 Return shift list (N what def-flag)
17247 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
17248 N is the number of WHATs to shift.
17249 DEF-FLAG is t when a double ++ or -- indicates shift relative to
17250 the DEFAULT date rather than TODAY."
17251 (require 'parse-time)
17252 (when (and
17253 (string-match
17254 (concat
17255 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
17256 "\\([0-9]+\\)?"
17257 "\\([hdwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
17258 "\\([ \t]\\|$\\)") s)
17259 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
17260 (let* ((dir (if (> (match-end 1) (match-beginning 1))
17261 (string-to-char (substring (match-string 1 s) -1))
17262 ?+))
17263 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
17264 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
17265 (what (if (match-end 3) (match-string 3 s) "d"))
17266 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
17267 (date (if rel default today))
17268 (wday (nth 6 (decode-time date)))
17269 delta)
17270 (if wday1
17271 (progn
17272 (setq delta (mod (+ 7 (- wday1 wday)) 7))
17273 (when (= delta 0) (setq delta 7))
17274 (when (= dir ?-)
17275 (setq delta (- delta 7))
17276 (when (= delta 0) (setq delta -7)))
17277 (when (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
17278 (list delta "d" rel))
17279 (list (* n (if (= dir ?-) -1 1)) what rel)))))
17281 (defun org-order-calendar-date-args (arg1 arg2 arg3)
17282 "Turn a user-specified date into the internal representation.
17283 The internal representation needed by the calendar is (month day year).
17284 This is a wrapper to handle the brain-dead convention in calendar that
17285 user function argument order change dependent on argument order."
17286 (if (boundp 'calendar-date-style)
17287 (cond
17288 ((eq calendar-date-style 'american)
17289 (list arg1 arg2 arg3))
17290 ((eq calendar-date-style 'european)
17291 (list arg2 arg1 arg3))
17292 ((eq calendar-date-style 'iso)
17293 (list arg2 arg3 arg1)))
17294 (org-no-warnings ;; european-calendar-style is obsolete as of version 23.1
17295 (if (org-bound-and-true-p european-calendar-style)
17296 (list arg2 arg1 arg3)
17297 (list arg1 arg2 arg3)))))
17299 (defun org-eval-in-calendar (form &optional keepdate)
17300 "Eval FORM in the calendar window and return to current window.
17301 Unless KEEPDATE is non-nil, update `org-ans2' to the cursor date."
17302 (let ((sf (selected-frame))
17303 (sw (selected-window)))
17304 (select-window (get-buffer-window "*Calendar*" t))
17305 (eval form)
17306 (when (and (not keepdate) (calendar-cursor-to-date))
17307 (let* ((date (calendar-cursor-to-date))
17308 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17309 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
17310 (move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
17311 (select-window sw)
17312 (org-select-frame-set-input-focus sf)))
17314 (defun org-calendar-select ()
17315 "Return to `org-read-date' with the date currently selected.
17316 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17317 (interactive)
17318 (when (calendar-cursor-to-date)
17319 (let* ((date (calendar-cursor-to-date))
17320 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17321 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17322 (when (active-minibuffer-window) (exit-minibuffer))))
17324 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
17325 "Insert a date stamp for the date given by the internal TIME.
17326 See `format-time-string' for the format of TIME.
17327 WITH-HM means use the stamp format that includes the time of the day.
17328 INACTIVE means use square brackets instead of angular ones, so that the
17329 stamp will not contribute to the agenda.
17330 PRE and POST are optional strings to be inserted before and after the
17331 stamp.
17332 The command returns the inserted time stamp."
17333 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
17334 stamp)
17335 (when inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
17336 (insert-before-markers (or pre ""))
17337 (when (listp extra)
17338 (setq extra (car extra))
17339 (if (and (stringp extra)
17340 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
17341 (setq extra (format "-%02d:%02d"
17342 (string-to-number (match-string 1 extra))
17343 (string-to-number (match-string 2 extra))))
17344 (setq extra nil)))
17345 (when extra
17346 (setq fmt (concat (substring fmt 0 -1) extra (substring fmt -1))))
17347 (insert-before-markers (setq stamp (format-time-string fmt time)))
17348 (insert-before-markers (or post ""))
17349 (setq org-last-inserted-timestamp stamp)))
17351 (defun org-toggle-time-stamp-overlays ()
17352 "Toggle the use of custom time stamp formats."
17353 (interactive)
17354 (setq org-display-custom-times (not org-display-custom-times))
17355 (unless org-display-custom-times
17356 (let ((p (point-min)) (bmp (buffer-modified-p)))
17357 (while (setq p (next-single-property-change p 'display))
17358 (when (and (get-text-property p 'display)
17359 (eq (get-text-property p 'face) 'org-date))
17360 (remove-text-properties
17361 p (setq p (next-single-property-change p 'display))
17362 '(display t))))
17363 (set-buffer-modified-p bmp)))
17364 (when (featurep 'xemacs)
17365 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
17366 (org-restart-font-lock)
17367 (setq org-table-may-need-update t)
17368 (if org-display-custom-times
17369 (message "Time stamps are overlaid with custom format")
17370 (message "Time stamp overlays removed")))
17372 (defun org-display-custom-time (beg end)
17373 "Overlay modified time stamp format over timestamp between BEG and END."
17374 (let* ((ts (buffer-substring beg end))
17375 t1 w1 with-hm tf time str w2 (off 0))
17376 (save-match-data
17377 (setq t1 (org-parse-time-string ts t))
17378 (when (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)?\\'" ts)
17379 (setq off (- (match-end 0) (match-beginning 0)))))
17380 (setq end (- end off))
17381 (setq w1 (- end beg)
17382 with-hm (and (nth 1 t1) (nth 2 t1))
17383 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
17384 time (org-fix-decoded-time t1)
17385 str (org-add-props
17386 (format-time-string
17387 (substring tf 1 -1) (apply 'encode-time time))
17388 nil 'mouse-face 'highlight)
17389 w2 (length str))
17390 (unless (= w2 w1)
17391 (add-text-properties (1+ beg) (+ 2 beg)
17392 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
17393 (if (featurep 'xemacs)
17394 (progn
17395 (put-text-property beg end 'invisible t)
17396 (put-text-property beg end 'end-glyph (make-glyph str)))
17397 (put-text-property beg end 'display str))))
17399 (defun org-fix-decoded-time (time)
17400 "Set 0 instead of nil for the first 6 elements of time.
17401 Don't touch the rest."
17402 (let ((n 0))
17403 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
17405 (define-obsolete-function-alias 'org-days-to-time 'org-time-stamp-to-now "24.4")
17407 (defun org-time-stamp-to-now (timestamp-string &optional seconds)
17408 "Difference between TIMESTAMP-STRING and now in days.
17409 If SECONDS is non-nil, return the difference in seconds."
17410 (let ((fdiff (if seconds 'org-float-time 'time-to-days)))
17411 (- (funcall fdiff (org-time-string-to-time timestamp-string))
17412 (funcall fdiff (current-time)))))
17414 (defun org-deadline-close (timestamp-string &optional ndays)
17415 "Is the time in TIMESTAMP-STRING close to the current date?"
17416 (setq ndays (or ndays (org-get-wdays timestamp-string)))
17417 (and (< (org-time-stamp-to-now timestamp-string) ndays)
17418 (not (org-entry-is-done-p))))
17420 (defun org-get-wdays (ts &optional delay zero-delay)
17421 "Get the deadline lead time appropriate for timestring TS.
17422 When DELAY is non-nil, get the delay time for scheduled items
17423 instead of the deadline lead time. When ZERO-DELAY is non-nil
17424 and `org-scheduled-delay-days' is 0, enforce 0 as the delay,
17425 don't try to find the delay cookie in the scheduled timestamp."
17426 (let ((tv (if delay org-scheduled-delay-days
17427 org-deadline-warning-days)))
17428 (cond
17429 ((or (and delay (< tv 0))
17430 (and delay zero-delay (<= tv 0))
17431 (and (not delay) (<= tv 0)))
17432 ;; Enforce this value no matter what
17433 (- tv))
17434 ((string-match "-\\([0-9]+\\)\\([hdwmy]\\)\\(\\'\\|>\\| \\)" ts)
17435 ;; lead time is specified.
17436 (floor (* (string-to-number (match-string 1 ts))
17437 (cdr (assoc (match-string 2 ts)
17438 '(("d" . 1) ("w" . 7)
17439 ("m" . 30.4) ("y" . 365.25)
17440 ("h" . 0.041667)))))))
17441 ;; go for the default.
17442 (t tv))))
17444 (defun org-calendar-select-mouse (ev)
17445 "Return to `org-read-date' with the date currently selected.
17446 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
17447 (interactive "e")
17448 (mouse-set-point ev)
17449 (when (calendar-cursor-to-date)
17450 (let* ((date (calendar-cursor-to-date))
17451 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17452 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
17453 (when (active-minibuffer-window) (exit-minibuffer))))
17455 (defun org-check-deadlines (ndays)
17456 "Check if there are any deadlines due or past due.
17457 A deadline is considered due if it happens within `org-deadline-warning-days'
17458 days from today's date. If the deadline appears in an entry marked DONE,
17459 it is not shown. The prefix arg NDAYS can be used to test that many
17460 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
17461 (interactive "P")
17462 (let* ((org-warn-days
17463 (cond
17464 ((equal ndays '(4)) 100000)
17465 (ndays (prefix-numeric-value ndays))
17466 (t (abs org-deadline-warning-days))))
17467 (case-fold-search nil)
17468 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
17469 (callback
17470 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
17471 (message "%d deadlines past-due or due within %d days"
17472 (org-occur regexp nil callback)
17473 org-warn-days)))
17475 (defsubst org-re-timestamp (type)
17476 "Return a regexp for timestamp TYPE.
17477 Allowed values for TYPE are:
17479 all: all timestamps
17480 active: only active timestamps (<...>)
17481 inactive: only inactive timestamps ([...])
17482 scheduled: only scheduled timestamps
17483 deadline: only deadline timestamps
17484 closed: only closed time-stamps
17486 When TYPE is nil, fall back on returning a regexp that matches
17487 both scheduled and deadline timestamps."
17488 (cl-case type
17489 (all org-ts-regexp-both)
17490 (active org-ts-regexp)
17491 (inactive org-ts-regexp-inactive)
17492 (scheduled org-scheduled-time-regexp)
17493 (deadline org-deadline-time-regexp)
17494 (closed org-closed-time-regexp)
17495 (otherwise
17496 (concat "\\<"
17497 (regexp-opt (list org-deadline-string org-scheduled-string))
17498 " *<\\([^>]+\\)>"))))
17500 (defun org-check-before-date (d)
17501 "Check if there are deadlines or scheduled entries before date D."
17502 (interactive (list (org-read-date)))
17503 (let* ((case-fold-search nil)
17504 (regexp (org-re-timestamp org-ts-type))
17505 (ts-type org-ts-type)
17506 (callback
17507 (lambda ()
17508 (let ((match (match-string 1)))
17509 (and (if (memq ts-type '(active inactive all))
17510 (eq (org-element-type (org-element-context)) 'timestamp)
17511 (org-at-planning-p))
17512 (time-less-p
17513 (org-time-string-to-time match)
17514 (org-time-string-to-time d)))))))
17515 (message "%d entries before %s"
17516 (org-occur regexp nil callback)
17517 d)))
17519 (defun org-check-after-date (d)
17520 "Check if there are deadlines or scheduled entries after date D."
17521 (interactive (list (org-read-date)))
17522 (let* ((case-fold-search nil)
17523 (regexp (org-re-timestamp org-ts-type))
17524 (ts-type org-ts-type)
17525 (callback
17526 (lambda ()
17527 (let ((match (match-string 1)))
17528 (and (if (memq ts-type '(active inactive all))
17529 (eq (org-element-type (org-element-context)) 'timestamp)
17530 (org-at-planning-p))
17531 (not (time-less-p
17532 (org-time-string-to-time match)
17533 (org-time-string-to-time d))))))))
17534 (message "%d entries after %s"
17535 (org-occur regexp nil callback)
17536 d)))
17538 (defun org-check-dates-range (start-date end-date)
17539 "Check for deadlines/scheduled entries between START-DATE and END-DATE."
17540 (interactive (list (org-read-date nil nil nil "Range starts")
17541 (org-read-date nil nil nil "Range end")))
17542 (let ((case-fold-search nil)
17543 (regexp (org-re-timestamp org-ts-type))
17544 (callback
17545 (let ((type org-ts-type))
17546 (lambda ()
17547 (let ((match (match-string 1)))
17548 (and
17549 (if (memq type '(active inactive all))
17550 (eq (org-element-type (org-element-context)) 'timestamp)
17551 (org-at-planning-p))
17552 (not (time-less-p
17553 (org-time-string-to-time match)
17554 (org-time-string-to-time start-date)))
17555 (time-less-p
17556 (org-time-string-to-time match)
17557 (org-time-string-to-time end-date))))))))
17558 (message "%d entries between %s and %s"
17559 (org-occur regexp nil callback) start-date end-date)))
17561 (defun org-evaluate-time-range (&optional to-buffer)
17562 "Evaluate a time range by computing the difference between start and end.
17563 Normally the result is just printed in the echo area, but with prefix arg
17564 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
17565 If the time range is actually in a table, the result is inserted into the
17566 next column.
17567 For time difference computation, a year is assumed to be exactly 365
17568 days in order to avoid rounding problems."
17569 (interactive "P")
17571 (org-clock-update-time-maybe)
17572 (save-excursion
17573 (unless (org-at-date-range-p t)
17574 (goto-char (point-at-bol))
17575 (re-search-forward org-tr-regexp-both (point-at-eol) t))
17576 (unless (org-at-date-range-p t)
17577 (user-error "Not at a time-stamp range, and none found in current line")))
17578 (let* ((ts1 (match-string 1))
17579 (ts2 (match-string 2))
17580 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
17581 (match-end (match-end 0))
17582 (time1 (org-time-string-to-time ts1))
17583 (time2 (org-time-string-to-time ts2))
17584 (t1 (org-float-time time1))
17585 (t2 (org-float-time time2))
17586 (diff (abs (- t2 t1)))
17587 (negative (< (- t2 t1) 0))
17588 ;; (ys (floor (* 365 24 60 60)))
17589 (ds (* 24 60 60))
17590 (hs (* 60 60))
17591 (fy "%dy %dd %02d:%02d")
17592 (fy1 "%dy %dd")
17593 (fd "%dd %02d:%02d")
17594 (fd1 "%dd")
17595 (fh "%02d:%02d")
17596 y d h m align)
17597 (if havetime
17598 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17600 d (floor (/ diff ds)) diff (mod diff ds)
17601 h (floor (/ diff hs)) diff (mod diff hs)
17602 m (floor (/ diff 60)))
17603 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
17605 d (floor (+ (/ diff ds) 0.5))
17606 h 0 m 0))
17607 (if (not to-buffer)
17608 (message "%s" (org-make-tdiff-string y d h m))
17609 (if (org-at-table-p)
17610 (progn
17611 (goto-char match-end)
17612 (setq align t)
17613 (and (looking-at " *|") (goto-char (match-end 0))))
17614 (goto-char match-end))
17615 (when (looking-at
17616 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
17617 (replace-match ""))
17618 (when negative (insert " -"))
17619 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
17620 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
17621 (insert " " (format fh h m))))
17622 (when align (org-table-align))
17623 (message "Time difference inserted")))))
17625 (defun org-make-tdiff-string (y d h m)
17626 (let ((fmt "")
17627 (l nil))
17628 (when (> y 0)
17629 (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " "))
17630 (push y l))
17631 (when (> d 0)
17632 (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " "))
17633 (push d l))
17634 (when (> h 0)
17635 (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " "))
17636 (push h l))
17637 (when (> m 0)
17638 (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " "))
17639 (push m l))
17640 (apply 'format fmt (nreverse l))))
17642 (defun org-time-string-to-time (s &optional buffer pos)
17643 "Convert a timestamp string into internal time."
17644 (condition-case errdata
17645 (apply 'encode-time (org-parse-time-string s))
17646 (error (error "Bad timestamp `%s'%s\nError was: %s"
17647 s (if (not (and buffer pos))
17649 (format-message " at %d in buffer `%s'" pos buffer))
17650 (cdr errdata)))))
17652 (defun org-time-string-to-seconds (s)
17653 "Convert a timestamp string to a number of seconds."
17654 (org-float-time (org-time-string-to-time s)))
17656 (org-define-error 'org-diary-sexp-no-match "Unable to match diary sexp")
17658 (defun org-time-string-to-absolute (s &optional daynr prefer show-all buffer pos)
17659 "Convert time stamp S to an absolute day number.
17661 If DAYNR in non-nil, and there is a specifier for a cyclic time
17662 stamp, get the closest date to DAYNR. If PREFER is
17663 `past' (respectively `future') return a date past (respectively
17664 after) or equal to DAYNR.
17666 POS is the location of time stamp S, as a buffer position in
17667 BUFFER.
17669 Diary sexp timestamps are matched against DAYNR, when non-nil.
17670 If matching fails or DAYNR is nil, `org-diary-sexp-no-match' is
17671 signalled."
17672 (cond
17673 ((string-match "\\`%%\\((.*)\\)" s)
17674 ;; Sexp timestamp: try to match DAYNR, if available, since we're
17675 ;; only able to match individual dates. If it fails, raise an
17676 ;; error.
17677 (if (and daynr
17678 (org-diary-sexp-entry
17679 (match-string 1 s) "" (calendar-gregorian-from-absolute daynr)))
17680 daynr
17681 (signal 'org-diary-sexp-no-match (list s))))
17682 ((and daynr show-all) (org-closest-date s daynr prefer))
17683 (t (time-to-days
17684 (condition-case errdata
17685 (apply #'encode-time (org-parse-time-string s))
17686 (error (error "Bad timestamp `%s'%s\nError was: %s"
17688 (if (not (and buffer pos)) ""
17689 (format-message " at %d in buffer `%s'" pos buffer))
17690 (cdr errdata))))))))
17692 (defun org-days-to-iso-week (days)
17693 "Return the iso week number."
17694 (require 'cal-iso)
17695 (car (calendar-iso-from-absolute days)))
17697 (defun org-small-year-to-year (year)
17698 "Convert 2-digit years into 4-digit years.
17699 YEAR is expanded into one of the 30 next years, if possible, or
17700 into a past one. Any year larger than 99 is returned unchanged."
17701 (if (>= year 100) year
17702 (let* ((current (string-to-number (format-time-string "%Y" (current-time))))
17703 (century (/ current 100))
17704 (offset (- year (% current 100))))
17705 (cond ((> offset 30) (+ (* (1- century) 100) year))
17706 ((> offset -70) (+ (* century 100) year))
17707 (t (+ (* (1+ century) 100) year))))))
17709 (defun org-time-from-absolute (d)
17710 "Return the time corresponding to date D.
17711 D may be an absolute day number, or a calendar-type list (month day year)."
17712 (when (numberp d) (setq d (calendar-gregorian-from-absolute d)))
17713 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
17715 (defvar org-agenda-current-date)
17716 (defun org-calendar-holiday ()
17717 "List of holidays, for Diary display in Org mode."
17718 (require 'holidays)
17719 (let ((hl (calendar-check-holidays org-agenda-current-date)))
17720 (and hl (mapconcat #'identity hl "; "))))
17722 (defun org-diary-sexp-entry (sexp entry d)
17723 "Process a SEXP diary ENTRY for date D."
17724 (require 'diary-lib)
17725 ;; `org-anniversary' and alike expect ENTRY and DATE to be bound
17726 ;; dynamically.
17727 (let* ((sexp `(let ((entry ,entry)
17728 (date ',d))
17729 ,(car (read-from-string sexp))))
17730 (result (if calendar-debug-sexp (eval sexp)
17731 (condition-case nil
17732 (eval sexp)
17733 (error
17734 (beep)
17735 (message "Bad sexp at line %d in %s: %s"
17736 (org-current-line)
17737 (buffer-file-name) sexp)
17738 (sleep-for 2))))))
17739 (cond ((stringp result) (split-string result "; "))
17740 ((and (consp result)
17741 (not (consp (cdr result)))
17742 (stringp (cdr result))) (cdr result))
17743 ((and (consp result)
17744 (stringp (car result))) result)
17745 (result entry))))
17747 (defun org-diary-to-ical-string (frombuf)
17748 "Get iCalendar entries from diary entries in buffer FROMBUF.
17749 This uses the icalendar.el library."
17750 (let* ((tmpdir (if (featurep 'xemacs)
17751 (temp-directory)
17752 temporary-file-directory))
17753 (tmpfile (make-temp-name
17754 (expand-file-name "orgics" tmpdir)))
17755 buf rtn b e)
17756 (with-current-buffer frombuf
17757 (icalendar-export-region (point-min) (point-max) tmpfile)
17758 (setq buf (find-buffer-visiting tmpfile))
17759 (set-buffer buf)
17760 (goto-char (point-min))
17761 (when (re-search-forward "^BEGIN:VEVENT" nil t)
17762 (setq b (match-beginning 0)))
17763 (goto-char (point-max))
17764 (when (re-search-backward "^END:VEVENT" nil t)
17765 (setq e (match-end 0)))
17766 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
17767 (kill-buffer buf)
17768 (delete-file tmpfile)
17769 rtn))
17771 (defun org-closest-date (start current prefer)
17772 "Return closest date to CURRENT starting from START.
17774 CURRENT and START are both time stamps.
17776 When PREFER is `past', return a date that is either CURRENT or
17777 past. When PREFER is `future', return a date that is either
17778 CURRENT or future.
17780 Only time stamps with a repeater are modified. Any other time
17781 stamp stay unchanged. In any case, return value is an absolute
17782 day number."
17783 (if (not (string-match "\\+\\([0-9]+\\)\\([hdwmy]\\)" start))
17784 ;; No repeater. Do not shift time stamp.
17785 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17786 (let ((value (string-to-number (match-string 1 start)))
17787 (type (match-string 2 start)))
17788 (if (= 0 value)
17789 ;; Repeater with a 0-value is considered as void.
17790 (time-to-days (apply #'encode-time (org-parse-time-string start)))
17791 (let* ((base (org-date-to-gregorian start))
17792 (target (org-date-to-gregorian current))
17793 (sday (calendar-absolute-from-gregorian base))
17794 (cday (calendar-absolute-from-gregorian target))
17795 n1 n2)
17796 ;; If START is already past CURRENT, just return START.
17797 (if (<= cday sday) sday
17798 ;; Compute closest date before (N1) and closest date past
17799 ;; (N2) CURRENT.
17800 (pcase type
17801 ("h"
17802 (let ((missing-hours
17803 (mod (+ (- (* 24 (- cday sday))
17804 (nth 2 (org-parse-time-string start)))
17805 org-extend-today-until)
17806 value)))
17807 (setf n1 (if (= missing-hours 0) cday
17808 (- cday (1+ (/ missing-hours 24)))))
17809 (setf n2 (+ cday (/ (- value missing-hours) 24)))))
17810 ((or "d" "w")
17811 (let ((value (if (equal type "w") (* 7 value) value)))
17812 (setf n1 (+ sday (* value (/ (- cday sday) value))))
17813 (setf n2 (+ n1 value))))
17814 ("m"
17815 (let* ((add-months
17816 (lambda (d n)
17817 ;; Add N months to gregorian date D, i.e.,
17818 ;; a list (MONTH DAY YEAR). Return a valid
17819 ;; gregorian date.
17820 (let ((m (+ (nth 0 d) n)))
17821 (list (mod m 12)
17822 (nth 1 d)
17823 (+ (/ m 12) (nth 2 d))))))
17824 (months ; Complete months to TARGET.
17825 (* (/ (+ (* 12 (- (nth 2 target) (nth 2 base)))
17826 (- (nth 0 target) (nth 0 base))
17827 ;; If START's day is greater than
17828 ;; TARGET's, remove incomplete month.
17829 (if (> (nth 1 target) (nth 1 base)) 0 -1))
17830 value)
17831 value))
17832 (before (funcall add-months base months)))
17833 (setf n1 (calendar-absolute-from-gregorian before))
17834 (setf n2
17835 (calendar-absolute-from-gregorian
17836 (funcall add-months before value)))))
17838 (let* ((d (nth 1 base))
17839 (m (nth 0 base))
17840 (y (nth 2 base))
17841 (years ; Complete years to TARGET.
17842 (* (/ (- (nth 2 target)
17844 ;; If START's month and day are
17845 ;; greater than TARGET's, remove
17846 ;; incomplete year.
17847 (if (or (> (nth 0 target) m)
17848 (and (= (nth 0 target) m)
17849 (> (nth 1 target) d)))
17852 value)
17853 value))
17854 (before (list m d (+ y years))))
17855 (setf n1 (calendar-absolute-from-gregorian before))
17856 (setf n2 (calendar-absolute-from-gregorian
17857 (list m d (+ (nth 2 before) value)))))))
17858 ;; Handle PREFER parameter, if any.
17859 (cond
17860 ((eq prefer 'past) (if (= cday n2) n2 n1))
17861 ((eq prefer 'future) (if (= cday n1) n1 n2))
17862 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))))))))
17864 (defun org-date-to-gregorian (d)
17865 "Turn any specification of date D into a Gregorian date for the calendar."
17866 (cond ((integerp d) (calendar-gregorian-from-absolute d))
17867 ((and (listp d) (= (length d) 3)) d)
17868 ((stringp d)
17869 (let ((d (org-parse-time-string d)))
17870 (list (nth 4 d) (nth 3 d) (nth 5 d))))
17871 ((listp d) (list (nth 4 d) (nth 3 d) (nth 5 d)))))
17873 (defun org-parse-time-string (s &optional nodefault)
17874 "Parse the standard Org-mode time string.
17875 This should be a lot faster than the normal `parse-time-string'.
17876 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
17877 hour and minute fields will be nil if not given."
17878 (cond ((string-match org-ts-regexp0 s)
17879 (list 0
17880 (when (or (match-beginning 8) (not nodefault))
17881 (string-to-number (or (match-string 8 s) "0")))
17882 (when (or (match-beginning 7) (not nodefault))
17883 (string-to-number (or (match-string 7 s) "0")))
17884 (string-to-number (match-string 4 s))
17885 (string-to-number (match-string 3 s))
17886 (string-to-number (match-string 2 s))
17887 nil nil nil))
17888 ((string-match "^<[^>]+>$" s)
17889 (decode-time (seconds-to-time (org-matcher-time s))))
17890 (t (error "Not a standard Org-mode time string: %s" s))))
17892 (defun org-timestamp-up (&optional arg)
17893 "Increase the date item at the cursor by one.
17894 If the cursor is on the year, change the year. If it is on the month,
17895 the day or the time, change that.
17896 With prefix ARG, change by that many units."
17897 (interactive "p")
17898 (org-timestamp-change (prefix-numeric-value arg) nil 'updown))
17900 (defun org-timestamp-down (&optional arg)
17901 "Decrease the date item at the cursor by one.
17902 If the cursor is on the year, change the year. If it is on the month,
17903 the day or the time, change that.
17904 With prefix ARG, change by that many units."
17905 (interactive "p")
17906 (org-timestamp-change (- (prefix-numeric-value arg)) nil 'updown))
17908 (defun org-timestamp-up-day (&optional arg)
17909 "Increase the date in the time stamp by one day.
17910 With prefix ARG, change that many days."
17911 (interactive "p")
17912 (if (and (not (org-at-timestamp-p t))
17913 (org-at-heading-p))
17914 (org-todo 'up)
17915 (org-timestamp-change (prefix-numeric-value arg) 'day 'updown)))
17917 (defun org-timestamp-down-day (&optional arg)
17918 "Decrease the date in the time stamp by one day.
17919 With prefix ARG, change that many days."
17920 (interactive "p")
17921 (if (and (not (org-at-timestamp-p t))
17922 (org-at-heading-p))
17923 (org-todo 'down)
17924 (org-timestamp-change (- (prefix-numeric-value arg)) 'day) 'updown))
17926 (defun org-at-timestamp-p (&optional inactive-ok)
17927 "Non-nil if point is inside a timestamp.
17929 When optional argument INACTIVE-OK is non-nil, also consider
17930 inactive timestamps.
17932 When this function returns a non-nil value, match data is set
17933 according to `org-ts-regexp3' or `org-ts-regexp2', depending on
17934 INACTIVE-OK."
17935 (interactive)
17936 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
17937 (pos (point))
17938 (ans (or (looking-at tsr)
17939 (save-excursion
17940 (skip-chars-backward "^[<\n\r\t")
17941 (when (> (point) (point-min)) (backward-char 1))
17942 (and (looking-at tsr)
17943 (> (- (match-end 0) pos) -1))))))
17944 (and ans
17945 (boundp 'org-ts-what)
17946 (setq org-ts-what
17947 (cond
17948 ((= pos (match-beginning 0)) 'bracket)
17949 ;; Point is considered to be "on the bracket" whether
17950 ;; it's really on it or right after it.
17951 ((= pos (1- (match-end 0))) 'bracket)
17952 ((= pos (match-end 0)) 'after)
17953 ((org-pos-in-match-range pos 2) 'year)
17954 ((org-pos-in-match-range pos 3) 'month)
17955 ((org-pos-in-match-range pos 7) 'hour)
17956 ((org-pos-in-match-range pos 8) 'minute)
17957 ((or (org-pos-in-match-range pos 4)
17958 (org-pos-in-match-range pos 5)) 'day)
17959 ((and (> pos (or (match-end 8) (match-end 5)))
17960 (< pos (match-end 0)))
17961 (- pos (or (match-end 8) (match-end 5))))
17962 (t 'day))))
17963 ans))
17965 (defun org-toggle-timestamp-type ()
17966 "Toggle the type (<active> or [inactive]) of a time stamp."
17967 (interactive)
17968 (when (org-at-timestamp-p t)
17969 (let ((beg (match-beginning 0)) (end (match-end 0))
17970 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
17971 (save-excursion
17972 (goto-char beg)
17973 (while (re-search-forward "[][<>]" end t)
17974 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
17975 t t)))
17976 (message "Timestamp is now %sactive"
17977 (if (equal (char-after beg) ?<) "" "in")))))
17979 (defun org-at-clock-log-p nil
17980 "Is the cursor on the clock log line?"
17981 (save-excursion
17982 (move-beginning-of-line 1)
17983 (looking-at org-clock-line-re)))
17985 (defvar org-clock-history) ; defined in org-clock.el
17986 (defvar org-clock-adjust-closest nil) ; defined in org-clock.el
17987 (defun org-timestamp-change (n &optional what updown suppress-tmp-delay)
17988 "Change the date in the time stamp at point.
17989 The date will be changed by N times WHAT. WHAT can be `day', `month',
17990 `year', `minute', `second'. If WHAT is not given, the cursor position
17991 in the timestamp determines what will be changed.
17992 When SUPPRESS-TMP-DELAY is non-nil, suppress delays like \"--2d\"."
17993 (let ((origin (point)) origin-cat
17994 with-hm inactive
17995 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
17996 org-ts-what
17997 extra rem
17998 ts time time0 fixnext clrgx)
17999 (unless (org-at-timestamp-p t)
18000 (user-error "Not at a timestamp"))
18001 (if (and (not what) (eq org-ts-what 'bracket))
18002 (org-toggle-timestamp-type)
18003 ;; Point isn't on brackets. Remember the part of the time-stamp
18004 ;; the point was in. Indeed, size of time-stamps may change,
18005 ;; but point must be kept in the same category nonetheless.
18006 (setq origin-cat org-ts-what)
18007 (when (and (not what) (not (eq org-ts-what 'day))
18008 org-display-custom-times
18009 (get-text-property (point) 'display)
18010 (not (get-text-property (1- (point)) 'display)))
18011 (setq org-ts-what 'day))
18012 (setq org-ts-what (or what org-ts-what)
18013 inactive (= (char-after (match-beginning 0)) ?\[)
18014 ts (match-string 0))
18015 (replace-match "")
18016 (when (string-match
18017 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?-?[-+][0-9]+[hdwmy]\\(/[0-9]+[hdwmy]\\)?\\)*\\)[]>]"
18019 (setq extra (match-string 1 ts))
18020 (when suppress-tmp-delay
18021 (setq extra (replace-regexp-in-string " --[0-9]+[hdwmy]" "" extra))))
18022 (when (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
18023 (setq with-hm t))
18024 (setq time0 (org-parse-time-string ts))
18025 (when (and updown
18026 (eq org-ts-what 'minute)
18027 (not current-prefix-arg))
18028 ;; This looks like s-up and s-down. Change by one rounding step.
18029 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
18030 (unless (= 0 (setq rem (% (nth 1 time0) dm)))
18031 (setcar (cdr time0) (+ (nth 1 time0)
18032 (if (> n 0) (- rem) (- dm rem))))))
18033 (setq time
18034 (apply #'encode-time
18035 (or (car time0) 0)
18036 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
18037 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
18038 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
18039 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
18040 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
18041 (nthcdr 6 time0)))
18042 (when (and (member org-ts-what '(hour minute))
18043 extra
18044 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
18045 (setq extra (org-modify-ts-extra
18046 extra
18047 (if (eq org-ts-what 'hour) 2 5)
18048 n dm)))
18049 (when (integerp org-ts-what)
18050 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
18051 (when (eq what 'calendar)
18052 (let ((cal-date (org-get-date-from-calendar)))
18053 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
18054 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
18055 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
18056 (setcar time0 (or (car time0) 0))
18057 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
18058 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
18059 (setq time (apply 'encode-time time0))))
18060 ;; Insert the new time-stamp, and ensure point stays in the same
18061 ;; category as before (i.e. not after the last position in that
18062 ;; category).
18063 (let ((pos (point)))
18064 ;; Stay before inserted string. `save-excursion' is of no use.
18065 (setq org-last-changed-timestamp
18066 (org-insert-time-stamp time with-hm inactive nil nil extra))
18067 (goto-char pos))
18068 (save-match-data
18069 (looking-at org-ts-regexp3)
18070 (goto-char (cond
18071 ;; `day' category ends before `hour' if any, or at
18072 ;; the end of the day name.
18073 ((eq origin-cat 'day)
18074 (min (or (match-beginning 7) (1- (match-end 5))) origin))
18075 ((eq origin-cat 'hour) (min (match-end 7) origin))
18076 ((eq origin-cat 'minute) (min (1- (match-end 8)) origin))
18077 ((integerp origin-cat) (min (1- (match-end 0)) origin))
18078 ;; `year' and `month' have both fixed size: point
18079 ;; couldn't have moved into another part.
18080 (t origin))))
18081 ;; Update clock if on a CLOCK line.
18082 (org-clock-update-time-maybe)
18083 ;; Maybe adjust the closest clock in `org-clock-history'
18084 (when org-clock-adjust-closest
18085 (if (not (and (org-at-clock-log-p)
18086 (< 1 (length (delq nil (mapcar 'marker-position
18087 org-clock-history))))))
18088 (message "No clock to adjust")
18089 (cond ((save-excursion ; fix previous clock?
18090 (re-search-backward org-ts-regexp0 nil t)
18091 (org-looking-back (concat org-clock-string " \\[")
18092 (line-beginning-position)))
18093 (setq fixnext 1 clrgx (concat org-ts-regexp0 "\\] =>.*$")))
18094 ((save-excursion ; fix next clock?
18095 (re-search-backward org-ts-regexp0 nil t)
18096 (looking-at (concat org-ts-regexp0 "\\] =>")))
18097 (setq fixnext -1 clrgx (concat org-clock-string " \\[" org-ts-regexp0))))
18098 (save-window-excursion
18099 ;; Find closest clock to point, adjust the previous/next one in history
18100 (let* ((p (save-excursion (org-back-to-heading t)))
18101 (cl (mapcar (lambda(c) (abs (- (marker-position c) p))) org-clock-history))
18102 (clfixnth
18103 (+ fixnext (- (length cl) (or (length (member (apply 'min cl) cl)) 100))))
18104 (clfixpos (unless (> 0 clfixnth) (nth clfixnth org-clock-history))))
18105 (if (not clfixpos)
18106 (message "No clock to adjust")
18107 (save-excursion
18108 (org-goto-marker-or-bmk clfixpos)
18109 (org-show-subtree)
18110 (when (re-search-forward clrgx nil t)
18111 (goto-char (match-beginning 1))
18112 (let (org-clock-adjust-closest)
18113 (org-timestamp-change n org-ts-what updown))
18114 (message "Clock adjusted in %s for heading: %s"
18115 (file-name-nondirectory (buffer-file-name))
18116 (org-get-heading t t)))))))))
18117 ;; Try to recenter the calendar window, if any.
18118 (when (and org-calendar-follow-timestamp-change
18119 (get-buffer-window "*Calendar*" t)
18120 (memq org-ts-what '(day month year)))
18121 (org-recenter-calendar (time-to-days time))))))
18123 (defun org-modify-ts-extra (s pos n dm)
18124 "Change the different parts of the lead-time and repeat fields in timestamp."
18125 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
18126 ng h m new rem)
18127 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
18128 (cond
18129 ((or (org-pos-in-match-range pos 2)
18130 (org-pos-in-match-range pos 3))
18131 (setq m (string-to-number (match-string 3 s))
18132 h (string-to-number (match-string 2 s)))
18133 (if (org-pos-in-match-range pos 2)
18134 (setq h (+ h n))
18135 (setq n (* dm (org-no-warnings (signum n))))
18136 (unless (= 0 (setq rem (% m dm)))
18137 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
18138 (setq m (+ m n)))
18139 (when (< m 0) (setq m (+ m 60) h (1- h)))
18140 (when (> m 59) (setq m (- m 60) h (1+ h)))
18141 (setq h (mod h 24))
18142 (setq ng 1 new (format "-%02d:%02d" h m)))
18143 ((org-pos-in-match-range pos 6)
18144 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
18145 ((org-pos-in-match-range pos 5)
18146 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
18148 ((org-pos-in-match-range pos 9)
18149 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
18150 ((org-pos-in-match-range pos 8)
18151 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
18153 (when ng
18154 (setq s (concat
18155 (substring s 0 (match-beginning ng))
18157 (substring s (match-end ng))))))
18160 (defun org-recenter-calendar (d)
18161 "If the calendar is visible, recenter it to date D."
18162 (let ((cwin (get-buffer-window "*Calendar*" t)))
18163 (when cwin
18164 (let ((calendar-move-hook nil))
18165 (with-selected-window cwin
18166 (calendar-goto-date
18167 (if (listp d) d (calendar-gregorian-from-absolute d))))))))
18169 (defun org-goto-calendar (&optional arg)
18170 "Go to the Emacs calendar at the current date.
18171 If there is a time stamp in the current line, go to that date.
18172 A prefix ARG can be used to force the current date."
18173 (interactive "P")
18174 (let ((tsr org-ts-regexp) diff
18175 (calendar-move-hook nil)
18176 (calendar-view-holidays-initially-flag nil)
18177 (calendar-view-diary-initially-flag nil))
18178 (when (or (org-at-timestamp-p)
18179 (save-excursion
18180 (beginning-of-line 1)
18181 (looking-at (concat ".*" tsr))))
18182 (let ((d1 (time-to-days (current-time)))
18183 (d2 (time-to-days
18184 (org-time-string-to-time (match-string 1)))))
18185 (setq diff (- d2 d1))))
18186 (calendar)
18187 (calendar-goto-today)
18188 (when (and diff (not arg)) (calendar-forward-day diff))))
18190 (defun org-get-date-from-calendar ()
18191 "Return a list (month day year) of date at point in calendar."
18192 (with-current-buffer "*Calendar*"
18193 (save-match-data
18194 (calendar-cursor-to-date))))
18196 (defun org-date-from-calendar ()
18197 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
18198 If there is already a time stamp at the cursor position, update it."
18199 (interactive)
18200 (if (org-at-timestamp-p t)
18201 (org-timestamp-change 0 'calendar)
18202 (let ((cal-date (org-get-date-from-calendar)))
18203 (org-insert-time-stamp
18204 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
18206 (defcustom org-effort-durations
18207 `(("min" . 1)
18208 ("h" . 60)
18209 ("d" . ,(* 60 8))
18210 ("w" . ,(* 60 8 5))
18211 ("m" . ,(* 60 8 5 4))
18212 ("y" . ,(* 60 8 5 40)))
18213 "Conversion factor to minutes for an effort modifier.
18215 Each entry has the form (MODIFIER . MINUTES).
18217 In an effort string, a number followed by MODIFIER is multiplied
18218 by the specified number of MINUTES to obtain an effort in
18219 minutes.
18221 For example, if the value of this variable is ((\"hours\" . 60)), then an
18222 effort string \"2hours\" is equivalent to 120 minutes."
18223 :group 'org-agenda
18224 :version "25.1"
18225 :package-version '(Org . "8.3")
18226 :type '(alist :key-type (string :tag "Modifier")
18227 :value-type (number :tag "Minutes")))
18229 (defun org-minutes-to-clocksum-string (m)
18230 "Format number of minutes as a clocksum string.
18231 The format is determined by `org-time-clocksum-format',
18232 `org-time-clocksum-use-fractional' and
18233 `org-time-clocksum-fractional-format' and
18234 `org-time-clocksum-use-effort-durations'."
18235 (let ((clocksum "")
18236 (m (round m)) ; Don't allow fractions of minutes
18237 h d w mo y fmt n)
18238 (setq h (if org-time-clocksum-use-effort-durations
18239 (cdr (assoc "h" org-effort-durations)) 60)
18240 d (if org-time-clocksum-use-effort-durations
18241 (/ (cdr (assoc "d" org-effort-durations)) h) 24)
18242 w (if org-time-clocksum-use-effort-durations
18243 (/ (cdr (assoc "w" org-effort-durations)) (* d h)) 7)
18244 mo (if org-time-clocksum-use-effort-durations
18245 (/ (cdr (assoc "m" org-effort-durations)) (* d h)) 30)
18246 y (if org-time-clocksum-use-effort-durations
18247 (/ (cdr (assoc "y" org-effort-durations)) (* d h)) 365))
18248 ;; fractional format
18249 (if org-time-clocksum-use-fractional
18250 (cond
18251 ;; single format string
18252 ((stringp org-time-clocksum-fractional-format)
18253 (format org-time-clocksum-fractional-format (/ m (float h))))
18254 ;; choice of fractional formats for different time units
18255 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :years))
18256 (> (/ (truncate m) (* y d h)) 0))
18257 (format fmt (/ m (* y d (float h)))))
18258 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :months))
18259 (> (/ (truncate m) (* mo d h)) 0))
18260 (format fmt (/ m (* mo d (float h)))))
18261 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18262 (> (/ (truncate m) (* w d h)) 0))
18263 (format fmt (/ m (* w d (float h)))))
18264 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :days))
18265 (> (/ (truncate m) (* d h)) 0))
18266 (format fmt (/ m (* d (float h)))))
18267 ((and (setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18268 (> (/ (truncate m) h) 0))
18269 (format fmt (/ m (float h))))
18270 ((setq fmt (plist-get org-time-clocksum-fractional-format :minutes))
18271 (format fmt m))
18272 ;; fall back to smallest time unit with a format
18273 ((setq fmt (plist-get org-time-clocksum-fractional-format :hours))
18274 (format fmt (/ m (float h))))
18275 ((setq fmt (plist-get org-time-clocksum-fractional-format :days))
18276 (format fmt (/ m (* d (float h)))))
18277 ((setq fmt (plist-get org-time-clocksum-fractional-format :weeks))
18278 (format fmt (/ m (* w d (float h)))))
18279 ((setq fmt (plist-get org-time-clocksum-fractional-format :months))
18280 (format fmt (/ m (* mo d (float h)))))
18281 ((setq fmt (plist-get org-time-clocksum-fractional-format :years))
18282 (format fmt (/ m (* y d (float h))))))
18283 ;; standard (non-fractional) format, with single format string
18284 (if (stringp org-time-clocksum-format)
18285 (format org-time-clocksum-format (setq n (/ m h)) (- m (* h n)))
18286 ;; separate formats components
18287 (and (setq fmt (plist-get org-time-clocksum-format :years))
18288 (or (> (setq n (/ (truncate m) (* y d h))) 0)
18289 (plist-get org-time-clocksum-format :require-years))
18290 (setq clocksum (concat clocksum (format fmt n))
18291 m (- m (* n y d h))))
18292 (and (setq fmt (plist-get org-time-clocksum-format :months))
18293 (or (> (setq n (/ (truncate m) (* mo d h))) 0)
18294 (plist-get org-time-clocksum-format :require-months))
18295 (setq clocksum (concat clocksum (format fmt n))
18296 m (- m (* n mo d h))))
18297 (and (setq fmt (plist-get org-time-clocksum-format :weeks))
18298 (or (> (setq n (/ (truncate m) (* w d h))) 0)
18299 (plist-get org-time-clocksum-format :require-weeks))
18300 (setq clocksum (concat clocksum (format fmt n))
18301 m (- m (* n w d h))))
18302 (and (setq fmt (plist-get org-time-clocksum-format :days))
18303 (or (> (setq n (/ (truncate m) (* d h))) 0)
18304 (plist-get org-time-clocksum-format :require-days))
18305 (setq clocksum (concat clocksum (format fmt n))
18306 m (- m (* n d h))))
18307 (and (setq fmt (plist-get org-time-clocksum-format :hours))
18308 (or (> (setq n (/ (truncate m) h)) 0)
18309 (plist-get org-time-clocksum-format :require-hours))
18310 (setq clocksum (concat clocksum (format fmt n))
18311 m (- m (* n h))))
18312 (and (setq fmt (plist-get org-time-clocksum-format :minutes))
18313 (or (> m 0) (plist-get org-time-clocksum-format :require-minutes))
18314 (setq clocksum (concat clocksum (format fmt m))))
18315 ;; return formatted time duration
18316 clocksum))))
18318 (defalias 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string)
18319 (make-obsolete 'org-minutes-to-hh:mm-string 'org-minutes-to-clocksum-string
18320 "Org mode version 8.0")
18322 (defun org-hours-to-clocksum-string (n)
18323 (org-minutes-to-clocksum-string (* n 60)))
18325 (defun org-hh:mm-string-to-minutes (s)
18326 "Convert a string H:MM to a number of minutes.
18327 If the string is just a number, interpret it as minutes.
18328 In fact, the first hh:mm or number in the string will be taken,
18329 there can be extra stuff in the string.
18330 If no number is found, the return value is 0."
18331 (cond
18332 ((integerp s) s)
18333 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
18334 (+ (* (string-to-number (match-string 1 s)) 60)
18335 (string-to-number (match-string 2 s))))
18336 ((string-match "\\([0-9]+\\)" s)
18337 (string-to-number (match-string 1 s)))
18338 (t 0)))
18340 (defcustom org-image-actual-width t
18341 "Should we use the actual width of images when inlining them?
18343 When set to t, always use the image width.
18345 When set to a number, use imagemagick (when available) to set
18346 the image's width to this value.
18348 When set to a number in a list, try to get the width from any
18349 #+ATTR.* keyword if it matches a width specification like
18351 #+ATTR_HTML: :width 300px
18353 and fall back on that number if none is found.
18355 When set to nil, try to get the width from an #+ATTR.* keyword
18356 and fall back on the original width if none is found.
18358 This requires Emacs >= 24.1, build with imagemagick support."
18359 :group 'org-appearance
18360 :version "24.4"
18361 :package-version '(Org . "8.0")
18362 :type '(choice
18363 (const :tag "Use the image width" t)
18364 (integer :tag "Use a number of pixels")
18365 (list :tag "Use #+ATTR* or a number of pixels" (integer))
18366 (const :tag "Use #+ATTR* or don't resize" nil)))
18368 (defcustom org-agenda-inhibit-startup nil
18369 "Inhibit startup when preparing agenda buffers.
18370 When this variable is t, the initialization of the Org agenda
18371 buffers is inhibited: e.g. the visibility state is not set, the
18372 tables are not re-aligned, etc."
18373 :type 'boolean
18374 :version "24.3"
18375 :group 'org-agenda)
18377 (define-obsolete-variable-alias
18378 'org-agenda-ignore-drawer-properties
18379 'org-agenda-ignore-properties "25.1")
18381 (defcustom org-agenda-ignore-properties nil
18382 "Avoid updating text properties when building the agenda.
18383 Properties are used to prepare buffers for effort estimates,
18384 appointments, statistics and subtree-local categories.
18385 If you don't use these in the agenda, you can add them to this
18386 list and agenda building will be a bit faster.
18387 The value is a list, with zero or more of the symbols `effort', `appt',
18388 `stats' or `category'."
18389 :type '(set :greedy t
18390 (const effort)
18391 (const appt)
18392 (const stats)
18393 (const category))
18394 :version "25.1"
18395 :package-version '(Org . "8.3")
18396 :group 'org-agenda)
18398 (defun org-duration-string-to-minutes (s &optional output-to-string)
18399 "Convert a duration string S to minutes.
18401 A bare number is interpreted as minutes, modifiers can be set by
18402 customizing `org-effort-durations' (which see).
18404 Entries containing a colon are interpreted as H:MM by
18405 `org-hh:mm-string-to-minutes'."
18406 (let ((result 0)
18407 (re (concat "\\([0-9.]+\\) *\\("
18408 (regexp-opt (mapcar 'car org-effort-durations))
18409 "\\)")))
18410 (while (string-match re s)
18411 (cl-incf result (* (cdr (assoc (match-string 2 s) org-effort-durations))
18412 (string-to-number (match-string 1 s))))
18413 (setq s (replace-match "" nil t s)))
18414 (setq result (floor result))
18415 (cl-incf result (org-hh:mm-string-to-minutes s))
18416 (if output-to-string (number-to-string result) result)))
18418 ;;;; Files
18420 (defun org-save-all-org-buffers ()
18421 "Save all Org-mode buffers without user confirmation."
18422 (interactive)
18423 (message "Saving all Org-mode buffers...")
18424 (save-some-buffers t (lambda () (derived-mode-p 'org-mode)))
18425 (when (featurep 'org-id) (org-id-locations-save))
18426 (message "Saving all Org-mode buffers... done"))
18428 (defun org-revert-all-org-buffers ()
18429 "Revert all Org-mode buffers.
18430 Prompt for confirmation when there are unsaved changes.
18431 Be sure you know what you are doing before letting this function
18432 overwrite your changes.
18434 This function is useful in a setup where one tracks org files
18435 with a version control system, to revert on one machine after pulling
18436 changes from another. I believe the procedure must be like this:
18438 1. M-x org-save-all-org-buffers
18439 2. Pull changes from the other machine, resolve conflicts
18440 3. M-x org-revert-all-org-buffers"
18441 (interactive)
18442 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
18443 (user-error "Abort"))
18444 (save-excursion
18445 (save-window-excursion
18446 (dolist (b (buffer-list))
18447 (when (and (with-current-buffer b (derived-mode-p 'org-mode))
18448 (with-current-buffer b buffer-file-name))
18449 (org-pop-to-buffer-same-window b)
18450 (revert-buffer t 'no-confirm)))
18451 (when (and (featurep 'org-id) org-id-track-globally)
18452 (org-id-locations-load)))))
18454 ;;;; Agenda files
18456 ;;;###autoload
18457 (defun org-switchb (&optional arg)
18458 "Switch between Org buffers.
18460 With \\[universal-argument] prefix, restrict available buffers to files.
18462 With \\[universal-argument] \\[universal-argument] \
18463 prefix, restrict available buffers to agenda files."
18464 (interactive "P")
18465 (let ((blist (org-buffer-list
18466 (cond ((equal arg '(4)) 'files)
18467 ((equal arg '(16)) 'agenda)))))
18468 (org-pop-to-buffer-same-window
18469 (completing-read "Org buffer: "
18470 (mapcar #'list (mapcar #'buffer-name blist))
18471 nil t))))
18473 (defun org-buffer-list (&optional predicate exclude-tmp)
18474 "Return a list of Org buffers.
18475 PREDICATE can be `export', `files' or `agenda'.
18477 export restrict the list to Export buffers.
18478 files restrict the list to buffers visiting Org files.
18479 agenda restrict the list to buffers visiting agenda files.
18481 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
18482 (let* ((bfn nil)
18483 (agenda-files (and (eq predicate 'agenda)
18484 (mapcar 'file-truename (org-agenda-files t))))
18485 (filter
18486 (cond
18487 ((eq predicate 'files)
18488 (lambda (b) (with-current-buffer b (derived-mode-p 'org-mode))))
18489 ((eq predicate 'export)
18490 (lambda (b) (string-match "\\*Org .*Export" (buffer-name b))))
18491 ((eq predicate 'agenda)
18492 (lambda (b)
18493 (with-current-buffer b
18494 (and (derived-mode-p 'org-mode)
18495 (setq bfn (buffer-file-name b))
18496 (member (file-truename bfn) agenda-files)))))
18497 (t (lambda (b) (with-current-buffer b
18498 (or (derived-mode-p 'org-mode)
18499 (string-match "\\*Org .*Export"
18500 (buffer-name b)))))))))
18501 (delq nil
18502 (mapcar
18503 (lambda(b)
18504 (if (and (funcall filter b)
18505 (or (not exclude-tmp)
18506 (not (string-match "tmp" (buffer-name b)))))
18508 nil))
18509 (buffer-list)))))
18511 (defun org-agenda-files (&optional unrestricted archives)
18512 "Get the list of agenda files.
18513 Optional UNRESTRICTED means return the full list even if a restriction
18514 is currently in place.
18515 When ARCHIVES is t, include all archive files that are really being
18516 used by the agenda files. If ARCHIVE is `ifmode', do this only if
18517 `org-agenda-archives-mode' is t."
18518 (let ((files
18519 (cond
18520 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
18521 ((stringp org-agenda-files) (org-read-agenda-file-list))
18522 ((listp org-agenda-files) org-agenda-files)
18523 (t (error "Invalid value of `org-agenda-files'")))))
18524 (setq files (apply 'append
18525 (mapcar (lambda (f)
18526 (if (file-directory-p f)
18527 (directory-files
18528 f t org-agenda-file-regexp)
18529 (list f)))
18530 files)))
18531 (when org-agenda-skip-unavailable-files
18532 (setq files (delq nil
18533 (mapcar (function
18534 (lambda (file)
18535 (and (file-readable-p file) file)))
18536 files))))
18537 (when (or (eq archives t)
18538 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
18539 (setq files (org-add-archive-files files)))
18540 files))
18542 (defun org-agenda-file-p (&optional file)
18543 "Return non-nil, if FILE is an agenda file.
18544 If FILE is omitted, use the file associated with the current
18545 buffer."
18546 (let ((fname (or file (buffer-file-name))))
18547 (and fname
18548 (member (file-truename fname)
18549 (mapcar #'file-truename (org-agenda-files t))))))
18551 (defun org-edit-agenda-file-list ()
18552 "Edit the list of agenda files.
18553 Depending on setup, this either uses customize to edit the variable
18554 `org-agenda-files', or it visits the file that is holding the list. In the
18555 latter case, the buffer is set up in a way that saving it automatically kills
18556 the buffer and restores the previous window configuration."
18557 (interactive)
18558 (if (stringp org-agenda-files)
18559 (let ((cw (current-window-configuration)))
18560 (find-file org-agenda-files)
18561 (setq-local org-window-configuration cw)
18562 (org-add-hook 'after-save-hook
18563 (lambda ()
18564 (set-window-configuration
18565 (prog1 org-window-configuration
18566 (kill-buffer (current-buffer))))
18567 (org-install-agenda-files-menu)
18568 (message "New agenda file list installed"))
18569 nil 'local)
18570 (message "%s" (substitute-command-keys
18571 "Edit list and finish with \\[save-buffer]")))
18572 (customize-variable 'org-agenda-files)))
18574 (defun org-store-new-agenda-file-list (list)
18575 "Set new value for the agenda file list and save it correctly."
18576 (if (stringp org-agenda-files)
18577 (let ((fe (org-read-agenda-file-list t)) b u)
18578 (while (setq b (find-buffer-visiting org-agenda-files))
18579 (kill-buffer b))
18580 (with-temp-file org-agenda-files
18581 (insert
18582 (mapconcat
18583 (lambda (f) ;; Keep un-expanded entries.
18584 (if (setq u (assoc f fe))
18585 (cdr u)
18587 list "\n")
18588 "\n")))
18589 (let ((org-mode-hook nil) (org-inhibit-startup t)
18590 (org-insert-mode-line-in-empty-file nil))
18591 (setq org-agenda-files list)
18592 (customize-save-variable 'org-agenda-files org-agenda-files))))
18594 (defun org-read-agenda-file-list (&optional pair-with-expansion)
18595 "Read the list of agenda files from a file.
18596 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
18597 filenames, used by `org-store-new-agenda-file-list' to write back
18598 un-expanded file names."
18599 (when (file-directory-p org-agenda-files)
18600 (error "`org-agenda-files' cannot be a single directory"))
18601 (when (stringp org-agenda-files)
18602 (with-temp-buffer
18603 (insert-file-contents org-agenda-files)
18604 (mapcar
18605 (lambda (f)
18606 (let ((e (expand-file-name (substitute-in-file-name f)
18607 org-directory)))
18608 (if pair-with-expansion
18609 (cons e f)
18610 e)))
18611 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
18613 ;;;###autoload
18614 (defun org-cycle-agenda-files ()
18615 "Cycle through the files in `org-agenda-files'.
18616 If the current buffer visits an agenda file, find the next one in the list.
18617 If the current buffer does not, find the first agenda file."
18618 (interactive)
18619 (let* ((fs (or (org-agenda-files t)
18620 (user-error "No agenda files")))
18621 (files (copy-sequence fs))
18622 (tcf (and buffer-file-name (file-truename buffer-file-name)))
18623 file)
18624 (when tcf
18625 (while (and (setq file (pop files))
18626 (not (equal (file-truename file) tcf)))))
18627 (find-file (car (or files fs)))
18628 (when (buffer-base-buffer) (org-pop-to-buffer-same-window (buffer-base-buffer)))))
18630 (defun org-agenda-file-to-front (&optional to-end)
18631 "Move/add the current file to the top of the agenda file list.
18632 If the file is not present in the list, it is added to the front. If it is
18633 present, it is moved there. With optional argument TO-END, add/move to the
18634 end of the list."
18635 (interactive "P")
18636 (let ((org-agenda-skip-unavailable-files nil)
18637 (file-alist (mapcar (lambda (x)
18638 (cons (file-truename x) x))
18639 (org-agenda-files t)))
18640 (ctf (file-truename
18641 (or buffer-file-name
18642 (user-error "Please save the current buffer to a file"))))
18643 x had)
18644 (setq x (assoc ctf file-alist) had x)
18646 (unless x (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
18647 (if to-end
18648 (setq file-alist (append (delq x file-alist) (list x)))
18649 (setq file-alist (cons x (delq x file-alist))))
18650 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
18651 (org-install-agenda-files-menu)
18652 (message "File %s to %s of agenda file list"
18653 (if had "moved" "added") (if to-end "end" "front"))))
18655 (defun org-remove-file (&optional file)
18656 "Remove current file from the list of files in variable `org-agenda-files'.
18657 These are the files which are being checked for agenda entries.
18658 Optional argument FILE means use this file instead of the current."
18659 (interactive)
18660 (let* ((org-agenda-skip-unavailable-files nil)
18661 (file (or file buffer-file-name
18662 (user-error "Current buffer does not visit a file")))
18663 (true-file (file-truename file))
18664 (afile (abbreviate-file-name file))
18665 (files (delq nil (mapcar
18666 (lambda (x)
18667 (unless (equal true-file
18668 (file-truename x))
18670 (org-agenda-files t)))))
18671 (if (not (= (length files) (length (org-agenda-files t))))
18672 (progn
18673 (org-store-new-agenda-file-list files)
18674 (org-install-agenda-files-menu)
18675 (message "Removed from Org Agenda list: %s" afile))
18676 (message "File was not in list: %s (not removed)" afile))))
18678 (defun org-file-menu-entry (file)
18679 (vector file (list 'find-file file) t))
18681 (defun org-check-agenda-file (file)
18682 "Make sure FILE exists. If not, ask user what to do."
18683 (unless (file-exists-p file)
18684 (message "Non-existent agenda file %s. [R]emove from list or [A]bort?"
18685 (abbreviate-file-name file))
18686 (let ((r (downcase (read-char-exclusive))))
18687 (cond
18688 ((equal r ?r)
18689 (org-remove-file file)
18690 (throw 'nextfile t))
18691 (t (user-error "Abort"))))))
18693 (defun org-get-agenda-file-buffer (file)
18694 "Get an agenda buffer visiting FILE.
18695 If the buffer needs to be created, add it to the list of buffers
18696 which might be released later."
18697 (let ((buf (org-find-base-buffer-visiting file)))
18698 (if buf
18699 buf ; just return it
18700 ;; Make a new buffer and remember it
18701 (setq buf (find-file-noselect file))
18702 (when buf (push buf org-agenda-new-buffers))
18703 buf)))
18705 (defun org-release-buffers (blist)
18706 "Release all buffers in list, asking the user for confirmation when needed.
18707 When a buffer is unmodified, it is just killed. When modified, it is saved
18708 \(if the user agrees) and then killed."
18709 (let (file)
18710 (dolist (buf blist)
18711 (setq file (buffer-file-name buf))
18712 (when (and (buffer-modified-p buf)
18713 file
18714 (y-or-n-p (format "Save file %s? " file)))
18715 (with-current-buffer buf (save-buffer)))
18716 (kill-buffer buf))))
18718 (defun org-agenda-prepare-buffers (files)
18719 "Create buffers for all agenda files, protect archived trees and comments."
18720 (interactive)
18721 (let ((pa '(:org-archived t))
18722 (pc '(:org-comment t))
18723 (pall '(:org-archived t :org-comment t))
18724 (inhibit-read-only t)
18725 (org-inhibit-startup org-agenda-inhibit-startup)
18726 (rea (concat ":" org-archive-tag ":"))
18727 re pos)
18728 (setq org-tag-alist-for-agenda nil
18729 org-tag-groups-alist-for-agenda nil)
18730 (save-excursion
18731 (save-restriction
18732 (dolist (file files)
18733 (catch 'nextfile
18734 (if (bufferp file)
18735 (set-buffer file)
18736 (org-check-agenda-file file)
18737 (set-buffer (org-get-agenda-file-buffer file)))
18738 (widen)
18739 (org-set-regexps-and-options 'tags-only)
18740 (setq pos (point))
18741 (or (memq 'category org-agenda-ignore-properties)
18742 (org-refresh-category-properties))
18743 (or (memq 'stats org-agenda-ignore-properties)
18744 (org-refresh-stats-properties))
18745 (or (memq 'effort org-agenda-ignore-properties)
18746 (org-refresh-effort-properties))
18747 (or (memq 'appt org-agenda-ignore-properties)
18748 (org-refresh-properties "APPT_WARNTIME" 'org-appt-warntime))
18749 (setq org-todo-keywords-for-agenda
18750 (append org-todo-keywords-for-agenda org-todo-keywords-1))
18751 (setq org-done-keywords-for-agenda
18752 (append org-done-keywords-for-agenda org-done-keywords))
18753 (setq org-todo-keyword-alist-for-agenda
18754 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
18755 (setq org-tag-alist-for-agenda
18756 (org-uniquify
18757 (append org-tag-alist-for-agenda
18758 org-current-tag-alist)))
18759 ;; Merge current file's tag groups into global
18760 ;; `org-tag-groups-alist-for-agenda'.
18761 (when org-group-tags
18762 (dolist (alist org-tag-groups-alist)
18763 (let ((old (assoc (car alist) org-tag-groups-alist-for-agenda)))
18764 (if old
18765 (setcdr old (org-uniquify (append (cdr old) (cdr alist))))
18766 (push alist org-tag-groups-alist-for-agenda)))))
18767 (org-with-silent-modifications
18768 (save-excursion
18769 (remove-text-properties (point-min) (point-max) pall)
18770 (when org-agenda-skip-archived-trees
18771 (goto-char (point-min))
18772 (while (re-search-forward rea nil t)
18773 (when (org-at-heading-p t)
18774 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
18775 (goto-char (point-min))
18776 (setq re (format "^\\*+ .*\\<%s\\>" org-comment-string))
18777 (while (re-search-forward re nil t)
18778 (when (save-match-data (org-in-commented-heading-p t))
18779 (add-text-properties
18780 (match-beginning 0) (org-end-of-subtree t) pc)))))
18781 (goto-char pos)))))
18782 (setq org-todo-keywords-for-agenda
18783 (org-uniquify org-todo-keywords-for-agenda))
18784 (setq org-todo-keyword-alist-for-agenda
18785 (org-uniquify org-todo-keyword-alist-for-agenda))))
18788 ;;;; CDLaTeX minor mode
18790 (defvar org-cdlatex-mode-map (make-sparse-keymap)
18791 "Keymap for the minor `org-cdlatex-mode'.")
18793 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
18794 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
18795 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
18796 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
18797 (org-defkey org-cdlatex-mode-map "\C-c{" 'org-cdlatex-environment-indent)
18799 (defvar org-cdlatex-texmathp-advice-is-done nil
18800 "Flag remembering if we have applied the advice to texmathp already.")
18802 (define-minor-mode org-cdlatex-mode
18803 "Toggle the minor `org-cdlatex-mode'.
18804 This mode supports entering LaTeX environment and math in LaTeX fragments
18805 in Org-mode.
18806 \\{org-cdlatex-mode-map}"
18807 nil " OCDL" nil
18808 (when org-cdlatex-mode
18809 (require 'cdlatex)
18810 (run-hooks 'cdlatex-mode-hook)
18811 (cdlatex-compute-tables))
18812 (unless org-cdlatex-texmathp-advice-is-done
18813 (setq org-cdlatex-texmathp-advice-is-done t)
18814 (defadvice texmathp (around org-math-always-on activate)
18815 "Always return t in org-mode buffers.
18816 This is because we want to insert math symbols without dollars even outside
18817 the LaTeX math segments. If Orgmode thinks that point is actually inside
18818 an embedded LaTeX fragment, let texmathp do its job.
18819 \\[org-cdlatex-mode-map]"
18820 (interactive)
18821 (let (p)
18822 (cond
18823 ((not (derived-mode-p 'org-mode)) ad-do-it)
18824 ((eq this-command 'cdlatex-math-symbol)
18825 (setq ad-return-value t
18826 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
18828 (let ((p (org-inside-LaTeX-fragment-p)))
18829 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
18830 (setq ad-return-value t
18831 texmathp-why '("Org-mode embedded math" . 0))
18832 (when p ad-do-it)))))))))
18834 (defun turn-on-org-cdlatex ()
18835 "Unconditionally turn on `org-cdlatex-mode'."
18836 (org-cdlatex-mode 1))
18838 (defun org-try-cdlatex-tab ()
18839 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
18840 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
18841 - inside a LaTeX fragment, or
18842 - after the first word in a line, where an abbreviation expansion could
18843 insert a LaTeX environment."
18844 (when org-cdlatex-mode
18845 (cond
18846 ;; Before any word on the line: No expansion possible.
18847 ((save-excursion (skip-chars-backward " \t") (bolp)) nil)
18848 ;; Just after first word on the line: Expand it. Make sure it
18849 ;; cannot happen on headlines, though.
18850 ((save-excursion
18851 (skip-chars-backward "a-zA-Z0-9*")
18852 (skip-chars-backward " \t")
18853 (and (bolp) (not (org-at-heading-p))))
18854 (cdlatex-tab) t)
18855 ((org-inside-LaTeX-fragment-p) (cdlatex-tab) t))))
18857 (defun org-cdlatex-underscore-caret (&optional _arg)
18858 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
18859 Revert to the normal definition outside of these fragments."
18860 (interactive "P")
18861 (if (org-inside-LaTeX-fragment-p)
18862 (call-interactively 'cdlatex-sub-superscript)
18863 (let (org-cdlatex-mode)
18864 (call-interactively (key-binding (vector last-input-event))))))
18866 (defun org-cdlatex-math-modify (&optional _arg)
18867 "Execute `cdlatex-math-modify' in LaTeX fragments.
18868 Revert to the normal definition outside of these fragments."
18869 (interactive "P")
18870 (if (org-inside-LaTeX-fragment-p)
18871 (call-interactively 'cdlatex-math-modify)
18872 (let (org-cdlatex-mode)
18873 (call-interactively (key-binding (vector last-input-event))))))
18875 (defun org-cdlatex-environment-indent (&optional environment item)
18876 "Execute `cdlatex-environment' and indent the inserted environment.
18878 ENVIRONMENT and ITEM are passed to `cdlatex-environment'.
18880 The inserted environment is indented to current indentation
18881 unless point is at the beginning of the line, in which the
18882 environment remains unintended."
18883 (interactive)
18884 ;; cdlatex-environment always return nil. Therefore, capture output
18885 ;; first and determine if an environment was selected.
18886 (let* ((beg (point-marker))
18887 (end (copy-marker (point) t))
18888 (inserted (progn
18889 (ignore-errors (cdlatex-environment environment item))
18890 (< beg end)))
18891 ;; Figure out how many lines to move forward after the
18892 ;; environment has been inserted.
18893 (lines (when inserted
18894 (save-excursion
18895 (- (cl-loop while (< beg (point))
18896 with x = 0
18897 do (forward-line -1)
18898 (cl-incf x)
18899 finally return x)
18900 (if (progn (goto-char beg)
18901 (and (progn (skip-chars-forward " \t") (eolp))
18902 (progn (skip-chars-backward " \t") (bolp))))
18903 1 0)))))
18904 (env (org-trim (delete-and-extract-region beg end))))
18905 (when inserted
18906 ;; Get indentation of next line unless at column 0.
18907 (let ((ind (if (bolp) 0
18908 (save-excursion
18909 (org-return-indent)
18910 (prog1 (org-get-indentation)
18911 (when (progn (skip-chars-forward " \t") (eolp))
18912 (delete-region beg (point)))))))
18913 (bol (progn (skip-chars-backward " \t") (bolp))))
18914 ;; Insert a newline before environment unless at column zero
18915 ;; to "escape" the current line. Insert a newline if
18916 ;; something is one the same line as \end{ENVIRONMENT}.
18917 (insert
18918 (concat (unless bol "\n") env
18919 (when (and (skip-chars-forward " \t") (not (eolp))) "\n")))
18920 (unless (zerop ind)
18921 (save-excursion
18922 (goto-char beg)
18923 (while (< (point) end)
18924 (unless (eolp) (org-indent-line-to ind))
18925 (forward-line))))
18926 (goto-char beg)
18927 (forward-line lines)
18928 (org-indent-line-to ind)))
18929 (set-marker beg nil)
18930 (set-marker end nil)))
18933 ;;;; LaTeX fragments
18935 (defun org-inside-LaTeX-fragment-p ()
18936 "Test if point is inside a LaTeX fragment.
18937 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
18938 sequence appearing also before point.
18939 Even though the matchers for math are configurable, this function assumes
18940 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
18941 delimiters are skipped when they have been removed by customization.
18942 The return value is nil, or a cons cell with the delimiter and the
18943 position of this delimiter.
18945 This function does a reasonably good job, but can locally be fooled by
18946 for example currency specifications. For example it will assume being in
18947 inline math after \"$22.34\". The LaTeX fragment formatter will only format
18948 fragments that are properly closed, but during editing, we have to live
18949 with the uncertainty caused by missing closing delimiters. This function
18950 looks only before point, not after."
18951 (catch 'exit
18952 (let ((pos (point))
18953 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
18954 (lim (progn
18955 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
18956 (point)))
18957 dd-on str (start 0) m re)
18958 (goto-char pos)
18959 (when dodollar
18960 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
18961 re (nth 1 (assoc "$" org-latex-regexps)))
18962 (while (string-match re str start)
18963 (cond
18964 ((= (match-end 0) (length str))
18965 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
18966 ((= (match-end 0) (- (length str) 5))
18967 (throw 'exit nil))
18968 (t (setq start (match-end 0))))))
18969 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
18970 (goto-char pos)
18971 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
18972 (and (match-beginning 2) (throw 'exit nil))
18973 ;; count $$
18974 (while (re-search-backward "\\$\\$" lim t)
18975 (setq dd-on (not dd-on)))
18976 (goto-char pos)
18977 (when dd-on (cons "$$" m))))))
18979 (defun org-inside-latex-macro-p ()
18980 "Is point inside a LaTeX macro or its arguments?"
18981 (save-match-data
18982 (org-in-regexp
18983 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
18985 (defun org--format-latex-make-overlay (beg end image)
18986 "Build an overlay between BEG and END using IMAGE file."
18987 (let ((ov (make-overlay beg end)))
18988 (overlay-put ov 'org-overlay-type 'org-latex-overlay)
18989 (overlay-put ov 'evaporate t)
18990 (overlay-put ov
18991 'modification-hooks
18992 (list (lambda (o _flag _beg _end &optional _l)
18993 (delete-overlay o))))
18994 (if (featurep 'xemacs)
18995 (progn
18996 (overlay-put ov 'invisible t)
18997 (overlay-put ov 'end-glyph (make-glyph (vector 'png :file image))))
18998 (overlay-put ov
18999 'display
19000 (list 'image :type 'png :file image :ascent 'center)))))
19002 (defun org--list-latex-overlays (&optional beg end)
19003 "List all Org LaTeX overlays in current buffer.
19004 Limit to overlays between BEG and END when those are provided."
19005 (cl-remove-if-not
19006 (lambda (o) (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay))
19007 (overlays-in (or beg (point-min)) (or end (point-max)))))
19009 (defun org-remove-latex-fragment-image-overlays (&optional beg end)
19010 "Remove all overlays with LaTeX fragment images in current buffer.
19011 When optional arguments BEG and END are non-nil, remove all
19012 overlays between them instead. Return a non-nil value when some
19013 overlays were removed, nil otherwise."
19014 (let ((overlays (org--list-latex-overlays beg end)))
19015 (mapc #'delete-overlay overlays)
19016 overlays))
19018 (define-obsolete-function-alias
19019 'org-preview-latex-fragment 'org-toggle-latex-fragment "24.4")
19020 (defun org-toggle-latex-fragment (&optional arg)
19021 "Preview the LaTeX fragment at point, or all locally or globally.
19023 If the cursor is on a LaTeX fragment, create the image and overlay
19024 it over the source code, if there is none. Remove it otherwise.
19025 If there is no fragment at point, display all fragments in the
19026 current section.
19028 With prefix ARG, preview or clear image for all fragments in the
19029 current subtree or in the whole buffer when used before the first
19030 headline. With a double prefix ARG \\[universal-argument] \
19031 \\[universal-argument] preview or clear images
19032 for all fragments in the buffer."
19033 (interactive "P")
19034 (when (display-graphic-p)
19035 (catch 'exit
19036 (save-excursion
19037 (let ((window-start (window-start)) msg)
19038 (save-restriction
19039 (cond
19040 ((or (equal arg '(16))
19041 (and (equal arg '(4))
19042 (org-with-limited-levels (org-before-first-heading-p))))
19043 (if (org-remove-latex-fragment-image-overlays)
19044 (progn (message "LaTeX fragments images removed from buffer")
19045 (throw 'exit nil))
19046 (setq msg "Creating images for buffer...")))
19047 ((equal arg '(4))
19048 (org-with-limited-levels (org-back-to-heading t))
19049 (let ((beg (point))
19050 (end (progn (org-end-of-subtree t) (point))))
19051 (if (org-remove-latex-fragment-image-overlays beg end)
19052 (progn
19053 (message "LaTeX fragment images removed from subtree")
19054 (throw 'exit nil))
19055 (setq msg "Creating images for subtree...")
19056 (narrow-to-region beg end))))
19057 ((let ((datum (org-element-context)))
19058 (when (memq (org-element-type datum)
19059 '(latex-environment latex-fragment))
19060 (let* ((beg (org-element-property :begin datum))
19061 (end (org-element-property :end datum)))
19062 (if (org-remove-latex-fragment-image-overlays beg end)
19063 (progn (message "LaTeX fragment image removed")
19064 (throw 'exit nil))
19065 (narrow-to-region beg end)
19066 (setq msg "Creating image..."))))))
19068 (org-with-limited-levels
19069 (let ((beg (if (org-at-heading-p) (line-beginning-position)
19070 (outline-previous-heading)
19071 (point)))
19072 (end (progn (outline-next-heading) (point))))
19073 (if (org-remove-latex-fragment-image-overlays beg end)
19074 (progn
19075 (message "LaTeX fragment images removed from section")
19076 (throw 'exit nil))
19077 (setq msg "Creating images for section...")
19078 (narrow-to-region beg end))))))
19079 (let ((file (buffer-file-name (buffer-base-buffer))))
19080 (org-format-latex
19081 (concat org-latex-preview-ltxpng-directory "org-ltxpng")
19082 ;; Emacs cannot overlay images from remote hosts.
19083 ;; Create it in `temporary-file-directory' instead.
19084 (if (or (not file) (file-remote-p file))
19085 temporary-file-directory
19086 default-directory)
19087 'overlays msg 'forbuffer
19088 org-latex-create-formula-image-program)))
19089 ;; Work around a bug that doesn't restore window's start
19090 ;; when widening back the buffer.
19091 (set-window-start nil window-start)
19092 (message (concat msg "done")))))))
19094 (defun org-format-latex
19095 (prefix &optional dir overlays msg forbuffer processing-type)
19096 "Replace LaTeX fragments with links to an image, and produce images.
19098 When optional argument OVERLAYS is non-nil, display the image on
19099 top of the fragment instead of replacing it.
19101 PROCESSING-TYPE is the conversion method to use, as a symbol.
19103 Some of the options can be changed using the variable
19104 `org-format-latex-options', which see."
19105 (when (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
19106 (unless (eq processing-type 'verbatim)
19107 (let* ((math-regexp "\\$\\|\\\\[([]\\|^[ \t]*\\\\begin{[A-Za-z0-9*]+}")
19108 (cnt 0)
19109 checkdir-flag)
19110 (goto-char (point-min))
19111 ;; Optimize overlay creation: (info "(elisp) Managing Overlays").
19112 (when (and overlays (memq processing-type '(dvipng imagemagick)))
19113 (overlay-recenter (point-max)))
19114 (while (re-search-forward math-regexp nil t)
19115 (unless (and overlays
19116 (eq (get-char-property (point) 'org-overlay-type)
19117 'org-latex-overlay))
19118 (let* ((context (org-element-context))
19119 (type (org-element-type context)))
19120 (when (memq type '(latex-environment latex-fragment))
19121 (let ((block-type (eq type 'latex-environment))
19122 (value (org-element-property :value context))
19123 (beg (org-element-property :begin context))
19124 (end (save-excursion
19125 (goto-char (org-element-property :end context))
19126 (skip-chars-backward " \r\t\n")
19127 (point))))
19128 (cl-case processing-type
19129 (mathjax
19130 ;; Prepare for MathJax processing.
19131 (if (not (string-match "\\`\\$\\$?" value))
19132 (goto-char end)
19133 (delete-region beg end)
19134 (if (string= (match-string 0 value) "$$")
19135 (insert "\\[" (substring value 2 -2) "\\]")
19136 (insert "\\(" (substring value 1 -1) "\\)"))))
19137 ((dvipng imagemagick)
19138 ;; Process to an image.
19139 (cl-incf cnt)
19140 (goto-char beg)
19141 (let* ((face (face-at-point))
19142 ;; Get the colors from the face at point.
19144 (let ((color (plist-get org-format-latex-options
19145 :foreground)))
19146 (if (and forbuffer (eq color 'auto))
19147 (face-attribute face :foreground nil 'default)
19148 color)))
19150 (let ((color (plist-get org-format-latex-options
19151 :background)))
19152 (if (and forbuffer (eq color 'auto))
19153 (face-attribute face :background nil 'default)
19154 color)))
19155 (hash (sha1 (prin1-to-string
19156 (list org-format-latex-header
19157 org-latex-default-packages-alist
19158 org-latex-packages-alist
19159 org-format-latex-options
19160 forbuffer value fg bg))))
19161 (absprefix (expand-file-name prefix dir))
19162 (linkfile (format "%s_%s.png" prefix hash))
19163 (movefile (format "%s_%s.png" absprefix hash))
19164 (sep (and block-type "\n\n"))
19165 (link (concat sep "[[file:" linkfile "]]" sep))
19166 (options
19167 (org-combine-plists
19168 org-format-latex-options
19169 `(:foreground ,fg :background ,bg))))
19170 (when msg (message msg cnt))
19171 (unless checkdir-flag ; Ensure the directory exists.
19172 (setq checkdir-flag t)
19173 (let ((todir (file-name-directory absprefix)))
19174 (unless (file-directory-p todir)
19175 (make-directory todir t))))
19176 (unless (file-exists-p movefile)
19177 (org-create-formula-image
19178 value movefile options forbuffer processing-type))
19179 (if overlays
19180 (progn
19181 (dolist (o (overlays-in beg end))
19182 (when (eq (overlay-get o 'org-overlay-type)
19183 'org-latex-overlay)
19184 (delete-overlay o)))
19185 (org--format-latex-make-overlay beg end movefile)
19186 (goto-char end))
19187 (delete-region beg end)
19188 (insert
19189 (org-add-props link
19190 (list 'org-latex-src
19191 (replace-regexp-in-string "\"" "" value)
19192 'org-latex-src-embed-type
19193 (if block-type 'paragraph 'character)))))))
19194 (mathml
19195 ;; Process to MathML.
19196 (unless (org-format-latex-mathml-available-p)
19197 (user-error "LaTeX to MathML converter not configured"))
19198 (cl-incf cnt)
19199 (when msg (message msg cnt))
19200 (goto-char beg)
19201 (delete-region beg end)
19202 (insert (org-format-latex-as-mathml
19203 value block-type prefix dir)))
19204 (otherwise
19205 (error "Unknown conversion type %s for LaTeX fragments"
19206 processing-type)))))))))))
19208 (defun org-create-math-formula (latex-frag &optional mathml-file)
19209 "Convert LATEX-FRAG to MathML and store it in MATHML-FILE.
19210 Use `org-latex-to-mathml-convert-command'. If the conversion is
19211 sucessful, return the portion between \"<math...> </math>\"
19212 elements otherwise return nil. When MATHML-FILE is specified,
19213 write the results in to that file. When invoked as an
19214 interactive command, prompt for LATEX-FRAG, with initial value
19215 set to the current active region and echo the results for user
19216 inspection."
19217 (interactive (list (let ((frag (when (org-region-active-p)
19218 (buffer-substring-no-properties
19219 (region-beginning) (region-end)))))
19220 (read-string "LaTeX Fragment: " frag nil frag))))
19221 (unless latex-frag (user-error "Invalid LaTeX fragment"))
19222 (let* ((tmp-in-file
19223 (let ((file (file-relative-name
19224 (make-temp-name (expand-file-name "ltxmathml-in")))))
19225 (write-region latex-frag nil file)
19226 file))
19227 (tmp-out-file (file-relative-name
19228 (make-temp-name (expand-file-name "ltxmathml-out"))))
19229 (cmd (format-spec
19230 org-latex-to-mathml-convert-command
19231 `((?j . ,(and org-latex-to-mathml-jar-file
19232 (shell-quote-argument
19233 (expand-file-name
19234 org-latex-to-mathml-jar-file))))
19235 (?I . ,(shell-quote-argument tmp-in-file))
19236 (?i . ,latex-frag)
19237 (?o . ,(shell-quote-argument tmp-out-file)))))
19238 mathml shell-command-output)
19239 (when (org-called-interactively-p 'any)
19240 (unless (org-format-latex-mathml-available-p)
19241 (user-error "LaTeX to MathML converter not configured")))
19242 (message "Running %s" cmd)
19243 (setq shell-command-output (shell-command-to-string cmd))
19244 (setq mathml
19245 (when (file-readable-p tmp-out-file)
19246 (with-current-buffer (find-file-noselect tmp-out-file t)
19247 (goto-char (point-min))
19248 (when (re-search-forward
19249 (concat
19250 (regexp-quote
19251 "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"")
19252 "[^>]*?>"
19253 "\\(.\\|\n\\)*"
19254 "</math>")
19255 nil t)
19256 (prog1 (match-string 0) (kill-buffer))))))
19257 (cond
19258 (mathml
19259 (setq mathml
19260 (concat "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" mathml))
19261 (when mathml-file
19262 (write-region mathml nil mathml-file))
19263 (when (org-called-interactively-p 'any)
19264 (message mathml)))
19265 ((message "LaTeX to MathML conversion failed")
19266 (message shell-command-output)))
19267 (delete-file tmp-in-file)
19268 (when (file-exists-p tmp-out-file)
19269 (delete-file tmp-out-file))
19270 mathml))
19272 (defun org-format-latex-as-mathml (latex-frag latex-frag-type
19273 prefix &optional dir)
19274 "Use `org-create-math-formula' but check local cache first."
19275 (let* ((absprefix (expand-file-name prefix dir))
19276 (print-length nil) (print-level nil)
19277 (formula-id (concat
19278 "formula-"
19279 (sha1
19280 (prin1-to-string
19281 (list latex-frag
19282 org-latex-to-mathml-convert-command)))))
19283 (formula-cache (format "%s-%s.mathml" absprefix formula-id))
19284 (formula-cache-dir (file-name-directory formula-cache)))
19286 (unless (file-directory-p formula-cache-dir)
19287 (make-directory formula-cache-dir t))
19289 (unless (file-exists-p formula-cache)
19290 (org-create-math-formula latex-frag formula-cache))
19292 (if (file-exists-p formula-cache)
19293 ;; Successful conversion. Return the link to MathML file.
19294 (org-add-props
19295 (format "[[file:%s]]" (file-relative-name formula-cache dir))
19296 (list 'org-latex-src (replace-regexp-in-string "\"" "" latex-frag)
19297 'org-latex-src-embed-type (if latex-frag-type
19298 'paragraph 'character)))
19299 ;; Failed conversion. Return the LaTeX fragment verbatim
19300 latex-frag)))
19302 (defun org-create-formula-image (string tofile options buffer &optional type)
19303 "Create an image from LaTeX source using dvipng or convert.
19304 This function calls either `org-create-formula-image-with-dvipng'
19305 or `org-create-formula-image-with-imagemagick' depending on the
19306 value of `org-latex-create-formula-image-program' or on the value
19307 of the optional TYPE variable.
19309 Note: ultimately these two function should be combined as they
19310 share a good deal of logic."
19311 (org-check-external-command
19312 "latex" "needed to convert LaTeX fragments to images")
19313 (funcall
19314 (cl-case (or type org-latex-create-formula-image-program)
19315 (dvipng
19316 (org-check-external-command
19317 "dvipng" "needed to convert LaTeX fragments to images")
19318 #'org-create-formula-image-with-dvipng)
19319 (imagemagick
19320 (org-check-external-command
19321 "convert" "you need to install imagemagick")
19322 #'org-create-formula-image-with-imagemagick)
19323 (t (error
19324 "Invalid value of `org-latex-create-formula-image-program'")))
19325 string tofile options buffer))
19327 (declare-function org-export-get-backend "ox" (name))
19328 (declare-function org-export--get-global-options "ox" (&optional backend))
19329 (declare-function org-export--get-inbuffer-options "ox" (&optional backend))
19330 (declare-function org-latex-guess-inputenc "ox-latex" (header))
19331 (declare-function org-latex-guess-babel-language "ox-latex" (header info))
19332 (defun org-create-formula--latex-header ()
19333 "Return LaTeX header appropriate for previewing a LaTeX snippet."
19334 (let ((info (org-combine-plists (org-export--get-global-options
19335 (org-export-get-backend 'latex))
19336 (org-export--get-inbuffer-options
19337 (org-export-get-backend 'latex)))))
19338 (org-latex-guess-babel-language
19339 (org-latex-guess-inputenc
19340 (org-splice-latex-header
19341 org-format-latex-header
19342 org-latex-default-packages-alist
19343 org-latex-packages-alist t
19344 (plist-get info :latex-header)))
19345 info)))
19347 (defun org--get-display-dpi ()
19348 "Get the DPI of the display.
19350 Assumes that the display has the same pixel width in the
19351 horizontal and vertical directions."
19352 (if (display-graphic-p)
19353 (round (/ (display-pixel-height)
19354 (/ (display-mm-height) 25.4)))
19355 (error "Attempt to calculate the dpi of a non-graphic display")))
19357 ;; This function borrows from Ganesh Swami's latex2png.el
19358 (defun org-create-formula-image-with-dvipng (string tofile options buffer)
19359 "This calls dvipng."
19360 (require 'ox-latex)
19361 (let* ((tmpdir (if (featurep 'xemacs)
19362 (temp-directory)
19363 temporary-file-directory))
19364 (texfilebase (make-temp-name
19365 (expand-file-name "orgtex" tmpdir)))
19366 (texfile (concat texfilebase ".tex"))
19367 (dvifile (concat texfilebase ".dvi"))
19368 (pngfile (concat texfilebase ".png"))
19369 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19370 ;; This assumes that the display has the same pixel width in
19371 ;; the horizontal and vertical directions
19372 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19373 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19374 "Black"))
19375 (bg (or (plist-get options (if buffer :background :html-background))
19376 "Transparent")))
19377 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground))
19378 (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg))))
19379 (if (eq bg 'default) (setq bg (org-dvipng-color :background))
19380 (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg))))
19381 (let ((latex-header (org-create-formula--latex-header)))
19382 (with-temp-file texfile
19383 (insert latex-header)
19384 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")))
19385 (let ((dir default-directory))
19386 (ignore-errors
19387 (cd tmpdir)
19388 (call-process "latex" nil nil nil texfile))
19389 (cd dir))
19390 (if (not (file-exists-p dvifile))
19391 (progn (message "Failed to create dvi file from %s" texfile) nil)
19392 (ignore-errors
19393 (if (featurep 'xemacs)
19394 (call-process "dvipng" nil nil nil
19395 "-fg" fg "-bg" bg
19396 "-T" "tight"
19397 "-o" pngfile
19398 dvifile)
19399 (call-process "dvipng" nil nil nil
19400 "-fg" fg "-bg" bg
19401 "-D" dpi
19402 ;;"-x" scale "-y" scale
19403 "-T" "tight"
19404 "-o" pngfile
19405 dvifile)))
19406 (if (not (file-exists-p pngfile))
19407 (if org-format-latex-signal-error
19408 (error "Failed to create png file from %s" texfile)
19409 (message "Failed to create png file from %s" texfile)
19410 nil)
19411 ;; Use the requested file name and clean up
19412 (copy-file pngfile tofile 'replace)
19413 (dolist (e '(".dvi" ".tex" ".aux" ".log" ".png" ".out"))
19414 (when (file-exists-p (concat texfilebase e))
19415 (delete-file (concat texfilebase e))))
19416 pngfile))))
19418 (declare-function org-latex-compile "ox-latex" (texfile &optional snippet))
19419 (defun org-create-formula-image-with-imagemagick (string tofile options buffer)
19420 "This calls convert, which is included into imagemagick."
19421 (require 'ox-latex)
19422 (let* ((tmpdir (if (featurep 'xemacs)
19423 (temp-directory)
19424 temporary-file-directory))
19425 (texfilebase (make-temp-name
19426 (expand-file-name "orgtex" tmpdir)))
19427 (texfile (concat texfilebase ".tex"))
19428 (pdffile (concat texfilebase ".pdf"))
19429 (pngfile (concat texfilebase ".png"))
19430 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
19431 (dpi (number-to-string (* scale (if buffer (org--get-display-dpi) 120))))
19432 (fg (or (plist-get options (if buffer :foreground :html-foreground))
19433 "black"))
19434 (bg (or (plist-get options (if buffer :background :html-background))
19435 "white")))
19436 (if (eq fg 'default) (setq fg (org-latex-color :foreground))
19437 (setq fg (org-latex-color-format fg)))
19438 (if (eq bg 'default) (setq bg (org-latex-color :background))
19439 (setq bg (org-latex-color-format
19440 (if (string= bg "Transparent") "white" bg))))
19441 (let ((latex-header (org-create-formula--latex-header)))
19442 (with-temp-file texfile
19443 (insert latex-header)
19444 (insert "\n\\begin{document}\n"
19445 "\\definecolor{fg}{rgb}{" fg "}\n"
19446 "\\definecolor{bg}{rgb}{" bg "}\n"
19447 "\n\\pagecolor{bg}\n"
19448 "\n{\\color{fg}\n"
19449 string
19450 "\n}\n"
19451 "\n\\end{document}\n")))
19452 (org-latex-compile texfile t)
19453 (if (not (file-exists-p pdffile))
19454 (progn (message "Failed to create pdf file from %s" texfile) nil)
19455 (ignore-errors
19456 (if (featurep 'xemacs)
19457 (call-process "convert" nil nil nil
19458 "-density" "96"
19459 "-trim"
19460 "-antialias"
19461 pdffile
19462 "-quality" "100"
19463 ;; "-sharpen" "0x1.0"
19464 pngfile)
19465 (call-process "convert" nil nil nil
19466 "-density" dpi
19467 "-trim"
19468 "-antialias"
19469 pdffile
19470 "-quality" "100"
19471 ;; "-sharpen" "0x1.0"
19472 pngfile)))
19473 (if (not (file-exists-p pngfile))
19474 (if org-format-latex-signal-error
19475 (error "Failed to create png file from %s" texfile)
19476 (message "Failed to create png file from %s" texfile)
19477 nil)
19478 ;; Use the requested file name and clean up
19479 (copy-file pngfile tofile 'replace)
19480 (dolist (e '(".pdf" ".tex" ".aux" ".log" ".png"))
19481 (when (file-exists-p (concat texfilebase e))
19482 (delete-file (concat texfilebase e))))
19483 pngfile))))
19485 (defun org-splice-latex-header (tpl def-pkg pkg snippets-p &optional extra)
19486 "Fill a LaTeX header template TPL.
19487 In the template, the following place holders will be recognized:
19489 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
19490 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
19491 [PACKAGES] \\usepackage statements for PKG
19492 [NO-PACKAGES] do not include PKG
19493 [EXTRA] the string EXTRA
19494 [NO-EXTRA] do not include EXTRA
19496 For backward compatibility, if both the positive and the negative place
19497 holder is missing, the positive one (without the \"NO-\") will be
19498 assumed to be present at the end of the template.
19499 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
19500 EXTRA is a string.
19501 SNIPPETS-P indicates if this is run to create snippet images for HTML."
19502 (let (rpl (end ""))
19503 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
19504 (setq rpl (if (or (match-end 1) (not def-pkg))
19505 "" (org-latex-packages-to-string def-pkg snippets-p t))
19506 tpl (replace-match rpl t t tpl))
19507 (when def-pkg (setq end (org-latex-packages-to-string def-pkg snippets-p))))
19509 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
19510 (setq rpl (if (or (match-end 1) (not pkg))
19511 "" (org-latex-packages-to-string pkg snippets-p t))
19512 tpl (replace-match rpl t t tpl))
19513 (when pkg (setq end
19514 (concat end "\n"
19515 (org-latex-packages-to-string pkg snippets-p)))))
19517 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
19518 (setq rpl (if (or (match-end 1) (not extra))
19519 "" (concat extra "\n"))
19520 tpl (replace-match rpl t t tpl))
19521 (when (and extra (string-match "\\S-" extra))
19522 (setq end (concat end "\n" extra))))
19524 (if (string-match "\\S-" end)
19525 (concat tpl "\n" end)
19526 tpl)))
19528 (defun org-latex-packages-to-string (pkg &optional snippets-p newline)
19529 "Turn an alist of packages into a string with the \\usepackage macros."
19530 (setq pkg (mapconcat (lambda(p)
19531 (cond
19532 ((stringp p) p)
19533 ((and snippets-p (>= (length p) 3) (not (nth 2 p)))
19534 (format "%% Package %s omitted" (cadr p)))
19535 ((equal "" (car p))
19536 (format "\\usepackage{%s}" (cadr p)))
19538 (format "\\usepackage[%s]{%s}"
19539 (car p) (cadr p)))))
19541 "\n"))
19542 (if newline (concat pkg "\n") pkg))
19544 (defun org-dvipng-color (attr)
19545 "Return a RGB color specification for dvipng."
19546 (apply 'format "rgb %s %s %s"
19547 (mapcar 'org-normalize-color
19548 (if (featurep 'xemacs)
19549 (color-rgb-components
19550 (face-property 'default
19551 (cond ((eq attr :foreground) 'foreground)
19552 ((eq attr :background) 'background))))
19553 (color-values (face-attribute 'default attr nil))))))
19555 (defun org-dvipng-color-format (color-name)
19556 "Convert COLOR-NAME to a RGB color value for dvipng."
19557 (apply 'format "rgb %s %s %s"
19558 (mapcar 'org-normalize-color
19559 (color-values color-name))))
19561 (defun org-latex-color (attr)
19562 "Return a RGB color for the LaTeX color package."
19563 (apply 'format "%s,%s,%s"
19564 (mapcar 'org-normalize-color
19565 (if (featurep 'xemacs)
19566 (color-rgb-components
19567 (face-property 'default
19568 (cond ((eq attr :foreground) 'foreground)
19569 ((eq attr :background) 'background))))
19570 (color-values (face-attribute 'default attr nil))))))
19572 (defun org-latex-color-format (color-name)
19573 "Convert COLOR-NAME to a RGB color value."
19574 (apply 'format "%s,%s,%s"
19575 (mapcar 'org-normalize-color
19576 (color-values color-name))))
19578 (defun org-normalize-color (value)
19579 "Return string to be used as color value for an RGB component."
19580 (format "%g" (/ value 65535.0)))
19584 ;; Image display
19586 (defvar-local org-inline-image-overlays nil)
19588 (defun org-toggle-inline-images (&optional include-linked)
19589 "Toggle the display of inline images.
19590 INCLUDE-LINKED is passed to `org-display-inline-images'."
19591 (interactive "P")
19592 (if org-inline-image-overlays
19593 (progn
19594 (org-remove-inline-images)
19595 (when (org-called-interactively-p 'interactive)
19596 (message "Inline image display turned off")))
19597 (org-display-inline-images include-linked)
19598 (when (org-called-interactively-p 'interactive)
19599 (message (if org-inline-image-overlays
19600 (format "%d images displayed inline"
19601 (length org-inline-image-overlays))
19602 "No images to display inline")))))
19604 (defun org-redisplay-inline-images ()
19605 "Refresh the display of inline images."
19606 (interactive)
19607 (if (not org-inline-image-overlays)
19608 (org-toggle-inline-images)
19609 (org-toggle-inline-images)
19610 (org-toggle-inline-images)))
19612 (defun org-display-inline-images (&optional include-linked refresh beg end)
19613 "Display inline images.
19615 An inline image is a link which follows either of these
19616 conventions:
19618 1. Its path is a file with an extension matching return value
19619 from `image-file-name-regexp' and it has no contents.
19621 2. Its description consists in a single link of the previous
19622 type.
19624 When optional argument INCLUDE-LINKED is non-nil, also links with
19625 a text description part will be inlined. This can be nice for
19626 a quick look at those images, but it does not reflect what
19627 exported files will look like.
19629 When optional argument REFRESH is non-nil, refresh existing
19630 images between BEG and END. This will create new image displays
19631 only if necessary. BEG and END default to the buffer
19632 boundaries."
19633 (interactive "P")
19634 (when (display-graphic-p)
19635 (unless refresh
19636 (org-remove-inline-images)
19637 (when (fboundp 'clear-image-cache) (clear-image-cache)))
19638 (org-with-wide-buffer
19639 (goto-char (or beg (point-min)))
19640 (let ((case-fold-search t)
19641 (file-extension-re (image-file-name-regexp)))
19642 (while (re-search-forward "[][]\\[\\(?:file\\|[./~]\\)" end t)
19643 (let ((link (save-match-data (org-element-context))))
19644 ;; Check if we're at an inline image.
19645 (when (and (equal (org-element-property :type link) "file")
19646 (or include-linked
19647 (not (org-element-property :contents-begin link)))
19648 (let ((parent (org-element-property :parent link)))
19649 (or (not (eq (org-element-type parent) 'link))
19650 (not (cdr (org-element-contents parent)))))
19651 (org-string-match-p file-extension-re
19652 (org-element-property :path link)))
19653 (let ((file (expand-file-name
19654 (org-link-unescape
19655 (org-element-property :path link)))))
19656 (when (file-exists-p file)
19657 (let ((width
19658 ;; Apply `org-image-actual-width' specifications.
19659 (cond
19660 ((not (image-type-available-p 'imagemagick)) nil)
19661 ((eq org-image-actual-width t) nil)
19662 ((listp org-image-actual-width)
19664 ;; First try to find a width among
19665 ;; attributes associated to the paragraph
19666 ;; containing link.
19667 (let ((paragraph
19668 (let ((e link))
19669 (while (and (setq e (org-element-property
19670 :parent e))
19671 (not (eq (org-element-type e)
19672 'paragraph))))
19673 e)))
19674 (when paragraph
19675 (save-excursion
19676 (goto-char (org-element-property :begin paragraph))
19677 (when
19678 (re-search-forward
19679 "^[ \t]*#\\+attr_.*?: +.*?:width +\\(\\S-+\\)"
19680 (org-element-property
19681 :post-affiliated paragraph)
19683 (string-to-number (match-string 1))))))
19684 ;; Otherwise, fall-back to provided number.
19685 (car org-image-actual-width)))
19686 ((numberp org-image-actual-width)
19687 org-image-actual-width)))
19688 (old (get-char-property-and-overlay
19689 (org-element-property :begin link)
19690 'org-image-overlay)))
19691 (if (and (car-safe old) refresh)
19692 (image-refresh (overlay-get (cdr old) 'display))
19693 (let ((image (create-image file
19694 (and width 'imagemagick)
19696 :width width)))
19697 (when image
19698 (let* ((link
19699 ;; If inline image is the description
19700 ;; of another link, be sure to
19701 ;; consider the latter as the one to
19702 ;; apply the overlay on.
19703 (let ((parent
19704 (org-element-property :parent link)))
19705 (if (eq (org-element-type parent) 'link)
19706 parent
19707 link)))
19708 (ov (make-overlay
19709 (org-element-property :begin link)
19710 (progn
19711 (goto-char
19712 (org-element-property :end link))
19713 (skip-chars-backward " \t")
19714 (point)))))
19715 (overlay-put ov 'display image)
19716 (overlay-put ov 'face 'default)
19717 (overlay-put ov 'org-image-overlay t)
19718 (overlay-put
19719 ov 'modification-hooks
19720 (list 'org-display-inline-remove-overlay))
19721 (push ov org-inline-image-overlays)))))))))))))))
19723 (define-obsolete-function-alias
19724 'org-display-inline-modification-hook 'org-display-inline-remove-overlay "24.3")
19726 (defun org-display-inline-remove-overlay (ov after _beg _end &optional _len)
19727 "Remove inline-display overlay if a corresponding region is modified."
19728 (let ((inhibit-modification-hooks t))
19729 (when (and ov after)
19730 (delete ov org-inline-image-overlays)
19731 (delete-overlay ov))))
19733 (defun org-remove-inline-images ()
19734 "Remove inline display of images."
19735 (interactive)
19736 (mapc #'delete-overlay org-inline-image-overlays)
19737 (setq org-inline-image-overlays nil))
19739 ;;;; Key bindings
19741 ;; Outline functions from `outline-mode-prefix-map'
19742 ;; that can be remapped in Org:
19743 (define-key org-mode-map [remap outline-mark-subtree] 'org-mark-subtree)
19744 (define-key org-mode-map [remap outline-show-subtree] 'org-show-subtree)
19745 (define-key org-mode-map [remap outline-forward-same-level]
19746 'org-forward-heading-same-level)
19747 (define-key org-mode-map [remap outline-backward-same-level]
19748 'org-backward-heading-same-level)
19749 (define-key org-mode-map [remap outline-show-branches]
19750 'org-kill-note-or-show-branches)
19751 (define-key org-mode-map [remap outline-promote] 'org-promote-subtree)
19752 (define-key org-mode-map [remap outline-demote] 'org-demote-subtree)
19753 (define-key org-mode-map [remap outline-insert-heading] 'org-ctrl-c-ret)
19754 (define-key org-mode-map [remap outline-next-visible-heading]
19755 'org-next-visible-heading)
19756 (define-key org-mode-map [remap outline-previous-visible-heading]
19757 'org-previous-visible-heading)
19758 (define-key org-mode-map [remap show-children] 'org-show-children)
19760 ;; Outline functions from `outline-mode-prefix-map' that can not
19761 ;; be remapped in Org:
19763 ;; - the column "key binding" shows whether the Outline function is still
19764 ;; available in Org mode on the same key that it has been bound to in
19765 ;; Outline mode:
19766 ;; - "overridden": key used for a different functionality in Org mode
19767 ;; - else: key still bound to the same Outline function in Org mode
19769 ;; | Outline function | key binding | Org replacement |
19770 ;; |------------------------------------+-------------+--------------------------|
19771 ;; | `outline-up-heading' | `C-c C-u' | still same function |
19772 ;; | `outline-move-subtree-up' | overridden | better: org-shiftup |
19773 ;; | `outline-move-subtree-down' | overridden | better: org-shiftdown |
19774 ;; | `show-entry' | overridden | no replacement |
19775 ;; | `show-branches' | `C-c C-k' | still same function |
19776 ;; | `show-subtree' | overridden | visibility cycling |
19777 ;; | `show-all' | overridden | no replacement |
19778 ;; | `hide-subtree' | overridden | visibility cycling |
19779 ;; | `hide-body' | overridden | no replacement |
19780 ;; | `hide-entry' | overridden | visibility cycling |
19781 ;; | `hide-leaves' | overridden | no replacement |
19782 ;; | `hide-sublevels' | overridden | no replacement |
19783 ;; | `hide-other' | overridden | no replacement |
19785 ;; Make `C-c C-x' a prefix key
19786 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
19788 ;; TAB key with modifiers
19789 (org-defkey org-mode-map "\C-i" 'org-cycle)
19790 (org-defkey org-mode-map [(tab)] 'org-cycle)
19791 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
19792 (org-defkey org-mode-map "\M-\t" #'pcomplete)
19793 ;; The following line is necessary under Suse GNU/Linux
19794 (unless (featurep 'xemacs)
19795 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
19796 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
19797 (define-key org-mode-map [backtab] 'org-shifttab)
19799 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
19800 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
19801 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
19803 ;; Cursor keys with modifiers
19804 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
19805 (org-defkey org-mode-map [(meta right)] 'org-metaright)
19806 (org-defkey org-mode-map [(meta up)] 'org-metaup)
19807 (org-defkey org-mode-map [(meta down)] 'org-metadown)
19809 (org-defkey org-mode-map [(control meta shift right)] 'org-increase-number-at-point)
19810 (org-defkey org-mode-map [(control meta shift left)] 'org-decrease-number-at-point)
19811 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
19812 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
19813 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
19814 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
19816 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
19817 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
19818 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
19819 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
19821 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
19822 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
19823 (org-defkey org-mode-map [(control shift up)] 'org-shiftcontrolup)
19824 (org-defkey org-mode-map [(control shift down)] 'org-shiftcontroldown)
19826 ;; Babel keys
19827 (define-key org-mode-map org-babel-key-prefix org-babel-map)
19828 (dolist (pair org-babel-key-bindings)
19829 (define-key org-babel-map (car pair) (cdr pair)))
19831 ;;; Extra keys for tty access.
19832 ;; We only set them when really needed because otherwise the
19833 ;; menus don't show the simple keys
19835 (when (or org-use-extra-keys
19836 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
19837 (not window-system))
19838 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
19839 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
19840 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
19841 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
19842 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
19843 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
19844 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
19845 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
19846 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
19847 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
19848 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
19849 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
19850 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
19851 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
19852 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
19853 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
19854 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
19855 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
19856 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
19857 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
19858 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
19859 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
19860 (org-defkey org-mode-map [?\e (tab)] #'pcomplete)
19861 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
19862 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
19863 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
19864 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
19865 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
19867 ;; All the other keys
19869 (org-defkey org-mode-map "\C-c\C-a" 'outline-show-all) ; in case allout messed up.
19870 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
19871 (if (boundp 'narrow-map)
19872 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
19873 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
19874 (if (boundp 'narrow-map)
19875 (org-defkey narrow-map "b" 'org-narrow-to-block)
19876 (org-defkey org-mode-map "\C-xnb" 'org-narrow-to-block))
19877 (if (boundp 'narrow-map)
19878 (org-defkey narrow-map "e" 'org-narrow-to-element)
19879 (org-defkey org-mode-map "\C-xne" 'org-narrow-to-element))
19880 (org-defkey org-mode-map "\C-\M-t" 'org-transpose-element)
19881 (org-defkey org-mode-map "\M-}" 'org-forward-element)
19882 (org-defkey org-mode-map "\M-{" 'org-backward-element)
19883 (org-defkey org-mode-map "\C-c\C-^" 'org-up-element)
19884 (org-defkey org-mode-map "\C-c\C-_" 'org-down-element)
19885 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-heading-same-level)
19886 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-heading-same-level)
19887 (org-defkey org-mode-map "\C-c\M-f" 'org-next-block)
19888 (org-defkey org-mode-map "\C-c\M-b" 'org-previous-block)
19889 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
19890 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-archive-subtree)
19891 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
19892 (org-defkey org-mode-map "\C-c\C-xd" 'org-insert-drawer)
19893 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
19894 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
19895 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
19896 (org-defkey org-mode-map "\C-c\C-xq" 'org-toggle-tags-groups)
19897 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
19898 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
19899 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
19900 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
19901 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
19902 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
19903 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
19904 (org-defkey org-mode-map "\C-c\M-w" 'org-copy)
19905 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
19906 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
19907 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
19908 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
19909 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
19910 (org-defkey org-mode-map "\C-c\C-xv" 'org-copy-visible)
19911 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
19912 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
19913 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
19914 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
19915 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
19916 (org-defkey org-mode-map "\C-c\M-l" 'org-insert-last-stored-link)
19917 (org-defkey org-mode-map "\C-c\C-\M-l" 'org-insert-all-links)
19918 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
19919 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
19920 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
19921 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
19922 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
19923 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
19924 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
19925 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
19926 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
19927 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
19928 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
19929 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
19930 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
19931 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
19932 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
19933 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
19934 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
19935 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
19936 (org-defkey org-mode-map "\C-c^" 'org-sort)
19937 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
19938 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
19939 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
19940 (org-defkey org-mode-map [remap open-line] 'org-open-line)
19941 (org-defkey org-mode-map [remap comment-dwim] 'org-comment-dwim)
19942 (org-defkey org-mode-map [remap forward-paragraph] 'org-forward-paragraph)
19943 (org-defkey org-mode-map [remap backward-paragraph] 'org-backward-paragraph)
19944 (org-defkey org-mode-map "\M-^" 'org-delete-indentation)
19945 (org-defkey org-mode-map "\C-m" 'org-return)
19946 (org-defkey org-mode-map "\C-j" 'org-return-indent)
19947 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
19948 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
19949 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
19950 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
19951 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
19952 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
19953 (org-defkey org-mode-map "\C-c\"a" 'orgtbl-ascii-plot)
19954 (org-defkey org-mode-map "\C-c\"g" 'org-plot/gnuplot)
19955 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
19956 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
19957 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
19958 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
19959 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
19960 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
19961 (org-defkey org-mode-map "\C-c\C-e" 'org-export-dispatch)
19962 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width)
19963 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
19964 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
19965 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
19966 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
19967 (org-defkey org-mode-map "\C-c@" 'org-mark-subtree)
19968 (org-defkey org-mode-map "\M-h" 'org-mark-element)
19969 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
19970 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
19972 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
19973 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
19974 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
19976 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
19977 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
19978 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-in-last)
19979 (org-defkey org-mode-map "\C-c\C-x\C-z" 'org-resolve-clocks)
19980 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
19981 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
19982 (org-defkey org-mode-map "\C-c\C-x\C-q" 'org-clock-cancel)
19983 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
19984 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
19985 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
19986 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-toggle-latex-fragment)
19987 (org-defkey org-mode-map "\C-c\C-x\C-v" 'org-toggle-inline-images)
19988 (org-defkey org-mode-map "\C-c\C-x\C-\M-v" 'org-redisplay-inline-images)
19989 (org-defkey org-mode-map "\C-c\C-x\\" 'org-toggle-pretty-entities)
19990 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
19991 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
19992 (org-defkey org-mode-map "\C-c\C-xP" 'org-set-property-and-value)
19993 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
19994 (org-defkey org-mode-map "\C-c\C-xE" 'org-inc-effort)
19995 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
19996 (org-defkey org-mode-map "\C-c\C-xi" 'org-columns-insert-dblock)
19997 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
19999 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
20000 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
20001 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
20002 (org-defkey org-mode-map "\C-c\C-x_" 'org-timer-stop)
20003 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
20005 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
20007 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
20009 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
20010 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
20012 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
20015 (when (featurep 'xemacs)
20016 (org-defkey org-mode-map 'button3 'popup-mode-menu))
20019 (defconst org-speed-commands-default
20021 ("Outline Navigation")
20022 ("n" . (org-speed-move-safe 'org-next-visible-heading))
20023 ("p" . (org-speed-move-safe 'org-previous-visible-heading))
20024 ("f" . (org-speed-move-safe 'org-forward-heading-same-level))
20025 ("b" . (org-speed-move-safe 'org-backward-heading-same-level))
20026 ("F" . org-next-block)
20027 ("B" . org-previous-block)
20028 ("u" . (org-speed-move-safe 'outline-up-heading))
20029 ("j" . org-goto)
20030 ("g" . (org-refile t))
20031 ("Outline Visibility")
20032 ("c" . org-cycle)
20033 ("C" . org-shifttab)
20034 (" " . org-display-outline-path)
20035 ("s" . org-narrow-to-subtree)
20036 ("=" . org-columns)
20037 ("Outline Structure Editing")
20038 ("U" . org-metaup)
20039 ("D" . org-metadown)
20040 ("r" . org-metaright)
20041 ("l" . org-metaleft)
20042 ("R" . org-shiftmetaright)
20043 ("L" . org-shiftmetaleft)
20044 ("i" . (progn (forward-char 1) (call-interactively
20045 'org-insert-heading-respect-content)))
20046 ("^" . org-sort)
20047 ("w" . org-refile)
20048 ("a" . org-archive-subtree-default-with-confirmation)
20049 ("@" . org-mark-subtree)
20050 ("#" . org-toggle-comment)
20051 ("Clock Commands")
20052 ("I" . org-clock-in)
20053 ("O" . org-clock-out)
20054 ("Meta Data Editing")
20055 ("t" . org-todo)
20056 ("," . (org-priority))
20057 ("0" . (org-priority ?\ ))
20058 ("1" . (org-priority ?A))
20059 ("2" . (org-priority ?B))
20060 ("3" . (org-priority ?C))
20061 (":" . org-set-tags-command)
20062 ("e" . org-set-effort)
20063 ("E" . org-inc-effort)
20064 ("W" . (lambda(m) (interactive "sMinutes before warning: ")
20065 (org-entry-put (point) "APPT_WARNTIME" m)))
20066 ("Agenda Views etc")
20067 ("v" . org-agenda)
20068 ("/" . org-sparse-tree)
20069 ("Misc")
20070 ("o" . org-open-at-point)
20071 ("?" . org-speed-command-help)
20072 ("<" . (org-agenda-set-restriction-lock 'subtree))
20073 (">" . (org-agenda-remove-restriction-lock))
20075 "The default speed commands.")
20077 (defun org-print-speed-command (e)
20078 (if (> (length (car e)) 1)
20079 (progn
20080 (princ "\n")
20081 (princ (car e))
20082 (princ "\n")
20083 (princ (make-string (length (car e)) ?-))
20084 (princ "\n"))
20085 (princ (car e))
20086 (princ " ")
20087 (if (symbolp (cdr e))
20088 (princ (symbol-name (cdr e)))
20089 (prin1 (cdr e)))
20090 (princ "\n")))
20092 (defun org-speed-command-help ()
20093 "Show the available speed commands."
20094 (interactive)
20095 (if (not org-use-speed-commands)
20096 (user-error "Speed commands are not activated, customize `org-use-speed-commands'")
20097 (with-output-to-temp-buffer "*Help*"
20098 (princ "User-defined Speed commands\n===========================\n")
20099 (mapc #'org-print-speed-command org-speed-commands-user)
20100 (princ "\n")
20101 (princ "Built-in Speed commands\n=======================\n")
20102 (mapc #'org-print-speed-command org-speed-commands-default))
20103 (with-current-buffer "*Help*"
20104 (setq truncate-lines t))))
20106 (defun org-speed-move-safe (cmd)
20107 "Execute CMD, but make sure that the cursor always ends up in a headline.
20108 If not, return to the original position and throw an error."
20109 (interactive)
20110 (let ((pos (point)))
20111 (call-interactively cmd)
20112 (unless (and (bolp) (org-at-heading-p))
20113 (goto-char pos)
20114 (error "Boundary reached while executing %s" cmd))))
20116 (defvar org-self-insert-command-undo-counter 0)
20118 (defvar org-table-auto-blank-field) ; defined in org-table.el
20119 (defvar org-speed-command nil)
20121 (define-obsolete-function-alias
20122 'org-speed-command-default-hook 'org-speed-command-activate "24.3")
20124 (defun org-speed-command-activate (keys)
20125 "Hook for activating single-letter speed commands.
20126 `org-speed-commands-default' specifies a minimal command set.
20127 Use `org-speed-commands-user' for further customization."
20128 (when (or (and (bolp) (looking-at org-outline-regexp))
20129 (and (functionp org-use-speed-commands)
20130 (funcall org-use-speed-commands)))
20131 (cdr (assoc keys (append org-speed-commands-user
20132 org-speed-commands-default)))))
20134 (define-obsolete-function-alias
20135 'org-babel-speed-command-hook 'org-babel-speed-command-activate "24.3")
20137 (defun org-babel-speed-command-activate (keys)
20138 "Hook for activating single-letter code block commands."
20139 (when (and (bolp) (looking-at org-babel-src-block-regexp))
20140 (cdr (assoc keys org-babel-key-bindings))))
20142 (defcustom org-speed-command-hook
20143 '(org-speed-command-default-hook org-babel-speed-command-hook)
20144 "Hook for activating speed commands at strategic locations.
20145 Hook functions are called in sequence until a valid handler is
20146 found.
20148 Each hook takes a single argument, a user-pressed command key
20149 which is also a `self-insert-command' from the global map.
20151 Within the hook, examine the cursor position and the command key
20152 and return nil or a valid handler as appropriate. Handler could
20153 be one of an interactive command, a function, or a form.
20155 Set `org-use-speed-commands' to non-nil value to enable this
20156 hook. The default setting is `org-speed-command-activate'."
20157 :group 'org-structure
20158 :version "24.1"
20159 :type 'hook)
20161 (defun org-self-insert-command (N)
20162 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
20163 If the cursor is in a table looking at whitespace, the whitespace is
20164 overwritten, and the table is not marked as requiring realignment."
20165 (interactive "p")
20166 (org-check-before-invisible-edit 'insert)
20167 (cond
20168 ((and org-use-speed-commands
20169 (let ((kv (this-command-keys-vector)))
20170 (setq org-speed-command
20171 (run-hook-with-args-until-success
20172 'org-speed-command-hook
20173 (make-string 1 (aref kv (1- (length kv))))))))
20174 (cond
20175 ((commandp org-speed-command)
20176 (setq this-command org-speed-command)
20177 (call-interactively org-speed-command))
20178 ((functionp org-speed-command)
20179 (funcall org-speed-command))
20180 ((and org-speed-command (listp org-speed-command))
20181 (eval org-speed-command))
20182 (t (let (org-use-speed-commands)
20183 (call-interactively 'org-self-insert-command)))))
20184 ((and
20185 (org-at-table-p)
20186 (progn
20187 ;; Check if we blank the field, and if that triggers align.
20188 (and (featurep 'org-table) org-table-auto-blank-field
20189 (memq last-command
20190 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
20191 (if (or (eq (char-after) ?\s) (looking-at "[^|\n]* |"))
20192 ;; Got extra space, this field does not determine
20193 ;; column width.
20194 (let (org-table-may-need-update) (org-table-blank-field))
20195 ;; No extra space, this field may determine column
20196 ;; width.
20197 (org-table-blank-field)))
20199 (eq N 1)
20200 (looking-at "[^|\n]* \\( \\)|"))
20201 ;; There is room for insertion without re-aligning the table.
20202 (delete-region (match-beginning 1) (match-end 1))
20203 (self-insert-command N))
20205 (setq org-table-may-need-update t)
20206 (self-insert-command N)
20207 (org-fix-tags-on-the-fly)
20208 (when org-self-insert-cluster-for-undo
20209 (if (not (eq last-command 'org-self-insert-command))
20210 (setq org-self-insert-command-undo-counter 1)
20211 (if (>= org-self-insert-command-undo-counter 20)
20212 (setq org-self-insert-command-undo-counter 1)
20213 (and (> org-self-insert-command-undo-counter 0)
20214 buffer-undo-list (listp buffer-undo-list)
20215 (not (cadr buffer-undo-list)) ; remove nil entry
20216 (setcdr buffer-undo-list (cddr buffer-undo-list)))
20217 (setq org-self-insert-command-undo-counter
20218 (1+ org-self-insert-command-undo-counter))))))))
20220 (defun org-check-before-invisible-edit (kind)
20221 "Check is editing if kind KIND would be dangerous with invisible text around.
20222 The detailed reaction depends on the user option `org-catch-invisible-edits'."
20223 ;; First, try to get out of here as quickly as possible, to reduce overhead
20224 (when (and org-catch-invisible-edits
20225 (or (not (boundp 'visible-mode)) (not visible-mode))
20226 (or (get-char-property (point) 'invisible)
20227 (get-char-property (max (point-min) (1- (point))) 'invisible)))
20228 ;; OK, we need to take a closer look
20229 (let* ((invisible-at-point (get-char-property (point) 'invisible))
20230 (invisible-before-point (unless (bobp) (get-char-property
20231 (1- (point)) 'invisible)))
20232 (border-and-ok-direction
20234 ;; Check if we are acting predictably before invisible text
20235 (and invisible-at-point (not invisible-before-point)
20236 (memq kind '(insert delete-backward)))
20237 ;; Check if we are acting predictably after invisible text
20238 ;; This works not well, and I have turned it off. It seems
20239 ;; better to always show and stop after invisible text.
20240 ;; (and (not invisible-at-point) invisible-before-point
20241 ;; (memq kind '(insert delete)))
20243 (when (or (memq invisible-at-point '(outline org-hide-block t))
20244 (memq invisible-before-point '(outline org-hide-block t)))
20245 (when (eq org-catch-invisible-edits 'error)
20246 (user-error "Editing in invisible areas is prohibited, make them visible first"))
20247 (if (and org-custom-properties-overlays
20248 (y-or-n-p "Display invisible properties in this buffer? "))
20249 (org-toggle-custom-properties-visibility)
20250 ;; Make the area visible
20251 (save-excursion
20252 (when invisible-before-point
20253 (goto-char (previous-single-char-property-change
20254 (point) 'invisible)))
20255 (outline-show-subtree))
20256 (cond
20257 ((eq org-catch-invisible-edits 'show)
20258 ;; That's it, we do the edit after showing
20259 (message
20260 "Unfolding invisible region around point before editing")
20261 (sit-for 1))
20262 ((and (eq org-catch-invisible-edits 'smart)
20263 border-and-ok-direction)
20264 (message "Unfolding invisible region around point before editing"))
20266 ;; Don't do the edit, make the user repeat it in full visibility
20267 (user-error "Edit in invisible region aborted, repeat to confirm with text visible"))))))))
20269 (defun org-fix-tags-on-the-fly ()
20270 (when (and (equal (char-after (point-at-bol)) ?*)
20271 (org-at-heading-p))
20272 (org-align-tags-here org-tags-column)))
20274 (defun org-delete-backward-char (N)
20275 "Like `delete-backward-char', insert whitespace at field end in tables.
20276 When deleting backwards, in tables this function will insert whitespace in
20277 front of the next \"|\" separator, to keep the table aligned. The table will
20278 still be marked for re-alignment if the field did fill the entire column,
20279 because, in this case the deletion might narrow the column."
20280 (interactive "p")
20281 (save-match-data
20282 (org-check-before-invisible-edit 'delete-backward)
20283 (if (and (org-at-table-p)
20284 (eq N 1)
20285 (string-match "|" (buffer-substring (point-at-bol) (point)))
20286 (looking-at ".*?|"))
20287 (let ((pos (point))
20288 (noalign (looking-at "[^|\n\r]* |"))
20289 (c org-table-may-need-update))
20290 (backward-delete-char N)
20291 (unless overwrite-mode
20292 (skip-chars-forward "^|")
20293 (insert " ")
20294 (goto-char (1- pos)))
20295 ;; noalign: if there were two spaces at the end, this field
20296 ;; does not determine the width of the column.
20297 (when noalign (setq org-table-may-need-update c)))
20298 (backward-delete-char N)
20299 (org-fix-tags-on-the-fly))))
20301 (defun org-delete-char (N)
20302 "Like `delete-char', but insert whitespace at field end in tables.
20303 When deleting characters, in tables this function will insert whitespace in
20304 front of the next \"|\" separator, to keep the table aligned. The table will
20305 still be marked for re-alignment if the field did fill the entire column,
20306 because, in this case the deletion might narrow the column."
20307 (interactive "p")
20308 (save-match-data
20309 (org-check-before-invisible-edit 'delete)
20310 (if (and (org-at-table-p)
20311 (not (bolp))
20312 (not (= (char-after) ?|))
20313 (eq N 1))
20314 (if (looking-at ".*?|")
20315 (let ((pos (point))
20316 (noalign (looking-at "[^|\n\r]* |"))
20317 (c org-table-may-need-update))
20318 (replace-match
20319 (concat (substring (match-string 0) 1 -1) " |") nil t)
20320 (goto-char pos)
20321 ;; noalign: if there were two spaces at the end, this field
20322 ;; does not determine the width of the column.
20323 (when noalign (setq org-table-may-need-update c)))
20324 (delete-char N))
20325 (delete-char N)
20326 (org-fix-tags-on-the-fly))))
20328 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
20329 (put 'org-self-insert-command 'delete-selection
20330 (lambda ()
20331 (not (run-hook-with-args-until-success
20332 'self-insert-uses-region-functions))))
20333 (put 'orgtbl-self-insert-command 'delete-selection
20334 (lambda ()
20335 (not (run-hook-with-args-until-success
20336 'self-insert-uses-region-functions))))
20337 (put 'org-delete-char 'delete-selection 'supersede)
20338 (put 'org-delete-backward-char 'delete-selection 'supersede)
20339 (put 'org-yank 'delete-selection 'yank)
20341 ;; Make `flyspell-mode' delay after some commands
20342 (put 'org-self-insert-command 'flyspell-delayed t)
20343 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
20344 (put 'org-delete-char 'flyspell-delayed t)
20345 (put 'org-delete-backward-char 'flyspell-delayed t)
20347 ;; Make pabbrev-mode expand after org-mode commands
20348 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
20349 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
20351 (defun org-remap (map &rest commands)
20352 "In MAP, remap the functions given in COMMANDS.
20353 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
20354 (let (new old)
20355 (while commands
20356 (setq old (pop commands) new (pop commands))
20357 (if (fboundp 'command-remapping)
20358 (org-defkey map (vector 'remap old) new)
20359 (substitute-key-definition old new map global-map)))))
20361 (defun org-transpose-words ()
20362 "Transpose words for Org.
20363 This uses the `org-mode-transpose-word-syntax-table' syntax
20364 table, which interprets characters in `org-emphasis-alist' as
20365 word constituents."
20366 (interactive)
20367 (with-syntax-table org-mode-transpose-word-syntax-table
20368 (call-interactively 'transpose-words)))
20369 (org-remap org-mode-map 'transpose-words 'org-transpose-words)
20371 (when (eq org-enable-table-editor 'optimized)
20372 ;; If the user wants maximum table support, we need to hijack
20373 ;; some standard editing functions
20374 (org-remap org-mode-map
20375 'self-insert-command 'org-self-insert-command
20376 'delete-char 'org-delete-char
20377 'delete-backward-char 'org-delete-backward-char)
20378 (org-defkey org-mode-map "|" 'org-force-self-insert))
20380 (defvar org-ctrl-c-ctrl-c-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 before any other test, while `org-ctrl-c-ctrl-c-final-hook' is
20386 run after the last 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-ctrl-c-ctrl-c-final-hook nil
20394 "Hook for functions attaching themselves to `C-c C-c'.
20396 This can be used to add additional functionality to the C-c C-c
20397 key which executes context-dependent commands. This hook is run
20398 after any other test, while `org-ctrl-c-ctrl-c-hook' is run
20399 before the first test.
20401 Each function will be called with no arguments. The function
20402 must check if the context is appropriate for it to act. If yes,
20403 it should do its thing and then return a non-nil value. If the
20404 context is wrong, just do nothing and return nil.")
20406 (defvar org-tab-first-hook nil
20407 "Hook for functions to attach themselves to TAB.
20408 See `org-ctrl-c-ctrl-c-hook' for more information.
20409 This hook runs as the first action when TAB is pressed, even before
20410 `org-cycle' messes around with the `outline-regexp' to cater for
20411 inline tasks and plain list item folding.
20412 If any function in this hook returns t, any other actions that
20413 would have been caused by TAB (such as table field motion or visibility
20414 cycling) will not occur.")
20416 (defvar org-tab-after-check-for-table-hook nil
20417 "Hook for functions to attach themselves to TAB.
20418 See `org-ctrl-c-ctrl-c-hook' for more information.
20419 This hook runs after it has been established that the cursor is not in a
20420 table, but before checking if the cursor is in a headline or if global cycling
20421 should be done.
20422 If any function in this hook returns t, not other actions like visibility
20423 cycling will be done.")
20425 (defvar org-tab-after-check-for-cycling-hook nil
20426 "Hook for functions to attach themselves to TAB.
20427 See `org-ctrl-c-ctrl-c-hook' for more information.
20428 This hook runs after it has been established that not table field motion and
20429 not visibility should be done because of current context. This is probably
20430 the place where a package like yasnippets can hook in.")
20432 (defvar org-tab-before-tab-emulation-hook nil
20433 "Hook for functions to attach themselves to TAB.
20434 See `org-ctrl-c-ctrl-c-hook' for more information.
20435 This hook runs after every other options for TAB have been exhausted, but
20436 before indentation and \t insertion takes place.")
20438 (defvar org-metaleft-hook nil
20439 "Hook for functions attaching themselves to `M-left'.
20440 See `org-ctrl-c-ctrl-c-hook' for more information.")
20441 (defvar org-metaright-hook nil
20442 "Hook for functions attaching themselves to `M-right'.
20443 See `org-ctrl-c-ctrl-c-hook' for more information.")
20444 (defvar org-metaup-hook nil
20445 "Hook for functions attaching themselves to `M-up'.
20446 See `org-ctrl-c-ctrl-c-hook' for more information.")
20447 (defvar org-metadown-hook nil
20448 "Hook for functions attaching themselves to `M-down'.
20449 See `org-ctrl-c-ctrl-c-hook' for more information.")
20450 (defvar org-shiftmetaleft-hook nil
20451 "Hook for functions attaching themselves to `M-S-left'.
20452 See `org-ctrl-c-ctrl-c-hook' for more information.")
20453 (defvar org-shiftmetaright-hook nil
20454 "Hook for functions attaching themselves to `M-S-right'.
20455 See `org-ctrl-c-ctrl-c-hook' for more information.")
20456 (defvar org-shiftmetaup-hook nil
20457 "Hook for functions attaching themselves to `M-S-up'.
20458 See `org-ctrl-c-ctrl-c-hook' for more information.")
20459 (defvar org-shiftmetadown-hook nil
20460 "Hook for functions attaching themselves to `M-S-down'.
20461 See `org-ctrl-c-ctrl-c-hook' for more information.")
20462 (defvar org-metareturn-hook nil
20463 "Hook for functions attaching themselves to `M-RET'.
20464 See `org-ctrl-c-ctrl-c-hook' for more information.")
20465 (defvar org-shiftup-hook nil
20466 "Hook for functions attaching themselves to `S-up'.
20467 See `org-ctrl-c-ctrl-c-hook' for more information.")
20468 (defvar org-shiftup-final-hook nil
20469 "Hook for functions attaching themselves to `S-up'.
20470 This one runs after all other options except shift-select have been excluded.
20471 See `org-ctrl-c-ctrl-c-hook' for more information.")
20472 (defvar org-shiftdown-hook nil
20473 "Hook for functions attaching themselves to `S-down'.
20474 See `org-ctrl-c-ctrl-c-hook' for more information.")
20475 (defvar org-shiftdown-final-hook nil
20476 "Hook for functions attaching themselves to `S-down'.
20477 This one runs after all other options except shift-select have been excluded.
20478 See `org-ctrl-c-ctrl-c-hook' for more information.")
20479 (defvar org-shiftleft-hook nil
20480 "Hook for functions attaching themselves to `S-left'.
20481 See `org-ctrl-c-ctrl-c-hook' for more information.")
20482 (defvar org-shiftleft-final-hook nil
20483 "Hook for functions attaching themselves to `S-left'.
20484 This one runs after all other options except shift-select have been excluded.
20485 See `org-ctrl-c-ctrl-c-hook' for more information.")
20486 (defvar org-shiftright-hook nil
20487 "Hook for functions attaching themselves to `S-right'.
20488 See `org-ctrl-c-ctrl-c-hook' for more information.")
20489 (defvar org-shiftright-final-hook nil
20490 "Hook for functions attaching themselves to `S-right'.
20491 This one runs after all other options except shift-select have been excluded.
20492 See `org-ctrl-c-ctrl-c-hook' for more information.")
20494 (defun org-modifier-cursor-error ()
20495 "Throw an error, a modified cursor command was applied in wrong context."
20496 (user-error "This command is active in special context like tables, headlines or items"))
20498 (defun org-shiftselect-error ()
20499 "Throw an error because Shift-Cursor command was applied in wrong context."
20500 (if (and (boundp 'shift-select-mode) shift-select-mode)
20501 (user-error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
20502 (user-error "This command works only in special context like headlines or timestamps")))
20504 (defun org-call-for-shift-select (cmd)
20505 (let ((this-command-keys-shift-translated t))
20506 (call-interactively cmd)))
20508 (defun org-shifttab (&optional arg)
20509 "Global visibility cycling or move to previous table field.
20510 Call `org-table-previous-field' within a table.
20511 When ARG is nil, cycle globally through visibility states.
20512 When ARG is a numeric prefix, show contents of this level."
20513 (interactive "P")
20514 (cond
20515 ((org-at-table-p) (call-interactively 'org-table-previous-field))
20516 ((integerp arg)
20517 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
20518 (message "Content view to level: %d" arg)
20519 (org-content (prefix-numeric-value arg2))
20520 (org-cycle-show-empty-lines t)
20521 (setq org-cycle-global-status 'overview)))
20522 (t (call-interactively 'org-global-cycle))))
20524 (defun org-shiftmetaleft ()
20525 "Promote subtree or delete table column.
20526 Calls `org-promote-subtree', `org-outdent-item-tree', or
20527 `org-table-delete-column', depending on context. See the
20528 individual commands for more information."
20529 (interactive)
20530 (cond
20531 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
20532 ((org-at-table-p) (call-interactively 'org-table-delete-column))
20533 ((org-at-heading-p) (call-interactively 'org-promote-subtree))
20534 ((if (not (org-region-active-p)) (org-at-item-p)
20535 (save-excursion (goto-char (region-beginning))
20536 (org-at-item-p)))
20537 (call-interactively 'org-outdent-item-tree))
20538 (t (org-modifier-cursor-error))))
20540 (defun org-shiftmetaright ()
20541 "Demote subtree or insert table column.
20542 Calls `org-demote-subtree', `org-indent-item-tree', or
20543 `org-table-insert-column', depending on context. See the
20544 individual commands for more information."
20545 (interactive)
20546 (cond
20547 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
20548 ((org-at-table-p) (call-interactively 'org-table-insert-column))
20549 ((org-at-heading-p) (call-interactively 'org-demote-subtree))
20550 ((if (not (org-region-active-p)) (org-at-item-p)
20551 (save-excursion (goto-char (region-beginning))
20552 (org-at-item-p)))
20553 (call-interactively 'org-indent-item-tree))
20554 (t (org-modifier-cursor-error))))
20556 (defun org-shiftmetaup (&optional _arg)
20557 "Drag the line at point up.
20558 In a table, kill the current row.
20559 On a clock timestamp, update the value of the timestamp like `S-<up>'
20560 but also adjust the previous clocked item in the clock history.
20561 Everywhere else, drag the line at point up."
20562 (interactive "P")
20563 (cond
20564 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
20565 ((org-at-table-p) (call-interactively 'org-table-kill-row))
20566 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20567 (call-interactively 'org-timestamp-up)))
20568 (t (call-interactively 'org-drag-line-backward))))
20570 (defun org-shiftmetadown (&optional _arg)
20571 "Drag the line at point down.
20572 In a table, insert an empty row at the current line.
20573 On a clock timestamp, update the value of the timestamp like `S-<down>'
20574 but also adjust the previous clocked item in the clock history.
20575 Everywhere else, drag the line at point down."
20576 (interactive "P")
20577 (cond
20578 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
20579 ((org-at-table-p) (call-interactively 'org-table-insert-row))
20580 ((org-at-clock-log-p) (let ((org-clock-adjust-closest t))
20581 (call-interactively 'org-timestamp-down)))
20582 (t (call-interactively 'org-drag-line-forward))))
20584 (defsubst org-hidden-tree-error ()
20585 (user-error
20586 "Hidden subtree, open with TAB or use subtree command M-S-<left>/<right>"))
20588 (defun org-metaleft (&optional _arg)
20589 "Promote heading, list item at point or move table column left.
20591 Calls `org-do-promote', `org-outdent-item' or `org-table-move-column',
20592 depending on context. With no specific context, calls the Emacs
20593 default `backward-word'. See the individual commands for more
20594 information.
20596 This function runs the hook `org-metaleft-hook' as a first step,
20597 and returns at first non-nil value."
20598 (interactive "P")
20599 (cond
20600 ((run-hook-with-args-until-success 'org-metaleft-hook))
20601 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
20602 ((org-with-limited-levels
20603 (or (org-at-heading-p)
20604 (and (org-region-active-p)
20605 (save-excursion
20606 (goto-char (region-beginning))
20607 (org-at-heading-p)))))
20608 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20609 (call-interactively 'org-do-promote))
20610 ;; At an inline task.
20611 ((org-at-heading-p)
20612 (call-interactively 'org-inlinetask-promote))
20613 ((or (org-at-item-p)
20614 (and (org-region-active-p)
20615 (save-excursion
20616 (goto-char (region-beginning))
20617 (org-at-item-p))))
20618 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20619 (call-interactively 'org-outdent-item))
20620 (t (call-interactively 'backward-word))))
20622 (defun org-metaright (&optional _arg)
20623 "Demote heading, list item at point or move table column right.
20625 In front of a drawer or a block keyword, indent it correctly.
20627 Calls `org-do-demote', `org-indent-item', `org-table-move-column',
20628 `org-indnet-drawer' or `org-indent-block' depending on context.
20629 With no specific context, calls the Emacs default `forward-word'.
20630 See the individual commands for more information.
20632 This function runs the hook `org-metaright-hook' as a first step,
20633 and returns at first non-nil value."
20634 (interactive "P")
20635 (cond
20636 ((run-hook-with-args-until-success 'org-metaright-hook))
20637 ((org-at-table-p) (call-interactively 'org-table-move-column))
20638 ((org-at-drawer-p) (call-interactively 'org-indent-drawer))
20639 ((org-at-block-p) (call-interactively 'org-indent-block))
20640 ((org-with-limited-levels
20641 (or (org-at-heading-p)
20642 (and (org-region-active-p)
20643 (save-excursion
20644 (goto-char (region-beginning))
20645 (org-at-heading-p)))))
20646 (when (org-check-for-hidden 'headlines) (org-hidden-tree-error))
20647 (call-interactively 'org-do-demote))
20648 ;; At an inline task.
20649 ((org-at-heading-p)
20650 (call-interactively 'org-inlinetask-demote))
20651 ((or (org-at-item-p)
20652 (and (org-region-active-p)
20653 (save-excursion
20654 (goto-char (region-beginning))
20655 (org-at-item-p))))
20656 (when (org-check-for-hidden 'items) (org-hidden-tree-error))
20657 (call-interactively 'org-indent-item))
20658 (t (call-interactively 'forward-word))))
20660 (defun org-check-for-hidden (what)
20661 "Check if there are hidden headlines/items in the current visual line.
20662 WHAT can be either `headlines' or `items'. If the current line is
20663 an outline or item heading and it has a folded subtree below it,
20664 this function returns t, nil otherwise."
20665 (let ((re (cond
20666 ((eq what 'headlines) org-outline-regexp-bol)
20667 ((eq what 'items) (org-item-beginning-re))
20668 (t (error "This should not happen"))))
20669 beg end)
20670 (save-excursion
20671 (catch 'exit
20672 (unless (org-region-active-p)
20673 (setq beg (point-at-bol))
20674 (beginning-of-line 2)
20675 (while (and (not (eobp)) ;; this is like `next-line'
20676 (get-char-property (1- (point)) 'invisible))
20677 (beginning-of-line 2))
20678 (setq end (point))
20679 (goto-char beg)
20680 (goto-char (point-at-eol))
20681 (setq end (max end (point)))
20682 (while (re-search-forward re end t)
20683 (when (get-char-property (match-beginning 0) 'invisible)
20684 (throw 'exit t))))
20685 nil))))
20687 (defun org-metaup (&optional _arg)
20688 "Move subtree up or move table row up.
20689 Calls `org-move-subtree-up' or `org-table-move-row' or
20690 `org-move-item-up', depending on context. See the individual commands
20691 for more information."
20692 (interactive "P")
20693 (cond
20694 ((run-hook-with-args-until-success 'org-metaup-hook))
20695 ((org-region-active-p)
20696 (let* ((a (min (region-beginning) (region-end)))
20697 (b (1- (max (region-beginning) (region-end))))
20698 (c (save-excursion (goto-char a)
20699 (move-beginning-of-line 0)))
20700 (d (save-excursion (goto-char a)
20701 (move-end-of-line 0) (point))))
20702 (transpose-regions a b c d)
20703 (goto-char c)))
20704 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
20705 ((org-at-heading-p) (call-interactively 'org-move-subtree-up))
20706 ((org-at-item-p) (call-interactively 'org-move-item-up))
20707 (t (org-drag-element-backward))))
20709 (defun org-metadown (&optional _arg)
20710 "Move subtree down or move table row down.
20711 Calls `org-move-subtree-down' or `org-table-move-row' or
20712 `org-move-item-down', depending on context. See the individual
20713 commands for more information."
20714 (interactive "P")
20715 (cond
20716 ((run-hook-with-args-until-success 'org-metadown-hook))
20717 ((org-region-active-p)
20718 (let* ((a (min (region-beginning) (region-end)))
20719 (b (max (region-beginning) (region-end)))
20720 (c (save-excursion (goto-char b)
20721 (move-beginning-of-line 1)))
20722 (d (save-excursion (goto-char b)
20723 (move-end-of-line 1) (1+ (point)))))
20724 (transpose-regions a b c d)
20725 (goto-char d)))
20726 ((org-at-table-p) (call-interactively 'org-table-move-row))
20727 ((org-at-heading-p) (call-interactively 'org-move-subtree-down))
20728 ((org-at-item-p) (call-interactively 'org-move-item-down))
20729 (t (org-drag-element-forward))))
20731 (defun org-shiftup (&optional arg)
20732 "Increase item in timestamp or increase priority of current headline.
20733 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
20734 depending on context. See the individual commands for more information."
20735 (interactive "P")
20736 (cond
20737 ((run-hook-with-args-until-success 'org-shiftup-hook))
20738 ((and org-support-shift-select (org-region-active-p))
20739 (org-call-for-shift-select 'previous-line))
20740 ((org-at-timestamp-p t)
20741 (call-interactively (if org-edit-timestamp-down-means-later
20742 'org-timestamp-down 'org-timestamp-up)))
20743 ((and (not (eq org-support-shift-select 'always))
20744 org-enable-priority-commands
20745 (org-at-heading-p))
20746 (call-interactively 'org-priority-up))
20747 ((and (not org-support-shift-select) (org-at-item-p))
20748 (call-interactively 'org-previous-item))
20749 ((org-clocktable-try-shift 'up arg))
20750 ((run-hook-with-args-until-success 'org-shiftup-final-hook))
20751 (org-support-shift-select
20752 (org-call-for-shift-select 'previous-line))
20753 (t (org-shiftselect-error))))
20755 (defun org-shiftdown (&optional arg)
20756 "Decrease item in timestamp or decrease priority of current headline.
20757 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
20758 depending on context. See the individual commands for more information."
20759 (interactive "P")
20760 (cond
20761 ((run-hook-with-args-until-success 'org-shiftdown-hook))
20762 ((and org-support-shift-select (org-region-active-p))
20763 (org-call-for-shift-select 'next-line))
20764 ((org-at-timestamp-p t)
20765 (call-interactively (if org-edit-timestamp-down-means-later
20766 'org-timestamp-up 'org-timestamp-down)))
20767 ((and (not (eq org-support-shift-select 'always))
20768 org-enable-priority-commands
20769 (org-at-heading-p))
20770 (call-interactively 'org-priority-down))
20771 ((and (not org-support-shift-select) (org-at-item-p))
20772 (call-interactively 'org-next-item))
20773 ((org-clocktable-try-shift 'down arg))
20774 ((run-hook-with-args-until-success 'org-shiftdown-final-hook))
20775 (org-support-shift-select
20776 (org-call-for-shift-select 'next-line))
20777 (t (org-shiftselect-error))))
20779 (defun org-shiftright (&optional arg)
20780 "Cycle the thing at point or in the current line, depending on context.
20781 Depending on context, this does one of the following:
20783 - switch a timestamp at point one day into the future
20784 - on a headline, switch to the next TODO keyword.
20785 - on an item, switch entire list to the next bullet type
20786 - on a property line, switch to the next allowed value
20787 - on a clocktable definition line, move time block into the future"
20788 (interactive "P")
20789 (cond
20790 ((run-hook-with-args-until-success 'org-shiftright-hook))
20791 ((and org-support-shift-select (org-region-active-p))
20792 (org-call-for-shift-select 'forward-char))
20793 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
20794 ((and (not (eq org-support-shift-select 'always))
20795 (org-at-heading-p))
20796 (let ((org-inhibit-logging
20797 (not org-treat-S-cursor-todo-selection-as-state-change))
20798 (org-inhibit-blocking
20799 (not org-treat-S-cursor-todo-selection-as-state-change)))
20800 (org-call-with-arg 'org-todo 'right)))
20801 ((or (and org-support-shift-select
20802 (not (eq org-support-shift-select 'always))
20803 (org-at-item-bullet-p))
20804 (and (not org-support-shift-select) (org-at-item-p)))
20805 (org-call-with-arg 'org-cycle-list-bullet nil))
20806 ((and (not (eq org-support-shift-select 'always))
20807 (org-at-property-p))
20808 (call-interactively 'org-property-next-allowed-value))
20809 ((org-clocktable-try-shift 'right arg))
20810 ((run-hook-with-args-until-success 'org-shiftright-final-hook))
20811 (org-support-shift-select
20812 (org-call-for-shift-select 'forward-char))
20813 (t (org-shiftselect-error))))
20815 (defun org-shiftleft (&optional arg)
20816 "Cycle the thing at point or in the current line, depending on context.
20817 Depending on context, this does one of the following:
20819 - switch a timestamp at point one day into the past
20820 - on a headline, switch to the previous TODO keyword.
20821 - on an item, switch entire list to the previous bullet type
20822 - on a property line, switch to the previous allowed value
20823 - on a clocktable definition line, move time block into the past"
20824 (interactive "P")
20825 (cond
20826 ((run-hook-with-args-until-success 'org-shiftleft-hook))
20827 ((and org-support-shift-select (org-region-active-p))
20828 (org-call-for-shift-select 'backward-char))
20829 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
20830 ((and (not (eq org-support-shift-select 'always))
20831 (org-at-heading-p))
20832 (let ((org-inhibit-logging
20833 (not org-treat-S-cursor-todo-selection-as-state-change))
20834 (org-inhibit-blocking
20835 (not org-treat-S-cursor-todo-selection-as-state-change)))
20836 (org-call-with-arg 'org-todo 'left)))
20837 ((or (and org-support-shift-select
20838 (not (eq org-support-shift-select 'always))
20839 (org-at-item-bullet-p))
20840 (and (not org-support-shift-select) (org-at-item-p)))
20841 (org-call-with-arg 'org-cycle-list-bullet 'previous))
20842 ((and (not (eq org-support-shift-select 'always))
20843 (org-at-property-p))
20844 (call-interactively 'org-property-previous-allowed-value))
20845 ((org-clocktable-try-shift 'left arg))
20846 ((run-hook-with-args-until-success 'org-shiftleft-final-hook))
20847 (org-support-shift-select
20848 (org-call-for-shift-select 'backward-char))
20849 (t (org-shiftselect-error))))
20851 (defun org-shiftcontrolright ()
20852 "Switch to next TODO set."
20853 (interactive)
20854 (cond
20855 ((and org-support-shift-select (org-region-active-p))
20856 (org-call-for-shift-select 'forward-word))
20857 ((and (not (eq org-support-shift-select 'always))
20858 (org-at-heading-p))
20859 (org-call-with-arg 'org-todo 'nextset))
20860 (org-support-shift-select
20861 (org-call-for-shift-select 'forward-word))
20862 (t (org-shiftselect-error))))
20864 (defun org-shiftcontrolleft ()
20865 "Switch to previous TODO set."
20866 (interactive)
20867 (cond
20868 ((and org-support-shift-select (org-region-active-p))
20869 (org-call-for-shift-select 'backward-word))
20870 ((and (not (eq org-support-shift-select 'always))
20871 (org-at-heading-p))
20872 (org-call-with-arg 'org-todo 'previousset))
20873 (org-support-shift-select
20874 (org-call-for-shift-select 'backward-word))
20875 (t (org-shiftselect-error))))
20877 (defun org-shiftcontrolup (&optional n)
20878 "Change timestamps synchronously up in CLOCK log lines.
20879 Optional argument N tells to change by that many units."
20880 (interactive "P")
20881 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20882 (let (org-support-shift-select)
20883 (org-clock-timestamps-up n))
20884 (user-error "Not at a clock log")))
20886 (defun org-shiftcontroldown (&optional n)
20887 "Change timestamps synchronously down in CLOCK log lines.
20888 Optional argument N tells to change by that many units."
20889 (interactive "P")
20890 (if (and (org-at-clock-log-p) (org-at-timestamp-p t))
20891 (let (org-support-shift-select)
20892 (org-clock-timestamps-down n))
20893 (user-error "Not at a clock log")))
20895 (defun org-increase-number-at-point (&optional inc)
20896 "Increment the number at point.
20897 With an optional prefix numeric argument INC, increment using
20898 this numeric value."
20899 (interactive "p")
20900 (if (not (number-at-point))
20901 (user-error "Not on a number")
20902 (unless inc (setq inc 1))
20903 (let ((pos (point))
20904 (beg (skip-chars-backward "-+^/*0-9eE."))
20905 (end (skip-chars-forward "-+^/*0-9eE^.")) nap)
20906 (setq nap (buffer-substring-no-properties
20907 (+ pos beg) (+ pos beg end)))
20908 (delete-region (+ pos beg) (+ pos beg end))
20909 (insert (calc-eval (concat (number-to-string inc) "+" nap))))
20910 (when (org-at-table-p)
20911 (org-table-align)
20912 (org-table-end-of-field 1))))
20914 (defun org-decrease-number-at-point (&optional inc)
20915 "Decrement the number at point.
20916 With an optional prefix numeric argument INC, decrement using
20917 this numeric value."
20918 (interactive "p")
20919 (org-increase-number-at-point (- (or inc 1))))
20921 (defun org-ctrl-c-ret ()
20922 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
20923 (interactive)
20924 (cond
20925 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
20926 (t (call-interactively 'org-insert-heading))))
20928 (defun org-find-visible ()
20929 (let ((s (point)))
20930 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20931 (get-char-property s 'invisible)))
20933 (defun org-find-invisible ()
20934 (let ((s (point)))
20935 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
20936 (not (get-char-property s 'invisible))))
20939 (defun org-copy-visible (beg end)
20940 "Copy the visible parts of the region."
20941 (interactive "r")
20942 (let (snippets s)
20943 (save-excursion
20944 (save-restriction
20945 (narrow-to-region beg end)
20946 (setq s (goto-char (point-min)))
20947 (while (not (= (point) (point-max)))
20948 (goto-char (org-find-invisible))
20949 (push (buffer-substring s (point)) snippets)
20950 (setq s (goto-char (org-find-visible))))))
20951 (kill-new (apply 'concat (nreverse snippets)))))
20953 (defun org-copy-special ()
20954 "Copy region in table or copy current subtree.
20955 Calls `org-table-copy' or `org-copy-subtree', depending on context.
20956 See the individual commands for more information."
20957 (interactive)
20958 (call-interactively
20959 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
20961 (defun org-cut-special ()
20962 "Cut region in table or cut current subtree.
20963 Calls `org-table-copy' or `org-cut-subtree', depending on context.
20964 See the individual commands for more information."
20965 (interactive)
20966 (call-interactively
20967 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
20969 (defun org-paste-special (arg)
20970 "Paste rectangular region into table, or past subtree relative to level.
20971 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
20972 See the individual commands for more information."
20973 (interactive "P")
20974 (if (org-at-table-p)
20975 (org-table-paste-rectangle)
20976 (org-paste-subtree arg)))
20978 (defsubst org-in-fixed-width-region-p ()
20979 "Is point in a fixed-width region?"
20980 (save-match-data
20981 (eq 'fixed-width (org-element-type (org-element-at-point)))))
20983 (defun org-edit-special (&optional arg)
20984 "Call a special editor for the element at point.
20985 When at a table, call the formula editor with `org-table-edit-formulas'.
20986 When in a source code block, call `org-edit-src-code'.
20987 When in a fixed-width region, call `org-edit-fixed-width-region'.
20988 When in an export block, call `org-edit-export-block'.
20989 When at an #+INCLUDE keyword, visit the included file.
20990 When at a footnote reference, call `org-edit-footnote-reference'
20991 On a link, call `ffap' to visit the link at point.
20992 Otherwise, return a user error."
20993 (interactive "P")
20994 (let ((element (org-element-at-point)))
20995 (cl-assert (not buffer-read-only) nil
20996 "Buffer is read-only: %s" (buffer-name))
20997 (pcase (org-element-type element)
20998 (`src-block
20999 (if (not arg) (org-edit-src-code)
21000 (let* ((info (org-babel-get-src-block-info))
21001 (lang (nth 0 info))
21002 (params (nth 2 info))
21003 (session (cdr (assq :session params))))
21004 (if (not session) (org-edit-src-code)
21005 ;; At a src-block with a session and function called with
21006 ;; an ARG: switch to the buffer related to the inferior
21007 ;; process.
21008 (switch-to-buffer
21009 (funcall (intern (concat "org-babel-prep-session:" lang))
21010 session params))))))
21011 (`keyword
21012 (if (member (org-element-property :key element) '("INCLUDE" "SETUPFILE"))
21013 (org-open-link-from-string
21014 (format "[[%s]]"
21015 (expand-file-name
21016 (let ((value (org-element-property :value element)))
21017 (cond ((not (org-string-nw-p value))
21018 (user-error "No file to edit"))
21019 ((string-match "\\`\"\\(.*?\\)\"" value)
21020 (match-string 1 value))
21021 ((string-match "\\`[^ \t\"]\\S-*" value)
21022 (match-string 0 value))
21023 (t (user-error "No valid file specified")))))))
21024 (user-error "No special environment to edit here")))
21025 (`table
21026 (if (eq (org-element-property :type element) 'table.el)
21027 (org-edit-table.el)
21028 (call-interactively 'org-table-edit-formulas)))
21029 ;; Only Org tables contain `table-row' type elements.
21030 (`table-row (call-interactively 'org-table-edit-formulas))
21031 (`example-block (org-edit-src-code))
21032 (`export-block (org-edit-export-block))
21033 (`fixed-width (org-edit-fixed-width-region))
21035 ;; No notable element at point. Though, we may be at a link or
21036 ;; a footnote reference, which are objects. Thus, scan deeper.
21037 (let ((context (org-element-context element)))
21038 (pcase (org-element-type context)
21039 (`footnote-reference (org-edit-footnote-reference))
21040 (`inline-src-block (org-edit-inline-src-code))
21041 (`link (call-interactively #'ffap))
21042 (_ (user-error "No special environment to edit here"))))))))
21044 (defvar org-table-coordinate-overlays) ; defined in org-table.el
21045 (defun org-ctrl-c-ctrl-c (&optional arg)
21046 "Set tags in headline, or update according to changed information at point.
21048 This command does many different things, depending on context:
21050 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
21051 this is what we do.
21053 - If the cursor is on a statistics cookie, update it.
21055 - If the cursor is in a headline, prompt for tags and insert them
21056 into the current line, aligned to `org-tags-column'. When called
21057 with prefix arg, realign all tags in the current buffer.
21059 - If the cursor is in one of the special #+KEYWORD lines, this
21060 triggers scanning the buffer for these lines and updating the
21061 information.
21063 - If the cursor is inside a table, realign the table. This command
21064 works even if the automatic table editor has been turned off.
21066 - If the cursor is on a #+TBLFM line, re-apply the formulas to
21067 the entire table.
21069 - If the cursor is at a footnote reference or definition, jump to
21070 the corresponding definition or references, respectively.
21072 - If the cursor is a the beginning of a dynamic block, update it.
21074 - If the current buffer is a capture buffer, close note and file it.
21076 - If the cursor is on a <<<target>>>, update radio targets and
21077 corresponding links in this buffer.
21079 - If the cursor is on a numbered item in a plain list, renumber the
21080 ordered list.
21082 - If the cursor is on a checkbox, toggle it.
21084 - If the cursor is on a code block, evaluate it. The variable
21085 `org-confirm-babel-evaluate' can be used to control prompting
21086 before code block evaluation, by default every code block
21087 evaluation requires confirmation. Code block evaluation can be
21088 inhibited by setting `org-babel-no-eval-on-ctrl-c-ctrl-c'."
21089 (interactive "P")
21090 (cond
21091 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
21092 org-occur-highlights)
21093 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
21094 (org-remove-occur-highlights)
21095 (message "Temporary highlights/overlays removed from current buffer"))
21096 ((and (local-variable-p 'org-finish-function (current-buffer))
21097 (fboundp org-finish-function))
21098 (funcall org-finish-function))
21099 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
21101 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
21102 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21103 (user-error "C-c C-c can do nothing useful at this location"))
21104 (let* ((context (org-element-context))
21105 (type (org-element-type context)))
21106 (cl-case type
21107 ;; When at a link, act according to the parent instead.
21108 (link (setq context (org-element-property :parent context))
21109 (setq type (org-element-type context)))
21110 ;; Unsupported object types: refer to the first supported
21111 ;; element or object containing it.
21112 ((bold code entity export-snippet inline-babel-call inline-src-block
21113 italic latex-fragment line-break macro strike-through subscript
21114 superscript underline verbatim)
21115 (setq context
21116 (org-element-lineage
21117 context '(radio-target paragraph verse-block table-cell)))))
21118 ;; For convenience: at the first line of a paragraph on the
21119 ;; same line as an item, apply function on that item instead.
21120 (when (eq type 'paragraph)
21121 (let ((parent (org-element-property :parent context)))
21122 (when (and (eq (org-element-type parent) 'item)
21123 (= (line-beginning-position)
21124 (org-element-property :begin parent)))
21125 (setq context parent type 'item))))
21126 ;; Act according to type of element or object at point.
21127 (cl-case type
21128 (clock (org-clock-update-time-maybe))
21129 (dynamic-block
21130 (save-excursion
21131 (goto-char (org-element-property :post-affiliated context))
21132 (org-update-dblock)))
21133 (footnote-definition
21134 (goto-char (org-element-property :post-affiliated context))
21135 (call-interactively 'org-footnote-action))
21136 (footnote-reference (call-interactively 'org-footnote-action))
21137 ((headline inlinetask)
21138 (save-excursion (goto-char (org-element-property :begin context))
21139 (call-interactively 'org-set-tags)))
21140 (item
21141 ;; At an item: a double C-u set checkbox to "[-]"
21142 ;; unconditionally, whereas a single one will toggle its
21143 ;; presence. Without a universal argument, if the item
21144 ;; has a checkbox, toggle it. Otherwise repair the list.
21145 (let* ((box (org-element-property :checkbox context))
21146 (struct (org-element-property :structure context))
21147 (old-struct (copy-tree struct))
21148 (parents (org-list-parents-alist struct))
21149 (prevs (org-list-prevs-alist struct))
21150 (orderedp (org-not-nil (org-entry-get nil "ORDERED"))))
21151 (org-list-set-checkbox
21152 (org-element-property :begin context) struct
21153 (cond ((equal arg '(16)) "[-]")
21154 ((and (not box) (equal arg '(4))) "[ ]")
21155 ((or (not box) (equal arg '(4))) nil)
21156 ((eq box 'on) "[ ]")
21157 (t "[X]")))
21158 ;; Mimic `org-list-write-struct' but with grabbing
21159 ;; a return value from `org-list-struct-fix-box'.
21160 (org-list-struct-fix-ind struct parents 2)
21161 (org-list-struct-fix-item-end struct)
21162 (org-list-struct-fix-bul struct prevs)
21163 (org-list-struct-fix-ind struct parents)
21164 (let ((block-item
21165 (org-list-struct-fix-box struct parents prevs orderedp)))
21166 (if (and box (equal struct old-struct))
21167 (if (equal arg '(16))
21168 (message "Checkboxes already reset")
21169 (user-error "Cannot toggle this checkbox: %s"
21170 (if (eq box 'on)
21171 "all subitems checked"
21172 "unchecked subitems")))
21173 (org-list-struct-apply-struct struct old-struct)
21174 (org-update-checkbox-count-maybe))
21175 (when block-item
21176 (message "Checkboxes were removed due to empty box at line %d"
21177 (org-current-line block-item))))))
21178 (keyword
21179 (let ((org-inhibit-startup-visibility-stuff t)
21180 (org-startup-align-all-tables nil))
21181 (when (boundp 'org-table-coordinate-overlays)
21182 (mapc #'delete-overlay org-table-coordinate-overlays)
21183 (setq org-table-coordinate-overlays nil))
21184 (org-save-outline-visibility 'use-markers (org-mode-restart)))
21185 (message "Local setup has been refreshed"))
21186 (plain-list
21187 ;; At a plain list, with a double C-u argument, set
21188 ;; checkboxes of each item to "[-]", whereas a single one
21189 ;; will toggle their presence according to the state of the
21190 ;; first item in the list. Without an argument, repair the
21191 ;; list.
21192 (let* ((begin (org-element-property :contents-begin context))
21193 (beginm (move-marker (make-marker) begin))
21194 (struct (org-element-property :structure context))
21195 (old-struct (copy-tree struct))
21196 (first-box (save-excursion
21197 (goto-char begin)
21198 (looking-at org-list-full-item-re)
21199 (match-string-no-properties 3)))
21200 (new-box (cond ((equal arg '(16)) "[-]")
21201 ((equal arg '(4)) (unless first-box "[ ]"))
21202 ((equal first-box "[X]") "[ ]")
21203 (t "[X]"))))
21204 (cond
21205 (arg
21206 (dolist (pos
21207 (org-list-get-all-items
21208 begin struct (org-list-prevs-alist struct)))
21209 (org-list-set-checkbox pos struct new-box)))
21210 ((and first-box (eq (point) begin))
21211 ;; For convenience, when point is at bol on the first
21212 ;; item of the list and no argument is provided, simply
21213 ;; toggle checkbox of that item, if any.
21214 (org-list-set-checkbox begin struct new-box)))
21215 (org-list-write-struct
21216 struct (org-list-parents-alist struct) old-struct)
21217 (org-update-checkbox-count-maybe)
21218 (save-excursion (goto-char beginm) (org-list-send-list 'maybe))))
21219 ((property-drawer node-property)
21220 (call-interactively 'org-property-action))
21221 ((radio-target target)
21222 (call-interactively 'org-update-radio-target-regexp))
21223 (statistics-cookie
21224 (call-interactively 'org-update-statistics-cookies))
21225 ((table table-cell table-row)
21226 ;; At a table, recalculate every field and align it. Also
21227 ;; send the table if necessary. If the table has
21228 ;; a `table.el' type, just give up. At a table row or
21229 ;; cell, maybe recalculate line but always align table.
21230 (if (eq (org-element-property :type context) 'table.el)
21231 (message "%s" (substitute-command-keys "\\<org-mode-map>\
21232 Use \\[org-edit-special] to edit table.el tables"))
21233 (let ((org-enable-table-editor t))
21234 (if (or (eq type 'table)
21235 ;; Check if point is at a TBLFM line.
21236 (and (eq type 'table-row)
21237 (= (point) (org-element-property :end context))))
21238 (save-excursion
21239 (if (org-at-TBLFM-p)
21240 (progn (require 'org-table)
21241 (org-table-calc-current-TBLFM))
21242 (goto-char (org-element-property :contents-begin context))
21243 (org-call-with-arg 'org-table-recalculate (or arg t))
21244 (orgtbl-send-table 'maybe)))
21245 (org-table-maybe-eval-formula)
21246 (cond (arg (call-interactively 'org-table-recalculate))
21247 ((org-table-maybe-recalculate-line))
21248 (t (org-table-align)))))))
21249 (timestamp (org-timestamp-change 0 'day))
21250 (otherwise
21251 (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook)
21252 (user-error
21253 "C-c C-c can do nothing useful at this location")))))))))
21255 (defun org-mode-restart ()
21256 (interactive)
21257 (let ((indent-status (org-bound-and-true-p org-indent-mode)))
21258 (funcall major-mode)
21259 (hack-local-variables)
21260 (when (and indent-status (not (org-bound-and-true-p org-indent-mode)))
21261 (org-indent-mode -1)))
21262 (message "%s restarted" major-mode))
21264 (defun org-kill-note-or-show-branches ()
21265 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
21266 (interactive)
21267 (if (not org-finish-function)
21268 (progn
21269 (outline-hide-subtree)
21270 (call-interactively 'outline-show-branches))
21271 (let ((org-note-abort t))
21272 (funcall org-finish-function))))
21274 (defun org-delete-indentation (&optional ARG)
21275 "Join current line to previous and fix whitespace at join.
21277 If previous line is a headline add to headline title. Otherwise
21278 the function calls `delete-indentation'.
21280 With argument, join this line to following line."
21281 (interactive "*P")
21282 (if (save-excursion
21283 (if ARG (beginning-of-line)
21284 (forward-line -1))
21285 (looking-at org-complex-heading-regexp))
21286 ;; At headline.
21287 (let ((tags-column (when (match-beginning 5)
21288 (save-excursion (goto-char (match-beginning 5))
21289 (current-column))))
21290 (string (concat " " (progn (when ARG (forward-line 1))
21291 (org-trim (delete-and-extract-region
21292 (line-beginning-position)
21293 (line-end-position)))))))
21294 (unless (bobp) (delete-region (point) (1- (point))))
21295 (goto-char (or (match-end 4)
21296 (match-beginning 5)
21297 (match-end 0)))
21298 (skip-chars-backward " \t")
21299 (save-excursion (insert string))
21300 ;; Adjust alignment of tags.
21301 (when tags-column
21302 (org-align-tags-here (if org-auto-align-tags
21303 org-tags-column
21304 tags-column))))
21305 (delete-indentation ARG)))
21307 (defun org-open-line (n)
21308 "Insert a new row in tables, call `open-line' elsewhere.
21309 If `org-special-ctrl-o' is nil, just call `open-line' everywhere."
21310 (interactive "*p")
21311 (cond
21312 ((not org-special-ctrl-o)
21313 (open-line n))
21314 ((org-at-table-p)
21315 (org-table-insert-row))
21317 (open-line n))))
21319 (defun org-return (&optional indent)
21320 "Goto next table row or insert a newline.
21322 Calls `org-table-next-row' or `newline', depending on context.
21324 When optional INDENT argument is non-nil, call
21325 `newline-and-indent' instead of `newline'.
21327 When `org-return-follows-link' is non-nil and point is on
21328 a timestamp or a link, call `org-open-at-point'. However, it
21329 will not happen if point is in a table or on a \"dead\"
21330 object (e.g., within a comment). In these case, you need to use
21331 `org-open-at-point' directly."
21332 (interactive)
21333 (let ((context (if org-return-follows-link (org-element-context)
21334 (org-element-at-point))))
21335 (cond
21336 ;; In a table, call `org-table-next-row'.
21337 ((or (and (eq (org-element-type context) 'table)
21338 (>= (point) (org-element-property :contents-begin context))
21339 (< (point) (org-element-property :contents-end context)))
21340 (org-element-lineage context '(table-row table-cell) t))
21341 (org-table-justify-field-maybe)
21342 (call-interactively #'org-table-next-row))
21343 ;; On a link or a timestamp, call `org-open-at-point' if
21344 ;; `org-return-follows-link' allows it. Tolerate fuzzy
21345 ;; locations, e.g., in a comment, as `org-open-at-point'.
21346 ((and org-return-follows-link
21347 (or (org-in-regexp org-ts-regexp-both nil t)
21348 (org-in-regexp org-tsr-regexp-both nil t)
21349 (org-in-regexp org-any-link-re nil t)))
21350 (call-interactively #'org-open-at-point))
21351 ;; Insert newline in heading, but preserve tags.
21352 ((and (not (bolp))
21353 (save-excursion (beginning-of-line)
21354 (looking-at org-complex-heading-regexp)))
21355 ;; At headline. Split line. However, if point is on keyword,
21356 ;; priority cookie or tags, do not break any of them: add
21357 ;; a newline after the headline instead.
21358 (let ((tags-column (and (match-beginning 5)
21359 (save-excursion (goto-char (match-beginning 5))
21360 (current-column))))
21361 (string
21362 (when (and (match-end 4)
21363 (>= (point)
21364 (or (match-end 3) (match-end 2) (1+ (match-end 1))))
21365 (<= (point) (match-end 4)))
21366 (delete-and-extract-region (point) (match-end 4)))))
21367 (when (and tags-column string) ; Adjust tag alignment.
21368 (org-align-tags-here
21369 (if org-auto-align-tags org-tags-column tags-column)))
21370 (end-of-line)
21371 (org-show-entry)
21372 (if indent (newline-and-indent) (newline))
21373 (when string (save-excursion (insert (org-trim string))))))
21374 ;; In a list, make sure indenting keeps trailing text within.
21375 ((and indent
21376 (not (eolp))
21377 (org-element-lineage context '(item)))
21378 (let ((trailing-data
21379 (delete-and-extract-region (point) (line-end-position))))
21380 (newline-and-indent)
21381 (save-excursion (insert trailing-data))))
21382 (t (if indent (newline-and-indent) (newline))))))
21384 (defun org-return-indent ()
21385 "Goto next table row or insert a newline and indent.
21386 Calls `org-table-next-row' or `newline-and-indent', depending on
21387 context. See the individual commands for more information."
21388 (interactive)
21389 (org-return t))
21391 (defun org-ctrl-c-star ()
21392 "Compute table, or change heading status of lines.
21393 Calls `org-table-recalculate' or `org-toggle-heading',
21394 depending on context."
21395 (interactive)
21396 (cond
21397 ((org-at-table-p)
21398 (call-interactively 'org-table-recalculate))
21400 ;; Convert all lines in region to list items
21401 (call-interactively 'org-toggle-heading))))
21403 (defun org-ctrl-c-minus ()
21404 "Insert separator line in table or modify bullet status of line.
21405 Also turns a plain line or a region of lines into list items.
21406 Calls `org-table-insert-hline', `org-toggle-item', or
21407 `org-cycle-list-bullet', depending on context."
21408 (interactive)
21409 (cond
21410 ((org-at-table-p)
21411 (call-interactively 'org-table-insert-hline))
21412 ((org-region-active-p)
21413 (call-interactively 'org-toggle-item))
21414 ((org-in-item-p)
21415 (call-interactively 'org-cycle-list-bullet))
21417 (call-interactively 'org-toggle-item))))
21419 (defun org-toggle-item (arg)
21420 "Convert headings or normal lines to items, items to normal lines.
21421 If there is no active region, only the current line is considered.
21423 If the first non blank line in the region is a headline, convert
21424 all headlines to items, shifting text accordingly.
21426 If it is an item, convert all items to normal lines.
21428 If it is normal text, change region into a list of items.
21429 With a prefix argument ARG, change the region in a single item."
21430 (interactive "P")
21431 (let ((shift-text
21432 (function
21433 ;; Shift text in current section to IND, from point to END.
21434 ;; The function leaves point to END line.
21435 (lambda (ind end)
21436 (let ((min-i 1000) (end (copy-marker end)))
21437 ;; First determine the minimum indentation (MIN-I) of
21438 ;; the text.
21439 (save-excursion
21440 (catch 'exit
21441 (while (< (point) end)
21442 (let ((i (org-get-indentation)))
21443 (cond
21444 ;; Skip blank lines and inline tasks.
21445 ((looking-at "^[ \t]*$"))
21446 ((looking-at org-outline-regexp-bol))
21447 ;; We can't find less than 0 indentation.
21448 ((zerop i) (throw 'exit (setq min-i 0)))
21449 ((< i min-i) (setq min-i i))))
21450 (forward-line))))
21451 ;; Then indent each line so that a line indented to
21452 ;; MIN-I becomes indented to IND. Ignore blank lines
21453 ;; and inline tasks in the process.
21454 (let ((delta (- ind min-i)))
21455 (while (< (point) end)
21456 (unless (or (looking-at "^[ \t]*$")
21457 (looking-at org-outline-regexp-bol))
21458 (org-indent-line-to (+ (org-get-indentation) delta)))
21459 (forward-line)))))))
21460 (skip-blanks
21461 (function
21462 ;; Return beginning of first non-blank line, starting from
21463 ;; line at POS.
21464 (lambda (pos)
21465 (save-excursion
21466 (goto-char pos)
21467 (skip-chars-forward " \r\t\n")
21468 (point-at-bol)))))
21469 beg end)
21470 ;; Determine boundaries of changes.
21471 (if (org-region-active-p)
21472 (setq beg (funcall skip-blanks (region-beginning))
21473 end (copy-marker (region-end)))
21474 (setq beg (funcall skip-blanks (point-at-bol))
21475 end (copy-marker (point-at-eol))))
21476 ;; Depending on the starting line, choose an action on the text
21477 ;; between BEG and END.
21478 (org-with-limited-levels
21479 (save-excursion
21480 (goto-char beg)
21481 (cond
21482 ;; Case 1. Start at an item: de-itemize. Note that it only
21483 ;; happens when a region is active: `org-ctrl-c-minus'
21484 ;; would call `org-cycle-list-bullet' otherwise.
21485 ((org-at-item-p)
21486 (while (< (point) end)
21487 (when (org-at-item-p)
21488 (skip-chars-forward " \t")
21489 (delete-region (point) (match-end 0)))
21490 (forward-line)))
21491 ;; Case 2. Start at an heading: convert to items.
21492 ((org-at-heading-p)
21493 (let* ((bul (org-list-bullet-string "-"))
21494 (bul-len (length bul))
21495 (done (org-entry-is-done-p))
21496 (todo (org-entry-is-todo-p))
21497 ;; Indentation of the first heading. It should be
21498 ;; relative to the indentation of its parent, if any.
21499 (start-ind (save-excursion
21500 (cond
21501 ((not org-adapt-indentation) 0)
21502 ((not (outline-previous-heading)) 0)
21503 (t (length (match-string 0))))))
21504 ;; Level of first heading. Further headings will be
21505 ;; compared to it to determine hierarchy in the list.
21506 (ref-level (org-reduced-level (org-outline-level))))
21507 (when (or done todo) (org-todo ""))
21508 (while (< (point) end)
21509 (let* ((level (org-reduced-level (org-outline-level)))
21510 (delta (max 0 (- level ref-level))))
21511 ;; If current headline is less indented than the first
21512 ;; one, set it as reference, in order to preserve
21513 ;; subtrees.
21514 (when (< level ref-level) (setq ref-level level))
21515 (replace-match bul t t)
21516 (org-indent-line-to (+ start-ind (* delta bul-len)))
21517 (when (or done todo)
21518 (let* ((struct (org-list-struct))
21519 (old (copy-tree struct)))
21520 (org-list-set-checkbox (line-beginning-position)
21521 struct
21522 (if done "[X]" "[ ]"))
21523 (org-list-write-struct struct
21524 (org-list-parents-alist struct)
21525 old)))
21526 ;; Ensure all text down to END (or SECTION-END) belongs
21527 ;; to the newly created item.
21528 (let ((section-end (save-excursion
21529 (or (outline-next-heading) (point)))))
21530 (forward-line)
21531 (funcall shift-text
21532 (+ start-ind (* (1+ delta) bul-len))
21533 (min end section-end)))))))
21534 ;; Case 3. Normal line with ARG: make the first line of region
21535 ;; an item, and shift indentation of others lines to
21536 ;; set them as item's body.
21537 (arg (let* ((bul (org-list-bullet-string "-"))
21538 (bul-len (length bul))
21539 (ref-ind (org-get-indentation)))
21540 (skip-chars-forward " \t")
21541 (insert bul)
21542 (forward-line)
21543 (while (< (point) end)
21544 ;; Ensure that lines less indented than first one
21545 ;; still get included in item body.
21546 (funcall shift-text
21547 (+ ref-ind bul-len)
21548 (min end (save-excursion (or (outline-next-heading)
21549 (point)))))
21550 (forward-line))))
21551 ;; Case 4. Normal line without ARG: turn each non-item line
21552 ;; into an item.
21554 (while (< (point) end)
21555 (unless (or (org-at-heading-p) (org-at-item-p))
21556 (when (looking-at "\\([ \t]*\\)\\(\\S-\\)")
21557 (replace-match
21558 (concat "\\1" (org-list-bullet-string "-") "\\2"))))
21559 (forward-line))))))))
21561 (defun org-toggle-heading (&optional nstars)
21562 "Convert headings to normal text, or items or text to headings.
21563 If there is no active region, only convert the current line.
21565 With a \\[universal-argument] prefix, convert the whole list at
21566 point into heading.
21568 In a region:
21570 - If the first non blank line is a headline, remove the stars
21571 from all headlines in the region.
21573 - If it is a normal line, turn each and every normal line (i.e.,
21574 not an heading or an item) in the region into headings. If you
21575 want to convert only the first line of this region, use one
21576 universal prefix argument.
21578 - If it is a plain list item, turn all plain list items into headings.
21580 When converting a line into a heading, the number of stars is chosen
21581 such that the lines become children of the current entry. However,
21582 when a numeric prefix argument is given, its value determines the
21583 number of stars to add."
21584 (interactive "P")
21585 (let ((skip-blanks
21586 (function
21587 ;; Return beginning of first non-blank line, starting from
21588 ;; line at POS.
21589 (lambda (pos)
21590 (save-excursion
21591 (goto-char pos)
21592 (while (org-at-comment-p) (forward-line))
21593 (skip-chars-forward " \r\t\n")
21594 (point-at-bol)))))
21595 beg end toggled)
21596 ;; Determine boundaries of changes. If a universal prefix has
21597 ;; been given, put the list in a region. If region ends at a bol,
21598 ;; do not consider the last line to be in the region.
21600 (when (and current-prefix-arg (org-at-item-p))
21601 (when (listp current-prefix-arg) (setq current-prefix-arg 1))
21602 (org-mark-element))
21604 (if (org-region-active-p)
21605 (setq beg (funcall skip-blanks (region-beginning))
21606 end (copy-marker (save-excursion
21607 (goto-char (region-end))
21608 (if (bolp) (point) (point-at-eol)))))
21609 (setq beg (funcall skip-blanks (point-at-bol))
21610 end (copy-marker (point-at-eol))))
21611 ;; Ensure inline tasks don't count as headings.
21612 (org-with-limited-levels
21613 (save-excursion
21614 (goto-char beg)
21615 (cond
21616 ;; Case 1. Started at an heading: de-star headings.
21617 ((org-at-heading-p)
21618 (while (< (point) end)
21619 (when (org-at-heading-p t)
21620 (looking-at org-outline-regexp) (replace-match "")
21621 (setq toggled t))
21622 (forward-line)))
21623 ;; Case 2. Started at an item: change items into headlines.
21624 ;; One star will be added by `org-list-to-subtree'.
21625 ((org-at-item-p)
21626 (while (< (point) end)
21627 (when (org-at-item-p)
21628 ;; Pay attention to cases when region ends before list.
21629 (let* ((struct (org-list-struct))
21630 (list-end
21631 (min (org-list-get-bottom-point struct) (1+ end))))
21632 (save-restriction
21633 (narrow-to-region (point) list-end)
21634 (insert (org-list-to-subtree (org-list-to-lisp t)) "\n")))
21635 (setq toggled t))
21636 (forward-line)))
21637 ;; Case 3. Started at normal text: make every line an heading,
21638 ;; skipping headlines and items.
21639 (t (let* ((stars
21640 (make-string
21641 (if (numberp nstars) nstars (or (org-current-level) 0)) ?*))
21642 (add-stars
21643 (cond (nstars "") ; stars from prefix only
21644 ((equal stars "") "*") ; before first heading
21645 (org-odd-levels-only "**") ; inside heading, odd
21646 (t "*"))) ; inside heading, oddeven
21647 (rpl (concat stars add-stars " "))
21648 (lend (when (listp nstars) (save-excursion (end-of-line) (point)))))
21649 (while (< (point) (if (equal nstars '(4)) lend end))
21650 (when (and (not (or (org-at-heading-p) (org-at-item-p) (org-at-comment-p)))
21651 (looking-at "\\([ \t]*\\)\\(\\S-\\)"))
21652 (replace-match (concat rpl (match-string 2))) (setq toggled t))
21653 (forward-line)))))))
21654 (unless toggled (message "Cannot toggle heading from here"))))
21656 (defun org-meta-return (&optional _arg)
21657 "Insert a new heading or wrap a region in a table.
21658 Calls `org-insert-heading' or `org-table-wrap-region', depending
21659 on context. See the individual commands for more information."
21660 (interactive)
21661 (org-check-before-invisible-edit 'insert)
21662 (or (run-hook-with-args-until-success 'org-metareturn-hook)
21663 (call-interactively (if (org-at-table-p) #'org-table-wrap-region
21664 #'org-insert-heading))))
21666 ;;; Menu entries
21668 (defsubst org-in-subtree-not-table-p ()
21669 "Are we in a subtree and not in a table?"
21670 (and (not (org-before-first-heading-p))
21671 (not (org-at-table-p))))
21673 ;; Define the Org-mode menus
21674 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
21675 '("Tbl"
21676 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
21677 ["Next Field" org-cycle (org-at-table-p)]
21678 ["Previous Field" org-shifttab (org-at-table-p)]
21679 ["Next Row" org-return (org-at-table-p)]
21680 "--"
21681 ["Blank Field" org-table-blank-field (org-at-table-p)]
21682 ["Edit Field" org-table-edit-field (org-at-table-p)]
21683 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
21684 "--"
21685 ("Column"
21686 ["Move Column Left" org-metaleft (org-at-table-p)]
21687 ["Move Column Right" org-metaright (org-at-table-p)]
21688 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
21689 ["Insert Column" org-shiftmetaright (org-at-table-p)])
21690 ("Row"
21691 ["Move Row Up" org-metaup (org-at-table-p)]
21692 ["Move Row Down" org-metadown (org-at-table-p)]
21693 ["Delete Row" org-shiftmetaup (org-at-table-p)]
21694 ["Insert Row" org-shiftmetadown (org-at-table-p)]
21695 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
21696 "--"
21697 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
21698 ("Rectangle"
21699 ["Copy Rectangle" org-copy-special (org-at-table-p)]
21700 ["Cut Rectangle" org-cut-special (org-at-table-p)]
21701 ["Paste Rectangle" org-paste-special (org-at-table-p)]
21702 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
21703 "--"
21704 ("Calculate"
21705 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
21706 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
21707 ["Edit Formulas" org-edit-special (org-at-table-p)]
21708 "--"
21709 ["Recalculate line" org-table-recalculate (org-at-table-p)]
21710 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
21711 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
21712 "--"
21713 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
21714 "--"
21715 ["Sum Column/Rectangle" org-table-sum
21716 (or (org-at-table-p) (org-region-active-p))]
21717 ["Which Column?" org-table-current-column (org-at-table-p)])
21718 ["Debug Formulas"
21719 org-table-toggle-formula-debugger
21720 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
21721 ["Show Col/Row Numbers"
21722 org-table-toggle-coordinate-overlays
21723 :style toggle
21724 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
21725 "--"
21726 ["Create" org-table-create (and (not (org-at-table-p))
21727 org-enable-table-editor)]
21728 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
21729 ["Import from File" org-table-import (not (org-at-table-p))]
21730 ["Export to File" org-table-export (org-at-table-p)]
21731 "--"
21732 ["Create/Convert from/to table.el" org-table-create-with-table.el t]
21733 "--"
21734 ("Plot"
21735 ["Ascii plot" orgtbl-ascii-plot :active (org-at-table-p) :keys "C-c \" a"]
21736 ["Gnuplot" org-plot/gnuplot :active (org-at-table-p) :keys "C-c \" g"])))
21738 (easy-menu-define org-org-menu org-mode-map "Org menu"
21739 '("Org"
21740 ("Show/Hide"
21741 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
21742 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
21743 ["Sparse Tree..." org-sparse-tree t]
21744 ["Reveal Context" org-reveal t]
21745 ["Show All" outline-show-all t]
21746 "--"
21747 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
21748 "--"
21749 ["New Heading" org-insert-heading t]
21750 ("Navigate Headings"
21751 ["Up" outline-up-heading t]
21752 ["Next" outline-next-visible-heading t]
21753 ["Previous" outline-previous-visible-heading t]
21754 ["Next Same Level" outline-forward-same-level t]
21755 ["Previous Same Level" outline-backward-same-level t]
21756 "--"
21757 ["Jump" org-goto t])
21758 ("Edit Structure"
21759 ["Refile Subtree" org-refile (org-in-subtree-not-table-p)]
21760 "--"
21761 ["Move Subtree Up" org-metaup (org-at-heading-p)]
21762 ["Move Subtree Down" org-metadown (org-at-heading-p)]
21763 "--"
21764 ["Copy Subtree" org-copy-special (org-in-subtree-not-table-p)]
21765 ["Cut Subtree" org-cut-special (org-in-subtree-not-table-p)]
21766 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
21767 "--"
21768 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
21769 "--"
21770 ["Copy visible text" org-copy-visible t]
21771 "--"
21772 ["Promote Heading" org-metaleft (org-in-subtree-not-table-p)]
21773 ["Promote Subtree" org-shiftmetaleft (org-in-subtree-not-table-p)]
21774 ["Demote Heading" org-metaright (org-in-subtree-not-table-p)]
21775 ["Demote Subtree" org-shiftmetaright (org-in-subtree-not-table-p)]
21776 "--"
21777 ["Sort Region/Children" org-sort t]
21778 "--"
21779 ["Convert to odd levels" org-convert-to-odd-levels t]
21780 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
21781 ("Editing"
21782 ["Emphasis..." org-emphasize t]
21783 ["Edit Source Example" org-edit-special t]
21784 "--"
21785 ["Footnote new/jump" org-footnote-action t]
21786 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
21787 ("Archive"
21788 ["Archive (default method)" org-archive-subtree-default (org-in-subtree-not-table-p)]
21789 "--"
21790 ["Move Subtree to Archive file" org-archive-subtree (org-in-subtree-not-table-p)]
21791 ["Toggle ARCHIVE tag" org-toggle-archive-tag (org-in-subtree-not-table-p)]
21792 ["Move subtree to Archive sibling" org-archive-to-archive-sibling (org-in-subtree-not-table-p)]
21794 "--"
21795 ("Hyperlinks"
21796 ["Store Link (Global)" org-store-link t]
21797 ["Find existing link to here" org-occur-link-in-agenda-files t]
21798 ["Insert Link" org-insert-link t]
21799 ["Follow Link" org-open-at-point t]
21800 "--"
21801 ["Next link" org-next-link t]
21802 ["Previous link" org-previous-link t]
21803 "--"
21804 ["Descriptive Links"
21805 org-toggle-link-display
21806 :style radio
21807 :selected org-descriptive-links
21809 ["Literal Links"
21810 org-toggle-link-display
21811 :style radio
21812 :selected (not org-descriptive-links)])
21813 "--"
21814 ("TODO Lists"
21815 ["TODO/DONE/-" org-todo t]
21816 ("Select keyword"
21817 ["Next keyword" org-shiftright (org-at-heading-p)]
21818 ["Previous keyword" org-shiftleft (org-at-heading-p)]
21819 ["Complete Keyword" pcomplete (assq :todo-keyword (org-context))]
21820 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))]
21821 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-at-heading-p))])
21822 ["Show TODO Tree" org-show-todo-tree :active t :keys "C-c / t"]
21823 ["Global TODO list" org-todo-list :active t :keys "C-c a t"]
21824 "--"
21825 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
21826 :selected org-enforce-todo-dependencies :style toggle :active t]
21827 "Settings for tree at point"
21828 ["Do Children sequentially" org-toggle-ordered-property :style radio
21829 :selected (org-entry-get nil "ORDERED")
21830 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21831 ["Do Children parallel" org-toggle-ordered-property :style radio
21832 :selected (not (org-entry-get nil "ORDERED"))
21833 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
21834 "--"
21835 ["Set Priority" org-priority t]
21836 ["Priority Up" org-shiftup t]
21837 ["Priority Down" org-shiftdown t]
21838 "--"
21839 ["Get news from all feeds" org-feed-update-all t]
21840 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
21841 ["Customize feeds" (customize-variable 'org-feed-alist) t])
21842 ("TAGS and Properties"
21843 ["Set Tags" org-set-tags-command (not (org-before-first-heading-p))]
21844 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
21845 "--"
21846 ["Set property" org-set-property (not (org-before-first-heading-p))]
21847 ["Column view of properties" org-columns t]
21848 ["Insert Column View DBlock" org-columns-insert-dblock t])
21849 ("Dates and Scheduling"
21850 ["Timestamp" org-time-stamp (not (org-before-first-heading-p))]
21851 ["Timestamp (inactive)" org-time-stamp-inactive (not (org-before-first-heading-p))]
21852 ("Change Date"
21853 ["1 Day Later" org-shiftright (org-at-timestamp-p)]
21854 ["1 Day Earlier" org-shiftleft (org-at-timestamp-p)]
21855 ["1 ... Later" org-shiftup (org-at-timestamp-p)]
21856 ["1 ... Earlier" org-shiftdown (org-at-timestamp-p)])
21857 ["Compute Time Range" org-evaluate-time-range t]
21858 ["Schedule Item" org-schedule (not (org-before-first-heading-p))]
21859 ["Deadline" org-deadline (not (org-before-first-heading-p))]
21860 "--"
21861 ["Custom time format" org-toggle-time-stamp-overlays
21862 :style radio :selected org-display-custom-times]
21863 "--"
21864 ["Goto Calendar" org-goto-calendar t]
21865 ["Date from Calendar" org-date-from-calendar t]
21866 "--"
21867 ["Start/Restart Timer" org-timer-start t]
21868 ["Pause/Continue Timer" org-timer-pause-or-continue t]
21869 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
21870 ["Insert Timer String" org-timer t]
21871 ["Insert Timer Item" org-timer-item t])
21872 ("Logging work"
21873 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
21874 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
21875 ["Clock out" org-clock-out t]
21876 ["Clock cancel" org-clock-cancel t]
21877 "--"
21878 ["Mark as default task" org-clock-mark-default-task t]
21879 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
21880 ["Goto running clock" org-clock-goto t]
21881 "--"
21882 ["Display times" org-clock-display t]
21883 ["Create clock table" org-clock-report t]
21884 "--"
21885 ["Record DONE time"
21886 (progn (setq org-log-done (not org-log-done))
21887 (message "Switching to %s will %s record a timestamp"
21888 (car org-done-keywords)
21889 (if org-log-done "automatically" "not")))
21890 :style toggle :selected org-log-done])
21891 "--"
21892 ["Agenda Command..." org-agenda t]
21893 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
21894 ("File List for Agenda")
21895 ("Special views current file"
21896 ["TODO Tree" org-show-todo-tree t]
21897 ["Check Deadlines" org-check-deadlines t]
21898 ["Timeline" org-timeline t]
21899 ["Tags/Property tree" org-match-sparse-tree t])
21900 "--"
21901 ["Export/Publish..." org-export-dispatch t]
21902 ("LaTeX"
21903 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
21904 :selected org-cdlatex-mode]
21905 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
21906 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
21907 ["Modify math symbol" org-cdlatex-math-modify
21908 (org-inside-LaTeX-fragment-p)]
21909 ["Insert citation" org-reftex-citation t]
21910 "--"
21911 ["Template for BEAMER" (org-beamer-insert-options-template) t])
21912 "--"
21913 ("MobileOrg"
21914 ["Push Files and Views" org-mobile-push t]
21915 ["Get Captured and Flagged" org-mobile-pull t]
21916 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
21917 "--"
21918 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
21919 "--"
21920 ("Documentation"
21921 ["Show Version" org-version t]
21922 ["Info Documentation" org-info t])
21923 ("Customize"
21924 ["Browse Org Group" org-customize t]
21925 "--"
21926 ["Expand This Menu" org-create-customize-menu
21927 (fboundp 'customize-menu-create)])
21928 ["Send bug report" org-submit-bug-report t]
21929 "--"
21930 ("Refresh/Reload"
21931 ["Refresh setup current buffer" org-mode-restart t]
21932 ["Reload Org (after update)" org-reload t]
21933 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x !"])
21936 (defun org-info (&optional node)
21937 "Read documentation for Org-mode in the info system.
21938 With optional NODE, go directly to that node."
21939 (interactive)
21940 (info (format "(org)%s" (or node ""))))
21942 ;;;###autoload
21943 (defun org-submit-bug-report ()
21944 "Submit a bug report on Org-mode via mail.
21946 Don't hesitate to report any problems or inaccurate documentation.
21948 If you don't have setup sending mail from (X)Emacs, please copy the
21949 output buffer into your mail program, as it gives us important
21950 information about your Org-mode version and configuration."
21951 (interactive)
21952 (require 'reporter)
21953 (defvar reporter-prompt-for-summary-p)
21954 (org-load-modules-maybe)
21955 (org-require-autoloaded-modules)
21956 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
21957 (reporter-submit-bug-report
21958 "emacs-orgmode@gnu.org"
21959 (org-version nil 'full)
21960 (let (list)
21961 (save-window-excursion
21962 (org-pop-to-buffer-same-window (get-buffer-create "*Warn about privacy*"))
21963 (delete-other-windows)
21964 (erase-buffer)
21965 (insert "You are about to submit a bug report to the Org-mode mailing list.
21967 We would like to add your full Org-mode and Outline configuration to the
21968 bug report. This greatly simplifies the work of the maintainer and
21969 other experts on the mailing list.
21971 HOWEVER, some variables you have customized may contain private
21972 information. The names of customers, colleagues, or friends, might
21973 appear in the form of file names, tags, todo states, or search strings.
21974 If you answer yes to the prompt, you might want to check and remove
21975 such private information before sending the email.")
21976 (add-text-properties (point-min) (point-max) '(face org-warning))
21977 (when (yes-or-no-p "Include your Org-mode configuration ")
21978 (mapatoms
21979 (lambda (v)
21980 (and (boundp v)
21981 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
21982 (or (and (symbol-value v)
21983 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
21984 (and
21985 (get v 'custom-type) (get v 'standard-value)
21986 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
21987 (push v list)))))
21988 (kill-buffer (get-buffer "*Warn about privacy*"))
21989 list))
21990 nil nil
21991 "Remember to cover the basics, that is, what you expected to happen and
21992 what in fact did happen. You don't know how to make a good report? See
21994 http://orgmode.org/manual/Feedback.html#Feedback
21996 Your bug report will be posted to the Org-mode mailing list.
21997 ------------------------------------------------------------------------")
21998 (save-excursion
21999 (when (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
22000 (replace-match "\\1Bug: \\3 [\\2]")))))
22003 (defun org-install-agenda-files-menu ()
22004 (let ((bl (buffer-list)))
22005 (save-excursion
22006 (while bl
22007 (set-buffer (pop bl))
22008 (when (derived-mode-p 'org-mode) (setq bl nil)))
22009 (when (derived-mode-p 'org-mode)
22010 (easy-menu-change
22011 '("Org") "File List for Agenda"
22012 (append
22013 (list
22014 ["Edit File List" (org-edit-agenda-file-list) t]
22015 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
22016 ["Remove Current File from List" org-remove-file t]
22017 ["Cycle through agenda files" org-cycle-agenda-files t]
22018 ["Occur in all agenda files" org-occur-in-agenda-files t]
22019 "--")
22020 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
22022 ;;;; Documentation
22024 (defun org-require-autoloaded-modules ()
22025 (interactive)
22026 (mapc #'require
22027 '(org-agenda org-archive org-attach org-clock org-colview org-id
22028 org-table org-timer)))
22030 ;;;###autoload
22031 (defun org-reload (&optional uncompiled)
22032 "Reload all org lisp files.
22033 With prefix arg UNCOMPILED, load the uncompiled versions."
22034 (interactive "P")
22035 (require 'loadhist)
22036 (let* ((org-dir (org-find-library-dir "org"))
22037 (contrib-dir (or (org-find-library-dir "org-contribdir") org-dir))
22038 (feature-re "^\\(org\\|ob\\|ox\\)\\(-.*\\)?")
22039 (remove-re (mapconcat 'identity
22040 (mapcar (lambda (f) (concat "^" f "$"))
22041 (list (if (featurep 'xemacs)
22042 "org-colview"
22043 "org-colview-xemacs")
22044 "org" "org-loaddefs" "org-version"))
22045 "\\|"))
22046 (feats (delete-dups
22047 (mapcar 'file-name-sans-extension
22048 (mapcar 'file-name-nondirectory
22049 (delq nil
22050 (mapcar 'feature-file
22051 features))))))
22052 (lfeat (append
22053 (sort
22054 (setq feats
22055 (delq nil (mapcar
22056 (lambda (f)
22057 (if (and (string-match feature-re f)
22058 (not (string-match remove-re f)))
22059 f nil))
22060 feats)))
22061 'string-lessp)
22062 (list "org-version" "org")))
22063 (load-suffixes (when (boundp 'load-suffixes) load-suffixes))
22064 (load-suffixes (if uncompiled (reverse load-suffixes) load-suffixes))
22065 load-uncore load-misses)
22066 (setq load-misses
22067 (delq 't
22068 (mapcar (lambda (f)
22069 (or (org-load-noerror-mustsuffix (concat org-dir f))
22070 (and (string= org-dir contrib-dir)
22071 (org-load-noerror-mustsuffix (concat contrib-dir f)))
22072 (and (org-load-noerror-mustsuffix (concat (org-find-library-dir f) f))
22073 (add-to-list 'load-uncore f 'append)
22076 lfeat)))
22077 (when load-uncore
22078 (message "The following feature%s found in load-path, please check if that's correct:\n%s"
22079 (if (> (length load-uncore) 1) "s were" " was") load-uncore))
22080 (if load-misses
22081 (message "Some error occurred while reloading Org feature%s\n%s\nPlease check *Messages*!\n%s"
22082 (if (> (length load-misses) 1) "s" "") load-misses (org-version nil 'full))
22083 (message "Successfully reloaded Org\n%s" (org-version nil 'full)))))
22085 ;;;###autoload
22086 (defun org-customize ()
22087 "Call the customize function with org as argument."
22088 (interactive)
22089 (org-load-modules-maybe)
22090 (org-require-autoloaded-modules)
22091 (customize-browse 'org))
22093 (defun org-create-customize-menu ()
22094 "Create a full customization menu for Org-mode, insert it into the menu."
22095 (interactive)
22096 (org-load-modules-maybe)
22097 (org-require-autoloaded-modules)
22098 (if (fboundp 'customize-menu-create)
22099 (progn
22100 (easy-menu-change
22101 '("Org") "Customize"
22102 `(["Browse Org group" org-customize t]
22103 "--"
22104 ,(customize-menu-create 'org)
22105 ["Set" Custom-set t]
22106 ["Save" Custom-save t]
22107 ["Reset to Current" Custom-reset-current t]
22108 ["Reset to Saved" Custom-reset-saved t]
22109 ["Reset to Standard Settings" Custom-reset-standard t]))
22110 (message "\"Org\"-menu now contains full customization menu"))
22111 (error "Cannot expand menu (outdated version of cus-edit.el)")))
22113 ;;;; Miscellaneous stuff
22115 ;;; Generally useful functions
22117 (defun org-get-at-eol (property n)
22118 "Get text property PROPERTY at the end of line less N characters."
22119 (get-text-property (- (point-at-eol) n) property))
22121 (defun org-find-text-property-in-string (prop s)
22122 "Return the first non-nil value of property PROP in string S."
22123 (or (get-text-property 0 prop s)
22124 (get-text-property (or (next-single-property-change 0 prop s) 0)
22125 prop s)))
22127 (defun org-display-warning (message) ;; Copied from Emacs-Muse
22128 "Display the given MESSAGE as a warning."
22129 (if (fboundp 'display-warning)
22130 (display-warning 'org message
22131 (if (featurep 'xemacs) 'warning :warning))
22132 (let ((buf (get-buffer-create "*Org warnings*")))
22133 (with-current-buffer buf
22134 (goto-char (point-max))
22135 (insert "Warning (Org): " message)
22136 (unless (bolp)
22137 (newline)))
22138 (display-buffer buf)
22139 (sit-for 0))))
22141 (defun org-eval (form)
22142 "Eval FORM and return result."
22143 (condition-case error
22144 (eval form)
22145 (error (format "%%![Error: %s]" error))))
22147 (defun org-in-clocktable-p ()
22148 "Check if the cursor is in a clocktable."
22149 (let ((pos (point)) start)
22150 (save-excursion
22151 (end-of-line 1)
22152 (and (re-search-backward "^[ \t]*#\\+BEGIN:[ \t]+clocktable" nil t)
22153 (setq start (match-beginning 0))
22154 (re-search-forward "^[ \t]*#\\+END:.*" nil t)
22155 (>= (match-end 0) pos)
22156 start))))
22158 (defun org-in-verbatim-emphasis ()
22159 (save-match-data
22160 (and (org-in-regexp org-emph-re 2)
22161 (>= (point) (match-beginning 3))
22162 (<= (point) (match-end 4))
22163 (member (match-string 3) '("=" "~")))))
22165 (defun org-goto-marker-or-bmk (marker &optional bookmark)
22166 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
22167 (if (and marker (marker-buffer marker)
22168 (buffer-live-p (marker-buffer marker)))
22169 (progn
22170 (org-pop-to-buffer-same-window (marker-buffer marker))
22171 (when (or (> marker (point-max)) (< marker (point-min)))
22172 (widen))
22173 (goto-char marker)
22174 (org-show-context 'org-goto))
22175 (if bookmark
22176 (bookmark-jump bookmark)
22177 (error "Cannot find location"))))
22179 (defun org-quote-csv-field (s)
22180 "Quote field for inclusion in CSV material."
22181 (if (string-match "[\",]" s)
22182 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
22185 (defun org-force-self-insert (N)
22186 "Needed to enforce self-insert under remapping."
22187 (interactive "p")
22188 (self-insert-command N))
22190 (defun org-string-width (s)
22191 "Compute width of string, ignoring invisible characters.
22192 This ignores character with invisibility property `org-link', and also
22193 characters with property `org-cwidth', because these will become invisible
22194 upon the next fontification round."
22195 (let (b l)
22196 (when (or (eq t buffer-invisibility-spec)
22197 (assq 'org-link buffer-invisibility-spec))
22198 (while (setq b (text-property-any 0 (length s)
22199 'invisible 'org-link s))
22200 (setq s (concat (substring s 0 b)
22201 (substring s (or (next-single-property-change
22202 b 'invisible s)
22203 (length s)))))))
22204 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
22205 (setq s (concat (substring s 0 b)
22206 (substring s (or (next-single-property-change
22207 b 'org-cwidth s)
22208 (length s))))))
22209 (setq l (string-width s) b -1)
22210 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
22211 (setq l (- l (get-text-property b 'org-dwidth-n s))))
22214 (defun org-shorten-string (s maxlength)
22215 "Shorten string S so tht it is no longer than MAXLENGTH characters.
22216 If the string is shorter or has length MAXLENGTH, just return the
22217 original string. If it is longer, the functions finds a space in the
22218 string, breaks this string off at that locations and adds three dots
22219 as ellipsis. Including the ellipsis, the string will not be longer
22220 than MAXLENGTH. If finding a good breaking point in the string does
22221 not work, the string is just chopped off in the middle of a word
22222 if necessary."
22223 (if (<= (length s) maxlength)
22225 (let* ((n (max (- maxlength 4) 1))
22226 (re (concat "\\`\\(.\\{1," (int-to-string n) "\\}[^ ]\\)\\([ ]\\|\\'\\)")))
22227 (if (string-match re s)
22228 (concat (match-string 1 s) "...")
22229 (concat (substring s 0 (max (- maxlength 3) 0)) "...")))))
22231 (defun org-get-indentation (&optional line)
22232 "Get the indentation of the current line, interpreting tabs.
22233 When LINE is given, assume it represents a line and compute its indentation."
22234 (if line
22235 (when (string-match "^ *" (org-remove-tabs line))
22236 (match-end 0))
22237 (save-excursion
22238 (beginning-of-line 1)
22239 (skip-chars-forward " \t")
22240 (current-column))))
22242 (defun org-get-string-indentation (s)
22243 "What indentation has S due to SPACE and TAB at the beginning of the string?"
22244 (let ((n -1) (i 0) (w tab-width) c)
22245 (catch 'exit
22246 (while (< (setq n (1+ n)) (length s))
22247 (setq c (aref s n))
22248 (cond ((= c ?\ ) (setq i (1+ i)))
22249 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
22250 (t (throw 'exit t)))))
22253 (defun org-remove-tabs (s &optional width)
22254 "Replace tabulators in S with spaces.
22255 Assumes that s is a single line, starting in column 0."
22256 (setq width (or width tab-width))
22257 (while (string-match "\t" s)
22258 (setq s (replace-match
22259 (make-string
22260 (- (* width (/ (+ (match-beginning 0) width) width))
22261 (match-beginning 0)) ?\ )
22262 t t s)))
22265 (defun org-fix-indentation (line ind)
22266 "Fix indentation in LINE.
22267 IND is a cons cell with target and minimum indentation.
22268 If the current indentation in LINE is smaller than the minimum,
22269 leave it alone. If it is larger than ind, set it to the target."
22270 (let* ((l (org-remove-tabs line))
22271 (i (org-get-indentation l))
22272 (i1 (car ind)) (i2 (cdr ind)))
22273 (when (>= i i2) (setq l (substring line i2)))
22274 (if (> i1 0)
22275 (concat (make-string i1 ?\ ) l)
22276 l)))
22278 (defun org-remove-indentation (code &optional n)
22279 "Remove maximum common indentation in string CODE and return it.
22280 N may optionally be the number of columns to remove. Return CODE
22281 as-is if removal failed."
22282 (with-temp-buffer
22283 (insert code)
22284 (if (org-do-remove-indentation n) (buffer-string) code)))
22286 (defun org-do-remove-indentation (&optional n)
22287 "Remove the maximum common indentation from the buffer.
22288 When optional argument N is a positive integer, remove exactly
22289 that much characters from indentation, if possible. Return nil
22290 if it fails."
22291 (catch :exit
22292 (goto-char (point-min))
22293 ;; Find maximum common indentation, if not specified.
22294 (let ((n (or n
22295 (let ((min-ind (point-max)))
22296 (save-excursion
22297 (while (re-search-forward "^[ \t]*\\S-" nil t)
22298 (let ((ind (1- (current-column))))
22299 (if (zerop ind) (throw :exit nil)
22300 (setq min-ind (min min-ind ind))))))
22301 min-ind))))
22302 (if (zerop n) (throw :exit nil)
22303 ;; Remove exactly N indentation, but give up if not possible.
22304 (while (not (eobp))
22305 (let ((ind (progn (skip-chars-forward " \t") (current-column))))
22306 (cond ((eolp) (delete-region (line-beginning-position) (point)))
22307 ((< ind n) (throw :exit nil))
22308 (t (org-indent-line-to (- ind n))))
22309 (forward-line)))
22310 ;; Signal success.
22311 t))))
22313 (defun org-fill-template (template alist)
22314 "Find each %key of ALIST in TEMPLATE and replace it."
22315 (let ((case-fold-search nil))
22316 (dolist (entry (sort (copy-sequence alist)
22317 (lambda (a b) (< (length (car a)) (length (car b))))))
22318 (setq template
22319 (replace-regexp-in-string
22320 (concat "%" (regexp-quote (car entry)))
22321 (or (cdr entry) "") template t t)))
22322 template))
22324 (defun org-base-buffer (buffer)
22325 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
22326 (if (not buffer)
22327 buffer
22328 (or (buffer-base-buffer buffer)
22329 buffer)))
22331 (defun org-wrap (string &optional width lines)
22332 "Wrap string to either a number of lines, or a width in characters.
22333 If WIDTH is non-nil, the string is wrapped to that width, however many lines
22334 that costs. If there is a word longer than WIDTH, the text is actually
22335 wrapped to the length of that word.
22336 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
22337 many lines, whatever width that takes.
22338 The return value is a list of lines, without newlines at the end."
22339 (let* ((words (org-split-string string "[ \t\n]+"))
22340 (maxword (apply 'max (mapcar 'org-string-width words)))
22341 w ll)
22342 (cond (width
22343 (org-do-wrap words (max maxword width)))
22344 (lines
22345 (setq w maxword)
22346 (setq ll (org-do-wrap words maxword))
22347 (if (<= (length ll) lines)
22349 (setq ll words)
22350 (while (> (length ll) lines)
22351 (setq w (1+ w))
22352 (setq ll (org-do-wrap words w)))
22353 ll))
22354 (t (error "Cannot wrap this")))))
22356 (defun org-do-wrap (words width)
22357 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
22358 (let (lines line)
22359 (while words
22360 (setq line (pop words))
22361 (while (and words (< (+ (length line) (length (car words))) width))
22362 (setq line (concat line " " (pop words))))
22363 (setq lines (push line lines)))
22364 (nreverse lines)))
22366 (defun org-split-string (string &optional separators)
22367 "Splits STRING into substrings at SEPARATORS.
22368 SEPARATORS is a regular expression.
22369 No empty strings are returned if there are matches at the beginning
22370 and end of string."
22371 ;; FIXME: why not use (split-string STRING SEPARATORS t)?
22372 (let ((start 0) notfirst list)
22373 (while (and (string-match (or separators "[ \f\t\n\r\v]+") string
22374 (if (and notfirst
22375 (= start (match-beginning 0))
22376 (< start (length string)))
22377 (1+ start) start))
22378 (< (match-beginning 0) (length string)))
22379 (setq notfirst t)
22380 (or (eq (match-beginning 0) 0)
22381 (and (eq (match-beginning 0) (match-end 0))
22382 (eq (match-beginning 0) start))
22383 (push (substring string start (match-beginning 0)) list))
22384 (setq start (match-end 0)))
22385 (or (eq start (length string))
22386 (push (substring string start) list))
22387 (nreverse list)))
22389 (defun org-quote-vert (s)
22390 "Replace \"|\" with \"\\vert\"."
22391 (while (string-match "|" s)
22392 (setq s (replace-match "\\vert" t t s)))
22395 (defun org-uuidgen-p (s)
22396 "Is S an ID created by UUIDGEN?"
22397 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
22399 (defun org-in-src-block-p (&optional inside)
22400 "Whether point is in a code source block.
22401 When INSIDE is non-nil, don't consider we are within a src block
22402 when point is at #+BEGIN_SRC or #+END_SRC."
22403 (let ((case-fold-search t))
22404 (or (and (eq (get-char-property (point) 'src-block) t))
22405 (and (not inside)
22406 (save-match-data
22407 (save-excursion
22408 (beginning-of-line)
22409 (looking-at ".*#\\+\\(begin\\|end\\)_src")))))))
22411 (defun org-context ()
22412 "Return a list of contexts of the current cursor position.
22413 If several contexts apply, all are returned.
22414 Each context entry is a list with a symbol naming the context, and
22415 two positions indicating start and end of the context. Possible
22416 contexts are:
22418 :headline anywhere in a headline
22419 :headline-stars on the leading stars in a headline
22420 :todo-keyword on a TODO keyword (including DONE) in a headline
22421 :tags on the TAGS in a headline
22422 :priority on the priority cookie in a headline
22423 :item on the first line of a plain list item
22424 :item-bullet on the bullet/number of a plain list item
22425 :checkbox on the checkbox in a plain list item
22426 :table in an org-mode table
22427 :table-special on a special filed in a table
22428 :table-table in a table.el table
22429 :clocktable in a clocktable
22430 :src-block in a source block
22431 :link on a hyperlink
22432 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE, COMMENT.
22433 :target on a <<target>>
22434 :radio-target on a <<<radio-target>>>
22435 :latex-fragment on a LaTeX fragment
22436 :latex-preview on a LaTeX fragment with overlaid preview image
22438 This function expects the position to be visible because it uses font-lock
22439 faces as a help to recognize the following contexts: :table-special, :link,
22440 and :keyword."
22441 (let* ((f (get-text-property (point) 'face))
22442 (faces (if (listp f) f (list f)))
22443 (case-fold-search t)
22444 (p (point)) clist o)
22445 ;; First the large context
22446 (cond
22447 ((org-at-heading-p t)
22448 (push (list :headline (point-at-bol) (point-at-eol)) clist)
22449 (when (progn
22450 (beginning-of-line 1)
22451 (looking-at org-todo-line-tags-regexp))
22452 (push (org-point-in-group p 1 :headline-stars) clist)
22453 (push (org-point-in-group p 2 :todo-keyword) clist)
22454 (push (org-point-in-group p 4 :tags) clist))
22455 (goto-char p)
22456 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
22457 (when (looking-at "\\[#[A-Z0-9]\\]")
22458 (push (org-point-in-group p 0 :priority) clist)))
22460 ((org-at-item-p)
22461 (push (org-point-in-group p 2 :item-bullet) clist)
22462 (push (list :item (point-at-bol)
22463 (save-excursion (org-end-of-item) (point)))
22464 clist)
22465 (and (org-at-item-checkbox-p)
22466 (push (org-point-in-group p 0 :checkbox) clist)))
22468 ((org-at-table-p)
22469 (push (list :table (org-table-begin) (org-table-end)) clist)
22470 (when (memq 'org-formula faces)
22471 (push (list :table-special
22472 (previous-single-property-change p 'face)
22473 (next-single-property-change p 'face)) clist)))
22474 ((org-at-table-p 'any)
22475 (push (list :table-table) clist)))
22476 (goto-char p)
22478 (let ((case-fold-search t))
22479 ;; New the "medium" contexts: clocktables, source blocks
22480 (cond ((org-in-clocktable-p)
22481 (push (list :clocktable
22482 (and (or (looking-at "[ \t]*\\(#\\+BEGIN: clocktable\\)")
22483 (re-search-backward "[ \t]*\\(#+BEGIN: clocktable\\)" nil t))
22484 (match-beginning 1))
22485 (and (re-search-forward "[ \t]*#\\+END:?" nil t)
22486 (match-end 0))) clist))
22487 ((org-in-src-block-p)
22488 (push (list :src-block
22489 (and (or (looking-at "[ \t]*\\(#\\+BEGIN_SRC\\)")
22490 (re-search-backward "[ \t]*\\(#+BEGIN_SRC\\)" nil t))
22491 (match-beginning 1))
22492 (and (search-forward "#+END_SRC" nil t)
22493 (match-beginning 0))) clist))))
22494 (goto-char p)
22496 ;; Now the small context
22497 (cond
22498 ((org-at-timestamp-p)
22499 (push (org-point-in-group p 0 :timestamp) clist))
22500 ((memq 'org-link faces)
22501 (push (list :link
22502 (previous-single-property-change p 'face)
22503 (next-single-property-change p 'face)) clist))
22504 ((memq 'org-special-keyword faces)
22505 (push (list :keyword
22506 (previous-single-property-change p 'face)
22507 (next-single-property-change p 'face)) clist))
22508 ((org-at-target-p)
22509 (push (org-point-in-group p 0 :target) clist)
22510 (goto-char (1- (match-beginning 0)))
22511 (when (looking-at org-radio-target-regexp)
22512 (push (org-point-in-group p 0 :radio-target) clist))
22513 (goto-char p))
22514 ((setq o (cl-some
22515 (lambda (o)
22516 (and (eq (overlay-get o 'org-overlay-type) 'org-latex-overlay)
22518 (overlays-at (point))))
22519 (push (list :latex-fragment
22520 (overlay-start o) (overlay-end o)) clist)
22521 (push (list :latex-preview
22522 (overlay-start o) (overlay-end o)) clist))
22523 ((org-inside-LaTeX-fragment-p)
22524 ;; FIXME: positions wrong.
22525 (push (list :latex-fragment (point) (point)) clist)))
22527 (setq clist (nreverse (delq nil clist)))
22528 clist))
22530 (defun org-in-regexp (regexp &optional nlines visually)
22531 "Check if point is inside a match of REGEXP.
22533 Normally only the current line is checked, but you can include
22534 NLINES extra lines around point into the search. If VISUALLY is
22535 set, require that the cursor is not after the match but really
22536 on, so that the block visually is on the match.
22538 Return nil or a cons cell (BEG . END) where BEG and END are,
22539 respectively, the positions at the beginning and the end of the
22540 match."
22541 (catch :exit
22542 (let ((pos (point))
22543 (eol (line-end-position (if nlines (1+ nlines) 1))))
22544 (save-excursion
22545 (beginning-of-line (- 1 (or nlines 0)))
22546 (while (and (re-search-forward regexp eol t)
22547 (<= (match-beginning 0) pos))
22548 (let ((end (match-end 0)))
22549 (when (or (> end pos) (and (= end pos) (not visually)))
22550 (throw :exit (cons (match-beginning 0) (match-end 0))))))))))
22551 (define-obsolete-function-alias 'org-at-regexp-p 'org-in-regexp
22552 "Org mode 8.3")
22554 (defun org-between-regexps-p (start-re end-re &optional lim-up lim-down)
22555 "Non-nil when point is between matches of START-RE and END-RE.
22557 Also return a non-nil value when point is on one of the matches.
22559 Optional arguments LIM-UP and LIM-DOWN bound the search; they are
22560 buffer positions. Default values are the positions of headlines
22561 surrounding the point.
22563 The functions returns a cons cell whose car (resp. cdr) is the
22564 position before START-RE (resp. after END-RE)."
22565 (save-match-data
22566 (let ((pos (point))
22567 (limit-up (or lim-up (save-excursion (outline-previous-heading))))
22568 (limit-down (or lim-down (save-excursion (outline-next-heading))))
22569 beg end)
22570 (save-excursion
22571 ;; Point is on a block when on START-RE or if START-RE can be
22572 ;; found before it...
22573 (and (or (org-in-regexp start-re)
22574 (re-search-backward start-re limit-up t))
22575 (setq beg (match-beginning 0))
22576 ;; ... and END-RE after it...
22577 (goto-char (match-end 0))
22578 (re-search-forward end-re limit-down t)
22579 (> (setq end (match-end 0)) pos)
22580 ;; ... without another START-RE in-between.
22581 (goto-char (match-beginning 0))
22582 (not (re-search-backward start-re (1+ beg) t))
22583 ;; Return value.
22584 (cons beg end))))))
22586 (defun org-in-block-p (names)
22587 "Non-nil when point belongs to a block whose name belongs to NAMES.
22589 NAMES is a list of strings containing names of blocks.
22591 Return first block name matched, or nil. Beware that in case of
22592 nested blocks, the returned name may not belong to the closest
22593 block from point."
22594 (save-match-data
22595 (catch 'exit
22596 (let ((case-fold-search t)
22597 (lim-up (save-excursion (outline-previous-heading)))
22598 (lim-down (save-excursion (outline-next-heading))))
22599 (dolist (name names)
22600 (let ((n (regexp-quote name)))
22601 (when (org-between-regexps-p
22602 (concat "^[ \t]*#\\+begin_" n)
22603 (concat "^[ \t]*#\\+end_" n)
22604 lim-up lim-down)
22605 (throw 'exit n)))))
22606 nil)))
22608 (defun org-occur-in-agenda-files (regexp &optional _nlines)
22609 "Call `multi-occur' with buffers for all agenda files."
22610 (interactive "sOrg-files matching: ")
22611 (let* ((files (org-agenda-files))
22612 (tnames (mapcar #'file-truename files))
22613 (extra org-agenda-text-search-extra-files))
22614 (when (eq (car extra) 'agenda-archives)
22615 (setq extra (cdr extra))
22616 (setq files (org-add-archive-files files)))
22617 (dolist (f extra)
22618 (unless (member (file-truename f) tnames)
22619 (unless (member f files) (setq files (append files (list f))))
22620 (setq tnames (append tnames (list (file-truename f))))))
22621 (multi-occur
22622 (mapcar (lambda (x)
22623 (with-current-buffer
22624 ;; FIXME: Why not just (find-file-noselect x)?
22625 ;; Is it to avoid the "revert buffer" prompt?
22626 (or (get-file-buffer x) (find-file-noselect x))
22627 (widen)
22628 (current-buffer)))
22629 files)
22630 regexp)))
22632 (if (boundp 'occur-mode-find-occurrence-hook)
22633 ;; Emacs 23
22634 (add-hook 'occur-mode-find-occurrence-hook
22635 (lambda ()
22636 (when (derived-mode-p 'org-mode)
22637 (org-reveal))))
22638 ;; Emacs 22
22639 (defadvice occur-mode-goto-occurrence
22640 (after org-occur-reveal activate)
22641 (and (derived-mode-p 'org-mode) (org-reveal)))
22642 (defadvice occur-mode-goto-occurrence-other-window
22643 (after org-occur-reveal activate)
22644 (and (derived-mode-p 'org-mode) (org-reveal)))
22645 (defadvice occur-mode-display-occurrence
22646 (after org-occur-reveal activate)
22647 (when (derived-mode-p 'org-mode)
22648 (let ((pos (occur-mode-find-occurrence)))
22649 (with-current-buffer (marker-buffer pos)
22650 (save-excursion
22651 (goto-char pos)
22652 (org-reveal)))))))
22654 (defun org-occur-link-in-agenda-files ()
22655 "Create a link and search for it in the agendas.
22656 The link is not stored in `org-stored-links', it is just created
22657 for the search purpose."
22658 (interactive)
22659 (let ((link (condition-case nil
22660 (org-store-link nil)
22661 (error "Unable to create a link to here"))))
22662 (org-occur-in-agenda-files (regexp-quote link))))
22664 (defun org-reverse-string (string)
22665 "Return the reverse of STRING."
22666 (apply 'string (reverse (string-to-list string))))
22668 ;; defsubst org-uniquify must be defined before first use
22670 (defun org-uniquify-alist (alist)
22671 "Merge elements of ALIST with the same key.
22673 For example, in this alist:
22675 \(org-uniquify-alist \\='((a 1) (b 2) (a 3)))
22676 => \\='((a 1 3) (b 2))
22678 merge (a 1) and (a 3) into (a 1 3).
22680 The function returns the new ALIST."
22681 (let (rtn)
22682 (dolist (e alist rtn)
22683 (let (n)
22684 (if (not (assoc (car e) rtn))
22685 (push e rtn)
22686 (setq n (cons (car e) (append (cdr (assoc (car e) rtn)) (cdr e))))
22687 (setq rtn (assq-delete-all (car e) rtn))
22688 (push n rtn))))))
22690 (defun org-delete-all (elts list)
22691 "Remove all elements in ELTS from LIST."
22692 (while elts
22693 (setq list (delete (pop elts) list)))
22694 list)
22696 (defun org-back-over-empty-lines ()
22697 "Move backwards over whitespace, to the beginning of the first empty line.
22698 Returns the number of empty lines passed."
22699 (let ((pos (point)))
22700 (if (cdr (assoc 'heading org-blank-before-new-entry))
22701 (skip-chars-backward " \t\n\r")
22702 (unless (eobp)
22703 (forward-line -1)))
22704 (beginning-of-line 2)
22705 (goto-char (min (point) pos))
22706 (count-lines (point) pos)))
22708 (defun org-skip-whitespace ()
22709 (skip-chars-forward " \t\n\r"))
22711 (defun org-point-in-group (point group &optional context)
22712 "Check if POINT is in match-group GROUP.
22713 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
22714 match. If the match group does not exist or point is not inside it,
22715 return nil."
22716 (and (match-beginning group)
22717 (>= point (match-beginning group))
22718 (<= point (match-end group))
22719 (if context
22720 (list context (match-beginning group) (match-end group))
22721 t)))
22723 (defun org-switch-to-buffer-other-window (&rest args)
22724 "Switch to buffer in a second window on the current frame.
22725 In particular, do not allow pop-up frames.
22726 Returns the newly created buffer."
22727 (org-no-popups
22728 (apply 'switch-to-buffer-other-window args)))
22730 (defun org-combine-plists (&rest plists)
22731 "Create a single property list from all plists in PLISTS.
22732 The process starts by copying the first list, and then setting properties
22733 from the other lists. Settings in the last list are the most significant
22734 ones and overrule settings in the other lists."
22735 (let ((rtn (copy-sequence (pop plists)))
22736 p v ls)
22737 (while plists
22738 (setq ls (pop plists))
22739 (while ls
22740 (setq p (pop ls) v (pop ls))
22741 (setq rtn (plist-put rtn p v))))
22742 rtn))
22744 (defun org-replace-escapes (string table)
22745 "Replace %-escapes in STRING with values in TABLE.
22746 TABLE is an association list with keys like \"%a\" and string values.
22747 The sequences in STRING may contain normal field width and padding information,
22748 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
22749 so values can contain further %-escapes if they are define later in TABLE."
22750 (let ((tbl (copy-alist table))
22751 (case-fold-search nil)
22752 (pchg 0)
22753 re rpl)
22754 (dolist (e tbl)
22755 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
22756 (when (and (cdr e) (string-match re (cdr e)))
22757 (let ((sref (substring (cdr e) (match-beginning 0) (match-end 0)))
22758 (safe "SREF"))
22759 (add-text-properties 0 3 (list 'sref sref) safe)
22760 (setcdr e (replace-match safe t t (cdr e)))))
22761 (while (string-match re string)
22762 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
22763 (cdr e)))
22764 (setq string (replace-match rpl t t string))))
22765 (while (setq pchg (next-property-change pchg string))
22766 (let ((sref (get-text-property pchg 'sref string)))
22767 (when (and sref (string-match "SREF" string pchg))
22768 (setq string (replace-match sref t t string)))))
22769 string))
22771 (defun org-sublist (list start end)
22772 "Return a section of LIST, from START to END.
22774 Counting starts at 1."
22775 (cl-subseq list (1- start) end))
22776 (make-obsolete 'org-sublist "cl-subseq (note the 0-based counting)." "Org 9.0")
22778 (defun org-find-base-buffer-visiting (file)
22779 "Like `find-buffer-visiting' but always return the base buffer and
22780 not an indirect buffer."
22781 (let ((buf (or (get-file-buffer file)
22782 (find-buffer-visiting file))))
22783 (if buf
22784 (or (buffer-base-buffer buf) buf)
22785 nil)))
22787 (define-obsolete-function-alias 'org-image-file-name-regexp 'image-file-name-regexp
22788 "Org 9.0")
22790 ;;; TODO: Only called once, from ox-odt which should probably use
22791 ;;; org-export-inline-image-p or something.
22792 (defun org-file-image-p (file)
22793 "Return non-nil if FILE is an image."
22794 (save-match-data
22795 (string-match (image-file-name-regexp) file)))
22797 (defun org-get-cursor-date (&optional with-time)
22798 "Return the date at cursor in as a time.
22799 This works in the calendar and in the agenda, anywhere else it just
22800 returns the current time.
22801 If WITH-TIME is non-nil, returns the time of the event at point (in
22802 the agenda) or the current time of the day."
22803 (let (date day defd tp hod mod)
22804 (when with-time
22805 (setq tp (get-text-property (point) 'time))
22806 (when (and tp (string-match "\\([0-9][0-9]\\):\\([0-9][0-9]\\)" tp))
22807 (setq hod (string-to-number (match-string 1 tp))
22808 mod (string-to-number (match-string 2 tp))))
22809 (or tp (let ((now (decode-time)))
22810 (setq hod (nth 2 now)
22811 mod (nth 1 now)))))
22812 (cond
22813 ((eq major-mode 'calendar-mode)
22814 (setq date (calendar-cursor-to-date)
22815 defd (encode-time 0 (or mod 0) (or hod 0)
22816 (nth 1 date) (nth 0 date) (nth 2 date))))
22817 ((eq major-mode 'org-agenda-mode)
22818 (setq day (get-text-property (point) 'day))
22819 (when day
22820 (setq date (calendar-gregorian-from-absolute day)
22821 defd (encode-time 0 (or mod 0) (or hod 0)
22822 (nth 1 date) (nth 0 date) (nth 2 date))))))
22823 (or defd (current-time))))
22825 (defun org-mark-subtree (&optional up)
22826 "Mark the current subtree.
22827 This puts point at the start of the current subtree, and mark at
22828 the end. If a numeric prefix UP is given, move up into the
22829 hierarchy of headlines by UP levels before marking the subtree."
22830 (interactive "P")
22831 (org-with-limited-levels
22832 (cond ((org-at-heading-p) (beginning-of-line))
22833 ((org-before-first-heading-p) (user-error "Not in a subtree"))
22834 (t (outline-previous-visible-heading 1))))
22835 (when up (while (and (> up 0) (org-up-heading-safe)) (cl-decf up)))
22836 (if (org-called-interactively-p 'any)
22837 (call-interactively 'org-mark-element)
22838 (org-mark-element)))
22841 ;;; Indentation
22843 (defun org--get-expected-indentation (element contentsp)
22844 "Expected indentation column for current line, according to ELEMENT.
22845 ELEMENT is an element containing point. CONTENTSP is non-nil
22846 when indentation is to be computed according to contents of
22847 ELEMENT."
22848 (let ((type (org-element-type element))
22849 (start (org-element-property :begin element))
22850 (post-affiliated (org-element-property :post-affiliated element)))
22851 (org-with-wide-buffer
22852 (cond
22853 (contentsp
22854 (cl-case type
22855 ((diary-sexp footnote-definition) 0)
22856 ((headline inlinetask nil)
22857 (if (not org-adapt-indentation) 0
22858 (let ((level (org-current-level)))
22859 (if level (1+ level) 0))))
22860 ((item plain-list) (org-list-item-body-column post-affiliated))
22862 (goto-char start)
22863 (org-get-indentation))))
22864 ((memq type '(headline inlinetask nil))
22865 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*$"))
22866 (org--get-expected-indentation element t)
22868 ((memq type '(diary-sexp footnote-definition)) 0)
22869 ;; First paragraph of a footnote definition or an item.
22870 ;; Indent like parent.
22871 ((< (line-beginning-position) start)
22872 (org--get-expected-indentation
22873 (org-element-property :parent element) t))
22874 ;; At first line: indent according to previous sibling, if any,
22875 ;; ignoring footnote definitions and inline tasks, or parent's
22876 ;; contents.
22877 ((= (line-beginning-position) start)
22878 (catch 'exit
22879 (while t
22880 (if (= (point-min) start) (throw 'exit 0)
22881 (goto-char (1- start))
22882 (let* ((previous (org-element-at-point))
22883 (parent previous))
22884 (while (and parent (<= (org-element-property :end parent) start))
22885 (setq previous parent
22886 parent (org-element-property :parent parent)))
22887 (cond
22888 ((not previous) (throw 'exit 0))
22889 ((> (org-element-property :end previous) start)
22890 (throw 'exit (org--get-expected-indentation previous t)))
22891 ((memq (org-element-type previous)
22892 '(footnote-definition inlinetask))
22893 (setq start (org-element-property :begin previous)))
22894 (t (goto-char (org-element-property :begin previous))
22895 (throw 'exit
22896 (if (bolp) (org-get-indentation)
22897 ;; At first paragraph in an item or
22898 ;; a footnote definition.
22899 (org--get-expected-indentation
22900 (org-element-property :parent previous) t))))))))))
22901 ;; Otherwise, move to the first non-blank line above.
22903 (beginning-of-line)
22904 (let ((pos (point)))
22905 (skip-chars-backward " \r\t\n")
22906 (cond
22907 ;; Two blank lines end a footnote definition or a plain
22908 ;; list. When we indent an empty line after them, the
22909 ;; containing list or footnote definition is over, so it
22910 ;; qualifies as a previous sibling. Therefore, we indent
22911 ;; like its first line.
22912 ((and (memq type '(footnote-definition plain-list))
22913 (> (count-lines (point) pos) 2))
22914 (goto-char start)
22915 (org-get-indentation))
22916 ;; Line above is the first one of a paragraph at the
22917 ;; beginning of an item or a footnote definition. Indent
22918 ;; like parent.
22919 ((< (line-beginning-position) start)
22920 (org--get-expected-indentation
22921 (org-element-property :parent element) t))
22922 ;; Line above is the beginning of an element, i.e., point
22923 ;; was originally on the blank lines between element's start
22924 ;; and contents.
22925 ((= (line-beginning-position) post-affiliated)
22926 (org--get-expected-indentation element t))
22927 ;; POS is after contents in a greater element. Indent like
22928 ;; the beginning of the element.
22930 ;; As a special case, if point is at the end of a footnote
22931 ;; definition or an item, indent like the very last element
22932 ;; within. If that last element is an item, indent like its
22933 ;; contents.
22934 ((and (not (eq type 'paragraph))
22935 (let ((cend (org-element-property :contents-end element)))
22936 (and cend (<= cend pos))))
22937 (if (memq type '(footnote-definition item plain-list))
22938 (let ((last (org-element-at-point)))
22939 (org--get-expected-indentation
22940 last (eq (org-element-type last) 'item)))
22941 (goto-char start)
22942 (org-get-indentation)))
22943 ;; In any other case, indent like the current line.
22944 (t (org-get-indentation)))))))))
22946 (defun org--align-node-property ()
22947 "Align node property at point.
22948 Alignment is done according to `org-property-format', which see."
22949 (when (save-excursion
22950 (beginning-of-line)
22951 (looking-at org-property-re))
22952 (replace-match
22953 (concat (match-string 4)
22954 (org-trim
22955 (format org-property-format (match-string 1) (match-string 3))))
22956 t t)))
22958 (defun org-indent-line ()
22959 "Indent line depending on context.
22961 Indentation is done according to the following rules:
22963 - Footnote definitions, diary sexps, headlines and inline tasks
22964 have to start at column 0.
22966 - On the very first line of an element, consider, in order, the
22967 next rules until one matches:
22969 1. If there's a sibling element before, ignoring footnote
22970 definitions and inline tasks, indent like its first line.
22972 2. If element has a parent, indent like its contents. More
22973 precisely, if parent is an item, indent after the
22974 description part, if any, or the bullet (see
22975 `org-list-description-max-indent'). Else, indent like
22976 parent's first line.
22978 3. Otherwise, indent relatively to current level, if
22979 `org-adapt-indentation' is non-nil, or to left margin.
22981 - On a blank line at the end of an element, indent according to
22982 the type of the element. More precisely
22984 1. If element is a plain list, an item, or a footnote
22985 definition, indent like the very last element within.
22987 2. If element is a paragraph, indent like its last non blank
22988 line.
22990 3. Otherwise, indent like its very first line.
22992 - In the code part of a source block, use language major mode
22993 to indent current line if `org-src-tab-acts-natively' is
22994 non-nil. If it is nil, do nothing.
22996 - Otherwise, indent like the first non-blank line above.
22998 The function doesn't indent an item as it could break the whole
22999 list structure. Instead, use \\<org-mode-map>\\[org-shiftmetaleft] or \
23000 \\[org-shiftmetaright].
23002 Also align node properties according to `org-property-format'."
23003 (interactive)
23004 (cond
23005 (orgstruct-is-++
23006 (let ((indent-line-function
23007 (cl-cadadr (assq 'indent-line-function org-fb-vars))))
23008 (indent-according-to-mode)))
23009 ((org-at-heading-p) 'noindent)
23011 (let* ((element (save-excursion (beginning-of-line) (org-element-at-point)))
23012 (type (org-element-type element)))
23013 (cond ((and (memq type '(plain-list item))
23014 (= (line-beginning-position)
23015 (org-element-property :post-affiliated element)))
23016 'noindent)
23017 ((and (eq type 'src-block)
23018 org-src-tab-acts-natively
23019 (> (line-beginning-position)
23020 (org-element-property :post-affiliated element))
23021 (< (line-beginning-position)
23022 (org-with-wide-buffer
23023 (goto-char (org-element-property :end element))
23024 (skip-chars-backward " \r\t\n")
23025 (line-beginning-position))))
23026 (org-babel-do-key-sequence-in-edit-buffer (kbd "TAB")))
23028 (let ((column (org--get-expected-indentation element nil)))
23029 ;; Preserve current column.
23030 (if (<= (current-column) (current-indentation))
23031 (org-indent-line-to column)
23032 (save-excursion (org-indent-line-to column))))
23033 ;; Align node property. Also preserve current column.
23034 (when (eq type 'node-property)
23035 (let ((column (current-column)))
23036 (org--align-node-property)
23037 (org-move-to-column column)))))))))
23039 (defun org-indent-region (start end)
23040 "Indent each non-blank line in the region.
23041 Called from a program, START and END specify the region to
23042 indent. The function will not indent contents of example blocks,
23043 verse blocks and export blocks as leading white spaces are
23044 assumed to be significant there."
23045 (interactive "r")
23046 (save-excursion
23047 (goto-char start)
23048 (skip-chars-forward " \r\t\n")
23049 (unless (eobp) (beginning-of-line))
23050 (let ((indent-to
23051 (lambda (ind pos)
23052 ;; Set IND as indentation for all lines between point and
23053 ;; POS. Blank lines are ignored. Leave point after POS
23054 ;; once done.
23055 (let ((limit (copy-marker pos)))
23056 (while (< (point) limit)
23057 (unless (org-looking-at-p "[ \t]*$") (org-indent-line-to ind))
23058 (forward-line))
23059 (set-marker limit nil))))
23060 (end (copy-marker end)))
23061 (while (< (point) end)
23062 (if (or (org-looking-at-p " \r\t\n") (org-at-heading-p)) (forward-line)
23063 (let* ((element (org-element-at-point))
23064 (type (org-element-type element))
23065 (element-end (copy-marker (org-element-property :end element)))
23066 (ind (org--get-expected-indentation element nil)))
23067 (cond
23068 ((or (memq type '(paragraph table table-row))
23069 (not (or (org-element-property :contents-begin element)
23070 (memq type
23071 '(example-block export-block src-block)))))
23072 ;; Elements here are indented as a single block. Also
23073 ;; align node properties.
23074 (when (eq type 'node-property)
23075 (org--align-node-property)
23076 (beginning-of-line))
23077 (funcall indent-to ind (min element-end end)))
23079 ;; Elements in this category consist of three parts:
23080 ;; before the contents, the contents, and after the
23081 ;; contents. The contents are treated specially,
23082 ;; according to the element type, or not indented at
23083 ;; all. Other parts are indented as a single block.
23084 (let* ((post (copy-marker
23085 (org-element-property :post-affiliated element)))
23086 (cbeg
23087 (copy-marker
23088 (cond
23089 ((not (org-element-property :contents-begin element))
23090 ;; Fake contents for source blocks.
23091 (org-with-wide-buffer
23092 (goto-char post)
23093 (forward-line)
23094 (point)))
23095 ((memq type '(footnote-definition item plain-list))
23096 ;; Contents in these elements could start on
23097 ;; the same line as the beginning of the
23098 ;; element. Make sure we start indenting
23099 ;; from the second line.
23100 (org-with-wide-buffer
23101 (goto-char post)
23102 (end-of-line)
23103 (skip-chars-forward " \r\t\n")
23104 (if (eobp) (point) (line-beginning-position))))
23105 (t (org-element-property :contents-begin element)))))
23106 (cend (copy-marker
23107 (or (org-element-property :contents-end element)
23108 ;; Fake contents for source blocks.
23109 (org-with-wide-buffer
23110 (goto-char element-end)
23111 (skip-chars-backward " \r\t\n")
23112 (line-beginning-position)))
23113 t)))
23114 ;; Do not change items indentation individually as it
23115 ;; might break the list as a whole. On the other
23116 ;; hand, when at a plain list, indent it as a whole.
23117 (cond ((eq type 'plain-list)
23118 (let ((offset (- ind (org-get-indentation))))
23119 (unless (zerop offset)
23120 (indent-rigidly (org-element-property :begin element)
23121 (org-element-property :end element)
23122 offset))
23123 (goto-char cbeg)))
23124 ((eq type 'item) (goto-char cbeg))
23125 (t (funcall indent-to ind (min cbeg end))))
23126 (when (< (point) end)
23127 (cl-case type
23128 ((example-block export-block verse-block))
23129 (src-block
23130 ;; In a source block, indent source code
23131 ;; according to language major mode, but only if
23132 ;; `org-src-tab-acts-natively' is non-nil.
23133 (when (and (< (point) end) org-src-tab-acts-natively)
23134 (ignore-errors
23135 (org-babel-do-in-edit-buffer
23136 (indent-region (point-min) (point-max))))))
23137 (t (org-indent-region (point) (min cend end))))
23138 (goto-char (min cend end))
23139 (when (< (point) end)
23140 (funcall indent-to ind (min element-end end))))
23141 (set-marker post nil)
23142 (set-marker cbeg nil)
23143 (set-marker cend nil))))
23144 (set-marker element-end nil))))
23145 (set-marker end nil))))
23147 (defun org-indent-drawer ()
23148 "Indent the drawer at point."
23149 (interactive)
23150 (unless (save-excursion
23151 (beginning-of-line)
23152 (org-looking-at-p org-drawer-regexp))
23153 (user-error "Not at a drawer"))
23154 (let ((element (org-element-at-point)))
23155 (unless (memq (org-element-type element) '(drawer property-drawer))
23156 (user-error "Not at a drawer"))
23157 (org-with-wide-buffer
23158 (org-indent-region (org-element-property :begin element)
23159 (org-element-property :end element))))
23160 (message "Drawer at point indented"))
23162 (defun org-indent-block ()
23163 "Indent the block at point."
23164 (interactive)
23165 (unless (save-excursion
23166 (beginning-of-line)
23167 (let ((case-fold-search t))
23168 (org-looking-at-p "[ \t]*#\\+\\(begin\\|end\\)_")))
23169 (user-error "Not at a block"))
23170 (let ((element (org-element-at-point)))
23171 (unless (memq (org-element-type element)
23172 '(comment-block center-block dynamic-block example-block
23173 export-block quote-block special-block
23174 src-block verse-block))
23175 (user-error "Not at a block"))
23176 (org-with-wide-buffer
23177 (org-indent-region (org-element-property :begin element)
23178 (org-element-property :end element))))
23179 (message "Block at point indented"))
23182 ;;; Filling
23184 ;; We use our own fill-paragraph and auto-fill functions.
23186 ;; `org-fill-paragraph' relies on adaptive filling and context
23187 ;; checking. Appropriate `fill-prefix' is computed with
23188 ;; `org-adaptive-fill-function'.
23190 ;; `org-auto-fill-function' takes care of auto-filling. It calls
23191 ;; `do-auto-fill' only on valid areas with `fill-prefix' shadowed with
23192 ;; `org-adaptive-fill-function' value. Internally,
23193 ;; `org-comment-line-break-function' breaks the line.
23195 ;; `org-setup-filling' installs filling and auto-filling related
23196 ;; variables during `org-mode' initialization.
23198 (defvar org-element-paragraph-separate) ; org-element.el
23199 (defun org-setup-filling ()
23200 (require 'org-element)
23201 ;; Prevent auto-fill from inserting unwanted new items.
23202 (when (boundp 'fill-nobreak-predicate)
23203 (setq-local
23204 fill-nobreak-predicate
23205 (org-uniquify
23206 (append fill-nobreak-predicate
23207 '(org-fill-line-break-nobreak-p
23208 org-fill-paragraph-with-timestamp-nobreak-p)))))
23209 (let ((paragraph-ending (substring org-element-paragraph-separate 1)))
23210 (setq-local paragraph-start paragraph-ending)
23211 (setq-local paragraph-separate paragraph-ending))
23212 (setq-local fill-paragraph-function 'org-fill-paragraph)
23213 (setq-local auto-fill-inhibit-regexp nil)
23214 (setq-local adaptive-fill-function 'org-adaptive-fill-function)
23215 (setq-local normal-auto-fill-function 'org-auto-fill-function)
23216 (setq-local comment-line-break-function 'org-comment-line-break-function))
23218 (defun org-fill-line-break-nobreak-p ()
23219 "Non-nil when a new line at point would create an Org line break."
23220 (save-excursion
23221 (skip-chars-backward "[ \t]")
23222 (skip-chars-backward "\\\\")
23223 (looking-at "\\\\\\\\\\($\\|[^\\\\]\\)")))
23225 (defun org-fill-paragraph-with-timestamp-nobreak-p ()
23226 "Non-nil when a new line at point would split a timestamp."
23227 (and (org-at-timestamp-p t)
23228 (not (looking-at org-ts-regexp-both))))
23230 (declare-function message-in-body-p "message" ())
23231 (defvar orgtbl-line-start-regexp) ; From org-table.el
23232 (defun org-adaptive-fill-function ()
23233 "Compute a fill prefix for the current line.
23234 Return fill prefix, as a string, or nil if current line isn't
23235 meant to be filled. For convenience, if `adaptive-fill-regexp'
23236 matches in paragraphs or comments, use it."
23237 (catch 'exit
23238 (when (derived-mode-p 'message-mode)
23239 (save-excursion
23240 (beginning-of-line)
23241 (cond ((not (message-in-body-p)) (throw 'exit nil))
23242 ((org-looking-at-p org-table-line-regexp) (throw 'exit nil))
23243 ((looking-at message-cite-prefix-regexp)
23244 (throw 'exit (match-string-no-properties 0)))
23245 ((looking-at org-outline-regexp)
23246 (throw 'exit (make-string (length (match-string 0)) ?\s))))))
23247 (org-with-wide-buffer
23248 (unless (org-at-heading-p)
23249 (let* ((p (line-beginning-position))
23250 (element (save-excursion
23251 (beginning-of-line)
23252 (org-element-at-point)))
23253 (type (org-element-type element))
23254 (post-affiliated (org-element-property :post-affiliated element)))
23255 (unless (< p post-affiliated)
23256 (cl-case type
23257 (comment
23258 (save-excursion
23259 (beginning-of-line)
23260 (looking-at "[ \t]*")
23261 (concat (match-string 0) "# ")))
23262 (footnote-definition "")
23263 ((item plain-list)
23264 (make-string (org-list-item-body-column post-affiliated) ?\s))
23265 (paragraph
23266 ;; Fill prefix is usually the same as the current line,
23267 ;; unless the paragraph is at the beginning of an item.
23268 (let ((parent (org-element-property :parent element)))
23269 (save-excursion
23270 (beginning-of-line)
23271 (cond ((eq (org-element-type parent) 'item)
23272 (make-string (org-list-item-body-column
23273 (org-element-property :begin parent))
23274 ?\s))
23275 ((and adaptive-fill-regexp
23276 ;; Locally disable
23277 ;; `adaptive-fill-function' to let
23278 ;; `fill-context-prefix' handle
23279 ;; `adaptive-fill-regexp' variable.
23280 (let (adaptive-fill-function)
23281 (fill-context-prefix
23282 post-affiliated
23283 (org-element-property :end element)))))
23284 ((looking-at "[ \t]+") (match-string 0))
23285 (t "")))))
23286 (comment-block
23287 ;; Only fill contents if P is within block boundaries.
23288 (let* ((cbeg (save-excursion (goto-char post-affiliated)
23289 (forward-line)
23290 (point)))
23291 (cend (save-excursion
23292 (goto-char (org-element-property :end element))
23293 (skip-chars-backward " \r\t\n")
23294 (line-beginning-position))))
23295 (when (and (>= p cbeg) (< p cend))
23296 (if (save-excursion (beginning-of-line) (looking-at "[ \t]+"))
23297 (match-string 0)
23298 "")))))))))))
23300 (declare-function message-goto-body "message" ())
23301 (defvar message-cite-prefix-regexp) ; From message.el
23302 (defun org-fill-paragraph (&optional justify)
23303 "Fill element at point, when applicable.
23305 This function only applies to comment blocks, comments, example
23306 blocks and paragraphs. Also, as a special case, re-align table
23307 when point is at one.
23309 If JUSTIFY is non-nil (interactively, with prefix argument),
23310 justify as well. If `sentence-end-double-space' is non-nil, then
23311 period followed by one space does not end a sentence, so don't
23312 break a line there. The variable `fill-column' controls the
23313 width for filling.
23315 For convenience, when point is at a plain list, an item or
23316 a footnote definition, try to fill the first paragraph within."
23317 (interactive)
23318 (if (and (derived-mode-p 'message-mode)
23319 (or (not (message-in-body-p))
23320 (save-excursion (move-beginning-of-line 1)
23321 (looking-at message-cite-prefix-regexp))))
23322 ;; First ensure filling is correct in message-mode.
23323 (let ((fill-paragraph-function
23324 (cl-cadadr (assq 'fill-paragraph-function org-fb-vars)))
23325 (fill-prefix (cl-cadadr (assq 'fill-prefix org-fb-vars)))
23326 (paragraph-start (cl-cadadr (assq 'paragraph-start org-fb-vars)))
23327 (paragraph-separate
23328 (cl-cadadr (assq 'paragraph-separate org-fb-vars))))
23329 (fill-paragraph nil))
23330 (with-syntax-table org-mode-transpose-word-syntax-table
23331 ;; Move to end of line in order to get the first paragraph
23332 ;; within a plain list or a footnote definition.
23333 (let ((element (save-excursion
23334 (end-of-line)
23335 (or (ignore-errors (org-element-at-point))
23336 (user-error "An element cannot be parsed line %d"
23337 (line-number-at-pos (point)))))))
23338 ;; First check if point is in a blank line at the beginning of
23339 ;; the buffer. In that case, ignore filling.
23340 (cl-case (org-element-type element)
23341 ;; Use major mode filling function is src blocks.
23342 (src-block (org-babel-do-key-sequence-in-edit-buffer (kbd "M-q")))
23343 ;; Align Org tables, leave table.el tables as-is.
23344 (table-row (org-table-align) t)
23345 (table
23346 (when (eq (org-element-property :type element) 'org)
23347 (save-excursion
23348 (goto-char (org-element-property :post-affiliated element))
23349 (org-table-align)))
23351 (paragraph
23352 ;; Paragraphs may contain `line-break' type objects.
23353 (let ((beg (max (point-min)
23354 (org-element-property :contents-begin element)))
23355 (end (min (point-max)
23356 (org-element-property :contents-end element))))
23357 ;; Do nothing if point is at an affiliated keyword.
23358 (if (< (line-end-position) beg) t
23359 (when (derived-mode-p 'message-mode)
23360 ;; In `message-mode', do not fill following citation
23361 ;; in current paragraph nor text before message body.
23362 (let ((body-start (save-excursion (message-goto-body))))
23363 (when body-start (setq beg (max body-start beg))))
23364 (when (save-excursion
23365 (re-search-forward
23366 (concat "^" message-cite-prefix-regexp) end t))
23367 (setq end (match-beginning 0))))
23368 ;; Fill paragraph, taking line breaks into account.
23369 (save-excursion
23370 (goto-char beg)
23371 (let ((cuts (list beg)))
23372 (while (re-search-forward "\\\\\\\\[ \t]*\n" end t)
23373 (when (eq 'line-break
23374 (org-element-type
23375 (save-excursion (backward-char)
23376 (org-element-context))))
23377 (push (point) cuts)))
23378 (dolist (c (delq end cuts))
23379 (fill-region-as-paragraph c end justify)
23380 (setq end c))))
23381 t)))
23382 ;; Contents of `comment-block' type elements should be
23383 ;; filled as plain text, but only if point is within block
23384 ;; markers.
23385 (comment-block
23386 (let* ((case-fold-search t)
23387 (beg (save-excursion
23388 (goto-char (org-element-property :begin element))
23389 (re-search-forward "^[ \t]*#\\+begin_comment" nil t)
23390 (forward-line)
23391 (point)))
23392 (end (save-excursion
23393 (goto-char (org-element-property :end element))
23394 (re-search-backward "^[ \t]*#\\+end_comment" nil t)
23395 (line-beginning-position))))
23396 (if (or (< (point) beg) (> (point) end)) t
23397 (fill-region-as-paragraph
23398 (save-excursion (end-of-line)
23399 (re-search-backward "^[ \t]*$" beg 'move)
23400 (line-beginning-position))
23401 (save-excursion (beginning-of-line)
23402 (re-search-forward "^[ \t]*$" end 'move)
23403 (line-beginning-position))
23404 justify))))
23405 ;; Fill comments.
23406 (comment
23407 (let ((begin (org-element-property :post-affiliated element))
23408 (end (org-element-property :end element)))
23409 (when (and (>= (point) begin) (<= (point) end))
23410 (let ((begin (save-excursion
23411 (end-of-line)
23412 (if (re-search-backward "^[ \t]*#[ \t]*$" begin t)
23413 (progn (forward-line) (point))
23414 begin)))
23415 (end (save-excursion
23416 (end-of-line)
23417 (if (re-search-forward "^[ \t]*#[ \t]*$" end 'move)
23418 (1- (line-beginning-position))
23419 (skip-chars-backward " \r\t\n")
23420 (line-end-position)))))
23421 ;; Do not fill comments when at a blank line.
23422 (when (> end begin)
23423 (let ((fill-prefix
23424 (save-excursion
23425 (beginning-of-line)
23426 (looking-at "[ \t]*#")
23427 (let ((comment-prefix (match-string 0)))
23428 (goto-char (match-end 0))
23429 (if (looking-at adaptive-fill-regexp)
23430 (concat comment-prefix (match-string 0))
23431 (concat comment-prefix " "))))))
23432 (save-excursion
23433 (fill-region-as-paragraph begin end justify))))))
23435 ;; Ignore every other element.
23436 (otherwise t))))))
23438 (defun org-auto-fill-function ()
23439 "Auto-fill function."
23440 ;; Check if auto-filling is meaningful.
23441 (let ((fc (current-fill-column)))
23442 (when (and fc (> (current-column) fc))
23443 (let* ((fill-prefix (org-adaptive-fill-function))
23444 ;; Enforce empty fill prefix, if required. Otherwise, it
23445 ;; will be computed again.
23446 (adaptive-fill-mode (not (equal fill-prefix ""))))
23447 (when fill-prefix (do-auto-fill))))))
23449 (defun org-comment-line-break-function (&optional soft)
23450 "Break line at point and indent, continuing comment if within one.
23451 The inserted newline is marked hard if variable
23452 `use-hard-newlines' is true, unless optional argument SOFT is
23453 non-nil."
23454 (if soft (insert-and-inherit ?\n) (newline 1))
23455 (save-excursion (forward-char -1) (delete-horizontal-space))
23456 (delete-horizontal-space)
23457 (indent-to-left-margin)
23458 (insert-before-markers-and-inherit fill-prefix))
23461 ;;; Fixed Width Areas
23463 (defun org-toggle-fixed-width ()
23464 "Toggle fixed-width markup.
23466 Add or remove fixed-width markup on current line, whenever it
23467 makes sense. Return an error otherwise.
23469 If a region is active and if it contains only fixed-width areas
23470 or blank lines, remove all fixed-width markup in it. If the
23471 region contains anything else, convert all non-fixed-width lines
23472 to fixed-width ones.
23474 Blank lines at the end of the region are ignored unless the
23475 region only contains such lines."
23476 (interactive)
23477 (if (not (org-region-active-p))
23478 ;; No region:
23480 ;; Remove fixed width marker only in a fixed-with element.
23482 ;; Add fixed width maker in paragraphs, in blank lines after
23483 ;; elements or at the beginning of a headline or an inlinetask,
23484 ;; and before any one-line elements (e.g., a clock).
23485 (progn
23486 (beginning-of-line)
23487 (let* ((element (org-element-at-point))
23488 (type (org-element-type element)))
23489 (cond
23490 ((and (eq type 'fixed-width)
23491 (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)"))
23492 (replace-match
23493 "" nil nil nil (if (= (line-end-position) (match-end 0)) 0 1)))
23494 ((and (memq type '(babel-call clock comment diary-sexp headline
23495 horizontal-rule keyword paragraph
23496 planning))
23497 (<= (org-element-property :post-affiliated element) (point)))
23498 (skip-chars-forward " \t")
23499 (insert ": "))
23500 ((and (org-looking-at-p "[ \t]*$")
23501 (or (eq type 'inlinetask)
23502 (save-excursion
23503 (skip-chars-forward " \r\t\n")
23504 (<= (org-element-property :end element) (point)))))
23505 (delete-region (point) (line-end-position))
23506 (org-indent-line)
23507 (insert ": "))
23508 (t (user-error "Cannot insert a fixed-width line here")))))
23509 ;; Region active.
23510 (let* ((begin (save-excursion
23511 (goto-char (region-beginning))
23512 (line-beginning-position)))
23513 (end (copy-marker
23514 (save-excursion
23515 (goto-char (region-end))
23516 (unless (eolp) (beginning-of-line))
23517 (if (save-excursion (re-search-backward "\\S-" begin t))
23518 (progn (skip-chars-backward " \r\t\n") (point))
23519 (point)))))
23520 (all-fixed-width-p
23521 (catch 'not-all-p
23522 (save-excursion
23523 (goto-char begin)
23524 (skip-chars-forward " \r\t\n")
23525 (when (eobp) (throw 'not-all-p nil))
23526 (while (< (point) end)
23527 (let ((element (org-element-at-point)))
23528 (if (eq (org-element-type element) 'fixed-width)
23529 (goto-char (org-element-property :end element))
23530 (throw 'not-all-p nil))))
23531 t))))
23532 (if all-fixed-width-p
23533 (save-excursion
23534 (goto-char begin)
23535 (while (< (point) end)
23536 (when (looking-at "[ \t]*\\(:\\(?: \\|$\\)\\)")
23537 (replace-match
23538 "" nil nil nil
23539 (if (= (line-end-position) (match-end 0)) 0 1)))
23540 (forward-line)))
23541 (let ((min-ind (point-max)))
23542 ;; Find minimum indentation across all lines.
23543 (save-excursion
23544 (goto-char begin)
23545 (if (not (save-excursion (re-search-forward "\\S-" end t)))
23546 (setq min-ind 0)
23547 (catch 'zerop
23548 (while (< (point) end)
23549 (unless (org-looking-at-p "[ \t]*$")
23550 (let ((ind (org-get-indentation)))
23551 (setq min-ind (min min-ind ind))
23552 (when (zerop ind) (throw 'zerop t))))
23553 (forward-line)))))
23554 ;; Loop over all lines and add fixed-width markup everywhere
23555 ;; but in fixed-width lines.
23556 (save-excursion
23557 (goto-char begin)
23558 (while (< (point) end)
23559 (cond
23560 ((org-at-heading-p)
23561 (insert ": ")
23562 (forward-line)
23563 (while (and (< (point) end) (org-looking-at-p "[ \t]*$"))
23564 (insert ":")
23565 (forward-line)))
23566 ((org-looking-at-p "[ \t]*:\\( \\|$\\)")
23567 (let* ((element (org-element-at-point))
23568 (element-end (org-element-property :end element)))
23569 (if (eq (org-element-type element) 'fixed-width)
23570 (progn (goto-char element-end)
23571 (skip-chars-backward " \r\t\n")
23572 (forward-line))
23573 (let ((limit (min end element-end)))
23574 (while (< (point) limit)
23575 (org-move-to-column min-ind t)
23576 (insert ": ")
23577 (forward-line))))))
23579 (org-move-to-column min-ind t)
23580 (insert ": ")
23581 (forward-line)))))))
23582 (set-marker end nil))))
23585 ;;; Comments
23587 ;; Org comments syntax is quite complex. It requires the entire line
23588 ;; to be just a comment. Also, even with the right syntax at the
23589 ;; beginning of line, some some elements (i.e. verse-block or
23590 ;; example-block) don't accept comments. Usual Emacs comment commands
23591 ;; cannot cope with those requirements. Therefore, Org replaces them.
23593 ;; Org still relies on `comment-dwim', but cannot trust
23594 ;; `comment-only-p'. So, `comment-region-function' and
23595 ;; `uncomment-region-function' both point
23596 ;; to`org-comment-or-uncomment-region'. Eventually,
23597 ;; `org-insert-comment' takes care of insertion of comments at the
23598 ;; beginning of line.
23600 ;; `org-setup-comments-handling' install comments related variables
23601 ;; during `org-mode' initialization.
23603 (defun org-setup-comments-handling ()
23604 (interactive)
23605 (setq-local comment-use-syntax nil)
23606 (setq-local comment-start "# ")
23607 (setq-local comment-start-skip "^\\s-*#\\(?: \\|$\\)")
23608 (setq-local comment-insert-comment-function 'org-insert-comment)
23609 (setq-local comment-region-function 'org-comment-or-uncomment-region)
23610 (setq-local uncomment-region-function 'org-comment-or-uncomment-region))
23612 (defun org-insert-comment ()
23613 "Insert an empty comment above current line.
23614 If the line is empty, insert comment at its beginning. When
23615 point is within a source block, comment according to the related
23616 major mode."
23617 (if (let ((element (org-element-at-point)))
23618 (and (eq (org-element-type element) 'src-block)
23619 (< (save-excursion
23620 (goto-char (org-element-property :post-affiliated element))
23621 (line-end-position))
23622 (point))
23623 (> (save-excursion
23624 (goto-char (org-element-property :end element))
23625 (skip-chars-backward " \r\t\n")
23626 (line-beginning-position))
23627 (point))))
23628 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23629 (beginning-of-line)
23630 (if (looking-at "\\s-*$") (delete-region (point) (point-at-eol))
23631 (open-line 1))
23632 (org-indent-line)
23633 (insert "# ")))
23635 (defvar comment-empty-lines) ; From newcomment.el.
23636 (defun org-comment-or-uncomment-region (beg end &rest _)
23637 "Comment or uncomment each non-blank line in the region.
23638 Uncomment each non-blank line between BEG and END if it only
23639 contains commented lines. Otherwise, comment them. If region is
23640 strictly within a source block, use appropriate comment syntax."
23641 (if (let ((element (org-element-at-point)))
23642 (and (eq (org-element-type element) 'src-block)
23643 (< (save-excursion
23644 (goto-char (org-element-property :post-affiliated element))
23645 (line-end-position))
23646 beg)
23647 (>= (save-excursion
23648 (goto-char (org-element-property :end element))
23649 (skip-chars-backward " \r\t\n")
23650 (line-beginning-position))
23651 end)))
23652 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23653 (save-restriction
23654 ;; Restrict region
23655 (narrow-to-region (save-excursion (goto-char beg)
23656 (skip-chars-forward " \r\t\n" end)
23657 (line-beginning-position))
23658 (save-excursion (goto-char end)
23659 (skip-chars-backward " \r\t\n" beg)
23660 (line-end-position)))
23661 (let ((uncommentp
23662 ;; UNCOMMENTP is non-nil when every non blank line between
23663 ;; BEG and END is a comment.
23664 (save-excursion
23665 (goto-char (point-min))
23666 (while (and (not (eobp))
23667 (let ((element (org-element-at-point)))
23668 (and (eq (org-element-type element) 'comment)
23669 (goto-char (min (point-max)
23670 (org-element-property
23671 :end element)))))))
23672 (eobp))))
23673 (if uncommentp
23674 ;; Only blank lines and comments in region: uncomment it.
23675 (save-excursion
23676 (goto-char (point-min))
23677 (while (not (eobp))
23678 (when (looking-at "[ \t]*\\(#\\(?: \\|$\\)\\)")
23679 (replace-match "" nil nil nil 1))
23680 (forward-line)))
23681 ;; Comment each line in region.
23682 (let ((min-indent (point-max)))
23683 ;; First find the minimum indentation across all lines.
23684 (save-excursion
23685 (goto-char (point-min))
23686 (while (and (not (eobp)) (not (zerop min-indent)))
23687 (unless (looking-at "[ \t]*$")
23688 (setq min-indent (min min-indent (current-indentation))))
23689 (forward-line)))
23690 ;; Then loop over all lines.
23691 (save-excursion
23692 (goto-char (point-min))
23693 (while (not (eobp))
23694 (unless (and (not comment-empty-lines) (looking-at "[ \t]*$"))
23695 ;; Don't get fooled by invisible text (e.g. link path)
23696 ;; when moving to column MIN-INDENT.
23697 (let ((buffer-invisibility-spec nil))
23698 (org-move-to-column min-indent t))
23699 (insert comment-start))
23700 (forward-line)))))))))
23702 (defun org-comment-dwim (_arg)
23703 "Call `comment-dwim' within a source edit buffer if needed."
23704 (interactive "*P")
23705 (if (org-in-src-block-p)
23706 (org-babel-do-in-edit-buffer (call-interactively 'comment-dwim))
23707 (call-interactively 'comment-dwim)))
23710 ;;; Timestamps API
23712 ;; This section contains tools to operate on timestamp objects, as
23713 ;; returned by, e.g. `org-element-context'.
23715 (defun org-timestamp--to-internal-time (timestamp &optional end)
23716 "Encode TIMESTAMP object into Emacs internal time.
23717 Use end of date range or time range when END is non-nil."
23718 (apply #'encode-time
23719 (cons 0
23720 (mapcar
23721 (lambda (prop) (or (org-element-property prop timestamp) 0))
23722 (if end '(:minute-end :hour-end :day-end :month-end :year-end)
23723 '(:minute-start :hour-start :day-start :month-start
23724 :year-start))))))
23726 (defun org-timestamp-has-time-p (timestamp)
23727 "Non-nil when TIMESTAMP has a time specified."
23728 (org-element-property :hour-start timestamp))
23730 (defun org-timestamp-format (timestamp format &optional end utc)
23731 "Format a TIMESTAMP object into a string.
23733 FORMAT is a format specifier to be passed to
23734 `format-time-string'.
23736 When optional argument END is non-nil, use end of date-range or
23737 time-range, if possible.
23739 When optional argument UTC is non-nil, time will be expressed as
23740 Universal Time."
23741 (format-time-string
23742 format (org-timestamp--to-internal-time timestamp end)
23743 (and utc t)))
23745 (defun org-timestamp-split-range (timestamp &optional end)
23746 "Extract a TIMESTAMP object from a date or time range.
23748 END, when non-nil, means extract the end of the range.
23749 Otherwise, extract its start.
23751 Return a new timestamp object."
23752 (let ((type (org-element-property :type timestamp)))
23753 (if (memq type '(active inactive diary)) timestamp
23754 (let ((split-ts (org-element-copy timestamp)))
23755 ;; Set new type.
23756 (org-element-put-property
23757 split-ts :type (if (eq type 'active-range) 'active 'inactive))
23758 ;; Copy start properties over end properties if END is
23759 ;; non-nil. Otherwise, copy end properties over `start' ones.
23760 (let ((p-alist '((:minute-start . :minute-end)
23761 (:hour-start . :hour-end)
23762 (:day-start . :day-end)
23763 (:month-start . :month-end)
23764 (:year-start . :year-end))))
23765 (dolist (p-cell p-alist)
23766 (org-element-put-property
23767 split-ts
23768 (funcall (if end #'car #'cdr) p-cell)
23769 (org-element-property
23770 (funcall (if end #'cdr #'car) p-cell) split-ts)))
23771 ;; Eventually refresh `:raw-value'.
23772 (org-element-put-property split-ts :raw-value nil)
23773 (org-element-put-property
23774 split-ts :raw-value (org-element-interpret-data split-ts)))))))
23776 (defun org-timestamp-translate (timestamp &optional boundary)
23777 "Translate TIMESTAMP object to custom format.
23779 Format string is defined in `org-time-stamp-custom-formats',
23780 which see.
23782 When optional argument BOUNDARY is non-nil, it is either the
23783 symbol `start' or `end'. In this case, only translate the
23784 starting or ending part of TIMESTAMP if it is a date or time
23785 range. Otherwise, translate both parts.
23787 Return timestamp as-is if `org-display-custom-times' is nil or if
23788 it has a `diary' type."
23789 (let ((type (org-element-property :type timestamp)))
23790 (if (or (not org-display-custom-times) (eq type 'diary))
23791 (org-element-interpret-data timestamp)
23792 (let ((fmt (funcall (if (org-timestamp-has-time-p timestamp) #'cdr #'car)
23793 org-time-stamp-custom-formats)))
23794 (if (and (not boundary) (memq type '(active-range inactive-range)))
23795 (concat (org-timestamp-format timestamp fmt)
23796 "--"
23797 (org-timestamp-format timestamp fmt t))
23798 (org-timestamp-format timestamp fmt (eq boundary 'end)))))))
23802 ;;; Other stuff.
23804 (defvar reftex-docstruct-symbol)
23805 (defvar reftex-cite-format)
23806 (defvar org--rds)
23808 (defun org-reftex-citation ()
23809 "Use reftex-citation to insert a citation into the buffer.
23810 This looks for a line like
23812 #+BIBLIOGRAPHY: foo plain option:-d
23814 and derives from it that foo.bib is the bibliography file relevant
23815 for this document. It then installs the necessary environment for RefTeX
23816 to work in this buffer and calls `reftex-citation' to insert a citation
23817 into the buffer.
23819 Export of such citations to both LaTeX and HTML is handled by the contributed
23820 package ox-bibtex by Taru Karttunen."
23821 (interactive)
23822 (let ((reftex-docstruct-symbol 'org--rds)
23823 (reftex-cite-format "\\cite{%l}")
23824 org--rds bib)
23825 (save-excursion
23826 (save-restriction
23827 (widen)
23828 (let ((case-fold-search t)
23829 (re "^[ \t]*#\\+BIBLIOGRAPHY:[ \t]+\\([^ \t\n]+\\)"))
23830 (if (not (save-excursion
23831 (or (re-search-forward re nil t)
23832 (re-search-backward re nil t))))
23833 (user-error "No bibliography defined in file")
23834 (setq bib (concat (match-string 1) ".bib")
23835 org--rds (list (list 'bib bib)))))))
23836 (call-interactively 'reftex-citation)))
23838 ;;;; Functions extending outline functionality
23840 (defun org-beginning-of-line (&optional arg)
23841 "Go to the beginning of the current line. If that is invisible, continue
23842 to a visible line beginning. This makes the function of C-a more intuitive.
23843 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
23844 first attempt, and only move to after the tags when the cursor is already
23845 beyond the end of the headline."
23846 (interactive "P")
23847 (let ((pos (point))
23848 (special (if (consp org-special-ctrl-a/e)
23849 (car org-special-ctrl-a/e)
23850 org-special-ctrl-a/e))
23851 deactivate-mark refpos)
23852 (call-interactively (if (org-bound-and-true-p visual-line-mode)
23853 #'beginning-of-visual-line
23854 #'move-beginning-of-line))
23855 (cond
23856 ((or arg (not special)))
23857 ((and (looking-at org-complex-heading-regexp)
23858 (eq (char-after (match-end 1)) ?\s))
23859 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
23860 (point-at-eol)))
23861 (goto-char
23862 (if (eq special t)
23863 (cond ((> pos refpos) refpos)
23864 ((= pos (point)) refpos)
23865 (t (point)))
23866 (cond ((> pos (point)) (point))
23867 ((not (eq last-command this-command)) (point))
23868 (t refpos)))))
23869 ((org-at-item-p)
23870 ;; Being at an item and not looking at an the item means point
23871 ;; was previously moved to beginning of a visual line, which
23872 ;; doesn't contain the item. Therefore, do nothing special,
23873 ;; just stay here.
23874 (when (looking-at org-list-full-item-re)
23875 ;; Set special position at first white space character after
23876 ;; bullet, and check-box, if any.
23877 (let ((after-bullet
23878 (let ((box (match-end 3)))
23879 (if (not box) (match-end 1)
23880 (let ((after (char-after box)))
23881 (if (and after (= after ? )) (1+ box) box))))))
23882 ;; Special case: Move point to special position when
23883 ;; currently after it or at beginning of line.
23884 (if (eq special t)
23885 (when (or (> pos after-bullet) (= (point) pos))
23886 (goto-char after-bullet))
23887 ;; Reversed case: Move point to special position when
23888 ;; point was already at beginning of line and command is
23889 ;; repeated.
23890 (when (and (= (point) pos) (eq last-command this-command))
23891 (goto-char after-bullet))))))))
23892 (setq disable-point-adjustment
23893 (or (not (invisible-p (point)))
23894 (not (invisible-p (max (point-min) (1- (point))))))))
23896 (defun org-end-of-line (&optional arg)
23897 "Go to the end of the line.
23898 If this is a headline, and `org-special-ctrl-a/e' is set, ignore
23899 tags on the first attempt, and only move to after the tags when
23900 the cursor is already beyond the end of the headline."
23901 (interactive "P")
23902 (let ((special (if (consp org-special-ctrl-a/e) (cdr org-special-ctrl-a/e)
23903 org-special-ctrl-a/e))
23904 (move-fun (cond ((org-bound-and-true-p visual-line-mode)
23905 'end-of-visual-line)
23906 ((fboundp 'move-end-of-line) 'move-end-of-line)
23907 (t 'end-of-line)))
23908 deactivate-mark)
23909 (if (or (not special) arg) (call-interactively move-fun)
23910 (let* ((element (save-excursion (beginning-of-line)
23911 (org-element-at-point)))
23912 (type (org-element-type element)))
23913 (cond
23914 ((memq type '(headline inlinetask))
23915 (let ((pos (point)))
23916 (beginning-of-line 1)
23917 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@#%:]+:\\)?[ \t]*\\)?$"))
23918 (if (eq special t)
23919 (if (or (< pos (match-beginning 1)) (= pos (match-end 0)))
23920 (goto-char (match-beginning 1))
23921 (goto-char (match-end 0)))
23922 (if (or (< pos (match-end 0))
23923 (not (eq this-command last-command)))
23924 (goto-char (match-end 0))
23925 (goto-char (match-beginning 1))))
23926 (call-interactively move-fun))))
23927 ((outline-invisible-p (line-end-position))
23928 ;; If element is hidden, `move-end-of-line' would put point
23929 ;; after it. Use `end-of-line' to stay on current line.
23930 (call-interactively 'end-of-line))
23931 (t (call-interactively move-fun)))))
23932 (org-no-warnings (and (featurep 'xemacs) (setq zmacs-region-stays t))))
23933 (setq disable-point-adjustment
23934 (or (not (invisible-p (point)))
23935 (not (invisible-p (max (point-min) (1- (point))))))))
23937 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
23938 (define-key org-mode-map "\C-e" 'org-end-of-line)
23940 (defun org-backward-sentence (&optional _arg)
23941 "Go to beginning of sentence, or beginning of table field.
23942 This will call `backward-sentence' or `org-table-beginning-of-field',
23943 depending on context."
23944 (interactive)
23945 (let* ((element (org-element-at-point))
23946 (contents-begin (org-element-property :contents-begin element))
23947 (table (org-element-lineage element '(table) t)))
23948 (if (and table
23949 (> (point) contents-begin)
23950 (<= (point) (org-element-property :contents-end table)))
23951 (call-interactively #'org-table-beginning-of-field)
23952 (save-restriction
23953 (when (and contents-begin
23954 (< (point-min) contents-begin)
23955 (> (point) contents-begin))
23956 (narrow-to-region contents-begin
23957 (org-element-property :contents-end element)))
23958 (call-interactively #'backward-sentence)))))
23960 (defun org-forward-sentence (&optional _arg)
23961 "Go to end of sentence, or end of table field.
23962 This will call `forward-sentence' or `org-table-end-of-field',
23963 depending on context."
23964 (interactive)
23965 (let* ((element (org-element-at-point))
23966 (contents-end (org-element-property :contents-end element))
23967 (table (org-element-lineage element '(table) t)))
23968 (if (and table
23969 (>= (point) (org-element-property :contents-begin table))
23970 (< (point) contents-end))
23971 (call-interactively #'org-table-end-of-field)
23972 (save-restriction
23973 (when (and contents-end
23974 (> (point-max) contents-end)
23975 ;; Skip blank lines between elements.
23976 (< (org-element-property :end element)
23977 (save-excursion (goto-char contents-end)
23978 (skip-chars-forward " \r\t\n"))))
23979 (narrow-to-region (org-element-property :contents-begin element)
23980 contents-end))
23981 (call-interactively #'forward-sentence)))))
23983 (define-key org-mode-map "\M-a" 'org-backward-sentence)
23984 (define-key org-mode-map "\M-e" 'org-forward-sentence)
23986 (defun org-kill-line (&optional _arg)
23987 "Kill line, to tags or end of line."
23988 (interactive)
23989 (cond
23990 ((or (not org-special-ctrl-k)
23991 (bolp)
23992 (not (org-at-heading-p)))
23993 (when (and (get-char-property (min (point-max) (point-at-eol)) 'invisible)
23994 org-ctrl-k-protect-subtree
23995 (or (eq org-ctrl-k-protect-subtree 'error)
23996 (not (y-or-n-p "Kill hidden subtree along with headline? "))))
23997 (user-error "C-k aborted as it would kill a hidden subtree"))
23998 (call-interactively
23999 (if (org-bound-and-true-p visual-line-mode) 'kill-visual-line 'kill-line)))
24000 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@#%:]+:\\)\\)[ \t]*$"))
24001 (kill-region (point) (match-beginning 1))
24002 (org-set-tags nil t))
24003 (t (kill-region (point) (point-at-eol)))))
24005 (define-key org-mode-map "\C-k" 'org-kill-line)
24007 (defun org-yank (&optional arg)
24008 "Yank. If the kill is a subtree, treat it specially.
24009 This command will look at the current kill and check if is a single
24010 subtree, or a series of subtrees[1]. If it passes the test, and if the
24011 cursor is at the beginning of a line or after the stars of a currently
24012 empty headline, then the yank is handled specially. How exactly depends
24013 on the value of the following variables.
24015 `org-yank-folded-subtrees'
24016 By default, this variable is non-nil, which results in subtree(s)
24017 being folded after insertion, but only if doing so would now
24018 swallow text after the yanked text.
24020 `org-yank-adjusted-subtrees'
24021 When non-nil (the default value is nil), the subtree will be
24022 promoted or demoted in order to fit into the local outline tree
24023 structure, which means that the level will be adjusted so that it
24024 becomes the smaller one of the two *visible* surrounding headings.
24026 Any prefix to this command will cause `yank' to be called directly with
24027 no special treatment. In particular, a simple \\[universal-argument] prefix \
24028 will just
24029 plainly yank the text as it is.
24031 \[1] The test checks if the first non-white line is a heading
24032 and if there are no other headings with fewer stars."
24033 (interactive "P")
24034 (org-yank-generic 'yank arg))
24036 (defun org-yank-generic (command arg)
24037 "Perform some yank-like command.
24039 This function implements the behavior described in the `org-yank'
24040 documentation. However, it has been generalized to work for any
24041 interactive command with similar behavior."
24043 ;; pretend to be command COMMAND
24044 (setq this-command command)
24046 (if arg
24047 (call-interactively command)
24049 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
24050 (and (org-kill-is-subtree-p)
24051 (or (bolp)
24052 (and (looking-at "[ \t]*$")
24053 (string-match
24054 "\\`\\*+\\'"
24055 (buffer-substring (point-at-bol) (point)))))))
24056 swallowp)
24057 (cond
24058 ((and subtreep org-yank-folded-subtrees)
24059 (let ((beg (point))
24060 end)
24061 (if (and subtreep org-yank-adjusted-subtrees)
24062 (org-paste-subtree nil nil 'for-yank)
24063 (call-interactively command))
24065 (setq end (point))
24066 (goto-char beg)
24067 (when (and (bolp) subtreep
24068 (not (setq swallowp
24069 (org-yank-folding-would-swallow-text beg end))))
24070 (org-with-limited-levels
24071 (or (looking-at org-outline-regexp)
24072 (re-search-forward org-outline-regexp-bol end t))
24073 (while (and (< (point) end) (looking-at org-outline-regexp))
24074 (outline-hide-subtree)
24075 (org-cycle-show-empty-lines 'folded)
24076 (condition-case nil
24077 (outline-forward-same-level 1)
24078 (error (goto-char end))))))
24079 (when swallowp
24080 (message
24081 "Inserted text not folded because that would swallow text"))
24083 (goto-char end)
24084 (skip-chars-forward " \t\n\r")
24085 (beginning-of-line 1)
24086 (push-mark beg 'nomsg)))
24087 ((and subtreep org-yank-adjusted-subtrees)
24088 (let ((beg (point-at-bol)))
24089 (org-paste-subtree nil nil 'for-yank)
24090 (push-mark beg 'nomsg)))
24092 (call-interactively command))))))
24094 (defun org-yank-folding-would-swallow-text (beg end)
24095 "Would hide-subtree at BEG swallow any text after END?"
24096 (let (level)
24097 (org-with-limited-levels
24098 (save-excursion
24099 (goto-char beg)
24100 (when (or (looking-at org-outline-regexp)
24101 (re-search-forward org-outline-regexp-bol end t))
24102 (setq level (org-outline-level)))
24103 (goto-char end)
24104 (skip-chars-forward " \t\r\n\v\f")
24105 (not (or (eobp)
24106 (and (bolp) (looking-at-p org-outline-regexp)
24107 (<= (org-outline-level) level))))))))
24109 (define-key org-mode-map "\C-y" 'org-yank)
24111 (defun org-truely-invisible-p ()
24112 "Check if point is at a character currently not visible.
24113 This version does not only check the character property, but also
24114 `visible-mode'."
24115 ;; Early versions of noutline don't have `outline-invisible-p'.
24116 (unless (org-bound-and-true-p visible-mode)
24117 (outline-invisible-p)))
24119 (defun org-invisible-p2 ()
24120 "Check if point is at a character currently not visible."
24121 (save-excursion
24122 (when (and (eolp) (not (bobp))) (backward-char 1))
24123 ;; Early versions of noutline don't have `outline-invisible-p'.
24124 (outline-invisible-p)))
24126 (defun org-back-to-heading (&optional invisible-ok)
24127 "Call `outline-back-to-heading', but provide a better error message."
24128 (condition-case nil
24129 (outline-back-to-heading invisible-ok)
24130 (error (error "Before first headline at position %d in buffer %s"
24131 (point) (current-buffer)))))
24133 (defun org-before-first-heading-p ()
24134 "Before first heading?"
24135 (save-excursion
24136 (end-of-line)
24137 (null (re-search-backward org-outline-regexp-bol nil t))))
24139 (defun org-at-heading-p (&optional ignored)
24140 (outline-on-heading-p t))
24141 ;;; Though the function was obsoleted in 7.8.03, the byte-compiler
24142 ;;; warning was only added in Org 9.0, which should be taken into
24143 ;;; account when deciding when to remove the alias.
24144 (define-obsolete-function-alias 'org-on-heading-p 'org-at-heading-p "Org 7.8.03")
24146 (defun org-in-commented-heading-p (&optional no-inheritance)
24147 "Non-nil if point is under a commented heading.
24148 This function also checks ancestors of the current headline,
24149 unless optional argument NO-INHERITANCE is non-nil."
24150 (cond
24151 ((org-before-first-heading-p) nil)
24152 ((let ((headline (nth 4 (org-heading-components))))
24153 (and headline
24154 (let ((case-fold-search nil))
24155 (org-string-match-p (concat "^" org-comment-string "\\(?: \\|$\\)")
24156 headline)))))
24157 (no-inheritance nil)
24159 (save-excursion (and (org-up-heading-safe) (org-in-commented-heading-p))))))
24161 (defun org-at-comment-p nil
24162 "Is cursor in a commented line?"
24163 (save-excursion
24164 (save-match-data
24165 (beginning-of-line)
24166 (looking-at "^[ \t]*# "))))
24168 (defun org-at-drawer-p nil
24169 "Is cursor at a drawer keyword?"
24170 (save-excursion
24171 (move-beginning-of-line 1)
24172 (looking-at org-drawer-regexp)))
24174 (defun org-at-block-p nil
24175 "Is cursor at a block keyword?"
24176 (save-excursion
24177 (move-beginning-of-line 1)
24178 (looking-at org-block-regexp)))
24180 (defun org-point-at-end-of-empty-headline ()
24181 "If point is at the end of an empty headline, return t, else nil.
24182 If the heading only contains a TODO keyword, it is still still considered
24183 empty."
24184 (and (looking-at "[ \t]*$")
24185 (when org-todo-line-regexp
24186 (save-excursion
24187 (beginning-of-line 1)
24188 (let ((case-fold-search nil))
24189 (looking-at org-todo-line-regexp)
24190 (string= (match-string 3) ""))))))
24192 (defun org-at-heading-or-item-p ()
24193 (or (org-at-heading-p) (org-at-item-p)))
24195 (defun org-at-target-p ()
24196 (or (org-in-regexp org-radio-target-regexp)
24197 (org-in-regexp org-target-regexp)))
24198 ;; Compatibility alias with Org versions < 7.8.03
24199 (defalias 'org-on-target-p 'org-at-target-p)
24201 (defun org-up-heading-all (arg)
24202 "Move to the heading line of which the present line is a subheading.
24203 This function considers both visible and invisible heading lines.
24204 With argument, move up ARG levels."
24205 (if (fboundp 'outline-up-heading-all)
24206 (outline-up-heading-all arg) ; emacs 21 version of outline.el
24207 (outline-up-heading arg t))) ; emacs 22 version of outline.el
24209 (defun org-up-heading-safe ()
24210 "Move to the heading line of which the present line is a subheading.
24211 This version will not throw an error. It will return the level of the
24212 headline found, or nil if no higher level is found.
24214 Also, this function will be a lot faster than `outline-up-heading',
24215 because it relies on stars being the outline starters. This can really
24216 make a significant difference in outlines with very many siblings."
24217 (when (ignore-errors (org-back-to-heading t))
24218 (let ((level-up (1- (funcall outline-level))))
24219 (and (> level-up 0)
24220 (re-search-backward (format "^\\*\\{1,%d\\} " level-up) nil t)
24221 (funcall outline-level)))))
24223 (defun org-first-sibling-p ()
24224 "Is this heading the first child of its parents?"
24225 (interactive)
24226 (let ((re org-outline-regexp-bol)
24227 level l)
24228 (unless (org-at-heading-p t)
24229 (user-error "Not at a heading"))
24230 (setq level (funcall outline-level))
24231 (save-excursion
24232 (if (not (re-search-backward re nil t))
24234 (setq l (funcall outline-level))
24235 (< l level)))))
24237 (defun org-goto-sibling (&optional previous)
24238 "Goto the next sibling, even if it is invisible.
24239 When PREVIOUS is set, go to the previous sibling instead. Returns t
24240 when a sibling was found. When none is found, return nil and don't
24241 move point."
24242 (let ((fun (if previous 're-search-backward 're-search-forward))
24243 (pos (point))
24244 (re org-outline-regexp-bol)
24245 level l)
24246 (when (ignore-errors (org-back-to-heading t))
24247 (setq level (funcall outline-level))
24248 (catch 'exit
24249 (or previous (forward-char 1))
24250 (while (funcall fun re nil t)
24251 (setq l (funcall outline-level))
24252 (when (< l level) (goto-char pos) (throw 'exit nil))
24253 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
24254 (goto-char pos)
24255 nil))))
24257 (defun org-show-siblings ()
24258 "Show all siblings of the current headline."
24259 (save-excursion
24260 (while (org-goto-sibling) (org-flag-heading nil)))
24261 (save-excursion
24262 (while (org-goto-sibling 'previous)
24263 (org-flag-heading nil))))
24265 (defun org-goto-first-child ()
24266 "Goto the first child, even if it is invisible.
24267 Return t when a child was found. Otherwise don't move point and
24268 return nil."
24269 (let (level (pos (point)) (re org-outline-regexp-bol))
24270 (when (ignore-errors (org-back-to-heading t))
24271 (setq level (outline-level))
24272 (forward-char 1)
24273 (if (and (re-search-forward re nil t) (> (outline-level) level))
24274 (progn (goto-char (match-beginning 0)) t)
24275 (goto-char pos) nil))))
24277 (defun org-show-hidden-entry ()
24278 "Show an entry where even the heading is hidden."
24279 (save-excursion
24280 (org-show-entry)))
24282 (defun org-flag-heading (flag &optional entry)
24283 "Flag the current heading. FLAG non-nil means make invisible.
24284 When ENTRY is non-nil, show the entire entry."
24285 (save-excursion
24286 (org-back-to-heading t)
24287 ;; Check if we should show the entire entry
24288 (if entry
24289 (progn
24290 (org-show-entry)
24291 (save-excursion
24292 (and (outline-next-heading)
24293 (org-flag-heading nil))))
24294 (outline-flag-region (max (point-min) (1- (point)))
24295 (save-excursion (outline-end-of-heading) (point))
24296 flag))))
24298 (defun org-get-next-sibling ()
24299 "Move to next heading of the same level, and return point.
24300 If there is no such heading, return nil.
24301 This is like outline-next-sibling, but invisible headings are ok."
24302 (let ((level (funcall outline-level)))
24303 (outline-next-heading)
24304 (while (and (not (eobp)) (> (funcall outline-level) level))
24305 (outline-next-heading))
24306 (unless (or (eobp) (< (funcall outline-level) level))
24307 (point))))
24309 (defun org-get-last-sibling ()
24310 "Move to previous heading of the same level, and return point.
24311 If there is no such heading, return nil."
24312 (let ((opoint (point))
24313 (level (funcall outline-level)))
24314 (outline-previous-heading)
24315 (when (and (/= (point) opoint) (outline-on-heading-p t))
24316 (while (and (> (funcall outline-level) level)
24317 (not (bobp)))
24318 (outline-previous-heading))
24319 (unless (< (funcall outline-level) level)
24320 (point)))))
24322 (defun org-end-of-subtree (&optional invisible-ok to-heading)
24323 "Goto to the end of a subtree."
24324 ;; This contains an exact copy of the original function, but it uses
24325 ;; `org-back-to-heading', to make it work also in invisible
24326 ;; trees. And is uses an invisible-ok argument.
24327 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
24328 ;; Furthermore, when used inside Org, finding the end of a large subtree
24329 ;; with many children and grandchildren etc, this can be much faster
24330 ;; than the outline version.
24331 (org-back-to-heading invisible-ok)
24332 (let ((first t)
24333 (level (funcall outline-level)))
24334 (if (and (derived-mode-p 'org-mode) (< level 1000))
24335 ;; A true heading (not a plain list item), in Org-mode
24336 ;; This means we can easily find the end by looking
24337 ;; only for the right number of stars. Using a regexp to do
24338 ;; this is so much faster than using a Lisp loop.
24339 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
24340 (forward-char 1)
24341 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
24342 ;; something else, do it the slow way
24343 (while (and (not (eobp))
24344 (or first (> (funcall outline-level) level)))
24345 (setq first nil)
24346 (outline-next-heading)))
24347 (unless to-heading
24348 (when (memq (preceding-char) '(?\n ?\^M))
24349 ;; Go to end of line before heading
24350 (forward-char -1)
24351 (when (memq (preceding-char) '(?\n ?\^M))
24352 ;; leave blank line before heading
24353 (forward-char -1)))))
24354 (point))
24356 (defun org-end-of-meta-data (&optional full)
24357 "Skip planning line and properties drawer in current entry.
24358 When optional argument FULL is non-nil, also skip empty lines,
24359 clocking lines and regular drawers at the beginning of the
24360 entry."
24361 (org-back-to-heading t)
24362 (forward-line)
24363 (when (org-looking-at-p org-planning-line-re) (forward-line))
24364 (when (looking-at org-property-drawer-re)
24365 (goto-char (match-end 0))
24366 (forward-line))
24367 (when (and full (not (org-at-heading-p)))
24368 (catch 'exit
24369 (let ((end (save-excursion (outline-next-heading) (point)))
24370 (re (concat "[ \t]*$" "\\|" org-clock-line-re)))
24371 (while (not (eobp))
24372 (cond ((org-looking-at-p org-drawer-regexp)
24373 (if (re-search-forward "^[ \t]*:END:[ \t]*$" end t)
24374 (forward-line)
24375 (throw 'exit t)))
24376 ((org-looking-at-p re) (forward-line))
24377 (t (throw 'exit t))))))))
24379 (defun org-forward-heading-same-level (arg &optional invisible-ok)
24380 "Move forward to the ARG'th subheading at same level as this one.
24381 Stop at the first and last subheadings of a superior heading.
24382 Normally this only looks at visible headings, but when INVISIBLE-OK is
24383 non-nil it will also look at invisible ones."
24384 (interactive "p")
24385 (if (not (ignore-errors (org-back-to-heading invisible-ok)))
24386 (if (and arg (< arg 0))
24387 (goto-char (point-min))
24388 (outline-next-heading))
24389 (org-at-heading-p)
24390 (let ((level (- (match-end 0) (match-beginning 0) 1))
24391 (f (if (and arg (< arg 0))
24392 're-search-backward
24393 're-search-forward))
24394 (count (if arg (abs arg) 1))
24395 (result (point)))
24396 (while (and (prog1 (> count 0)
24397 (forward-char (if (and arg (< arg 0)) -1 1)))
24398 (funcall f org-outline-regexp-bol nil 'move))
24399 (let ((l (- (match-end 0) (match-beginning 0) 1)))
24400 (cond ((< l level) (setq count 0))
24401 ((and (= l level)
24402 (or invisible-ok
24403 (progn
24404 (goto-char (line-beginning-position))
24405 (not (outline-invisible-p)))))
24406 (setq count (1- count))
24407 (when (eq l level)
24408 (setq result (point)))))))
24409 (goto-char result))
24410 (beginning-of-line 1)))
24412 (defun org-backward-heading-same-level (arg &optional invisible-ok)
24413 "Move backward to the ARG'th subheading at same level as this one.
24414 Stop at the first and last subheadings of a superior heading."
24415 (interactive "p")
24416 (org-forward-heading-same-level (if arg (- arg) -1) invisible-ok))
24418 (defun org-next-visible-heading (arg)
24419 "Move to the next visible heading.
24421 This function wraps `outline-next-visible-heading' with
24422 `org-with-limited-levels' in order to skip over inline tasks and
24423 respect customization of `org-odd-levels-only'."
24424 (interactive "p")
24425 (org-with-limited-levels
24426 (outline-next-visible-heading arg)))
24428 (defun org-previous-visible-heading (arg)
24429 "Move to the previous visible heading.
24431 This function wraps `outline-previous-visible-heading' with
24432 `org-with-limited-levels' in order to skip over inline tasks and
24433 respect customization of `org-odd-levels-only'."
24434 (interactive "p")
24435 (org-with-limited-levels
24436 (outline-previous-visible-heading arg)))
24438 (defun org-next-block (arg &optional backward block-regexp)
24439 "Jump to the next block.
24441 With a prefix argument ARG, jump forward ARG many blocks.
24443 When BACKWARD is non-nil, jump to the previous block.
24445 When BLOCK-REGEXP is non-nil, use this regexp to find blocks.
24446 Match data is set according to this regexp when the function
24447 returns.
24449 Return point at beginning of the opening line of found block.
24450 Throw an error if no block is found."
24451 (interactive "p")
24452 (let ((re (or block-regexp "^[ \t]*#\\+BEGIN"))
24453 (case-fold-search t)
24454 (search-fn (if backward #'re-search-backward #'re-search-forward))
24455 (count (or arg 1))
24456 (origin (point))
24457 last-element)
24458 (if backward (beginning-of-line) (end-of-line))
24459 (while (and (> count 0) (funcall search-fn re nil t))
24460 (let ((element (save-excursion
24461 (goto-char (match-beginning 0))
24462 (save-match-data (org-element-at-point)))))
24463 (when (and (memq (org-element-type element)
24464 '(center-block comment-block dynamic-block
24465 example-block export-block quote-block
24466 special-block src-block verse-block))
24467 (<= (match-beginning 0)
24468 (org-element-property :post-affiliated element)))
24469 (setq last-element element)
24470 (cl-decf count))))
24471 (if (= count 0)
24472 (prog1 (goto-char (org-element-property :post-affiliated last-element))
24473 (save-match-data (org-show-context)))
24474 (goto-char origin)
24475 (user-error "No %s code blocks" (if backward "previous" "further")))))
24477 (defun org-previous-block (arg &optional block-regexp)
24478 "Jump to the previous block.
24479 With a prefix argument ARG, jump backward ARG many source blocks.
24480 When BLOCK-REGEXP is non-nil, use this regexp to find blocks."
24481 (interactive "p")
24482 (org-next-block arg t block-regexp))
24484 (defun org-forward-paragraph ()
24485 "Move forward to beginning of next paragraph or equivalent.
24487 The function moves point to the beginning of the next visible
24488 structural element, which can be a paragraph, a table, a list
24489 item, etc. It also provides some special moves for convenience:
24491 - On an affiliated keyword, jump to the beginning of the
24492 relative element.
24493 - On an item or a footnote definition, move to the second
24494 element inside, if any.
24495 - On a table or a property drawer, jump after it.
24496 - On a verse or source block, stop after blank lines."
24497 (interactive)
24498 (when (eobp) (user-error "Cannot move further down"))
24499 (let* ((deactivate-mark nil)
24500 (element (org-element-at-point))
24501 (type (org-element-type element))
24502 (post-affiliated (org-element-property :post-affiliated element))
24503 (contents-begin (org-element-property :contents-begin element))
24504 (contents-end (org-element-property :contents-end element))
24505 (end (let ((end (org-element-property :end element)) (parent element))
24506 (while (and (setq parent (org-element-property :parent parent))
24507 (= (org-element-property :contents-end parent) end))
24508 (setq end (org-element-property :end parent)))
24509 end)))
24510 (cond ((not element)
24511 (skip-chars-forward " \r\t\n")
24512 (or (eobp) (beginning-of-line)))
24513 ;; On affiliated keywords, move to element's beginning.
24514 ((< (point) post-affiliated)
24515 (goto-char post-affiliated))
24516 ;; At a table row, move to the end of the table. Similarly,
24517 ;; at a node property, move to the end of the property
24518 ;; drawer.
24519 ((memq type '(node-property table-row))
24520 (goto-char (org-element-property
24521 :end (org-element-property :parent element))))
24522 ((memq type '(property-drawer table)) (goto-char end))
24523 ;; Consider blank lines as separators in verse and source
24524 ;; blocks to ease editing.
24525 ((memq type '(src-block verse-block))
24526 (when (eq type 'src-block)
24527 (setq contents-end
24528 (save-excursion (goto-char end)
24529 (skip-chars-backward " \r\t\n")
24530 (line-beginning-position))))
24531 (beginning-of-line)
24532 (when (looking-at "[ \t]*$") (skip-chars-forward " \r\t\n"))
24533 (if (not (re-search-forward "^[ \t]*$" contents-end t))
24534 (goto-char end)
24535 (skip-chars-forward " \r\t\n")
24536 (if (= (point) contents-end) (goto-char end)
24537 (beginning-of-line))))
24538 ;; With no contents, just skip element.
24539 ((not contents-begin) (goto-char end))
24540 ;; If contents are invisible, skip the element altogether.
24541 ((outline-invisible-p (line-end-position))
24542 (cl-case type
24543 (headline
24544 (org-with-limited-levels (outline-next-visible-heading 1)))
24545 ;; At a plain list, make sure we move to the next item
24546 ;; instead of skipping the whole list.
24547 (plain-list (forward-char)
24548 (org-forward-paragraph))
24549 (otherwise (goto-char end))))
24550 ((>= (point) contents-end) (goto-char end))
24551 ((>= (point) contents-begin)
24552 ;; This can only happen on paragraphs and plain lists.
24553 (cl-case type
24554 (paragraph (goto-char end))
24555 ;; At a plain list, try to move to second element in
24556 ;; first item, if possible.
24557 (plain-list (end-of-line)
24558 (org-forward-paragraph))))
24559 ;; When contents start on the middle of a line (e.g. in
24560 ;; items and footnote definitions), try to reach first
24561 ;; element starting after current line.
24562 ((> (line-end-position) contents-begin)
24563 (end-of-line)
24564 (org-forward-paragraph))
24565 (t (goto-char contents-begin)))))
24567 (defun org-backward-paragraph ()
24568 "Move backward to start of previous paragraph or equivalent.
24570 The function moves point to the beginning of the current
24571 structural element, which can be a paragraph, a table, a list
24572 item, etc., or to the beginning of the previous visible one if
24573 point is already there. It also provides some special moves for
24574 convenience:
24576 - On an affiliated keyword, jump to the first one.
24577 - On a table or a property drawer, move to its beginning.
24578 - On a verse or source block, stop before blank lines."
24579 (interactive)
24580 (when (bobp) (user-error "Cannot move further up"))
24581 (let* ((deactivate-mark nil)
24582 (element (org-element-at-point))
24583 (type (org-element-type element))
24584 (contents-begin (org-element-property :contents-begin element))
24585 (contents-end (org-element-property :contents-end element))
24586 (post-affiliated (org-element-property :post-affiliated element))
24587 (begin (org-element-property :begin element)))
24588 (cond
24589 ((not element) (goto-char (point-min)))
24590 ((= (point) begin)
24591 (backward-char)
24592 (org-backward-paragraph))
24593 ((<= (point) post-affiliated) (goto-char begin))
24594 ((memq type '(node-property table-row))
24595 (goto-char (org-element-property
24596 :post-affiliated (org-element-property :parent element))))
24597 ((memq type '(property-drawer table)) (goto-char begin))
24598 ((memq type '(src-block verse-block))
24599 (when (eq type 'src-block)
24600 (setq contents-begin
24601 (save-excursion (goto-char begin) (forward-line) (point))))
24602 (if (= (point) contents-begin) (goto-char post-affiliated)
24603 ;; Inside a verse block, see blank lines as paragraph
24604 ;; separators.
24605 (let ((origin (point)))
24606 (skip-chars-backward " \r\t\n" contents-begin)
24607 (when (re-search-backward "^[ \t]*$" contents-begin 'move)
24608 (skip-chars-forward " \r\t\n" origin)
24609 (if (= (point) origin) (goto-char contents-begin)
24610 (beginning-of-line))))))
24611 ((not contents-begin) (goto-char (or post-affiliated begin)))
24612 ((eq type 'paragraph)
24613 (goto-char contents-begin)
24614 ;; When at first paragraph in an item or a footnote definition,
24615 ;; move directly to beginning of line.
24616 (let ((parent-contents
24617 (org-element-property
24618 :contents-begin (org-element-property :parent element))))
24619 (when (and parent-contents (= parent-contents contents-begin))
24620 (beginning-of-line))))
24621 ;; At the end of a greater element, move to the beginning of the
24622 ;; last element within.
24623 ((>= (point) contents-end)
24624 (goto-char (1- contents-end))
24625 (org-backward-paragraph))
24626 (t (goto-char (or post-affiliated begin))))
24627 ;; Ensure we never leave point invisible.
24628 (when (outline-invisible-p (point)) (beginning-of-visual-line))))
24630 (defun org-forward-element ()
24631 "Move forward by one element.
24632 Move to the next element at the same level, when possible."
24633 (interactive)
24634 (cond ((eobp) (user-error "Cannot move further down"))
24635 ((org-with-limited-levels (org-at-heading-p))
24636 (let ((origin (point)))
24637 (goto-char (org-end-of-subtree nil t))
24638 (unless (org-with-limited-levels (org-at-heading-p))
24639 (goto-char origin)
24640 (user-error "Cannot move further down"))))
24642 (let* ((elem (org-element-at-point))
24643 (end (org-element-property :end elem))
24644 (parent (org-element-property :parent elem)))
24645 (cond ((and parent (= (org-element-property :contents-end parent) end))
24646 (goto-char (org-element-property :end parent)))
24647 ((integer-or-marker-p end) (goto-char end))
24648 (t (message "No element at point")))))))
24650 (defun org-backward-element ()
24651 "Move backward by one element.
24652 Move to the previous element at the same level, when possible."
24653 (interactive)
24654 (cond ((bobp) (user-error "Cannot move further up"))
24655 ((org-with-limited-levels (org-at-heading-p))
24656 ;; At a headline, move to the previous one, if any, or stay
24657 ;; here.
24658 (let ((origin (point)))
24659 (org-with-limited-levels (org-backward-heading-same-level 1))
24660 ;; When current headline has no sibling above, move to its
24661 ;; parent.
24662 (when (= (point) origin)
24663 (or (org-with-limited-levels (org-up-heading-safe))
24664 (progn (goto-char origin)
24665 (user-error "Cannot move further up"))))))
24667 (let* ((elem (org-element-at-point))
24668 (beg (org-element-property :begin elem)))
24669 (cond
24670 ;; Move to beginning of current element if point isn't
24671 ;; there already.
24672 ((null beg) (message "No element at point"))
24673 ((/= (point) beg) (goto-char beg))
24674 (t (goto-char beg)
24675 (skip-chars-backward " \r\t\n")
24676 (unless (bobp)
24677 (let ((prev (org-element-at-point)))
24678 (goto-char (org-element-property :begin prev))
24679 (while (and (setq prev (org-element-property :parent prev))
24680 (<= (org-element-property :end prev) beg))
24681 (goto-char (org-element-property :begin prev)))))))))))
24683 (defun org-up-element ()
24684 "Move to upper element."
24685 (interactive)
24686 (if (org-with-limited-levels (org-at-heading-p))
24687 (unless (org-up-heading-safe) (user-error "No surrounding element"))
24688 (let* ((elem (org-element-at-point))
24689 (parent (org-element-property :parent elem)))
24690 (if parent (goto-char (org-element-property :begin parent))
24691 (if (org-with-limited-levels (org-before-first-heading-p))
24692 (user-error "No surrounding element")
24693 (org-with-limited-levels (org-back-to-heading)))))))
24695 (defvar org-element-greater-elements)
24696 (defun org-down-element ()
24697 "Move to inner element."
24698 (interactive)
24699 (let ((element (org-element-at-point)))
24700 (cond
24701 ((memq (org-element-type element) '(plain-list table))
24702 (goto-char (org-element-property :contents-begin element))
24703 (forward-char))
24704 ((memq (org-element-type element) org-element-greater-elements)
24705 ;; If contents are hidden, first disclose them.
24706 (when (outline-invisible-p (line-end-position)) (org-cycle))
24707 (goto-char (or (org-element-property :contents-begin element)
24708 (user-error "No content for this element"))))
24709 (t (user-error "No inner element")))))
24711 (defun org-drag-element-backward ()
24712 "Move backward element at point."
24713 (interactive)
24714 (if (org-with-limited-levels (org-at-heading-p)) (org-move-subtree-up)
24715 (let* ((elem (org-element-at-point))
24716 (prev-elem
24717 (save-excursion
24718 (goto-char (org-element-property :begin elem))
24719 (skip-chars-backward " \r\t\n")
24720 (unless (bobp)
24721 (let* ((beg (org-element-property :begin elem))
24722 (prev (org-element-at-point))
24723 (up prev))
24724 (while (and (setq up (org-element-property :parent up))
24725 (<= (org-element-property :end up) beg))
24726 (setq prev up))
24727 prev)))))
24728 ;; Error out if no previous element or previous element is
24729 ;; a parent of the current one.
24730 (if (or (not prev-elem) (org-element-nested-p elem prev-elem))
24731 (user-error "Cannot drag element backward")
24732 (let ((pos (point)))
24733 (org-element-swap-A-B prev-elem elem)
24734 (goto-char (+ (org-element-property :begin prev-elem)
24735 (- pos (org-element-property :begin elem)))))))))
24737 (defun org-drag-element-forward ()
24738 "Move forward element at point."
24739 (interactive)
24740 (let* ((pos (point))
24741 (elem (org-element-at-point)))
24742 (when (= (point-max) (org-element-property :end elem))
24743 (user-error "Cannot drag element forward"))
24744 (goto-char (org-element-property :end elem))
24745 (let ((next-elem (org-element-at-point)))
24746 (when (or (org-element-nested-p elem next-elem)
24747 (and (eq (org-element-type next-elem) 'headline)
24748 (not (eq (org-element-type elem) 'headline))))
24749 (goto-char pos)
24750 (user-error "Cannot drag element forward"))
24751 ;; Compute new position of point: it's shifted by NEXT-ELEM
24752 ;; body's length (without final blanks) and by the length of
24753 ;; blanks between ELEM and NEXT-ELEM.
24754 (let ((size-next (- (save-excursion
24755 (goto-char (org-element-property :end next-elem))
24756 (skip-chars-backward " \r\t\n")
24757 (forward-line)
24758 ;; Small correction if buffer doesn't end
24759 ;; with a newline character.
24760 (if (and (eolp) (not (bolp))) (1+ (point)) (point)))
24761 (org-element-property :begin next-elem)))
24762 (size-blank (- (org-element-property :end elem)
24763 (save-excursion
24764 (goto-char (org-element-property :end elem))
24765 (skip-chars-backward " \r\t\n")
24766 (forward-line)
24767 (point)))))
24768 (org-element-swap-A-B elem next-elem)
24769 (goto-char (+ pos size-next size-blank))))))
24771 (defun org-drag-line-forward (arg)
24772 "Drag the line at point ARG lines forward."
24773 (interactive "p")
24774 (dotimes (_ (abs arg))
24775 (let ((c (current-column)))
24776 (if (< 0 arg)
24777 (progn
24778 (beginning-of-line 2)
24779 (transpose-lines 1)
24780 (beginning-of-line 0))
24781 (transpose-lines 1)
24782 (beginning-of-line -1))
24783 (org-move-to-column c))))
24785 (defun org-drag-line-backward (arg)
24786 "Drag the line at point ARG lines backward."
24787 (interactive "p")
24788 (org-drag-line-forward (- arg)))
24790 (defun org-mark-element ()
24791 "Put point at beginning of this element, mark at end.
24793 Interactively, if this command is repeated or (in Transient Mark
24794 mode) if the mark is active, it marks the next element after the
24795 ones already marked."
24796 (interactive)
24797 (let (deactivate-mark)
24798 (if (and (org-called-interactively-p 'any)
24799 (or (and (eq last-command this-command) (mark t))
24800 (and transient-mark-mode mark-active)))
24801 (set-mark
24802 (save-excursion
24803 (goto-char (mark))
24804 (goto-char (org-element-property :end (org-element-at-point)))))
24805 (let ((element (org-element-at-point)))
24806 (end-of-line)
24807 (push-mark (org-element-property :end element) t t)
24808 (goto-char (org-element-property :begin element))))))
24810 (defun org-narrow-to-element ()
24811 "Narrow buffer to current element."
24812 (interactive)
24813 (let ((elem (org-element-at-point)))
24814 (cond
24815 ((eq (car elem) 'headline)
24816 (narrow-to-region
24817 (org-element-property :begin elem)
24818 (org-element-property :end elem)))
24819 ((memq (car elem) org-element-greater-elements)
24820 (narrow-to-region
24821 (org-element-property :contents-begin elem)
24822 (org-element-property :contents-end elem)))
24824 (narrow-to-region
24825 (org-element-property :begin elem)
24826 (org-element-property :end elem))))))
24828 (defun org-transpose-element ()
24829 "Transpose current and previous elements, keeping blank lines between.
24830 Point is moved after both elements."
24831 (interactive)
24832 (org-skip-whitespace)
24833 (let ((end (org-element-property :end (org-element-at-point))))
24834 (org-drag-element-backward)
24835 (goto-char end)))
24837 (defun org-unindent-buffer ()
24838 "Un-indent the visible part of the buffer.
24839 Relative indentation (between items, inside blocks, etc.) isn't
24840 modified."
24841 (interactive)
24842 (unless (eq major-mode 'org-mode)
24843 (user-error "Cannot un-indent a buffer not in Org mode"))
24844 (letrec ((parse-tree (org-element-parse-buffer 'greater-element))
24845 (unindent-tree
24846 (lambda (contents)
24847 (dolist (element (reverse contents))
24848 (if (memq (org-element-type element) '(headline section))
24849 (funcall unindent-tree (org-element-contents element))
24850 (save-excursion
24851 (save-restriction
24852 (narrow-to-region
24853 (org-element-property :begin element)
24854 (org-element-property :end element))
24855 (org-do-remove-indentation))))))))
24856 (funcall unindent-tree (org-element-contents parse-tree))))
24858 (defun org-show-children (&optional level)
24859 "Show all direct subheadings of this heading.
24860 Prefix arg LEVEL is how many levels below the current level
24861 should be shown. Default is enough to cause the following
24862 heading to appear."
24863 (interactive "p")
24864 ;; If `orgstruct-mode' is active, use the slower version.
24865 (if orgstruct-mode (call-interactively #'outline-show-children)
24866 (save-excursion
24867 (org-back-to-heading t)
24868 (let* ((current-level (funcall outline-level))
24869 (max-level (org-get-valid-level
24870 current-level
24871 (if level (prefix-numeric-value level) 1)))
24872 (end (save-excursion (org-end-of-subtree t t)))
24873 (regexp-fmt "^\\*\\{%d,%s\\}\\(?: \\|$\\)")
24874 (past-first-child nil)
24875 ;; Make sure to skip inlinetasks.
24876 (re (format regexp-fmt
24877 current-level
24878 (cond
24879 ((not (featurep 'org-inlinetask)) "")
24880 (org-odd-levels-only (- (* 2 org-inlinetask-min-level)
24882 (t (1- org-inlinetask-min-level))))))
24883 ;; Display parent heading.
24884 (outline-flag-region (line-end-position 0) (line-end-position) nil)
24885 (forward-line)
24886 ;; Display children. First child may be deeper than expected
24887 ;; MAX-LEVEL. Since we want to display it anyway, adjust
24888 ;; MAX-LEVEL accordingly.
24889 (while (re-search-forward re end t)
24890 (unless past-first-child
24891 (setq re (format regexp-fmt
24892 current-level
24893 (max (funcall outline-level) max-level)))
24894 (setq past-first-child t))
24895 (outline-flag-region
24896 (line-end-position 0) (line-end-position) nil))))))
24898 (defun org-show-subtree ()
24899 "Show everything after this heading at deeper levels."
24900 (interactive)
24901 (outline-flag-region
24902 (point)
24903 (save-excursion
24904 (org-end-of-subtree t t))
24905 nil))
24907 (defun org-show-entry ()
24908 "Show the body directly following this heading.
24909 Show the heading too, if it is currently invisible."
24910 (interactive)
24911 (save-excursion
24912 (ignore-errors
24913 (org-back-to-heading t)
24914 (outline-flag-region
24915 (max (point-min) (1- (point)))
24916 (save-excursion
24917 (if (re-search-forward
24918 (concat "[\r\n]\\(" org-outline-regexp "\\)") nil t)
24919 (match-beginning 1)
24920 (point-max)))
24921 nil)
24922 (org-cycle-hide-drawers 'children))))
24924 (defun org-make-options-regexp (kwds &optional extra)
24925 "Make a regular expression for keyword lines.
24926 KWDS is a list of keywords, as strings. Optional argument EXTRA,
24927 when non-nil, is a regexp matching keywords names."
24928 (concat "^[ \t]*#\\+\\("
24929 (regexp-opt kwds)
24930 (and extra (concat (and kwds "\\|") extra))
24931 "\\):[ \t]*\\(.*\\)"))
24933 ;;;; Integration with and fixes for other packages
24935 ;;; Imenu support
24937 (defvar-local org-imenu-markers nil
24938 "All markers currently used by Imenu.")
24940 (defun org-imenu-new-marker (&optional pos)
24941 "Return a new marker for use by Imenu, and remember the marker."
24942 (let ((m (make-marker)))
24943 (move-marker m (or pos (point)))
24944 (push m org-imenu-markers)
24947 (defun org-imenu-get-tree ()
24948 "Produce the index for Imenu."
24949 (dolist (x org-imenu-markers) (move-marker x nil))
24950 (setq org-imenu-markers nil)
24951 (let* ((n org-imenu-depth)
24952 (re (concat "^" (org-get-limited-outline-regexp)))
24953 (subs (make-vector (1+ n) nil))
24954 (last-level 0)
24955 m level head0 head)
24956 (save-excursion
24957 (save-restriction
24958 (widen)
24959 (goto-char (point-max))
24960 (while (re-search-backward re nil t)
24961 (setq level (org-reduced-level (funcall outline-level)))
24962 (when (and (<= level n)
24963 (looking-at org-complex-heading-regexp)
24964 (setq head0 (org-match-string-no-properties 4)))
24965 (setq head (org-link-display-format head0)
24966 m (org-imenu-new-marker))
24967 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
24968 (if (>= level last-level)
24969 (push (cons head m) (aref subs level))
24970 (push (cons head (aref subs (1+ level))) (aref subs level))
24971 (cl-loop for i from (1+ level) to n do (aset subs i nil)))
24972 (setq last-level level)))))
24973 (aref subs 1)))
24975 (eval-after-load "imenu"
24976 '(progn
24977 (add-hook 'imenu-after-jump-hook
24978 (lambda ()
24979 (when (derived-mode-p 'org-mode)
24980 (org-show-context 'org-goto))))))
24982 (defun org-link-display-format (s)
24983 "Replace links in string S with their description.
24984 If there is no description, use the link target."
24985 (save-match-data
24986 (replace-regexp-in-string
24987 org-bracket-link-analytic-regexp
24988 (lambda (m)
24989 (if (match-end 5) (match-string 5 m)
24990 (concat (match-string 1 m) (match-string 3 m))))
24991 s nil t)))
24993 (defun org-toggle-link-display ()
24994 "Toggle the literal or descriptive display of links."
24995 (interactive)
24996 (if org-descriptive-links
24997 (progn (org-remove-from-invisibility-spec '(org-link))
24998 (org-restart-font-lock)
24999 (setq org-descriptive-links nil))
25000 (progn (add-to-invisibility-spec '(org-link))
25001 (org-restart-font-lock)
25002 (setq org-descriptive-links t))))
25004 ;; Speedbar support
25006 (defvar org-speedbar-restriction-lock-overlay (make-overlay 1 1)
25007 "Overlay marking the agenda restriction line in speedbar.")
25008 (overlay-put org-speedbar-restriction-lock-overlay
25009 'face 'org-agenda-restriction-lock)
25010 (overlay-put org-speedbar-restriction-lock-overlay
25011 'help-echo "Agendas are currently limited to this item.")
25012 (org-detach-overlay org-speedbar-restriction-lock-overlay)
25014 (defun org-speedbar-set-agenda-restriction ()
25015 "Restrict future agenda commands to the location at point in speedbar.
25016 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
25017 (interactive)
25018 (require 'org-agenda)
25019 (let (p m tp np dir txt)
25020 (cond
25021 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25022 'org-imenu t))
25023 (setq m (get-text-property p 'org-imenu-marker))
25024 (with-current-buffer (marker-buffer m)
25025 (goto-char m)
25026 (org-agenda-set-restriction-lock 'subtree)))
25027 ((setq p (text-property-any (point-at-bol) (point-at-eol)
25028 'speedbar-function 'speedbar-find-file))
25029 (setq tp (previous-single-property-change
25030 (1+ p) 'speedbar-function)
25031 np (next-single-property-change
25032 tp 'speedbar-function)
25033 dir (speedbar-line-directory)
25034 txt (buffer-substring-no-properties (or tp (point-min))
25035 (or np (point-max))))
25036 (with-current-buffer (find-file-noselect
25037 (let ((default-directory dir))
25038 (expand-file-name txt)))
25039 (unless (derived-mode-p 'org-mode)
25040 (user-error "Cannot restrict to non-Org-mode file"))
25041 (org-agenda-set-restriction-lock 'file)))
25042 (t (user-error "Don't know how to restrict Org-mode's agenda")))
25043 (move-overlay org-speedbar-restriction-lock-overlay
25044 (point-at-bol) (point-at-eol))
25045 (setq current-prefix-arg nil)
25046 (org-agenda-maybe-redo)))
25048 (defvar speedbar-file-key-map)
25049 (declare-function speedbar-add-supported-extension "speedbar" (extension))
25050 (eval-after-load "speedbar"
25051 '(progn
25052 (speedbar-add-supported-extension ".org")
25053 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
25054 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
25055 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
25056 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
25057 (add-hook 'speedbar-visiting-tag-hook
25058 (lambda () (and (derived-mode-p 'org-mode) (org-show-context 'org-goto))))))
25060 ;;; Fixes and Hacks for problems with other packages
25062 (defun org--flyspell-object-check-p (element)
25063 "Non-nil when Flyspell can check object at point.
25064 ELEMENT is the element at point."
25065 (let ((object (save-excursion
25066 (when (org-looking-at-p "\\>") (backward-char))
25067 (org-element-context element))))
25068 (cl-case (org-element-type object)
25069 ;; Prevent checks in links due to keybinding conflict with
25070 ;; Flyspell.
25071 ((code entity export-snippet inline-babel-call
25072 inline-src-block line-break latex-fragment link macro
25073 statistics-cookie target timestamp verbatim)
25074 nil)
25075 (footnote-reference
25076 ;; Only in inline footnotes, within the definition.
25077 (and (eq (org-element-property :type object) 'inline)
25078 (< (save-excursion
25079 (goto-char (org-element-property :begin object))
25080 (search-forward ":" nil t 2))
25081 (point))))
25082 (otherwise t))))
25084 (defun org-mode-flyspell-verify ()
25085 "Function used for `flyspell-generic-check-word-predicate'."
25086 (if (org-at-heading-p)
25087 ;; At a headline or an inlinetask, check title only. This is
25088 ;; faster than relying on `org-element-at-point'.
25089 (and (save-excursion (beginning-of-line)
25090 (and (let ((case-fold-search t))
25091 (not (looking-at "\\*+ END[ \t]*$")))
25092 (looking-at org-complex-heading-regexp)))
25093 (match-beginning 4)
25094 (>= (point) (match-beginning 4))
25095 (or (not (match-beginning 5))
25096 (< (point) (match-beginning 5))))
25097 (let* ((element (org-element-at-point))
25098 (post-affiliated (org-element-property :post-affiliated element)))
25099 (cond
25100 ;; Ignore checks in all affiliated keywords but captions.
25101 ((< (point) post-affiliated)
25102 (and (save-excursion
25103 (beginning-of-line)
25104 (let ((case-fold-search t)) (looking-at "[ \t]*#\\+CAPTION:")))
25105 (> (point) (match-end 0))
25106 (org--flyspell-object-check-p element)))
25107 ;; Ignore checks in LOGBOOK (or equivalent) drawer.
25108 ((let ((log (org-log-into-drawer)))
25109 (and log
25110 (let ((drawer (org-element-lineage element '(drawer))))
25111 (and drawer
25112 (eq (compare-strings
25113 log nil nil
25114 (org-element-property :drawer-name drawer) nil nil t)
25115 t)))))
25116 nil)
25118 (cl-case (org-element-type element)
25119 ((comment quote-section) t)
25120 (comment-block
25121 ;; Allow checks between block markers, not on them.
25122 (and (> (line-beginning-position) post-affiliated)
25123 (save-excursion
25124 (end-of-line)
25125 (skip-chars-forward " \r\t\n")
25126 (< (point) (org-element-property :end element)))))
25127 ;; Arbitrary list of keywords where checks are meaningful.
25128 ;; Make sure point is on the value part of the element.
25129 (keyword
25130 (and (member (org-element-property :key element)
25131 '("DESCRIPTION" "TITLE"))
25132 (save-excursion
25133 (search-backward ":" (line-beginning-position) t))))
25134 ;; Check is globally allowed in paragraphs verse blocks and
25135 ;; table rows (after affiliated keywords) but some objects
25136 ;; must not be affected.
25137 ((paragraph table-row verse-block)
25138 (let ((cbeg (org-element-property :contents-begin element))
25139 (cend (org-element-property :contents-end element)))
25140 (and cbeg (>= (point) cbeg) (< (point) cend)
25141 (org--flyspell-object-check-p element))))))))))
25142 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
25144 (defun org-remove-flyspell-overlays-in (beg end)
25145 "Remove flyspell overlays in region."
25146 (and (org-bound-and-true-p flyspell-mode)
25147 (fboundp 'flyspell-delete-region-overlays)
25148 (flyspell-delete-region-overlays beg end)))
25150 (defvar flyspell-delayed-commands)
25151 (eval-after-load "flyspell"
25152 '(add-to-list 'flyspell-delayed-commands 'org-self-insert-command))
25154 ;; Make `bookmark-jump' shows the jump location if it was hidden.
25155 (eval-after-load "bookmark"
25156 '(if (boundp 'bookmark-after-jump-hook)
25157 ;; We can use the hook
25158 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
25159 ;; Hook not available, use advice
25160 (defadvice bookmark-jump (after org-make-visible activate)
25161 "Make the position visible."
25162 (org-bookmark-jump-unhide))))
25164 ;; Make sure saveplace shows the location if it was hidden
25165 (eval-after-load "saveplace"
25166 '(defadvice save-place-find-file-hook (after org-make-visible activate)
25167 "Make the position visible."
25168 (org-bookmark-jump-unhide)))
25170 ;; Make sure ecb shows the location if it was hidden
25171 (eval-after-load "ecb"
25172 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
25173 "Make hierarchy visible when jumping into location from ECB tree buffer."
25174 (when (derived-mode-p 'org-mode)
25175 (org-show-context))))
25177 (defun org-bookmark-jump-unhide ()
25178 "Unhide the current position, to show the bookmark location."
25179 (and (derived-mode-p 'org-mode)
25180 (or (outline-invisible-p)
25181 (save-excursion (goto-char (max (point-min) (1- (point))))
25182 (outline-invisible-p)))
25183 (org-show-context 'bookmark-jump)))
25185 (defun org-mark-jump-unhide ()
25186 "Make the point visible with `org-show-context' after jumping to the mark."
25187 (when (and (derived-mode-p 'org-mode)
25188 (outline-invisible-p))
25189 (org-show-context 'mark-goto)))
25191 (eval-after-load "simple"
25192 '(defadvice pop-to-mark-command (after org-make-visible activate)
25193 "Make the point visible with `org-show-context'."
25194 (org-mark-jump-unhide)))
25196 (eval-after-load "simple"
25197 '(defadvice exchange-point-and-mark (after org-make-visible activate)
25198 "Make the point visible with `org-show-context'."
25199 (org-mark-jump-unhide)))
25201 (eval-after-load "simple"
25202 '(defadvice pop-global-mark (after org-make-visible activate)
25203 "Make the point visible with `org-show-context'."
25204 (org-mark-jump-unhide)))
25206 ;; Make session.el ignore our circular variable
25207 (defvar session-globals-exclude)
25208 (eval-after-load "session"
25209 '(add-to-list 'session-globals-exclude 'org-mark-ring))
25211 ;;;; Finish up
25213 (provide 'org)
25215 (run-hooks 'org-load-hook)
25217 ;;; org.el ends here